176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
276aa662cSKarthik Bhat //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
676aa662cSKarthik Bhat //
776aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
876aa662cSKarthik Bhat //
976aa662cSKarthik Bhat // This file defines common loop utility functions.
1076aa662cSKarthik Bhat //
1176aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
1276aa662cSKarthik Bhat 
132f2bd8caSAdam Nemet #include "llvm/Transforms/Utils/LoopUtils.h"
147a87e8f9SFlorian Hahn #include "llvm/ADT/DenseSet.h"
157a87e8f9SFlorian Hahn #include "llvm/ADT/Optional.h"
167a87e8f9SFlorian Hahn #include "llvm/ADT/PriorityWorklist.h"
174a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h"
187a87e8f9SFlorian Hahn #include "llvm/ADT/SetVector.h"
197a87e8f9SFlorian Hahn #include "llvm/ADT/SmallPtrSet.h"
207a87e8f9SFlorian Hahn #include "llvm/ADT/SmallVector.h"
2131088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
2231088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
235f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.h"
2431088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
25e00158edSFlorian Hahn #include "llvm/Analysis/InstSimplifyFolder.h"
26616657b3SFlorian Hahn #include "llvm/Analysis/LoopAccessAnalysis.h"
272f2bd8caSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
28c3ccf5d7SIgor Laevsky #include "llvm/Analysis/LoopPass.h"
296da79ce1SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
3097468e92SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
3145d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
322f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3345d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
34744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h"
3531088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3676aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
37744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h"
38af7e1588SEvgeniy Brevnov #include "llvm/IR/MDBuilder.h"
3945d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
4076aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
4176aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
4205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
4331088a9dSChandler Carruth #include "llvm/Pass.h"
4476aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
454a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
4693175a5cSSjoerd Meijer #include "llvm/Transforms/Utils/Local.h"
47bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
4876aa662cSKarthik Bhat 
4976aa662cSKarthik Bhat using namespace llvm;
5076aa662cSKarthik Bhat using namespace llvm::PatternMatch;
5176aa662cSKarthik Bhat 
5276aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
5376aa662cSKarthik Bhat 
5472448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
554f64f1baSTim Corringham static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
5672448525SMichael Kruse 
formDedicatedExitBlocks(Loop * L,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)574a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
5897468e92SAlina Sbirlea                                    MemorySSAUpdater *MSSAU,
594a000883SChandler Carruth                                    bool PreserveLCSSA) {
604a000883SChandler Carruth   bool Changed = false;
614a000883SChandler Carruth 
624a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
634a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
644a000883SChandler Carruth 
654a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
664a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
674a000883SChandler Carruth            "Must start with an empty predecessors list!");
684a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
694a000883SChandler Carruth 
704a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
714a000883SChandler Carruth     // keep track of the in-loop predecessors.
724a000883SChandler Carruth     bool IsDedicatedExit = true;
734a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
744a000883SChandler Carruth       if (L->contains(PredBB)) {
754a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
764a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
774a000883SChandler Carruth           return false;
784a000883SChandler Carruth 
794a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
804a000883SChandler Carruth       } else {
814a000883SChandler Carruth         IsDedicatedExit = false;
824a000883SChandler Carruth       }
834a000883SChandler Carruth 
844a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
854a000883SChandler Carruth 
864a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
874a000883SChandler Carruth     if (IsDedicatedExit)
884a000883SChandler Carruth       return false;
894a000883SChandler Carruth 
904a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
9197468e92SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
924a000883SChandler Carruth 
934a000883SChandler Carruth     if (!NewExitBB)
94d34e60caSNicola Zaghen       LLVM_DEBUG(
95d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
964a000883SChandler Carruth                  << *L << "\n");
974a000883SChandler Carruth     else
98d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
994a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
1004a000883SChandler Carruth     return true;
1014a000883SChandler Carruth   };
1024a000883SChandler Carruth 
1034a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
1044a000883SChandler Carruth   // them, but only visit each one once.
1054a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
1064a000883SChandler Carruth   for (auto *BB : L->blocks())
1074a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
1084a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1094a000883SChandler Carruth       if (L->contains(SuccBB))
1104a000883SChandler Carruth         continue;
1114a000883SChandler Carruth 
1124a000883SChandler Carruth       // Visit each exit block exactly once.
1134a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1144a000883SChandler Carruth         continue;
1154a000883SChandler Carruth 
1164a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1174a000883SChandler Carruth     }
1184a000883SChandler Carruth 
1194a000883SChandler Carruth   return Changed;
1204a000883SChandler Carruth }
1214a000883SChandler Carruth 
1225f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
findDefsUsedOutsideOfLoop(Loop * L)123c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
124c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
125c5b7b555SAshutosh Nema 
126c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
127c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
128c5b7b555SAshutosh Nema     // be adapted into a pointer.
129c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
130c5b7b555SAshutosh Nema       auto Users = Inst.users();
1310a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
132c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
133c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
134c5b7b555SAshutosh Nema           }))
135c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
136c5b7b555SAshutosh Nema     }
137c5b7b555SAshutosh Nema 
138c5b7b555SAshutosh Nema   return UsedOutside;
139c5b7b555SAshutosh Nema }
14031088a9dSChandler Carruth 
getLoopAnalysisUsage(AnalysisUsage & AU)14131088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
14231088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
14331088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
14431088a9dSChandler Carruth   // pass manager, they must also preserve these.
14531088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
14631088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
14731088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
14831088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
14931088a9dSChandler Carruth 
15031088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
15131088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
15231088a9dSChandler Carruth   extern char &LoopSimplifyID;
15331088a9dSChandler Carruth   extern char &LCSSAID;
15431088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
15531088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
15631088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
15731088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
158c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
159c3ccf5d7SIgor Laevsky   // which preserve lcssa form
160c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
161c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
16231088a9dSChandler Carruth 
16331088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
16431088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
16531088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
16631088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
16731088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
16831088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
16931088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
17031088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
17131088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
17231088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
17331088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
17431088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
17531088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
17631088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
1776da79ce1SAlina Sbirlea   // FIXME: When all loop passes preserve MemorySSA, it can be required and
1786da79ce1SAlina Sbirlea   // preserved here instead of the individual handling in each pass.
17931088a9dSChandler Carruth }
18031088a9dSChandler Carruth 
18131088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
18231088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
18331088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
18431088a9dSChandler Carruth /// with:
18531088a9dSChandler Carruth ///
18631088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
18731088a9dSChandler Carruth ///
18831088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
initializeLoopPassPass(PassRegistry & Registry)18931088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
19031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
19131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
19231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
193e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
19431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
19531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
19631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
19731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
19831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1996da79ce1SAlina Sbirlea   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
20031088a9dSChandler Carruth }
201963341c8SAdam Nemet 
2023c3a7652SSerguei Katkov /// Create MDNode for input string.
createStringMetadata(Loop * TheLoop,StringRef Name,unsigned V)2033c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2043c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2053c3a7652SSerguei Katkov   Metadata *MDs[] = {
2063c3a7652SSerguei Katkov       MDString::get(Context, Name),
2073c3a7652SSerguei Katkov       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2083c3a7652SSerguei Katkov   return MDNode::get(Context, MDs);
2093c3a7652SSerguei Katkov }
2103c3a7652SSerguei Katkov 
2113c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact.
2127f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is
2137f8c8095SSerguei Katkov /// different.
addStringMetadataToLoop(Loop * TheLoop,const char * StringMD,unsigned V)2147f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2153c3a7652SSerguei Katkov                                    unsigned V) {
2163c3a7652SSerguei Katkov   SmallVector<Metadata *, 4> MDs(1);
2173c3a7652SSerguei Katkov   // If the loop already has metadata, retain it.
2183c3a7652SSerguei Katkov   MDNode *LoopID = TheLoop->getLoopID();
2193c3a7652SSerguei Katkov   if (LoopID) {
2203c3a7652SSerguei Katkov     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2213c3a7652SSerguei Katkov       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2227f8c8095SSerguei Katkov       // If it is of form key = value, try to parse it.
2237f8c8095SSerguei Katkov       if (Node->getNumOperands() == 2) {
2247f8c8095SSerguei Katkov         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
2257f8c8095SSerguei Katkov         if (S && S->getString().equals(StringMD)) {
2267f8c8095SSerguei Katkov           ConstantInt *IntMD =
2277f8c8095SSerguei Katkov               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2287f8c8095SSerguei Katkov           if (IntMD && IntMD->getSExtValue() == V)
2297f8c8095SSerguei Katkov             // It is already in place. Do nothing.
2307f8c8095SSerguei Katkov             return;
2317f8c8095SSerguei Katkov           // We need to update the value, so just skip it here and it will
2327f8c8095SSerguei Katkov           // be added after copying other existed nodes.
2337f8c8095SSerguei Katkov           continue;
2347f8c8095SSerguei Katkov         }
2357f8c8095SSerguei Katkov       }
2363c3a7652SSerguei Katkov       MDs.push_back(Node);
2373c3a7652SSerguei Katkov     }
2383c3a7652SSerguei Katkov   }
2393c3a7652SSerguei Katkov   // Add new metadata.
2407f8c8095SSerguei Katkov   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2413c3a7652SSerguei Katkov   // Replace current metadata node with new one.
2423c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2433c3a7652SSerguei Katkov   MDNode *NewLoopID = MDNode::get(Context, MDs);
2443c3a7652SSerguei Katkov   // Set operand 0 to refer to the loop id itself.
2453c3a7652SSerguei Katkov   NewLoopID->replaceOperandWith(0, NewLoopID);
2463c3a7652SSerguei Katkov   TheLoop->setLoopID(NewLoopID);
2473c3a7652SSerguei Katkov }
2483c3a7652SSerguei Katkov 
24971bd59f0SDavid Sherwood Optional<ElementCount>
getOptionalElementCountLoopAttribute(const Loop * TheLoop)250ddb3b26aSBardia Mahjour llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
25171bd59f0SDavid Sherwood   Optional<int> Width =
25271bd59f0SDavid Sherwood       getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
25371bd59f0SDavid Sherwood 
254e0e687a6SKazu Hirata   if (Width) {
25571bd59f0SDavid Sherwood     Optional<int> IsScalable = getOptionalIntLoopAttribute(
25671bd59f0SDavid Sherwood         TheLoop, "llvm.loop.vectorize.scalable.enable");
257129b531cSKazu Hirata     return ElementCount::get(*Width, IsScalable.value_or(false));
25871bd59f0SDavid Sherwood   }
25971bd59f0SDavid Sherwood 
26071bd59f0SDavid Sherwood   return None;
26171bd59f0SDavid Sherwood }
26271bd59f0SDavid Sherwood 
makeFollowupLoopID(MDNode * OrigLoopID,ArrayRef<StringRef> FollowupOptions,const char * InheritOptionsExceptPrefix,bool AlwaysNew)26372448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
26472448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
26572448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
26672448525SMichael Kruse   if (!OrigLoopID) {
26772448525SMichael Kruse     if (AlwaysNew)
26872448525SMichael Kruse       return nullptr;
26972448525SMichael Kruse     return None;
27072448525SMichael Kruse   }
27172448525SMichael Kruse 
27272448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
27372448525SMichael Kruse 
27472448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
27572448525SMichael Kruse   bool InheritSomeAttrs =
27672448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
27772448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
27872448525SMichael Kruse   MDs.push_back(nullptr);
27972448525SMichael Kruse 
28072448525SMichael Kruse   bool Changed = false;
28172448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
282dc300bebSKazu Hirata     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
28372448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
28472448525SMichael Kruse 
28572448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
28672448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
28772448525SMichael Kruse         if (!InheritSomeAttrs)
28872448525SMichael Kruse           return false;
28972448525SMichael Kruse 
29072448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
29172448525SMichael Kruse         if (Op->getNumOperands() == 0)
29272448525SMichael Kruse           return true;
29372448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
29472448525SMichael Kruse         if (!isa<MDString>(NameMD))
29572448525SMichael Kruse           return true;
29672448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
29772448525SMichael Kruse 
29872448525SMichael Kruse         // Do not inherit excluded attributes.
29972448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
30072448525SMichael Kruse       };
30172448525SMichael Kruse 
30272448525SMichael Kruse       if (InheritThisAttribute(Op))
30372448525SMichael Kruse         MDs.push_back(Op);
30472448525SMichael Kruse       else
30572448525SMichael Kruse         Changed = true;
30672448525SMichael Kruse     }
30772448525SMichael Kruse   } else {
30872448525SMichael Kruse     // Modified if we dropped at least one attribute.
30972448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
31072448525SMichael Kruse   }
31172448525SMichael Kruse 
31272448525SMichael Kruse   bool HasAnyFollowup = false;
31372448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
314978ba615SMichael Kruse     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
31572448525SMichael Kruse     if (!FollowupNode)
31672448525SMichael Kruse       continue;
31772448525SMichael Kruse 
31872448525SMichael Kruse     HasAnyFollowup = true;
319dc300bebSKazu Hirata     for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
32072448525SMichael Kruse       MDs.push_back(Option.get());
32172448525SMichael Kruse       Changed = true;
32272448525SMichael Kruse     }
32372448525SMichael Kruse   }
32472448525SMichael Kruse 
32572448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
32672448525SMichael Kruse   // transformation pass to add suitable attributes.
32772448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
32872448525SMichael Kruse     return None;
32972448525SMichael Kruse 
33072448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
33172448525SMichael Kruse   if (!AlwaysNew && !Changed)
33272448525SMichael Kruse     return OrigLoopID;
33372448525SMichael Kruse 
33472448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
33572448525SMichael Kruse   if (MDs.size() == 1)
33672448525SMichael Kruse     return nullptr;
33772448525SMichael Kruse 
33872448525SMichael Kruse   // Build the new loop ID.
33972448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
34072448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
34172448525SMichael Kruse   return FollowupLoopID;
34272448525SMichael Kruse }
34372448525SMichael Kruse 
hasDisableAllTransformsHint(const Loop * L)34472448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
34572448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
34672448525SMichael Kruse }
34772448525SMichael Kruse 
hasDisableLICMTransformsHint(const Loop * L)3484f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
3494f64f1baSTim Corringham   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
3504f64f1baSTim Corringham }
3514f64f1baSTim Corringham 
hasUnrollTransformation(const Loop * L)352ddb3b26aSBardia Mahjour TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
35372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
35472448525SMichael Kruse     return TM_SuppressedByUser;
35572448525SMichael Kruse 
35672448525SMichael Kruse   Optional<int> Count =
35772448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
358a7938c74SKazu Hirata   if (Count)
359611ffcf4SKazu Hirata     return Count.value() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
36072448525SMichael Kruse 
36172448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
36272448525SMichael Kruse     return TM_ForcedByUser;
36372448525SMichael Kruse 
36472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
36572448525SMichael Kruse     return TM_ForcedByUser;
36672448525SMichael Kruse 
36772448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
36872448525SMichael Kruse     return TM_Disable;
36972448525SMichael Kruse 
37072448525SMichael Kruse   return TM_Unspecified;
37172448525SMichael Kruse }
37272448525SMichael Kruse 
hasUnrollAndJamTransformation(const Loop * L)373ddb3b26aSBardia Mahjour TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
37472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
37572448525SMichael Kruse     return TM_SuppressedByUser;
37672448525SMichael Kruse 
37772448525SMichael Kruse   Optional<int> Count =
37872448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
379a7938c74SKazu Hirata   if (Count)
380611ffcf4SKazu Hirata     return Count.value() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
38172448525SMichael Kruse 
38272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
38372448525SMichael Kruse     return TM_ForcedByUser;
38472448525SMichael Kruse 
38572448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
38672448525SMichael Kruse     return TM_Disable;
38772448525SMichael Kruse 
38872448525SMichael Kruse   return TM_Unspecified;
38972448525SMichael Kruse }
39072448525SMichael Kruse 
hasVectorizeTransformation(const Loop * L)391ddb3b26aSBardia Mahjour TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
39272448525SMichael Kruse   Optional<bool> Enable =
39372448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
39472448525SMichael Kruse 
39572448525SMichael Kruse   if (Enable == false)
39672448525SMichael Kruse     return TM_SuppressedByUser;
39772448525SMichael Kruse 
39871bd59f0SDavid Sherwood   Optional<ElementCount> VectorizeWidth =
39971bd59f0SDavid Sherwood       getOptionalElementCountLoopAttribute(L);
40072448525SMichael Kruse   Optional<int> InterleaveCount =
40172448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
40272448525SMichael Kruse 
40372448525SMichael Kruse   // 'Forcing' vector width and interleave count to one effectively disables
40472448525SMichael Kruse   // this tranformation.
40571bd59f0SDavid Sherwood   if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
40671bd59f0SDavid Sherwood       InterleaveCount == 1)
40772448525SMichael Kruse     return TM_SuppressedByUser;
40872448525SMichael Kruse 
40972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
41072448525SMichael Kruse     return TM_Disable;
41172448525SMichael Kruse 
41270560a0aSMichael Kruse   if (Enable == true)
41370560a0aSMichael Kruse     return TM_ForcedByUser;
41470560a0aSMichael Kruse 
41571bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
41672448525SMichael Kruse     return TM_Disable;
41772448525SMichael Kruse 
41871bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
41972448525SMichael Kruse     return TM_Enable;
42072448525SMichael Kruse 
42172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
42272448525SMichael Kruse     return TM_Disable;
42372448525SMichael Kruse 
42472448525SMichael Kruse   return TM_Unspecified;
42572448525SMichael Kruse }
42672448525SMichael Kruse 
hasDistributeTransformation(const Loop * L)427ddb3b26aSBardia Mahjour TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
42872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
42972448525SMichael Kruse     return TM_ForcedByUser;
43072448525SMichael Kruse 
43172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
43272448525SMichael Kruse     return TM_Disable;
43372448525SMichael Kruse 
43472448525SMichael Kruse   return TM_Unspecified;
43572448525SMichael Kruse }
43672448525SMichael Kruse 
hasLICMVersioningTransformation(const Loop * L)437ddb3b26aSBardia Mahjour TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
43872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
43972448525SMichael Kruse     return TM_SuppressedByUser;
44072448525SMichael Kruse 
44172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
44272448525SMichael Kruse     return TM_Disable;
44372448525SMichael Kruse 
44472448525SMichael Kruse   return TM_Unspecified;
445963341c8SAdam Nemet }
446122f984aSEvgeniy Stepanov 
4477ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
4487ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
4497ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
collectChildrenInLoop(DomTreeNode * N,const Loop * CurLoop)4507ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
4517ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
4527ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
4537ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
4547ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
4557ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
4567ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
4577ed5856aSAlina Sbirlea   };
4587ed5856aSAlina Sbirlea 
4597ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
4607ed5856aSAlina Sbirlea 
46176c5cb05SNicolai Hähnle   for (size_t I = 0; I < Worklist.size(); I++) {
46276c5cb05SNicolai Hähnle     for (DomTreeNode *Child : Worklist[I]->children())
4637ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
46476c5cb05SNicolai Hähnle   }
4657ed5856aSAlina Sbirlea 
4667ed5856aSAlina Sbirlea   return Worklist;
4677ed5856aSAlina Sbirlea }
4687ed5856aSAlina Sbirlea 
deleteDeadLoop(Loop * L,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,MemorySSA * MSSA)469efb130fcSAlina Sbirlea void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
470efb130fcSAlina Sbirlea                           LoopInfo *LI, MemorySSA *MSSA) {
471899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
472df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
473df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
474df3e71e0SMarcello Maggioni 
475efb130fcSAlina Sbirlea   std::unique_ptr<MemorySSAUpdater> MSSAU;
476efb130fcSAlina Sbirlea   if (MSSA)
477efb130fcSAlina Sbirlea     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
478efb130fcSAlina Sbirlea 
479df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
480df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
481df3e71e0SMarcello Maggioni   //
482df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
483df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
484df3e71e0SMarcello Maggioni 
485df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
486df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
487df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
488df3e71e0SMarcello Maggioni   if (SE)
489df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
490df3e71e0SMarcello Maggioni 
49165d59b42SNikita Popov   Instruction *OldTerm = Preheader->getTerminator();
49265d59b42SNikita Popov   assert(!OldTerm->mayHaveSideEffects() &&
49365d59b42SNikita Popov          "Preheader must end with a side-effect-free terminator");
49465d59b42SNikita Popov   assert(OldTerm->getNumSuccessors() == 1 &&
49565d59b42SNikita Popov          "Preheader must have a single successor");
496df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
497df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
498df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
499df3e71e0SMarcello Maggioni   // preheader -> header.
500df3e71e0SMarcello Maggioni   //
501df3e71e0SMarcello Maggioni   //
502df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
503df3e71e0SMarcello Maggioni   //        |                    |   |                   |
504df3e71e0SMarcello Maggioni   //        V                    |   V                   |
505df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
506df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
507df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
508df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
509df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
510df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
511df3e71e0SMarcello Maggioni   //
512df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
513df3e71e0SMarcello Maggioni   // update without using the batch update API.
514df3e71e0SMarcello Maggioni   //
515df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
516df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
517df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
518df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
519df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
520df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
52165d59b42SNikita Popov   IRBuilder<> Builder(OldTerm);
522babc224cSAtmn Patel 
523babc224cSAtmn Patel   auto *ExitBlock = L->getUniqueExitBlock();
524f88a7975SAtmn Patel   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
525babc224cSAtmn Patel   if (ExitBlock) {
526babc224cSAtmn Patel     assert(ExitBlock && "Should have a unique exit block!");
527babc224cSAtmn Patel     assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
528babc224cSAtmn Patel 
529df3e71e0SMarcello Maggioni     Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
530df3e71e0SMarcello Maggioni     // Remove the old branch. The conditional branch becomes a new terminator.
53165d59b42SNikita Popov     OldTerm->eraseFromParent();
532df3e71e0SMarcello Maggioni 
533df3e71e0SMarcello Maggioni     // Rewrite phis in the exit block to get their inputs from the Preheader
534df3e71e0SMarcello Maggioni     // instead of the exiting block.
535c7fc81e6SBenjamin Kramer     for (PHINode &P : ExitBlock->phis()) {
536df3e71e0SMarcello Maggioni       // Set the zero'th element of Phi to be from the preheader and remove all
537df3e71e0SMarcello Maggioni       // other incoming values. Given the loop has dedicated exits, all other
538df3e71e0SMarcello Maggioni       // incoming values must be from the exiting blocks.
539df3e71e0SMarcello Maggioni       int PredIndex = 0;
540c7fc81e6SBenjamin Kramer       P.setIncomingBlock(PredIndex, Preheader);
541df3e71e0SMarcello Maggioni       // Removes all incoming values from all other exiting blocks (including
542df3e71e0SMarcello Maggioni       // duplicate values from an exiting block).
543df3e71e0SMarcello Maggioni       // Nuke all entries except the zero'th entry which is the preheader entry.
544df3e71e0SMarcello Maggioni       // NOTE! We need to remove Incoming Values in the reverse order as done
545df3e71e0SMarcello Maggioni       // below, to keep the indices valid for deletion (removeIncomingValues
546babc224cSAtmn Patel       // updates getNumIncomingValues and shifts all values down into the
547babc224cSAtmn Patel       // operand being deleted).
548c7fc81e6SBenjamin Kramer       for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
549c7fc81e6SBenjamin Kramer         P.removeIncomingValue(e - i, false);
550df3e71e0SMarcello Maggioni 
551c7fc81e6SBenjamin Kramer       assert((P.getNumIncomingValues() == 1 &&
552c7fc81e6SBenjamin Kramer               P.getIncomingBlock(PredIndex) == Preheader) &&
553df3e71e0SMarcello Maggioni              "Should have exactly one value and that's from the preheader!");
554df3e71e0SMarcello Maggioni     }
555df3e71e0SMarcello Maggioni 
556efb130fcSAlina Sbirlea     if (DT) {
557efb130fcSAlina Sbirlea       DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
558efb130fcSAlina Sbirlea       if (MSSA) {
559babc224cSAtmn Patel         MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
560babc224cSAtmn Patel                             *DT);
561efb130fcSAlina Sbirlea         if (VerifyMemorySSA)
562efb130fcSAlina Sbirlea           MSSA->verifyMemorySSA();
563efb130fcSAlina Sbirlea       }
564efb130fcSAlina Sbirlea     }
565efb130fcSAlina Sbirlea 
566df3e71e0SMarcello Maggioni     // Disconnect the loop body by branching directly to its exit.
567df3e71e0SMarcello Maggioni     Builder.SetInsertPoint(Preheader->getTerminator());
568df3e71e0SMarcello Maggioni     Builder.CreateBr(ExitBlock);
569df3e71e0SMarcello Maggioni     // Remove the old branch.
570df3e71e0SMarcello Maggioni     Preheader->getTerminator()->eraseFromParent();
571f88a7975SAtmn Patel   } else {
572f88a7975SAtmn Patel     assert(L->hasNoExitBlocks() &&
573f88a7975SAtmn Patel            "Loop should have either zero or one exit blocks.");
574f88a7975SAtmn Patel 
57565d59b42SNikita Popov     Builder.SetInsertPoint(OldTerm);
576f88a7975SAtmn Patel     Builder.CreateUnreachable();
577f88a7975SAtmn Patel     Preheader->getTerminator()->eraseFromParent();
578f88a7975SAtmn Patel   }
579df3e71e0SMarcello Maggioni 
580df3e71e0SMarcello Maggioni   if (DT) {
581efb130fcSAlina Sbirlea     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
582efb130fcSAlina Sbirlea     if (MSSA) {
583f88a7975SAtmn Patel       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
584f88a7975SAtmn Patel                           *DT);
585efb130fcSAlina Sbirlea       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
586efb130fcSAlina Sbirlea                                                    L->block_end());
587efb130fcSAlina Sbirlea       MSSAU->removeBlocks(DeadBlockSet);
588519b019aSAlina Sbirlea       if (VerifyMemorySSA)
589519b019aSAlina Sbirlea         MSSA->verifyMemorySSA();
590efb130fcSAlina Sbirlea     }
591df3e71e0SMarcello Maggioni   }
592df3e71e0SMarcello Maggioni 
593744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
5948ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
595744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
596744c3c32SDavide Italiano 
597babc224cSAtmn Patel   if (ExitBlock) {
598a757d65cSSerguei Katkov     // Given LCSSA form is satisfied, we should not have users of instructions
599a757d65cSSerguei Katkov     // within the dead loop outside of the loop. However, LCSSA doesn't take
600a757d65cSSerguei Katkov     // unreachable uses into account. We handle them here.
601a757d65cSSerguei Katkov     // We could do it after drop all references (in this case all users in the
602a757d65cSSerguei Katkov     // loop will be already eliminated and we have less work to do but according
603a757d65cSSerguei Katkov     // to API doc of User::dropAllReferences only valid operation after dropping
604a757d65cSSerguei Katkov     // references, is deletion. So let's substitute all usages of
6059df0b254SNuno Lopes     // instruction from the loop with poison value of corresponding type first.
606a757d65cSSerguei Katkov     for (auto *Block : L->blocks())
607a757d65cSSerguei Katkov       for (Instruction &I : *Block) {
6089df0b254SNuno Lopes         auto *Poison = PoisonValue::get(I.getType());
6090d182d9dSKazu Hirata         for (Use &U : llvm::make_early_inc_range(I.uses())) {
610a757d65cSSerguei Katkov           if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
611a757d65cSSerguei Katkov             if (L->contains(Usr->getParent()))
612a757d65cSSerguei Katkov               continue;
613a757d65cSSerguei Katkov           // If we have a DT then we can check that uses outside a loop only in
614a757d65cSSerguei Katkov           // unreachable block.
615a757d65cSSerguei Katkov           if (DT)
616a757d65cSSerguei Katkov             assert(!DT->isReachableFromEntry(U) &&
617a757d65cSSerguei Katkov                    "Unexpected user in reachable block");
6189df0b254SNuno Lopes           U.set(Poison);
619a757d65cSSerguei Katkov         }
620744c3c32SDavide Italiano         auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
621744c3c32SDavide Italiano         if (!DVI)
622744c3c32SDavide Italiano           continue;
623babc224cSAtmn Patel         auto Key =
624babc224cSAtmn Patel             DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
6258ee59ca6SDavide Italiano         if (Key != DeadDebugSet.end())
626744c3c32SDavide Italiano           continue;
6278ee59ca6SDavide Italiano         DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
628744c3c32SDavide Italiano         DeadDebugInst.push_back(DVI);
629a757d65cSSerguei Katkov       }
630a757d65cSSerguei Katkov 
631744c3c32SDavide Italiano     // After the loop has been deleted all the values defined and modified
632744c3c32SDavide Italiano     // inside the loop are going to be unavailable.
633744c3c32SDavide Italiano     // Since debug values in the loop have been deleted, inserting an undef
634744c3c32SDavide Italiano     // dbg.value truncates the range of any dbg.value before the loop where the
635744c3c32SDavide Italiano     // loop used to be. This is particularly important for constant values.
636744c3c32SDavide Italiano     DIBuilder DIB(*ExitBlock->getModule());
637e5be660eSRoman Lebedev     Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
638e5be660eSRoman Lebedev     assert(InsertDbgValueBefore &&
639e5be660eSRoman Lebedev            "There should be a non-PHI instruction in exit block, else these "
640e5be660eSRoman Lebedev            "instructions will have no parent.");
641744c3c32SDavide Italiano     for (auto *DVI : DeadDebugInst)
642e5be660eSRoman Lebedev       DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
643e5be660eSRoman Lebedev                                   DVI->getVariable(), DVI->getExpression(),
644e5be660eSRoman Lebedev                                   DVI->getDebugLoc(), InsertDbgValueBefore);
645babc224cSAtmn Patel   }
646744c3c32SDavide Italiano 
647df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
648df3e71e0SMarcello Maggioni   // delete it freely later.
649df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
650df3e71e0SMarcello Maggioni     Block->dropAllReferences();
651df3e71e0SMarcello Maggioni 
652efb130fcSAlina Sbirlea   if (MSSA && VerifyMemorySSA)
653efb130fcSAlina Sbirlea     MSSA->verifyMemorySSA();
654efb130fcSAlina Sbirlea 
655df3e71e0SMarcello Maggioni   if (LI) {
656df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
657df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
658df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
659df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
660d1abf481SKazu Hirata     for (BasicBlock *BB : L->blocks())
661d1abf481SKazu Hirata       BB->eraseFromParent();
662df3e71e0SMarcello Maggioni 
663df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
664df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
665df3e71e0SMarcello Maggioni 
666df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
667df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
668df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
669df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
670df3e71e0SMarcello Maggioni 
671df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
6729883d7edSWhitney Tsang     // Note: LoopInfo::erase remove the given loop and relink its subloops with
6739883d7edSWhitney Tsang     // its parent. While removeLoop/removeChildLoop remove the given loop but
6749883d7edSWhitney Tsang     // not relink its subloops, which is what we want.
6759883d7edSWhitney Tsang     if (Loop *ParentLoop = L->getParentLoop()) {
6765d6c5b46SWhitney Tsang       Loop::iterator I = find(*ParentLoop, L);
6779883d7edSWhitney Tsang       assert(I != ParentLoop->end() && "Couldn't find loop");
6789883d7edSWhitney Tsang       ParentLoop->removeChildLoop(I);
6799883d7edSWhitney Tsang     } else {
6805d6c5b46SWhitney Tsang       Loop::iterator I = find(*LI, L);
6819883d7edSWhitney Tsang       assert(I != LI->end() && "Couldn't find loop");
6829883d7edSWhitney Tsang       LI->removeLoop(I);
6839883d7edSWhitney Tsang     }
6849883d7edSWhitney Tsang     LI->destroy(L);
685df3e71e0SMarcello Maggioni   }
686df3e71e0SMarcello Maggioni }
687df3e71e0SMarcello Maggioni 
breakLoopBackedge(Loop * L,DominatorTree & DT,ScalarEvolution & SE,LoopInfo & LI,MemorySSA * MSSA)6884739dd67SPhilip Reames void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
6894739dd67SPhilip Reames                              LoopInfo &LI, MemorySSA *MSSA) {
6904739dd67SPhilip Reames   auto *Latch = L->getLoopLatch();
6914739dd67SPhilip Reames   assert(Latch && "multiple latches not yet supported");
6924739dd67SPhilip Reames   auto *Header = L->getHeader();
693d77f9448SNikita Popov   Loop *OutermostLoop = L->getOutermostLoop();
6944739dd67SPhilip Reames 
6954739dd67SPhilip Reames   SE.forgetLoop(L);
6964739dd67SPhilip Reames 
6974739dd67SPhilip Reames   std::unique_ptr<MemorySSAUpdater> MSSAU;
6984739dd67SPhilip Reames   if (MSSA)
6994739dd67SPhilip Reames     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
7004739dd67SPhilip Reames 
7016a823760SPhilip Reames   // Update the CFG and domtree.  We chose to special case a couple of
7026a823760SPhilip Reames   // of common cases for code quality and test readability reasons.
7036a823760SPhilip Reames   [&]() -> void {
7046a823760SPhilip Reames     if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
7056a823760SPhilip Reames       if (!BI->isConditional()) {
7066a823760SPhilip Reames         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
7076a823760SPhilip Reames         (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
7086a823760SPhilip Reames                                   MSSAU.get());
7096a823760SPhilip Reames         return;
7106a823760SPhilip Reames       }
7116a823760SPhilip Reames 
7126a823760SPhilip Reames       // Conditional latch/exit - note that latch can be shared by inner
7136a823760SPhilip Reames       // and outer loop so the other target doesn't need to an exit
7146a823760SPhilip Reames       if (L->isLoopExiting(Latch)) {
7156a823760SPhilip Reames         // TODO: Generalize ConstantFoldTerminator so that it can be used
716c3b3aa27SPhilip Reames         // here without invalidating LCSSA or MemorySSA.  (Tricky case for
717c3b3aa27SPhilip Reames         // LCSSA: header is an exit block of a preceeding sibling loop w/o
718c3b3aa27SPhilip Reames         // dedicated exits.)
7196a823760SPhilip Reames         const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
7206a823760SPhilip Reames         BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
7216a823760SPhilip Reames 
7226a823760SPhilip Reames         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
7236a823760SPhilip Reames         Header->removePredecessor(Latch, true);
7246a823760SPhilip Reames 
7256a823760SPhilip Reames         IRBuilder<> Builder(BI);
7266a823760SPhilip Reames         auto *NewBI = Builder.CreateBr(ExitBB);
7276a823760SPhilip Reames         // Transfer the metadata to the new branch instruction (minus the
7286a823760SPhilip Reames         // loop info since this is no longer a loop)
7296a823760SPhilip Reames         NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
7306a823760SPhilip Reames                                   LLVMContext::MD_annotation});
7316a823760SPhilip Reames 
7326a823760SPhilip Reames         BI->eraseFromParent();
7336a823760SPhilip Reames         DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
734c3b3aa27SPhilip Reames         if (MSSA)
735c3b3aa27SPhilip Reames           MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
7366a823760SPhilip Reames         return;
7376a823760SPhilip Reames       }
7386a823760SPhilip Reames     }
7396a823760SPhilip Reames 
7406a823760SPhilip Reames     // General case.  By splitting the backedge, and then explicitly making it
7416a823760SPhilip Reames     // unreachable we gracefully handle corner cases such as switch and invoke
7426a823760SPhilip Reames     // termiantors.
7434739dd67SPhilip Reames     auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
7444739dd67SPhilip Reames 
7454739dd67SPhilip Reames     DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
74625a3130dSJohannes Doerfert     (void)changeToUnreachable(BackedgeBB->getTerminator(),
7474739dd67SPhilip Reames                               /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
7486a823760SPhilip Reames   }();
7494739dd67SPhilip Reames 
7504739dd67SPhilip Reames   // Erase (and destroy) this loop instance.  Handles relinking sub-loops
7514739dd67SPhilip Reames   // and blocks within the loop as needed.
7524739dd67SPhilip Reames   LI.erase(L);
753ef51eed3SPhilip Reames 
754ef51eed3SPhilip Reames   // If the loop we broke had a parent, then changeToUnreachable might have
755ef51eed3SPhilip Reames   // caused a block to be removed from the parent loop (see loop_nest_lcssa
756ef51eed3SPhilip Reames   // test case in zero-btc.ll for an example), thus changing the parent's
757ef51eed3SPhilip Reames   // exit blocks.  If that happened, we need to rebuild LCSSA on the outermost
758ef51eed3SPhilip Reames   // loop which might have a had a block removed.
759ef51eed3SPhilip Reames   if (OutermostLoop != L)
760ef51eed3SPhilip Reames     formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
7614739dd67SPhilip Reames }
7624739dd67SPhilip Reames 
7634739dd67SPhilip Reames 
7642d31b025SPhilip Reames /// Checks if \p L has an exiting latch branch.  There may also be other
7652d31b025SPhilip Reames /// exiting blocks.  Returns branch instruction terminating the loop
766af7e1588SEvgeniy Brevnov /// latch if above check is successful, nullptr otherwise.
getExpectedExitLoopLatchBranch(Loop * L)767af7e1588SEvgeniy Brevnov static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
76845c43e7dSSerguei Katkov   BasicBlock *Latch = L->getLoopLatch();
76945c43e7dSSerguei Katkov   if (!Latch)
770af7e1588SEvgeniy Brevnov     return nullptr;
771af7e1588SEvgeniy Brevnov 
77245c43e7dSSerguei Katkov   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
77345c43e7dSSerguei Katkov   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
774af7e1588SEvgeniy Brevnov     return nullptr;
77541d72a86SDehao Chen 
77641d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
77741d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
77841d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
77941d72a86SDehao Chen 
780af7e1588SEvgeniy Brevnov   return LatchBR;
781af7e1588SEvgeniy Brevnov }
782af7e1588SEvgeniy Brevnov 
783f632c494SPhilip Reames /// Return the estimated trip count for any exiting branch which dominates
784f632c494SPhilip Reames /// the loop latch.
785f632c494SPhilip Reames static Optional<uint64_t>
getEstimatedTripCount(BranchInst * ExitingBranch,Loop * L,uint64_t & OrigExitWeight)786f632c494SPhilip Reames getEstimatedTripCount(BranchInst *ExitingBranch, Loop *L,
787f632c494SPhilip Reames                       uint64_t &OrigExitWeight) {
788f632c494SPhilip Reames   // To estimate the number of times the loop body was executed, we want to
789f632c494SPhilip Reames   // know the number of times the backedge was taken, vs. the number of times
790f632c494SPhilip Reames   // we exited the loop.
791f632c494SPhilip Reames   uint64_t LoopWeight, ExitWeight;
792f632c494SPhilip Reames   if (!ExitingBranch->extractProfMetadata(LoopWeight, ExitWeight))
793f632c494SPhilip Reames     return None;
794f632c494SPhilip Reames 
795f632c494SPhilip Reames   if (L->contains(ExitingBranch->getSuccessor(1)))
796f632c494SPhilip Reames     std::swap(LoopWeight, ExitWeight);
797f632c494SPhilip Reames 
798f632c494SPhilip Reames   if (!ExitWeight)
799f632c494SPhilip Reames     // Don't have a way to return predicated infinite
800f632c494SPhilip Reames     return None;
801f632c494SPhilip Reames 
802f632c494SPhilip Reames   OrigExitWeight = ExitWeight;
803f632c494SPhilip Reames 
804f632c494SPhilip Reames   // Estimated exit count is a ratio of the loop weight by the weight of the
805f632c494SPhilip Reames   // edge exiting the loop, rounded to nearest.
806f632c494SPhilip Reames   uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
807f632c494SPhilip Reames   // Estimated trip count is one plus estimated exit count.
808f632c494SPhilip Reames   return ExitCount + 1;
809f632c494SPhilip Reames }
810f632c494SPhilip Reames 
811af7e1588SEvgeniy Brevnov Optional<unsigned>
getLoopEstimatedTripCount(Loop * L,unsigned * EstimatedLoopInvocationWeight)812af7e1588SEvgeniy Brevnov llvm::getLoopEstimatedTripCount(Loop *L,
813af7e1588SEvgeniy Brevnov                                 unsigned *EstimatedLoopInvocationWeight) {
8142d31b025SPhilip Reames   // Currently we take the estimate exit count only from the loop latch,
8152d31b025SPhilip Reames   // ignoring other exiting blocks.  This can overestimate the trip count
8162d31b025SPhilip Reames   // if we exit through another exit, but can never underestimate it.
8172d31b025SPhilip Reames   // TODO: incorporate information from other exits
818f632c494SPhilip Reames   if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) {
819f632c494SPhilip Reames     uint64_t ExitWeight;
820f632c494SPhilip Reames     if (Optional<uint64_t> EstTripCount =
821f632c494SPhilip Reames         getEstimatedTripCount(LatchBranch, L, ExitWeight)) {
822af7e1588SEvgeniy Brevnov       if (EstimatedLoopInvocationWeight)
823f632c494SPhilip Reames         *EstimatedLoopInvocationWeight = ExitWeight;
824f632c494SPhilip Reames       return *EstTripCount;
825f632c494SPhilip Reames     }
826f632c494SPhilip Reames   }
827f632c494SPhilip Reames   return None;
82841d72a86SDehao Chen }
829cf9daa33SAmara Emerson 
setLoopEstimatedTripCount(Loop * L,unsigned EstimatedTripCount,unsigned EstimatedloopInvocationWeight)830af7e1588SEvgeniy Brevnov bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
831af7e1588SEvgeniy Brevnov                                      unsigned EstimatedloopInvocationWeight) {
8322d31b025SPhilip Reames   // At the moment, we currently support changing the estimate trip count of
8332d31b025SPhilip Reames   // the latch branch only.  We could extend this API to manipulate estimated
8342d31b025SPhilip Reames   // trip counts for any exit.
835af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
836af7e1588SEvgeniy Brevnov   if (!LatchBranch)
837af7e1588SEvgeniy Brevnov     return false;
838af7e1588SEvgeniy Brevnov 
839af7e1588SEvgeniy Brevnov   // Calculate taken and exit weights.
840af7e1588SEvgeniy Brevnov   unsigned LatchExitWeight = 0;
841af7e1588SEvgeniy Brevnov   unsigned BackedgeTakenWeight = 0;
842af7e1588SEvgeniy Brevnov 
843af7e1588SEvgeniy Brevnov   if (EstimatedTripCount > 0) {
844af7e1588SEvgeniy Brevnov     LatchExitWeight = EstimatedloopInvocationWeight;
845af7e1588SEvgeniy Brevnov     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
846af7e1588SEvgeniy Brevnov   }
847af7e1588SEvgeniy Brevnov 
848af7e1588SEvgeniy Brevnov   // Make a swap if back edge is taken when condition is "false".
849af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
850af7e1588SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
851af7e1588SEvgeniy Brevnov 
852af7e1588SEvgeniy Brevnov   MDBuilder MDB(LatchBranch->getContext());
853af7e1588SEvgeniy Brevnov 
854af7e1588SEvgeniy Brevnov   // Set/Update profile metadata.
855af7e1588SEvgeniy Brevnov   LatchBranch->setMetadata(
856af7e1588SEvgeniy Brevnov       LLVMContext::MD_prof,
857af7e1588SEvgeniy Brevnov       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
858af7e1588SEvgeniy Brevnov 
859af7e1588SEvgeniy Brevnov   return true;
860af7e1588SEvgeniy Brevnov }
861af7e1588SEvgeniy Brevnov 
hasIterationCountInvariantInParent(Loop * InnerLoop,ScalarEvolution & SE)8626cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
863395b80cdSDavid Green                                               ScalarEvolution &SE) {
864395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
865395b80cdSDavid Green   if (!OuterL)
866395b80cdSDavid Green     return true;
867395b80cdSDavid Green 
868395b80cdSDavid Green   // Get the backedge taken count for the inner loop
869395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
870395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
871395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
872395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
873395b80cdSDavid Green     return false;
874395b80cdSDavid Green 
875395b80cdSDavid Green   // Get whether count is invariant to the outer loop
876395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
877395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
878395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
879395b80cdSDavid Green     return false;
880395b80cdSDavid Green 
881395b80cdSDavid Green   return true;
882395b80cdSDavid Green }
883395b80cdSDavid Green 
getMinMaxReductionPredicate(RecurKind RK)8840dcd2b40SSimon Pilgrim CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
8856594dc37SVikram TV   switch (RK) {
8866594dc37SVikram TV   default:
8876594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
888c74e8539SSanjay Patel   case RecurKind::UMin:
8890dcd2b40SSimon Pilgrim     return CmpInst::ICMP_ULT;
890c74e8539SSanjay Patel   case RecurKind::UMax:
8910dcd2b40SSimon Pilgrim     return CmpInst::ICMP_UGT;
892c74e8539SSanjay Patel   case RecurKind::SMin:
8930dcd2b40SSimon Pilgrim     return CmpInst::ICMP_SLT;
894c74e8539SSanjay Patel   case RecurKind::SMax:
8950dcd2b40SSimon Pilgrim     return CmpInst::ICMP_SGT;
896c74e8539SSanjay Patel   case RecurKind::FMin:
8970dcd2b40SSimon Pilgrim     return CmpInst::FCMP_OLT;
898c74e8539SSanjay Patel   case RecurKind::FMax:
8990dcd2b40SSimon Pilgrim     return CmpInst::FCMP_OGT;
9000dcd2b40SSimon Pilgrim   }
9016594dc37SVikram TV }
9026594dc37SVikram TV 
createSelectCmpOp(IRBuilderBase & Builder,Value * StartVal,RecurKind RK,Value * Left,Value * Right)90326b7d9d6SDavid Sherwood Value *llvm::createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal,
90426b7d9d6SDavid Sherwood                                RecurKind RK, Value *Left, Value *Right) {
90526b7d9d6SDavid Sherwood   if (auto VTy = dyn_cast<VectorType>(Left->getType()))
90626b7d9d6SDavid Sherwood     StartVal = Builder.CreateVectorSplat(VTy->getElementCount(), StartVal);
90726b7d9d6SDavid Sherwood   Value *Cmp =
90826b7d9d6SDavid Sherwood       Builder.CreateCmp(CmpInst::ICMP_NE, Left, StartVal, "rdx.select.cmp");
90926b7d9d6SDavid Sherwood   return Builder.CreateSelect(Cmp, Left, Right, "rdx.select");
91026b7d9d6SDavid Sherwood }
91126b7d9d6SDavid Sherwood 
createMinMaxOp(IRBuilderBase & Builder,RecurKind RK,Value * Left,Value * Right)9120dcd2b40SSimon Pilgrim Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
9130dcd2b40SSimon Pilgrim                             Value *Right) {
9140dcd2b40SSimon Pilgrim   CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
91509b1c563SSanjay Patel   Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
9166594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
9176594dc37SVikram TV   return Select;
9186594dc37SVikram TV }
9196594dc37SVikram TV 
92023c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
getOrderedReduction(IRBuilderBase & Builder,Value * Acc,Value * Src,unsigned Op,RecurKind RdxKind)921c74e8539SSanjay Patel Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
922b24db85cSPhilip Reames                                  unsigned Op, RecurKind RdxKind) {
9238d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
92423c2182cSSimon Pilgrim 
92523c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
92623c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
92723c2182cSSimon Pilgrim   Value *Result = Acc;
92823c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
92923c2182cSSimon Pilgrim     Value *Ext =
93023c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
93123c2182cSSimon Pilgrim 
93223c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
93323c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
93423c2182cSSimon Pilgrim                                    "bin.rdx");
93523c2182cSSimon Pilgrim     } else {
936c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
93723c2182cSSimon Pilgrim              "Invalid min/max");
938c74e8539SSanjay Patel       Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
93923c2182cSSimon Pilgrim     }
94023c2182cSSimon Pilgrim   }
94123c2182cSSimon Pilgrim 
94223c2182cSSimon Pilgrim   return Result;
94323c2182cSSimon Pilgrim }
94423c2182cSSimon Pilgrim 
945cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
getShuffleReduction(IRBuilderBase & Builder,Value * Src,unsigned Op,RecurKind RdxKind)946c74e8539SSanjay Patel Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
947b24db85cSPhilip Reames                                  unsigned Op, RecurKind RdxKind) {
9488d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
949cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
950cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
951cf9daa33SAmara Emerson   // round.
952cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
953cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
9540d13f94cSPhilip Reames   // Note: fast-math-flags flags are controlled by the builder configuration
9550d13f94cSPhilip Reames   // and are assumed to apply to all generated arithmetic instructions.  Other
9560d13f94cSPhilip Reames   // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
9570d13f94cSPhilip Reames   // of the builder configuration, and since they're not passed explicitly,
9580d13f94cSPhilip Reames   // will never be relevant here.  Note that it would be generally unsound to
9590d13f94cSPhilip Reames   // propagate these from an intrinsic call to the expansion anyways as we/
9600d13f94cSPhilip Reames   // change the order of operations.
961cf9daa33SAmara Emerson   Value *TmpVec = Src;
9626f64dacaSBenjamin Kramer   SmallVector<int, 32> ShuffleMask(VF);
963cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
964cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
965cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
9666f64dacaSBenjamin Kramer       ShuffleMask[j] = i / 2 + j;
967cf9daa33SAmara Emerson 
968cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
9696f64dacaSBenjamin Kramer     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
970cf9daa33SAmara Emerson 
9719b296102SJuneyoung Lee     Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
972cf9daa33SAmara Emerson 
973cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
974ad62a3a2SSanjay Patel       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
975ad62a3a2SSanjay Patel                                    "bin.rdx");
976cf9daa33SAmara Emerson     } else {
977c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
978cf9daa33SAmara Emerson              "Invalid min/max");
979c74e8539SSanjay Patel       TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
980cf9daa33SAmara Emerson     }
981cf9daa33SAmara Emerson   }
982cf9daa33SAmara Emerson   // The result is in the first element of the vector.
983cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
984cf9daa33SAmara Emerson }
985cf9daa33SAmara Emerson 
createSelectCmpTargetReduction(IRBuilderBase & Builder,const TargetTransformInfo * TTI,Value * Src,const RecurrenceDescriptor & Desc,PHINode * OrigPhi)98626b7d9d6SDavid Sherwood Value *llvm::createSelectCmpTargetReduction(IRBuilderBase &Builder,
98726b7d9d6SDavid Sherwood                                             const TargetTransformInfo *TTI,
98826b7d9d6SDavid Sherwood                                             Value *Src,
98926b7d9d6SDavid Sherwood                                             const RecurrenceDescriptor &Desc,
99026b7d9d6SDavid Sherwood                                             PHINode *OrigPhi) {
99126b7d9d6SDavid Sherwood   assert(RecurrenceDescriptor::isSelectCmpRecurrenceKind(
99226b7d9d6SDavid Sherwood              Desc.getRecurrenceKind()) &&
99326b7d9d6SDavid Sherwood          "Unexpected reduction kind");
99426b7d9d6SDavid Sherwood   Value *InitVal = Desc.getRecurrenceStartValue();
99526b7d9d6SDavid Sherwood   Value *NewVal = nullptr;
99626b7d9d6SDavid Sherwood 
99726b7d9d6SDavid Sherwood   // First use the original phi to determine the new value we're trying to
99826b7d9d6SDavid Sherwood   // select from in the loop.
99926b7d9d6SDavid Sherwood   SelectInst *SI = nullptr;
100026b7d9d6SDavid Sherwood   for (auto *U : OrigPhi->users()) {
100126b7d9d6SDavid Sherwood     if ((SI = dyn_cast<SelectInst>(U)))
100226b7d9d6SDavid Sherwood       break;
100326b7d9d6SDavid Sherwood   }
100426b7d9d6SDavid Sherwood   assert(SI && "One user of the original phi should be a select");
100526b7d9d6SDavid Sherwood 
100626b7d9d6SDavid Sherwood   if (SI->getTrueValue() == OrigPhi)
100726b7d9d6SDavid Sherwood     NewVal = SI->getFalseValue();
100826b7d9d6SDavid Sherwood   else {
100926b7d9d6SDavid Sherwood     assert(SI->getFalseValue() == OrigPhi &&
101026b7d9d6SDavid Sherwood            "At least one input to the select should be the original Phi");
101126b7d9d6SDavid Sherwood     NewVal = SI->getTrueValue();
101226b7d9d6SDavid Sherwood   }
101326b7d9d6SDavid Sherwood 
101426b7d9d6SDavid Sherwood   // Create a splat vector with the new value and compare this to the vector
101526b7d9d6SDavid Sherwood   // we want to reduce.
101626b7d9d6SDavid Sherwood   ElementCount EC = cast<VectorType>(Src->getType())->getElementCount();
101726b7d9d6SDavid Sherwood   Value *Right = Builder.CreateVectorSplat(EC, InitVal);
101826b7d9d6SDavid Sherwood   Value *Cmp =
101926b7d9d6SDavid Sherwood       Builder.CreateCmp(CmpInst::ICMP_NE, Src, Right, "rdx.select.cmp");
102026b7d9d6SDavid Sherwood 
102126b7d9d6SDavid Sherwood   // If any predicate is true it means that we want to select the new value.
102226b7d9d6SDavid Sherwood   Cmp = Builder.CreateOrReduce(Cmp);
102326b7d9d6SDavid Sherwood   return Builder.CreateSelect(Cmp, NewVal, InitVal, "rdx.select");
102426b7d9d6SDavid Sherwood }
102526b7d9d6SDavid Sherwood 
createSimpleTargetReduction(IRBuilderBase & Builder,const TargetTransformInfo * TTI,Value * Src,RecurKind RdxKind)1026c74e8539SSanjay Patel Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder,
1027c74e8539SSanjay Patel                                          const TargetTransformInfo *TTI,
1028b24db85cSPhilip Reames                                          Value *Src, RecurKind RdxKind) {
102997669575SSanjay Patel   auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
103036263a7cSSanjay Patel   switch (RdxKind) {
103136263a7cSSanjay Patel   case RecurKind::Add:
103297669575SSanjay Patel     return Builder.CreateAddReduce(Src);
103336263a7cSSanjay Patel   case RecurKind::Mul:
103497669575SSanjay Patel     return Builder.CreateMulReduce(Src);
103536263a7cSSanjay Patel   case RecurKind::And:
103697669575SSanjay Patel     return Builder.CreateAndReduce(Src);
103736263a7cSSanjay Patel   case RecurKind::Or:
103897669575SSanjay Patel     return Builder.CreateOrReduce(Src);
103936263a7cSSanjay Patel   case RecurKind::Xor:
104097669575SSanjay Patel     return Builder.CreateXorReduce(Src);
1041c2441b6bSRosie Sumpter   case RecurKind::FMulAdd:
104236263a7cSSanjay Patel   case RecurKind::FAdd:
104397669575SSanjay Patel     return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
104497669575SSanjay Patel                                     Src);
104536263a7cSSanjay Patel   case RecurKind::FMul:
104697669575SSanjay Patel     return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
1047c74e8539SSanjay Patel   case RecurKind::SMax:
104897669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, true);
1049c74e8539SSanjay Patel   case RecurKind::SMin:
105097669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, true);
1051c74e8539SSanjay Patel   case RecurKind::UMax:
105297669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, false);
1053c74e8539SSanjay Patel   case RecurKind::UMin:
105497669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, false);
105536263a7cSSanjay Patel   case RecurKind::FMax:
105697669575SSanjay Patel     return Builder.CreateFPMaxReduce(Src);
105736263a7cSSanjay Patel   case RecurKind::FMin:
105897669575SSanjay Patel     return Builder.CreateFPMinReduce(Src);
1059cf9daa33SAmara Emerson   default:
1060cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1061cf9daa33SAmara Emerson   }
1062cf9daa33SAmara Emerson }
1063cf9daa33SAmara Emerson 
createTargetReduction(IRBuilderBase & B,const TargetTransformInfo * TTI,const RecurrenceDescriptor & Desc,Value * Src,PHINode * OrigPhi)106428ffe38bSNikita Popov Value *llvm::createTargetReduction(IRBuilderBase &B,
1065cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
106626b7d9d6SDavid Sherwood                                    const RecurrenceDescriptor &Desc, Value *Src,
106726b7d9d6SDavid Sherwood                                    PHINode *OrigPhi) {
1068cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
1069ad62a3a2SSanjay Patel   // All ops in the reduction inherit fast-math-flags from the recurrence
1070ad62a3a2SSanjay Patel   // descriptor.
107128ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1072ad62a3a2SSanjay Patel   B.setFastMathFlags(Desc.getFastMathFlags());
107326b7d9d6SDavid Sherwood 
107426b7d9d6SDavid Sherwood   RecurKind RK = Desc.getRecurrenceKind();
107526b7d9d6SDavid Sherwood   if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
107626b7d9d6SDavid Sherwood     return createSelectCmpTargetReduction(B, TTI, Src, Desc, OrigPhi);
107726b7d9d6SDavid Sherwood 
107826b7d9d6SDavid Sherwood   return createSimpleTargetReduction(B, TTI, Src, RK);
1079cf9daa33SAmara Emerson }
1080cf9daa33SAmara Emerson 
createOrderedReduction(IRBuilderBase & B,const RecurrenceDescriptor & Desc,Value * Src,Value * Start)10817344f3d3SKerry McLaughlin Value *llvm::createOrderedReduction(IRBuilderBase &B,
10825e6bfb66SSimon Pilgrim                                     const RecurrenceDescriptor &Desc,
10835e6bfb66SSimon Pilgrim                                     Value *Src, Value *Start) {
1084c2441b6bSRosie Sumpter   assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
1085c2441b6bSRosie Sumpter           Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
1086ce4acb01SBenjamin Kramer          "Unexpected reduction kind");
10877344f3d3SKerry McLaughlin   assert(Src->getType()->isVectorTy() && "Expected a vector type");
10887344f3d3SKerry McLaughlin   assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
10897344f3d3SKerry McLaughlin 
10907344f3d3SKerry McLaughlin   return B.CreateFAddReduce(Start, Src);
10917344f3d3SKerry McLaughlin }
10927344f3d3SKerry McLaughlin 
propagateIRFlags(Value * I,ArrayRef<Value * > VL,Value * OpValue,bool IncludeWrapFlags)109310f41a21SAlexey Bataev void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue,
109410f41a21SAlexey Bataev                             bool IncludeWrapFlags) {
1095a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1096a61f4b89SDinar Temirbulatov   if (!VecOp)
1097a61f4b89SDinar Temirbulatov     return;
1098a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1099a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1100a61f4b89SDinar Temirbulatov   if (!Intersection)
1101a61f4b89SDinar Temirbulatov     return;
1102a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
110310f41a21SAlexey Bataev   VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
1104a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1105a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1106a61f4b89SDinar Temirbulatov     if (!Instr)
1107a61f4b89SDinar Temirbulatov       continue;
1108a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1109a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1110cf9daa33SAmara Emerson   }
1111cf9daa33SAmara Emerson }
1112a78dc4d6SMax Kazantsev 
isKnownNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1113a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1114a78dc4d6SMax Kazantsev                                  ScalarEvolution &SE) {
1115a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1116a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1117a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1118a78dc4d6SMax Kazantsev }
1119a78dc4d6SMax Kazantsev 
isKnownNonNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1120a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1121a78dc4d6SMax Kazantsev                                     ScalarEvolution &SE) {
1122a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1123a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1124a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1125a78dc4d6SMax Kazantsev }
1126a78dc4d6SMax Kazantsev 
cannotBeMinInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1127a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1128a78dc4d6SMax Kazantsev                              bool Signed) {
1129a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1130a78dc4d6SMax Kazantsev   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1131a78dc4d6SMax Kazantsev     APInt::getMinValue(BitWidth);
1132a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1133a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1134a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1135a78dc4d6SMax Kazantsev                                      SE.getConstant(Min));
1136a78dc4d6SMax Kazantsev }
1137a78dc4d6SMax Kazantsev 
cannotBeMaxInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1138a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1139a78dc4d6SMax Kazantsev                              bool Signed) {
1140a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1141a78dc4d6SMax Kazantsev   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1142a78dc4d6SMax Kazantsev     APInt::getMaxValue(BitWidth);
1143a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1144a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1145a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1146a78dc4d6SMax Kazantsev                                      SE.getConstant(Max));
1147a78dc4d6SMax Kazantsev }
114893175a5cSSjoerd Meijer 
114993175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
115093175a5cSSjoerd Meijer // rewriteLoopExitValues - Optimize IV users outside the loop.
115193175a5cSSjoerd Meijer // As a side effect, reduces the amount of IV processing within the loop.
115293175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
115393175a5cSSjoerd Meijer 
hasHardUserWithinLoop(const Loop * L,const Instruction * I)115493175a5cSSjoerd Meijer static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
115593175a5cSSjoerd Meijer   SmallPtrSet<const Instruction *, 8> Visited;
115693175a5cSSjoerd Meijer   SmallVector<const Instruction *, 8> WorkList;
115793175a5cSSjoerd Meijer   Visited.insert(I);
115893175a5cSSjoerd Meijer   WorkList.push_back(I);
115993175a5cSSjoerd Meijer   while (!WorkList.empty()) {
116093175a5cSSjoerd Meijer     const Instruction *Curr = WorkList.pop_back_val();
116193175a5cSSjoerd Meijer     // This use is outside the loop, nothing to do.
116293175a5cSSjoerd Meijer     if (!L->contains(Curr))
116393175a5cSSjoerd Meijer       continue;
116493175a5cSSjoerd Meijer     // Do we assume it is a "hard" use which will not be eliminated easily?
116593175a5cSSjoerd Meijer     if (Curr->mayHaveSideEffects())
116693175a5cSSjoerd Meijer       return true;
116793175a5cSSjoerd Meijer     // Otherwise, add all its users to worklist.
116893175a5cSSjoerd Meijer     for (auto U : Curr->users()) {
116993175a5cSSjoerd Meijer       auto *UI = cast<Instruction>(U);
117093175a5cSSjoerd Meijer       if (Visited.insert(UI).second)
117193175a5cSSjoerd Meijer         WorkList.push_back(UI);
117293175a5cSSjoerd Meijer     }
117393175a5cSSjoerd Meijer   }
117493175a5cSSjoerd Meijer   return false;
117593175a5cSSjoerd Meijer }
117693175a5cSSjoerd Meijer 
117793175a5cSSjoerd Meijer // Collect information about PHI nodes which can be transformed in
117893175a5cSSjoerd Meijer // rewriteLoopExitValues.
117993175a5cSSjoerd Meijer struct RewritePhi {
1180b2df9612SRoman Lebedev   PHINode *PN;               // For which PHI node is this replacement?
1181b2df9612SRoman Lebedev   unsigned Ith;              // For which incoming value?
1182b2df9612SRoman Lebedev   const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1183b2df9612SRoman Lebedev   Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1184b2df9612SRoman Lebedev   bool HighCost;               // Is this expansion a high-cost?
118593175a5cSSjoerd Meijer 
RewritePhiRewritePhi1186b2df9612SRoman Lebedev   RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1187b2df9612SRoman Lebedev              bool H)
1188b2df9612SRoman Lebedev       : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1189b2df9612SRoman Lebedev         HighCost(H) {}
119093175a5cSSjoerd Meijer };
119193175a5cSSjoerd Meijer 
119293175a5cSSjoerd Meijer // Check whether it is possible to delete the loop after rewriting exit
119393175a5cSSjoerd Meijer // value. If it is possible, ignore ReplaceExitValue and do rewriting
119493175a5cSSjoerd Meijer // aggressively.
canLoopBeDeleted(Loop * L,SmallVector<RewritePhi,8> & RewritePhiSet)119593175a5cSSjoerd Meijer static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
119693175a5cSSjoerd Meijer   BasicBlock *Preheader = L->getLoopPreheader();
119793175a5cSSjoerd Meijer   // If there is no preheader, the loop will not be deleted.
119893175a5cSSjoerd Meijer   if (!Preheader)
119993175a5cSSjoerd Meijer     return false;
120093175a5cSSjoerd Meijer 
120193175a5cSSjoerd Meijer   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
120293175a5cSSjoerd Meijer   // We obviate multiple ExitingBlocks case for simplicity.
120393175a5cSSjoerd Meijer   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
120493175a5cSSjoerd Meijer   // after exit value rewriting, we can enhance the logic here.
120593175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 4> ExitingBlocks;
120693175a5cSSjoerd Meijer   L->getExitingBlocks(ExitingBlocks);
120793175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 8> ExitBlocks;
120893175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
120993175a5cSSjoerd Meijer   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
121093175a5cSSjoerd Meijer     return false;
121193175a5cSSjoerd Meijer 
121293175a5cSSjoerd Meijer   BasicBlock *ExitBlock = ExitBlocks[0];
121393175a5cSSjoerd Meijer   BasicBlock::iterator BI = ExitBlock->begin();
121493175a5cSSjoerd Meijer   while (PHINode *P = dyn_cast<PHINode>(BI)) {
121593175a5cSSjoerd Meijer     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
121693175a5cSSjoerd Meijer 
121793175a5cSSjoerd Meijer     // If the Incoming value of P is found in RewritePhiSet, we know it
121893175a5cSSjoerd Meijer     // could be rewritten to use a loop invariant value in transformation
121993175a5cSSjoerd Meijer     // phase later. Skip it in the loop invariant check below.
122093175a5cSSjoerd Meijer     bool found = false;
122193175a5cSSjoerd Meijer     for (const RewritePhi &Phi : RewritePhiSet) {
122293175a5cSSjoerd Meijer       unsigned i = Phi.Ith;
122393175a5cSSjoerd Meijer       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
122493175a5cSSjoerd Meijer         found = true;
122593175a5cSSjoerd Meijer         break;
122693175a5cSSjoerd Meijer       }
122793175a5cSSjoerd Meijer     }
122893175a5cSSjoerd Meijer 
122993175a5cSSjoerd Meijer     Instruction *I;
123093175a5cSSjoerd Meijer     if (!found && (I = dyn_cast<Instruction>(Incoming)))
123193175a5cSSjoerd Meijer       if (!L->hasLoopInvariantOperands(I))
123293175a5cSSjoerd Meijer         return false;
123393175a5cSSjoerd Meijer 
123493175a5cSSjoerd Meijer     ++BI;
123593175a5cSSjoerd Meijer   }
123693175a5cSSjoerd Meijer 
123793175a5cSSjoerd Meijer   for (auto *BB : L->blocks())
123893175a5cSSjoerd Meijer     if (llvm::any_of(*BB, [](Instruction &I) {
123993175a5cSSjoerd Meijer           return I.mayHaveSideEffects();
124093175a5cSSjoerd Meijer         }))
124193175a5cSSjoerd Meijer       return false;
124293175a5cSSjoerd Meijer 
124393175a5cSSjoerd Meijer   return true;
124493175a5cSSjoerd Meijer }
124593175a5cSSjoerd Meijer 
124658b9666dSZaara Syeda /// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
124758b9666dSZaara Syeda /// and returns true if this Phi is an induction phi in the loop. When
124858b9666dSZaara Syeda /// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
checkIsIndPhi(PHINode * Phi,Loop * L,ScalarEvolution * SE,InductionDescriptor & ID)124958b9666dSZaara Syeda static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
125058b9666dSZaara Syeda                           InductionDescriptor &ID) {
125158b9666dSZaara Syeda   if (!Phi)
125258b9666dSZaara Syeda     return false;
125358b9666dSZaara Syeda   if (!L->getLoopPreheader())
125458b9666dSZaara Syeda     return false;
125558b9666dSZaara Syeda   if (Phi->getParent() != L->getHeader())
125658b9666dSZaara Syeda     return false;
125758b9666dSZaara Syeda   return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
125858b9666dSZaara Syeda }
125958b9666dSZaara Syeda 
rewriteLoopExitValues(Loop * L,LoopInfo * LI,TargetLibraryInfo * TLI,ScalarEvolution * SE,const TargetTransformInfo * TTI,SCEVExpander & Rewriter,DominatorTree * DT,ReplaceExitVal ReplaceExitValue,SmallVector<WeakTrackingVH,16> & DeadInsts)12600789f280SRoman Lebedev int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
12610789f280SRoman Lebedev                                 ScalarEvolution *SE,
12620789f280SRoman Lebedev                                 const TargetTransformInfo *TTI,
12630789f280SRoman Lebedev                                 SCEVExpander &Rewriter, DominatorTree *DT,
12640789f280SRoman Lebedev                                 ReplaceExitVal ReplaceExitValue,
126593175a5cSSjoerd Meijer                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
126693175a5cSSjoerd Meijer   // Check a pre-condition.
126793175a5cSSjoerd Meijer   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
126893175a5cSSjoerd Meijer          "Indvars did not preserve LCSSA!");
126993175a5cSSjoerd Meijer 
127093175a5cSSjoerd Meijer   SmallVector<BasicBlock*, 8> ExitBlocks;
127193175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
127293175a5cSSjoerd Meijer 
127393175a5cSSjoerd Meijer   SmallVector<RewritePhi, 8> RewritePhiSet;
127493175a5cSSjoerd Meijer   // Find all values that are computed inside the loop, but used outside of it.
127593175a5cSSjoerd Meijer   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
127693175a5cSSjoerd Meijer   // the exit blocks of the loop to find them.
127793175a5cSSjoerd Meijer   for (BasicBlock *ExitBB : ExitBlocks) {
127893175a5cSSjoerd Meijer     // If there are no PHI nodes in this exit block, then no values defined
127993175a5cSSjoerd Meijer     // inside the loop are used on this path, skip it.
128093175a5cSSjoerd Meijer     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
128193175a5cSSjoerd Meijer     if (!PN) continue;
128293175a5cSSjoerd Meijer 
128393175a5cSSjoerd Meijer     unsigned NumPreds = PN->getNumIncomingValues();
128493175a5cSSjoerd Meijer 
128593175a5cSSjoerd Meijer     // Iterate over all of the PHI nodes.
128693175a5cSSjoerd Meijer     BasicBlock::iterator BBI = ExitBB->begin();
128793175a5cSSjoerd Meijer     while ((PN = dyn_cast<PHINode>(BBI++))) {
128893175a5cSSjoerd Meijer       if (PN->use_empty())
128993175a5cSSjoerd Meijer         continue; // dead use, don't replace it
129093175a5cSSjoerd Meijer 
129193175a5cSSjoerd Meijer       if (!SE->isSCEVable(PN->getType()))
129293175a5cSSjoerd Meijer         continue;
129393175a5cSSjoerd Meijer 
129493175a5cSSjoerd Meijer       // Iterate over all of the values in all the PHI nodes.
129593175a5cSSjoerd Meijer       for (unsigned i = 0; i != NumPreds; ++i) {
129693175a5cSSjoerd Meijer         // If the value being merged in is not integer or is not defined
129793175a5cSSjoerd Meijer         // in the loop, skip it.
129893175a5cSSjoerd Meijer         Value *InVal = PN->getIncomingValue(i);
129993175a5cSSjoerd Meijer         if (!isa<Instruction>(InVal))
130093175a5cSSjoerd Meijer           continue;
130193175a5cSSjoerd Meijer 
130293175a5cSSjoerd Meijer         // If this pred is for a subloop, not L itself, skip it.
130393175a5cSSjoerd Meijer         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
130493175a5cSSjoerd Meijer           continue; // The Block is in a subloop, skip it.
130593175a5cSSjoerd Meijer 
130693175a5cSSjoerd Meijer         // Check that InVal is defined in the loop.
130793175a5cSSjoerd Meijer         Instruction *Inst = cast<Instruction>(InVal);
130893175a5cSSjoerd Meijer         if (!L->contains(Inst))
130993175a5cSSjoerd Meijer           continue;
131093175a5cSSjoerd Meijer 
1311dbf6ab5eSZaara Syeda         // Find exit values which are induction variables in the loop, and are
1312dbf6ab5eSZaara Syeda         // unused in the loop, with the only use being the exit block PhiNode,
1313dbf6ab5eSZaara Syeda         // and the induction variable update binary operator.
1314dbf6ab5eSZaara Syeda         // The exit value can be replaced with the final value when it is cheap
1315dbf6ab5eSZaara Syeda         // to do so.
1316dbf6ab5eSZaara Syeda         if (ReplaceExitValue == UnusedIndVarInLoop) {
1317dbf6ab5eSZaara Syeda           InductionDescriptor ID;
1318dbf6ab5eSZaara Syeda           PHINode *IndPhi = dyn_cast<PHINode>(Inst);
1319dbf6ab5eSZaara Syeda           if (IndPhi) {
132058b9666dSZaara Syeda             if (!checkIsIndPhi(IndPhi, L, SE, ID))
1321dbf6ab5eSZaara Syeda               continue;
1322dbf6ab5eSZaara Syeda             // This is an induction PHI. Check that the only users are PHI
1323dbf6ab5eSZaara Syeda             // nodes, and induction variable update binary operators.
1324dbf6ab5eSZaara Syeda             if (llvm::any_of(Inst->users(), [&](User *U) {
1325dbf6ab5eSZaara Syeda                   if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
1326dbf6ab5eSZaara Syeda                     return true;
1327dbf6ab5eSZaara Syeda                   BinaryOperator *B = dyn_cast<BinaryOperator>(U);
1328dbf6ab5eSZaara Syeda                   if (B && B != ID.getInductionBinOp())
1329dbf6ab5eSZaara Syeda                     return true;
1330dbf6ab5eSZaara Syeda                   return false;
1331dbf6ab5eSZaara Syeda                 }))
1332dbf6ab5eSZaara Syeda               continue;
1333dbf6ab5eSZaara Syeda           } else {
1334dbf6ab5eSZaara Syeda             // If it is not an induction phi, it must be an induction update
1335dbf6ab5eSZaara Syeda             // binary operator with an induction phi user.
1336dbf6ab5eSZaara Syeda             BinaryOperator *B = dyn_cast<BinaryOperator>(Inst);
1337dbf6ab5eSZaara Syeda             if (!B)
1338dbf6ab5eSZaara Syeda               continue;
1339dbf6ab5eSZaara Syeda             if (llvm::any_of(Inst->users(), [&](User *U) {
1340dbf6ab5eSZaara Syeda                   PHINode *Phi = dyn_cast<PHINode>(U);
134158b9666dSZaara Syeda                   if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
1342dbf6ab5eSZaara Syeda                     return true;
1343dbf6ab5eSZaara Syeda                   return false;
1344dbf6ab5eSZaara Syeda                 }))
1345dbf6ab5eSZaara Syeda               continue;
1346dbf6ab5eSZaara Syeda             if (B != ID.getInductionBinOp())
1347dbf6ab5eSZaara Syeda               continue;
1348dbf6ab5eSZaara Syeda           }
1349dbf6ab5eSZaara Syeda         }
1350dbf6ab5eSZaara Syeda 
135193175a5cSSjoerd Meijer         // Okay, this instruction has a user outside of the current loop
135293175a5cSSjoerd Meijer         // and varies predictably *inside* the loop.  Evaluate the value it
135393175a5cSSjoerd Meijer         // contains when the loop exits, if possible.  We prefer to start with
135493175a5cSSjoerd Meijer         // expressions which are true for all exits (so as to maximize
135593175a5cSSjoerd Meijer         // expression reuse by the SCEVExpander), but resort to per-exit
135693175a5cSSjoerd Meijer         // evaluation if that fails.
135793175a5cSSjoerd Meijer         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
135893175a5cSSjoerd Meijer         if (isa<SCEVCouldNotCompute>(ExitValue) ||
135993175a5cSSjoerd Meijer             !SE->isLoopInvariant(ExitValue, L) ||
1360dcf4b733SNikita Popov             !Rewriter.isSafeToExpand(ExitValue)) {
136193175a5cSSjoerd Meijer           // TODO: This should probably be sunk into SCEV in some way; maybe a
136293175a5cSSjoerd Meijer           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
136393175a5cSSjoerd Meijer           // most SCEV expressions and other recurrence types (e.g. shift
136493175a5cSSjoerd Meijer           // recurrences).  Is there existing code we can reuse?
136593175a5cSSjoerd Meijer           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
136693175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitCount))
136793175a5cSSjoerd Meijer             continue;
136893175a5cSSjoerd Meijer           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
136993175a5cSSjoerd Meijer             if (AddRec->getLoop() == L)
137093175a5cSSjoerd Meijer               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
137193175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitValue) ||
137293175a5cSSjoerd Meijer               !SE->isLoopInvariant(ExitValue, L) ||
1373dcf4b733SNikita Popov               !Rewriter.isSafeToExpand(ExitValue))
137493175a5cSSjoerd Meijer             continue;
137593175a5cSSjoerd Meijer         }
137693175a5cSSjoerd Meijer 
137793175a5cSSjoerd Meijer         // Computing the value outside of the loop brings no benefit if it is
137893175a5cSSjoerd Meijer         // definitely used inside the loop in a way which can not be optimized
13797d572ef2SRoman Lebedev         // away. Avoid doing so unless we know we have a value which computes
13807d572ef2SRoman Lebedev         // the ExitValue already. TODO: This should be merged into SCEV
13817d572ef2SRoman Lebedev         // expander to leverage its knowledge of existing expressions.
13827d572ef2SRoman Lebedev         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
13837d572ef2SRoman Lebedev             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
138493175a5cSSjoerd Meijer           continue;
138593175a5cSSjoerd Meijer 
1386b2df9612SRoman Lebedev         // Check if expansions of this SCEV would count as being high cost.
13877d572ef2SRoman Lebedev         bool HighCost = Rewriter.isHighCostExpansion(
13887d572ef2SRoman Lebedev             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1389b2df9612SRoman Lebedev 
1390b2df9612SRoman Lebedev         // Note that we must not perform expansions until after
1391b2df9612SRoman Lebedev         // we query *all* the costs, because if we perform temporary expansion
1392b2df9612SRoman Lebedev         // inbetween, one that we might not intend to keep, said expansion
1393b2df9612SRoman Lebedev         // *may* affect cost calculation of the the next SCEV's we'll query,
1394b2df9612SRoman Lebedev         // and next SCEV may errneously get smaller cost.
1395b2df9612SRoman Lebedev 
1396b2df9612SRoman Lebedev         // Collect all the candidate PHINodes to be rewritten.
1397*be166916SPhilip Reames         Instruction *InsertPt =
1398*be166916SPhilip Reames           (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ?
1399*be166916SPhilip Reames           &*Inst->getParent()->getFirstInsertionPt() : Inst;
1400*be166916SPhilip Reames         RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost);
1401b2df9612SRoman Lebedev       }
1402b2df9612SRoman Lebedev     }
1403b2df9612SRoman Lebedev   }
1404b2df9612SRoman Lebedev 
1405795d142dSRoman Lebedev   // TODO: evaluate whether it is beneficial to change how we calculate
1406795d142dSRoman Lebedev   // high-cost: if we have SCEV 'A' which we know we will expand, should we
1407795d142dSRoman Lebedev   // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1408795d142dSRoman Lebedev   // potentially giving cost bonus to those other SCEV's?
140993175a5cSSjoerd Meijer 
141093175a5cSSjoerd Meijer   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
141193175a5cSSjoerd Meijer   int NumReplaced = 0;
141293175a5cSSjoerd Meijer 
141393175a5cSSjoerd Meijer   // Transformation.
141493175a5cSSjoerd Meijer   for (const RewritePhi &Phi : RewritePhiSet) {
141593175a5cSSjoerd Meijer     PHINode *PN = Phi.PN;
141693175a5cSSjoerd Meijer 
141793175a5cSSjoerd Meijer     // Only do the rewrite when the ExitValue can be expanded cheaply.
141893175a5cSSjoerd Meijer     // If LoopCanBeDel is true, rewrite exit value aggressively.
1419dbf6ab5eSZaara Syeda     if ((ReplaceExitValue == OnlyCheapRepl ||
1420dbf6ab5eSZaara Syeda          ReplaceExitValue == UnusedIndVarInLoop) &&
1421dbf6ab5eSZaara Syeda         !LoopCanBeDel && Phi.HighCost)
142293175a5cSSjoerd Meijer       continue;
1423795d142dSRoman Lebedev 
1424795d142dSRoman Lebedev     Value *ExitVal = Rewriter.expandCodeFor(
1425795d142dSRoman Lebedev         Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
1426795d142dSRoman Lebedev 
1427795d142dSRoman Lebedev     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1428795d142dSRoman Lebedev                       << '\n'
1429795d142dSRoman Lebedev                       << "  LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1430795d142dSRoman Lebedev 
1431795d142dSRoman Lebedev #ifndef NDEBUG
1432795d142dSRoman Lebedev     // If we reuse an instruction from a loop which is neither L nor one of
1433795d142dSRoman Lebedev     // its containing loops, we end up breaking LCSSA form for this loop by
1434795d142dSRoman Lebedev     // creating a new use of its instruction.
1435795d142dSRoman Lebedev     if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1436795d142dSRoman Lebedev       if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1437795d142dSRoman Lebedev         if (EVL != L)
1438795d142dSRoman Lebedev           assert(EVL->contains(L) && "LCSSA breach detected!");
1439795d142dSRoman Lebedev #endif
144093175a5cSSjoerd Meijer 
144193175a5cSSjoerd Meijer     NumReplaced++;
144293175a5cSSjoerd Meijer     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
144393175a5cSSjoerd Meijer     PN->setIncomingValue(Phi.Ith, ExitVal);
14448977bd58SFlorian Hahn     // It's necessary to tell ScalarEvolution about this explicitly so that
14458977bd58SFlorian Hahn     // it can walk the def-use list and forget all SCEVs, as it may not be
14468977bd58SFlorian Hahn     // watching the PHI itself. Once the new exit value is in place, there
14478977bd58SFlorian Hahn     // may not be a def-use connection between the loop and every instruction
14488977bd58SFlorian Hahn     // which got a SCEVAddRecExpr for that loop.
14498977bd58SFlorian Hahn     SE->forgetValue(PN);
145093175a5cSSjoerd Meijer 
145193175a5cSSjoerd Meijer     // If this instruction is dead now, delete it. Don't do it now to avoid
145293175a5cSSjoerd Meijer     // invalidating iterators.
145393175a5cSSjoerd Meijer     if (isInstructionTriviallyDead(Inst, TLI))
145493175a5cSSjoerd Meijer       DeadInsts.push_back(Inst);
145593175a5cSSjoerd Meijer 
145693175a5cSSjoerd Meijer     // Replace PN with ExitVal if that is legal and does not break LCSSA.
145793175a5cSSjoerd Meijer     if (PN->getNumIncomingValues() == 1 &&
145893175a5cSSjoerd Meijer         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
145993175a5cSSjoerd Meijer       PN->replaceAllUsesWith(ExitVal);
146093175a5cSSjoerd Meijer       PN->eraseFromParent();
146193175a5cSSjoerd Meijer     }
146293175a5cSSjoerd Meijer   }
146393175a5cSSjoerd Meijer 
146493175a5cSSjoerd Meijer   // The insertion point instruction may have been deleted; clear it out
146593175a5cSSjoerd Meijer   // so that the rewriter doesn't trip over it later.
146693175a5cSSjoerd Meijer   Rewriter.clearInsertPoint();
146793175a5cSSjoerd Meijer   return NumReplaced;
146893175a5cSSjoerd Meijer }
1469af7e1588SEvgeniy Brevnov 
1470af7e1588SEvgeniy Brevnov /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1471af7e1588SEvgeniy Brevnov /// \p OrigLoop.
setProfileInfoAfterUnrolling(Loop * OrigLoop,Loop * UnrolledLoop,Loop * RemainderLoop,uint64_t UF)1472af7e1588SEvgeniy Brevnov void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1473af7e1588SEvgeniy Brevnov                                         Loop *RemainderLoop, uint64_t UF) {
1474af7e1588SEvgeniy Brevnov   assert(UF > 0 && "Zero unrolled factor is not supported");
1475af7e1588SEvgeniy Brevnov   assert(UnrolledLoop != RemainderLoop &&
1476af7e1588SEvgeniy Brevnov          "Unrolled and Remainder loops are expected to distinct");
1477af7e1588SEvgeniy Brevnov 
1478af7e1588SEvgeniy Brevnov   // Get number of iterations in the original scalar loop.
1479af7e1588SEvgeniy Brevnov   unsigned OrigLoopInvocationWeight = 0;
1480af7e1588SEvgeniy Brevnov   Optional<unsigned> OrigAverageTripCount =
1481af7e1588SEvgeniy Brevnov       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1482af7e1588SEvgeniy Brevnov   if (!OrigAverageTripCount)
1483af7e1588SEvgeniy Brevnov     return;
1484af7e1588SEvgeniy Brevnov 
1485af7e1588SEvgeniy Brevnov   // Calculate number of iterations in unrolled loop.
1486af7e1588SEvgeniy Brevnov   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1487af7e1588SEvgeniy Brevnov   // Calculate number of iterations for remainder loop.
1488af7e1588SEvgeniy Brevnov   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1489af7e1588SEvgeniy Brevnov 
1490af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1491af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1492af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1493af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1494af7e1588SEvgeniy Brevnov }
1495388de9dfSAlina Sbirlea 
1496388de9dfSAlina Sbirlea /// Utility that implements appending of loops onto a worklist.
1497388de9dfSAlina Sbirlea /// Loops are added in preorder (analogous for reverse postorder for trees),
1498388de9dfSAlina Sbirlea /// and the worklist is processed LIFO.
1499388de9dfSAlina Sbirlea template <typename RangeT>
appendReversedLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1500388de9dfSAlina Sbirlea void llvm::appendReversedLoopsToWorklist(
1501388de9dfSAlina Sbirlea     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1502388de9dfSAlina Sbirlea   // We use an internal worklist to build up the preorder traversal without
1503388de9dfSAlina Sbirlea   // recursion.
1504388de9dfSAlina Sbirlea   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1505388de9dfSAlina Sbirlea 
1506388de9dfSAlina Sbirlea   // We walk the initial sequence of loops in reverse because we generally want
1507388de9dfSAlina Sbirlea   // to visit defs before uses and the worklist is LIFO.
1508388de9dfSAlina Sbirlea   for (Loop *RootL : Loops) {
1509388de9dfSAlina Sbirlea     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1510388de9dfSAlina Sbirlea     assert(PreOrderWorklist.empty() &&
1511388de9dfSAlina Sbirlea            "Must start with an empty preorder walk worklist.");
1512388de9dfSAlina Sbirlea     PreOrderWorklist.push_back(RootL);
1513388de9dfSAlina Sbirlea     do {
1514388de9dfSAlina Sbirlea       Loop *L = PreOrderWorklist.pop_back_val();
1515388de9dfSAlina Sbirlea       PreOrderWorklist.append(L->begin(), L->end());
1516388de9dfSAlina Sbirlea       PreOrderLoops.push_back(L);
1517388de9dfSAlina Sbirlea     } while (!PreOrderWorklist.empty());
1518388de9dfSAlina Sbirlea 
1519388de9dfSAlina Sbirlea     Worklist.insert(std::move(PreOrderLoops));
1520388de9dfSAlina Sbirlea     PreOrderLoops.clear();
1521388de9dfSAlina Sbirlea   }
1522388de9dfSAlina Sbirlea }
1523388de9dfSAlina Sbirlea 
1524388de9dfSAlina Sbirlea template <typename RangeT>
appendLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1525388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(RangeT &&Loops,
1526388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1527388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1528388de9dfSAlina Sbirlea }
1529388de9dfSAlina Sbirlea 
1530388de9dfSAlina Sbirlea template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1531388de9dfSAlina Sbirlea     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1532388de9dfSAlina Sbirlea 
153367904db2SAlina Sbirlea template void
153467904db2SAlina Sbirlea llvm::appendLoopsToWorklist<Loop &>(Loop &L,
153567904db2SAlina Sbirlea                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
153667904db2SAlina Sbirlea 
appendLoopsToWorklist(LoopInfo & LI,SmallPriorityWorklist<Loop *,4> & Worklist)1537388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(LoopInfo &LI,
1538388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1539388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(LI, Worklist);
1540388de9dfSAlina Sbirlea }
15413dcaf296SArkady Shlykov 
cloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)15423dcaf296SArkady Shlykov Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
15433dcaf296SArkady Shlykov                       LoopInfo *LI, LPPassManager *LPM) {
15443dcaf296SArkady Shlykov   Loop &New = *LI->AllocateLoop();
15453dcaf296SArkady Shlykov   if (PL)
15463dcaf296SArkady Shlykov     PL->addChildLoop(&New);
15473dcaf296SArkady Shlykov   else
15483dcaf296SArkady Shlykov     LI->addTopLevelLoop(&New);
15493dcaf296SArkady Shlykov 
15503dcaf296SArkady Shlykov   if (LPM)
15513dcaf296SArkady Shlykov     LPM->addLoop(New);
15523dcaf296SArkady Shlykov 
15533dcaf296SArkady Shlykov   // Add all of the blocks in L to the new loop.
1554d1abf481SKazu Hirata   for (BasicBlock *BB : L->blocks())
1555d1abf481SKazu Hirata     if (LI->getLoopFor(BB) == L)
1556d1abf481SKazu Hirata       New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
15573dcaf296SArkady Shlykov 
15583dcaf296SArkady Shlykov   // Add all of the subloops to the new loop.
15593dcaf296SArkady Shlykov   for (Loop *I : *L)
15603dcaf296SArkady Shlykov     cloneLoop(I, &New, VM, LI, LPM);
15613dcaf296SArkady Shlykov 
15623dcaf296SArkady Shlykov   return &New;
15633dcaf296SArkady Shlykov }
15648528186bSFlorian Hahn 
15658528186bSFlorian Hahn /// IR Values for the lower and upper bounds of a pointer evolution.  We
15668528186bSFlorian Hahn /// need to use value-handles because SCEV expansion can invalidate previously
15678528186bSFlorian Hahn /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
15688528186bSFlorian Hahn /// a previous one.
15698528186bSFlorian Hahn struct PointerBounds {
15708528186bSFlorian Hahn   TrackingVH<Value> Start;
15718528186bSFlorian Hahn   TrackingVH<Value> End;
15728528186bSFlorian Hahn };
15738528186bSFlorian Hahn 
15748528186bSFlorian Hahn /// Expand code for the lower and upper bound of the pointer group \p CG
15758528186bSFlorian Hahn /// in \p TheLoop.  \return the values for the bounds.
expandBounds(const RuntimeCheckingPtrGroup * CG,Loop * TheLoop,Instruction * Loc,SCEVExpander & Exp)15768528186bSFlorian Hahn static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
15778528186bSFlorian Hahn                                   Loop *TheLoop, Instruction *Loc,
157828410d17SFlorian Hahn                                   SCEVExpander &Exp) {
15798528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
15806d753b07SFlorian Hahn   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, CG->AddressSpace);
15818528186bSFlorian Hahn 
15828528186bSFlorian Hahn   Value *Start = nullptr, *End = nullptr;
15838528186bSFlorian Hahn   LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
15848528186bSFlorian Hahn   Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
15858528186bSFlorian Hahn   End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1586e9cced27SFlorian Hahn   if (CG->NeedsFreeze) {
1587e9cced27SFlorian Hahn     IRBuilder<> Builder(Loc);
1588e9cced27SFlorian Hahn     Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
1589e9cced27SFlorian Hahn     End = Builder.CreateFreeze(End, End->getName() + ".fr");
1590e9cced27SFlorian Hahn   }
1591e908e063SMindong Chen   LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
15928528186bSFlorian Hahn   return {Start, End};
15938528186bSFlorian Hahn }
15948528186bSFlorian Hahn 
15958528186bSFlorian Hahn /// Turns a collection of checks into a collection of expanded upper and
15968528186bSFlorian Hahn /// lower bounds for both pointers in the check.
15978528186bSFlorian Hahn static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
expandBounds(const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,Loop * L,Instruction * Loc,SCEVExpander & Exp)15988528186bSFlorian Hahn expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
159928410d17SFlorian Hahn              Instruction *Loc, SCEVExpander &Exp) {
16008528186bSFlorian Hahn   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
16018528186bSFlorian Hahn 
16028528186bSFlorian Hahn   // Here we're relying on the SCEV Expander's cache to only emit code for the
16038528186bSFlorian Hahn   // same bounds once.
16048528186bSFlorian Hahn   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
16058528186bSFlorian Hahn             [&](const RuntimePointerCheck &Check) {
160628410d17SFlorian Hahn               PointerBounds First = expandBounds(Check.first, L, Loc, Exp),
160728410d17SFlorian Hahn                             Second = expandBounds(Check.second, L, Loc, Exp);
16088528186bSFlorian Hahn               return std::make_pair(First, Second);
16098528186bSFlorian Hahn             });
16108528186bSFlorian Hahn 
16118528186bSFlorian Hahn   return ChecksWithBounds;
16128528186bSFlorian Hahn }
16138528186bSFlorian Hahn 
addRuntimeChecks(Instruction * Loc,Loop * TheLoop,const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,SCEVExpander & Exp)1614e844f053SFlorian Hahn Value *llvm::addRuntimeChecks(
16158528186bSFlorian Hahn     Instruction *Loc, Loop *TheLoop,
16168528186bSFlorian Hahn     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
161728410d17SFlorian Hahn     SCEVExpander &Exp) {
16188528186bSFlorian Hahn   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
16198528186bSFlorian Hahn   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
162028410d17SFlorian Hahn   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, Exp);
16218528186bSFlorian Hahn 
16228528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
1623e00158edSFlorian Hahn   IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1624e00158edSFlorian Hahn                                            Loc->getModule()->getDataLayout());
1625e00158edSFlorian Hahn   ChkBuilder.SetInsertPoint(Loc);
16268528186bSFlorian Hahn   // Our instructions might fold to a constant.
16278528186bSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
16288528186bSFlorian Hahn 
16298528186bSFlorian Hahn   for (const auto &Check : ExpandedChecks) {
16308528186bSFlorian Hahn     const PointerBounds &A = Check.first, &B = Check.second;
16318528186bSFlorian Hahn     // Check if two pointers (A and B) conflict where conflict is computed as:
16328528186bSFlorian Hahn     // start(A) <= end(B) && start(B) <= end(A)
16338528186bSFlorian Hahn     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
16348528186bSFlorian Hahn     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
16358528186bSFlorian Hahn 
16368528186bSFlorian Hahn     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
16378528186bSFlorian Hahn            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
16388528186bSFlorian Hahn            "Trying to bounds check pointers with different address spaces");
16398528186bSFlorian Hahn 
16408528186bSFlorian Hahn     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
16418528186bSFlorian Hahn     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
16428528186bSFlorian Hahn 
16438528186bSFlorian Hahn     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
16448528186bSFlorian Hahn     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
16458528186bSFlorian Hahn     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
16468528186bSFlorian Hahn     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
16478528186bSFlorian Hahn 
16488528186bSFlorian Hahn     // [A|B].Start points to the first accessed byte under base [A|B].
16498528186bSFlorian Hahn     // [A|B].End points to the last accessed byte, plus one.
16508528186bSFlorian Hahn     // There is no conflict when the intervals are disjoint:
16518528186bSFlorian Hahn     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
16528528186bSFlorian Hahn     //
16538528186bSFlorian Hahn     // bound0 = (B.Start < A.End)
16548528186bSFlorian Hahn     // bound1 = (A.Start < B.End)
16558528186bSFlorian Hahn     //  IsConflict = bound0 & bound1
16568528186bSFlorian Hahn     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
16578528186bSFlorian Hahn     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
16588528186bSFlorian Hahn     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16598528186bSFlorian Hahn     if (MemoryRuntimeCheck) {
16608528186bSFlorian Hahn       IsConflict =
16618528186bSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
16628528186bSFlorian Hahn     }
16638528186bSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
16648528186bSFlorian Hahn   }
16658528186bSFlorian Hahn 
1666e844f053SFlorian Hahn   return MemoryRuntimeCheck;
16678528186bSFlorian Hahn }
1668cfe87d4eSJingu Kang 
addDiffRuntimeChecks(Instruction * Loc,Loop * TheLoop,ArrayRef<PointerDiffInfo> Checks,SCEVExpander & Expander,function_ref<Value * (IRBuilderBase &,unsigned)> GetVF,unsigned IC)1669b7315ffcSFlorian Hahn Value *llvm::addDiffRuntimeChecks(
1670b7315ffcSFlorian Hahn     Instruction *Loc, Loop *TheLoop, ArrayRef<PointerDiffInfo> Checks,
1671b7315ffcSFlorian Hahn     SCEVExpander &Expander,
1672b7315ffcSFlorian Hahn     function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
1673b7315ffcSFlorian Hahn 
1674b7315ffcSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
1675b7315ffcSFlorian Hahn   IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1676b7315ffcSFlorian Hahn                                            Loc->getModule()->getDataLayout());
1677b7315ffcSFlorian Hahn   ChkBuilder.SetInsertPoint(Loc);
1678b7315ffcSFlorian Hahn   // Our instructions might fold to a constant.
1679b7315ffcSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
1680b7315ffcSFlorian Hahn 
1681b7315ffcSFlorian Hahn   for (auto &C : Checks) {
1682b7315ffcSFlorian Hahn     Type *Ty = C.SinkStart->getType();
1683b7315ffcSFlorian Hahn     // Compute VF * IC * AccessSize.
1684b7315ffcSFlorian Hahn     auto *VFTimesUFTimesSize =
1685b7315ffcSFlorian Hahn         ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
1686b7315ffcSFlorian Hahn                              ConstantInt::get(Ty, IC * C.AccessSize));
1687b7315ffcSFlorian Hahn     Value *Sink = Expander.expandCodeFor(C.SinkStart, Ty, Loc);
1688b7315ffcSFlorian Hahn     Value *Src = Expander.expandCodeFor(C.SrcStart, Ty, Loc);
1689e9cced27SFlorian Hahn     if (C.NeedsFreeze) {
1690e9cced27SFlorian Hahn       IRBuilder<> Builder(Loc);
1691e9cced27SFlorian Hahn       Sink = Builder.CreateFreeze(Sink, Sink->getName() + ".fr");
1692e9cced27SFlorian Hahn       Src = Builder.CreateFreeze(Src, Src->getName() + ".fr");
1693e9cced27SFlorian Hahn     }
1694b7315ffcSFlorian Hahn     Value *Diff = ChkBuilder.CreateSub(Sink, Src);
1695b7315ffcSFlorian Hahn     Value *IsConflict =
1696b7315ffcSFlorian Hahn         ChkBuilder.CreateICmpULT(Diff, VFTimesUFTimesSize, "diff.check");
1697b7315ffcSFlorian Hahn 
1698b7315ffcSFlorian Hahn     if (MemoryRuntimeCheck) {
1699b7315ffcSFlorian Hahn       IsConflict =
1700b7315ffcSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1701b7315ffcSFlorian Hahn     }
1702b7315ffcSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
1703b7315ffcSFlorian Hahn   }
1704b7315ffcSFlorian Hahn 
1705b7315ffcSFlorian Hahn   return MemoryRuntimeCheck;
1706b7315ffcSFlorian Hahn }
1707b7315ffcSFlorian Hahn 
hasPartialIVCondition(Loop & L,unsigned MSSAThreshold,MemorySSA & MSSA,AAResults & AA)1708e4abb641SJingu Kang Optional<IVConditionInfo> llvm::hasPartialIVCondition(Loop &L,
1709cfe87d4eSJingu Kang                                                       unsigned MSSAThreshold,
1710e4abb641SJingu Kang                                                       MemorySSA &MSSA,
1711e4abb641SJingu Kang                                                       AAResults &AA) {
1712e4abb641SJingu Kang   auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
1713cfe87d4eSJingu Kang   if (!TI || !TI->isConditional())
1714cfe87d4eSJingu Kang     return {};
1715cfe87d4eSJingu Kang 
1716cfe87d4eSJingu Kang   auto *CondI = dyn_cast<CmpInst>(TI->getCondition());
1717cfe87d4eSJingu Kang   // The case with the condition outside the loop should already be handled
1718cfe87d4eSJingu Kang   // earlier.
1719e4abb641SJingu Kang   if (!CondI || !L.contains(CondI))
1720cfe87d4eSJingu Kang     return {};
1721cfe87d4eSJingu Kang 
1722cfe87d4eSJingu Kang   SmallVector<Instruction *> InstToDuplicate;
1723cfe87d4eSJingu Kang   InstToDuplicate.push_back(CondI);
1724cfe87d4eSJingu Kang 
1725cfe87d4eSJingu Kang   SmallVector<Value *, 4> WorkList;
1726cfe87d4eSJingu Kang   WorkList.append(CondI->op_begin(), CondI->op_end());
1727cfe87d4eSJingu Kang 
1728cfe87d4eSJingu Kang   SmallVector<MemoryAccess *, 4> AccessesToCheck;
1729cfe87d4eSJingu Kang   SmallVector<MemoryLocation, 4> AccessedLocs;
1730cfe87d4eSJingu Kang   while (!WorkList.empty()) {
1731cfe87d4eSJingu Kang     Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
1732e4abb641SJingu Kang     if (!I || !L.contains(I))
1733cfe87d4eSJingu Kang       continue;
1734cfe87d4eSJingu Kang 
1735cfe87d4eSJingu Kang     // TODO: support additional instructions.
1736cfe87d4eSJingu Kang     if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
1737cfe87d4eSJingu Kang       return {};
1738cfe87d4eSJingu Kang 
1739cfe87d4eSJingu Kang     // Do not duplicate volatile and atomic loads.
1740cfe87d4eSJingu Kang     if (auto *LI = dyn_cast<LoadInst>(I))
1741cfe87d4eSJingu Kang       if (LI->isVolatile() || LI->isAtomic())
1742cfe87d4eSJingu Kang         return {};
1743cfe87d4eSJingu Kang 
1744cfe87d4eSJingu Kang     InstToDuplicate.push_back(I);
1745e4abb641SJingu Kang     if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
1746cfe87d4eSJingu Kang       if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
1747cfe87d4eSJingu Kang         // Queue the defining access to check for alias checks.
1748cfe87d4eSJingu Kang         AccessesToCheck.push_back(MemUse->getDefiningAccess());
1749cfe87d4eSJingu Kang         AccessedLocs.push_back(MemoryLocation::get(I));
1750cfe87d4eSJingu Kang       } else {
1751cfe87d4eSJingu Kang         // MemoryDefs may clobber the location or may be atomic memory
1752cfe87d4eSJingu Kang         // operations. Bail out.
1753cfe87d4eSJingu Kang         return {};
1754cfe87d4eSJingu Kang       }
1755cfe87d4eSJingu Kang     }
1756cfe87d4eSJingu Kang     WorkList.append(I->op_begin(), I->op_end());
1757cfe87d4eSJingu Kang   }
1758cfe87d4eSJingu Kang 
1759cfe87d4eSJingu Kang   if (InstToDuplicate.empty())
1760cfe87d4eSJingu Kang     return {};
1761cfe87d4eSJingu Kang 
1762cfe87d4eSJingu Kang   SmallVector<BasicBlock *, 4> ExitingBlocks;
1763e4abb641SJingu Kang   L.getExitingBlocks(ExitingBlocks);
1764cfe87d4eSJingu Kang   auto HasNoClobbersOnPath =
1765e4abb641SJingu Kang       [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
1766cfe87d4eSJingu Kang        MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
1767cfe87d4eSJingu Kang                       SmallVector<MemoryAccess *, 4> AccessesToCheck)
1768cfe87d4eSJingu Kang       -> Optional<IVConditionInfo> {
1769cfe87d4eSJingu Kang     IVConditionInfo Info;
1770cfe87d4eSJingu Kang     // First, collect all blocks in the loop that are on a patch from Succ
1771cfe87d4eSJingu Kang     // to the header.
1772cfe87d4eSJingu Kang     SmallVector<BasicBlock *, 4> WorkList;
1773cfe87d4eSJingu Kang     WorkList.push_back(Succ);
1774cfe87d4eSJingu Kang     WorkList.push_back(Header);
1775cfe87d4eSJingu Kang     SmallPtrSet<BasicBlock *, 4> Seen;
1776cfe87d4eSJingu Kang     Seen.insert(Header);
1777cfe87d4eSJingu Kang     Info.PathIsNoop &=
1778cfe87d4eSJingu Kang         all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1779cfe87d4eSJingu Kang 
1780cfe87d4eSJingu Kang     while (!WorkList.empty()) {
1781cfe87d4eSJingu Kang       BasicBlock *Current = WorkList.pop_back_val();
1782e4abb641SJingu Kang       if (!L.contains(Current))
1783cfe87d4eSJingu Kang         continue;
1784cfe87d4eSJingu Kang       const auto &SeenIns = Seen.insert(Current);
1785cfe87d4eSJingu Kang       if (!SeenIns.second)
1786cfe87d4eSJingu Kang         continue;
1787cfe87d4eSJingu Kang 
1788cfe87d4eSJingu Kang       Info.PathIsNoop &= all_of(
1789cfe87d4eSJingu Kang           *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1790cfe87d4eSJingu Kang       WorkList.append(succ_begin(Current), succ_end(Current));
1791cfe87d4eSJingu Kang     }
1792cfe87d4eSJingu Kang 
1793cfe87d4eSJingu Kang     // Require at least 2 blocks on a path through the loop. This skips
1794cfe87d4eSJingu Kang     // paths that directly exit the loop.
1795cfe87d4eSJingu Kang     if (Seen.size() < 2)
1796cfe87d4eSJingu Kang       return {};
1797cfe87d4eSJingu Kang 
1798cfe87d4eSJingu Kang     // Next, check if there are any MemoryDefs that are on the path through
1799cfe87d4eSJingu Kang     // the loop (in the Seen set) and they may-alias any of the locations in
1800cfe87d4eSJingu Kang     // AccessedLocs. If that is the case, they may modify the condition and
1801cfe87d4eSJingu Kang     // partial unswitching is not possible.
1802cfe87d4eSJingu Kang     SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
1803cfe87d4eSJingu Kang     while (!AccessesToCheck.empty()) {
1804cfe87d4eSJingu Kang       MemoryAccess *Current = AccessesToCheck.pop_back_val();
1805cfe87d4eSJingu Kang       auto SeenI = SeenAccesses.insert(Current);
1806cfe87d4eSJingu Kang       if (!SeenI.second || !Seen.contains(Current->getBlock()))
1807cfe87d4eSJingu Kang         continue;
1808cfe87d4eSJingu Kang 
1809cfe87d4eSJingu Kang       // Bail out if exceeded the threshold.
1810cfe87d4eSJingu Kang       if (SeenAccesses.size() >= MSSAThreshold)
1811cfe87d4eSJingu Kang         return {};
1812cfe87d4eSJingu Kang 
1813cfe87d4eSJingu Kang       // MemoryUse are read-only accesses.
1814cfe87d4eSJingu Kang       if (isa<MemoryUse>(Current))
1815cfe87d4eSJingu Kang         continue;
1816cfe87d4eSJingu Kang 
1817cfe87d4eSJingu Kang       // For a MemoryDef, check if is aliases any of the location feeding
1818cfe87d4eSJingu Kang       // the original condition.
1819cfe87d4eSJingu Kang       if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
1820e4abb641SJingu Kang         if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
1821cfe87d4eSJingu Kang               return isModSet(
1822e4abb641SJingu Kang                   AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
1823cfe87d4eSJingu Kang             }))
1824cfe87d4eSJingu Kang           return {};
1825cfe87d4eSJingu Kang       }
1826cfe87d4eSJingu Kang 
1827cfe87d4eSJingu Kang       for (Use &U : Current->uses())
1828cfe87d4eSJingu Kang         AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
1829cfe87d4eSJingu Kang     }
1830cfe87d4eSJingu Kang 
1831cfe87d4eSJingu Kang     // We could also allow loops with known trip counts without mustprogress,
1832cfe87d4eSJingu Kang     // but ScalarEvolution may not be available.
18337629b2a0SPhilip Reames     Info.PathIsNoop &= isMustProgress(&L);
1834cfe87d4eSJingu Kang 
1835cfe87d4eSJingu Kang     // If the path is considered a no-op so far, check if it reaches a
1836cfe87d4eSJingu Kang     // single exit block without any phis. This ensures no values from the
1837cfe87d4eSJingu Kang     // loop are used outside of the loop.
1838cfe87d4eSJingu Kang     if (Info.PathIsNoop) {
1839cfe87d4eSJingu Kang       for (auto *Exiting : ExitingBlocks) {
1840cfe87d4eSJingu Kang         if (!Seen.contains(Exiting))
1841cfe87d4eSJingu Kang           continue;
1842cfe87d4eSJingu Kang         for (auto *Succ : successors(Exiting)) {
1843e4abb641SJingu Kang           if (L.contains(Succ))
1844cfe87d4eSJingu Kang             continue;
1845cfe87d4eSJingu Kang 
1846cfe87d4eSJingu Kang           Info.PathIsNoop &= llvm::empty(Succ->phis()) &&
1847cfe87d4eSJingu Kang                              (!Info.ExitForPath || Info.ExitForPath == Succ);
1848cfe87d4eSJingu Kang           if (!Info.PathIsNoop)
1849cfe87d4eSJingu Kang             break;
1850cfe87d4eSJingu Kang           assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
1851cfe87d4eSJingu Kang                  "cannot have multiple exit blocks");
1852cfe87d4eSJingu Kang           Info.ExitForPath = Succ;
1853cfe87d4eSJingu Kang         }
1854cfe87d4eSJingu Kang       }
1855cfe87d4eSJingu Kang     }
1856cfe87d4eSJingu Kang     if (!Info.ExitForPath)
1857cfe87d4eSJingu Kang       Info.PathIsNoop = false;
1858cfe87d4eSJingu Kang 
1859cfe87d4eSJingu Kang     Info.InstToDuplicate = InstToDuplicate;
1860cfe87d4eSJingu Kang     return Info;
1861cfe87d4eSJingu Kang   };
1862cfe87d4eSJingu Kang 
1863cfe87d4eSJingu Kang   // If we branch to the same successor, partial unswitching will not be
1864cfe87d4eSJingu Kang   // beneficial.
1865cfe87d4eSJingu Kang   if (TI->getSuccessor(0) == TI->getSuccessor(1))
1866cfe87d4eSJingu Kang     return {};
1867cfe87d4eSJingu Kang 
1868e4abb641SJingu Kang   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
1869cfe87d4eSJingu Kang                                       AccessesToCheck)) {
1870cfe87d4eSJingu Kang     Info->KnownValue = ConstantInt::getTrue(TI->getContext());
1871cfe87d4eSJingu Kang     return Info;
1872cfe87d4eSJingu Kang   }
1873e4abb641SJingu Kang   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
1874cfe87d4eSJingu Kang                                       AccessesToCheck)) {
1875cfe87d4eSJingu Kang     Info->KnownValue = ConstantInt::getFalse(TI->getContext());
1876cfe87d4eSJingu Kang     return Info;
1877cfe87d4eSJingu Kang   }
1878cfe87d4eSJingu Kang 
1879cfe87d4eSJingu Kang   return {};
1880cfe87d4eSJingu Kang }
1881