LoopSimplify.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. //===- LoopSimplify.cpp - Loop Canonicalization 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 pass performs several transformations to transform natural loops into a
  11. // simpler form, which makes subsequent analyses and transformations simpler and
  12. // more effective.
  13. //
  14. // Loop pre-header insertion guarantees that there is a single, non-critical
  15. // entry edge from outside of the loop to the loop header. This simplifies a
  16. // number of analyses and transformations, such as LICM.
  17. //
  18. // Loop exit-block insertion guarantees that all exit blocks from the loop
  19. // (blocks which are outside of the loop that have predecessors inside of the
  20. // loop) only have predecessors from inside of the loop (and are thus dominated
  21. // by the loop header). This simplifies transformations such as store-sinking
  22. // that are built into LICM.
  23. //
  24. // This pass also guarantees that loops will have exactly one backedge.
  25. //
  26. // Indirectbr instructions introduce several complications. If the loop
  27. // contains or is entered by an indirectbr instruction, it may not be possible
  28. // to transform the loop and make these guarantees. Client code should check
  29. // that these conditions are true before relying on them.
  30. //
  31. // Note that the simplifycfg pass will clean up blocks which are split out but
  32. // end up being unnecessary, so usage of this pass should not pessimize
  33. // generated code.
  34. //
  35. // This pass obviously modifies the CFG, but updates loop information and
  36. // dominator information.
  37. //
  38. //===----------------------------------------------------------------------===//
  39. #define DEBUG_TYPE "loopsimplify"
  40. #include "llvm/Transforms/Scalar.h"
  41. #include "llvm/Constants.h"
  42. #include "llvm/Instructions.h"
  43. #include "llvm/IntrinsicInst.h"
  44. #include "llvm/Function.h"
  45. #include "llvm/LLVMContext.h"
  46. #include "llvm/Type.h"
  47. #include "llvm/Analysis/AliasAnalysis.h"
  48. #include "llvm/Analysis/ScalarEvolution.h"
  49. #include "llvm/Analysis/Dominators.h"
  50. #include "llvm/Analysis/LoopPass.h"
  51. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  52. #include "llvm/Transforms/Utils/Local.h"
  53. #include "llvm/Support/CFG.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/ADT/SetOperations.h"
  56. #include "llvm/ADT/SetVector.h"
  57. #include "llvm/ADT/Statistic.h"
  58. #include "llvm/ADT/DepthFirstIterator.h"
  59. using namespace llvm;
  60. STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
  61. STATISTIC(NumNested , "Number of nested loops split out");
  62. namespace {
  63. struct LoopSimplify : public LoopPass {
  64. static char ID; // Pass identification, replacement for typeid
  65. LoopSimplify() : LoopPass(ID) {}
  66. // AA - If we have an alias analysis object to update, this is it, otherwise
  67. // this is null.
  68. AliasAnalysis *AA;
  69. LoopInfo *LI;
  70. DominatorTree *DT;
  71. ScalarEvolution *SE;
  72. Loop *L;
  73. virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
  74. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  75. // We need loop information to identify the loops...
  76. AU.addRequired<DominatorTree>();
  77. AU.addPreserved<DominatorTree>();
  78. AU.addRequired<LoopInfo>();
  79. AU.addPreserved<LoopInfo>();
  80. AU.addPreserved<AliasAnalysis>();
  81. AU.addPreserved<ScalarEvolution>();
  82. AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
  83. AU.addPreserved<DominanceFrontier>();
  84. AU.addPreservedID(LCSSAID);
  85. }
  86. /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
  87. void verifyAnalysis() const;
  88. private:
  89. bool ProcessLoop(Loop *L, LPPassManager &LPM);
  90. BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
  91. BasicBlock *InsertPreheaderForLoop(Loop *L);
  92. Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM);
  93. BasicBlock *InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
  94. void PlaceSplitBlockCarefully(BasicBlock *NewBB,
  95. SmallVectorImpl<BasicBlock*> &SplitPreds,
  96. Loop *L);
  97. };
  98. }
  99. char LoopSimplify::ID = 0;
  100. INITIALIZE_PASS_BEGIN(LoopSimplify, "loopsimplify",
  101. "Canonicalize natural loops", true, false)
  102. INITIALIZE_PASS_DEPENDENCY(DominatorTree)
  103. INITIALIZE_PASS_DEPENDENCY(LoopInfo)
  104. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  105. INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
  106. INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
  107. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  108. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  109. INITIALIZE_PASS_END(LoopSimplify, "loopsimplify",
  110. "Canonicalize natural loops", true, false)
  111. // Publically exposed interface to pass...
  112. char &llvm::LoopSimplifyID = LoopSimplify::ID;
  113. Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
  114. /// runOnLoop - Run down all loops in the CFG (recursively, but we could do
  115. /// it in any convenient order) inserting preheaders...
  116. ///
  117. bool LoopSimplify::runOnLoop(Loop *l, LPPassManager &LPM) {
  118. L = l;
  119. bool Changed = false;
  120. LI = &getAnalysis<LoopInfo>();
  121. AA = getAnalysisIfAvailable<AliasAnalysis>();
  122. DT = &getAnalysis<DominatorTree>();
  123. SE = getAnalysisIfAvailable<ScalarEvolution>();
  124. Changed |= ProcessLoop(L, LPM);
  125. return Changed;
  126. }
  127. /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
  128. /// all loops have preheaders.
  129. ///
  130. bool LoopSimplify::ProcessLoop(Loop *L, LPPassManager &LPM) {
  131. bool Changed = false;
  132. ReprocessLoop:
  133. // Check to see that no blocks (other than the header) in this loop have
  134. // predecessors that are not in the loop. This is not valid for natural
  135. // loops, but can occur if the blocks are unreachable. Since they are
  136. // unreachable we can just shamelessly delete those CFG edges!
  137. for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
  138. BB != E; ++BB) {
  139. if (*BB == L->getHeader()) continue;
  140. SmallPtrSet<BasicBlock*, 4> BadPreds;
  141. for (pred_iterator PI = pred_begin(*BB),
  142. PE = pred_end(*BB); PI != PE; ++PI) {
  143. BasicBlock *P = *PI;
  144. if (!L->contains(P))
  145. BadPreds.insert(P);
  146. }
  147. // Delete each unique out-of-loop (and thus dead) predecessor.
  148. for (SmallPtrSet<BasicBlock*, 4>::iterator I = BadPreds.begin(),
  149. E = BadPreds.end(); I != E; ++I) {
  150. DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor ";
  151. WriteAsOperand(dbgs(), *I, false);
  152. dbgs() << "\n");
  153. // Inform each successor of each dead pred.
  154. for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
  155. (*SI)->removePredecessor(*I);
  156. // Zap the dead pred's terminator and replace it with unreachable.
  157. TerminatorInst *TI = (*I)->getTerminator();
  158. TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
  159. (*I)->getTerminator()->eraseFromParent();
  160. new UnreachableInst((*I)->getContext(), *I);
  161. Changed = true;
  162. }
  163. }
  164. // If there are exiting blocks with branches on undef, resolve the undef in
  165. // the direction which will exit the loop. This will help simplify loop
  166. // trip count computations.
  167. SmallVector<BasicBlock*, 8> ExitingBlocks;
  168. L->getExitingBlocks(ExitingBlocks);
  169. for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
  170. E = ExitingBlocks.end(); I != E; ++I)
  171. if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
  172. if (BI->isConditional()) {
  173. if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
  174. DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in ";
  175. WriteAsOperand(dbgs(), *I, false);
  176. dbgs() << "\n");
  177. BI->setCondition(ConstantInt::get(Cond->getType(),
  178. !L->contains(BI->getSuccessor(0))));
  179. Changed = true;
  180. }
  181. }
  182. // Does the loop already have a preheader? If so, don't insert one.
  183. BasicBlock *Preheader = L->getLoopPreheader();
  184. if (!Preheader) {
  185. Preheader = InsertPreheaderForLoop(L);
  186. if (Preheader) {
  187. ++NumInserted;
  188. Changed = true;
  189. }
  190. }
  191. // Next, check to make sure that all exit nodes of the loop only have
  192. // predecessors that are inside of the loop. This check guarantees that the
  193. // loop preheader/header will dominate the exit blocks. If the exit block has
  194. // predecessors from outside of the loop, split the edge now.
  195. SmallVector<BasicBlock*, 8> ExitBlocks;
  196. L->getExitBlocks(ExitBlocks);
  197. SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
  198. ExitBlocks.end());
  199. for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(),
  200. E = ExitBlockSet.end(); I != E; ++I) {
  201. BasicBlock *ExitBlock = *I;
  202. for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
  203. PI != PE; ++PI)
  204. // Must be exactly this loop: no subloops, parent loops, or non-loop preds
  205. // allowed.
  206. if (!L->contains(*PI)) {
  207. if (RewriteLoopExitBlock(L, ExitBlock)) {
  208. ++NumInserted;
  209. Changed = true;
  210. }
  211. break;
  212. }
  213. }
  214. // If the header has more than two predecessors at this point (from the
  215. // preheader and from multiple backedges), we must adjust the loop.
  216. BasicBlock *LoopLatch = L->getLoopLatch();
  217. if (!LoopLatch) {
  218. // If this is really a nested loop, rip it out into a child loop. Don't do
  219. // this for loops with a giant number of backedges, just factor them into a
  220. // common backedge instead.
  221. if (L->getNumBackEdges() < 8) {
  222. if (SeparateNestedLoop(L, LPM)) {
  223. ++NumNested;
  224. // This is a big restructuring change, reprocess the whole loop.
  225. Changed = true;
  226. // GCC doesn't tail recursion eliminate this.
  227. goto ReprocessLoop;
  228. }
  229. }
  230. // If we either couldn't, or didn't want to, identify nesting of the loops,
  231. // insert a new block that all backedges target, then make it jump to the
  232. // loop header.
  233. LoopLatch = InsertUniqueBackedgeBlock(L, Preheader);
  234. if (LoopLatch) {
  235. ++NumInserted;
  236. Changed = true;
  237. }
  238. }
  239. // Scan over the PHI nodes in the loop header. Since they now have only two
  240. // incoming values (the loop is canonicalized), we may have simplified the PHI
  241. // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
  242. PHINode *PN;
  243. for (BasicBlock::iterator I = L->getHeader()->begin();
  244. (PN = dyn_cast<PHINode>(I++)); )
  245. if (Value *V = PN->hasConstantValue(DT)) {
  246. if (AA) AA->deleteValue(PN);
  247. PN->replaceAllUsesWith(V);
  248. PN->eraseFromParent();
  249. }
  250. // If this loop has multiple exits and the exits all go to the same
  251. // block, attempt to merge the exits. This helps several passes, such
  252. // as LoopRotation, which do not support loops with multiple exits.
  253. // SimplifyCFG also does this (and this code uses the same utility
  254. // function), however this code is loop-aware, where SimplifyCFG is
  255. // not. That gives it the advantage of being able to hoist
  256. // loop-invariant instructions out of the way to open up more
  257. // opportunities, and the disadvantage of having the responsibility
  258. // to preserve dominator information.
  259. bool UniqueExit = true;
  260. if (!ExitBlocks.empty())
  261. for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
  262. if (ExitBlocks[i] != ExitBlocks[0]) {
  263. UniqueExit = false;
  264. break;
  265. }
  266. if (UniqueExit) {
  267. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  268. BasicBlock *ExitingBlock = ExitingBlocks[i];
  269. if (!ExitingBlock->getSinglePredecessor()) continue;
  270. BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  271. if (!BI || !BI->isConditional()) continue;
  272. CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
  273. if (!CI || CI->getParent() != ExitingBlock) continue;
  274. // Attempt to hoist out all instructions except for the
  275. // comparison and the branch.
  276. bool AllInvariant = true;
  277. for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
  278. Instruction *Inst = I++;
  279. // Skip debug info intrinsics.
  280. if (isa<DbgInfoIntrinsic>(Inst))
  281. continue;
  282. if (Inst == CI)
  283. continue;
  284. if (!L->makeLoopInvariant(Inst, Changed,
  285. Preheader ? Preheader->getTerminator() : 0)) {
  286. AllInvariant = false;
  287. break;
  288. }
  289. }
  290. if (!AllInvariant) continue;
  291. // The block has now been cleared of all instructions except for
  292. // a comparison and a conditional branch. SimplifyCFG may be able
  293. // to fold it now.
  294. if (!FoldBranchToCommonDest(BI)) continue;
  295. // Success. The block is now dead, so remove it from the loop,
  296. // update the dominator tree and dominance frontier, and delete it.
  297. DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block ";
  298. WriteAsOperand(dbgs(), ExitingBlock, false);
  299. dbgs() << "\n");
  300. assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
  301. Changed = true;
  302. LI->removeBlock(ExitingBlock);
  303. DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>();
  304. DomTreeNode *Node = DT->getNode(ExitingBlock);
  305. const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
  306. Node->getChildren();
  307. while (!Children.empty()) {
  308. DomTreeNode *Child = Children.front();
  309. DT->changeImmediateDominator(Child, Node->getIDom());
  310. if (DF) DF->changeImmediateDominator(Child->getBlock(),
  311. Node->getIDom()->getBlock(),
  312. DT);
  313. }
  314. DT->eraseNode(ExitingBlock);
  315. if (DF) DF->removeBlock(ExitingBlock);
  316. BI->getSuccessor(0)->removePredecessor(ExitingBlock);
  317. BI->getSuccessor(1)->removePredecessor(ExitingBlock);
  318. ExitingBlock->eraseFromParent();
  319. }
  320. }
  321. return Changed;
  322. }
  323. /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
  324. /// preheader, this method is called to insert one. This method has two phases:
  325. /// preheader insertion and analysis updating.
  326. ///
  327. BasicBlock *LoopSimplify::InsertPreheaderForLoop(Loop *L) {
  328. BasicBlock *Header = L->getHeader();
  329. // Compute the set of predecessors of the loop that are not in the loop.
  330. SmallVector<BasicBlock*, 8> OutsideBlocks;
  331. for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
  332. PI != PE; ++PI) {
  333. BasicBlock *P = *PI;
  334. if (!L->contains(P)) { // Coming in from outside the loop?
  335. // If the loop is branched to from an indirect branch, we won't
  336. // be able to fully transform the loop, because it prohibits
  337. // edge splitting.
  338. if (isa<IndirectBrInst>(P->getTerminator())) return 0;
  339. // Keep track of it.
  340. OutsideBlocks.push_back(P);
  341. }
  342. }
  343. // Split out the loop pre-header.
  344. BasicBlock *NewBB =
  345. SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
  346. ".preheader", this);
  347. DEBUG(dbgs() << "LoopSimplify: Creating pre-header ";
  348. WriteAsOperand(dbgs(), NewBB, false);
  349. dbgs() << "\n");
  350. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  351. // code layout too horribly.
  352. PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
  353. return NewBB;
  354. }
  355. /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
  356. /// blocks. This method is used to split exit blocks that have predecessors
  357. /// outside of the loop.
  358. BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
  359. SmallVector<BasicBlock*, 8> LoopBlocks;
  360. for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
  361. BasicBlock *P = *I;
  362. if (L->contains(P)) {
  363. // Don't do this if the loop is exited via an indirect branch.
  364. if (isa<IndirectBrInst>(P->getTerminator())) return 0;
  365. LoopBlocks.push_back(P);
  366. }
  367. }
  368. assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
  369. BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0],
  370. LoopBlocks.size(), ".loopexit",
  371. this);
  372. DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block ";
  373. WriteAsOperand(dbgs(), NewBB, false);
  374. dbgs() << "\n");
  375. return NewBB;
  376. }
  377. /// AddBlockAndPredsToSet - Add the specified block, and all of its
  378. /// predecessors, to the specified set, if it's not already in there. Stop
  379. /// predecessor traversal when we reach StopBlock.
  380. static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
  381. std::set<BasicBlock*> &Blocks) {
  382. std::vector<BasicBlock *> WorkList;
  383. WorkList.push_back(InputBB);
  384. do {
  385. BasicBlock *BB = WorkList.back(); WorkList.pop_back();
  386. if (Blocks.insert(BB).second && BB != StopBlock)
  387. // If BB is not already processed and it is not a stop block then
  388. // insert its predecessor in the work list
  389. for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  390. BasicBlock *WBB = *I;
  391. WorkList.push_back(WBB);
  392. }
  393. } while(!WorkList.empty());
  394. }
  395. /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
  396. /// PHI node that tells us how to partition the loops.
  397. static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
  398. AliasAnalysis *AA) {
  399. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
  400. PHINode *PN = cast<PHINode>(I);
  401. ++I;
  402. if (Value *V = PN->hasConstantValue(DT)) {
  403. // This is a degenerate PHI already, don't modify it!
  404. PN->replaceAllUsesWith(V);
  405. if (AA) AA->deleteValue(PN);
  406. PN->eraseFromParent();
  407. continue;
  408. }
  409. // Scan this PHI node looking for a use of the PHI node by itself.
  410. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  411. if (PN->getIncomingValue(i) == PN &&
  412. L->contains(PN->getIncomingBlock(i)))
  413. // We found something tasty to remove.
  414. return PN;
  415. }
  416. return 0;
  417. }
  418. // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
  419. // right after some 'outside block' block. This prevents the preheader from
  420. // being placed inside the loop body, e.g. when the loop hasn't been rotated.
  421. void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
  422. SmallVectorImpl<BasicBlock*> &SplitPreds,
  423. Loop *L) {
  424. // Check to see if NewBB is already well placed.
  425. Function::iterator BBI = NewBB; --BBI;
  426. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  427. if (&*BBI == SplitPreds[i])
  428. return;
  429. }
  430. // If it isn't already after an outside block, move it after one. This is
  431. // always good as it makes the uncond branch from the outside block into a
  432. // fall-through.
  433. // Figure out *which* outside block to put this after. Prefer an outside
  434. // block that neighbors a BB actually in the loop.
  435. BasicBlock *FoundBB = 0;
  436. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  437. Function::iterator BBI = SplitPreds[i];
  438. if (++BBI != NewBB->getParent()->end() &&
  439. L->contains(BBI)) {
  440. FoundBB = SplitPreds[i];
  441. break;
  442. }
  443. }
  444. // If our heuristic for a *good* bb to place this after doesn't find
  445. // anything, just pick something. It's likely better than leaving it within
  446. // the loop.
  447. if (!FoundBB)
  448. FoundBB = SplitPreds[0];
  449. NewBB->moveAfter(FoundBB);
  450. }
  451. /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
  452. /// them out into a nested loop. This is important for code that looks like
  453. /// this:
  454. ///
  455. /// Loop:
  456. /// ...
  457. /// br cond, Loop, Next
  458. /// ...
  459. /// br cond2, Loop, Out
  460. ///
  461. /// To identify this common case, we look at the PHI nodes in the header of the
  462. /// loop. PHI nodes with unchanging values on one backedge correspond to values
  463. /// that change in the "outer" loop, but not in the "inner" loop.
  464. ///
  465. /// If we are able to separate out a loop, return the new outer loop that was
  466. /// created.
  467. ///
  468. Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM) {
  469. PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
  470. if (PN == 0) return 0; // No known way to partition.
  471. // Pull out all predecessors that have varying values in the loop. This
  472. // handles the case when a PHI node has multiple instances of itself as
  473. // arguments.
  474. SmallVector<BasicBlock*, 8> OuterLoopPreds;
  475. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  476. if (PN->getIncomingValue(i) != PN ||
  477. !L->contains(PN->getIncomingBlock(i))) {
  478. // We can't split indirectbr edges.
  479. if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
  480. return 0;
  481. OuterLoopPreds.push_back(PN->getIncomingBlock(i));
  482. }
  483. DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
  484. // If ScalarEvolution is around and knows anything about values in
  485. // this loop, tell it to forget them, because we're about to
  486. // substantially change it.
  487. if (SE)
  488. SE->forgetLoop(L);
  489. BasicBlock *Header = L->getHeader();
  490. BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
  491. OuterLoopPreds.size(),
  492. ".outer", this);
  493. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  494. // code layout too horribly.
  495. PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
  496. // Create the new outer loop.
  497. Loop *NewOuter = new Loop();
  498. // Change the parent loop to use the outer loop as its child now.
  499. if (Loop *Parent = L->getParentLoop())
  500. Parent->replaceChildLoopWith(L, NewOuter);
  501. else
  502. LI->changeTopLevelLoop(L, NewOuter);
  503. // L is now a subloop of our outer loop.
  504. NewOuter->addChildLoop(L);
  505. // Add the new loop to the pass manager queue.
  506. LPM.insertLoopIntoQueue(NewOuter);
  507. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  508. I != E; ++I)
  509. NewOuter->addBlockEntry(*I);
  510. // Now reset the header in L, which had been moved by
  511. // SplitBlockPredecessors for the outer loop.
  512. L->moveToHeader(Header);
  513. // Determine which blocks should stay in L and which should be moved out to
  514. // the Outer loop now.
  515. std::set<BasicBlock*> BlocksInL;
  516. for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
  517. BasicBlock *P = *PI;
  518. if (DT->dominates(Header, P))
  519. AddBlockAndPredsToSet(P, Header, BlocksInL);
  520. }
  521. // Scan all of the loop children of L, moving them to OuterLoop if they are
  522. // not part of the inner loop.
  523. const std::vector<Loop*> &SubLoops = L->getSubLoops();
  524. for (size_t I = 0; I != SubLoops.size(); )
  525. if (BlocksInL.count(SubLoops[I]->getHeader()))
  526. ++I; // Loop remains in L
  527. else
  528. NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
  529. // Now that we know which blocks are in L and which need to be moved to
  530. // OuterLoop, move any blocks that need it.
  531. for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
  532. BasicBlock *BB = L->getBlocks()[i];
  533. if (!BlocksInL.count(BB)) {
  534. // Move this block to the parent, updating the exit blocks sets
  535. L->removeBlockFromLoop(BB);
  536. if ((*LI)[BB] == L)
  537. LI->changeLoopFor(BB, NewOuter);
  538. --i;
  539. }
  540. }
  541. return NewOuter;
  542. }
  543. /// InsertUniqueBackedgeBlock - This method is called when the specified loop
  544. /// has more than one backedge in it. If this occurs, revector all of these
  545. /// backedges to target a new basic block and have that block branch to the loop
  546. /// header. This ensures that loops have exactly one backedge.
  547. ///
  548. BasicBlock *
  549. LoopSimplify::InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader) {
  550. assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
  551. // Get information about the loop
  552. BasicBlock *Header = L->getHeader();
  553. Function *F = Header->getParent();
  554. // Unique backedge insertion currently depends on having a preheader.
  555. if (!Preheader)
  556. return 0;
  557. // Figure out which basic blocks contain back-edges to the loop header.
  558. std::vector<BasicBlock*> BackedgeBlocks;
  559. for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
  560. BasicBlock *P = *I;
  561. // Indirectbr edges cannot be split, so we must fail if we find one.
  562. if (isa<IndirectBrInst>(P->getTerminator()))
  563. return 0;
  564. if (P != Preheader) BackedgeBlocks.push_back(P);
  565. }
  566. // Create and insert the new backedge block...
  567. BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
  568. Header->getName()+".backedge", F);
  569. BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
  570. DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block ";
  571. WriteAsOperand(dbgs(), BEBlock, false);
  572. dbgs() << "\n");
  573. // Move the new backedge block to right after the last backedge block.
  574. Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
  575. F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
  576. // Now that the block has been inserted into the function, create PHI nodes in
  577. // the backedge block which correspond to any PHI nodes in the header block.
  578. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  579. PHINode *PN = cast<PHINode>(I);
  580. PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
  581. BETerminator);
  582. NewPN->reserveOperandSpace(BackedgeBlocks.size());
  583. if (AA) AA->copyValue(PN, NewPN);
  584. // Loop over the PHI node, moving all entries except the one for the
  585. // preheader over to the new PHI node.
  586. unsigned PreheaderIdx = ~0U;
  587. bool HasUniqueIncomingValue = true;
  588. Value *UniqueValue = 0;
  589. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  590. BasicBlock *IBB = PN->getIncomingBlock(i);
  591. Value *IV = PN->getIncomingValue(i);
  592. if (IBB == Preheader) {
  593. PreheaderIdx = i;
  594. } else {
  595. NewPN->addIncoming(IV, IBB);
  596. if (HasUniqueIncomingValue) {
  597. if (UniqueValue == 0)
  598. UniqueValue = IV;
  599. else if (UniqueValue != IV)
  600. HasUniqueIncomingValue = false;
  601. }
  602. }
  603. }
  604. // Delete all of the incoming values from the old PN except the preheader's
  605. assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
  606. if (PreheaderIdx != 0) {
  607. PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
  608. PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
  609. }
  610. // Nuke all entries except the zero'th.
  611. for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
  612. PN->removeIncomingValue(e-i, false);
  613. // Finally, add the newly constructed PHI node as the entry for the BEBlock.
  614. PN->addIncoming(NewPN, BEBlock);
  615. // As an optimization, if all incoming values in the new PhiNode (which is a
  616. // subset of the incoming values of the old PHI node) have the same value,
  617. // eliminate the PHI Node.
  618. if (HasUniqueIncomingValue) {
  619. NewPN->replaceAllUsesWith(UniqueValue);
  620. if (AA) AA->deleteValue(NewPN);
  621. BEBlock->getInstList().erase(NewPN);
  622. }
  623. }
  624. // Now that all of the PHI nodes have been inserted and adjusted, modify the
  625. // backedge blocks to just to the BEBlock instead of the header.
  626. for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
  627. TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
  628. for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
  629. if (TI->getSuccessor(Op) == Header)
  630. TI->setSuccessor(Op, BEBlock);
  631. }
  632. //===--- Update all analyses which we must preserve now -----------------===//
  633. // Update Loop Information - we know that this block is now in the current
  634. // loop and all parent loops.
  635. L->addBasicBlockToLoop(BEBlock, LI->getBase());
  636. // Update dominator information
  637. DT->splitBlock(BEBlock);
  638. if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>())
  639. DF->splitBlock(BEBlock);
  640. return BEBlock;
  641. }
  642. void LoopSimplify::verifyAnalysis() const {
  643. // It used to be possible to just assert L->isLoopSimplifyForm(), however
  644. // with the introduction of indirectbr, there are now cases where it's
  645. // not possible to transform a loop as necessary. We can at least check
  646. // that there is an indirectbr near any time there's trouble.
  647. // Indirectbr can interfere with preheader and unique backedge insertion.
  648. if (!L->getLoopPreheader() || !L->getLoopLatch()) {
  649. bool HasIndBrPred = false;
  650. for (pred_iterator PI = pred_begin(L->getHeader()),
  651. PE = pred_end(L->getHeader()); PI != PE; ++PI)
  652. if (isa<IndirectBrInst>((*PI)->getTerminator())) {
  653. HasIndBrPred = true;
  654. break;
  655. }
  656. assert(HasIndBrPred &&
  657. "LoopSimplify has no excuse for missing loop header info!");
  658. }
  659. // Indirectbr can interfere with exit block canonicalization.
  660. if (!L->hasDedicatedExits()) {
  661. bool HasIndBrExiting = false;
  662. SmallVector<BasicBlock*, 8> ExitingBlocks;
  663. L->getExitingBlocks(ExitingBlocks);
  664. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i)
  665. if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
  666. HasIndBrExiting = true;
  667. break;
  668. }
  669. assert(HasIndBrExiting &&
  670. "LoopSimplify has no excuse for missing exit block info!");
  671. }
  672. }