CodePlacementOpt.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //===-- CodePlacementOpt.cpp - Code Placement 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 the pass that optimize code placement and align loop
  11. // headers to target specific alignment boundary.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "code-placement"
  15. #include "llvm/CodeGen/MachineLoopInfo.h"
  16. #include "llvm/CodeGen/MachineFunctionPass.h"
  17. #include "llvm/CodeGen/Passes.h"
  18. #include "llvm/Target/TargetInstrInfo.h"
  19. #include "llvm/Target/TargetLowering.h"
  20. #include "llvm/Target/TargetMachine.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/ADT/Statistic.h"
  24. using namespace llvm;
  25. STATISTIC(NumLoopsAligned, "Number of loops aligned");
  26. STATISTIC(NumIntraElim, "Number of intra loop branches eliminated");
  27. STATISTIC(NumIntraMoved, "Number of intra loop branches moved");
  28. namespace {
  29. class CodePlacementOpt : public MachineFunctionPass {
  30. const MachineLoopInfo *MLI;
  31. const TargetInstrInfo *TII;
  32. const TargetLowering *TLI;
  33. public:
  34. static char ID;
  35. CodePlacementOpt() : MachineFunctionPass(&ID) {}
  36. virtual bool runOnMachineFunction(MachineFunction &MF);
  37. virtual const char *getPassName() const {
  38. return "Code Placement Optimizater";
  39. }
  40. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  41. AU.addRequired<MachineLoopInfo>();
  42. AU.addPreservedID(MachineDominatorsID);
  43. MachineFunctionPass::getAnalysisUsage(AU);
  44. }
  45. private:
  46. bool HasFallthrough(MachineBasicBlock *MBB);
  47. bool HasAnalyzableTerminator(MachineBasicBlock *MBB);
  48. void Splice(MachineFunction &MF,
  49. MachineFunction::iterator InsertPt,
  50. MachineFunction::iterator Begin,
  51. MachineFunction::iterator End);
  52. bool EliminateUnconditionalJumpsToTop(MachineFunction &MF,
  53. MachineLoop *L);
  54. bool MoveDiscontiguousLoopBlocks(MachineFunction &MF,
  55. MachineLoop *L);
  56. bool OptimizeIntraLoopEdgesInLoopNest(MachineFunction &MF, MachineLoop *L);
  57. bool OptimizeIntraLoopEdges(MachineFunction &MF);
  58. bool AlignLoops(MachineFunction &MF);
  59. bool AlignLoop(MachineFunction &MF, MachineLoop *L, unsigned Align);
  60. };
  61. char CodePlacementOpt::ID = 0;
  62. } // end anonymous namespace
  63. FunctionPass *llvm::createCodePlacementOptPass() {
  64. return new CodePlacementOpt();
  65. }
  66. /// HasFallthrough - Test whether the given branch has a fallthrough, either as
  67. /// a plain fallthrough or as a fallthrough case of a conditional branch.
  68. ///
  69. bool CodePlacementOpt::HasFallthrough(MachineBasicBlock *MBB) {
  70. MachineBasicBlock *TBB = 0, *FBB = 0;
  71. SmallVector<MachineOperand, 4> Cond;
  72. if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
  73. return false;
  74. // This conditional branch has no fallthrough.
  75. if (FBB)
  76. return false;
  77. // An unconditional branch has no fallthrough.
  78. if (Cond.empty() && TBB)
  79. return false;
  80. // It has a fallthrough.
  81. return true;
  82. }
  83. /// HasAnalyzableTerminator - Test whether AnalyzeBranch will succeed on MBB.
  84. /// This is called before major changes are begun to test whether it will be
  85. /// possible to complete the changes.
  86. ///
  87. /// Target-specific code is hereby encouraged to make AnalyzeBranch succeed
  88. /// whenever possible.
  89. ///
  90. bool CodePlacementOpt::HasAnalyzableTerminator(MachineBasicBlock *MBB) {
  91. // Conservatively ignore EH landing pads.
  92. if (MBB->isLandingPad()) return false;
  93. // Ignore blocks which look like they might have EH-related control flow.
  94. // At the time of this writing, there are blocks which AnalyzeBranch
  95. // thinks end in single uncoditional branches, yet which have two CFG
  96. // successors. Code in this file is not prepared to reason about such things.
  97. if (!MBB->empty() && MBB->back().isEHLabel())
  98. return false;
  99. // Aggressively handle return blocks and similar constructs.
  100. if (MBB->succ_empty()) return true;
  101. // Ask the target's AnalyzeBranch if it can handle this block.
  102. MachineBasicBlock *TBB = 0, *FBB = 0;
  103. SmallVector<MachineOperand, 4> Cond;
  104. // Make the the terminator is understood.
  105. if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
  106. return false;
  107. // Make sure we have the option of reversing the condition.
  108. if (!Cond.empty() && TII->ReverseBranchCondition(Cond))
  109. return false;
  110. return true;
  111. }
  112. /// Splice - Move the sequence of instructions [Begin,End) to just before
  113. /// InsertPt. Update branch instructions as needed to account for broken
  114. /// fallthrough edges and to take advantage of newly exposed fallthrough
  115. /// opportunities.
  116. ///
  117. void CodePlacementOpt::Splice(MachineFunction &MF,
  118. MachineFunction::iterator InsertPt,
  119. MachineFunction::iterator Begin,
  120. MachineFunction::iterator End) {
  121. assert(Begin != MF.begin() && End != MF.begin() && InsertPt != MF.begin() &&
  122. "Splice can't change the entry block!");
  123. MachineFunction::iterator OldBeginPrior = prior(Begin);
  124. MachineFunction::iterator OldEndPrior = prior(End);
  125. MF.splice(InsertPt, Begin, End);
  126. prior(Begin)->updateTerminator();
  127. OldBeginPrior->updateTerminator();
  128. OldEndPrior->updateTerminator();
  129. }
  130. /// EliminateUnconditionalJumpsToTop - Move blocks which unconditionally jump
  131. /// to the loop top to the top of the loop so that they have a fall through.
  132. /// This can introduce a branch on entry to the loop, but it can eliminate a
  133. /// branch within the loop. See the @simple case in
  134. /// test/CodeGen/X86/loop_blocks.ll for an example of this.
  135. bool CodePlacementOpt::EliminateUnconditionalJumpsToTop(MachineFunction &MF,
  136. MachineLoop *L) {
  137. bool Changed = false;
  138. MachineBasicBlock *TopMBB = L->getTopBlock();
  139. bool BotHasFallthrough = HasFallthrough(L->getBottomBlock());
  140. if (TopMBB == MF.begin() ||
  141. HasAnalyzableTerminator(prior(MachineFunction::iterator(TopMBB)))) {
  142. new_top:
  143. for (MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin(),
  144. PE = TopMBB->pred_end(); PI != PE; ++PI) {
  145. MachineBasicBlock *Pred = *PI;
  146. if (Pred == TopMBB) continue;
  147. if (HasFallthrough(Pred)) continue;
  148. if (!L->contains(Pred)) continue;
  149. // Verify that we can analyze all the loop entry edges before beginning
  150. // any changes which will require us to be able to analyze them.
  151. if (Pred == MF.begin())
  152. continue;
  153. if (!HasAnalyzableTerminator(Pred))
  154. continue;
  155. if (!HasAnalyzableTerminator(prior(MachineFunction::iterator(Pred))))
  156. continue;
  157. // Move the block.
  158. Changed = true;
  159. // Move it and all the blocks that can reach it via fallthrough edges
  160. // exclusively, to keep existing fallthrough edges intact.
  161. MachineFunction::iterator Begin = Pred;
  162. MachineFunction::iterator End = llvm::next(Begin);
  163. while (Begin != MF.begin()) {
  164. MachineFunction::iterator Prior = prior(Begin);
  165. if (Prior == MF.begin())
  166. break;
  167. // Stop when a non-fallthrough edge is found.
  168. if (!HasFallthrough(Prior))
  169. break;
  170. // Stop if a block which could fall-through out of the loop is found.
  171. if (Prior->isSuccessor(End))
  172. break;
  173. // If we've reached the top, stop scanning.
  174. if (Prior == MachineFunction::iterator(TopMBB)) {
  175. // We know top currently has a fall through (because we just checked
  176. // it) which would be lost if we do the transformation, so it isn't
  177. // worthwhile to do the transformation unless it would expose a new
  178. // fallthrough edge.
  179. if (!Prior->isSuccessor(End))
  180. goto next_pred;
  181. // Otherwise we can stop scanning and procede to move the blocks.
  182. break;
  183. }
  184. // If we hit a switch or something complicated, don't move anything
  185. // for this predecessor.
  186. if (!HasAnalyzableTerminator(prior(MachineFunction::iterator(Prior))))
  187. break;
  188. // Ok, the block prior to Begin will be moved along with the rest.
  189. // Extend the range to include it.
  190. Begin = Prior;
  191. ++NumIntraMoved;
  192. }
  193. // Move the blocks.
  194. Splice(MF, TopMBB, Begin, End);
  195. // Update TopMBB.
  196. TopMBB = L->getTopBlock();
  197. // We have a new loop top. Iterate on it. We shouldn't have to do this
  198. // too many times if BranchFolding has done a reasonable job.
  199. goto new_top;
  200. next_pred:;
  201. }
  202. }
  203. // If the loop previously didn't exit with a fall-through and it now does,
  204. // we eliminated a branch.
  205. if (Changed &&
  206. !BotHasFallthrough &&
  207. HasFallthrough(L->getBottomBlock())) {
  208. ++NumIntraElim;
  209. }
  210. return Changed;
  211. }
  212. /// MoveDiscontiguousLoopBlocks - Move any loop blocks that are not in the
  213. /// portion of the loop contiguous with the header. This usually makes the loop
  214. /// contiguous, provided that AnalyzeBranch can handle all the relevant
  215. /// branching. See the @cfg_islands case in test/CodeGen/X86/loop_blocks.ll
  216. /// for an example of this.
  217. bool CodePlacementOpt::MoveDiscontiguousLoopBlocks(MachineFunction &MF,
  218. MachineLoop *L) {
  219. bool Changed = false;
  220. MachineBasicBlock *TopMBB = L->getTopBlock();
  221. MachineBasicBlock *BotMBB = L->getBottomBlock();
  222. // Determine a position to move orphaned loop blocks to. If TopMBB is not
  223. // entered via fallthrough and BotMBB is exited via fallthrough, prepend them
  224. // to the top of the loop to avoid loosing that fallthrough. Otherwise append
  225. // them to the bottom, even if it previously had a fallthrough, on the theory
  226. // that it's worth an extra branch to keep the loop contiguous.
  227. MachineFunction::iterator InsertPt =
  228. llvm::next(MachineFunction::iterator(BotMBB));
  229. bool InsertAtTop = false;
  230. if (TopMBB != MF.begin() &&
  231. !HasFallthrough(prior(MachineFunction::iterator(TopMBB))) &&
  232. HasFallthrough(BotMBB)) {
  233. InsertPt = TopMBB;
  234. InsertAtTop = true;
  235. }
  236. // Keep a record of which blocks are in the portion of the loop contiguous
  237. // with the loop header.
  238. SmallPtrSet<MachineBasicBlock *, 8> ContiguousBlocks;
  239. for (MachineFunction::iterator I = TopMBB,
  240. E = llvm::next(MachineFunction::iterator(BotMBB)); I != E; ++I)
  241. ContiguousBlocks.insert(I);
  242. // Find non-contigous blocks and fix them.
  243. if (InsertPt != MF.begin() && HasAnalyzableTerminator(prior(InsertPt)))
  244. for (MachineLoop::block_iterator BI = L->block_begin(), BE = L->block_end();
  245. BI != BE; ++BI) {
  246. MachineBasicBlock *BB = *BI;
  247. // Verify that we can analyze all the loop entry edges before beginning
  248. // any changes which will require us to be able to analyze them.
  249. if (!HasAnalyzableTerminator(BB))
  250. continue;
  251. if (!HasAnalyzableTerminator(prior(MachineFunction::iterator(BB))))
  252. continue;
  253. // If the layout predecessor is part of the loop, this block will be
  254. // processed along with it. This keeps them in their relative order.
  255. if (BB != MF.begin() &&
  256. L->contains(prior(MachineFunction::iterator(BB))))
  257. continue;
  258. // Check to see if this block is already contiguous with the main
  259. // portion of the loop.
  260. if (!ContiguousBlocks.insert(BB))
  261. continue;
  262. // Move the block.
  263. Changed = true;
  264. // Process this block and all loop blocks contiguous with it, to keep
  265. // them in their relative order.
  266. MachineFunction::iterator Begin = BB;
  267. MachineFunction::iterator End = llvm::next(MachineFunction::iterator(BB));
  268. for (; End != MF.end(); ++End) {
  269. if (!L->contains(End)) break;
  270. if (!HasAnalyzableTerminator(End)) break;
  271. ContiguousBlocks.insert(End);
  272. ++NumIntraMoved;
  273. }
  274. // If we're inserting at the bottom of the loop, and the code we're
  275. // moving originally had fall-through successors, bring the sucessors
  276. // up with the loop blocks to preserve the fall-through edges.
  277. if (!InsertAtTop)
  278. for (; End != MF.end(); ++End) {
  279. if (L->contains(End)) break;
  280. if (!HasAnalyzableTerminator(End)) break;
  281. if (!HasFallthrough(prior(End))) break;
  282. }
  283. // Move the blocks. This may invalidate TopMBB and/or BotMBB, but
  284. // we don't need them anymore at this point.
  285. Splice(MF, InsertPt, Begin, End);
  286. }
  287. return Changed;
  288. }
  289. /// OptimizeIntraLoopEdgesInLoopNest - Reposition loop blocks to minimize
  290. /// intra-loop branching and to form contiguous loops.
  291. ///
  292. /// This code takes the approach of making minor changes to the existing
  293. /// layout to fix specific loop-oriented problems. Also, it depends on
  294. /// AnalyzeBranch, which can't understand complex control instructions.
  295. ///
  296. bool CodePlacementOpt::OptimizeIntraLoopEdgesInLoopNest(MachineFunction &MF,
  297. MachineLoop *L) {
  298. bool Changed = false;
  299. // Do optimization for nested loops.
  300. for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  301. Changed |= OptimizeIntraLoopEdgesInLoopNest(MF, *I);
  302. // Do optimization for this loop.
  303. Changed |= EliminateUnconditionalJumpsToTop(MF, L);
  304. Changed |= MoveDiscontiguousLoopBlocks(MF, L);
  305. return Changed;
  306. }
  307. /// OptimizeIntraLoopEdges - Reposition loop blocks to minimize
  308. /// intra-loop branching and to form contiguous loops.
  309. ///
  310. bool CodePlacementOpt::OptimizeIntraLoopEdges(MachineFunction &MF) {
  311. bool Changed = false;
  312. if (!TLI->shouldOptimizeCodePlacement())
  313. return Changed;
  314. // Do optimization for each loop in the function.
  315. for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
  316. I != E; ++I)
  317. if (!(*I)->getParentLoop())
  318. Changed |= OptimizeIntraLoopEdgesInLoopNest(MF, *I);
  319. return Changed;
  320. }
  321. /// AlignLoops - Align loop headers to target preferred alignments.
  322. ///
  323. bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
  324. const Function *F = MF.getFunction();
  325. if (F->hasFnAttr(Attribute::OptimizeForSize))
  326. return false;
  327. unsigned Align = TLI->getPrefLoopAlignment();
  328. if (!Align)
  329. return false; // Don't care about loop alignment.
  330. bool Changed = false;
  331. for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
  332. I != E; ++I)
  333. Changed |= AlignLoop(MF, *I, Align);
  334. return Changed;
  335. }
  336. /// AlignLoop - Align loop headers to target preferred alignments.
  337. ///
  338. bool CodePlacementOpt::AlignLoop(MachineFunction &MF, MachineLoop *L,
  339. unsigned Align) {
  340. bool Changed = false;
  341. // Do alignment for nested loops.
  342. for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  343. Changed |= AlignLoop(MF, *I, Align);
  344. L->getTopBlock()->setAlignment(Align);
  345. Changed = true;
  346. ++NumLoopsAligned;
  347. return Changed;
  348. }
  349. bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
  350. MLI = &getAnalysis<MachineLoopInfo>();
  351. if (MLI->empty())
  352. return false; // No loops.
  353. TLI = MF.getTarget().getTargetLowering();
  354. TII = MF.getTarget().getInstrInfo();
  355. bool Changed = OptimizeIntraLoopEdges(MF);
  356. Changed |= AlignLoops(MF);
  357. return Changed;
  358. }