FlattenCFGPass.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //===- FlattenCFGPass.cpp - CFG Flatten Pass ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements flattening of CFG.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/Analysis/AliasAnalysis.h"
  15. #include "llvm/IR/CFG.h"
  16. #include "llvm/Pass.h"
  17. #include "llvm/Transforms/Utils/Local.h"
  18. using namespace llvm;
  19. #define DEBUG_TYPE "flattencfg"
  20. namespace {
  21. struct FlattenCFGPass : public FunctionPass {
  22. static char ID; // Pass identification, replacement for typeid
  23. public:
  24. FlattenCFGPass() : FunctionPass(ID) {
  25. initializeFlattenCFGPassPass(*PassRegistry::getPassRegistry());
  26. }
  27. bool runOnFunction(Function &F) override;
  28. void getAnalysisUsage(AnalysisUsage &AU) const override {
  29. AU.addRequired<AliasAnalysis>();
  30. }
  31. private:
  32. AliasAnalysis *AA;
  33. };
  34. }
  35. char FlattenCFGPass::ID = 0;
  36. INITIALIZE_PASS_BEGIN(FlattenCFGPass, "flattencfg", "Flatten the CFG", false,
  37. false)
  38. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  39. INITIALIZE_PASS_END(FlattenCFGPass, "flattencfg", "Flatten the CFG", false,
  40. false)
  41. // Public interface to the FlattenCFG pass
  42. FunctionPass *llvm::createFlattenCFGPass() { return new FlattenCFGPass(); }
  43. /// iterativelyFlattenCFG - Call FlattenCFG on all the blocks in the function,
  44. /// iterating until no more changes are made.
  45. static bool iterativelyFlattenCFG(Function &F, AliasAnalysis *AA) {
  46. bool Changed = false;
  47. bool LocalChange = true;
  48. while (LocalChange) {
  49. LocalChange = false;
  50. // Loop over all of the basic blocks and remove them if they are unneeded...
  51. //
  52. for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
  53. if (FlattenCFG(BBIt++, AA)) {
  54. LocalChange = true;
  55. }
  56. }
  57. Changed |= LocalChange;
  58. }
  59. return Changed;
  60. }
  61. bool FlattenCFGPass::runOnFunction(Function &F) {
  62. AA = &getAnalysis<AliasAnalysis>();
  63. bool EverChanged = false;
  64. // iterativelyFlattenCFG can make some blocks dead.
  65. while (iterativelyFlattenCFG(F, AA)) {
  66. removeUnreachableBlocks(F);
  67. EverChanged = true;
  68. }
  69. return EverChanged;
  70. }