LoopSimplify.cpp 28 KB

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