109467b48Spatrick //===----------------- LoopRotationUtils.cpp -----------------------------===// 209467b48Spatrick // 309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information. 509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 609467b48Spatrick // 709467b48Spatrick //===----------------------------------------------------------------------===// 809467b48Spatrick // 909467b48Spatrick // This file provides utilities to convert a loop into a loop with bottom test. 1009467b48Spatrick // 1109467b48Spatrick //===----------------------------------------------------------------------===// 1209467b48Spatrick 1309467b48Spatrick #include "llvm/Transforms/Utils/LoopRotationUtils.h" 1409467b48Spatrick #include "llvm/ADT/Statistic.h" 1509467b48Spatrick #include "llvm/Analysis/AliasAnalysis.h" 1609467b48Spatrick #include "llvm/Analysis/AssumptionCache.h" 1709467b48Spatrick #include "llvm/Analysis/BasicAliasAnalysis.h" 1809467b48Spatrick #include "llvm/Analysis/CodeMetrics.h" 1909467b48Spatrick #include "llvm/Analysis/DomTreeUpdater.h" 2009467b48Spatrick #include "llvm/Analysis/GlobalsModRef.h" 2109467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h" 2209467b48Spatrick #include "llvm/Analysis/LoopPass.h" 2309467b48Spatrick #include "llvm/Analysis/MemorySSA.h" 2409467b48Spatrick #include "llvm/Analysis/MemorySSAUpdater.h" 2509467b48Spatrick #include "llvm/Analysis/ScalarEvolution.h" 2609467b48Spatrick #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 2709467b48Spatrick #include "llvm/Analysis/TargetTransformInfo.h" 2809467b48Spatrick #include "llvm/Analysis/ValueTracking.h" 2909467b48Spatrick #include "llvm/IR/CFG.h" 3009467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h" 3109467b48Spatrick #include "llvm/IR/Dominators.h" 3209467b48Spatrick #include "llvm/IR/Function.h" 3309467b48Spatrick #include "llvm/IR/IntrinsicInst.h" 3409467b48Spatrick #include "llvm/IR/Module.h" 3509467b48Spatrick #include "llvm/Support/CommandLine.h" 3609467b48Spatrick #include "llvm/Support/Debug.h" 3709467b48Spatrick #include "llvm/Support/raw_ostream.h" 3809467b48Spatrick #include "llvm/Transforms/Utils/BasicBlockUtils.h" 3909467b48Spatrick #include "llvm/Transforms/Utils/Local.h" 4009467b48Spatrick #include "llvm/Transforms/Utils/LoopUtils.h" 4109467b48Spatrick #include "llvm/Transforms/Utils/SSAUpdater.h" 4209467b48Spatrick #include "llvm/Transforms/Utils/ValueMapper.h" 4309467b48Spatrick using namespace llvm; 4409467b48Spatrick 4509467b48Spatrick #define DEBUG_TYPE "loop-rotate" 4609467b48Spatrick 4709467b48Spatrick STATISTIC(NumRotated, "Number of loops rotated"); 4809467b48Spatrick 49*097a140dSpatrick static cl::opt<bool> 50*097a140dSpatrick MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden, 51*097a140dSpatrick cl::desc("Allow loop rotation multiple times in order to reach " 52*097a140dSpatrick "a better latch exit")); 53*097a140dSpatrick 5409467b48Spatrick namespace { 5509467b48Spatrick /// A simple loop rotation transformation. 5609467b48Spatrick class LoopRotate { 5709467b48Spatrick const unsigned MaxHeaderSize; 5809467b48Spatrick LoopInfo *LI; 5909467b48Spatrick const TargetTransformInfo *TTI; 6009467b48Spatrick AssumptionCache *AC; 6109467b48Spatrick DominatorTree *DT; 6209467b48Spatrick ScalarEvolution *SE; 6309467b48Spatrick MemorySSAUpdater *MSSAU; 6409467b48Spatrick const SimplifyQuery &SQ; 6509467b48Spatrick bool RotationOnly; 6609467b48Spatrick bool IsUtilMode; 6709467b48Spatrick 6809467b48Spatrick public: 6909467b48Spatrick LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI, 7009467b48Spatrick const TargetTransformInfo *TTI, AssumptionCache *AC, 7109467b48Spatrick DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 7209467b48Spatrick const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode) 7309467b48Spatrick : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE), 7409467b48Spatrick MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly), 7509467b48Spatrick IsUtilMode(IsUtilMode) {} 7609467b48Spatrick bool processLoop(Loop *L); 7709467b48Spatrick 7809467b48Spatrick private: 7909467b48Spatrick bool rotateLoop(Loop *L, bool SimplifiedLatch); 8009467b48Spatrick bool simplifyLoopLatch(Loop *L); 8109467b48Spatrick }; 8209467b48Spatrick } // end anonymous namespace 8309467b48Spatrick 8409467b48Spatrick /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not 8509467b48Spatrick /// previously exist in the map, and the value was inserted. 8609467b48Spatrick static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) { 8709467b48Spatrick bool Inserted = VM.insert({K, V}).second; 8809467b48Spatrick assert(Inserted); 8909467b48Spatrick (void)Inserted; 9009467b48Spatrick } 9109467b48Spatrick /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the 9209467b48Spatrick /// old header into the preheader. If there were uses of the values produced by 9309467b48Spatrick /// these instruction that were outside of the loop, we have to insert PHI nodes 9409467b48Spatrick /// to merge the two values. Do this now. 9509467b48Spatrick static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, 9609467b48Spatrick BasicBlock *OrigPreheader, 9709467b48Spatrick ValueToValueMapTy &ValueMap, 9809467b48Spatrick SmallVectorImpl<PHINode*> *InsertedPHIs) { 9909467b48Spatrick // Remove PHI node entries that are no longer live. 10009467b48Spatrick BasicBlock::iterator I, E = OrigHeader->end(); 10109467b48Spatrick for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) 10209467b48Spatrick PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); 10309467b48Spatrick 10409467b48Spatrick // Now fix up users of the instructions in OrigHeader, inserting PHI nodes 10509467b48Spatrick // as necessary. 10609467b48Spatrick SSAUpdater SSA(InsertedPHIs); 10709467b48Spatrick for (I = OrigHeader->begin(); I != E; ++I) { 10809467b48Spatrick Value *OrigHeaderVal = &*I; 10909467b48Spatrick 11009467b48Spatrick // If there are no uses of the value (e.g. because it returns void), there 11109467b48Spatrick // is nothing to rewrite. 11209467b48Spatrick if (OrigHeaderVal->use_empty()) 11309467b48Spatrick continue; 11409467b48Spatrick 11509467b48Spatrick Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal); 11609467b48Spatrick 11709467b48Spatrick // The value now exits in two versions: the initial value in the preheader 11809467b48Spatrick // and the loop "next" value in the original header. 11909467b48Spatrick SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); 12009467b48Spatrick SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); 12109467b48Spatrick SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); 12209467b48Spatrick 12309467b48Spatrick // Visit each use of the OrigHeader instruction. 12409467b48Spatrick for (Value::use_iterator UI = OrigHeaderVal->use_begin(), 12509467b48Spatrick UE = OrigHeaderVal->use_end(); 12609467b48Spatrick UI != UE;) { 12709467b48Spatrick // Grab the use before incrementing the iterator. 12809467b48Spatrick Use &U = *UI; 12909467b48Spatrick 13009467b48Spatrick // Increment the iterator before removing the use from the list. 13109467b48Spatrick ++UI; 13209467b48Spatrick 13309467b48Spatrick // SSAUpdater can't handle a non-PHI use in the same block as an 13409467b48Spatrick // earlier def. We can easily handle those cases manually. 13509467b48Spatrick Instruction *UserInst = cast<Instruction>(U.getUser()); 13609467b48Spatrick if (!isa<PHINode>(UserInst)) { 13709467b48Spatrick BasicBlock *UserBB = UserInst->getParent(); 13809467b48Spatrick 13909467b48Spatrick // The original users in the OrigHeader are already using the 14009467b48Spatrick // original definitions. 14109467b48Spatrick if (UserBB == OrigHeader) 14209467b48Spatrick continue; 14309467b48Spatrick 14409467b48Spatrick // Users in the OrigPreHeader need to use the value to which the 14509467b48Spatrick // original definitions are mapped. 14609467b48Spatrick if (UserBB == OrigPreheader) { 14709467b48Spatrick U = OrigPreHeaderVal; 14809467b48Spatrick continue; 14909467b48Spatrick } 15009467b48Spatrick } 15109467b48Spatrick 15209467b48Spatrick // Anything else can be handled by SSAUpdater. 15309467b48Spatrick SSA.RewriteUse(U); 15409467b48Spatrick } 15509467b48Spatrick 15609467b48Spatrick // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug 15709467b48Spatrick // intrinsics. 15809467b48Spatrick SmallVector<DbgValueInst *, 1> DbgValues; 15909467b48Spatrick llvm::findDbgValues(DbgValues, OrigHeaderVal); 16009467b48Spatrick for (auto &DbgValue : DbgValues) { 16109467b48Spatrick // The original users in the OrigHeader are already using the original 16209467b48Spatrick // definitions. 16309467b48Spatrick BasicBlock *UserBB = DbgValue->getParent(); 16409467b48Spatrick if (UserBB == OrigHeader) 16509467b48Spatrick continue; 16609467b48Spatrick 16709467b48Spatrick // Users in the OrigPreHeader need to use the value to which the 16809467b48Spatrick // original definitions are mapped and anything else can be handled by 16909467b48Spatrick // the SSAUpdater. To avoid adding PHINodes, check if the value is 17009467b48Spatrick // available in UserBB, if not substitute undef. 17109467b48Spatrick Value *NewVal; 17209467b48Spatrick if (UserBB == OrigPreheader) 17309467b48Spatrick NewVal = OrigPreHeaderVal; 17409467b48Spatrick else if (SSA.HasValueForBlock(UserBB)) 17509467b48Spatrick NewVal = SSA.GetValueInMiddleOfBlock(UserBB); 17609467b48Spatrick else 17709467b48Spatrick NewVal = UndefValue::get(OrigHeaderVal->getType()); 17809467b48Spatrick DbgValue->setOperand(0, 17909467b48Spatrick MetadataAsValue::get(OrigHeaderVal->getContext(), 18009467b48Spatrick ValueAsMetadata::get(NewVal))); 18109467b48Spatrick } 18209467b48Spatrick } 18309467b48Spatrick } 18409467b48Spatrick 185*097a140dSpatrick // Assuming both header and latch are exiting, look for a phi which is only 186*097a140dSpatrick // used outside the loop (via a LCSSA phi) in the exit from the header. 187*097a140dSpatrick // This means that rotating the loop can remove the phi. 188*097a140dSpatrick static bool profitableToRotateLoopExitingLatch(Loop *L) { 18909467b48Spatrick BasicBlock *Header = L->getHeader(); 190*097a140dSpatrick BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator()); 191*097a140dSpatrick assert(BI && BI->isConditional() && "need header with conditional exit"); 192*097a140dSpatrick BasicBlock *HeaderExit = BI->getSuccessor(0); 19309467b48Spatrick if (L->contains(HeaderExit)) 194*097a140dSpatrick HeaderExit = BI->getSuccessor(1); 19509467b48Spatrick 19609467b48Spatrick for (auto &Phi : Header->phis()) { 19709467b48Spatrick // Look for uses of this phi in the loop/via exits other than the header. 19809467b48Spatrick if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) { 19909467b48Spatrick return cast<Instruction>(U)->getParent() != HeaderExit; 20009467b48Spatrick })) 20109467b48Spatrick continue; 20209467b48Spatrick return true; 20309467b48Spatrick } 204*097a140dSpatrick return false; 205*097a140dSpatrick } 20609467b48Spatrick 207*097a140dSpatrick // Check that latch exit is deoptimizing (which means - very unlikely to happen) 208*097a140dSpatrick // and there is another exit from the loop which is non-deoptimizing. 209*097a140dSpatrick // If we rotate latch to that exit our loop has a better chance of being fully 210*097a140dSpatrick // canonical. 211*097a140dSpatrick // 212*097a140dSpatrick // It can give false positives in some rare cases. 213*097a140dSpatrick static bool canRotateDeoptimizingLatchExit(Loop *L) { 214*097a140dSpatrick BasicBlock *Latch = L->getLoopLatch(); 215*097a140dSpatrick assert(Latch && "need latch"); 216*097a140dSpatrick BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 217*097a140dSpatrick // Need normal exiting latch. 218*097a140dSpatrick if (!BI || !BI->isConditional()) 219*097a140dSpatrick return false; 220*097a140dSpatrick 221*097a140dSpatrick BasicBlock *Exit = BI->getSuccessor(1); 222*097a140dSpatrick if (L->contains(Exit)) 223*097a140dSpatrick Exit = BI->getSuccessor(0); 224*097a140dSpatrick 225*097a140dSpatrick // Latch exit is non-deoptimizing, no need to rotate. 226*097a140dSpatrick if (!Exit->getPostdominatingDeoptimizeCall()) 227*097a140dSpatrick return false; 228*097a140dSpatrick 229*097a140dSpatrick SmallVector<BasicBlock *, 4> Exits; 230*097a140dSpatrick L->getUniqueExitBlocks(Exits); 231*097a140dSpatrick if (!Exits.empty()) { 232*097a140dSpatrick // There is at least one non-deoptimizing exit. 233*097a140dSpatrick // 234*097a140dSpatrick // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact, 235*097a140dSpatrick // as it can conservatively return false for deoptimizing exits with 236*097a140dSpatrick // complex enough control flow down to deoptimize call. 237*097a140dSpatrick // 238*097a140dSpatrick // That means here we can report success for a case where 239*097a140dSpatrick // all exits are deoptimizing but one of them has complex enough 240*097a140dSpatrick // control flow (e.g. with loops). 241*097a140dSpatrick // 242*097a140dSpatrick // That should be a very rare case and false positives for this function 243*097a140dSpatrick // have compile-time effect only. 244*097a140dSpatrick return any_of(Exits, [](const BasicBlock *BB) { 245*097a140dSpatrick return !BB->getPostdominatingDeoptimizeCall(); 246*097a140dSpatrick }); 247*097a140dSpatrick } 24809467b48Spatrick return false; 24909467b48Spatrick } 25009467b48Spatrick 25109467b48Spatrick /// Rotate loop LP. Return true if the loop is rotated. 25209467b48Spatrick /// 25309467b48Spatrick /// \param SimplifiedLatch is true if the latch was just folded into the final 25409467b48Spatrick /// loop exit. In this case we may want to rotate even though the new latch is 25509467b48Spatrick /// now an exiting branch. This rotation would have happened had the latch not 25609467b48Spatrick /// been simplified. However, if SimplifiedLatch is false, then we avoid 25709467b48Spatrick /// rotating loops in which the latch exits to avoid excessive or endless 25809467b48Spatrick /// rotation. LoopRotate should be repeatable and converge to a canonical 25909467b48Spatrick /// form. This property is satisfied because simplifying the loop latch can only 26009467b48Spatrick /// happen once across multiple invocations of the LoopRotate pass. 261*097a140dSpatrick /// 262*097a140dSpatrick /// If -loop-rotate-multi is enabled we can do multiple rotations in one go 263*097a140dSpatrick /// so to reach a suitable (non-deoptimizing) exit. 26409467b48Spatrick bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) { 26509467b48Spatrick // If the loop has only one block then there is not much to rotate. 26609467b48Spatrick if (L->getBlocks().size() == 1) 26709467b48Spatrick return false; 26809467b48Spatrick 269*097a140dSpatrick bool Rotated = false; 270*097a140dSpatrick do { 27109467b48Spatrick BasicBlock *OrigHeader = L->getHeader(); 27209467b48Spatrick BasicBlock *OrigLatch = L->getLoopLatch(); 27309467b48Spatrick 27409467b48Spatrick BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); 27509467b48Spatrick if (!BI || BI->isUnconditional()) 276*097a140dSpatrick return Rotated; 27709467b48Spatrick 27809467b48Spatrick // If the loop header is not one of the loop exiting blocks then 27909467b48Spatrick // either this loop is already rotated or it is not 28009467b48Spatrick // suitable for loop rotation transformations. 28109467b48Spatrick if (!L->isLoopExiting(OrigHeader)) 282*097a140dSpatrick return Rotated; 28309467b48Spatrick 28409467b48Spatrick // If the loop latch already contains a branch that leaves the loop then the 28509467b48Spatrick // loop is already rotated. 28609467b48Spatrick if (!OrigLatch) 287*097a140dSpatrick return Rotated; 28809467b48Spatrick 28909467b48Spatrick // Rotate if either the loop latch does *not* exit the loop, or if the loop 29009467b48Spatrick // latch was just simplified. Or if we think it will be profitable. 29109467b48Spatrick if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false && 292*097a140dSpatrick !profitableToRotateLoopExitingLatch(L) && 293*097a140dSpatrick !canRotateDeoptimizingLatchExit(L)) 294*097a140dSpatrick return Rotated; 29509467b48Spatrick 29609467b48Spatrick // Check size of original header and reject loop if it is very big or we can't 29709467b48Spatrick // duplicate blocks inside it. 29809467b48Spatrick { 29909467b48Spatrick SmallPtrSet<const Value *, 32> EphValues; 30009467b48Spatrick CodeMetrics::collectEphemeralValues(L, AC, EphValues); 30109467b48Spatrick 30209467b48Spatrick CodeMetrics Metrics; 30309467b48Spatrick Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues); 30409467b48Spatrick if (Metrics.notDuplicatable) { 30509467b48Spatrick LLVM_DEBUG( 30609467b48Spatrick dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable" 30709467b48Spatrick << " instructions: "; 30809467b48Spatrick L->dump()); 309*097a140dSpatrick return Rotated; 31009467b48Spatrick } 31109467b48Spatrick if (Metrics.convergent) { 31209467b48Spatrick LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent " 31309467b48Spatrick "instructions: "; 31409467b48Spatrick L->dump()); 315*097a140dSpatrick return Rotated; 31609467b48Spatrick } 317*097a140dSpatrick if (Metrics.NumInsts > MaxHeaderSize) { 318*097a140dSpatrick LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains " 319*097a140dSpatrick << Metrics.NumInsts 320*097a140dSpatrick << " instructions, which is more than the threshold (" 321*097a140dSpatrick << MaxHeaderSize << " instructions): "; 322*097a140dSpatrick L->dump()); 323*097a140dSpatrick return Rotated; 324*097a140dSpatrick } 32509467b48Spatrick } 32609467b48Spatrick 32709467b48Spatrick // Now, this loop is suitable for rotation. 32809467b48Spatrick BasicBlock *OrigPreheader = L->getLoopPreheader(); 32909467b48Spatrick 33009467b48Spatrick // If the loop could not be converted to canonical form, it must have an 33109467b48Spatrick // indirectbr in it, just give up. 33209467b48Spatrick if (!OrigPreheader || !L->hasDedicatedExits()) 333*097a140dSpatrick return Rotated; 33409467b48Spatrick 33509467b48Spatrick // Anything ScalarEvolution may know about this loop or the PHI nodes 33609467b48Spatrick // in its header will soon be invalidated. We should also invalidate 33709467b48Spatrick // all outer loops because insertion and deletion of blocks that happens 33809467b48Spatrick // during the rotation may violate invariants related to backedge taken 33909467b48Spatrick // infos in them. 34009467b48Spatrick if (SE) 34109467b48Spatrick SE->forgetTopmostLoop(L); 34209467b48Spatrick 34309467b48Spatrick LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump()); 34409467b48Spatrick if (MSSAU && VerifyMemorySSA) 34509467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 34609467b48Spatrick 34709467b48Spatrick // Find new Loop header. NewHeader is a Header's one and only successor 34809467b48Spatrick // that is inside loop. Header's other successor is outside the 34909467b48Spatrick // loop. Otherwise loop is not suitable for rotation. 35009467b48Spatrick BasicBlock *Exit = BI->getSuccessor(0); 35109467b48Spatrick BasicBlock *NewHeader = BI->getSuccessor(1); 35209467b48Spatrick if (L->contains(Exit)) 35309467b48Spatrick std::swap(Exit, NewHeader); 35409467b48Spatrick assert(NewHeader && "Unable to determine new loop header"); 35509467b48Spatrick assert(L->contains(NewHeader) && !L->contains(Exit) && 35609467b48Spatrick "Unable to determine loop header and exit blocks"); 35709467b48Spatrick 35809467b48Spatrick // This code assumes that the new header has exactly one predecessor. 35909467b48Spatrick // Remove any single-entry PHI nodes in it. 36009467b48Spatrick assert(NewHeader->getSinglePredecessor() && 36109467b48Spatrick "New header doesn't have one pred!"); 36209467b48Spatrick FoldSingleEntryPHINodes(NewHeader); 36309467b48Spatrick 36409467b48Spatrick // Begin by walking OrigHeader and populating ValueMap with an entry for 36509467b48Spatrick // each Instruction. 36609467b48Spatrick BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); 36709467b48Spatrick ValueToValueMapTy ValueMap, ValueMapMSSA; 36809467b48Spatrick 36909467b48Spatrick // For PHI nodes, the value available in OldPreHeader is just the 37009467b48Spatrick // incoming value from OldPreHeader. 37109467b48Spatrick for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) 37209467b48Spatrick InsertNewValueIntoMap(ValueMap, PN, 37309467b48Spatrick PN->getIncomingValueForBlock(OrigPreheader)); 37409467b48Spatrick 37509467b48Spatrick // For the rest of the instructions, either hoist to the OrigPreheader if 37609467b48Spatrick // possible or create a clone in the OldPreHeader if not. 37709467b48Spatrick Instruction *LoopEntryBranch = OrigPreheader->getTerminator(); 37809467b48Spatrick 37909467b48Spatrick // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication. 38009467b48Spatrick using DbgIntrinsicHash = 38109467b48Spatrick std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>; 38209467b48Spatrick auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash { 38309467b48Spatrick return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()}; 38409467b48Spatrick }; 38509467b48Spatrick SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics; 38609467b48Spatrick for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend(); 38709467b48Spatrick I != E; ++I) { 38809467b48Spatrick if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I)) 38909467b48Spatrick DbgIntrinsics.insert(makeHash(DII)); 39009467b48Spatrick else 39109467b48Spatrick break; 39209467b48Spatrick } 39309467b48Spatrick 39409467b48Spatrick while (I != E) { 39509467b48Spatrick Instruction *Inst = &*I++; 39609467b48Spatrick 39709467b48Spatrick // If the instruction's operands are invariant and it doesn't read or write 39809467b48Spatrick // memory, then it is safe to hoist. Doing this doesn't change the order of 39909467b48Spatrick // execution in the preheader, but does prevent the instruction from 40009467b48Spatrick // executing in each iteration of the loop. This means it is safe to hoist 40109467b48Spatrick // something that might trap, but isn't safe to hoist something that reads 40209467b48Spatrick // memory (without proving that the loop doesn't write). 40309467b48Spatrick if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() && 40409467b48Spatrick !Inst->mayWriteToMemory() && !Inst->isTerminator() && 40509467b48Spatrick !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) { 40609467b48Spatrick Inst->moveBefore(LoopEntryBranch); 40709467b48Spatrick continue; 40809467b48Spatrick } 40909467b48Spatrick 41009467b48Spatrick // Otherwise, create a duplicate of the instruction. 41109467b48Spatrick Instruction *C = Inst->clone(); 41209467b48Spatrick 41309467b48Spatrick // Eagerly remap the operands of the instruction. 41409467b48Spatrick RemapInstruction(C, ValueMap, 41509467b48Spatrick RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 41609467b48Spatrick 41709467b48Spatrick // Avoid inserting the same intrinsic twice. 41809467b48Spatrick if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C)) 41909467b48Spatrick if (DbgIntrinsics.count(makeHash(DII))) { 42009467b48Spatrick C->deleteValue(); 42109467b48Spatrick continue; 42209467b48Spatrick } 42309467b48Spatrick 42409467b48Spatrick // With the operands remapped, see if the instruction constant folds or is 42509467b48Spatrick // otherwise simplifyable. This commonly occurs because the entry from PHI 42609467b48Spatrick // nodes allows icmps and other instructions to fold. 42709467b48Spatrick Value *V = SimplifyInstruction(C, SQ); 42809467b48Spatrick if (V && LI->replacementPreservesLCSSAForm(C, V)) { 42909467b48Spatrick // If so, then delete the temporary instruction and stick the folded value 43009467b48Spatrick // in the map. 43109467b48Spatrick InsertNewValueIntoMap(ValueMap, Inst, V); 43209467b48Spatrick if (!C->mayHaveSideEffects()) { 43309467b48Spatrick C->deleteValue(); 43409467b48Spatrick C = nullptr; 43509467b48Spatrick } 43609467b48Spatrick } else { 43709467b48Spatrick InsertNewValueIntoMap(ValueMap, Inst, C); 43809467b48Spatrick } 43909467b48Spatrick if (C) { 44009467b48Spatrick // Otherwise, stick the new instruction into the new block! 44109467b48Spatrick C->setName(Inst->getName()); 44209467b48Spatrick C->insertBefore(LoopEntryBranch); 44309467b48Spatrick 44409467b48Spatrick if (auto *II = dyn_cast<IntrinsicInst>(C)) 44509467b48Spatrick if (II->getIntrinsicID() == Intrinsic::assume) 44609467b48Spatrick AC->registerAssumption(II); 44709467b48Spatrick // MemorySSA cares whether the cloned instruction was inserted or not, and 44809467b48Spatrick // not whether it can be remapped to a simplified value. 44909467b48Spatrick if (MSSAU) 45009467b48Spatrick InsertNewValueIntoMap(ValueMapMSSA, Inst, C); 45109467b48Spatrick } 45209467b48Spatrick } 45309467b48Spatrick 45409467b48Spatrick // Along with all the other instructions, we just cloned OrigHeader's 45509467b48Spatrick // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 45609467b48Spatrick // successors by duplicating their incoming values for OrigHeader. 45709467b48Spatrick for (BasicBlock *SuccBB : successors(OrigHeader)) 45809467b48Spatrick for (BasicBlock::iterator BI = SuccBB->begin(); 45909467b48Spatrick PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 46009467b48Spatrick PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 46109467b48Spatrick 46209467b48Spatrick // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 46309467b48Spatrick // OrigPreHeader's old terminator (the original branch into the loop), and 46409467b48Spatrick // remove the corresponding incoming values from the PHI nodes in OrigHeader. 46509467b48Spatrick LoopEntryBranch->eraseFromParent(); 46609467b48Spatrick 46709467b48Spatrick // Update MemorySSA before the rewrite call below changes the 1:1 46809467b48Spatrick // instruction:cloned_instruction_or_value mapping. 46909467b48Spatrick if (MSSAU) { 47009467b48Spatrick InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader); 47109467b48Spatrick MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader, 47209467b48Spatrick ValueMapMSSA); 47309467b48Spatrick } 47409467b48Spatrick 47509467b48Spatrick SmallVector<PHINode*, 2> InsertedPHIs; 47609467b48Spatrick // If there were any uses of instructions in the duplicated block outside the 47709467b48Spatrick // loop, update them, inserting PHI nodes as required 47809467b48Spatrick RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, 47909467b48Spatrick &InsertedPHIs); 48009467b48Spatrick 48109467b48Spatrick // Attach dbg.value intrinsics to the new phis if that phi uses a value that 48209467b48Spatrick // previously had debug metadata attached. This keeps the debug info 48309467b48Spatrick // up-to-date in the loop body. 48409467b48Spatrick if (!InsertedPHIs.empty()) 48509467b48Spatrick insertDebugValuesForPHIs(OrigHeader, InsertedPHIs); 48609467b48Spatrick 48709467b48Spatrick // NewHeader is now the header of the loop. 48809467b48Spatrick L->moveToHeader(NewHeader); 48909467b48Spatrick assert(L->getHeader() == NewHeader && "Latch block is our new header"); 49009467b48Spatrick 49109467b48Spatrick // Inform DT about changes to the CFG. 49209467b48Spatrick if (DT) { 49309467b48Spatrick // The OrigPreheader branches to the NewHeader and Exit now. Then, inform 49409467b48Spatrick // the DT about the removed edge to the OrigHeader (that got removed). 49509467b48Spatrick SmallVector<DominatorTree::UpdateType, 3> Updates; 49609467b48Spatrick Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit}); 49709467b48Spatrick Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader}); 49809467b48Spatrick Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader}); 49909467b48Spatrick DT->applyUpdates(Updates); 50009467b48Spatrick 50109467b48Spatrick if (MSSAU) { 50209467b48Spatrick MSSAU->applyUpdates(Updates, *DT); 50309467b48Spatrick if (VerifyMemorySSA) 50409467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 50509467b48Spatrick } 50609467b48Spatrick } 50709467b48Spatrick 50809467b48Spatrick // At this point, we've finished our major CFG changes. As part of cloning 50909467b48Spatrick // the loop into the preheader we've simplified instructions and the 51009467b48Spatrick // duplicated conditional branch may now be branching on a constant. If it is 51109467b48Spatrick // branching on a constant and if that constant means that we enter the loop, 51209467b48Spatrick // then we fold away the cond branch to an uncond branch. This simplifies the 51309467b48Spatrick // loop in cases important for nested loops, and it also means we don't have 51409467b48Spatrick // to split as many edges. 51509467b48Spatrick BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 51609467b48Spatrick assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 51709467b48Spatrick if (!isa<ConstantInt>(PHBI->getCondition()) || 51809467b48Spatrick PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) != 51909467b48Spatrick NewHeader) { 52009467b48Spatrick // The conditional branch can't be folded, handle the general case. 52109467b48Spatrick // Split edges as necessary to preserve LoopSimplify form. 52209467b48Spatrick 52309467b48Spatrick // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 52409467b48Spatrick // thus is not a preheader anymore. 52509467b48Spatrick // Split the edge to form a real preheader. 52609467b48Spatrick BasicBlock *NewPH = SplitCriticalEdge( 52709467b48Spatrick OrigPreheader, NewHeader, 52809467b48Spatrick CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()); 52909467b48Spatrick NewPH->setName(NewHeader->getName() + ".lr.ph"); 53009467b48Spatrick 53109467b48Spatrick // Preserve canonical loop form, which means that 'Exit' should have only 53209467b48Spatrick // one predecessor. Note that Exit could be an exit block for multiple 53309467b48Spatrick // nested loops, causing both of the edges to now be critical and need to 53409467b48Spatrick // be split. 53509467b48Spatrick SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit)); 53609467b48Spatrick bool SplitLatchEdge = false; 53709467b48Spatrick for (BasicBlock *ExitPred : ExitPreds) { 53809467b48Spatrick // We only need to split loop exit edges. 53909467b48Spatrick Loop *PredLoop = LI->getLoopFor(ExitPred); 54009467b48Spatrick if (!PredLoop || PredLoop->contains(Exit) || 54109467b48Spatrick ExitPred->getTerminator()->isIndirectTerminator()) 54209467b48Spatrick continue; 54309467b48Spatrick SplitLatchEdge |= L->getLoopLatch() == ExitPred; 54409467b48Spatrick BasicBlock *ExitSplit = SplitCriticalEdge( 54509467b48Spatrick ExitPred, Exit, 54609467b48Spatrick CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()); 54709467b48Spatrick ExitSplit->moveBefore(Exit); 54809467b48Spatrick } 54909467b48Spatrick assert(SplitLatchEdge && 55009467b48Spatrick "Despite splitting all preds, failed to split latch exit?"); 55109467b48Spatrick } else { 55209467b48Spatrick // We can fold the conditional branch in the preheader, this makes things 55309467b48Spatrick // simpler. The first step is to remove the extra edge to the Exit block. 55409467b48Spatrick Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 55509467b48Spatrick BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 55609467b48Spatrick NewBI->setDebugLoc(PHBI->getDebugLoc()); 55709467b48Spatrick PHBI->eraseFromParent(); 55809467b48Spatrick 55909467b48Spatrick // With our CFG finalized, update DomTree if it is available. 56009467b48Spatrick if (DT) DT->deleteEdge(OrigPreheader, Exit); 56109467b48Spatrick 56209467b48Spatrick // Update MSSA too, if available. 56309467b48Spatrick if (MSSAU) 56409467b48Spatrick MSSAU->removeEdge(OrigPreheader, Exit); 56509467b48Spatrick } 56609467b48Spatrick 56709467b48Spatrick assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 56809467b48Spatrick assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 56909467b48Spatrick 57009467b48Spatrick if (MSSAU && VerifyMemorySSA) 57109467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 57209467b48Spatrick 57309467b48Spatrick // Now that the CFG and DomTree are in a consistent state again, try to merge 57409467b48Spatrick // the OrigHeader block into OrigLatch. This will succeed if they are 57509467b48Spatrick // connected by an unconditional branch. This is just a cleanup so the 57609467b48Spatrick // emitted code isn't too gross in this common case. 57709467b48Spatrick DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 57809467b48Spatrick MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU); 57909467b48Spatrick 58009467b48Spatrick if (MSSAU && VerifyMemorySSA) 58109467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 58209467b48Spatrick 58309467b48Spatrick LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump()); 58409467b48Spatrick 58509467b48Spatrick ++NumRotated; 586*097a140dSpatrick 587*097a140dSpatrick Rotated = true; 588*097a140dSpatrick SimplifiedLatch = false; 589*097a140dSpatrick 590*097a140dSpatrick // Check that new latch is a deoptimizing exit and then repeat rotation if possible. 591*097a140dSpatrick // Deoptimizing latch exit is not a generally typical case, so we just loop over. 592*097a140dSpatrick // TODO: if it becomes a performance bottleneck extend rotation algorithm 593*097a140dSpatrick // to handle multiple rotations in one go. 594*097a140dSpatrick } while (MultiRotate && canRotateDeoptimizingLatchExit(L)); 595*097a140dSpatrick 596*097a140dSpatrick 59709467b48Spatrick return true; 59809467b48Spatrick } 59909467b48Spatrick 60009467b48Spatrick /// Determine whether the instructions in this range may be safely and cheaply 60109467b48Spatrick /// speculated. This is not an important enough situation to develop complex 60209467b48Spatrick /// heuristics. We handle a single arithmetic instruction along with any type 60309467b48Spatrick /// conversions. 60409467b48Spatrick static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 60509467b48Spatrick BasicBlock::iterator End, Loop *L) { 60609467b48Spatrick bool seenIncrement = false; 60709467b48Spatrick bool MultiExitLoop = false; 60809467b48Spatrick 60909467b48Spatrick if (!L->getExitingBlock()) 61009467b48Spatrick MultiExitLoop = true; 61109467b48Spatrick 61209467b48Spatrick for (BasicBlock::iterator I = Begin; I != End; ++I) { 61309467b48Spatrick 61409467b48Spatrick if (!isSafeToSpeculativelyExecute(&*I)) 61509467b48Spatrick return false; 61609467b48Spatrick 61709467b48Spatrick if (isa<DbgInfoIntrinsic>(I)) 61809467b48Spatrick continue; 61909467b48Spatrick 62009467b48Spatrick switch (I->getOpcode()) { 62109467b48Spatrick default: 62209467b48Spatrick return false; 62309467b48Spatrick case Instruction::GetElementPtr: 62409467b48Spatrick // GEPs are cheap if all indices are constant. 62509467b48Spatrick if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 62609467b48Spatrick return false; 62709467b48Spatrick // fall-thru to increment case 62809467b48Spatrick LLVM_FALLTHROUGH; 62909467b48Spatrick case Instruction::Add: 63009467b48Spatrick case Instruction::Sub: 63109467b48Spatrick case Instruction::And: 63209467b48Spatrick case Instruction::Or: 63309467b48Spatrick case Instruction::Xor: 63409467b48Spatrick case Instruction::Shl: 63509467b48Spatrick case Instruction::LShr: 63609467b48Spatrick case Instruction::AShr: { 63709467b48Spatrick Value *IVOpnd = 63809467b48Spatrick !isa<Constant>(I->getOperand(0)) 63909467b48Spatrick ? I->getOperand(0) 64009467b48Spatrick : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr; 64109467b48Spatrick if (!IVOpnd) 64209467b48Spatrick return false; 64309467b48Spatrick 64409467b48Spatrick // If increment operand is used outside of the loop, this speculation 64509467b48Spatrick // could cause extra live range interference. 64609467b48Spatrick if (MultiExitLoop) { 64709467b48Spatrick for (User *UseI : IVOpnd->users()) { 64809467b48Spatrick auto *UserInst = cast<Instruction>(UseI); 64909467b48Spatrick if (!L->contains(UserInst)) 65009467b48Spatrick return false; 65109467b48Spatrick } 65209467b48Spatrick } 65309467b48Spatrick 65409467b48Spatrick if (seenIncrement) 65509467b48Spatrick return false; 65609467b48Spatrick seenIncrement = true; 65709467b48Spatrick break; 65809467b48Spatrick } 65909467b48Spatrick case Instruction::Trunc: 66009467b48Spatrick case Instruction::ZExt: 66109467b48Spatrick case Instruction::SExt: 66209467b48Spatrick // ignore type conversions 66309467b48Spatrick break; 66409467b48Spatrick } 66509467b48Spatrick } 66609467b48Spatrick return true; 66709467b48Spatrick } 66809467b48Spatrick 66909467b48Spatrick /// Fold the loop tail into the loop exit by speculating the loop tail 67009467b48Spatrick /// instructions. Typically, this is a single post-increment. In the case of a 67109467b48Spatrick /// simple 2-block loop, hoisting the increment can be much better than 67209467b48Spatrick /// duplicating the entire loop header. In the case of loops with early exits, 67309467b48Spatrick /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 67409467b48Spatrick /// canonical form so downstream passes can handle it. 67509467b48Spatrick /// 67609467b48Spatrick /// I don't believe this invalidates SCEV. 67709467b48Spatrick bool LoopRotate::simplifyLoopLatch(Loop *L) { 67809467b48Spatrick BasicBlock *Latch = L->getLoopLatch(); 67909467b48Spatrick if (!Latch || Latch->hasAddressTaken()) 68009467b48Spatrick return false; 68109467b48Spatrick 68209467b48Spatrick BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 68309467b48Spatrick if (!Jmp || !Jmp->isUnconditional()) 68409467b48Spatrick return false; 68509467b48Spatrick 68609467b48Spatrick BasicBlock *LastExit = Latch->getSinglePredecessor(); 68709467b48Spatrick if (!LastExit || !L->isLoopExiting(LastExit)) 68809467b48Spatrick return false; 68909467b48Spatrick 69009467b48Spatrick BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 69109467b48Spatrick if (!BI) 69209467b48Spatrick return false; 69309467b48Spatrick 69409467b48Spatrick if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L)) 69509467b48Spatrick return false; 69609467b48Spatrick 69709467b48Spatrick LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 69809467b48Spatrick << LastExit->getName() << "\n"); 69909467b48Spatrick 70009467b48Spatrick DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 70109467b48Spatrick MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr, 70209467b48Spatrick /*PredecessorWithTwoSuccessors=*/true); 70309467b48Spatrick 70409467b48Spatrick if (MSSAU && VerifyMemorySSA) 70509467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 70609467b48Spatrick 70709467b48Spatrick return true; 70809467b48Spatrick } 70909467b48Spatrick 71009467b48Spatrick /// Rotate \c L, and return true if any modification was made. 71109467b48Spatrick bool LoopRotate::processLoop(Loop *L) { 71209467b48Spatrick // Save the loop metadata. 71309467b48Spatrick MDNode *LoopMD = L->getLoopID(); 71409467b48Spatrick 71509467b48Spatrick bool SimplifiedLatch = false; 71609467b48Spatrick 71709467b48Spatrick // Simplify the loop latch before attempting to rotate the header 71809467b48Spatrick // upward. Rotation may not be needed if the loop tail can be folded into the 71909467b48Spatrick // loop exit. 72009467b48Spatrick if (!RotationOnly) 72109467b48Spatrick SimplifiedLatch = simplifyLoopLatch(L); 72209467b48Spatrick 72309467b48Spatrick bool MadeChange = rotateLoop(L, SimplifiedLatch); 72409467b48Spatrick assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) && 72509467b48Spatrick "Loop latch should be exiting after loop-rotate."); 72609467b48Spatrick 72709467b48Spatrick // Restore the loop metadata. 72809467b48Spatrick // NB! We presume LoopRotation DOESN'T ADD its own metadata. 72909467b48Spatrick if ((MadeChange || SimplifiedLatch) && LoopMD) 73009467b48Spatrick L->setLoopID(LoopMD); 73109467b48Spatrick 73209467b48Spatrick return MadeChange || SimplifiedLatch; 73309467b48Spatrick } 73409467b48Spatrick 73509467b48Spatrick 73609467b48Spatrick /// The utility to convert a loop into a loop with bottom test. 73709467b48Spatrick bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI, 73809467b48Spatrick AssumptionCache *AC, DominatorTree *DT, 73909467b48Spatrick ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 74009467b48Spatrick const SimplifyQuery &SQ, bool RotationOnly = true, 74109467b48Spatrick unsigned Threshold = unsigned(-1), 74209467b48Spatrick bool IsUtilMode = true) { 74309467b48Spatrick if (MSSAU && VerifyMemorySSA) 74409467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 74509467b48Spatrick LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly, 74609467b48Spatrick IsUtilMode); 74709467b48Spatrick if (MSSAU && VerifyMemorySSA) 74809467b48Spatrick MSSAU->getMemorySSA()->verifyMemorySSA(); 74909467b48Spatrick 75009467b48Spatrick return LR.processLoop(L); 75109467b48Spatrick } 752