LoopSimplify.cpp 24 KB

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