LoopRotationUtils.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. //===----------------- LoopRotationUtils.cpp -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides utilities to convert a loop into a loop with bottom test.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/LoopRotationUtils.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/Analysis/BasicAliasAnalysis.h"
  16. #include "llvm/Analysis/CodeMetrics.h"
  17. #include "llvm/Analysis/DomTreeUpdater.h"
  18. #include "llvm/Analysis/GlobalsModRef.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/LoopPass.h"
  21. #include "llvm/Analysis/MemorySSA.h"
  22. #include "llvm/Analysis/MemorySSAUpdater.h"
  23. #include "llvm/Analysis/ScalarEvolution.h"
  24. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  25. #include "llvm/Analysis/TargetTransformInfo.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/IR/CFG.h"
  28. #include "llvm/IR/DebugInfo.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  37. #include "llvm/Transforms/Utils/Cloning.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Transforms/Utils/LoopUtils.h"
  40. #include "llvm/Transforms/Utils/SSAUpdater.h"
  41. #include "llvm/Transforms/Utils/ValueMapper.h"
  42. using namespace llvm;
  43. #define DEBUG_TYPE "loop-rotate"
  44. STATISTIC(NumNotRotatedDueToHeaderSize,
  45. "Number of loops not rotated due to the header size");
  46. STATISTIC(NumInstrsHoisted,
  47. "Number of instructions hoisted into loop preheader");
  48. STATISTIC(NumInstrsDuplicated,
  49. "Number of instructions cloned into loop preheader");
  50. STATISTIC(NumRotated, "Number of loops rotated");
  51. static cl::opt<bool>
  52. MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
  53. cl::desc("Allow loop rotation multiple times in order to reach "
  54. "a better latch exit"));
  55. namespace {
  56. /// A simple loop rotation transformation.
  57. class LoopRotate {
  58. const unsigned MaxHeaderSize;
  59. LoopInfo *LI;
  60. const TargetTransformInfo *TTI;
  61. AssumptionCache *AC;
  62. DominatorTree *DT;
  63. ScalarEvolution *SE;
  64. MemorySSAUpdater *MSSAU;
  65. const SimplifyQuery &SQ;
  66. bool RotationOnly;
  67. bool IsUtilMode;
  68. bool PrepareForLTO;
  69. public:
  70. LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
  71. const TargetTransformInfo *TTI, AssumptionCache *AC,
  72. DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
  73. const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
  74. bool PrepareForLTO)
  75. : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
  76. MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
  77. IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
  78. bool processLoop(Loop *L);
  79. private:
  80. bool rotateLoop(Loop *L, bool SimplifiedLatch);
  81. bool simplifyLoopLatch(Loop *L);
  82. };
  83. } // end anonymous namespace
  84. /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
  85. /// previously exist in the map, and the value was inserted.
  86. static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
  87. bool Inserted = VM.insert({K, V}).second;
  88. assert(Inserted);
  89. (void)Inserted;
  90. }
  91. /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
  92. /// old header into the preheader. If there were uses of the values produced by
  93. /// these instruction that were outside of the loop, we have to insert PHI nodes
  94. /// to merge the two values. Do this now.
  95. static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
  96. BasicBlock *OrigPreheader,
  97. ValueToValueMapTy &ValueMap,
  98. ScalarEvolution *SE,
  99. SmallVectorImpl<PHINode*> *InsertedPHIs) {
  100. // Remove PHI node entries that are no longer live.
  101. BasicBlock::iterator I, E = OrigHeader->end();
  102. for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
  103. PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
  104. // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
  105. // as necessary.
  106. SSAUpdater SSA(InsertedPHIs);
  107. for (I = OrigHeader->begin(); I != E; ++I) {
  108. Value *OrigHeaderVal = &*I;
  109. // If there are no uses of the value (e.g. because it returns void), there
  110. // is nothing to rewrite.
  111. if (OrigHeaderVal->use_empty())
  112. continue;
  113. Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
  114. // The value now exits in two versions: the initial value in the preheader
  115. // and the loop "next" value in the original header.
  116. SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
  117. // Force re-computation of OrigHeaderVal, as some users now need to use the
  118. // new PHI node.
  119. if (SE)
  120. SE->forgetValue(OrigHeaderVal);
  121. SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
  122. SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
  123. // Visit each use of the OrigHeader instruction.
  124. for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
  125. // SSAUpdater can't handle a non-PHI use in the same block as an
  126. // earlier def. We can easily handle those cases manually.
  127. Instruction *UserInst = cast<Instruction>(U.getUser());
  128. if (!isa<PHINode>(UserInst)) {
  129. BasicBlock *UserBB = UserInst->getParent();
  130. // The original users in the OrigHeader are already using the
  131. // original definitions.
  132. if (UserBB == OrigHeader)
  133. continue;
  134. // Users in the OrigPreHeader need to use the value to which the
  135. // original definitions are mapped.
  136. if (UserBB == OrigPreheader) {
  137. U = OrigPreHeaderVal;
  138. continue;
  139. }
  140. }
  141. // Anything else can be handled by SSAUpdater.
  142. SSA.RewriteUse(U);
  143. }
  144. // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
  145. // intrinsics.
  146. SmallVector<DbgValueInst *, 1> DbgValues;
  147. llvm::findDbgValues(DbgValues, OrigHeaderVal);
  148. for (auto &DbgValue : DbgValues) {
  149. // The original users in the OrigHeader are already using the original
  150. // definitions.
  151. BasicBlock *UserBB = DbgValue->getParent();
  152. if (UserBB == OrigHeader)
  153. continue;
  154. // Users in the OrigPreHeader need to use the value to which the
  155. // original definitions are mapped and anything else can be handled by
  156. // the SSAUpdater. To avoid adding PHINodes, check if the value is
  157. // available in UserBB, if not substitute undef.
  158. Value *NewVal;
  159. if (UserBB == OrigPreheader)
  160. NewVal = OrigPreHeaderVal;
  161. else if (SSA.HasValueForBlock(UserBB))
  162. NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
  163. else
  164. NewVal = UndefValue::get(OrigHeaderVal->getType());
  165. DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
  166. }
  167. }
  168. }
  169. // Assuming both header and latch are exiting, look for a phi which is only
  170. // used outside the loop (via a LCSSA phi) in the exit from the header.
  171. // This means that rotating the loop can remove the phi.
  172. static bool profitableToRotateLoopExitingLatch(Loop *L) {
  173. BasicBlock *Header = L->getHeader();
  174. BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
  175. assert(BI && BI->isConditional() && "need header with conditional exit");
  176. BasicBlock *HeaderExit = BI->getSuccessor(0);
  177. if (L->contains(HeaderExit))
  178. HeaderExit = BI->getSuccessor(1);
  179. for (auto &Phi : Header->phis()) {
  180. // Look for uses of this phi in the loop/via exits other than the header.
  181. if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
  182. return cast<Instruction>(U)->getParent() != HeaderExit;
  183. }))
  184. continue;
  185. return true;
  186. }
  187. return false;
  188. }
  189. // Check that latch exit is deoptimizing (which means - very unlikely to happen)
  190. // and there is another exit from the loop which is non-deoptimizing.
  191. // If we rotate latch to that exit our loop has a better chance of being fully
  192. // canonical.
  193. //
  194. // It can give false positives in some rare cases.
  195. static bool canRotateDeoptimizingLatchExit(Loop *L) {
  196. BasicBlock *Latch = L->getLoopLatch();
  197. assert(Latch && "need latch");
  198. BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
  199. // Need normal exiting latch.
  200. if (!BI || !BI->isConditional())
  201. return false;
  202. BasicBlock *Exit = BI->getSuccessor(1);
  203. if (L->contains(Exit))
  204. Exit = BI->getSuccessor(0);
  205. // Latch exit is non-deoptimizing, no need to rotate.
  206. if (!Exit->getPostdominatingDeoptimizeCall())
  207. return false;
  208. SmallVector<BasicBlock *, 4> Exits;
  209. L->getUniqueExitBlocks(Exits);
  210. if (!Exits.empty()) {
  211. // There is at least one non-deoptimizing exit.
  212. //
  213. // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
  214. // as it can conservatively return false for deoptimizing exits with
  215. // complex enough control flow down to deoptimize call.
  216. //
  217. // That means here we can report success for a case where
  218. // all exits are deoptimizing but one of them has complex enough
  219. // control flow (e.g. with loops).
  220. //
  221. // That should be a very rare case and false positives for this function
  222. // have compile-time effect only.
  223. return any_of(Exits, [](const BasicBlock *BB) {
  224. return !BB->getPostdominatingDeoptimizeCall();
  225. });
  226. }
  227. return false;
  228. }
  229. /// Rotate loop LP. Return true if the loop is rotated.
  230. ///
  231. /// \param SimplifiedLatch is true if the latch was just folded into the final
  232. /// loop exit. In this case we may want to rotate even though the new latch is
  233. /// now an exiting branch. This rotation would have happened had the latch not
  234. /// been simplified. However, if SimplifiedLatch is false, then we avoid
  235. /// rotating loops in which the latch exits to avoid excessive or endless
  236. /// rotation. LoopRotate should be repeatable and converge to a canonical
  237. /// form. This property is satisfied because simplifying the loop latch can only
  238. /// happen once across multiple invocations of the LoopRotate pass.
  239. ///
  240. /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
  241. /// so to reach a suitable (non-deoptimizing) exit.
  242. bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
  243. // If the loop has only one block then there is not much to rotate.
  244. if (L->getBlocks().size() == 1)
  245. return false;
  246. bool Rotated = false;
  247. do {
  248. BasicBlock *OrigHeader = L->getHeader();
  249. BasicBlock *OrigLatch = L->getLoopLatch();
  250. BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
  251. if (!BI || BI->isUnconditional())
  252. return Rotated;
  253. // If the loop header is not one of the loop exiting blocks then
  254. // either this loop is already rotated or it is not
  255. // suitable for loop rotation transformations.
  256. if (!L->isLoopExiting(OrigHeader))
  257. return Rotated;
  258. // If the loop latch already contains a branch that leaves the loop then the
  259. // loop is already rotated.
  260. if (!OrigLatch)
  261. return Rotated;
  262. // Rotate if either the loop latch does *not* exit the loop, or if the loop
  263. // latch was just simplified. Or if we think it will be profitable.
  264. if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
  265. !profitableToRotateLoopExitingLatch(L) &&
  266. !canRotateDeoptimizingLatchExit(L))
  267. return Rotated;
  268. // Check size of original header and reject loop if it is very big or we can't
  269. // duplicate blocks inside it.
  270. {
  271. SmallPtrSet<const Value *, 32> EphValues;
  272. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  273. CodeMetrics Metrics;
  274. Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
  275. if (Metrics.notDuplicatable) {
  276. LLVM_DEBUG(
  277. dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
  278. << " instructions: ";
  279. L->dump());
  280. return Rotated;
  281. }
  282. if (Metrics.convergent) {
  283. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
  284. "instructions: ";
  285. L->dump());
  286. return Rotated;
  287. }
  288. if (Metrics.NumInsts > MaxHeaderSize) {
  289. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
  290. << Metrics.NumInsts
  291. << " instructions, which is more than the threshold ("
  292. << MaxHeaderSize << " instructions): ";
  293. L->dump());
  294. ++NumNotRotatedDueToHeaderSize;
  295. return Rotated;
  296. }
  297. // When preparing for LTO, avoid rotating loops with calls that could be
  298. // inlined during the LTO stage.
  299. if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
  300. return Rotated;
  301. }
  302. // Now, this loop is suitable for rotation.
  303. BasicBlock *OrigPreheader = L->getLoopPreheader();
  304. // If the loop could not be converted to canonical form, it must have an
  305. // indirectbr in it, just give up.
  306. if (!OrigPreheader || !L->hasDedicatedExits())
  307. return Rotated;
  308. // Anything ScalarEvolution may know about this loop or the PHI nodes
  309. // in its header will soon be invalidated. We should also invalidate
  310. // all outer loops because insertion and deletion of blocks that happens
  311. // during the rotation may violate invariants related to backedge taken
  312. // infos in them.
  313. if (SE)
  314. SE->forgetTopmostLoop(L);
  315. LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
  316. if (MSSAU && VerifyMemorySSA)
  317. MSSAU->getMemorySSA()->verifyMemorySSA();
  318. // Find new Loop header. NewHeader is a Header's one and only successor
  319. // that is inside loop. Header's other successor is outside the
  320. // loop. Otherwise loop is not suitable for rotation.
  321. BasicBlock *Exit = BI->getSuccessor(0);
  322. BasicBlock *NewHeader = BI->getSuccessor(1);
  323. if (L->contains(Exit))
  324. std::swap(Exit, NewHeader);
  325. assert(NewHeader && "Unable to determine new loop header");
  326. assert(L->contains(NewHeader) && !L->contains(Exit) &&
  327. "Unable to determine loop header and exit blocks");
  328. // This code assumes that the new header has exactly one predecessor.
  329. // Remove any single-entry PHI nodes in it.
  330. assert(NewHeader->getSinglePredecessor() &&
  331. "New header doesn't have one pred!");
  332. FoldSingleEntryPHINodes(NewHeader);
  333. // Begin by walking OrigHeader and populating ValueMap with an entry for
  334. // each Instruction.
  335. BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
  336. ValueToValueMapTy ValueMap, ValueMapMSSA;
  337. // For PHI nodes, the value available in OldPreHeader is just the
  338. // incoming value from OldPreHeader.
  339. for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
  340. InsertNewValueIntoMap(ValueMap, PN,
  341. PN->getIncomingValueForBlock(OrigPreheader));
  342. // For the rest of the instructions, either hoist to the OrigPreheader if
  343. // possible or create a clone in the OldPreHeader if not.
  344. Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
  345. // Record all debug intrinsics preceding LoopEntryBranch to avoid
  346. // duplication.
  347. using DbgIntrinsicHash =
  348. std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
  349. auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
  350. auto VarLocOps = D->location_ops();
  351. return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
  352. D->getVariable()},
  353. D->getExpression()};
  354. };
  355. SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
  356. for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
  357. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
  358. DbgIntrinsics.insert(makeHash(DII));
  359. else
  360. break;
  361. }
  362. // Remember the local noalias scope declarations in the header. After the
  363. // rotation, they must be duplicated and the scope must be cloned. This
  364. // avoids unwanted interaction across iterations.
  365. SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
  366. for (Instruction &I : *OrigHeader)
  367. if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
  368. NoAliasDeclInstructions.push_back(Decl);
  369. while (I != E) {
  370. Instruction *Inst = &*I++;
  371. // If the instruction's operands are invariant and it doesn't read or write
  372. // memory, then it is safe to hoist. Doing this doesn't change the order of
  373. // execution in the preheader, but does prevent the instruction from
  374. // executing in each iteration of the loop. This means it is safe to hoist
  375. // something that might trap, but isn't safe to hoist something that reads
  376. // memory (without proving that the loop doesn't write).
  377. if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
  378. !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
  379. !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
  380. Inst->moveBefore(LoopEntryBranch);
  381. ++NumInstrsHoisted;
  382. continue;
  383. }
  384. // Otherwise, create a duplicate of the instruction.
  385. Instruction *C = Inst->clone();
  386. ++NumInstrsDuplicated;
  387. // Eagerly remap the operands of the instruction.
  388. RemapInstruction(C, ValueMap,
  389. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  390. // Avoid inserting the same intrinsic twice.
  391. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
  392. if (DbgIntrinsics.count(makeHash(DII))) {
  393. C->deleteValue();
  394. continue;
  395. }
  396. // With the operands remapped, see if the instruction constant folds or is
  397. // otherwise simplifyable. This commonly occurs because the entry from PHI
  398. // nodes allows icmps and other instructions to fold.
  399. Value *V = SimplifyInstruction(C, SQ);
  400. if (V && LI->replacementPreservesLCSSAForm(C, V)) {
  401. // If so, then delete the temporary instruction and stick the folded value
  402. // in the map.
  403. InsertNewValueIntoMap(ValueMap, Inst, V);
  404. if (!C->mayHaveSideEffects()) {
  405. C->deleteValue();
  406. C = nullptr;
  407. }
  408. } else {
  409. InsertNewValueIntoMap(ValueMap, Inst, C);
  410. }
  411. if (C) {
  412. // Otherwise, stick the new instruction into the new block!
  413. C->setName(Inst->getName());
  414. C->insertBefore(LoopEntryBranch);
  415. if (auto *II = dyn_cast<AssumeInst>(C))
  416. AC->registerAssumption(II);
  417. // MemorySSA cares whether the cloned instruction was inserted or not, and
  418. // not whether it can be remapped to a simplified value.
  419. if (MSSAU)
  420. InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
  421. }
  422. }
  423. if (!NoAliasDeclInstructions.empty()) {
  424. // There are noalias scope declarations:
  425. // (general):
  426. // Original: OrigPre { OrigHeader NewHeader ... Latch }
  427. // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
  428. //
  429. // with D: llvm.experimental.noalias.scope.decl,
  430. // U: !noalias or !alias.scope depending on D
  431. // ... { D U1 U2 } can transform into:
  432. // (0) : ... { D U1 U2 } // no relevant rotation for this part
  433. // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
  434. // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
  435. //
  436. // We now want to transform:
  437. // (1) -> : ... D' { D U1 U2 D'' }
  438. // (2) -> : ... D' U1' { D U2 D'' U1'' }
  439. // D: original llvm.experimental.noalias.scope.decl
  440. // D', U1': duplicate with replaced scopes
  441. // D'', U1'': different duplicate with replaced scopes
  442. // This ensures a safe fallback to 'may_alias' introduced by the rotate,
  443. // as U1'' and U1' scopes will not be compatible wrt to the local restrict
  444. // Clone the llvm.experimental.noalias.decl again for the NewHeader.
  445. Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
  446. for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
  447. LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
  448. << *NAD << "\n");
  449. Instruction *NewNAD = NAD->clone();
  450. NewNAD->insertBefore(NewHeaderInsertionPoint);
  451. }
  452. // Scopes must now be duplicated, once for OrigHeader and once for
  453. // OrigPreHeader'.
  454. {
  455. auto &Context = NewHeader->getContext();
  456. SmallVector<MDNode *, 8> NoAliasDeclScopes;
  457. for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
  458. NoAliasDeclScopes.push_back(NAD->getScopeList());
  459. LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
  460. cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
  461. "h.rot");
  462. LLVM_DEBUG(OrigHeader->dump());
  463. // Keep the compile time impact low by only adapting the inserted block
  464. // of instructions in the OrigPreHeader. This might result in slightly
  465. // more aliasing between these instructions and those that were already
  466. // present, but it will be much faster when the original PreHeader is
  467. // large.
  468. LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
  469. auto *FirstDecl =
  470. cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
  471. auto *LastInst = &OrigPreheader->back();
  472. cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
  473. Context, "pre.rot");
  474. LLVM_DEBUG(OrigPreheader->dump());
  475. LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
  476. LLVM_DEBUG(NewHeader->dump());
  477. }
  478. }
  479. // Along with all the other instructions, we just cloned OrigHeader's
  480. // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
  481. // successors by duplicating their incoming values for OrigHeader.
  482. for (BasicBlock *SuccBB : successors(OrigHeader))
  483. for (BasicBlock::iterator BI = SuccBB->begin();
  484. PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  485. PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
  486. // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
  487. // OrigPreHeader's old terminator (the original branch into the loop), and
  488. // remove the corresponding incoming values from the PHI nodes in OrigHeader.
  489. LoopEntryBranch->eraseFromParent();
  490. // Update MemorySSA before the rewrite call below changes the 1:1
  491. // instruction:cloned_instruction_or_value mapping.
  492. if (MSSAU) {
  493. InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
  494. MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
  495. ValueMapMSSA);
  496. }
  497. SmallVector<PHINode*, 2> InsertedPHIs;
  498. // If there were any uses of instructions in the duplicated block outside the
  499. // loop, update them, inserting PHI nodes as required
  500. RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
  501. &InsertedPHIs);
  502. // Attach dbg.value intrinsics to the new phis if that phi uses a value that
  503. // previously had debug metadata attached. This keeps the debug info
  504. // up-to-date in the loop body.
  505. if (!InsertedPHIs.empty())
  506. insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
  507. // NewHeader is now the header of the loop.
  508. L->moveToHeader(NewHeader);
  509. assert(L->getHeader() == NewHeader && "Latch block is our new header");
  510. // Inform DT about changes to the CFG.
  511. if (DT) {
  512. // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
  513. // the DT about the removed edge to the OrigHeader (that got removed).
  514. SmallVector<DominatorTree::UpdateType, 3> Updates;
  515. Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
  516. Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
  517. Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
  518. if (MSSAU) {
  519. MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
  520. if (VerifyMemorySSA)
  521. MSSAU->getMemorySSA()->verifyMemorySSA();
  522. } else {
  523. DT->applyUpdates(Updates);
  524. }
  525. }
  526. // At this point, we've finished our major CFG changes. As part of cloning
  527. // the loop into the preheader we've simplified instructions and the
  528. // duplicated conditional branch may now be branching on a constant. If it is
  529. // branching on a constant and if that constant means that we enter the loop,
  530. // then we fold away the cond branch to an uncond branch. This simplifies the
  531. // loop in cases important for nested loops, and it also means we don't have
  532. // to split as many edges.
  533. BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
  534. assert(PHBI->isConditional() && "Should be clone of BI condbr!");
  535. if (!isa<ConstantInt>(PHBI->getCondition()) ||
  536. PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
  537. NewHeader) {
  538. // The conditional branch can't be folded, handle the general case.
  539. // Split edges as necessary to preserve LoopSimplify form.
  540. // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
  541. // thus is not a preheader anymore.
  542. // Split the edge to form a real preheader.
  543. BasicBlock *NewPH = SplitCriticalEdge(
  544. OrigPreheader, NewHeader,
  545. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
  546. NewPH->setName(NewHeader->getName() + ".lr.ph");
  547. // Preserve canonical loop form, which means that 'Exit' should have only
  548. // one predecessor. Note that Exit could be an exit block for multiple
  549. // nested loops, causing both of the edges to now be critical and need to
  550. // be split.
  551. SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
  552. bool SplitLatchEdge = false;
  553. for (BasicBlock *ExitPred : ExitPreds) {
  554. // We only need to split loop exit edges.
  555. Loop *PredLoop = LI->getLoopFor(ExitPred);
  556. if (!PredLoop || PredLoop->contains(Exit) ||
  557. ExitPred->getTerminator()->isIndirectTerminator())
  558. continue;
  559. SplitLatchEdge |= L->getLoopLatch() == ExitPred;
  560. BasicBlock *ExitSplit = SplitCriticalEdge(
  561. ExitPred, Exit,
  562. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
  563. ExitSplit->moveBefore(Exit);
  564. }
  565. assert(SplitLatchEdge &&
  566. "Despite splitting all preds, failed to split latch exit?");
  567. (void)SplitLatchEdge;
  568. } else {
  569. // We can fold the conditional branch in the preheader, this makes things
  570. // simpler. The first step is to remove the extra edge to the Exit block.
  571. Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
  572. BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
  573. NewBI->setDebugLoc(PHBI->getDebugLoc());
  574. PHBI->eraseFromParent();
  575. // With our CFG finalized, update DomTree if it is available.
  576. if (DT) DT->deleteEdge(OrigPreheader, Exit);
  577. // Update MSSA too, if available.
  578. if (MSSAU)
  579. MSSAU->removeEdge(OrigPreheader, Exit);
  580. }
  581. assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
  582. assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
  583. if (MSSAU && VerifyMemorySSA)
  584. MSSAU->getMemorySSA()->verifyMemorySSA();
  585. // Now that the CFG and DomTree are in a consistent state again, try to merge
  586. // the OrigHeader block into OrigLatch. This will succeed if they are
  587. // connected by an unconditional branch. This is just a cleanup so the
  588. // emitted code isn't too gross in this common case.
  589. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  590. BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
  591. bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
  592. if (DidMerge)
  593. RemoveRedundantDbgInstrs(PredBB);
  594. if (MSSAU && VerifyMemorySSA)
  595. MSSAU->getMemorySSA()->verifyMemorySSA();
  596. LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
  597. ++NumRotated;
  598. Rotated = true;
  599. SimplifiedLatch = false;
  600. // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
  601. // Deoptimizing latch exit is not a generally typical case, so we just loop over.
  602. // TODO: if it becomes a performance bottleneck extend rotation algorithm
  603. // to handle multiple rotations in one go.
  604. } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
  605. return true;
  606. }
  607. /// Determine whether the instructions in this range may be safely and cheaply
  608. /// speculated. This is not an important enough situation to develop complex
  609. /// heuristics. We handle a single arithmetic instruction along with any type
  610. /// conversions.
  611. static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
  612. BasicBlock::iterator End, Loop *L) {
  613. bool seenIncrement = false;
  614. bool MultiExitLoop = false;
  615. if (!L->getExitingBlock())
  616. MultiExitLoop = true;
  617. for (BasicBlock::iterator I = Begin; I != End; ++I) {
  618. if (!isSafeToSpeculativelyExecute(&*I))
  619. return false;
  620. if (isa<DbgInfoIntrinsic>(I))
  621. continue;
  622. switch (I->getOpcode()) {
  623. default:
  624. return false;
  625. case Instruction::GetElementPtr:
  626. // GEPs are cheap if all indices are constant.
  627. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  628. return false;
  629. // fall-thru to increment case
  630. LLVM_FALLTHROUGH;
  631. case Instruction::Add:
  632. case Instruction::Sub:
  633. case Instruction::And:
  634. case Instruction::Or:
  635. case Instruction::Xor:
  636. case Instruction::Shl:
  637. case Instruction::LShr:
  638. case Instruction::AShr: {
  639. Value *IVOpnd =
  640. !isa<Constant>(I->getOperand(0))
  641. ? I->getOperand(0)
  642. : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
  643. if (!IVOpnd)
  644. return false;
  645. // If increment operand is used outside of the loop, this speculation
  646. // could cause extra live range interference.
  647. if (MultiExitLoop) {
  648. for (User *UseI : IVOpnd->users()) {
  649. auto *UserInst = cast<Instruction>(UseI);
  650. if (!L->contains(UserInst))
  651. return false;
  652. }
  653. }
  654. if (seenIncrement)
  655. return false;
  656. seenIncrement = true;
  657. break;
  658. }
  659. case Instruction::Trunc:
  660. case Instruction::ZExt:
  661. case Instruction::SExt:
  662. // ignore type conversions
  663. break;
  664. }
  665. }
  666. return true;
  667. }
  668. /// Fold the loop tail into the loop exit by speculating the loop tail
  669. /// instructions. Typically, this is a single post-increment. In the case of a
  670. /// simple 2-block loop, hoisting the increment can be much better than
  671. /// duplicating the entire loop header. In the case of loops with early exits,
  672. /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
  673. /// canonical form so downstream passes can handle it.
  674. ///
  675. /// I don't believe this invalidates SCEV.
  676. bool LoopRotate::simplifyLoopLatch(Loop *L) {
  677. BasicBlock *Latch = L->getLoopLatch();
  678. if (!Latch || Latch->hasAddressTaken())
  679. return false;
  680. BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
  681. if (!Jmp || !Jmp->isUnconditional())
  682. return false;
  683. BasicBlock *LastExit = Latch->getSinglePredecessor();
  684. if (!LastExit || !L->isLoopExiting(LastExit))
  685. return false;
  686. BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
  687. if (!BI)
  688. return false;
  689. if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
  690. return false;
  691. LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
  692. << LastExit->getName() << "\n");
  693. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  694. MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
  695. /*PredecessorWithTwoSuccessors=*/true);
  696. if (MSSAU && VerifyMemorySSA)
  697. MSSAU->getMemorySSA()->verifyMemorySSA();
  698. return true;
  699. }
  700. /// Rotate \c L, and return true if any modification was made.
  701. bool LoopRotate::processLoop(Loop *L) {
  702. // Save the loop metadata.
  703. MDNode *LoopMD = L->getLoopID();
  704. bool SimplifiedLatch = false;
  705. // Simplify the loop latch before attempting to rotate the header
  706. // upward. Rotation may not be needed if the loop tail can be folded into the
  707. // loop exit.
  708. if (!RotationOnly)
  709. SimplifiedLatch = simplifyLoopLatch(L);
  710. bool MadeChange = rotateLoop(L, SimplifiedLatch);
  711. assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
  712. "Loop latch should be exiting after loop-rotate.");
  713. // Restore the loop metadata.
  714. // NB! We presume LoopRotation DOESN'T ADD its own metadata.
  715. if ((MadeChange || SimplifiedLatch) && LoopMD)
  716. L->setLoopID(LoopMD);
  717. return MadeChange || SimplifiedLatch;
  718. }
  719. /// The utility to convert a loop into a loop with bottom test.
  720. bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
  721. AssumptionCache *AC, DominatorTree *DT,
  722. ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
  723. const SimplifyQuery &SQ, bool RotationOnly = true,
  724. unsigned Threshold = unsigned(-1),
  725. bool IsUtilMode = true, bool PrepareForLTO) {
  726. LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
  727. IsUtilMode, PrepareForLTO);
  728. return LR.processLoop(L);
  729. }