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"
25a21d5f1eSPhilip Reames #include "llvm/Analysis/InstructionSimplify.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"
3123aed5efSPhilip Reames #include "llvm/Analysis/MustExecute.h"
3245d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
332f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3445d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
356bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
36a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h"
37744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h"
3831088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3976aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
40744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h"
41af7e1588SEvgeniy Brevnov #include "llvm/IR/MDBuilder.h"
4245d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
437a87e8f9SFlorian Hahn #include "llvm/IR/Operator.h"
4476aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
4576aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
4605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
4731088a9dSChandler Carruth #include "llvm/Pass.h"
4876aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
49a097bc69SChad Rosier #include "llvm/Support/KnownBits.h"
504a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
5193175a5cSSjoerd Meijer #include "llvm/Transforms/Utils/Local.h"
52bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
5376aa662cSKarthik Bhat 
5476aa662cSKarthik Bhat using namespace llvm;
5576aa662cSKarthik Bhat using namespace llvm::PatternMatch;
5676aa662cSKarthik Bhat 
57ec7e4a9aSDavid Green static cl::opt<bool> ForceReductionIntrinsic(
58ec7e4a9aSDavid Green     "force-reduction-intrinsics", cl::Hidden,
59ec7e4a9aSDavid Green     cl::desc("Force creating reduction intrinsics for testing."),
60ec7e4a9aSDavid Green     cl::init(false));
61ec7e4a9aSDavid Green 
6276aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
6376aa662cSKarthik Bhat 
6472448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
654f64f1baSTim Corringham static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
66f88a7975SAtmn Patel static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
6772448525SMichael Kruse 
684a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
6997468e92SAlina Sbirlea                                    MemorySSAUpdater *MSSAU,
704a000883SChandler Carruth                                    bool PreserveLCSSA) {
714a000883SChandler Carruth   bool Changed = false;
724a000883SChandler Carruth 
734a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
744a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
754a000883SChandler Carruth 
764a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
774a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
784a000883SChandler Carruth            "Must start with an empty predecessors list!");
794a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
804a000883SChandler Carruth 
814a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
824a000883SChandler Carruth     // keep track of the in-loop predecessors.
834a000883SChandler Carruth     bool IsDedicatedExit = true;
844a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
854a000883SChandler Carruth       if (L->contains(PredBB)) {
864a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
874a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
884a000883SChandler Carruth           return false;
89784929d0SCraig Topper         if (isa<CallBrInst>(PredBB->getTerminator()))
90784929d0SCraig Topper           // We cannot rewrite exiting edges from a callbr.
91784929d0SCraig Topper           return false;
924a000883SChandler Carruth 
934a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
944a000883SChandler Carruth       } else {
954a000883SChandler Carruth         IsDedicatedExit = false;
964a000883SChandler Carruth       }
974a000883SChandler Carruth 
984a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
994a000883SChandler Carruth 
1004a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
1014a000883SChandler Carruth     if (IsDedicatedExit)
1024a000883SChandler Carruth       return false;
1034a000883SChandler Carruth 
1044a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
10597468e92SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
1064a000883SChandler Carruth 
1074a000883SChandler Carruth     if (!NewExitBB)
108d34e60caSNicola Zaghen       LLVM_DEBUG(
109d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
1104a000883SChandler Carruth                  << *L << "\n");
1114a000883SChandler Carruth     else
112d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
1134a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
1144a000883SChandler Carruth     return true;
1154a000883SChandler Carruth   };
1164a000883SChandler Carruth 
1174a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
1184a000883SChandler Carruth   // them, but only visit each one once.
1194a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
1204a000883SChandler Carruth   for (auto *BB : L->blocks())
1214a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
1224a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1234a000883SChandler Carruth       if (L->contains(SuccBB))
1244a000883SChandler Carruth         continue;
1254a000883SChandler Carruth 
1264a000883SChandler Carruth       // Visit each exit block exactly once.
1274a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1284a000883SChandler Carruth         continue;
1294a000883SChandler Carruth 
1304a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1314a000883SChandler Carruth     }
1324a000883SChandler Carruth 
1334a000883SChandler Carruth   return Changed;
1344a000883SChandler Carruth }
1354a000883SChandler Carruth 
1365f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
137c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
138c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
139c5b7b555SAshutosh Nema 
140c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
141c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
142c5b7b555SAshutosh Nema     // be adapted into a pointer.
143c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
144c5b7b555SAshutosh Nema       auto Users = Inst.users();
1450a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
146c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
147c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
148c5b7b555SAshutosh Nema           }))
149c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
150c5b7b555SAshutosh Nema     }
151c5b7b555SAshutosh Nema 
152c5b7b555SAshutosh Nema   return UsedOutside;
153c5b7b555SAshutosh Nema }
15431088a9dSChandler Carruth 
15531088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
15631088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
15731088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
15831088a9dSChandler Carruth   // pass manager, they must also preserve these.
15931088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
16031088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
16131088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
16231088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
16331088a9dSChandler Carruth 
16431088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
16531088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
16631088a9dSChandler Carruth   extern char &LoopSimplifyID;
16731088a9dSChandler Carruth   extern char &LCSSAID;
16831088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
16931088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
17031088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
17131088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
172c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
173c3ccf5d7SIgor Laevsky   // which preserve lcssa form
174c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
175c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
17631088a9dSChandler Carruth 
17731088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
17831088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
17931088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
18031088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
18131088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
18231088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
18331088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
18431088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
18531088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
18631088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
18731088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
18831088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
18931088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
19031088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
1916da79ce1SAlina Sbirlea   // FIXME: When all loop passes preserve MemorySSA, it can be required and
1926da79ce1SAlina Sbirlea   // preserved here instead of the individual handling in each pass.
19331088a9dSChandler Carruth }
19431088a9dSChandler Carruth 
19531088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
19631088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
19731088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
19831088a9dSChandler Carruth /// with:
19931088a9dSChandler Carruth ///
20031088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
20131088a9dSChandler Carruth ///
20231088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
20331088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
20431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
20531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
20631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
207e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
20831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
20931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
21031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
21131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
21231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2136da79ce1SAlina Sbirlea   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
21431088a9dSChandler Carruth }
215963341c8SAdam Nemet 
2163c3a7652SSerguei Katkov /// Create MDNode for input string.
2173c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2183c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2193c3a7652SSerguei Katkov   Metadata *MDs[] = {
2203c3a7652SSerguei Katkov       MDString::get(Context, Name),
2213c3a7652SSerguei Katkov       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2223c3a7652SSerguei Katkov   return MDNode::get(Context, MDs);
2233c3a7652SSerguei Katkov }
2243c3a7652SSerguei Katkov 
2253c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact.
2267f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is
2277f8c8095SSerguei Katkov /// different.
2287f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2293c3a7652SSerguei Katkov                                    unsigned V) {
2303c3a7652SSerguei Katkov   SmallVector<Metadata *, 4> MDs(1);
2313c3a7652SSerguei Katkov   // If the loop already has metadata, retain it.
2323c3a7652SSerguei Katkov   MDNode *LoopID = TheLoop->getLoopID();
2333c3a7652SSerguei Katkov   if (LoopID) {
2343c3a7652SSerguei Katkov     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2353c3a7652SSerguei Katkov       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2367f8c8095SSerguei Katkov       // If it is of form key = value, try to parse it.
2377f8c8095SSerguei Katkov       if (Node->getNumOperands() == 2) {
2387f8c8095SSerguei Katkov         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
2397f8c8095SSerguei Katkov         if (S && S->getString().equals(StringMD)) {
2407f8c8095SSerguei Katkov           ConstantInt *IntMD =
2417f8c8095SSerguei Katkov               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2427f8c8095SSerguei Katkov           if (IntMD && IntMD->getSExtValue() == V)
2437f8c8095SSerguei Katkov             // It is already in place. Do nothing.
2447f8c8095SSerguei Katkov             return;
2457f8c8095SSerguei Katkov           // We need to update the value, so just skip it here and it will
2467f8c8095SSerguei Katkov           // be added after copying other existed nodes.
2477f8c8095SSerguei Katkov           continue;
2487f8c8095SSerguei Katkov         }
2497f8c8095SSerguei Katkov       }
2503c3a7652SSerguei Katkov       MDs.push_back(Node);
2513c3a7652SSerguei Katkov     }
2523c3a7652SSerguei Katkov   }
2533c3a7652SSerguei Katkov   // Add new metadata.
2547f8c8095SSerguei Katkov   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2553c3a7652SSerguei Katkov   // Replace current metadata node with new one.
2563c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2573c3a7652SSerguei Katkov   MDNode *NewLoopID = MDNode::get(Context, MDs);
2583c3a7652SSerguei Katkov   // Set operand 0 to refer to the loop id itself.
2593c3a7652SSerguei Katkov   NewLoopID->replaceOperandWith(0, NewLoopID);
2603c3a7652SSerguei Katkov   TheLoop->setLoopID(NewLoopID);
2613c3a7652SSerguei Katkov }
2623c3a7652SSerguei Katkov 
26372448525SMichael Kruse /// Find string metadata for loop
26472448525SMichael Kruse ///
26572448525SMichael Kruse /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
26672448525SMichael Kruse /// operand or null otherwise.  If the string metadata is not found return
26772448525SMichael Kruse /// Optional's not-a-value.
268978ba615SMichael Kruse Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
26972448525SMichael Kruse                                                             StringRef Name) {
270978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
27172448525SMichael Kruse   if (!MD)
27272448525SMichael Kruse     return None;
273fe3def7cSAdam Nemet   switch (MD->getNumOperands()) {
274fe3def7cSAdam Nemet   case 1:
275fe3def7cSAdam Nemet     return nullptr;
276fe3def7cSAdam Nemet   case 2:
277fe3def7cSAdam Nemet     return &MD->getOperand(1);
278fe3def7cSAdam Nemet   default:
279fe3def7cSAdam Nemet     llvm_unreachable("loop metadata has 0 or 1 operand");
280963341c8SAdam Nemet   }
281fe3def7cSAdam Nemet }
28272448525SMichael Kruse 
28372448525SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
28472448525SMichael Kruse                                                    StringRef Name) {
285978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
286978ba615SMichael Kruse   if (!MD)
287fe3def7cSAdam Nemet     return None;
288978ba615SMichael Kruse   switch (MD->getNumOperands()) {
28972448525SMichael Kruse   case 1:
29072448525SMichael Kruse     // When the value is absent it is interpreted as 'attribute set'.
29172448525SMichael Kruse     return true;
29272448525SMichael Kruse   case 2:
293f9027e55SAlina Sbirlea     if (ConstantInt *IntMD =
294f9027e55SAlina Sbirlea             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
295f9027e55SAlina Sbirlea       return IntMD->getZExtValue();
296f9027e55SAlina Sbirlea     return true;
29772448525SMichael Kruse   }
29872448525SMichael Kruse   llvm_unreachable("unexpected number of options");
29972448525SMichael Kruse }
30072448525SMichael Kruse 
301c7e27538SDavid Green bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
30272448525SMichael Kruse   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
30372448525SMichael Kruse }
30472448525SMichael Kruse 
30571bd59f0SDavid Sherwood Optional<ElementCount>
30671bd59f0SDavid Sherwood llvm::getOptionalElementCountLoopAttribute(Loop *TheLoop) {
30771bd59f0SDavid Sherwood   Optional<int> Width =
30871bd59f0SDavid Sherwood       getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
30971bd59f0SDavid Sherwood 
31071bd59f0SDavid Sherwood   if (Width.hasValue()) {
31171bd59f0SDavid Sherwood     Optional<int> IsScalable = getOptionalIntLoopAttribute(
31271bd59f0SDavid Sherwood         TheLoop, "llvm.loop.vectorize.scalable.enable");
31371bd59f0SDavid Sherwood     return ElementCount::get(*Width,
31471bd59f0SDavid Sherwood                              IsScalable.hasValue() ? *IsScalable : false);
31571bd59f0SDavid Sherwood   }
31671bd59f0SDavid Sherwood 
31771bd59f0SDavid Sherwood   return None;
31871bd59f0SDavid Sherwood }
31971bd59f0SDavid Sherwood 
32072448525SMichael Kruse llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
32172448525SMichael Kruse                                                       StringRef Name) {
32272448525SMichael Kruse   const MDOperand *AttrMD =
32372448525SMichael Kruse       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
32472448525SMichael Kruse   if (!AttrMD)
32572448525SMichael Kruse     return None;
32672448525SMichael Kruse 
32772448525SMichael Kruse   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
32872448525SMichael Kruse   if (!IntMD)
32972448525SMichael Kruse     return None;
33072448525SMichael Kruse 
33172448525SMichael Kruse   return IntMD->getSExtValue();
33272448525SMichael Kruse }
33372448525SMichael Kruse 
33472448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
33572448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
33672448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
33772448525SMichael Kruse   if (!OrigLoopID) {
33872448525SMichael Kruse     if (AlwaysNew)
33972448525SMichael Kruse       return nullptr;
34072448525SMichael Kruse     return None;
34172448525SMichael Kruse   }
34272448525SMichael Kruse 
34372448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
34472448525SMichael Kruse 
34572448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
34672448525SMichael Kruse   bool InheritSomeAttrs =
34772448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
34872448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
34972448525SMichael Kruse   MDs.push_back(nullptr);
35072448525SMichael Kruse 
35172448525SMichael Kruse   bool Changed = false;
35272448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
35372448525SMichael Kruse     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
35472448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
35572448525SMichael Kruse 
35672448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
35772448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
35872448525SMichael Kruse         if (!InheritSomeAttrs)
35972448525SMichael Kruse           return false;
36072448525SMichael Kruse 
36172448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
36272448525SMichael Kruse         if (Op->getNumOperands() == 0)
36372448525SMichael Kruse           return true;
36472448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
36572448525SMichael Kruse         if (!isa<MDString>(NameMD))
36672448525SMichael Kruse           return true;
36772448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
36872448525SMichael Kruse 
36972448525SMichael Kruse         // Do not inherit excluded attributes.
37072448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
37172448525SMichael Kruse       };
37272448525SMichael Kruse 
37372448525SMichael Kruse       if (InheritThisAttribute(Op))
37472448525SMichael Kruse         MDs.push_back(Op);
37572448525SMichael Kruse       else
37672448525SMichael Kruse         Changed = true;
37772448525SMichael Kruse     }
37872448525SMichael Kruse   } else {
37972448525SMichael Kruse     // Modified if we dropped at least one attribute.
38072448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
38172448525SMichael Kruse   }
38272448525SMichael Kruse 
38372448525SMichael Kruse   bool HasAnyFollowup = false;
38472448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
385978ba615SMichael Kruse     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
38672448525SMichael Kruse     if (!FollowupNode)
38772448525SMichael Kruse       continue;
38872448525SMichael Kruse 
38972448525SMichael Kruse     HasAnyFollowup = true;
39072448525SMichael Kruse     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
39172448525SMichael Kruse       MDs.push_back(Option.get());
39272448525SMichael Kruse       Changed = true;
39372448525SMichael Kruse     }
39472448525SMichael Kruse   }
39572448525SMichael Kruse 
39672448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
39772448525SMichael Kruse   // transformation pass to add suitable attributes.
39872448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
39972448525SMichael Kruse     return None;
40072448525SMichael Kruse 
40172448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
40272448525SMichael Kruse   if (!AlwaysNew && !Changed)
40372448525SMichael Kruse     return OrigLoopID;
40472448525SMichael Kruse 
40572448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
40672448525SMichael Kruse   if (MDs.size() == 1)
40772448525SMichael Kruse     return nullptr;
40872448525SMichael Kruse 
40972448525SMichael Kruse   // Build the new loop ID.
41072448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
41172448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
41272448525SMichael Kruse   return FollowupLoopID;
41372448525SMichael Kruse }
41472448525SMichael Kruse 
41572448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
41672448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
41772448525SMichael Kruse }
41872448525SMichael Kruse 
4194f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
4204f64f1baSTim Corringham   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
4214f64f1baSTim Corringham }
4224f64f1baSTim Corringham 
423f88a7975SAtmn Patel bool llvm::hasMustProgress(const Loop *L) {
424f88a7975SAtmn Patel   return getBooleanLoopAttribute(L, LLVMLoopMustProgress);
425f88a7975SAtmn Patel }
426f88a7975SAtmn Patel 
42772448525SMichael Kruse TransformationMode llvm::hasUnrollTransformation(Loop *L) {
42872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
42972448525SMichael Kruse     return TM_SuppressedByUser;
43072448525SMichael Kruse 
43172448525SMichael Kruse   Optional<int> Count =
43272448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
43372448525SMichael Kruse   if (Count.hasValue())
43472448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
43572448525SMichael Kruse 
43672448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
43772448525SMichael Kruse     return TM_ForcedByUser;
43872448525SMichael Kruse 
43972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
44072448525SMichael Kruse     return TM_ForcedByUser;
44172448525SMichael Kruse 
44272448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
44372448525SMichael Kruse     return TM_Disable;
44472448525SMichael Kruse 
44572448525SMichael Kruse   return TM_Unspecified;
44672448525SMichael Kruse }
44772448525SMichael Kruse 
44872448525SMichael Kruse TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
44972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
45072448525SMichael Kruse     return TM_SuppressedByUser;
45172448525SMichael Kruse 
45272448525SMichael Kruse   Optional<int> Count =
45372448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
45472448525SMichael Kruse   if (Count.hasValue())
45572448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
45672448525SMichael Kruse 
45772448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
45872448525SMichael Kruse     return TM_ForcedByUser;
45972448525SMichael Kruse 
46072448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
46172448525SMichael Kruse     return TM_Disable;
46272448525SMichael Kruse 
46372448525SMichael Kruse   return TM_Unspecified;
46472448525SMichael Kruse }
46572448525SMichael Kruse 
46672448525SMichael Kruse TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
46772448525SMichael Kruse   Optional<bool> Enable =
46872448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
46972448525SMichael Kruse 
47072448525SMichael Kruse   if (Enable == false)
47172448525SMichael Kruse     return TM_SuppressedByUser;
47272448525SMichael Kruse 
47371bd59f0SDavid Sherwood   Optional<ElementCount> VectorizeWidth =
47471bd59f0SDavid Sherwood       getOptionalElementCountLoopAttribute(L);
47572448525SMichael Kruse   Optional<int> InterleaveCount =
47672448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
47772448525SMichael Kruse 
47872448525SMichael Kruse   // 'Forcing' vector width and interleave count to one effectively disables
47972448525SMichael Kruse   // this tranformation.
48071bd59f0SDavid Sherwood   if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
48171bd59f0SDavid Sherwood       InterleaveCount == 1)
48272448525SMichael Kruse     return TM_SuppressedByUser;
48372448525SMichael Kruse 
48472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
48572448525SMichael Kruse     return TM_Disable;
48672448525SMichael Kruse 
48770560a0aSMichael Kruse   if (Enable == true)
48870560a0aSMichael Kruse     return TM_ForcedByUser;
48970560a0aSMichael Kruse 
49071bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
49172448525SMichael Kruse     return TM_Disable;
49272448525SMichael Kruse 
49371bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
49472448525SMichael Kruse     return TM_Enable;
49572448525SMichael Kruse 
49672448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
49772448525SMichael Kruse     return TM_Disable;
49872448525SMichael Kruse 
49972448525SMichael Kruse   return TM_Unspecified;
50072448525SMichael Kruse }
50172448525SMichael Kruse 
50272448525SMichael Kruse TransformationMode llvm::hasDistributeTransformation(Loop *L) {
50372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
50472448525SMichael Kruse     return TM_ForcedByUser;
50572448525SMichael Kruse 
50672448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
50772448525SMichael Kruse     return TM_Disable;
50872448525SMichael Kruse 
50972448525SMichael Kruse   return TM_Unspecified;
51072448525SMichael Kruse }
51172448525SMichael Kruse 
51272448525SMichael Kruse TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
51372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
51472448525SMichael Kruse     return TM_SuppressedByUser;
51572448525SMichael Kruse 
51672448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
51772448525SMichael Kruse     return TM_Disable;
51872448525SMichael Kruse 
51972448525SMichael Kruse   return TM_Unspecified;
520963341c8SAdam Nemet }
521122f984aSEvgeniy Stepanov 
5227ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
5237ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
5247ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
5257ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
5267ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
5277ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
5287ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
5297ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
5307ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
5317ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
5327ed5856aSAlina Sbirlea   };
5337ed5856aSAlina Sbirlea 
5347ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
5357ed5856aSAlina Sbirlea 
53676c5cb05SNicolai Hähnle   for (size_t I = 0; I < Worklist.size(); I++) {
53776c5cb05SNicolai Hähnle     for (DomTreeNode *Child : Worklist[I]->children())
5387ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
53976c5cb05SNicolai Hähnle   }
5407ed5856aSAlina Sbirlea 
5417ed5856aSAlina Sbirlea   return Worklist;
5427ed5856aSAlina Sbirlea }
5437ed5856aSAlina Sbirlea 
544efb130fcSAlina Sbirlea void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
545efb130fcSAlina Sbirlea                           LoopInfo *LI, MemorySSA *MSSA) {
546899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
547df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
548df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
549df3e71e0SMarcello Maggioni 
550efb130fcSAlina Sbirlea   std::unique_ptr<MemorySSAUpdater> MSSAU;
551efb130fcSAlina Sbirlea   if (MSSA)
552efb130fcSAlina Sbirlea     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
553efb130fcSAlina Sbirlea 
554df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
555df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
556df3e71e0SMarcello Maggioni   //
557df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
558df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
559df3e71e0SMarcello Maggioni 
560df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
561df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
562df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
563df3e71e0SMarcello Maggioni   if (SE)
564df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
565df3e71e0SMarcello Maggioni 
566df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
567df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
568df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
569df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
570df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
571df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
572df3e71e0SMarcello Maggioni   // preheader -> header.
573df3e71e0SMarcello Maggioni   //
574df3e71e0SMarcello Maggioni   //
575df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
576df3e71e0SMarcello Maggioni   //        |                    |   |                   |
577df3e71e0SMarcello Maggioni   //        V                    |   V                   |
578df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
579df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
580df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
581df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
582df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
583df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
584df3e71e0SMarcello Maggioni   //
585df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
586df3e71e0SMarcello Maggioni   // update without using the batch update API.
587df3e71e0SMarcello Maggioni   //
588df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
589df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
590df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
591df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
592df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
593df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
594df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
595babc224cSAtmn Patel 
596babc224cSAtmn Patel   auto *ExitBlock = L->getUniqueExitBlock();
597f88a7975SAtmn Patel   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
598babc224cSAtmn Patel   if (ExitBlock) {
599babc224cSAtmn Patel     assert(ExitBlock && "Should have a unique exit block!");
600babc224cSAtmn Patel     assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
601babc224cSAtmn Patel 
602df3e71e0SMarcello Maggioni     Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
603df3e71e0SMarcello Maggioni     // Remove the old branch. The conditional branch becomes a new terminator.
604df3e71e0SMarcello Maggioni     OldBr->eraseFromParent();
605df3e71e0SMarcello Maggioni 
606df3e71e0SMarcello Maggioni     // Rewrite phis in the exit block to get their inputs from the Preheader
607df3e71e0SMarcello Maggioni     // instead of the exiting block.
608c7fc81e6SBenjamin Kramer     for (PHINode &P : ExitBlock->phis()) {
609df3e71e0SMarcello Maggioni       // Set the zero'th element of Phi to be from the preheader and remove all
610df3e71e0SMarcello Maggioni       // other incoming values. Given the loop has dedicated exits, all other
611df3e71e0SMarcello Maggioni       // incoming values must be from the exiting blocks.
612df3e71e0SMarcello Maggioni       int PredIndex = 0;
613c7fc81e6SBenjamin Kramer       P.setIncomingBlock(PredIndex, Preheader);
614df3e71e0SMarcello Maggioni       // Removes all incoming values from all other exiting blocks (including
615df3e71e0SMarcello Maggioni       // duplicate values from an exiting block).
616df3e71e0SMarcello Maggioni       // Nuke all entries except the zero'th entry which is the preheader entry.
617df3e71e0SMarcello Maggioni       // NOTE! We need to remove Incoming Values in the reverse order as done
618df3e71e0SMarcello Maggioni       // below, to keep the indices valid for deletion (removeIncomingValues
619babc224cSAtmn Patel       // updates getNumIncomingValues and shifts all values down into the
620babc224cSAtmn Patel       // operand being deleted).
621c7fc81e6SBenjamin Kramer       for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
622c7fc81e6SBenjamin Kramer         P.removeIncomingValue(e - i, false);
623df3e71e0SMarcello Maggioni 
624c7fc81e6SBenjamin Kramer       assert((P.getNumIncomingValues() == 1 &&
625c7fc81e6SBenjamin Kramer               P.getIncomingBlock(PredIndex) == Preheader) &&
626df3e71e0SMarcello Maggioni              "Should have exactly one value and that's from the preheader!");
627df3e71e0SMarcello Maggioni     }
628df3e71e0SMarcello Maggioni 
629efb130fcSAlina Sbirlea     if (DT) {
630efb130fcSAlina Sbirlea       DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
631efb130fcSAlina Sbirlea       if (MSSA) {
632babc224cSAtmn Patel         MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
633babc224cSAtmn Patel                             *DT);
634efb130fcSAlina Sbirlea         if (VerifyMemorySSA)
635efb130fcSAlina Sbirlea           MSSA->verifyMemorySSA();
636efb130fcSAlina Sbirlea       }
637efb130fcSAlina Sbirlea     }
638efb130fcSAlina Sbirlea 
639df3e71e0SMarcello Maggioni     // Disconnect the loop body by branching directly to its exit.
640df3e71e0SMarcello Maggioni     Builder.SetInsertPoint(Preheader->getTerminator());
641df3e71e0SMarcello Maggioni     Builder.CreateBr(ExitBlock);
642df3e71e0SMarcello Maggioni     // Remove the old branch.
643df3e71e0SMarcello Maggioni     Preheader->getTerminator()->eraseFromParent();
644f88a7975SAtmn Patel   } else {
645f88a7975SAtmn Patel     assert(L->hasNoExitBlocks() &&
646f88a7975SAtmn Patel            "Loop should have either zero or one exit blocks.");
647f88a7975SAtmn Patel 
648f88a7975SAtmn Patel     Builder.SetInsertPoint(OldBr);
649f88a7975SAtmn Patel     Builder.CreateUnreachable();
650f88a7975SAtmn Patel     Preheader->getTerminator()->eraseFromParent();
651f88a7975SAtmn Patel   }
652df3e71e0SMarcello Maggioni 
653df3e71e0SMarcello Maggioni   if (DT) {
654efb130fcSAlina Sbirlea     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
655efb130fcSAlina Sbirlea     if (MSSA) {
656f88a7975SAtmn Patel       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
657f88a7975SAtmn Patel                           *DT);
658efb130fcSAlina Sbirlea       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
659efb130fcSAlina Sbirlea                                                    L->block_end());
660efb130fcSAlina Sbirlea       MSSAU->removeBlocks(DeadBlockSet);
661519b019aSAlina Sbirlea       if (VerifyMemorySSA)
662519b019aSAlina Sbirlea         MSSA->verifyMemorySSA();
663efb130fcSAlina Sbirlea     }
664df3e71e0SMarcello Maggioni   }
665df3e71e0SMarcello Maggioni 
666744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
6678ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
668744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
669744c3c32SDavide Italiano 
670babc224cSAtmn Patel   if (ExitBlock) {
671a757d65cSSerguei Katkov     // Given LCSSA form is satisfied, we should not have users of instructions
672a757d65cSSerguei Katkov     // within the dead loop outside of the loop. However, LCSSA doesn't take
673a757d65cSSerguei Katkov     // unreachable uses into account. We handle them here.
674a757d65cSSerguei Katkov     // We could do it after drop all references (in this case all users in the
675a757d65cSSerguei Katkov     // loop will be already eliminated and we have less work to do but according
676a757d65cSSerguei Katkov     // to API doc of User::dropAllReferences only valid operation after dropping
677a757d65cSSerguei Katkov     // references, is deletion. So let's substitute all usages of
678a757d65cSSerguei Katkov     // instruction from the loop with undef value of corresponding type first.
679a757d65cSSerguei Katkov     for (auto *Block : L->blocks())
680a757d65cSSerguei Katkov       for (Instruction &I : *Block) {
681a757d65cSSerguei Katkov         auto *Undef = UndefValue::get(I.getType());
682babc224cSAtmn Patel         for (Value::use_iterator UI = I.use_begin(), E = I.use_end();
683babc224cSAtmn Patel              UI != E;) {
684a757d65cSSerguei Katkov           Use &U = *UI;
685a757d65cSSerguei Katkov           ++UI;
686a757d65cSSerguei Katkov           if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
687a757d65cSSerguei Katkov             if (L->contains(Usr->getParent()))
688a757d65cSSerguei Katkov               continue;
689a757d65cSSerguei Katkov           // If we have a DT then we can check that uses outside a loop only in
690a757d65cSSerguei Katkov           // unreachable block.
691a757d65cSSerguei Katkov           if (DT)
692a757d65cSSerguei Katkov             assert(!DT->isReachableFromEntry(U) &&
693a757d65cSSerguei Katkov                    "Unexpected user in reachable block");
694a757d65cSSerguei Katkov           U.set(Undef);
695a757d65cSSerguei Katkov         }
696744c3c32SDavide Italiano         auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
697744c3c32SDavide Italiano         if (!DVI)
698744c3c32SDavide Italiano           continue;
699babc224cSAtmn Patel         auto Key =
700babc224cSAtmn Patel             DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
7018ee59ca6SDavide Italiano         if (Key != DeadDebugSet.end())
702744c3c32SDavide Italiano           continue;
7038ee59ca6SDavide Italiano         DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
704744c3c32SDavide Italiano         DeadDebugInst.push_back(DVI);
705a757d65cSSerguei Katkov       }
706a757d65cSSerguei Katkov 
707744c3c32SDavide Italiano     // After the loop has been deleted all the values defined and modified
708744c3c32SDavide Italiano     // inside the loop are going to be unavailable.
709744c3c32SDavide Italiano     // Since debug values in the loop have been deleted, inserting an undef
710744c3c32SDavide Italiano     // dbg.value truncates the range of any dbg.value before the loop where the
711744c3c32SDavide Italiano     // loop used to be. This is particularly important for constant values.
712744c3c32SDavide Italiano     DIBuilder DIB(*ExitBlock->getModule());
713e5be660eSRoman Lebedev     Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
714e5be660eSRoman Lebedev     assert(InsertDbgValueBefore &&
715e5be660eSRoman Lebedev            "There should be a non-PHI instruction in exit block, else these "
716e5be660eSRoman Lebedev            "instructions will have no parent.");
717744c3c32SDavide Italiano     for (auto *DVI : DeadDebugInst)
718e5be660eSRoman Lebedev       DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
719e5be660eSRoman Lebedev                                   DVI->getVariable(), DVI->getExpression(),
720e5be660eSRoman Lebedev                                   DVI->getDebugLoc(), InsertDbgValueBefore);
721babc224cSAtmn Patel   }
722744c3c32SDavide Italiano 
723df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
724df3e71e0SMarcello Maggioni   // delete it freely later.
725df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
726df3e71e0SMarcello Maggioni     Block->dropAllReferences();
727df3e71e0SMarcello Maggioni 
728efb130fcSAlina Sbirlea   if (MSSA && VerifyMemorySSA)
729efb130fcSAlina Sbirlea     MSSA->verifyMemorySSA();
730efb130fcSAlina Sbirlea 
731df3e71e0SMarcello Maggioni   if (LI) {
732df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
733df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
734df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
735df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
736df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
737df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
738df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
739df3e71e0SMarcello Maggioni 
740df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
741df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
742df3e71e0SMarcello Maggioni 
743df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
744df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
745df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
746df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
747df3e71e0SMarcello Maggioni 
748df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
7499883d7edSWhitney Tsang     // Note: LoopInfo::erase remove the given loop and relink its subloops with
7509883d7edSWhitney Tsang     // its parent. While removeLoop/removeChildLoop remove the given loop but
7519883d7edSWhitney Tsang     // not relink its subloops, which is what we want.
7529883d7edSWhitney Tsang     if (Loop *ParentLoop = L->getParentLoop()) {
7535d6c5b46SWhitney Tsang       Loop::iterator I = find(*ParentLoop, L);
7549883d7edSWhitney Tsang       assert(I != ParentLoop->end() && "Couldn't find loop");
7559883d7edSWhitney Tsang       ParentLoop->removeChildLoop(I);
7569883d7edSWhitney Tsang     } else {
7575d6c5b46SWhitney Tsang       Loop::iterator I = find(*LI, L);
7589883d7edSWhitney Tsang       assert(I != LI->end() && "Couldn't find loop");
7599883d7edSWhitney Tsang       LI->removeLoop(I);
7609883d7edSWhitney Tsang     }
7619883d7edSWhitney Tsang     LI->destroy(L);
762df3e71e0SMarcello Maggioni   }
763df3e71e0SMarcello Maggioni }
764df3e71e0SMarcello Maggioni 
765*4739dd67SPhilip Reames void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
766*4739dd67SPhilip Reames                              LoopInfo &LI, MemorySSA *MSSA) {
767*4739dd67SPhilip Reames 
768*4739dd67SPhilip Reames   assert(L->isOutermost() && "Can't yet preserve LCSSA for this case");
769*4739dd67SPhilip Reames   auto *Latch = L->getLoopLatch();
770*4739dd67SPhilip Reames   assert(Latch && "multiple latches not yet supported");
771*4739dd67SPhilip Reames   auto *Header = L->getHeader();
772*4739dd67SPhilip Reames 
773*4739dd67SPhilip Reames   SE.forgetLoop(L);
774*4739dd67SPhilip Reames 
775*4739dd67SPhilip Reames   // Note: By splitting the backedge, and then explicitly making it unreachable
776*4739dd67SPhilip Reames   // we gracefully handle corner cases such as non-bottom tested loops and the
777*4739dd67SPhilip Reames   // like.  We also have the benefit of being able to reuse existing well tested
778*4739dd67SPhilip Reames   // code.  It might be worth special casing the common bottom tested case at
779*4739dd67SPhilip Reames   // some point to avoid code churn.
780*4739dd67SPhilip Reames 
781*4739dd67SPhilip Reames   std::unique_ptr<MemorySSAUpdater> MSSAU;
782*4739dd67SPhilip Reames   if (MSSA)
783*4739dd67SPhilip Reames     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
784*4739dd67SPhilip Reames 
785*4739dd67SPhilip Reames   auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
786*4739dd67SPhilip Reames 
787*4739dd67SPhilip Reames   DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
788*4739dd67SPhilip Reames   (void)changeToUnreachable(BackedgeBB->getTerminator(), /*UseTrap*/false,
789*4739dd67SPhilip Reames                             /*PreserveLCSSA*/true, &DTU, MSSAU.get());
790*4739dd67SPhilip Reames 
791*4739dd67SPhilip Reames   // Erase (and destroy) this loop instance.  Handles relinking sub-loops
792*4739dd67SPhilip Reames   // and blocks within the loop as needed.
793*4739dd67SPhilip Reames   LI.erase(L);
794*4739dd67SPhilip Reames }
795*4739dd67SPhilip Reames 
796*4739dd67SPhilip Reames 
797af7e1588SEvgeniy Brevnov /// Checks if \p L has single exit through latch block except possibly
798af7e1588SEvgeniy Brevnov /// "deoptimizing" exits. Returns branch instruction terminating the loop
799af7e1588SEvgeniy Brevnov /// latch if above check is successful, nullptr otherwise.
800af7e1588SEvgeniy Brevnov static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
80145c43e7dSSerguei Katkov   BasicBlock *Latch = L->getLoopLatch();
80245c43e7dSSerguei Katkov   if (!Latch)
803af7e1588SEvgeniy Brevnov     return nullptr;
804af7e1588SEvgeniy Brevnov 
80545c43e7dSSerguei Katkov   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
80645c43e7dSSerguei Katkov   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
807af7e1588SEvgeniy Brevnov     return nullptr;
80841d72a86SDehao Chen 
80941d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
81041d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
81141d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
81241d72a86SDehao Chen 
81345c43e7dSSerguei Katkov   SmallVector<BasicBlock *, 4> ExitBlocks;
81445c43e7dSSerguei Katkov   L->getUniqueNonLatchExitBlocks(ExitBlocks);
81545c43e7dSSerguei Katkov   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
816eae0d2e9SSerguei Katkov         return !EB->getTerminatingDeoptimizeCall();
81745c43e7dSSerguei Katkov       }))
818af7e1588SEvgeniy Brevnov     return nullptr;
819af7e1588SEvgeniy Brevnov 
820af7e1588SEvgeniy Brevnov   return LatchBR;
821af7e1588SEvgeniy Brevnov }
822af7e1588SEvgeniy Brevnov 
823af7e1588SEvgeniy Brevnov Optional<unsigned>
824af7e1588SEvgeniy Brevnov llvm::getLoopEstimatedTripCount(Loop *L,
825af7e1588SEvgeniy Brevnov                                 unsigned *EstimatedLoopInvocationWeight) {
826af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
827af7e1588SEvgeniy Brevnov   // deoptimize.
828af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
829af7e1588SEvgeniy Brevnov   if (!LatchBranch)
83045c43e7dSSerguei Katkov     return None;
83145c43e7dSSerguei Katkov 
83241d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
83341d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
83441d72a86SDehao Chen   // we exited the loop.
835f0abe820SEvgeniy Brevnov   uint64_t BackedgeTakenWeight, LatchExitWeight;
836af7e1588SEvgeniy Brevnov   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
83741d72a86SDehao Chen     return None;
83841d72a86SDehao Chen 
839af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
840f0abe820SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
841f0abe820SEvgeniy Brevnov 
84210357e1cSEvgeniy Brevnov   if (!LatchExitWeight)
84310357e1cSEvgeniy Brevnov     return None;
84441d72a86SDehao Chen 
845af7e1588SEvgeniy Brevnov   if (EstimatedLoopInvocationWeight)
846af7e1588SEvgeniy Brevnov     *EstimatedLoopInvocationWeight = LatchExitWeight;
847af7e1588SEvgeniy Brevnov 
84810357e1cSEvgeniy Brevnov   // Estimated backedge taken count is a ratio of the backedge taken weight by
849cfe97681SEvgeniy Brevnov   // the weight of the edge exiting the loop, rounded to nearest.
85010357e1cSEvgeniy Brevnov   uint64_t BackedgeTakenCount =
85110357e1cSEvgeniy Brevnov       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
85210357e1cSEvgeniy Brevnov   // Estimated trip count is one plus estimated backedge taken count.
85310357e1cSEvgeniy Brevnov   return BackedgeTakenCount + 1;
85441d72a86SDehao Chen }
855cf9daa33SAmara Emerson 
856af7e1588SEvgeniy Brevnov bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
857af7e1588SEvgeniy Brevnov                                      unsigned EstimatedloopInvocationWeight) {
858af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
859af7e1588SEvgeniy Brevnov   // deoptimize.
860af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
861af7e1588SEvgeniy Brevnov   if (!LatchBranch)
862af7e1588SEvgeniy Brevnov     return false;
863af7e1588SEvgeniy Brevnov 
864af7e1588SEvgeniy Brevnov   // Calculate taken and exit weights.
865af7e1588SEvgeniy Brevnov   unsigned LatchExitWeight = 0;
866af7e1588SEvgeniy Brevnov   unsigned BackedgeTakenWeight = 0;
867af7e1588SEvgeniy Brevnov 
868af7e1588SEvgeniy Brevnov   if (EstimatedTripCount > 0) {
869af7e1588SEvgeniy Brevnov     LatchExitWeight = EstimatedloopInvocationWeight;
870af7e1588SEvgeniy Brevnov     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
871af7e1588SEvgeniy Brevnov   }
872af7e1588SEvgeniy Brevnov 
873af7e1588SEvgeniy Brevnov   // Make a swap if back edge is taken when condition is "false".
874af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
875af7e1588SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
876af7e1588SEvgeniy Brevnov 
877af7e1588SEvgeniy Brevnov   MDBuilder MDB(LatchBranch->getContext());
878af7e1588SEvgeniy Brevnov 
879af7e1588SEvgeniy Brevnov   // Set/Update profile metadata.
880af7e1588SEvgeniy Brevnov   LatchBranch->setMetadata(
881af7e1588SEvgeniy Brevnov       LLVMContext::MD_prof,
882af7e1588SEvgeniy Brevnov       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
883af7e1588SEvgeniy Brevnov 
884af7e1588SEvgeniy Brevnov   return true;
885af7e1588SEvgeniy Brevnov }
886af7e1588SEvgeniy Brevnov 
8876cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
888395b80cdSDavid Green                                               ScalarEvolution &SE) {
889395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
890395b80cdSDavid Green   if (!OuterL)
891395b80cdSDavid Green     return true;
892395b80cdSDavid Green 
893395b80cdSDavid Green   // Get the backedge taken count for the inner loop
894395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
895395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
896395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
897395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
898395b80cdSDavid Green     return false;
899395b80cdSDavid Green 
900395b80cdSDavid Green   // Get whether count is invariant to the outer loop
901395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
902395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
903395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
904395b80cdSDavid Green     return false;
905395b80cdSDavid Green 
906395b80cdSDavid Green   return true;
907395b80cdSDavid Green }
908395b80cdSDavid Green 
909c74e8539SSanjay Patel Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
910c74e8539SSanjay Patel                             Value *Right) {
9116594dc37SVikram TV   CmpInst::Predicate P = CmpInst::ICMP_NE;
9126594dc37SVikram TV   switch (RK) {
9136594dc37SVikram TV   default:
9146594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
915c74e8539SSanjay Patel   case RecurKind::UMin:
9166594dc37SVikram TV     P = CmpInst::ICMP_ULT;
9176594dc37SVikram TV     break;
918c74e8539SSanjay Patel   case RecurKind::UMax:
9196594dc37SVikram TV     P = CmpInst::ICMP_UGT;
9206594dc37SVikram TV     break;
921c74e8539SSanjay Patel   case RecurKind::SMin:
9226594dc37SVikram TV     P = CmpInst::ICMP_SLT;
9236594dc37SVikram TV     break;
924c74e8539SSanjay Patel   case RecurKind::SMax:
9256594dc37SVikram TV     P = CmpInst::ICMP_SGT;
9266594dc37SVikram TV     break;
927c74e8539SSanjay Patel   case RecurKind::FMin:
9286594dc37SVikram TV     P = CmpInst::FCMP_OLT;
9296594dc37SVikram TV     break;
930c74e8539SSanjay Patel   case RecurKind::FMax:
9316594dc37SVikram TV     P = CmpInst::FCMP_OGT;
9326594dc37SVikram TV     break;
9336594dc37SVikram TV   }
9346594dc37SVikram TV 
9356594dc37SVikram TV   // We only match FP sequences that are 'fast', so we can unconditionally
9366594dc37SVikram TV   // set it on any generated instructions.
93728ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFG(Builder);
9386594dc37SVikram TV   FastMathFlags FMF;
9396594dc37SVikram TV   FMF.setFast();
9406594dc37SVikram TV   Builder.setFastMathFlags(FMF);
94146a285adSSanjay Patel   Value *Cmp = Builder.CreateCmp(P, Left, Right, "rdx.minmax.cmp");
9426594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
9436594dc37SVikram TV   return Select;
9446594dc37SVikram TV }
9456594dc37SVikram TV 
94623c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
947c74e8539SSanjay Patel Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
948c74e8539SSanjay Patel                                  unsigned Op, RecurKind RdxKind,
94923c2182cSSimon Pilgrim                                  ArrayRef<Value *> RedOps) {
9508d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
95123c2182cSSimon Pilgrim 
95223c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
95323c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
95423c2182cSSimon Pilgrim   Value *Result = Acc;
95523c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
95623c2182cSSimon Pilgrim     Value *Ext =
95723c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
95823c2182cSSimon Pilgrim 
95923c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
96023c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
96123c2182cSSimon Pilgrim                                    "bin.rdx");
96223c2182cSSimon Pilgrim     } else {
963c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
96423c2182cSSimon Pilgrim              "Invalid min/max");
965c74e8539SSanjay Patel       Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
96623c2182cSSimon Pilgrim     }
96723c2182cSSimon Pilgrim 
96823c2182cSSimon Pilgrim     if (!RedOps.empty())
96923c2182cSSimon Pilgrim       propagateIRFlags(Result, RedOps);
97023c2182cSSimon Pilgrim   }
97123c2182cSSimon Pilgrim 
97223c2182cSSimon Pilgrim   return Result;
97323c2182cSSimon Pilgrim }
97423c2182cSSimon Pilgrim 
975cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
976c74e8539SSanjay Patel Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
977c74e8539SSanjay Patel                                  unsigned Op, RecurKind RdxKind,
978ad62a3a2SSanjay Patel                                  ArrayRef<Value *> RedOps) {
9798d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
980cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
981cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
982cf9daa33SAmara Emerson   // round.
983cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
984cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
985cf9daa33SAmara Emerson   Value *TmpVec = Src;
9866f64dacaSBenjamin Kramer   SmallVector<int, 32> ShuffleMask(VF);
987cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
988cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
989cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
9906f64dacaSBenjamin Kramer       ShuffleMask[j] = i / 2 + j;
991cf9daa33SAmara Emerson 
992cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
9936f64dacaSBenjamin Kramer     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
994cf9daa33SAmara Emerson 
9959b296102SJuneyoung Lee     Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
996cf9daa33SAmara Emerson 
997cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
998ad62a3a2SSanjay Patel       // The builder propagates its fast-math-flags setting.
999ad62a3a2SSanjay Patel       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1000ad62a3a2SSanjay Patel                                    "bin.rdx");
1001cf9daa33SAmara Emerson     } else {
1002c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1003cf9daa33SAmara Emerson              "Invalid min/max");
1004c74e8539SSanjay Patel       TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
1005cf9daa33SAmara Emerson     }
1006cf9daa33SAmara Emerson     if (!RedOps.empty())
1007cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
1008bc1148e7SSanjay Patel 
1009bc1148e7SSanjay Patel     // We may compute the reassociated scalar ops in a way that does not
1010bc1148e7SSanjay Patel     // preserve nsw/nuw etc. Conservatively, drop those flags.
1011bc1148e7SSanjay Patel     if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec))
1012bc1148e7SSanjay Patel       ReductionInst->dropPoisonGeneratingFlags();
1013cf9daa33SAmara Emerson   }
1014cf9daa33SAmara Emerson   // The result is in the first element of the vector.
1015cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1016cf9daa33SAmara Emerson }
1017cf9daa33SAmara Emerson 
1018c74e8539SSanjay Patel Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder,
1019c74e8539SSanjay Patel                                          const TargetTransformInfo *TTI,
102036263a7cSSanjay Patel                                          Value *Src, RecurKind RdxKind,
1021cf9daa33SAmara Emerson                                          ArrayRef<Value *> RedOps) {
102236263a7cSSanjay Patel   unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
102358b6c5d9SSanjay Patel   TargetTransformInfo::ReductionFlags RdxFlags;
102497669575SSanjay Patel   RdxFlags.IsMaxOp = RdxKind == RecurKind::SMax || RdxKind == RecurKind::UMax ||
102558b6c5d9SSanjay Patel                      RdxKind == RecurKind::FMax;
102658b6c5d9SSanjay Patel   RdxFlags.IsSigned = RdxKind == RecurKind::SMax || RdxKind == RecurKind::SMin;
102758b6c5d9SSanjay Patel   if (!ForceReductionIntrinsic &&
102858b6c5d9SSanjay Patel       !TTI->useReductionIntrinsic(Opcode, Src->getType(), RdxFlags))
102958b6c5d9SSanjay Patel     return getShuffleReduction(Builder, Src, Opcode, RdxKind, RedOps);
103058b6c5d9SSanjay Patel 
103197669575SSanjay Patel   auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
103236263a7cSSanjay Patel   switch (RdxKind) {
103336263a7cSSanjay Patel   case RecurKind::Add:
103497669575SSanjay Patel     return Builder.CreateAddReduce(Src);
103536263a7cSSanjay Patel   case RecurKind::Mul:
103697669575SSanjay Patel     return Builder.CreateMulReduce(Src);
103736263a7cSSanjay Patel   case RecurKind::And:
103897669575SSanjay Patel     return Builder.CreateAndReduce(Src);
103936263a7cSSanjay Patel   case RecurKind::Or:
104097669575SSanjay Patel     return Builder.CreateOrReduce(Src);
104136263a7cSSanjay Patel   case RecurKind::Xor:
104297669575SSanjay Patel     return Builder.CreateXorReduce(Src);
104336263a7cSSanjay Patel   case RecurKind::FAdd:
104497669575SSanjay Patel     return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
104597669575SSanjay Patel                                     Src);
104636263a7cSSanjay Patel   case RecurKind::FMul:
104797669575SSanjay Patel     return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
1048c74e8539SSanjay Patel   case RecurKind::SMax:
104997669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, true);
1050c74e8539SSanjay Patel   case RecurKind::SMin:
105197669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, true);
1052c74e8539SSanjay Patel   case RecurKind::UMax:
105397669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, false);
1054c74e8539SSanjay Patel   case RecurKind::UMin:
105597669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, false);
105636263a7cSSanjay Patel   case RecurKind::FMax:
105797669575SSanjay Patel     return Builder.CreateFPMaxReduce(Src);
105836263a7cSSanjay Patel   case RecurKind::FMin:
105997669575SSanjay Patel     return Builder.CreateFPMinReduce(Src);
1060cf9daa33SAmara Emerson   default:
1061cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1062cf9daa33SAmara Emerson   }
1063cf9daa33SAmara Emerson }
1064cf9daa33SAmara Emerson 
106528ffe38bSNikita Popov Value *llvm::createTargetReduction(IRBuilderBase &B,
1066cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
10678ca60db4SSanjay Patel                                    RecurrenceDescriptor &Desc, Value *Src) {
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());
107336263a7cSSanjay Patel   return createSimpleTargetReduction(B, TTI, Src, Desc.getRecurrenceKind());
1074cf9daa33SAmara Emerson }
1075cf9daa33SAmara Emerson 
1076a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1077a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1078a61f4b89SDinar Temirbulatov   if (!VecOp)
1079a61f4b89SDinar Temirbulatov     return;
1080a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1081a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1082a61f4b89SDinar Temirbulatov   if (!Intersection)
1083a61f4b89SDinar Temirbulatov     return;
1084a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1085a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1086a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1087a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1088a61f4b89SDinar Temirbulatov     if (!Instr)
1089a61f4b89SDinar Temirbulatov       continue;
1090a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1091a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1092cf9daa33SAmara Emerson   }
1093cf9daa33SAmara Emerson }
1094a78dc4d6SMax Kazantsev 
1095a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1096a78dc4d6SMax Kazantsev                                  ScalarEvolution &SE) {
1097a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1098a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1099a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1100a78dc4d6SMax Kazantsev }
1101a78dc4d6SMax Kazantsev 
1102a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1103a78dc4d6SMax Kazantsev                                     ScalarEvolution &SE) {
1104a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1105a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1106a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1107a78dc4d6SMax Kazantsev }
1108a78dc4d6SMax Kazantsev 
1109a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1110a78dc4d6SMax Kazantsev                              bool Signed) {
1111a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1112a78dc4d6SMax Kazantsev   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1113a78dc4d6SMax Kazantsev     APInt::getMinValue(BitWidth);
1114a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1115a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1116a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1117a78dc4d6SMax Kazantsev                                      SE.getConstant(Min));
1118a78dc4d6SMax Kazantsev }
1119a78dc4d6SMax Kazantsev 
1120a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1121a78dc4d6SMax Kazantsev                              bool Signed) {
1122a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1123a78dc4d6SMax Kazantsev   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1124a78dc4d6SMax Kazantsev     APInt::getMaxValue(BitWidth);
1125a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1126a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1127a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1128a78dc4d6SMax Kazantsev                                      SE.getConstant(Max));
1129a78dc4d6SMax Kazantsev }
113093175a5cSSjoerd Meijer 
113193175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
113293175a5cSSjoerd Meijer // rewriteLoopExitValues - Optimize IV users outside the loop.
113393175a5cSSjoerd Meijer // As a side effect, reduces the amount of IV processing within the loop.
113493175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
113593175a5cSSjoerd Meijer 
113693175a5cSSjoerd Meijer // Return true if the SCEV expansion generated by the rewriter can replace the
113793175a5cSSjoerd Meijer // original value. SCEV guarantees that it produces the same value, but the way
113893175a5cSSjoerd Meijer // it is produced may be illegal IR.  Ideally, this function will only be
113993175a5cSSjoerd Meijer // called for verification.
114093175a5cSSjoerd Meijer static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
114193175a5cSSjoerd Meijer   // If an SCEV expression subsumed multiple pointers, its expansion could
114293175a5cSSjoerd Meijer   // reassociate the GEP changing the base pointer. This is illegal because the
114393175a5cSSjoerd Meijer   // final address produced by a GEP chain must be inbounds relative to its
114493175a5cSSjoerd Meijer   // underlying object. Otherwise basic alias analysis, among other things,
114593175a5cSSjoerd Meijer   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
114693175a5cSSjoerd Meijer   // producing an expression involving multiple pointers. Until then, we must
114793175a5cSSjoerd Meijer   // bail out here.
114893175a5cSSjoerd Meijer   //
114989051ebaSVitaly Buka   // Retrieve the pointer operand of the GEP. Don't use getUnderlyingObject
115093175a5cSSjoerd Meijer   // because it understands lcssa phis while SCEV does not.
115193175a5cSSjoerd Meijer   Value *FromPtr = FromVal;
115293175a5cSSjoerd Meijer   Value *ToPtr = ToVal;
115393175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
115493175a5cSSjoerd Meijer     FromPtr = GEP->getPointerOperand();
115593175a5cSSjoerd Meijer 
115693175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
115793175a5cSSjoerd Meijer     ToPtr = GEP->getPointerOperand();
115893175a5cSSjoerd Meijer 
115993175a5cSSjoerd Meijer   if (FromPtr != FromVal || ToPtr != ToVal) {
116093175a5cSSjoerd Meijer     // Quickly check the common case
116193175a5cSSjoerd Meijer     if (FromPtr == ToPtr)
116293175a5cSSjoerd Meijer       return true;
116393175a5cSSjoerd Meijer 
116493175a5cSSjoerd Meijer     // SCEV may have rewritten an expression that produces the GEP's pointer
116593175a5cSSjoerd Meijer     // operand. That's ok as long as the pointer operand has the same base
116689051ebaSVitaly Buka     // pointer. Unlike getUnderlyingObject(), getPointerBase() will find the
116793175a5cSSjoerd Meijer     // base of a recurrence. This handles the case in which SCEV expansion
116893175a5cSSjoerd Meijer     // converts a pointer type recurrence into a nonrecurrent pointer base
116993175a5cSSjoerd Meijer     // indexed by an integer recurrence.
117093175a5cSSjoerd Meijer 
117193175a5cSSjoerd Meijer     // If the GEP base pointer is a vector of pointers, abort.
117293175a5cSSjoerd Meijer     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
117393175a5cSSjoerd Meijer       return false;
117493175a5cSSjoerd Meijer 
117593175a5cSSjoerd Meijer     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
117693175a5cSSjoerd Meijer     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
117793175a5cSSjoerd Meijer     if (FromBase == ToBase)
117893175a5cSSjoerd Meijer       return true;
117993175a5cSSjoerd Meijer 
118093175a5cSSjoerd Meijer     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
118193175a5cSSjoerd Meijer                       << *FromBase << " != " << *ToBase << "\n");
118293175a5cSSjoerd Meijer 
118393175a5cSSjoerd Meijer     return false;
118493175a5cSSjoerd Meijer   }
118593175a5cSSjoerd Meijer   return true;
118693175a5cSSjoerd Meijer }
118793175a5cSSjoerd Meijer 
118893175a5cSSjoerd Meijer static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
118993175a5cSSjoerd Meijer   SmallPtrSet<const Instruction *, 8> Visited;
119093175a5cSSjoerd Meijer   SmallVector<const Instruction *, 8> WorkList;
119193175a5cSSjoerd Meijer   Visited.insert(I);
119293175a5cSSjoerd Meijer   WorkList.push_back(I);
119393175a5cSSjoerd Meijer   while (!WorkList.empty()) {
119493175a5cSSjoerd Meijer     const Instruction *Curr = WorkList.pop_back_val();
119593175a5cSSjoerd Meijer     // This use is outside the loop, nothing to do.
119693175a5cSSjoerd Meijer     if (!L->contains(Curr))
119793175a5cSSjoerd Meijer       continue;
119893175a5cSSjoerd Meijer     // Do we assume it is a "hard" use which will not be eliminated easily?
119993175a5cSSjoerd Meijer     if (Curr->mayHaveSideEffects())
120093175a5cSSjoerd Meijer       return true;
120193175a5cSSjoerd Meijer     // Otherwise, add all its users to worklist.
120293175a5cSSjoerd Meijer     for (auto U : Curr->users()) {
120393175a5cSSjoerd Meijer       auto *UI = cast<Instruction>(U);
120493175a5cSSjoerd Meijer       if (Visited.insert(UI).second)
120593175a5cSSjoerd Meijer         WorkList.push_back(UI);
120693175a5cSSjoerd Meijer     }
120793175a5cSSjoerd Meijer   }
120893175a5cSSjoerd Meijer   return false;
120993175a5cSSjoerd Meijer }
121093175a5cSSjoerd Meijer 
121193175a5cSSjoerd Meijer // Collect information about PHI nodes which can be transformed in
121293175a5cSSjoerd Meijer // rewriteLoopExitValues.
121393175a5cSSjoerd Meijer struct RewritePhi {
1214b2df9612SRoman Lebedev   PHINode *PN;               // For which PHI node is this replacement?
1215b2df9612SRoman Lebedev   unsigned Ith;              // For which incoming value?
1216b2df9612SRoman Lebedev   const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1217b2df9612SRoman Lebedev   Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1218b2df9612SRoman Lebedev   bool HighCost;               // Is this expansion a high-cost?
121993175a5cSSjoerd Meijer 
1220b2df9612SRoman Lebedev   Value *Expansion = nullptr;
1221b2df9612SRoman Lebedev   bool ValidRewrite = false;
1222b2df9612SRoman Lebedev 
1223b2df9612SRoman Lebedev   RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1224b2df9612SRoman Lebedev              bool H)
1225b2df9612SRoman Lebedev       : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1226b2df9612SRoman Lebedev         HighCost(H) {}
122793175a5cSSjoerd Meijer };
122893175a5cSSjoerd Meijer 
122993175a5cSSjoerd Meijer // Check whether it is possible to delete the loop after rewriting exit
123093175a5cSSjoerd Meijer // value. If it is possible, ignore ReplaceExitValue and do rewriting
123193175a5cSSjoerd Meijer // aggressively.
123293175a5cSSjoerd Meijer static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
123393175a5cSSjoerd Meijer   BasicBlock *Preheader = L->getLoopPreheader();
123493175a5cSSjoerd Meijer   // If there is no preheader, the loop will not be deleted.
123593175a5cSSjoerd Meijer   if (!Preheader)
123693175a5cSSjoerd Meijer     return false;
123793175a5cSSjoerd Meijer 
123893175a5cSSjoerd Meijer   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
123993175a5cSSjoerd Meijer   // We obviate multiple ExitingBlocks case for simplicity.
124093175a5cSSjoerd Meijer   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
124193175a5cSSjoerd Meijer   // after exit value rewriting, we can enhance the logic here.
124293175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 4> ExitingBlocks;
124393175a5cSSjoerd Meijer   L->getExitingBlocks(ExitingBlocks);
124493175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 8> ExitBlocks;
124593175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
124693175a5cSSjoerd Meijer   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
124793175a5cSSjoerd Meijer     return false;
124893175a5cSSjoerd Meijer 
124993175a5cSSjoerd Meijer   BasicBlock *ExitBlock = ExitBlocks[0];
125093175a5cSSjoerd Meijer   BasicBlock::iterator BI = ExitBlock->begin();
125193175a5cSSjoerd Meijer   while (PHINode *P = dyn_cast<PHINode>(BI)) {
125293175a5cSSjoerd Meijer     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
125393175a5cSSjoerd Meijer 
125493175a5cSSjoerd Meijer     // If the Incoming value of P is found in RewritePhiSet, we know it
125593175a5cSSjoerd Meijer     // could be rewritten to use a loop invariant value in transformation
125693175a5cSSjoerd Meijer     // phase later. Skip it in the loop invariant check below.
125793175a5cSSjoerd Meijer     bool found = false;
125893175a5cSSjoerd Meijer     for (const RewritePhi &Phi : RewritePhiSet) {
1259b2df9612SRoman Lebedev       if (!Phi.ValidRewrite)
1260b2df9612SRoman Lebedev         continue;
126193175a5cSSjoerd Meijer       unsigned i = Phi.Ith;
126293175a5cSSjoerd Meijer       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
126393175a5cSSjoerd Meijer         found = true;
126493175a5cSSjoerd Meijer         break;
126593175a5cSSjoerd Meijer       }
126693175a5cSSjoerd Meijer     }
126793175a5cSSjoerd Meijer 
126893175a5cSSjoerd Meijer     Instruction *I;
126993175a5cSSjoerd Meijer     if (!found && (I = dyn_cast<Instruction>(Incoming)))
127093175a5cSSjoerd Meijer       if (!L->hasLoopInvariantOperands(I))
127193175a5cSSjoerd Meijer         return false;
127293175a5cSSjoerd Meijer 
127393175a5cSSjoerd Meijer     ++BI;
127493175a5cSSjoerd Meijer   }
127593175a5cSSjoerd Meijer 
127693175a5cSSjoerd Meijer   for (auto *BB : L->blocks())
127793175a5cSSjoerd Meijer     if (llvm::any_of(*BB, [](Instruction &I) {
127893175a5cSSjoerd Meijer           return I.mayHaveSideEffects();
127993175a5cSSjoerd Meijer         }))
128093175a5cSSjoerd Meijer       return false;
128193175a5cSSjoerd Meijer 
128293175a5cSSjoerd Meijer   return true;
128393175a5cSSjoerd Meijer }
128493175a5cSSjoerd Meijer 
12850789f280SRoman Lebedev int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
12860789f280SRoman Lebedev                                 ScalarEvolution *SE,
12870789f280SRoman Lebedev                                 const TargetTransformInfo *TTI,
12880789f280SRoman Lebedev                                 SCEVExpander &Rewriter, DominatorTree *DT,
12890789f280SRoman Lebedev                                 ReplaceExitVal ReplaceExitValue,
129093175a5cSSjoerd Meijer                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
129193175a5cSSjoerd Meijer   // Check a pre-condition.
129293175a5cSSjoerd Meijer   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
129393175a5cSSjoerd Meijer          "Indvars did not preserve LCSSA!");
129493175a5cSSjoerd Meijer 
129593175a5cSSjoerd Meijer   SmallVector<BasicBlock*, 8> ExitBlocks;
129693175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
129793175a5cSSjoerd Meijer 
129893175a5cSSjoerd Meijer   SmallVector<RewritePhi, 8> RewritePhiSet;
129993175a5cSSjoerd Meijer   // Find all values that are computed inside the loop, but used outside of it.
130093175a5cSSjoerd Meijer   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
130193175a5cSSjoerd Meijer   // the exit blocks of the loop to find them.
130293175a5cSSjoerd Meijer   for (BasicBlock *ExitBB : ExitBlocks) {
130393175a5cSSjoerd Meijer     // If there are no PHI nodes in this exit block, then no values defined
130493175a5cSSjoerd Meijer     // inside the loop are used on this path, skip it.
130593175a5cSSjoerd Meijer     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
130693175a5cSSjoerd Meijer     if (!PN) continue;
130793175a5cSSjoerd Meijer 
130893175a5cSSjoerd Meijer     unsigned NumPreds = PN->getNumIncomingValues();
130993175a5cSSjoerd Meijer 
131093175a5cSSjoerd Meijer     // Iterate over all of the PHI nodes.
131193175a5cSSjoerd Meijer     BasicBlock::iterator BBI = ExitBB->begin();
131293175a5cSSjoerd Meijer     while ((PN = dyn_cast<PHINode>(BBI++))) {
131393175a5cSSjoerd Meijer       if (PN->use_empty())
131493175a5cSSjoerd Meijer         continue; // dead use, don't replace it
131593175a5cSSjoerd Meijer 
131693175a5cSSjoerd Meijer       if (!SE->isSCEVable(PN->getType()))
131793175a5cSSjoerd Meijer         continue;
131893175a5cSSjoerd Meijer 
131993175a5cSSjoerd Meijer       // It's necessary to tell ScalarEvolution about this explicitly so that
132093175a5cSSjoerd Meijer       // it can walk the def-use list and forget all SCEVs, as it may not be
132193175a5cSSjoerd Meijer       // watching the PHI itself. Once the new exit value is in place, there
132293175a5cSSjoerd Meijer       // may not be a def-use connection between the loop and every instruction
132393175a5cSSjoerd Meijer       // which got a SCEVAddRecExpr for that loop.
132493175a5cSSjoerd Meijer       SE->forgetValue(PN);
132593175a5cSSjoerd Meijer 
132693175a5cSSjoerd Meijer       // Iterate over all of the values in all the PHI nodes.
132793175a5cSSjoerd Meijer       for (unsigned i = 0; i != NumPreds; ++i) {
132893175a5cSSjoerd Meijer         // If the value being merged in is not integer or is not defined
132993175a5cSSjoerd Meijer         // in the loop, skip it.
133093175a5cSSjoerd Meijer         Value *InVal = PN->getIncomingValue(i);
133193175a5cSSjoerd Meijer         if (!isa<Instruction>(InVal))
133293175a5cSSjoerd Meijer           continue;
133393175a5cSSjoerd Meijer 
133493175a5cSSjoerd Meijer         // If this pred is for a subloop, not L itself, skip it.
133593175a5cSSjoerd Meijer         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
133693175a5cSSjoerd Meijer           continue; // The Block is in a subloop, skip it.
133793175a5cSSjoerd Meijer 
133893175a5cSSjoerd Meijer         // Check that InVal is defined in the loop.
133993175a5cSSjoerd Meijer         Instruction *Inst = cast<Instruction>(InVal);
134093175a5cSSjoerd Meijer         if (!L->contains(Inst))
134193175a5cSSjoerd Meijer           continue;
134293175a5cSSjoerd Meijer 
134393175a5cSSjoerd Meijer         // Okay, this instruction has a user outside of the current loop
134493175a5cSSjoerd Meijer         // and varies predictably *inside* the loop.  Evaluate the value it
134593175a5cSSjoerd Meijer         // contains when the loop exits, if possible.  We prefer to start with
134693175a5cSSjoerd Meijer         // expressions which are true for all exits (so as to maximize
134793175a5cSSjoerd Meijer         // expression reuse by the SCEVExpander), but resort to per-exit
134893175a5cSSjoerd Meijer         // evaluation if that fails.
134993175a5cSSjoerd Meijer         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
135093175a5cSSjoerd Meijer         if (isa<SCEVCouldNotCompute>(ExitValue) ||
135193175a5cSSjoerd Meijer             !SE->isLoopInvariant(ExitValue, L) ||
135293175a5cSSjoerd Meijer             !isSafeToExpand(ExitValue, *SE)) {
135393175a5cSSjoerd Meijer           // TODO: This should probably be sunk into SCEV in some way; maybe a
135493175a5cSSjoerd Meijer           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
135593175a5cSSjoerd Meijer           // most SCEV expressions and other recurrence types (e.g. shift
135693175a5cSSjoerd Meijer           // recurrences).  Is there existing code we can reuse?
135793175a5cSSjoerd Meijer           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
135893175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitCount))
135993175a5cSSjoerd Meijer             continue;
136093175a5cSSjoerd Meijer           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
136193175a5cSSjoerd Meijer             if (AddRec->getLoop() == L)
136293175a5cSSjoerd Meijer               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
136393175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitValue) ||
136493175a5cSSjoerd Meijer               !SE->isLoopInvariant(ExitValue, L) ||
136593175a5cSSjoerd Meijer               !isSafeToExpand(ExitValue, *SE))
136693175a5cSSjoerd Meijer             continue;
136793175a5cSSjoerd Meijer         }
136893175a5cSSjoerd Meijer 
136993175a5cSSjoerd Meijer         // Computing the value outside of the loop brings no benefit if it is
137093175a5cSSjoerd Meijer         // definitely used inside the loop in a way which can not be optimized
13717d572ef2SRoman Lebedev         // away. Avoid doing so unless we know we have a value which computes
13727d572ef2SRoman Lebedev         // the ExitValue already. TODO: This should be merged into SCEV
13737d572ef2SRoman Lebedev         // expander to leverage its knowledge of existing expressions.
13747d572ef2SRoman Lebedev         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
13757d572ef2SRoman Lebedev             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
137693175a5cSSjoerd Meijer           continue;
137793175a5cSSjoerd Meijer 
1378b2df9612SRoman Lebedev         // Check if expansions of this SCEV would count as being high cost.
13797d572ef2SRoman Lebedev         bool HighCost = Rewriter.isHighCostExpansion(
13807d572ef2SRoman Lebedev             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1381b2df9612SRoman Lebedev 
1382b2df9612SRoman Lebedev         // Note that we must not perform expansions until after
1383b2df9612SRoman Lebedev         // we query *all* the costs, because if we perform temporary expansion
1384b2df9612SRoman Lebedev         // inbetween, one that we might not intend to keep, said expansion
1385b2df9612SRoman Lebedev         // *may* affect cost calculation of the the next SCEV's we'll query,
1386b2df9612SRoman Lebedev         // and next SCEV may errneously get smaller cost.
1387b2df9612SRoman Lebedev 
1388b2df9612SRoman Lebedev         // Collect all the candidate PHINodes to be rewritten.
1389b2df9612SRoman Lebedev         RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost);
1390b2df9612SRoman Lebedev       }
1391b2df9612SRoman Lebedev     }
1392b2df9612SRoman Lebedev   }
1393b2df9612SRoman Lebedev 
1394b2df9612SRoman Lebedev   // Now that we've done preliminary filtering and billed all the SCEV's,
1395b2df9612SRoman Lebedev   // we can perform the last sanity check - the expansion must be valid.
1396b2df9612SRoman Lebedev   for (RewritePhi &Phi : RewritePhiSet) {
1397b2df9612SRoman Lebedev     Phi.Expansion = Rewriter.expandCodeFor(Phi.ExpansionSCEV, Phi.PN->getType(),
1398b2df9612SRoman Lebedev                                            Phi.ExpansionPoint);
139993175a5cSSjoerd Meijer 
140093175a5cSSjoerd Meijer     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
1401b2df9612SRoman Lebedev                       << *(Phi.Expansion) << '\n'
1402b2df9612SRoman Lebedev                       << "  LoopVal = " << *(Phi.ExpansionPoint) << "\n");
140393175a5cSSjoerd Meijer 
1404b2df9612SRoman Lebedev     // FIXME: isValidRewrite() is a hack. it should be an assert, eventually.
1405b2df9612SRoman Lebedev     Phi.ValidRewrite = isValidRewrite(SE, Phi.ExpansionPoint, Phi.Expansion);
1406b2df9612SRoman Lebedev     if (!Phi.ValidRewrite) {
1407b2df9612SRoman Lebedev       DeadInsts.push_back(Phi.Expansion);
140893175a5cSSjoerd Meijer       continue;
140993175a5cSSjoerd Meijer     }
141093175a5cSSjoerd Meijer 
141193175a5cSSjoerd Meijer #ifndef NDEBUG
141293175a5cSSjoerd Meijer     // If we reuse an instruction from a loop which is neither L nor one of
141393175a5cSSjoerd Meijer     // its containing loops, we end up breaking LCSSA form for this loop by
141493175a5cSSjoerd Meijer     // creating a new use of its instruction.
1415b2df9612SRoman Lebedev     if (auto *ExitInsn = dyn_cast<Instruction>(Phi.Expansion))
141693175a5cSSjoerd Meijer       if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
141793175a5cSSjoerd Meijer         if (EVL != L)
141893175a5cSSjoerd Meijer           assert(EVL->contains(L) && "LCSSA breach detected!");
141993175a5cSSjoerd Meijer #endif
1420b2df9612SRoman Lebedev   }
142193175a5cSSjoerd Meijer 
1422b2df9612SRoman Lebedev   // TODO: after isValidRewrite() is an assertion, evaluate whether
1423b2df9612SRoman Lebedev   // it is beneficial to change how we calculate high-cost:
1424b2df9612SRoman Lebedev   // if we have SCEV 'A' which we know we will expand, should we calculate
1425b2df9612SRoman Lebedev   // the cost of other SCEV's after expanding SCEV 'A',
1426b2df9612SRoman Lebedev   // thus potentially giving cost bonus to those other SCEV's?
142793175a5cSSjoerd Meijer 
142893175a5cSSjoerd Meijer   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
142993175a5cSSjoerd Meijer   int NumReplaced = 0;
143093175a5cSSjoerd Meijer 
143193175a5cSSjoerd Meijer   // Transformation.
143293175a5cSSjoerd Meijer   for (const RewritePhi &Phi : RewritePhiSet) {
1433b2df9612SRoman Lebedev     if (!Phi.ValidRewrite)
1434b2df9612SRoman Lebedev       continue;
1435b2df9612SRoman Lebedev 
143693175a5cSSjoerd Meijer     PHINode *PN = Phi.PN;
1437b2df9612SRoman Lebedev     Value *ExitVal = Phi.Expansion;
143893175a5cSSjoerd Meijer 
143993175a5cSSjoerd Meijer     // Only do the rewrite when the ExitValue can be expanded cheaply.
144093175a5cSSjoerd Meijer     // If LoopCanBeDel is true, rewrite exit value aggressively.
144193175a5cSSjoerd Meijer     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
144293175a5cSSjoerd Meijer       DeadInsts.push_back(ExitVal);
144393175a5cSSjoerd Meijer       continue;
144493175a5cSSjoerd Meijer     }
144593175a5cSSjoerd Meijer 
144693175a5cSSjoerd Meijer     NumReplaced++;
144793175a5cSSjoerd Meijer     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
144893175a5cSSjoerd Meijer     PN->setIncomingValue(Phi.Ith, ExitVal);
144993175a5cSSjoerd Meijer 
145093175a5cSSjoerd Meijer     // If this instruction is dead now, delete it. Don't do it now to avoid
145193175a5cSSjoerd Meijer     // invalidating iterators.
145293175a5cSSjoerd Meijer     if (isInstructionTriviallyDead(Inst, TLI))
145393175a5cSSjoerd Meijer       DeadInsts.push_back(Inst);
145493175a5cSSjoerd Meijer 
145593175a5cSSjoerd Meijer     // Replace PN with ExitVal if that is legal and does not break LCSSA.
145693175a5cSSjoerd Meijer     if (PN->getNumIncomingValues() == 1 &&
145793175a5cSSjoerd Meijer         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
145893175a5cSSjoerd Meijer       PN->replaceAllUsesWith(ExitVal);
145993175a5cSSjoerd Meijer       PN->eraseFromParent();
146093175a5cSSjoerd Meijer     }
146193175a5cSSjoerd Meijer   }
146293175a5cSSjoerd Meijer 
146393175a5cSSjoerd Meijer   // The insertion point instruction may have been deleted; clear it out
146493175a5cSSjoerd Meijer   // so that the rewriter doesn't trip over it later.
146593175a5cSSjoerd Meijer   Rewriter.clearInsertPoint();
146693175a5cSSjoerd Meijer   return NumReplaced;
146793175a5cSSjoerd Meijer }
1468af7e1588SEvgeniy Brevnov 
1469af7e1588SEvgeniy Brevnov /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1470af7e1588SEvgeniy Brevnov /// \p OrigLoop.
1471af7e1588SEvgeniy Brevnov void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1472af7e1588SEvgeniy Brevnov                                         Loop *RemainderLoop, uint64_t UF) {
1473af7e1588SEvgeniy Brevnov   assert(UF > 0 && "Zero unrolled factor is not supported");
1474af7e1588SEvgeniy Brevnov   assert(UnrolledLoop != RemainderLoop &&
1475af7e1588SEvgeniy Brevnov          "Unrolled and Remainder loops are expected to distinct");
1476af7e1588SEvgeniy Brevnov 
1477af7e1588SEvgeniy Brevnov   // Get number of iterations in the original scalar loop.
1478af7e1588SEvgeniy Brevnov   unsigned OrigLoopInvocationWeight = 0;
1479af7e1588SEvgeniy Brevnov   Optional<unsigned> OrigAverageTripCount =
1480af7e1588SEvgeniy Brevnov       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1481af7e1588SEvgeniy Brevnov   if (!OrigAverageTripCount)
1482af7e1588SEvgeniy Brevnov     return;
1483af7e1588SEvgeniy Brevnov 
1484af7e1588SEvgeniy Brevnov   // Calculate number of iterations in unrolled loop.
1485af7e1588SEvgeniy Brevnov   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1486af7e1588SEvgeniy Brevnov   // Calculate number of iterations for remainder loop.
1487af7e1588SEvgeniy Brevnov   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1488af7e1588SEvgeniy Brevnov 
1489af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1490af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1491af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1492af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1493af7e1588SEvgeniy Brevnov }
1494388de9dfSAlina Sbirlea 
1495388de9dfSAlina Sbirlea /// Utility that implements appending of loops onto a worklist.
1496388de9dfSAlina Sbirlea /// Loops are added in preorder (analogous for reverse postorder for trees),
1497388de9dfSAlina Sbirlea /// and the worklist is processed LIFO.
1498388de9dfSAlina Sbirlea template <typename RangeT>
1499388de9dfSAlina Sbirlea void llvm::appendReversedLoopsToWorklist(
1500388de9dfSAlina Sbirlea     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1501388de9dfSAlina Sbirlea   // We use an internal worklist to build up the preorder traversal without
1502388de9dfSAlina Sbirlea   // recursion.
1503388de9dfSAlina Sbirlea   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1504388de9dfSAlina Sbirlea 
1505388de9dfSAlina Sbirlea   // We walk the initial sequence of loops in reverse because we generally want
1506388de9dfSAlina Sbirlea   // to visit defs before uses and the worklist is LIFO.
1507388de9dfSAlina Sbirlea   for (Loop *RootL : Loops) {
1508388de9dfSAlina Sbirlea     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1509388de9dfSAlina Sbirlea     assert(PreOrderWorklist.empty() &&
1510388de9dfSAlina Sbirlea            "Must start with an empty preorder walk worklist.");
1511388de9dfSAlina Sbirlea     PreOrderWorklist.push_back(RootL);
1512388de9dfSAlina Sbirlea     do {
1513388de9dfSAlina Sbirlea       Loop *L = PreOrderWorklist.pop_back_val();
1514388de9dfSAlina Sbirlea       PreOrderWorklist.append(L->begin(), L->end());
1515388de9dfSAlina Sbirlea       PreOrderLoops.push_back(L);
1516388de9dfSAlina Sbirlea     } while (!PreOrderWorklist.empty());
1517388de9dfSAlina Sbirlea 
1518388de9dfSAlina Sbirlea     Worklist.insert(std::move(PreOrderLoops));
1519388de9dfSAlina Sbirlea     PreOrderLoops.clear();
1520388de9dfSAlina Sbirlea   }
1521388de9dfSAlina Sbirlea }
1522388de9dfSAlina Sbirlea 
1523388de9dfSAlina Sbirlea template <typename RangeT>
1524388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(RangeT &&Loops,
1525388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1526388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1527388de9dfSAlina Sbirlea }
1528388de9dfSAlina Sbirlea 
1529388de9dfSAlina Sbirlea template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1530388de9dfSAlina Sbirlea     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1531388de9dfSAlina Sbirlea 
153267904db2SAlina Sbirlea template void
153367904db2SAlina Sbirlea llvm::appendLoopsToWorklist<Loop &>(Loop &L,
153467904db2SAlina Sbirlea                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
153567904db2SAlina Sbirlea 
1536388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(LoopInfo &LI,
1537388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1538388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(LI, Worklist);
1539388de9dfSAlina Sbirlea }
15403dcaf296SArkady Shlykov 
15413dcaf296SArkady Shlykov Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
15423dcaf296SArkady Shlykov                       LoopInfo *LI, LPPassManager *LPM) {
15433dcaf296SArkady Shlykov   Loop &New = *LI->AllocateLoop();
15443dcaf296SArkady Shlykov   if (PL)
15453dcaf296SArkady Shlykov     PL->addChildLoop(&New);
15463dcaf296SArkady Shlykov   else
15473dcaf296SArkady Shlykov     LI->addTopLevelLoop(&New);
15483dcaf296SArkady Shlykov 
15493dcaf296SArkady Shlykov   if (LPM)
15503dcaf296SArkady Shlykov     LPM->addLoop(New);
15513dcaf296SArkady Shlykov 
15523dcaf296SArkady Shlykov   // Add all of the blocks in L to the new loop.
15533dcaf296SArkady Shlykov   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
15543dcaf296SArkady Shlykov        I != E; ++I)
15553dcaf296SArkady Shlykov     if (LI->getLoopFor(*I) == L)
15563dcaf296SArkady Shlykov       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *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.
15768528186bSFlorian Hahn static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
15778528186bSFlorian Hahn                                   Loop *TheLoop, Instruction *Loc,
15788528186bSFlorian Hahn                                   SCEVExpander &Exp, ScalarEvolution *SE) {
15798528186bSFlorian Hahn   // TODO: Add helper to retrieve pointers to CG.
15808528186bSFlorian Hahn   Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue;
15818528186bSFlorian Hahn   const SCEV *Sc = SE->getSCEV(Ptr);
15828528186bSFlorian Hahn 
15838528186bSFlorian Hahn   unsigned AS = Ptr->getType()->getPointerAddressSpace();
15848528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
15858528186bSFlorian Hahn 
15868528186bSFlorian Hahn   // Use this type for pointer arithmetic.
15878528186bSFlorian Hahn   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
15888528186bSFlorian Hahn 
15898528186bSFlorian Hahn   if (SE->isLoopInvariant(Sc, TheLoop)) {
15908528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:"
15918528186bSFlorian Hahn                       << *Ptr << "\n");
15928528186bSFlorian Hahn     // Ptr could be in the loop body. If so, expand a new one at the correct
15938528186bSFlorian Hahn     // location.
15948528186bSFlorian Hahn     Instruction *Inst = dyn_cast<Instruction>(Ptr);
15958528186bSFlorian Hahn     Value *NewPtr = (Inst && TheLoop->contains(Inst))
15968528186bSFlorian Hahn                         ? Exp.expandCodeFor(Sc, PtrArithTy, Loc)
15978528186bSFlorian Hahn                         : Ptr;
15988528186bSFlorian Hahn     // We must return a half-open range, which means incrementing Sc.
15998528186bSFlorian Hahn     const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy));
16008528186bSFlorian Hahn     Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc);
16018528186bSFlorian Hahn     return {NewPtr, NewPtrPlusOne};
16028528186bSFlorian Hahn   } else {
16038528186bSFlorian Hahn     Value *Start = nullptr, *End = nullptr;
16048528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
16058528186bSFlorian Hahn     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
16068528186bSFlorian Hahn     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
16078528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High
16088528186bSFlorian Hahn                       << "\n");
16098528186bSFlorian Hahn     return {Start, End};
16108528186bSFlorian Hahn   }
16118528186bSFlorian Hahn }
16128528186bSFlorian Hahn 
16138528186bSFlorian Hahn /// Turns a collection of checks into a collection of expanded upper and
16148528186bSFlorian Hahn /// lower bounds for both pointers in the check.
16158528186bSFlorian Hahn static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
16168528186bSFlorian Hahn expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
16178528186bSFlorian Hahn              Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) {
16188528186bSFlorian Hahn   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
16198528186bSFlorian Hahn 
16208528186bSFlorian Hahn   // Here we're relying on the SCEV Expander's cache to only emit code for the
16218528186bSFlorian Hahn   // same bounds once.
16228528186bSFlorian Hahn   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
16238528186bSFlorian Hahn             [&](const RuntimePointerCheck &Check) {
16248528186bSFlorian Hahn               PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE),
16258528186bSFlorian Hahn                             Second =
16268528186bSFlorian Hahn                                 expandBounds(Check.second, L, Loc, Exp, SE);
16278528186bSFlorian Hahn               return std::make_pair(First, Second);
16288528186bSFlorian Hahn             });
16298528186bSFlorian Hahn 
16308528186bSFlorian Hahn   return ChecksWithBounds;
16318528186bSFlorian Hahn }
16328528186bSFlorian Hahn 
16338528186bSFlorian Hahn std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks(
16348528186bSFlorian Hahn     Instruction *Loc, Loop *TheLoop,
16358528186bSFlorian Hahn     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
16368528186bSFlorian Hahn     ScalarEvolution *SE) {
16378528186bSFlorian Hahn   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
16388528186bSFlorian Hahn   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
16398528186bSFlorian Hahn   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
16408528186bSFlorian Hahn   SCEVExpander Exp(*SE, DL, "induction");
16418528186bSFlorian Hahn   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp);
16428528186bSFlorian Hahn 
16438528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
16448528186bSFlorian Hahn   Instruction *FirstInst = nullptr;
16458528186bSFlorian Hahn   IRBuilder<> ChkBuilder(Loc);
16468528186bSFlorian Hahn   // Our instructions might fold to a constant.
16478528186bSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
16488528186bSFlorian Hahn 
16498528186bSFlorian Hahn   // FIXME: this helper is currently a duplicate of the one in
16508528186bSFlorian Hahn   // LoopVectorize.cpp.
16518528186bSFlorian Hahn   auto GetFirstInst = [](Instruction *FirstInst, Value *V,
16528528186bSFlorian Hahn                          Instruction *Loc) -> Instruction * {
16538528186bSFlorian Hahn     if (FirstInst)
16548528186bSFlorian Hahn       return FirstInst;
16558528186bSFlorian Hahn     if (Instruction *I = dyn_cast<Instruction>(V))
16568528186bSFlorian Hahn       return I->getParent() == Loc->getParent() ? I : nullptr;
16578528186bSFlorian Hahn     return nullptr;
16588528186bSFlorian Hahn   };
16598528186bSFlorian Hahn 
16608528186bSFlorian Hahn   for (const auto &Check : ExpandedChecks) {
16618528186bSFlorian Hahn     const PointerBounds &A = Check.first, &B = Check.second;
16628528186bSFlorian Hahn     // Check if two pointers (A and B) conflict where conflict is computed as:
16638528186bSFlorian Hahn     // start(A) <= end(B) && start(B) <= end(A)
16648528186bSFlorian Hahn     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
16658528186bSFlorian Hahn     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
16668528186bSFlorian Hahn 
16678528186bSFlorian Hahn     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
16688528186bSFlorian Hahn            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
16698528186bSFlorian Hahn            "Trying to bounds check pointers with different address spaces");
16708528186bSFlorian Hahn 
16718528186bSFlorian Hahn     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
16728528186bSFlorian Hahn     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
16738528186bSFlorian Hahn 
16748528186bSFlorian Hahn     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
16758528186bSFlorian Hahn     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
16768528186bSFlorian Hahn     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
16778528186bSFlorian Hahn     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
16788528186bSFlorian Hahn 
16798528186bSFlorian Hahn     // [A|B].Start points to the first accessed byte under base [A|B].
16808528186bSFlorian Hahn     // [A|B].End points to the last accessed byte, plus one.
16818528186bSFlorian Hahn     // There is no conflict when the intervals are disjoint:
16828528186bSFlorian Hahn     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
16838528186bSFlorian Hahn     //
16848528186bSFlorian Hahn     // bound0 = (B.Start < A.End)
16858528186bSFlorian Hahn     // bound1 = (A.Start < B.End)
16868528186bSFlorian Hahn     //  IsConflict = bound0 & bound1
16878528186bSFlorian Hahn     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
16888528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp0, Loc);
16898528186bSFlorian Hahn     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
16908528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp1, Loc);
16918528186bSFlorian Hahn     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16928528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
16938528186bSFlorian Hahn     if (MemoryRuntimeCheck) {
16948528186bSFlorian Hahn       IsConflict =
16958528186bSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
16968528186bSFlorian Hahn       FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
16978528186bSFlorian Hahn     }
16988528186bSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
16998528186bSFlorian Hahn   }
17008528186bSFlorian Hahn 
17018528186bSFlorian Hahn   if (!MemoryRuntimeCheck)
17028528186bSFlorian Hahn     return std::make_pair(nullptr, nullptr);
17038528186bSFlorian Hahn 
17048528186bSFlorian Hahn   // We have to do this trickery because the IRBuilder might fold the check to a
17058528186bSFlorian Hahn   // constant expression in which case there is no Instruction anchored in a
17068528186bSFlorian Hahn   // the block.
17078528186bSFlorian Hahn   Instruction *Check =
17088528186bSFlorian Hahn       BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx));
17098528186bSFlorian Hahn   ChkBuilder.Insert(Check, "memcheck.conflict");
17108528186bSFlorian Hahn   FirstInst = GetFirstInst(FirstInst, Check, Loc);
17118528186bSFlorian Hahn   return std::make_pair(FirstInst, Check);
17128528186bSFlorian Hahn }
1713