14ba319b5SDimitry Andric //===----------------- LoopRotationUtils.cpp -----------------------------===//
24ba319b5SDimitry Andric //
34ba319b5SDimitry Andric // The LLVM Compiler Infrastructure
44ba319b5SDimitry Andric //
54ba319b5SDimitry Andric // This file is distributed under the University of Illinois Open Source
64ba319b5SDimitry Andric // License. See LICENSE.TXT for details.
74ba319b5SDimitry Andric //
84ba319b5SDimitry Andric //===----------------------------------------------------------------------===//
94ba319b5SDimitry Andric //
104ba319b5SDimitry Andric // This file provides utilities to convert a loop into a loop with bottom test.
114ba319b5SDimitry Andric //
124ba319b5SDimitry Andric //===----------------------------------------------------------------------===//
134ba319b5SDimitry Andric
144ba319b5SDimitry Andric #include "llvm/Transforms/Utils/LoopRotationUtils.h"
154ba319b5SDimitry Andric #include "llvm/ADT/Statistic.h"
164ba319b5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
174ba319b5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
184ba319b5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
194ba319b5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
204ba319b5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
214ba319b5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
224ba319b5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
23*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
24*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
254ba319b5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
264ba319b5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
274ba319b5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
284ba319b5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
294ba319b5SDimitry Andric #include "llvm/IR/CFG.h"
304ba319b5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
31*b5893f02SDimitry Andric #include "llvm/IR/DomTreeUpdater.h"
324ba319b5SDimitry Andric #include "llvm/IR/Dominators.h"
334ba319b5SDimitry Andric #include "llvm/IR/Function.h"
344ba319b5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
354ba319b5SDimitry Andric #include "llvm/IR/Module.h"
364ba319b5SDimitry Andric #include "llvm/Support/CommandLine.h"
374ba319b5SDimitry Andric #include "llvm/Support/Debug.h"
384ba319b5SDimitry Andric #include "llvm/Support/raw_ostream.h"
394ba319b5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
414ba319b5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
424ba319b5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
434ba319b5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
444ba319b5SDimitry Andric using namespace llvm;
454ba319b5SDimitry Andric
464ba319b5SDimitry Andric #define DEBUG_TYPE "loop-rotate"
474ba319b5SDimitry Andric
484ba319b5SDimitry Andric STATISTIC(NumRotated, "Number of loops rotated");
494ba319b5SDimitry Andric
504ba319b5SDimitry Andric namespace {
514ba319b5SDimitry Andric /// A simple loop rotation transformation.
524ba319b5SDimitry Andric class LoopRotate {
534ba319b5SDimitry Andric const unsigned MaxHeaderSize;
544ba319b5SDimitry Andric LoopInfo *LI;
554ba319b5SDimitry Andric const TargetTransformInfo *TTI;
564ba319b5SDimitry Andric AssumptionCache *AC;
574ba319b5SDimitry Andric DominatorTree *DT;
584ba319b5SDimitry Andric ScalarEvolution *SE;
59*b5893f02SDimitry Andric MemorySSAUpdater *MSSAU;
604ba319b5SDimitry Andric const SimplifyQuery &SQ;
614ba319b5SDimitry Andric bool RotationOnly;
624ba319b5SDimitry Andric bool IsUtilMode;
634ba319b5SDimitry Andric
644ba319b5SDimitry Andric public:
LoopRotate(unsigned MaxHeaderSize,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly,bool IsUtilMode)654ba319b5SDimitry Andric LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
664ba319b5SDimitry Andric const TargetTransformInfo *TTI, AssumptionCache *AC,
67*b5893f02SDimitry Andric DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
68*b5893f02SDimitry Andric const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode)
694ba319b5SDimitry Andric : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
70*b5893f02SDimitry Andric MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
71*b5893f02SDimitry Andric IsUtilMode(IsUtilMode) {}
724ba319b5SDimitry Andric bool processLoop(Loop *L);
734ba319b5SDimitry Andric
744ba319b5SDimitry Andric private:
754ba319b5SDimitry Andric bool rotateLoop(Loop *L, bool SimplifiedLatch);
764ba319b5SDimitry Andric bool simplifyLoopLatch(Loop *L);
774ba319b5SDimitry Andric };
784ba319b5SDimitry Andric } // end anonymous namespace
794ba319b5SDimitry Andric
804ba319b5SDimitry Andric /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
814ba319b5SDimitry Andric /// old header into the preheader. If there were uses of the values produced by
824ba319b5SDimitry Andric /// these instruction that were outside of the loop, we have to insert PHI nodes
834ba319b5SDimitry Andric /// to merge the two values. Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap,SmallVectorImpl<PHINode * > * InsertedPHIs)844ba319b5SDimitry Andric static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
854ba319b5SDimitry Andric BasicBlock *OrigPreheader,
864ba319b5SDimitry Andric ValueToValueMapTy &ValueMap,
874ba319b5SDimitry Andric SmallVectorImpl<PHINode*> *InsertedPHIs) {
884ba319b5SDimitry Andric // Remove PHI node entries that are no longer live.
894ba319b5SDimitry Andric BasicBlock::iterator I, E = OrigHeader->end();
904ba319b5SDimitry Andric for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
914ba319b5SDimitry Andric PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
924ba319b5SDimitry Andric
934ba319b5SDimitry Andric // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
944ba319b5SDimitry Andric // as necessary.
954ba319b5SDimitry Andric SSAUpdater SSA(InsertedPHIs);
964ba319b5SDimitry Andric for (I = OrigHeader->begin(); I != E; ++I) {
974ba319b5SDimitry Andric Value *OrigHeaderVal = &*I;
984ba319b5SDimitry Andric
994ba319b5SDimitry Andric // If there are no uses of the value (e.g. because it returns void), there
1004ba319b5SDimitry Andric // is nothing to rewrite.
1014ba319b5SDimitry Andric if (OrigHeaderVal->use_empty())
1024ba319b5SDimitry Andric continue;
1034ba319b5SDimitry Andric
1044ba319b5SDimitry Andric Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
1054ba319b5SDimitry Andric
1064ba319b5SDimitry Andric // The value now exits in two versions: the initial value in the preheader
1074ba319b5SDimitry Andric // and the loop "next" value in the original header.
1084ba319b5SDimitry Andric SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
1094ba319b5SDimitry Andric SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
1104ba319b5SDimitry Andric SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
1114ba319b5SDimitry Andric
1124ba319b5SDimitry Andric // Visit each use of the OrigHeader instruction.
1134ba319b5SDimitry Andric for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
1144ba319b5SDimitry Andric UE = OrigHeaderVal->use_end();
1154ba319b5SDimitry Andric UI != UE;) {
1164ba319b5SDimitry Andric // Grab the use before incrementing the iterator.
1174ba319b5SDimitry Andric Use &U = *UI;
1184ba319b5SDimitry Andric
1194ba319b5SDimitry Andric // Increment the iterator before removing the use from the list.
1204ba319b5SDimitry Andric ++UI;
1214ba319b5SDimitry Andric
1224ba319b5SDimitry Andric // SSAUpdater can't handle a non-PHI use in the same block as an
1234ba319b5SDimitry Andric // earlier def. We can easily handle those cases manually.
1244ba319b5SDimitry Andric Instruction *UserInst = cast<Instruction>(U.getUser());
1254ba319b5SDimitry Andric if (!isa<PHINode>(UserInst)) {
1264ba319b5SDimitry Andric BasicBlock *UserBB = UserInst->getParent();
1274ba319b5SDimitry Andric
1284ba319b5SDimitry Andric // The original users in the OrigHeader are already using the
1294ba319b5SDimitry Andric // original definitions.
1304ba319b5SDimitry Andric if (UserBB == OrigHeader)
1314ba319b5SDimitry Andric continue;
1324ba319b5SDimitry Andric
1334ba319b5SDimitry Andric // Users in the OrigPreHeader need to use the value to which the
1344ba319b5SDimitry Andric // original definitions are mapped.
1354ba319b5SDimitry Andric if (UserBB == OrigPreheader) {
1364ba319b5SDimitry Andric U = OrigPreHeaderVal;
1374ba319b5SDimitry Andric continue;
1384ba319b5SDimitry Andric }
1394ba319b5SDimitry Andric }
1404ba319b5SDimitry Andric
1414ba319b5SDimitry Andric // Anything else can be handled by SSAUpdater.
1424ba319b5SDimitry Andric SSA.RewriteUse(U);
1434ba319b5SDimitry Andric }
1444ba319b5SDimitry Andric
1454ba319b5SDimitry Andric // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
1464ba319b5SDimitry Andric // intrinsics.
1474ba319b5SDimitry Andric SmallVector<DbgValueInst *, 1> DbgValues;
1484ba319b5SDimitry Andric llvm::findDbgValues(DbgValues, OrigHeaderVal);
1494ba319b5SDimitry Andric for (auto &DbgValue : DbgValues) {
1504ba319b5SDimitry Andric // The original users in the OrigHeader are already using the original
1514ba319b5SDimitry Andric // definitions.
1524ba319b5SDimitry Andric BasicBlock *UserBB = DbgValue->getParent();
1534ba319b5SDimitry Andric if (UserBB == OrigHeader)
1544ba319b5SDimitry Andric continue;
1554ba319b5SDimitry Andric
1564ba319b5SDimitry Andric // Users in the OrigPreHeader need to use the value to which the
1574ba319b5SDimitry Andric // original definitions are mapped and anything else can be handled by
1584ba319b5SDimitry Andric // the SSAUpdater. To avoid adding PHINodes, check if the value is
1594ba319b5SDimitry Andric // available in UserBB, if not substitute undef.
1604ba319b5SDimitry Andric Value *NewVal;
1614ba319b5SDimitry Andric if (UserBB == OrigPreheader)
1624ba319b5SDimitry Andric NewVal = OrigPreHeaderVal;
1634ba319b5SDimitry Andric else if (SSA.HasValueForBlock(UserBB))
1644ba319b5SDimitry Andric NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
1654ba319b5SDimitry Andric else
1664ba319b5SDimitry Andric NewVal = UndefValue::get(OrigHeaderVal->getType());
1674ba319b5SDimitry Andric DbgValue->setOperand(0,
1684ba319b5SDimitry Andric MetadataAsValue::get(OrigHeaderVal->getContext(),
1694ba319b5SDimitry Andric ValueAsMetadata::get(NewVal)));
1704ba319b5SDimitry Andric }
1714ba319b5SDimitry Andric }
1724ba319b5SDimitry Andric }
1734ba319b5SDimitry Andric
1744ba319b5SDimitry Andric // Look for a phi which is only used outside the loop (via a LCSSA phi)
1754ba319b5SDimitry Andric // in the exit from the header. This means that rotating the loop can
1764ba319b5SDimitry Andric // remove the phi.
shouldRotateLoopExitingLatch(Loop * L)1774ba319b5SDimitry Andric static bool shouldRotateLoopExitingLatch(Loop *L) {
1784ba319b5SDimitry Andric BasicBlock *Header = L->getHeader();
1794ba319b5SDimitry Andric BasicBlock *HeaderExit = Header->getTerminator()->getSuccessor(0);
1804ba319b5SDimitry Andric if (L->contains(HeaderExit))
1814ba319b5SDimitry Andric HeaderExit = Header->getTerminator()->getSuccessor(1);
1824ba319b5SDimitry Andric
1834ba319b5SDimitry Andric for (auto &Phi : Header->phis()) {
1844ba319b5SDimitry Andric // Look for uses of this phi in the loop/via exits other than the header.
1854ba319b5SDimitry Andric if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
1864ba319b5SDimitry Andric return cast<Instruction>(U)->getParent() != HeaderExit;
1874ba319b5SDimitry Andric }))
1884ba319b5SDimitry Andric continue;
1894ba319b5SDimitry Andric return true;
1904ba319b5SDimitry Andric }
1914ba319b5SDimitry Andric
1924ba319b5SDimitry Andric return false;
1934ba319b5SDimitry Andric }
1944ba319b5SDimitry Andric
1954ba319b5SDimitry Andric /// Rotate loop LP. Return true if the loop is rotated.
1964ba319b5SDimitry Andric ///
1974ba319b5SDimitry Andric /// \param SimplifiedLatch is true if the latch was just folded into the final
1984ba319b5SDimitry Andric /// loop exit. In this case we may want to rotate even though the new latch is
1994ba319b5SDimitry Andric /// now an exiting branch. This rotation would have happened had the latch not
2004ba319b5SDimitry Andric /// been simplified. However, if SimplifiedLatch is false, then we avoid
2014ba319b5SDimitry Andric /// rotating loops in which the latch exits to avoid excessive or endless
2024ba319b5SDimitry Andric /// rotation. LoopRotate should be repeatable and converge to a canonical
2034ba319b5SDimitry Andric /// form. This property is satisfied because simplifying the loop latch can only
2044ba319b5SDimitry Andric /// happen once across multiple invocations of the LoopRotate pass.
rotateLoop(Loop * L,bool SimplifiedLatch)2054ba319b5SDimitry Andric bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
2064ba319b5SDimitry Andric // If the loop has only one block then there is not much to rotate.
2074ba319b5SDimitry Andric if (L->getBlocks().size() == 1)
2084ba319b5SDimitry Andric return false;
2094ba319b5SDimitry Andric
2104ba319b5SDimitry Andric BasicBlock *OrigHeader = L->getHeader();
2114ba319b5SDimitry Andric BasicBlock *OrigLatch = L->getLoopLatch();
2124ba319b5SDimitry Andric
2134ba319b5SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
2144ba319b5SDimitry Andric if (!BI || BI->isUnconditional())
2154ba319b5SDimitry Andric return false;
2164ba319b5SDimitry Andric
2174ba319b5SDimitry Andric // If the loop header is not one of the loop exiting blocks then
2184ba319b5SDimitry Andric // either this loop is already rotated or it is not
2194ba319b5SDimitry Andric // suitable for loop rotation transformations.
2204ba319b5SDimitry Andric if (!L->isLoopExiting(OrigHeader))
2214ba319b5SDimitry Andric return false;
2224ba319b5SDimitry Andric
2234ba319b5SDimitry Andric // If the loop latch already contains a branch that leaves the loop then the
2244ba319b5SDimitry Andric // loop is already rotated.
2254ba319b5SDimitry Andric if (!OrigLatch)
2264ba319b5SDimitry Andric return false;
2274ba319b5SDimitry Andric
2284ba319b5SDimitry Andric // Rotate if either the loop latch does *not* exit the loop, or if the loop
2294ba319b5SDimitry Andric // latch was just simplified. Or if we think it will be profitable.
2304ba319b5SDimitry Andric if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
2314ba319b5SDimitry Andric !shouldRotateLoopExitingLatch(L))
2324ba319b5SDimitry Andric return false;
2334ba319b5SDimitry Andric
2344ba319b5SDimitry Andric // Check size of original header and reject loop if it is very big or we can't
2354ba319b5SDimitry Andric // duplicate blocks inside it.
2364ba319b5SDimitry Andric {
2374ba319b5SDimitry Andric SmallPtrSet<const Value *, 32> EphValues;
2384ba319b5SDimitry Andric CodeMetrics::collectEphemeralValues(L, AC, EphValues);
2394ba319b5SDimitry Andric
2404ba319b5SDimitry Andric CodeMetrics Metrics;
2414ba319b5SDimitry Andric Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
2424ba319b5SDimitry Andric if (Metrics.notDuplicatable) {
2434ba319b5SDimitry Andric LLVM_DEBUG(
2444ba319b5SDimitry Andric dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
2454ba319b5SDimitry Andric << " instructions: ";
2464ba319b5SDimitry Andric L->dump());
2474ba319b5SDimitry Andric return false;
2484ba319b5SDimitry Andric }
2494ba319b5SDimitry Andric if (Metrics.convergent) {
2504ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
2514ba319b5SDimitry Andric "instructions: ";
2524ba319b5SDimitry Andric L->dump());
2534ba319b5SDimitry Andric return false;
2544ba319b5SDimitry Andric }
2554ba319b5SDimitry Andric if (Metrics.NumInsts > MaxHeaderSize)
2564ba319b5SDimitry Andric return false;
2574ba319b5SDimitry Andric }
2584ba319b5SDimitry Andric
2594ba319b5SDimitry Andric // Now, this loop is suitable for rotation.
2604ba319b5SDimitry Andric BasicBlock *OrigPreheader = L->getLoopPreheader();
2614ba319b5SDimitry Andric
2624ba319b5SDimitry Andric // If the loop could not be converted to canonical form, it must have an
2634ba319b5SDimitry Andric // indirectbr in it, just give up.
2644ba319b5SDimitry Andric if (!OrigPreheader || !L->hasDedicatedExits())
2654ba319b5SDimitry Andric return false;
2664ba319b5SDimitry Andric
2674ba319b5SDimitry Andric // Anything ScalarEvolution may know about this loop or the PHI nodes
2684ba319b5SDimitry Andric // in its header will soon be invalidated. We should also invalidate
2694ba319b5SDimitry Andric // all outer loops because insertion and deletion of blocks that happens
2704ba319b5SDimitry Andric // during the rotation may violate invariants related to backedge taken
2714ba319b5SDimitry Andric // infos in them.
2724ba319b5SDimitry Andric if (SE)
2734ba319b5SDimitry Andric SE->forgetTopmostLoop(L);
2744ba319b5SDimitry Andric
2754ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
276*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
277*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
2784ba319b5SDimitry Andric
2794ba319b5SDimitry Andric // Find new Loop header. NewHeader is a Header's one and only successor
2804ba319b5SDimitry Andric // that is inside loop. Header's other successor is outside the
2814ba319b5SDimitry Andric // loop. Otherwise loop is not suitable for rotation.
2824ba319b5SDimitry Andric BasicBlock *Exit = BI->getSuccessor(0);
2834ba319b5SDimitry Andric BasicBlock *NewHeader = BI->getSuccessor(1);
2844ba319b5SDimitry Andric if (L->contains(Exit))
2854ba319b5SDimitry Andric std::swap(Exit, NewHeader);
2864ba319b5SDimitry Andric assert(NewHeader && "Unable to determine new loop header");
2874ba319b5SDimitry Andric assert(L->contains(NewHeader) && !L->contains(Exit) &&
2884ba319b5SDimitry Andric "Unable to determine loop header and exit blocks");
2894ba319b5SDimitry Andric
2904ba319b5SDimitry Andric // This code assumes that the new header has exactly one predecessor.
2914ba319b5SDimitry Andric // Remove any single-entry PHI nodes in it.
2924ba319b5SDimitry Andric assert(NewHeader->getSinglePredecessor() &&
2934ba319b5SDimitry Andric "New header doesn't have one pred!");
2944ba319b5SDimitry Andric FoldSingleEntryPHINodes(NewHeader);
2954ba319b5SDimitry Andric
2964ba319b5SDimitry Andric // Begin by walking OrigHeader and populating ValueMap with an entry for
2974ba319b5SDimitry Andric // each Instruction.
2984ba319b5SDimitry Andric BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
2994ba319b5SDimitry Andric ValueToValueMapTy ValueMap;
3004ba319b5SDimitry Andric
3014ba319b5SDimitry Andric // For PHI nodes, the value available in OldPreHeader is just the
3024ba319b5SDimitry Andric // incoming value from OldPreHeader.
3034ba319b5SDimitry Andric for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
3044ba319b5SDimitry Andric ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
3054ba319b5SDimitry Andric
3064ba319b5SDimitry Andric // For the rest of the instructions, either hoist to the OrigPreheader if
3074ba319b5SDimitry Andric // possible or create a clone in the OldPreHeader if not.
308*b5893f02SDimitry Andric Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
3094ba319b5SDimitry Andric
3104ba319b5SDimitry Andric // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
3114ba319b5SDimitry Andric using DbgIntrinsicHash =
3124ba319b5SDimitry Andric std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
313*b5893f02SDimitry Andric auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
3144ba319b5SDimitry Andric return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
3154ba319b5SDimitry Andric };
3164ba319b5SDimitry Andric SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
3174ba319b5SDimitry Andric for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
3184ba319b5SDimitry Andric I != E; ++I) {
319*b5893f02SDimitry Andric if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
3204ba319b5SDimitry Andric DbgIntrinsics.insert(makeHash(DII));
3214ba319b5SDimitry Andric else
3224ba319b5SDimitry Andric break;
3234ba319b5SDimitry Andric }
3244ba319b5SDimitry Andric
3254ba319b5SDimitry Andric while (I != E) {
3264ba319b5SDimitry Andric Instruction *Inst = &*I++;
3274ba319b5SDimitry Andric
3284ba319b5SDimitry Andric // If the instruction's operands are invariant and it doesn't read or write
3294ba319b5SDimitry Andric // memory, then it is safe to hoist. Doing this doesn't change the order of
3304ba319b5SDimitry Andric // execution in the preheader, but does prevent the instruction from
3314ba319b5SDimitry Andric // executing in each iteration of the loop. This means it is safe to hoist
3324ba319b5SDimitry Andric // something that might trap, but isn't safe to hoist something that reads
3334ba319b5SDimitry Andric // memory (without proving that the loop doesn't write).
3344ba319b5SDimitry Andric if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
335*b5893f02SDimitry Andric !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
3364ba319b5SDimitry Andric !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
3374ba319b5SDimitry Andric Inst->moveBefore(LoopEntryBranch);
3384ba319b5SDimitry Andric continue;
3394ba319b5SDimitry Andric }
3404ba319b5SDimitry Andric
3414ba319b5SDimitry Andric // Otherwise, create a duplicate of the instruction.
3424ba319b5SDimitry Andric Instruction *C = Inst->clone();
3434ba319b5SDimitry Andric
3444ba319b5SDimitry Andric // Eagerly remap the operands of the instruction.
3454ba319b5SDimitry Andric RemapInstruction(C, ValueMap,
3464ba319b5SDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
3474ba319b5SDimitry Andric
3484ba319b5SDimitry Andric // Avoid inserting the same intrinsic twice.
349*b5893f02SDimitry Andric if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
3504ba319b5SDimitry Andric if (DbgIntrinsics.count(makeHash(DII))) {
3514ba319b5SDimitry Andric C->deleteValue();
3524ba319b5SDimitry Andric continue;
3534ba319b5SDimitry Andric }
3544ba319b5SDimitry Andric
3554ba319b5SDimitry Andric // With the operands remapped, see if the instruction constant folds or is
3564ba319b5SDimitry Andric // otherwise simplifyable. This commonly occurs because the entry from PHI
3574ba319b5SDimitry Andric // nodes allows icmps and other instructions to fold.
3584ba319b5SDimitry Andric Value *V = SimplifyInstruction(C, SQ);
3594ba319b5SDimitry Andric if (V && LI->replacementPreservesLCSSAForm(C, V)) {
3604ba319b5SDimitry Andric // If so, then delete the temporary instruction and stick the folded value
3614ba319b5SDimitry Andric // in the map.
3624ba319b5SDimitry Andric ValueMap[Inst] = V;
3634ba319b5SDimitry Andric if (!C->mayHaveSideEffects()) {
3644ba319b5SDimitry Andric C->deleteValue();
3654ba319b5SDimitry Andric C = nullptr;
3664ba319b5SDimitry Andric }
3674ba319b5SDimitry Andric } else {
3684ba319b5SDimitry Andric ValueMap[Inst] = C;
3694ba319b5SDimitry Andric }
3704ba319b5SDimitry Andric if (C) {
3714ba319b5SDimitry Andric // Otherwise, stick the new instruction into the new block!
3724ba319b5SDimitry Andric C->setName(Inst->getName());
3734ba319b5SDimitry Andric C->insertBefore(LoopEntryBranch);
3744ba319b5SDimitry Andric
3754ba319b5SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(C))
3764ba319b5SDimitry Andric if (II->getIntrinsicID() == Intrinsic::assume)
3774ba319b5SDimitry Andric AC->registerAssumption(II);
3784ba319b5SDimitry Andric }
3794ba319b5SDimitry Andric }
3804ba319b5SDimitry Andric
3814ba319b5SDimitry Andric // Along with all the other instructions, we just cloned OrigHeader's
3824ba319b5SDimitry Andric // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
3834ba319b5SDimitry Andric // successors by duplicating their incoming values for OrigHeader.
384*b5893f02SDimitry Andric for (BasicBlock *SuccBB : successors(OrigHeader))
3854ba319b5SDimitry Andric for (BasicBlock::iterator BI = SuccBB->begin();
3864ba319b5SDimitry Andric PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
3874ba319b5SDimitry Andric PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
3884ba319b5SDimitry Andric
3894ba319b5SDimitry Andric // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
3904ba319b5SDimitry Andric // OrigPreHeader's old terminator (the original branch into the loop), and
3914ba319b5SDimitry Andric // remove the corresponding incoming values from the PHI nodes in OrigHeader.
3924ba319b5SDimitry Andric LoopEntryBranch->eraseFromParent();
3934ba319b5SDimitry Andric
394*b5893f02SDimitry Andric // Update MemorySSA before the rewrite call below changes the 1:1
395*b5893f02SDimitry Andric // instruction:cloned_instruction_or_value mapping in ValueMap.
396*b5893f02SDimitry Andric if (MSSAU) {
397*b5893f02SDimitry Andric ValueMap[OrigHeader] = OrigPreheader;
398*b5893f02SDimitry Andric MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader, ValueMap);
399*b5893f02SDimitry Andric }
4004ba319b5SDimitry Andric
4014ba319b5SDimitry Andric SmallVector<PHINode*, 2> InsertedPHIs;
4024ba319b5SDimitry Andric // If there were any uses of instructions in the duplicated block outside the
4034ba319b5SDimitry Andric // loop, update them, inserting PHI nodes as required
4044ba319b5SDimitry Andric RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
4054ba319b5SDimitry Andric &InsertedPHIs);
4064ba319b5SDimitry Andric
4074ba319b5SDimitry Andric // Attach dbg.value intrinsics to the new phis if that phi uses a value that
4084ba319b5SDimitry Andric // previously had debug metadata attached. This keeps the debug info
4094ba319b5SDimitry Andric // up-to-date in the loop body.
4104ba319b5SDimitry Andric if (!InsertedPHIs.empty())
4114ba319b5SDimitry Andric insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
4124ba319b5SDimitry Andric
4134ba319b5SDimitry Andric // NewHeader is now the header of the loop.
4144ba319b5SDimitry Andric L->moveToHeader(NewHeader);
4154ba319b5SDimitry Andric assert(L->getHeader() == NewHeader && "Latch block is our new header");
4164ba319b5SDimitry Andric
4174ba319b5SDimitry Andric // Inform DT about changes to the CFG.
4184ba319b5SDimitry Andric if (DT) {
4194ba319b5SDimitry Andric // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
4204ba319b5SDimitry Andric // the DT about the removed edge to the OrigHeader (that got removed).
4214ba319b5SDimitry Andric SmallVector<DominatorTree::UpdateType, 3> Updates;
4224ba319b5SDimitry Andric Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
4234ba319b5SDimitry Andric Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
4244ba319b5SDimitry Andric Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
4254ba319b5SDimitry Andric DT->applyUpdates(Updates);
426*b5893f02SDimitry Andric
427*b5893f02SDimitry Andric if (MSSAU) {
428*b5893f02SDimitry Andric MSSAU->applyUpdates(Updates, *DT);
429*b5893f02SDimitry Andric if (VerifyMemorySSA)
430*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
431*b5893f02SDimitry Andric }
4324ba319b5SDimitry Andric }
4334ba319b5SDimitry Andric
4344ba319b5SDimitry Andric // At this point, we've finished our major CFG changes. As part of cloning
4354ba319b5SDimitry Andric // the loop into the preheader we've simplified instructions and the
4364ba319b5SDimitry Andric // duplicated conditional branch may now be branching on a constant. If it is
4374ba319b5SDimitry Andric // branching on a constant and if that constant means that we enter the loop,
4384ba319b5SDimitry Andric // then we fold away the cond branch to an uncond branch. This simplifies the
4394ba319b5SDimitry Andric // loop in cases important for nested loops, and it also means we don't have
4404ba319b5SDimitry Andric // to split as many edges.
4414ba319b5SDimitry Andric BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
4424ba319b5SDimitry Andric assert(PHBI->isConditional() && "Should be clone of BI condbr!");
4434ba319b5SDimitry Andric if (!isa<ConstantInt>(PHBI->getCondition()) ||
4444ba319b5SDimitry Andric PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
4454ba319b5SDimitry Andric NewHeader) {
4464ba319b5SDimitry Andric // The conditional branch can't be folded, handle the general case.
4474ba319b5SDimitry Andric // Split edges as necessary to preserve LoopSimplify form.
4484ba319b5SDimitry Andric
4494ba319b5SDimitry Andric // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
4504ba319b5SDimitry Andric // thus is not a preheader anymore.
4514ba319b5SDimitry Andric // Split the edge to form a real preheader.
4524ba319b5SDimitry Andric BasicBlock *NewPH = SplitCriticalEdge(
4534ba319b5SDimitry Andric OrigPreheader, NewHeader,
454*b5893f02SDimitry Andric CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
4554ba319b5SDimitry Andric NewPH->setName(NewHeader->getName() + ".lr.ph");
4564ba319b5SDimitry Andric
4574ba319b5SDimitry Andric // Preserve canonical loop form, which means that 'Exit' should have only
4584ba319b5SDimitry Andric // one predecessor. Note that Exit could be an exit block for multiple
4594ba319b5SDimitry Andric // nested loops, causing both of the edges to now be critical and need to
4604ba319b5SDimitry Andric // be split.
4614ba319b5SDimitry Andric SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
4624ba319b5SDimitry Andric bool SplitLatchEdge = false;
4634ba319b5SDimitry Andric for (BasicBlock *ExitPred : ExitPreds) {
4644ba319b5SDimitry Andric // We only need to split loop exit edges.
4654ba319b5SDimitry Andric Loop *PredLoop = LI->getLoopFor(ExitPred);
4664ba319b5SDimitry Andric if (!PredLoop || PredLoop->contains(Exit))
4674ba319b5SDimitry Andric continue;
4684ba319b5SDimitry Andric if (isa<IndirectBrInst>(ExitPred->getTerminator()))
4694ba319b5SDimitry Andric continue;
4704ba319b5SDimitry Andric SplitLatchEdge |= L->getLoopLatch() == ExitPred;
4714ba319b5SDimitry Andric BasicBlock *ExitSplit = SplitCriticalEdge(
4724ba319b5SDimitry Andric ExitPred, Exit,
473*b5893f02SDimitry Andric CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
4744ba319b5SDimitry Andric ExitSplit->moveBefore(Exit);
4754ba319b5SDimitry Andric }
4764ba319b5SDimitry Andric assert(SplitLatchEdge &&
4774ba319b5SDimitry Andric "Despite splitting all preds, failed to split latch exit?");
4784ba319b5SDimitry Andric } else {
4794ba319b5SDimitry Andric // We can fold the conditional branch in the preheader, this makes things
4804ba319b5SDimitry Andric // simpler. The first step is to remove the extra edge to the Exit block.
4814ba319b5SDimitry Andric Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
4824ba319b5SDimitry Andric BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
4834ba319b5SDimitry Andric NewBI->setDebugLoc(PHBI->getDebugLoc());
4844ba319b5SDimitry Andric PHBI->eraseFromParent();
4854ba319b5SDimitry Andric
4864ba319b5SDimitry Andric // With our CFG finalized, update DomTree if it is available.
4874ba319b5SDimitry Andric if (DT) DT->deleteEdge(OrigPreheader, Exit);
488*b5893f02SDimitry Andric
489*b5893f02SDimitry Andric // Update MSSA too, if available.
490*b5893f02SDimitry Andric if (MSSAU)
491*b5893f02SDimitry Andric MSSAU->removeEdge(OrigPreheader, Exit);
4924ba319b5SDimitry Andric }
4934ba319b5SDimitry Andric
4944ba319b5SDimitry Andric assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
4954ba319b5SDimitry Andric assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
4964ba319b5SDimitry Andric
497*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
498*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
499*b5893f02SDimitry Andric
5004ba319b5SDimitry Andric // Now that the CFG and DomTree are in a consistent state again, try to merge
5014ba319b5SDimitry Andric // the OrigHeader block into OrigLatch. This will succeed if they are
5024ba319b5SDimitry Andric // connected by an unconditional branch. This is just a cleanup so the
5034ba319b5SDimitry Andric // emitted code isn't too gross in this common case.
504*b5893f02SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
505*b5893f02SDimitry Andric MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
506*b5893f02SDimitry Andric
507*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
508*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
5094ba319b5SDimitry Andric
5104ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
5114ba319b5SDimitry Andric
5124ba319b5SDimitry Andric ++NumRotated;
5134ba319b5SDimitry Andric return true;
5144ba319b5SDimitry Andric }
5154ba319b5SDimitry Andric
5164ba319b5SDimitry Andric /// Determine whether the instructions in this range may be safely and cheaply
5174ba319b5SDimitry Andric /// speculated. This is not an important enough situation to develop complex
5184ba319b5SDimitry Andric /// heuristics. We handle a single arithmetic instruction along with any type
5194ba319b5SDimitry Andric /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)5204ba319b5SDimitry Andric static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
5214ba319b5SDimitry Andric BasicBlock::iterator End, Loop *L) {
5224ba319b5SDimitry Andric bool seenIncrement = false;
5234ba319b5SDimitry Andric bool MultiExitLoop = false;
5244ba319b5SDimitry Andric
5254ba319b5SDimitry Andric if (!L->getExitingBlock())
5264ba319b5SDimitry Andric MultiExitLoop = true;
5274ba319b5SDimitry Andric
5284ba319b5SDimitry Andric for (BasicBlock::iterator I = Begin; I != End; ++I) {
5294ba319b5SDimitry Andric
5304ba319b5SDimitry Andric if (!isSafeToSpeculativelyExecute(&*I))
5314ba319b5SDimitry Andric return false;
5324ba319b5SDimitry Andric
5334ba319b5SDimitry Andric if (isa<DbgInfoIntrinsic>(I))
5344ba319b5SDimitry Andric continue;
5354ba319b5SDimitry Andric
5364ba319b5SDimitry Andric switch (I->getOpcode()) {
5374ba319b5SDimitry Andric default:
5384ba319b5SDimitry Andric return false;
5394ba319b5SDimitry Andric case Instruction::GetElementPtr:
5404ba319b5SDimitry Andric // GEPs are cheap if all indices are constant.
5414ba319b5SDimitry Andric if (!cast<GEPOperator>(I)->hasAllConstantIndices())
5424ba319b5SDimitry Andric return false;
5434ba319b5SDimitry Andric // fall-thru to increment case
5444ba319b5SDimitry Andric LLVM_FALLTHROUGH;
5454ba319b5SDimitry Andric case Instruction::Add:
5464ba319b5SDimitry Andric case Instruction::Sub:
5474ba319b5SDimitry Andric case Instruction::And:
5484ba319b5SDimitry Andric case Instruction::Or:
5494ba319b5SDimitry Andric case Instruction::Xor:
5504ba319b5SDimitry Andric case Instruction::Shl:
5514ba319b5SDimitry Andric case Instruction::LShr:
5524ba319b5SDimitry Andric case Instruction::AShr: {
5534ba319b5SDimitry Andric Value *IVOpnd =
5544ba319b5SDimitry Andric !isa<Constant>(I->getOperand(0))
5554ba319b5SDimitry Andric ? I->getOperand(0)
5564ba319b5SDimitry Andric : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
5574ba319b5SDimitry Andric if (!IVOpnd)
5584ba319b5SDimitry Andric return false;
5594ba319b5SDimitry Andric
5604ba319b5SDimitry Andric // If increment operand is used outside of the loop, this speculation
5614ba319b5SDimitry Andric // could cause extra live range interference.
5624ba319b5SDimitry Andric if (MultiExitLoop) {
5634ba319b5SDimitry Andric for (User *UseI : IVOpnd->users()) {
5644ba319b5SDimitry Andric auto *UserInst = cast<Instruction>(UseI);
5654ba319b5SDimitry Andric if (!L->contains(UserInst))
5664ba319b5SDimitry Andric return false;
5674ba319b5SDimitry Andric }
5684ba319b5SDimitry Andric }
5694ba319b5SDimitry Andric
5704ba319b5SDimitry Andric if (seenIncrement)
5714ba319b5SDimitry Andric return false;
5724ba319b5SDimitry Andric seenIncrement = true;
5734ba319b5SDimitry Andric break;
5744ba319b5SDimitry Andric }
5754ba319b5SDimitry Andric case Instruction::Trunc:
5764ba319b5SDimitry Andric case Instruction::ZExt:
5774ba319b5SDimitry Andric case Instruction::SExt:
5784ba319b5SDimitry Andric // ignore type conversions
5794ba319b5SDimitry Andric break;
5804ba319b5SDimitry Andric }
5814ba319b5SDimitry Andric }
5824ba319b5SDimitry Andric return true;
5834ba319b5SDimitry Andric }
5844ba319b5SDimitry Andric
5854ba319b5SDimitry Andric /// Fold the loop tail into the loop exit by speculating the loop tail
5864ba319b5SDimitry Andric /// instructions. Typically, this is a single post-increment. In the case of a
5874ba319b5SDimitry Andric /// simple 2-block loop, hoisting the increment can be much better than
5884ba319b5SDimitry Andric /// duplicating the entire loop header. In the case of loops with early exits,
5894ba319b5SDimitry Andric /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
5904ba319b5SDimitry Andric /// canonical form so downstream passes can handle it.
5914ba319b5SDimitry Andric ///
5924ba319b5SDimitry Andric /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)5934ba319b5SDimitry Andric bool LoopRotate::simplifyLoopLatch(Loop *L) {
5944ba319b5SDimitry Andric BasicBlock *Latch = L->getLoopLatch();
5954ba319b5SDimitry Andric if (!Latch || Latch->hasAddressTaken())
5964ba319b5SDimitry Andric return false;
5974ba319b5SDimitry Andric
5984ba319b5SDimitry Andric BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
5994ba319b5SDimitry Andric if (!Jmp || !Jmp->isUnconditional())
6004ba319b5SDimitry Andric return false;
6014ba319b5SDimitry Andric
6024ba319b5SDimitry Andric BasicBlock *LastExit = Latch->getSinglePredecessor();
6034ba319b5SDimitry Andric if (!LastExit || !L->isLoopExiting(LastExit))
6044ba319b5SDimitry Andric return false;
6054ba319b5SDimitry Andric
6064ba319b5SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
6074ba319b5SDimitry Andric if (!BI)
6084ba319b5SDimitry Andric return false;
6094ba319b5SDimitry Andric
6104ba319b5SDimitry Andric if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
6114ba319b5SDimitry Andric return false;
6124ba319b5SDimitry Andric
6134ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
6144ba319b5SDimitry Andric << LastExit->getName() << "\n");
6154ba319b5SDimitry Andric
6164ba319b5SDimitry Andric // Hoist the instructions from Latch into LastExit.
617*b5893f02SDimitry Andric Instruction *FirstLatchInst = &*(Latch->begin());
6184ba319b5SDimitry Andric LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
6194ba319b5SDimitry Andric Latch->begin(), Jmp->getIterator());
6204ba319b5SDimitry Andric
621*b5893f02SDimitry Andric // Update MemorySSA
622*b5893f02SDimitry Andric if (MSSAU)
623*b5893f02SDimitry Andric MSSAU->moveAllAfterMergeBlocks(Latch, LastExit, FirstLatchInst);
624*b5893f02SDimitry Andric
6254ba319b5SDimitry Andric unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
6264ba319b5SDimitry Andric BasicBlock *Header = Jmp->getSuccessor(0);
6274ba319b5SDimitry Andric assert(Header == L->getHeader() && "expected a backward branch");
6284ba319b5SDimitry Andric
6294ba319b5SDimitry Andric // Remove Latch from the CFG so that LastExit becomes the new Latch.
6304ba319b5SDimitry Andric BI->setSuccessor(FallThruPath, Header);
6314ba319b5SDimitry Andric Latch->replaceSuccessorsPhiUsesWith(LastExit);
6324ba319b5SDimitry Andric Jmp->eraseFromParent();
6334ba319b5SDimitry Andric
6344ba319b5SDimitry Andric // Nuke the Latch block.
6354ba319b5SDimitry Andric assert(Latch->empty() && "unable to evacuate Latch");
6364ba319b5SDimitry Andric LI->removeBlock(Latch);
6374ba319b5SDimitry Andric if (DT)
6384ba319b5SDimitry Andric DT->eraseNode(Latch);
6394ba319b5SDimitry Andric Latch->eraseFromParent();
640*b5893f02SDimitry Andric
641*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
642*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
643*b5893f02SDimitry Andric
6444ba319b5SDimitry Andric return true;
6454ba319b5SDimitry Andric }
6464ba319b5SDimitry Andric
6474ba319b5SDimitry Andric /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)6484ba319b5SDimitry Andric bool LoopRotate::processLoop(Loop *L) {
6494ba319b5SDimitry Andric // Save the loop metadata.
6504ba319b5SDimitry Andric MDNode *LoopMD = L->getLoopID();
6514ba319b5SDimitry Andric
6524ba319b5SDimitry Andric bool SimplifiedLatch = false;
6534ba319b5SDimitry Andric
6544ba319b5SDimitry Andric // Simplify the loop latch before attempting to rotate the header
6554ba319b5SDimitry Andric // upward. Rotation may not be needed if the loop tail can be folded into the
6564ba319b5SDimitry Andric // loop exit.
6574ba319b5SDimitry Andric if (!RotationOnly)
6584ba319b5SDimitry Andric SimplifiedLatch = simplifyLoopLatch(L);
6594ba319b5SDimitry Andric
6604ba319b5SDimitry Andric bool MadeChange = rotateLoop(L, SimplifiedLatch);
6614ba319b5SDimitry Andric assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
6624ba319b5SDimitry Andric "Loop latch should be exiting after loop-rotate.");
6634ba319b5SDimitry Andric
6644ba319b5SDimitry Andric // Restore the loop metadata.
6654ba319b5SDimitry Andric // NB! We presume LoopRotation DOESN'T ADD its own metadata.
6664ba319b5SDimitry Andric if ((MadeChange || SimplifiedLatch) && LoopMD)
6674ba319b5SDimitry Andric L->setLoopID(LoopMD);
6684ba319b5SDimitry Andric
6694ba319b5SDimitry Andric return MadeChange || SimplifiedLatch;
6704ba319b5SDimitry Andric }
6714ba319b5SDimitry Andric
6724ba319b5SDimitry Andric
6734ba319b5SDimitry Andric /// The utility to convert a loop into a loop with bottom test.
LoopRotation(Loop * L,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly=true,unsigned Threshold=unsigned (-1),bool IsUtilMode=true)6744ba319b5SDimitry Andric bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
6754ba319b5SDimitry Andric AssumptionCache *AC, DominatorTree *DT,
676*b5893f02SDimitry Andric ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
677*b5893f02SDimitry Andric const SimplifyQuery &SQ, bool RotationOnly = true,
6784ba319b5SDimitry Andric unsigned Threshold = unsigned(-1),
6794ba319b5SDimitry Andric bool IsUtilMode = true) {
680*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
681*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
682*b5893f02SDimitry Andric LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
683*b5893f02SDimitry Andric IsUtilMode);
684*b5893f02SDimitry Andric if (MSSAU && VerifyMemorySSA)
685*b5893f02SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
6864ba319b5SDimitry Andric
6874ba319b5SDimitry Andric return LR.processLoop(L);
6884ba319b5SDimitry Andric }
689