LoopRotation.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements Loop Rotation Pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/Analysis/AssumptionCache.h"
  16. #include "llvm/Analysis/CodeMetrics.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/LoopPass.h"
  19. #include "llvm/Analysis/ScalarEvolution.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  31. #include "llvm/Transforms/Utils/Local.h"
  32. #include "llvm/Transforms/Utils/SSAUpdater.h"
  33. #include "llvm/Transforms/Utils/ValueMapper.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "loop-rotate"
  36. #if 0 // HLSL Change Starts - option pending
  37. static cl::opt<unsigned>
  38. DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
  39. cl::desc("The default maximum header size for automatic loop rotation"));
  40. #else
  41. static const unsigned DefaultRotationThreshold = 16;
  42. #endif // HLSL Change Ends
  43. STATISTIC(NumRotated, "Number of loops rotated");
  44. namespace {
  45. class LoopRotate : public LoopPass {
  46. public:
  47. static char ID; // Pass ID, replacement for typeid
  48. LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
  49. initializeLoopRotatePass(*PassRegistry::getPassRegistry());
  50. if (SpecifiedMaxHeaderSize == -1)
  51. MaxHeaderSize = DefaultRotationThreshold;
  52. else
  53. MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
  54. }
  55. // LCSSA form makes instruction renaming easier.
  56. void getAnalysisUsage(AnalysisUsage &AU) const override {
  57. AU.addRequired<AssumptionCacheTracker>();
  58. AU.addPreserved<DominatorTreeWrapperPass>();
  59. AU.addRequired<LoopInfoWrapperPass>();
  60. AU.addPreserved<LoopInfoWrapperPass>();
  61. AU.addRequiredID(LoopSimplifyID);
  62. AU.addPreservedID(LoopSimplifyID);
  63. AU.addRequiredID(LCSSAID);
  64. AU.addPreservedID(LCSSAID);
  65. AU.addPreserved<ScalarEvolution>();
  66. AU.addRequired<TargetTransformInfoWrapperPass>();
  67. }
  68. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  69. bool simplifyLoopLatch(Loop *L);
  70. bool rotateLoop(Loop *L, bool SimplifiedLatch);
  71. private:
  72. unsigned MaxHeaderSize;
  73. LoopInfo *LI;
  74. const TargetTransformInfo *TTI;
  75. AssumptionCache *AC;
  76. DominatorTree *DT;
  77. };
  78. }
  79. char LoopRotate::ID = 0;
  80. INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
  81. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  82. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  83. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  84. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  85. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  86. INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
  87. Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
  88. return new LoopRotate(MaxHeaderSize);
  89. }
  90. /// Rotate Loop L as many times as possible. Return true if
  91. /// the loop is rotated at least once.
  92. bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
  93. if (skipOptnoneFunction(L))
  94. return false;
  95. // Save the loop metadata.
  96. MDNode *LoopMD = L->getLoopID();
  97. Function &F = *L->getHeader()->getParent();
  98. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  99. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  100. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  101. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  102. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  103. // Simplify the loop latch before attempting to rotate the header
  104. // upward. Rotation may not be needed if the loop tail can be folded into the
  105. // loop exit.
  106. bool SimplifiedLatch = simplifyLoopLatch(L);
  107. // One loop can be rotated multiple times.
  108. bool MadeChange = false;
  109. while (rotateLoop(L, SimplifiedLatch)) {
  110. MadeChange = true;
  111. SimplifiedLatch = false;
  112. }
  113. // Restore the loop metadata.
  114. // NB! We presume LoopRotation DOESN'T ADD its own metadata.
  115. if ((MadeChange || SimplifiedLatch) && LoopMD)
  116. L->setLoopID(LoopMD);
  117. return MadeChange;
  118. }
  119. /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
  120. /// old header into the preheader. If there were uses of the values produced by
  121. /// these instruction that were outside of the loop, we have to insert PHI nodes
  122. /// to merge the two values. Do this now.
  123. static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
  124. BasicBlock *OrigPreheader,
  125. ValueToValueMapTy &ValueMap) {
  126. // Remove PHI node entries that are no longer live.
  127. BasicBlock::iterator I, E = OrigHeader->end();
  128. for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
  129. PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
  130. // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
  131. // as necessary.
  132. SSAUpdater SSA;
  133. for (I = OrigHeader->begin(); I != E; ++I) {
  134. Value *OrigHeaderVal = I;
  135. // If there are no uses of the value (e.g. because it returns void), there
  136. // is nothing to rewrite.
  137. if (OrigHeaderVal->use_empty())
  138. continue;
  139. Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
  140. // The value now exits in two versions: the initial value in the preheader
  141. // and the loop "next" value in the original header.
  142. SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
  143. SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
  144. SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
  145. // Visit each use of the OrigHeader instruction.
  146. for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
  147. UE = OrigHeaderVal->use_end(); UI != UE; ) {
  148. // Grab the use before incrementing the iterator.
  149. Use &U = *UI;
  150. // Increment the iterator before removing the use from the list.
  151. ++UI;
  152. // SSAUpdater can't handle a non-PHI use in the same block as an
  153. // earlier def. We can easily handle those cases manually.
  154. Instruction *UserInst = cast<Instruction>(U.getUser());
  155. if (!isa<PHINode>(UserInst)) {
  156. BasicBlock *UserBB = UserInst->getParent();
  157. // The original users in the OrigHeader are already using the
  158. // original definitions.
  159. if (UserBB == OrigHeader)
  160. continue;
  161. // Users in the OrigPreHeader need to use the value to which the
  162. // original definitions are mapped.
  163. if (UserBB == OrigPreheader) {
  164. U = OrigPreHeaderVal;
  165. continue;
  166. }
  167. }
  168. // Anything else can be handled by SSAUpdater.
  169. SSA.RewriteUse(U);
  170. }
  171. }
  172. }
  173. /// Determine whether the instructions in this range may be safely and cheaply
  174. /// speculated. This is not an important enough situation to develop complex
  175. /// heuristics. We handle a single arithmetic instruction along with any type
  176. /// conversions.
  177. static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
  178. BasicBlock::iterator End, Loop *L) {
  179. bool seenIncrement = false;
  180. bool MultiExitLoop = false;
  181. if (!L->getExitingBlock())
  182. MultiExitLoop = true;
  183. for (BasicBlock::iterator I = Begin; I != End; ++I) {
  184. if (!isSafeToSpeculativelyExecute(I))
  185. return false;
  186. if (isa<DbgInfoIntrinsic>(I))
  187. continue;
  188. switch (I->getOpcode()) {
  189. default:
  190. return false;
  191. case Instruction::GetElementPtr:
  192. // GEPs are cheap if all indices are constant.
  193. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  194. return false;
  195. // fall-thru to increment case
  196. case Instruction::Add:
  197. case Instruction::Sub:
  198. case Instruction::And:
  199. case Instruction::Or:
  200. case Instruction::Xor:
  201. case Instruction::Shl:
  202. case Instruction::LShr:
  203. case Instruction::AShr: {
  204. Value *IVOpnd = !isa<Constant>(I->getOperand(0))
  205. ? I->getOperand(0)
  206. : !isa<Constant>(I->getOperand(1))
  207. ? I->getOperand(1)
  208. : nullptr;
  209. if (!IVOpnd)
  210. return false;
  211. // If increment operand is used outside of the loop, this speculation
  212. // could cause extra live range interference.
  213. if (MultiExitLoop) {
  214. for (User *UseI : IVOpnd->users()) {
  215. auto *UserInst = cast<Instruction>(UseI);
  216. if (!L->contains(UserInst))
  217. return false;
  218. }
  219. }
  220. if (seenIncrement)
  221. return false;
  222. seenIncrement = true;
  223. break;
  224. }
  225. case Instruction::Trunc:
  226. case Instruction::ZExt:
  227. case Instruction::SExt:
  228. // ignore type conversions
  229. break;
  230. }
  231. }
  232. return true;
  233. }
  234. /// Fold the loop tail into the loop exit by speculating the loop tail
  235. /// instructions. Typically, this is a single post-increment. In the case of a
  236. /// simple 2-block loop, hoisting the increment can be much better than
  237. /// duplicating the entire loop header. In the case of loops with early exits,
  238. /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
  239. /// canonical form so downstream passes can handle it.
  240. ///
  241. /// I don't believe this invalidates SCEV.
  242. bool LoopRotate::simplifyLoopLatch(Loop *L) {
  243. BasicBlock *Latch = L->getLoopLatch();
  244. if (!Latch || Latch->hasAddressTaken())
  245. return false;
  246. BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
  247. if (!Jmp || !Jmp->isUnconditional())
  248. return false;
  249. BasicBlock *LastExit = Latch->getSinglePredecessor();
  250. if (!LastExit || !L->isLoopExiting(LastExit))
  251. return false;
  252. BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
  253. if (!BI)
  254. return false;
  255. if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
  256. return false;
  257. DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
  258. << LastExit->getName() << "\n");
  259. // Hoist the instructions from Latch into LastExit.
  260. LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
  261. unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
  262. BasicBlock *Header = Jmp->getSuccessor(0);
  263. assert(Header == L->getHeader() && "expected a backward branch");
  264. // Remove Latch from the CFG so that LastExit becomes the new Latch.
  265. BI->setSuccessor(FallThruPath, Header);
  266. Latch->replaceSuccessorsPhiUsesWith(LastExit);
  267. Jmp->eraseFromParent();
  268. // Nuke the Latch block.
  269. assert(Latch->empty() && "unable to evacuate Latch");
  270. LI->removeBlock(Latch);
  271. if (DT)
  272. DT->eraseNode(Latch);
  273. Latch->eraseFromParent();
  274. return true;
  275. }
  276. /// Rotate loop LP. Return true if the loop is rotated.
  277. ///
  278. /// \param SimplifiedLatch is true if the latch was just folded into the final
  279. /// loop exit. In this case we may want to rotate even though the new latch is
  280. /// now an exiting branch. This rotation would have happened had the latch not
  281. /// been simplified. However, if SimplifiedLatch is false, then we avoid
  282. /// rotating loops in which the latch exits to avoid excessive or endless
  283. /// rotation. LoopRotate should be repeatable and converge to a canonical
  284. /// form. This property is satisfied because simplifying the loop latch can only
  285. /// happen once across multiple invocations of the LoopRotate pass.
  286. bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
  287. // If the loop has only one block then there is not much to rotate.
  288. if (L->getBlocks().size() == 1)
  289. return false;
  290. BasicBlock *OrigHeader = L->getHeader();
  291. BasicBlock *OrigLatch = L->getLoopLatch();
  292. BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
  293. if (!BI || BI->isUnconditional())
  294. return false;
  295. // If the loop header is not one of the loop exiting blocks then
  296. // either this loop is already rotated or it is not
  297. // suitable for loop rotation transformations.
  298. if (!L->isLoopExiting(OrigHeader))
  299. return false;
  300. // If the loop latch already contains a branch that leaves the loop then the
  301. // loop is already rotated.
  302. if (!OrigLatch)
  303. return false;
  304. // Rotate if either the loop latch does *not* exit the loop, or if the loop
  305. // latch was just simplified.
  306. if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
  307. return false;
  308. // Check size of original header and reject loop if it is very big or we can't
  309. // duplicate blocks inside it.
  310. {
  311. SmallPtrSet<const Value *, 32> EphValues;
  312. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  313. CodeMetrics Metrics;
  314. Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
  315. if (Metrics.notDuplicatable) {
  316. DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
  317. << " instructions: "; L->dump());
  318. return false;
  319. }
  320. if (Metrics.NumInsts > MaxHeaderSize)
  321. return false;
  322. }
  323. // Now, this loop is suitable for rotation.
  324. BasicBlock *OrigPreheader = L->getLoopPreheader();
  325. // If the loop could not be converted to canonical form, it must have an
  326. // indirectbr in it, just give up.
  327. if (!OrigPreheader)
  328. return false;
  329. // Anything ScalarEvolution may know about this loop or the PHI nodes
  330. // in its header will soon be invalidated.
  331. if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
  332. SE->forgetLoop(L);
  333. DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
  334. // Find new Loop header. NewHeader is a Header's one and only successor
  335. // that is inside loop. Header's other successor is outside the
  336. // loop. Otherwise loop is not suitable for rotation.
  337. BasicBlock *Exit = BI->getSuccessor(0);
  338. BasicBlock *NewHeader = BI->getSuccessor(1);
  339. if (L->contains(Exit))
  340. std::swap(Exit, NewHeader);
  341. assert(NewHeader && "Unable to determine new loop header");
  342. assert(L->contains(NewHeader) && !L->contains(Exit) &&
  343. "Unable to determine loop header and exit blocks");
  344. // This code assumes that the new header has exactly one predecessor.
  345. // Remove any single-entry PHI nodes in it.
  346. assert(NewHeader->getSinglePredecessor() &&
  347. "New header doesn't have one pred!");
  348. FoldSingleEntryPHINodes(NewHeader);
  349. // Begin by walking OrigHeader and populating ValueMap with an entry for
  350. // each Instruction.
  351. BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
  352. ValueToValueMapTy ValueMap;
  353. // For PHI nodes, the value available in OldPreHeader is just the
  354. // incoming value from OldPreHeader.
  355. for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
  356. ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
  357. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  358. // For the rest of the instructions, either hoist to the OrigPreheader if
  359. // possible or create a clone in the OldPreHeader if not.
  360. TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
  361. while (I != E) {
  362. Instruction *Inst = I++;
  363. // If the instruction's operands are invariant and it doesn't read or write
  364. // memory, then it is safe to hoist. Doing this doesn't change the order of
  365. // execution in the preheader, but does prevent the instruction from
  366. // executing in each iteration of the loop. This means it is safe to hoist
  367. // something that might trap, but isn't safe to hoist something that reads
  368. // memory (without proving that the loop doesn't write).
  369. if (L->hasLoopInvariantOperands(Inst) &&
  370. !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
  371. !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
  372. !isa<AllocaInst>(Inst)) {
  373. Inst->moveBefore(LoopEntryBranch);
  374. continue;
  375. }
  376. // Otherwise, create a duplicate of the instruction.
  377. Instruction *C = Inst->clone();
  378. // Eagerly remap the operands of the instruction.
  379. RemapInstruction(C, ValueMap,
  380. RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
  381. // With the operands remapped, see if the instruction constant folds or is
  382. // otherwise simplifyable. This commonly occurs because the entry from PHI
  383. // nodes allows icmps and other instructions to fold.
  384. // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
  385. Value *V = SimplifyInstruction(C, DL);
  386. if (V && LI->replacementPreservesLCSSAForm(C, V)) {
  387. // If so, then delete the temporary instruction and stick the folded value
  388. // in the map.
  389. delete C;
  390. ValueMap[Inst] = V;
  391. } else {
  392. // Otherwise, stick the new instruction into the new block!
  393. C->setName(Inst->getName());
  394. C->insertBefore(LoopEntryBranch);
  395. ValueMap[Inst] = C;
  396. }
  397. }
  398. // Along with all the other instructions, we just cloned OrigHeader's
  399. // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
  400. // successors by duplicating their incoming values for OrigHeader.
  401. TerminatorInst *TI = OrigHeader->getTerminator();
  402. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  403. for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
  404. PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  405. PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
  406. // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
  407. // OrigPreHeader's old terminator (the original branch into the loop), and
  408. // remove the corresponding incoming values from the PHI nodes in OrigHeader.
  409. LoopEntryBranch->eraseFromParent();
  410. // If there were any uses of instructions in the duplicated block outside the
  411. // loop, update them, inserting PHI nodes as required
  412. RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
  413. // NewHeader is now the header of the loop.
  414. L->moveToHeader(NewHeader);
  415. assert(L->getHeader() == NewHeader && "Latch block is our new header");
  416. // At this point, we've finished our major CFG changes. As part of cloning
  417. // the loop into the preheader we've simplified instructions and the
  418. // duplicated conditional branch may now be branching on a constant. If it is
  419. // branching on a constant and if that constant means that we enter the loop,
  420. // then we fold away the cond branch to an uncond branch. This simplifies the
  421. // loop in cases important for nested loops, and it also means we don't have
  422. // to split as many edges.
  423. BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
  424. assert(PHBI->isConditional() && "Should be clone of BI condbr!");
  425. if (!isa<ConstantInt>(PHBI->getCondition()) ||
  426. PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
  427. != NewHeader) {
  428. // The conditional branch can't be folded, handle the general case.
  429. // Update DominatorTree to reflect the CFG change we just made. Then split
  430. // edges as necessary to preserve LoopSimplify form.
  431. if (DT) {
  432. // Everything that was dominated by the old loop header is now dominated
  433. // by the original loop preheader. Conceptually the header was merged
  434. // into the preheader, even though we reuse the actual block as a new
  435. // loop latch.
  436. DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
  437. SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
  438. OrigHeaderNode->end());
  439. DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
  440. for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
  441. DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
  442. assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
  443. assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
  444. // Update OrigHeader to be dominated by the new header block.
  445. DT->changeImmediateDominator(OrigHeader, OrigLatch);
  446. }
  447. // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
  448. // thus is not a preheader anymore.
  449. // Split the edge to form a real preheader.
  450. BasicBlock *NewPH = SplitCriticalEdge(
  451. OrigPreheader, NewHeader,
  452. CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  453. NewPH->setName(NewHeader->getName() + ".lr.ph");
  454. // Preserve canonical loop form, which means that 'Exit' should have only
  455. // one predecessor. Note that Exit could be an exit block for multiple
  456. // nested loops, causing both of the edges to now be critical and need to
  457. // be split.
  458. SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
  459. bool SplitLatchEdge = false;
  460. for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
  461. PE = ExitPreds.end();
  462. PI != PE; ++PI) {
  463. // We only need to split loop exit edges.
  464. Loop *PredLoop = LI->getLoopFor(*PI);
  465. if (!PredLoop || PredLoop->contains(Exit))
  466. continue;
  467. if (isa<IndirectBrInst>((*PI)->getTerminator()))
  468. continue;
  469. SplitLatchEdge |= L->getLoopLatch() == *PI;
  470. BasicBlock *ExitSplit = SplitCriticalEdge(
  471. *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  472. ExitSplit->moveBefore(Exit);
  473. }
  474. assert(SplitLatchEdge &&
  475. "Despite splitting all preds, failed to split latch exit?");
  476. } else {
  477. // We can fold the conditional branch in the preheader, this makes things
  478. // simpler. The first step is to remove the extra edge to the Exit block.
  479. Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
  480. BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
  481. NewBI->setDebugLoc(PHBI->getDebugLoc());
  482. PHBI->eraseFromParent();
  483. // With our CFG finalized, update DomTree if it is available.
  484. if (DT) {
  485. // Update OrigHeader to be dominated by the new header block.
  486. DT->changeImmediateDominator(NewHeader, OrigPreheader);
  487. DT->changeImmediateDominator(OrigHeader, OrigLatch);
  488. // Brute force incremental dominator tree update. Call
  489. // findNearestCommonDominator on all CFG predecessors of each child of the
  490. // original header.
  491. DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
  492. SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
  493. OrigHeaderNode->end());
  494. bool Changed;
  495. do {
  496. Changed = false;
  497. for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
  498. DomTreeNode *Node = HeaderChildren[I];
  499. BasicBlock *BB = Node->getBlock();
  500. pred_iterator PI = pred_begin(BB);
  501. BasicBlock *NearestDom = *PI;
  502. for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
  503. NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
  504. // Remember if this changes the DomTree.
  505. if (Node->getIDom()->getBlock() != NearestDom) {
  506. DT->changeImmediateDominator(BB, NearestDom);
  507. Changed = true;
  508. }
  509. }
  510. // If the dominator changed, this may have an effect on other
  511. // predecessors, continue until we reach a fixpoint.
  512. } while (Changed);
  513. }
  514. }
  515. assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
  516. assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
  517. // Now that the CFG and DomTree are in a consistent state again, try to merge
  518. // the OrigHeader block into OrigLatch. This will succeed if they are
  519. // connected by an unconditional branch. This is just a cleanup so the
  520. // emitted code isn't too gross in this common case.
  521. MergeBlockIntoPredecessor(OrigHeader, DT, LI);
  522. DEBUG(dbgs() << "LoopRotation: into "; L->dump());
  523. ++NumRotated;
  524. return true;
  525. }