CodePlacementOpt.cpp 15 KB

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