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"
52*bcbd26bfSFlorian 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";
6672448525SMichael Kruse 
674a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
6897468e92SAlina Sbirlea                                    MemorySSAUpdater *MSSAU,
694a000883SChandler Carruth                                    bool PreserveLCSSA) {
704a000883SChandler Carruth   bool Changed = false;
714a000883SChandler Carruth 
724a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
734a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
744a000883SChandler Carruth 
754a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
764a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
774a000883SChandler Carruth            "Must start with an empty predecessors list!");
784a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
794a000883SChandler Carruth 
804a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
814a000883SChandler Carruth     // keep track of the in-loop predecessors.
824a000883SChandler Carruth     bool IsDedicatedExit = true;
834a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
844a000883SChandler Carruth       if (L->contains(PredBB)) {
854a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
864a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
874a000883SChandler Carruth           return false;
88784929d0SCraig Topper         if (isa<CallBrInst>(PredBB->getTerminator()))
89784929d0SCraig Topper           // We cannot rewrite exiting edges from a callbr.
90784929d0SCraig Topper           return false;
914a000883SChandler Carruth 
924a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
934a000883SChandler Carruth       } else {
944a000883SChandler Carruth         IsDedicatedExit = false;
954a000883SChandler Carruth       }
964a000883SChandler Carruth 
974a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
984a000883SChandler Carruth 
994a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
1004a000883SChandler Carruth     if (IsDedicatedExit)
1014a000883SChandler Carruth       return false;
1024a000883SChandler Carruth 
1034a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
10497468e92SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
1054a000883SChandler Carruth 
1064a000883SChandler Carruth     if (!NewExitBB)
107d34e60caSNicola Zaghen       LLVM_DEBUG(
108d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
1094a000883SChandler Carruth                  << *L << "\n");
1104a000883SChandler Carruth     else
111d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
1124a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
1134a000883SChandler Carruth     return true;
1144a000883SChandler Carruth   };
1154a000883SChandler Carruth 
1164a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
1174a000883SChandler Carruth   // them, but only visit each one once.
1184a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
1194a000883SChandler Carruth   for (auto *BB : L->blocks())
1204a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
1214a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1224a000883SChandler Carruth       if (L->contains(SuccBB))
1234a000883SChandler Carruth         continue;
1244a000883SChandler Carruth 
1254a000883SChandler Carruth       // Visit each exit block exactly once.
1264a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1274a000883SChandler Carruth         continue;
1284a000883SChandler Carruth 
1294a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1304a000883SChandler Carruth     }
1314a000883SChandler Carruth 
1324a000883SChandler Carruth   return Changed;
1334a000883SChandler Carruth }
1344a000883SChandler Carruth 
1355f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
136c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
137c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
138c5b7b555SAshutosh Nema 
139c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
140c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
141c5b7b555SAshutosh Nema     // be adapted into a pointer.
142c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
143c5b7b555SAshutosh Nema       auto Users = Inst.users();
1440a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
145c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
146c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
147c5b7b555SAshutosh Nema           }))
148c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
149c5b7b555SAshutosh Nema     }
150c5b7b555SAshutosh Nema 
151c5b7b555SAshutosh Nema   return UsedOutside;
152c5b7b555SAshutosh Nema }
15331088a9dSChandler Carruth 
15431088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
15531088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
15631088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
15731088a9dSChandler Carruth   // pass manager, they must also preserve these.
15831088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
15931088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
16031088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
16131088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
16231088a9dSChandler Carruth 
16331088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
16431088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
16531088a9dSChandler Carruth   extern char &LoopSimplifyID;
16631088a9dSChandler Carruth   extern char &LCSSAID;
16731088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
16831088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
16931088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
17031088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
171c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
172c3ccf5d7SIgor Laevsky   // which preserve lcssa form
173c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
174c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
17531088a9dSChandler Carruth 
17631088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
17731088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
17831088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
17931088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
18031088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
18131088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
18231088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
18331088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
18431088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
18531088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
18631088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
18731088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
18831088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
18931088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
1906da79ce1SAlina Sbirlea   // FIXME: When all loop passes preserve MemorySSA, it can be required and
1916da79ce1SAlina Sbirlea   // preserved here instead of the individual handling in each pass.
19231088a9dSChandler Carruth }
19331088a9dSChandler Carruth 
19431088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
19531088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
19631088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
19731088a9dSChandler Carruth /// with:
19831088a9dSChandler Carruth ///
19931088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
20031088a9dSChandler Carruth ///
20131088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
20231088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
20331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
20431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
20531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
206e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
20731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
20831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
20931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
21031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
21131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2126da79ce1SAlina Sbirlea   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
21331088a9dSChandler Carruth }
214963341c8SAdam Nemet 
2153c3a7652SSerguei Katkov /// Create MDNode for input string.
2163c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2173c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2183c3a7652SSerguei Katkov   Metadata *MDs[] = {
2193c3a7652SSerguei Katkov       MDString::get(Context, Name),
2203c3a7652SSerguei Katkov       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2213c3a7652SSerguei Katkov   return MDNode::get(Context, MDs);
2223c3a7652SSerguei Katkov }
2233c3a7652SSerguei Katkov 
2243c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact.
2257f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is
2267f8c8095SSerguei Katkov /// different.
2277f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2283c3a7652SSerguei Katkov                                    unsigned V) {
2293c3a7652SSerguei Katkov   SmallVector<Metadata *, 4> MDs(1);
2303c3a7652SSerguei Katkov   // If the loop already has metadata, retain it.
2313c3a7652SSerguei Katkov   MDNode *LoopID = TheLoop->getLoopID();
2323c3a7652SSerguei Katkov   if (LoopID) {
2333c3a7652SSerguei Katkov     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2343c3a7652SSerguei Katkov       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2357f8c8095SSerguei Katkov       // If it is of form key = value, try to parse it.
2367f8c8095SSerguei Katkov       if (Node->getNumOperands() == 2) {
2377f8c8095SSerguei Katkov         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
2387f8c8095SSerguei Katkov         if (S && S->getString().equals(StringMD)) {
2397f8c8095SSerguei Katkov           ConstantInt *IntMD =
2407f8c8095SSerguei Katkov               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2417f8c8095SSerguei Katkov           if (IntMD && IntMD->getSExtValue() == V)
2427f8c8095SSerguei Katkov             // It is already in place. Do nothing.
2437f8c8095SSerguei Katkov             return;
2447f8c8095SSerguei Katkov           // We need to update the value, so just skip it here and it will
2457f8c8095SSerguei Katkov           // be added after copying other existed nodes.
2467f8c8095SSerguei Katkov           continue;
2477f8c8095SSerguei Katkov         }
2487f8c8095SSerguei Katkov       }
2493c3a7652SSerguei Katkov       MDs.push_back(Node);
2503c3a7652SSerguei Katkov     }
2513c3a7652SSerguei Katkov   }
2523c3a7652SSerguei Katkov   // Add new metadata.
2537f8c8095SSerguei Katkov   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2543c3a7652SSerguei Katkov   // Replace current metadata node with new one.
2553c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2563c3a7652SSerguei Katkov   MDNode *NewLoopID = MDNode::get(Context, MDs);
2573c3a7652SSerguei Katkov   // Set operand 0 to refer to the loop id itself.
2583c3a7652SSerguei Katkov   NewLoopID->replaceOperandWith(0, NewLoopID);
2593c3a7652SSerguei Katkov   TheLoop->setLoopID(NewLoopID);
2603c3a7652SSerguei Katkov }
2613c3a7652SSerguei Katkov 
26272448525SMichael Kruse /// Find string metadata for loop
26372448525SMichael Kruse ///
26472448525SMichael Kruse /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
26572448525SMichael Kruse /// operand or null otherwise.  If the string metadata is not found return
26672448525SMichael Kruse /// Optional's not-a-value.
267978ba615SMichael Kruse Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
26872448525SMichael Kruse                                                             StringRef Name) {
269978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
27072448525SMichael Kruse   if (!MD)
27172448525SMichael Kruse     return None;
272fe3def7cSAdam Nemet   switch (MD->getNumOperands()) {
273fe3def7cSAdam Nemet   case 1:
274fe3def7cSAdam Nemet     return nullptr;
275fe3def7cSAdam Nemet   case 2:
276fe3def7cSAdam Nemet     return &MD->getOperand(1);
277fe3def7cSAdam Nemet   default:
278fe3def7cSAdam Nemet     llvm_unreachable("loop metadata has 0 or 1 operand");
279963341c8SAdam Nemet   }
280fe3def7cSAdam Nemet }
28172448525SMichael Kruse 
28272448525SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
28372448525SMichael Kruse                                                    StringRef Name) {
284978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
285978ba615SMichael Kruse   if (!MD)
286fe3def7cSAdam Nemet     return None;
287978ba615SMichael Kruse   switch (MD->getNumOperands()) {
28872448525SMichael Kruse   case 1:
28972448525SMichael Kruse     // When the value is absent it is interpreted as 'attribute set'.
29072448525SMichael Kruse     return true;
29172448525SMichael Kruse   case 2:
292f9027e55SAlina Sbirlea     if (ConstantInt *IntMD =
293f9027e55SAlina Sbirlea             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
294f9027e55SAlina Sbirlea       return IntMD->getZExtValue();
295f9027e55SAlina Sbirlea     return true;
29672448525SMichael Kruse   }
29772448525SMichael Kruse   llvm_unreachable("unexpected number of options");
29872448525SMichael Kruse }
29972448525SMichael Kruse 
30072448525SMichael Kruse static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
30172448525SMichael Kruse   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
30272448525SMichael Kruse }
30372448525SMichael Kruse 
30472448525SMichael Kruse llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
30572448525SMichael Kruse                                                       StringRef Name) {
30672448525SMichael Kruse   const MDOperand *AttrMD =
30772448525SMichael Kruse       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
30872448525SMichael Kruse   if (!AttrMD)
30972448525SMichael Kruse     return None;
31072448525SMichael Kruse 
31172448525SMichael Kruse   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
31272448525SMichael Kruse   if (!IntMD)
31372448525SMichael Kruse     return None;
31472448525SMichael Kruse 
31572448525SMichael Kruse   return IntMD->getSExtValue();
31672448525SMichael Kruse }
31772448525SMichael Kruse 
31872448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
31972448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
32072448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
32172448525SMichael Kruse   if (!OrigLoopID) {
32272448525SMichael Kruse     if (AlwaysNew)
32372448525SMichael Kruse       return nullptr;
32472448525SMichael Kruse     return None;
32572448525SMichael Kruse   }
32672448525SMichael Kruse 
32772448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
32872448525SMichael Kruse 
32972448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
33072448525SMichael Kruse   bool InheritSomeAttrs =
33172448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
33272448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
33372448525SMichael Kruse   MDs.push_back(nullptr);
33472448525SMichael Kruse 
33572448525SMichael Kruse   bool Changed = false;
33672448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
33772448525SMichael Kruse     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
33872448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
33972448525SMichael Kruse 
34072448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
34172448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
34272448525SMichael Kruse         if (!InheritSomeAttrs)
34372448525SMichael Kruse           return false;
34472448525SMichael Kruse 
34572448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
34672448525SMichael Kruse         if (Op->getNumOperands() == 0)
34772448525SMichael Kruse           return true;
34872448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
34972448525SMichael Kruse         if (!isa<MDString>(NameMD))
35072448525SMichael Kruse           return true;
35172448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
35272448525SMichael Kruse 
35372448525SMichael Kruse         // Do not inherit excluded attributes.
35472448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
35572448525SMichael Kruse       };
35672448525SMichael Kruse 
35772448525SMichael Kruse       if (InheritThisAttribute(Op))
35872448525SMichael Kruse         MDs.push_back(Op);
35972448525SMichael Kruse       else
36072448525SMichael Kruse         Changed = true;
36172448525SMichael Kruse     }
36272448525SMichael Kruse   } else {
36372448525SMichael Kruse     // Modified if we dropped at least one attribute.
36472448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
36572448525SMichael Kruse   }
36672448525SMichael Kruse 
36772448525SMichael Kruse   bool HasAnyFollowup = false;
36872448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
369978ba615SMichael Kruse     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
37072448525SMichael Kruse     if (!FollowupNode)
37172448525SMichael Kruse       continue;
37272448525SMichael Kruse 
37372448525SMichael Kruse     HasAnyFollowup = true;
37472448525SMichael Kruse     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
37572448525SMichael Kruse       MDs.push_back(Option.get());
37672448525SMichael Kruse       Changed = true;
37772448525SMichael Kruse     }
37872448525SMichael Kruse   }
37972448525SMichael Kruse 
38072448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
38172448525SMichael Kruse   // transformation pass to add suitable attributes.
38272448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
38372448525SMichael Kruse     return None;
38472448525SMichael Kruse 
38572448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
38672448525SMichael Kruse   if (!AlwaysNew && !Changed)
38772448525SMichael Kruse     return OrigLoopID;
38872448525SMichael Kruse 
38972448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
39072448525SMichael Kruse   if (MDs.size() == 1)
39172448525SMichael Kruse     return nullptr;
39272448525SMichael Kruse 
39372448525SMichael Kruse   // Build the new loop ID.
39472448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
39572448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
39672448525SMichael Kruse   return FollowupLoopID;
39772448525SMichael Kruse }
39872448525SMichael Kruse 
39972448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
40072448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
40172448525SMichael Kruse }
40272448525SMichael Kruse 
4034f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
4044f64f1baSTim Corringham   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
4054f64f1baSTim Corringham }
4064f64f1baSTim Corringham 
40772448525SMichael Kruse TransformationMode llvm::hasUnrollTransformation(Loop *L) {
40872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
40972448525SMichael Kruse     return TM_SuppressedByUser;
41072448525SMichael Kruse 
41172448525SMichael Kruse   Optional<int> Count =
41272448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
41372448525SMichael Kruse   if (Count.hasValue())
41472448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
41572448525SMichael Kruse 
41672448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
41772448525SMichael Kruse     return TM_ForcedByUser;
41872448525SMichael Kruse 
41972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
42072448525SMichael Kruse     return TM_ForcedByUser;
42172448525SMichael Kruse 
42272448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
42372448525SMichael Kruse     return TM_Disable;
42472448525SMichael Kruse 
42572448525SMichael Kruse   return TM_Unspecified;
42672448525SMichael Kruse }
42772448525SMichael Kruse 
42872448525SMichael Kruse TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
42972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
43072448525SMichael Kruse     return TM_SuppressedByUser;
43172448525SMichael Kruse 
43272448525SMichael Kruse   Optional<int> Count =
43372448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
43472448525SMichael Kruse   if (Count.hasValue())
43572448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
43672448525SMichael Kruse 
43772448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
43872448525SMichael Kruse     return TM_ForcedByUser;
43972448525SMichael Kruse 
44072448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
44172448525SMichael Kruse     return TM_Disable;
44272448525SMichael Kruse 
44372448525SMichael Kruse   return TM_Unspecified;
44472448525SMichael Kruse }
44572448525SMichael Kruse 
44672448525SMichael Kruse TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
44772448525SMichael Kruse   Optional<bool> Enable =
44872448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
44972448525SMichael Kruse 
45072448525SMichael Kruse   if (Enable == false)
45172448525SMichael Kruse     return TM_SuppressedByUser;
45272448525SMichael Kruse 
45372448525SMichael Kruse   Optional<int> VectorizeWidth =
45472448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
45572448525SMichael Kruse   Optional<int> InterleaveCount =
45672448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
45772448525SMichael Kruse 
45872448525SMichael Kruse   // 'Forcing' vector width and interleave count to one effectively disables
45972448525SMichael Kruse   // this tranformation.
46070560a0aSMichael Kruse   if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
46172448525SMichael Kruse     return TM_SuppressedByUser;
46272448525SMichael Kruse 
46372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
46472448525SMichael Kruse     return TM_Disable;
46572448525SMichael Kruse 
46670560a0aSMichael Kruse   if (Enable == true)
46770560a0aSMichael Kruse     return TM_ForcedByUser;
46870560a0aSMichael Kruse 
46972448525SMichael Kruse   if (VectorizeWidth == 1 && InterleaveCount == 1)
47072448525SMichael Kruse     return TM_Disable;
47172448525SMichael Kruse 
47272448525SMichael Kruse   if (VectorizeWidth > 1 || InterleaveCount > 1)
47372448525SMichael Kruse     return TM_Enable;
47472448525SMichael Kruse 
47572448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
47672448525SMichael Kruse     return TM_Disable;
47772448525SMichael Kruse 
47872448525SMichael Kruse   return TM_Unspecified;
47972448525SMichael Kruse }
48072448525SMichael Kruse 
48172448525SMichael Kruse TransformationMode llvm::hasDistributeTransformation(Loop *L) {
48272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
48372448525SMichael Kruse     return TM_ForcedByUser;
48472448525SMichael Kruse 
48572448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
48672448525SMichael Kruse     return TM_Disable;
48772448525SMichael Kruse 
48872448525SMichael Kruse   return TM_Unspecified;
48972448525SMichael Kruse }
49072448525SMichael Kruse 
49172448525SMichael Kruse TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
49272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
49372448525SMichael Kruse     return TM_SuppressedByUser;
49472448525SMichael Kruse 
49572448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
49672448525SMichael Kruse     return TM_Disable;
49772448525SMichael Kruse 
49872448525SMichael Kruse   return TM_Unspecified;
499963341c8SAdam Nemet }
500122f984aSEvgeniy Stepanov 
5017ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
5027ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
5037ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
5047ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
5057ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
5067ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
5077ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
5087ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
5097ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
5107ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
5117ed5856aSAlina Sbirlea   };
5127ed5856aSAlina Sbirlea 
5137ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
5147ed5856aSAlina Sbirlea 
5157ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
5167ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
5177ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
5187ed5856aSAlina Sbirlea 
5197ed5856aSAlina Sbirlea   return Worklist;
5207ed5856aSAlina Sbirlea }
5217ed5856aSAlina Sbirlea 
522efb130fcSAlina Sbirlea void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
523efb130fcSAlina Sbirlea                           LoopInfo *LI, MemorySSA *MSSA) {
524899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
525df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
526df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
527df3e71e0SMarcello Maggioni 
528efb130fcSAlina Sbirlea   std::unique_ptr<MemorySSAUpdater> MSSAU;
529efb130fcSAlina Sbirlea   if (MSSA)
530efb130fcSAlina Sbirlea     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
531efb130fcSAlina Sbirlea 
532df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
533df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
534df3e71e0SMarcello Maggioni   //
535df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
536df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
537df3e71e0SMarcello Maggioni 
538df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
539df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
540df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
541df3e71e0SMarcello Maggioni   if (SE)
542df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
543df3e71e0SMarcello Maggioni 
544df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
545df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
546df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
547df3e71e0SMarcello Maggioni 
548df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
549df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
550df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
551df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
552df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
553df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
554df3e71e0SMarcello Maggioni   // preheader -> header.
555df3e71e0SMarcello Maggioni   //
556df3e71e0SMarcello Maggioni   //
557df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
558df3e71e0SMarcello Maggioni   //        |                    |   |                   |
559df3e71e0SMarcello Maggioni   //        V                    |   V                   |
560df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
561df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
562df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
563df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
564df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
565df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
566df3e71e0SMarcello Maggioni   //
567df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
568df3e71e0SMarcello Maggioni   // update without using the batch update API.
569df3e71e0SMarcello Maggioni   //
570df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
571df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
572df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
573df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
574df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
575df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
576df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
577df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
578df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
579df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
580df3e71e0SMarcello Maggioni 
581df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
582df3e71e0SMarcello Maggioni   // instead of the exiting block.
583c7fc81e6SBenjamin Kramer   for (PHINode &P : ExitBlock->phis()) {
584df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
585df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
586df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
587df3e71e0SMarcello Maggioni     int PredIndex = 0;
588c7fc81e6SBenjamin Kramer     P.setIncomingBlock(PredIndex, Preheader);
589df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
590df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
591df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
592df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
593df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
594df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
595df3e71e0SMarcello Maggioni     // being deleted).
596c7fc81e6SBenjamin Kramer     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
597c7fc81e6SBenjamin Kramer       P.removeIncomingValue(e - i, false);
598df3e71e0SMarcello Maggioni 
599c7fc81e6SBenjamin Kramer     assert((P.getNumIncomingValues() == 1 &&
600c7fc81e6SBenjamin Kramer             P.getIncomingBlock(PredIndex) == Preheader) &&
601df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
602df3e71e0SMarcello Maggioni   }
603df3e71e0SMarcello Maggioni 
604efb130fcSAlina Sbirlea   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
605efb130fcSAlina Sbirlea   if (DT) {
606efb130fcSAlina Sbirlea     DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
607efb130fcSAlina Sbirlea     if (MSSA) {
608efb130fcSAlina Sbirlea       MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT);
609efb130fcSAlina Sbirlea       if (VerifyMemorySSA)
610efb130fcSAlina Sbirlea         MSSA->verifyMemorySSA();
611efb130fcSAlina Sbirlea     }
612efb130fcSAlina Sbirlea   }
613efb130fcSAlina Sbirlea 
614df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
615df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
616df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
617df3e71e0SMarcello Maggioni   // Remove the old branch.
618df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
619df3e71e0SMarcello Maggioni 
620df3e71e0SMarcello Maggioni   if (DT) {
621efb130fcSAlina Sbirlea     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
622efb130fcSAlina Sbirlea     if (MSSA) {
623efb130fcSAlina Sbirlea       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
624efb130fcSAlina Sbirlea                           *DT);
625efb130fcSAlina Sbirlea       if (VerifyMemorySSA)
626efb130fcSAlina Sbirlea         MSSA->verifyMemorySSA();
627efb130fcSAlina Sbirlea       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
628efb130fcSAlina Sbirlea                                                    L->block_end());
629efb130fcSAlina Sbirlea       MSSAU->removeBlocks(DeadBlockSet);
630efb130fcSAlina Sbirlea     }
631df3e71e0SMarcello Maggioni   }
632df3e71e0SMarcello Maggioni 
633744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
6348ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
635744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
636744c3c32SDavide Italiano 
637a757d65cSSerguei Katkov   // Given LCSSA form is satisfied, we should not have users of instructions
638a757d65cSSerguei Katkov   // within the dead loop outside of the loop. However, LCSSA doesn't take
639a757d65cSSerguei Katkov   // unreachable uses into account. We handle them here.
640a757d65cSSerguei Katkov   // We could do it after drop all references (in this case all users in the
641a757d65cSSerguei Katkov   // loop will be already eliminated and we have less work to do but according
642a757d65cSSerguei Katkov   // to API doc of User::dropAllReferences only valid operation after dropping
643a757d65cSSerguei Katkov   // references, is deletion. So let's substitute all usages of
644a757d65cSSerguei Katkov   // instruction from the loop with undef value of corresponding type first.
645a757d65cSSerguei Katkov   for (auto *Block : L->blocks())
646a757d65cSSerguei Katkov     for (Instruction &I : *Block) {
647a757d65cSSerguei Katkov       auto *Undef = UndefValue::get(I.getType());
648a757d65cSSerguei Katkov       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
649a757d65cSSerguei Katkov         Use &U = *UI;
650a757d65cSSerguei Katkov         ++UI;
651a757d65cSSerguei Katkov         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
652a757d65cSSerguei Katkov           if (L->contains(Usr->getParent()))
653a757d65cSSerguei Katkov             continue;
654a757d65cSSerguei Katkov         // If we have a DT then we can check that uses outside a loop only in
655a757d65cSSerguei Katkov         // unreachable block.
656a757d65cSSerguei Katkov         if (DT)
657a757d65cSSerguei Katkov           assert(!DT->isReachableFromEntry(U) &&
658a757d65cSSerguei Katkov                  "Unexpected user in reachable block");
659a757d65cSSerguei Katkov         U.set(Undef);
660a757d65cSSerguei Katkov       }
661744c3c32SDavide Italiano       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
662744c3c32SDavide Italiano       if (!DVI)
663744c3c32SDavide Italiano         continue;
6648ee59ca6SDavide Italiano       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
6658ee59ca6SDavide Italiano       if (Key != DeadDebugSet.end())
666744c3c32SDavide Italiano         continue;
6678ee59ca6SDavide Italiano       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
668744c3c32SDavide Italiano       DeadDebugInst.push_back(DVI);
669a757d65cSSerguei Katkov     }
670a757d65cSSerguei Katkov 
671744c3c32SDavide Italiano   // After the loop has been deleted all the values defined and modified
672744c3c32SDavide Italiano   // inside the loop are going to be unavailable.
673744c3c32SDavide Italiano   // Since debug values in the loop have been deleted, inserting an undef
674744c3c32SDavide Italiano   // dbg.value truncates the range of any dbg.value before the loop where the
675744c3c32SDavide Italiano   // loop used to be. This is particularly important for constant values.
676744c3c32SDavide Italiano   DIBuilder DIB(*ExitBlock->getModule());
677e5be660eSRoman Lebedev   Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
678e5be660eSRoman Lebedev   assert(InsertDbgValueBefore &&
679e5be660eSRoman Lebedev          "There should be a non-PHI instruction in exit block, else these "
680e5be660eSRoman Lebedev          "instructions will have no parent.");
681744c3c32SDavide Italiano   for (auto *DVI : DeadDebugInst)
682e5be660eSRoman Lebedev     DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
683e5be660eSRoman Lebedev                                 DVI->getVariable(), DVI->getExpression(),
684e5be660eSRoman Lebedev                                 DVI->getDebugLoc(), InsertDbgValueBefore);
685744c3c32SDavide Italiano 
686df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
687df3e71e0SMarcello Maggioni   // delete it freely later.
688df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
689df3e71e0SMarcello Maggioni     Block->dropAllReferences();
690df3e71e0SMarcello Maggioni 
691efb130fcSAlina Sbirlea   if (MSSA && VerifyMemorySSA)
692efb130fcSAlina Sbirlea     MSSA->verifyMemorySSA();
693efb130fcSAlina Sbirlea 
694df3e71e0SMarcello Maggioni   if (LI) {
695df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
696df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
697df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
698df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
699df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
700df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
701df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
702df3e71e0SMarcello Maggioni 
703df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
704df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
705df3e71e0SMarcello Maggioni 
706df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
707df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
708df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
709df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
710df3e71e0SMarcello Maggioni 
711df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
7129883d7edSWhitney Tsang     // Note: LoopInfo::erase remove the given loop and relink its subloops with
7139883d7edSWhitney Tsang     // its parent. While removeLoop/removeChildLoop remove the given loop but
7149883d7edSWhitney Tsang     // not relink its subloops, which is what we want.
7159883d7edSWhitney Tsang     if (Loop *ParentLoop = L->getParentLoop()) {
7169883d7edSWhitney Tsang       Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L);
7179883d7edSWhitney Tsang       assert(I != ParentLoop->end() && "Couldn't find loop");
7189883d7edSWhitney Tsang       ParentLoop->removeChildLoop(I);
7199883d7edSWhitney Tsang     } else {
7209883d7edSWhitney Tsang       Loop::iterator I = find(LI->begin(), LI->end(), L);
7219883d7edSWhitney Tsang       assert(I != LI->end() && "Couldn't find loop");
7229883d7edSWhitney Tsang       LI->removeLoop(I);
7239883d7edSWhitney Tsang     }
7249883d7edSWhitney Tsang     LI->destroy(L);
725df3e71e0SMarcello Maggioni   }
726df3e71e0SMarcello Maggioni }
727df3e71e0SMarcello Maggioni 
728af7e1588SEvgeniy Brevnov /// Checks if \p L has single exit through latch block except possibly
729af7e1588SEvgeniy Brevnov /// "deoptimizing" exits. Returns branch instruction terminating the loop
730af7e1588SEvgeniy Brevnov /// latch if above check is successful, nullptr otherwise.
731af7e1588SEvgeniy Brevnov static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
73245c43e7dSSerguei Katkov   BasicBlock *Latch = L->getLoopLatch();
73345c43e7dSSerguei Katkov   if (!Latch)
734af7e1588SEvgeniy Brevnov     return nullptr;
735af7e1588SEvgeniy Brevnov 
73645c43e7dSSerguei Katkov   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
73745c43e7dSSerguei Katkov   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
738af7e1588SEvgeniy Brevnov     return nullptr;
73941d72a86SDehao Chen 
74041d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
74141d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
74241d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
74341d72a86SDehao Chen 
74445c43e7dSSerguei Katkov   SmallVector<BasicBlock *, 4> ExitBlocks;
74545c43e7dSSerguei Katkov   L->getUniqueNonLatchExitBlocks(ExitBlocks);
74645c43e7dSSerguei Katkov   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
74745c43e7dSSerguei Katkov         return !EB->getTerminatingDeoptimizeCall();
74845c43e7dSSerguei Katkov       }))
749af7e1588SEvgeniy Brevnov     return nullptr;
750af7e1588SEvgeniy Brevnov 
751af7e1588SEvgeniy Brevnov   return LatchBR;
752af7e1588SEvgeniy Brevnov }
753af7e1588SEvgeniy Brevnov 
754af7e1588SEvgeniy Brevnov Optional<unsigned>
755af7e1588SEvgeniy Brevnov llvm::getLoopEstimatedTripCount(Loop *L,
756af7e1588SEvgeniy Brevnov                                 unsigned *EstimatedLoopInvocationWeight) {
757af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
758af7e1588SEvgeniy Brevnov   // deoptimize.
759af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
760af7e1588SEvgeniy Brevnov   if (!LatchBranch)
76145c43e7dSSerguei Katkov     return None;
76245c43e7dSSerguei Katkov 
76341d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
76441d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
76541d72a86SDehao Chen   // we exited the loop.
766f0abe820SEvgeniy Brevnov   uint64_t BackedgeTakenWeight, LatchExitWeight;
767af7e1588SEvgeniy Brevnov   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
76841d72a86SDehao Chen     return None;
76941d72a86SDehao Chen 
770af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
771f0abe820SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
772f0abe820SEvgeniy Brevnov 
77310357e1cSEvgeniy Brevnov   if (!LatchExitWeight)
77410357e1cSEvgeniy Brevnov     return None;
77541d72a86SDehao Chen 
776af7e1588SEvgeniy Brevnov   if (EstimatedLoopInvocationWeight)
777af7e1588SEvgeniy Brevnov     *EstimatedLoopInvocationWeight = LatchExitWeight;
778af7e1588SEvgeniy Brevnov 
77910357e1cSEvgeniy Brevnov   // Estimated backedge taken count is a ratio of the backedge taken weight by
780cfe97681SEvgeniy Brevnov   // the weight of the edge exiting the loop, rounded to nearest.
78110357e1cSEvgeniy Brevnov   uint64_t BackedgeTakenCount =
78210357e1cSEvgeniy Brevnov       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
78310357e1cSEvgeniy Brevnov   // Estimated trip count is one plus estimated backedge taken count.
78410357e1cSEvgeniy Brevnov   return BackedgeTakenCount + 1;
78541d72a86SDehao Chen }
786cf9daa33SAmara Emerson 
787af7e1588SEvgeniy Brevnov bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
788af7e1588SEvgeniy Brevnov                                      unsigned EstimatedloopInvocationWeight) {
789af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
790af7e1588SEvgeniy Brevnov   // deoptimize.
791af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
792af7e1588SEvgeniy Brevnov   if (!LatchBranch)
793af7e1588SEvgeniy Brevnov     return false;
794af7e1588SEvgeniy Brevnov 
795af7e1588SEvgeniy Brevnov   // Calculate taken and exit weights.
796af7e1588SEvgeniy Brevnov   unsigned LatchExitWeight = 0;
797af7e1588SEvgeniy Brevnov   unsigned BackedgeTakenWeight = 0;
798af7e1588SEvgeniy Brevnov 
799af7e1588SEvgeniy Brevnov   if (EstimatedTripCount > 0) {
800af7e1588SEvgeniy Brevnov     LatchExitWeight = EstimatedloopInvocationWeight;
801af7e1588SEvgeniy Brevnov     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
802af7e1588SEvgeniy Brevnov   }
803af7e1588SEvgeniy Brevnov 
804af7e1588SEvgeniy Brevnov   // Make a swap if back edge is taken when condition is "false".
805af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
806af7e1588SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
807af7e1588SEvgeniy Brevnov 
808af7e1588SEvgeniy Brevnov   MDBuilder MDB(LatchBranch->getContext());
809af7e1588SEvgeniy Brevnov 
810af7e1588SEvgeniy Brevnov   // Set/Update profile metadata.
811af7e1588SEvgeniy Brevnov   LatchBranch->setMetadata(
812af7e1588SEvgeniy Brevnov       LLVMContext::MD_prof,
813af7e1588SEvgeniy Brevnov       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
814af7e1588SEvgeniy Brevnov 
815af7e1588SEvgeniy Brevnov   return true;
816af7e1588SEvgeniy Brevnov }
817af7e1588SEvgeniy Brevnov 
8186cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
819395b80cdSDavid Green                                               ScalarEvolution &SE) {
820395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
821395b80cdSDavid Green   if (!OuterL)
822395b80cdSDavid Green     return true;
823395b80cdSDavid Green 
824395b80cdSDavid Green   // Get the backedge taken count for the inner loop
825395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
826395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
827395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
828395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
829395b80cdSDavid Green     return false;
830395b80cdSDavid Green 
831395b80cdSDavid Green   // Get whether count is invariant to the outer loop
832395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
833395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
834395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
835395b80cdSDavid Green     return false;
836395b80cdSDavid Green 
837395b80cdSDavid Green   return true;
838395b80cdSDavid Green }
839395b80cdSDavid Green 
84028ffe38bSNikita Popov Value *llvm::createMinMaxOp(IRBuilderBase &Builder,
8416594dc37SVikram TV                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
8426594dc37SVikram TV                             Value *Left, Value *Right) {
8436594dc37SVikram TV   CmpInst::Predicate P = CmpInst::ICMP_NE;
8446594dc37SVikram TV   switch (RK) {
8456594dc37SVikram TV   default:
8466594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
8476594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMin:
8486594dc37SVikram TV     P = CmpInst::ICMP_ULT;
8496594dc37SVikram TV     break;
8506594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMax:
8516594dc37SVikram TV     P = CmpInst::ICMP_UGT;
8526594dc37SVikram TV     break;
8536594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMin:
8546594dc37SVikram TV     P = CmpInst::ICMP_SLT;
8556594dc37SVikram TV     break;
8566594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMax:
8576594dc37SVikram TV     P = CmpInst::ICMP_SGT;
8586594dc37SVikram TV     break;
8596594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMin:
8606594dc37SVikram TV     P = CmpInst::FCMP_OLT;
8616594dc37SVikram TV     break;
8626594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMax:
8636594dc37SVikram TV     P = CmpInst::FCMP_OGT;
8646594dc37SVikram TV     break;
8656594dc37SVikram TV   }
8666594dc37SVikram TV 
8676594dc37SVikram TV   // We only match FP sequences that are 'fast', so we can unconditionally
8686594dc37SVikram TV   // set it on any generated instructions.
86928ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFG(Builder);
8706594dc37SVikram TV   FastMathFlags FMF;
8716594dc37SVikram TV   FMF.setFast();
8726594dc37SVikram TV   Builder.setFastMathFlags(FMF);
8736594dc37SVikram TV 
8746594dc37SVikram TV   Value *Cmp;
8756594dc37SVikram TV   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
8766594dc37SVikram TV       RK == RecurrenceDescriptor::MRK_FloatMax)
8776594dc37SVikram TV     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
8786594dc37SVikram TV   else
8796594dc37SVikram TV     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
8806594dc37SVikram TV 
8816594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
8826594dc37SVikram TV   return Select;
8836594dc37SVikram TV }
8846594dc37SVikram TV 
88523c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
88623c2182cSSimon Pilgrim Value *
88728ffe38bSNikita Popov llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
88823c2182cSSimon Pilgrim                           unsigned Op,
88923c2182cSSimon Pilgrim                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
89023c2182cSSimon Pilgrim                           ArrayRef<Value *> RedOps) {
89100a10324SChristopher Tetreault   unsigned VF = cast<VectorType>(Src->getType())->getNumElements();
89223c2182cSSimon Pilgrim 
89323c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
89423c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
89523c2182cSSimon Pilgrim   Value *Result = Acc;
89623c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
89723c2182cSSimon Pilgrim     Value *Ext =
89823c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
89923c2182cSSimon Pilgrim 
90023c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
90123c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
90223c2182cSSimon Pilgrim                                    "bin.rdx");
90323c2182cSSimon Pilgrim     } else {
90423c2182cSSimon Pilgrim       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
90523c2182cSSimon Pilgrim              "Invalid min/max");
9066594dc37SVikram TV       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
90723c2182cSSimon Pilgrim     }
90823c2182cSSimon Pilgrim 
90923c2182cSSimon Pilgrim     if (!RedOps.empty())
91023c2182cSSimon Pilgrim       propagateIRFlags(Result, RedOps);
91123c2182cSSimon Pilgrim   }
91223c2182cSSimon Pilgrim 
91323c2182cSSimon Pilgrim   return Result;
91423c2182cSSimon Pilgrim }
91523c2182cSSimon Pilgrim 
916cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
917836b0f48SAmara Emerson Value *
91828ffe38bSNikita Popov llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
919836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
920ad62a3a2SSanjay Patel                           ArrayRef<Value *> RedOps) {
92100a10324SChristopher Tetreault   unsigned VF = cast<VectorType>(Src->getType())->getNumElements();
922cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
923cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
924cf9daa33SAmara Emerson   // round.
925cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
926cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
927cf9daa33SAmara Emerson   Value *TmpVec = Src;
9286f64dacaSBenjamin Kramer   SmallVector<int, 32> ShuffleMask(VF);
929cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
930cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
931cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
9326f64dacaSBenjamin Kramer       ShuffleMask[j] = i / 2 + j;
933cf9daa33SAmara Emerson 
934cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
9356f64dacaSBenjamin Kramer     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
936cf9daa33SAmara Emerson 
937cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
9386f64dacaSBenjamin Kramer         TmpVec, UndefValue::get(TmpVec->getType()), ShuffleMask, "rdx.shuf");
939cf9daa33SAmara Emerson 
940cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
941ad62a3a2SSanjay Patel       // The builder propagates its fast-math-flags setting.
942ad62a3a2SSanjay Patel       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
943ad62a3a2SSanjay Patel                                    "bin.rdx");
944cf9daa33SAmara Emerson     } else {
945cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
946cf9daa33SAmara Emerson              "Invalid min/max");
9476594dc37SVikram TV       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
948cf9daa33SAmara Emerson     }
949cf9daa33SAmara Emerson     if (!RedOps.empty())
950cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
951bc1148e7SSanjay Patel 
952bc1148e7SSanjay Patel     // We may compute the reassociated scalar ops in a way that does not
953bc1148e7SSanjay Patel     // preserve nsw/nuw etc. Conservatively, drop those flags.
954bc1148e7SSanjay Patel     if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec))
955bc1148e7SSanjay Patel       ReductionInst->dropPoisonGeneratingFlags();
956cf9daa33SAmara Emerson   }
957cf9daa33SAmara Emerson   // The result is in the first element of the vector.
958cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
959cf9daa33SAmara Emerson }
960cf9daa33SAmara Emerson 
961cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
962cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
963cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
96428ffe38bSNikita Popov     IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
965ad62a3a2SSanjay Patel     Value *Src, TargetTransformInfo::ReductionFlags Flags,
966cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
96700a10324SChristopher Tetreault   auto *SrcVTy = cast<VectorType>(Src->getType());
968cf9daa33SAmara Emerson 
969cf9daa33SAmara Emerson   std::function<Value *()> BuildFunc;
970cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
971cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
972cf9daa33SAmara Emerson 
973cf9daa33SAmara Emerson   switch (Opcode) {
974cf9daa33SAmara Emerson   case Instruction::Add:
975cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
976cf9daa33SAmara Emerson     break;
977cf9daa33SAmara Emerson   case Instruction::Mul:
978cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
979cf9daa33SAmara Emerson     break;
980cf9daa33SAmara Emerson   case Instruction::And:
981cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
982cf9daa33SAmara Emerson     break;
983cf9daa33SAmara Emerson   case Instruction::Or:
984cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
985cf9daa33SAmara Emerson     break;
986cf9daa33SAmara Emerson   case Instruction::Xor:
987cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
988cf9daa33SAmara Emerson     break;
989cf9daa33SAmara Emerson   case Instruction::FAdd:
990cf9daa33SAmara Emerson     BuildFunc = [&]() {
991cbeb563cSSander de Smalen       auto Rdx = Builder.CreateFAddReduce(
99200a10324SChristopher Tetreault           Constant::getNullValue(SrcVTy->getElementType()), Src);
993cf9daa33SAmara Emerson       return Rdx;
994cf9daa33SAmara Emerson     };
995cf9daa33SAmara Emerson     break;
996cf9daa33SAmara Emerson   case Instruction::FMul:
997cf9daa33SAmara Emerson     BuildFunc = [&]() {
99800a10324SChristopher Tetreault       Type *Ty = SrcVTy->getElementType();
999cbeb563cSSander de Smalen       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
1000cf9daa33SAmara Emerson       return Rdx;
1001cf9daa33SAmara Emerson     };
1002cf9daa33SAmara Emerson     break;
1003cf9daa33SAmara Emerson   case Instruction::ICmp:
1004cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1005cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1006cf9daa33SAmara Emerson       BuildFunc = [&]() {
1007cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1008cf9daa33SAmara Emerson       };
1009cf9daa33SAmara Emerson     } else {
1010cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1011cf9daa33SAmara Emerson       BuildFunc = [&]() {
1012cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1013cf9daa33SAmara Emerson       };
1014cf9daa33SAmara Emerson     }
1015cf9daa33SAmara Emerson     break;
1016cf9daa33SAmara Emerson   case Instruction::FCmp:
1017cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1018cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1019cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1020cf9daa33SAmara Emerson     } else {
1021cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1022cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1023cf9daa33SAmara Emerson     }
1024cf9daa33SAmara Emerson     break;
1025cf9daa33SAmara Emerson   default:
1026cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1027cf9daa33SAmara Emerson     break;
1028cf9daa33SAmara Emerson   }
1029ec7e4a9aSDavid Green   if (ForceReductionIntrinsic ||
1030ec7e4a9aSDavid Green       TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1031cf9daa33SAmara Emerson     return BuildFunc();
1032ad62a3a2SSanjay Patel   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1033cf9daa33SAmara Emerson }
1034cf9daa33SAmara Emerson 
1035cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
103628ffe38bSNikita Popov Value *llvm::createTargetReduction(IRBuilderBase &B,
1037cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1038cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1039cf9daa33SAmara Emerson                                    bool NoNaN) {
1040cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
10413e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
10423e069f57SSanjay Patel   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1043cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1044cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1045ad62a3a2SSanjay Patel 
1046ad62a3a2SSanjay Patel   // All ops in the reduction inherit fast-math-flags from the recurrence
1047ad62a3a2SSanjay Patel   // descriptor.
104828ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1049ad62a3a2SSanjay Patel   B.setFastMathFlags(Desc.getFastMathFlags());
1050ad62a3a2SSanjay Patel 
1051cf9daa33SAmara Emerson   switch (RecKind) {
10523e069f57SSanjay Patel   case RD::RK_FloatAdd:
1053ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
10543e069f57SSanjay Patel   case RD::RK_FloatMult:
1055ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
10563e069f57SSanjay Patel   case RD::RK_IntegerAdd:
1057ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
10583e069f57SSanjay Patel   case RD::RK_IntegerMult:
1059ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
10603e069f57SSanjay Patel   case RD::RK_IntegerAnd:
1061ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
10623e069f57SSanjay Patel   case RD::RK_IntegerOr:
1063ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
10643e069f57SSanjay Patel   case RD::RK_IntegerXor:
1065ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
10663e069f57SSanjay Patel   case RD::RK_IntegerMinMax: {
10673e069f57SSanjay Patel     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
10683e069f57SSanjay Patel     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
10693e069f57SSanjay Patel     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1070ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1071cf9daa33SAmara Emerson   }
10723e069f57SSanjay Patel   case RD::RK_FloatMinMax: {
10733e069f57SSanjay Patel     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
1074ad62a3a2SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1075cf9daa33SAmara Emerson   }
1076cf9daa33SAmara Emerson   default:
1077cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
1078cf9daa33SAmara Emerson   }
1079cf9daa33SAmara Emerson }
1080cf9daa33SAmara Emerson 
1081a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1082a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1083a61f4b89SDinar Temirbulatov   if (!VecOp)
1084a61f4b89SDinar Temirbulatov     return;
1085a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1086a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1087a61f4b89SDinar Temirbulatov   if (!Intersection)
1088a61f4b89SDinar Temirbulatov     return;
1089a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1090a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1091a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1092a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1093a61f4b89SDinar Temirbulatov     if (!Instr)
1094a61f4b89SDinar Temirbulatov       continue;
1095a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1096a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1097cf9daa33SAmara Emerson   }
1098cf9daa33SAmara Emerson }
1099a78dc4d6SMax Kazantsev 
1100a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1101a78dc4d6SMax Kazantsev                                  ScalarEvolution &SE) {
1102a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1103a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1104a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1105a78dc4d6SMax Kazantsev }
1106a78dc4d6SMax Kazantsev 
1107a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1108a78dc4d6SMax Kazantsev                                     ScalarEvolution &SE) {
1109a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1110a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1111a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1112a78dc4d6SMax Kazantsev }
1113a78dc4d6SMax Kazantsev 
1114a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1115a78dc4d6SMax Kazantsev                              bool Signed) {
1116a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1117a78dc4d6SMax Kazantsev   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1118a78dc4d6SMax Kazantsev     APInt::getMinValue(BitWidth);
1119a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1120a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1121a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1122a78dc4d6SMax Kazantsev                                      SE.getConstant(Min));
1123a78dc4d6SMax Kazantsev }
1124a78dc4d6SMax Kazantsev 
1125a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1126a78dc4d6SMax Kazantsev                              bool Signed) {
1127a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1128a78dc4d6SMax Kazantsev   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1129a78dc4d6SMax Kazantsev     APInt::getMaxValue(BitWidth);
1130a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1131a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1132a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1133a78dc4d6SMax Kazantsev                                      SE.getConstant(Max));
1134a78dc4d6SMax Kazantsev }
113593175a5cSSjoerd Meijer 
113693175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
113793175a5cSSjoerd Meijer // rewriteLoopExitValues - Optimize IV users outside the loop.
113893175a5cSSjoerd Meijer // As a side effect, reduces the amount of IV processing within the loop.
113993175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
114093175a5cSSjoerd Meijer 
114193175a5cSSjoerd Meijer // Return true if the SCEV expansion generated by the rewriter can replace the
114293175a5cSSjoerd Meijer // original value. SCEV guarantees that it produces the same value, but the way
114393175a5cSSjoerd Meijer // it is produced may be illegal IR.  Ideally, this function will only be
114493175a5cSSjoerd Meijer // called for verification.
114593175a5cSSjoerd Meijer static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
114693175a5cSSjoerd Meijer   // If an SCEV expression subsumed multiple pointers, its expansion could
114793175a5cSSjoerd Meijer   // reassociate the GEP changing the base pointer. This is illegal because the
114893175a5cSSjoerd Meijer   // final address produced by a GEP chain must be inbounds relative to its
114993175a5cSSjoerd Meijer   // underlying object. Otherwise basic alias analysis, among other things,
115093175a5cSSjoerd Meijer   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
115193175a5cSSjoerd Meijer   // producing an expression involving multiple pointers. Until then, we must
115293175a5cSSjoerd Meijer   // bail out here.
115393175a5cSSjoerd Meijer   //
115493175a5cSSjoerd Meijer   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
115593175a5cSSjoerd Meijer   // because it understands lcssa phis while SCEV does not.
115693175a5cSSjoerd Meijer   Value *FromPtr = FromVal;
115793175a5cSSjoerd Meijer   Value *ToPtr = ToVal;
115893175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
115993175a5cSSjoerd Meijer     FromPtr = GEP->getPointerOperand();
116093175a5cSSjoerd Meijer 
116193175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
116293175a5cSSjoerd Meijer     ToPtr = GEP->getPointerOperand();
116393175a5cSSjoerd Meijer 
116493175a5cSSjoerd Meijer   if (FromPtr != FromVal || ToPtr != ToVal) {
116593175a5cSSjoerd Meijer     // Quickly check the common case
116693175a5cSSjoerd Meijer     if (FromPtr == ToPtr)
116793175a5cSSjoerd Meijer       return true;
116893175a5cSSjoerd Meijer 
116993175a5cSSjoerd Meijer     // SCEV may have rewritten an expression that produces the GEP's pointer
117093175a5cSSjoerd Meijer     // operand. That's ok as long as the pointer operand has the same base
117193175a5cSSjoerd Meijer     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
117293175a5cSSjoerd Meijer     // base of a recurrence. This handles the case in which SCEV expansion
117393175a5cSSjoerd Meijer     // converts a pointer type recurrence into a nonrecurrent pointer base
117493175a5cSSjoerd Meijer     // indexed by an integer recurrence.
117593175a5cSSjoerd Meijer 
117693175a5cSSjoerd Meijer     // If the GEP base pointer is a vector of pointers, abort.
117793175a5cSSjoerd Meijer     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
117893175a5cSSjoerd Meijer       return false;
117993175a5cSSjoerd Meijer 
118093175a5cSSjoerd Meijer     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
118193175a5cSSjoerd Meijer     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
118293175a5cSSjoerd Meijer     if (FromBase == ToBase)
118393175a5cSSjoerd Meijer       return true;
118493175a5cSSjoerd Meijer 
118593175a5cSSjoerd Meijer     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
118693175a5cSSjoerd Meijer                       << *FromBase << " != " << *ToBase << "\n");
118793175a5cSSjoerd Meijer 
118893175a5cSSjoerd Meijer     return false;
118993175a5cSSjoerd Meijer   }
119093175a5cSSjoerd Meijer   return true;
119193175a5cSSjoerd Meijer }
119293175a5cSSjoerd Meijer 
119393175a5cSSjoerd Meijer static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
119493175a5cSSjoerd Meijer   SmallPtrSet<const Instruction *, 8> Visited;
119593175a5cSSjoerd Meijer   SmallVector<const Instruction *, 8> WorkList;
119693175a5cSSjoerd Meijer   Visited.insert(I);
119793175a5cSSjoerd Meijer   WorkList.push_back(I);
119893175a5cSSjoerd Meijer   while (!WorkList.empty()) {
119993175a5cSSjoerd Meijer     const Instruction *Curr = WorkList.pop_back_val();
120093175a5cSSjoerd Meijer     // This use is outside the loop, nothing to do.
120193175a5cSSjoerd Meijer     if (!L->contains(Curr))
120293175a5cSSjoerd Meijer       continue;
120393175a5cSSjoerd Meijer     // Do we assume it is a "hard" use which will not be eliminated easily?
120493175a5cSSjoerd Meijer     if (Curr->mayHaveSideEffects())
120593175a5cSSjoerd Meijer       return true;
120693175a5cSSjoerd Meijer     // Otherwise, add all its users to worklist.
120793175a5cSSjoerd Meijer     for (auto U : Curr->users()) {
120893175a5cSSjoerd Meijer       auto *UI = cast<Instruction>(U);
120993175a5cSSjoerd Meijer       if (Visited.insert(UI).second)
121093175a5cSSjoerd Meijer         WorkList.push_back(UI);
121193175a5cSSjoerd Meijer     }
121293175a5cSSjoerd Meijer   }
121393175a5cSSjoerd Meijer   return false;
121493175a5cSSjoerd Meijer }
121593175a5cSSjoerd Meijer 
121693175a5cSSjoerd Meijer // Collect information about PHI nodes which can be transformed in
121793175a5cSSjoerd Meijer // rewriteLoopExitValues.
121893175a5cSSjoerd Meijer struct RewritePhi {
121993175a5cSSjoerd Meijer   PHINode *PN;
122093175a5cSSjoerd Meijer   unsigned Ith;   // Ith incoming value.
122193175a5cSSjoerd Meijer   Value *Val;     // Exit value after expansion.
122293175a5cSSjoerd Meijer   bool HighCost;  // High Cost when expansion.
122393175a5cSSjoerd Meijer 
122493175a5cSSjoerd Meijer   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
122593175a5cSSjoerd Meijer       : PN(P), Ith(I), Val(V), HighCost(H) {}
122693175a5cSSjoerd Meijer };
122793175a5cSSjoerd Meijer 
122893175a5cSSjoerd Meijer // Check whether it is possible to delete the loop after rewriting exit
122993175a5cSSjoerd Meijer // value. If it is possible, ignore ReplaceExitValue and do rewriting
123093175a5cSSjoerd Meijer // aggressively.
123193175a5cSSjoerd Meijer static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
123293175a5cSSjoerd Meijer   BasicBlock *Preheader = L->getLoopPreheader();
123393175a5cSSjoerd Meijer   // If there is no preheader, the loop will not be deleted.
123493175a5cSSjoerd Meijer   if (!Preheader)
123593175a5cSSjoerd Meijer     return false;
123693175a5cSSjoerd Meijer 
123793175a5cSSjoerd Meijer   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
123893175a5cSSjoerd Meijer   // We obviate multiple ExitingBlocks case for simplicity.
123993175a5cSSjoerd Meijer   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
124093175a5cSSjoerd Meijer   // after exit value rewriting, we can enhance the logic here.
124193175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 4> ExitingBlocks;
124293175a5cSSjoerd Meijer   L->getExitingBlocks(ExitingBlocks);
124393175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 8> ExitBlocks;
124493175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
124593175a5cSSjoerd Meijer   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
124693175a5cSSjoerd Meijer     return false;
124793175a5cSSjoerd Meijer 
124893175a5cSSjoerd Meijer   BasicBlock *ExitBlock = ExitBlocks[0];
124993175a5cSSjoerd Meijer   BasicBlock::iterator BI = ExitBlock->begin();
125093175a5cSSjoerd Meijer   while (PHINode *P = dyn_cast<PHINode>(BI)) {
125193175a5cSSjoerd Meijer     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
125293175a5cSSjoerd Meijer 
125393175a5cSSjoerd Meijer     // If the Incoming value of P is found in RewritePhiSet, we know it
125493175a5cSSjoerd Meijer     // could be rewritten to use a loop invariant value in transformation
125593175a5cSSjoerd Meijer     // phase later. Skip it in the loop invariant check below.
125693175a5cSSjoerd Meijer     bool found = false;
125793175a5cSSjoerd Meijer     for (const RewritePhi &Phi : RewritePhiSet) {
125893175a5cSSjoerd Meijer       unsigned i = Phi.Ith;
125993175a5cSSjoerd Meijer       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
126093175a5cSSjoerd Meijer         found = true;
126193175a5cSSjoerd Meijer         break;
126293175a5cSSjoerd Meijer       }
126393175a5cSSjoerd Meijer     }
126493175a5cSSjoerd Meijer 
126593175a5cSSjoerd Meijer     Instruction *I;
126693175a5cSSjoerd Meijer     if (!found && (I = dyn_cast<Instruction>(Incoming)))
126793175a5cSSjoerd Meijer       if (!L->hasLoopInvariantOperands(I))
126893175a5cSSjoerd Meijer         return false;
126993175a5cSSjoerd Meijer 
127093175a5cSSjoerd Meijer     ++BI;
127193175a5cSSjoerd Meijer   }
127293175a5cSSjoerd Meijer 
127393175a5cSSjoerd Meijer   for (auto *BB : L->blocks())
127493175a5cSSjoerd Meijer     if (llvm::any_of(*BB, [](Instruction &I) {
127593175a5cSSjoerd Meijer           return I.mayHaveSideEffects();
127693175a5cSSjoerd Meijer         }))
127793175a5cSSjoerd Meijer       return false;
127893175a5cSSjoerd Meijer 
127993175a5cSSjoerd Meijer   return true;
128093175a5cSSjoerd Meijer }
128193175a5cSSjoerd Meijer 
12820789f280SRoman Lebedev int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
12830789f280SRoman Lebedev                                 ScalarEvolution *SE,
12840789f280SRoman Lebedev                                 const TargetTransformInfo *TTI,
12850789f280SRoman Lebedev                                 SCEVExpander &Rewriter, DominatorTree *DT,
12860789f280SRoman Lebedev                                 ReplaceExitVal ReplaceExitValue,
128793175a5cSSjoerd Meijer                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
128893175a5cSSjoerd Meijer   // Check a pre-condition.
128993175a5cSSjoerd Meijer   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
129093175a5cSSjoerd Meijer          "Indvars did not preserve LCSSA!");
129193175a5cSSjoerd Meijer 
129293175a5cSSjoerd Meijer   SmallVector<BasicBlock*, 8> ExitBlocks;
129393175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
129493175a5cSSjoerd Meijer 
129593175a5cSSjoerd Meijer   SmallVector<RewritePhi, 8> RewritePhiSet;
129693175a5cSSjoerd Meijer   // Find all values that are computed inside the loop, but used outside of it.
129793175a5cSSjoerd Meijer   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
129893175a5cSSjoerd Meijer   // the exit blocks of the loop to find them.
129993175a5cSSjoerd Meijer   for (BasicBlock *ExitBB : ExitBlocks) {
130093175a5cSSjoerd Meijer     // If there are no PHI nodes in this exit block, then no values defined
130193175a5cSSjoerd Meijer     // inside the loop are used on this path, skip it.
130293175a5cSSjoerd Meijer     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
130393175a5cSSjoerd Meijer     if (!PN) continue;
130493175a5cSSjoerd Meijer 
130593175a5cSSjoerd Meijer     unsigned NumPreds = PN->getNumIncomingValues();
130693175a5cSSjoerd Meijer 
130793175a5cSSjoerd Meijer     // Iterate over all of the PHI nodes.
130893175a5cSSjoerd Meijer     BasicBlock::iterator BBI = ExitBB->begin();
130993175a5cSSjoerd Meijer     while ((PN = dyn_cast<PHINode>(BBI++))) {
131093175a5cSSjoerd Meijer       if (PN->use_empty())
131193175a5cSSjoerd Meijer         continue; // dead use, don't replace it
131293175a5cSSjoerd Meijer 
131393175a5cSSjoerd Meijer       if (!SE->isSCEVable(PN->getType()))
131493175a5cSSjoerd Meijer         continue;
131593175a5cSSjoerd Meijer 
131693175a5cSSjoerd Meijer       // It's necessary to tell ScalarEvolution about this explicitly so that
131793175a5cSSjoerd Meijer       // it can walk the def-use list and forget all SCEVs, as it may not be
131893175a5cSSjoerd Meijer       // watching the PHI itself. Once the new exit value is in place, there
131993175a5cSSjoerd Meijer       // may not be a def-use connection between the loop and every instruction
132093175a5cSSjoerd Meijer       // which got a SCEVAddRecExpr for that loop.
132193175a5cSSjoerd Meijer       SE->forgetValue(PN);
132293175a5cSSjoerd Meijer 
132393175a5cSSjoerd Meijer       // Iterate over all of the values in all the PHI nodes.
132493175a5cSSjoerd Meijer       for (unsigned i = 0; i != NumPreds; ++i) {
132593175a5cSSjoerd Meijer         // If the value being merged in is not integer or is not defined
132693175a5cSSjoerd Meijer         // in the loop, skip it.
132793175a5cSSjoerd Meijer         Value *InVal = PN->getIncomingValue(i);
132893175a5cSSjoerd Meijer         if (!isa<Instruction>(InVal))
132993175a5cSSjoerd Meijer           continue;
133093175a5cSSjoerd Meijer 
133193175a5cSSjoerd Meijer         // If this pred is for a subloop, not L itself, skip it.
133293175a5cSSjoerd Meijer         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
133393175a5cSSjoerd Meijer           continue; // The Block is in a subloop, skip it.
133493175a5cSSjoerd Meijer 
133593175a5cSSjoerd Meijer         // Check that InVal is defined in the loop.
133693175a5cSSjoerd Meijer         Instruction *Inst = cast<Instruction>(InVal);
133793175a5cSSjoerd Meijer         if (!L->contains(Inst))
133893175a5cSSjoerd Meijer           continue;
133993175a5cSSjoerd Meijer 
134093175a5cSSjoerd Meijer         // Okay, this instruction has a user outside of the current loop
134193175a5cSSjoerd Meijer         // and varies predictably *inside* the loop.  Evaluate the value it
134293175a5cSSjoerd Meijer         // contains when the loop exits, if possible.  We prefer to start with
134393175a5cSSjoerd Meijer         // expressions which are true for all exits (so as to maximize
134493175a5cSSjoerd Meijer         // expression reuse by the SCEVExpander), but resort to per-exit
134593175a5cSSjoerd Meijer         // evaluation if that fails.
134693175a5cSSjoerd Meijer         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
134793175a5cSSjoerd Meijer         if (isa<SCEVCouldNotCompute>(ExitValue) ||
134893175a5cSSjoerd Meijer             !SE->isLoopInvariant(ExitValue, L) ||
134993175a5cSSjoerd Meijer             !isSafeToExpand(ExitValue, *SE)) {
135093175a5cSSjoerd Meijer           // TODO: This should probably be sunk into SCEV in some way; maybe a
135193175a5cSSjoerd Meijer           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
135293175a5cSSjoerd Meijer           // most SCEV expressions and other recurrence types (e.g. shift
135393175a5cSSjoerd Meijer           // recurrences).  Is there existing code we can reuse?
135493175a5cSSjoerd Meijer           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
135593175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitCount))
135693175a5cSSjoerd Meijer             continue;
135793175a5cSSjoerd Meijer           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
135893175a5cSSjoerd Meijer             if (AddRec->getLoop() == L)
135993175a5cSSjoerd Meijer               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
136093175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitValue) ||
136193175a5cSSjoerd Meijer               !SE->isLoopInvariant(ExitValue, L) ||
136293175a5cSSjoerd Meijer               !isSafeToExpand(ExitValue, *SE))
136393175a5cSSjoerd Meijer             continue;
136493175a5cSSjoerd Meijer         }
136593175a5cSSjoerd Meijer 
136693175a5cSSjoerd Meijer         // Computing the value outside of the loop brings no benefit if it is
136793175a5cSSjoerd Meijer         // definitely used inside the loop in a way which can not be optimized
13687d572ef2SRoman Lebedev         // away. Avoid doing so unless we know we have a value which computes
13697d572ef2SRoman Lebedev         // the ExitValue already. TODO: This should be merged into SCEV
13707d572ef2SRoman Lebedev         // expander to leverage its knowledge of existing expressions.
13717d572ef2SRoman Lebedev         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
13727d572ef2SRoman Lebedev             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
137393175a5cSSjoerd Meijer           continue;
137493175a5cSSjoerd Meijer 
13757d572ef2SRoman Lebedev         bool HighCost = Rewriter.isHighCostExpansion(
13767d572ef2SRoman Lebedev             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
137793175a5cSSjoerd Meijer         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
137893175a5cSSjoerd Meijer 
137993175a5cSSjoerd Meijer         LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
138093175a5cSSjoerd Meijer                           << *ExitVal << '\n' << "  LoopVal = " << *Inst
138193175a5cSSjoerd Meijer                           << "\n");
138293175a5cSSjoerd Meijer 
138393175a5cSSjoerd Meijer         if (!isValidRewrite(SE, Inst, ExitVal)) {
138493175a5cSSjoerd Meijer           DeadInsts.push_back(ExitVal);
138593175a5cSSjoerd Meijer           continue;
138693175a5cSSjoerd Meijer         }
138793175a5cSSjoerd Meijer 
138893175a5cSSjoerd Meijer #ifndef NDEBUG
138993175a5cSSjoerd Meijer         // If we reuse an instruction from a loop which is neither L nor one of
139093175a5cSSjoerd Meijer         // its containing loops, we end up breaking LCSSA form for this loop by
139193175a5cSSjoerd Meijer         // creating a new use of its instruction.
139293175a5cSSjoerd Meijer         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
139393175a5cSSjoerd Meijer           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
139493175a5cSSjoerd Meijer             if (EVL != L)
139593175a5cSSjoerd Meijer               assert(EVL->contains(L) && "LCSSA breach detected!");
139693175a5cSSjoerd Meijer #endif
139793175a5cSSjoerd Meijer 
139893175a5cSSjoerd Meijer         // Collect all the candidate PHINodes to be rewritten.
139993175a5cSSjoerd Meijer         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
140093175a5cSSjoerd Meijer       }
140193175a5cSSjoerd Meijer     }
140293175a5cSSjoerd Meijer   }
140393175a5cSSjoerd Meijer 
140493175a5cSSjoerd Meijer   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
140593175a5cSSjoerd Meijer   int NumReplaced = 0;
140693175a5cSSjoerd Meijer 
140793175a5cSSjoerd Meijer   // Transformation.
140893175a5cSSjoerd Meijer   for (const RewritePhi &Phi : RewritePhiSet) {
140993175a5cSSjoerd Meijer     PHINode *PN = Phi.PN;
141093175a5cSSjoerd Meijer     Value *ExitVal = Phi.Val;
141193175a5cSSjoerd Meijer 
141293175a5cSSjoerd Meijer     // Only do the rewrite when the ExitValue can be expanded cheaply.
141393175a5cSSjoerd Meijer     // If LoopCanBeDel is true, rewrite exit value aggressively.
141493175a5cSSjoerd Meijer     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
141593175a5cSSjoerd Meijer       DeadInsts.push_back(ExitVal);
141693175a5cSSjoerd Meijer       continue;
141793175a5cSSjoerd Meijer     }
141893175a5cSSjoerd Meijer 
141993175a5cSSjoerd Meijer     NumReplaced++;
142093175a5cSSjoerd Meijer     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
142193175a5cSSjoerd Meijer     PN->setIncomingValue(Phi.Ith, ExitVal);
142293175a5cSSjoerd Meijer 
142393175a5cSSjoerd Meijer     // If this instruction is dead now, delete it. Don't do it now to avoid
142493175a5cSSjoerd Meijer     // invalidating iterators.
142593175a5cSSjoerd Meijer     if (isInstructionTriviallyDead(Inst, TLI))
142693175a5cSSjoerd Meijer       DeadInsts.push_back(Inst);
142793175a5cSSjoerd Meijer 
142893175a5cSSjoerd Meijer     // Replace PN with ExitVal if that is legal and does not break LCSSA.
142993175a5cSSjoerd Meijer     if (PN->getNumIncomingValues() == 1 &&
143093175a5cSSjoerd Meijer         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
143193175a5cSSjoerd Meijer       PN->replaceAllUsesWith(ExitVal);
143293175a5cSSjoerd Meijer       PN->eraseFromParent();
143393175a5cSSjoerd Meijer     }
143493175a5cSSjoerd Meijer   }
143593175a5cSSjoerd Meijer 
143693175a5cSSjoerd Meijer   // The insertion point instruction may have been deleted; clear it out
143793175a5cSSjoerd Meijer   // so that the rewriter doesn't trip over it later.
143893175a5cSSjoerd Meijer   Rewriter.clearInsertPoint();
143993175a5cSSjoerd Meijer   return NumReplaced;
144093175a5cSSjoerd Meijer }
1441af7e1588SEvgeniy Brevnov 
1442af7e1588SEvgeniy Brevnov /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1443af7e1588SEvgeniy Brevnov /// \p OrigLoop.
1444af7e1588SEvgeniy Brevnov void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1445af7e1588SEvgeniy Brevnov                                         Loop *RemainderLoop, uint64_t UF) {
1446af7e1588SEvgeniy Brevnov   assert(UF > 0 && "Zero unrolled factor is not supported");
1447af7e1588SEvgeniy Brevnov   assert(UnrolledLoop != RemainderLoop &&
1448af7e1588SEvgeniy Brevnov          "Unrolled and Remainder loops are expected to distinct");
1449af7e1588SEvgeniy Brevnov 
1450af7e1588SEvgeniy Brevnov   // Get number of iterations in the original scalar loop.
1451af7e1588SEvgeniy Brevnov   unsigned OrigLoopInvocationWeight = 0;
1452af7e1588SEvgeniy Brevnov   Optional<unsigned> OrigAverageTripCount =
1453af7e1588SEvgeniy Brevnov       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1454af7e1588SEvgeniy Brevnov   if (!OrigAverageTripCount)
1455af7e1588SEvgeniy Brevnov     return;
1456af7e1588SEvgeniy Brevnov 
1457af7e1588SEvgeniy Brevnov   // Calculate number of iterations in unrolled loop.
1458af7e1588SEvgeniy Brevnov   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1459af7e1588SEvgeniy Brevnov   // Calculate number of iterations for remainder loop.
1460af7e1588SEvgeniy Brevnov   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1461af7e1588SEvgeniy Brevnov 
1462af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1463af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1464af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1465af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1466af7e1588SEvgeniy Brevnov }
1467388de9dfSAlina Sbirlea 
1468388de9dfSAlina Sbirlea /// Utility that implements appending of loops onto a worklist.
1469388de9dfSAlina Sbirlea /// Loops are added in preorder (analogous for reverse postorder for trees),
1470388de9dfSAlina Sbirlea /// and the worklist is processed LIFO.
1471388de9dfSAlina Sbirlea template <typename RangeT>
1472388de9dfSAlina Sbirlea void llvm::appendReversedLoopsToWorklist(
1473388de9dfSAlina Sbirlea     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1474388de9dfSAlina Sbirlea   // We use an internal worklist to build up the preorder traversal without
1475388de9dfSAlina Sbirlea   // recursion.
1476388de9dfSAlina Sbirlea   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1477388de9dfSAlina Sbirlea 
1478388de9dfSAlina Sbirlea   // We walk the initial sequence of loops in reverse because we generally want
1479388de9dfSAlina Sbirlea   // to visit defs before uses and the worklist is LIFO.
1480388de9dfSAlina Sbirlea   for (Loop *RootL : Loops) {
1481388de9dfSAlina Sbirlea     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1482388de9dfSAlina Sbirlea     assert(PreOrderWorklist.empty() &&
1483388de9dfSAlina Sbirlea            "Must start with an empty preorder walk worklist.");
1484388de9dfSAlina Sbirlea     PreOrderWorklist.push_back(RootL);
1485388de9dfSAlina Sbirlea     do {
1486388de9dfSAlina Sbirlea       Loop *L = PreOrderWorklist.pop_back_val();
1487388de9dfSAlina Sbirlea       PreOrderWorklist.append(L->begin(), L->end());
1488388de9dfSAlina Sbirlea       PreOrderLoops.push_back(L);
1489388de9dfSAlina Sbirlea     } while (!PreOrderWorklist.empty());
1490388de9dfSAlina Sbirlea 
1491388de9dfSAlina Sbirlea     Worklist.insert(std::move(PreOrderLoops));
1492388de9dfSAlina Sbirlea     PreOrderLoops.clear();
1493388de9dfSAlina Sbirlea   }
1494388de9dfSAlina Sbirlea }
1495388de9dfSAlina Sbirlea 
1496388de9dfSAlina Sbirlea template <typename RangeT>
1497388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(RangeT &&Loops,
1498388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1499388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1500388de9dfSAlina Sbirlea }
1501388de9dfSAlina Sbirlea 
1502388de9dfSAlina Sbirlea template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1503388de9dfSAlina Sbirlea     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1504388de9dfSAlina Sbirlea 
150567904db2SAlina Sbirlea template void
150667904db2SAlina Sbirlea llvm::appendLoopsToWorklist<Loop &>(Loop &L,
150767904db2SAlina Sbirlea                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
150867904db2SAlina Sbirlea 
1509388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(LoopInfo &LI,
1510388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1511388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(LI, Worklist);
1512388de9dfSAlina Sbirlea }
15133dcaf296SArkady Shlykov 
15143dcaf296SArkady Shlykov Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
15153dcaf296SArkady Shlykov                       LoopInfo *LI, LPPassManager *LPM) {
15163dcaf296SArkady Shlykov   Loop &New = *LI->AllocateLoop();
15173dcaf296SArkady Shlykov   if (PL)
15183dcaf296SArkady Shlykov     PL->addChildLoop(&New);
15193dcaf296SArkady Shlykov   else
15203dcaf296SArkady Shlykov     LI->addTopLevelLoop(&New);
15213dcaf296SArkady Shlykov 
15223dcaf296SArkady Shlykov   if (LPM)
15233dcaf296SArkady Shlykov     LPM->addLoop(New);
15243dcaf296SArkady Shlykov 
15253dcaf296SArkady Shlykov   // Add all of the blocks in L to the new loop.
15263dcaf296SArkady Shlykov   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
15273dcaf296SArkady Shlykov        I != E; ++I)
15283dcaf296SArkady Shlykov     if (LI->getLoopFor(*I) == L)
15293dcaf296SArkady Shlykov       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
15303dcaf296SArkady Shlykov 
15313dcaf296SArkady Shlykov   // Add all of the subloops to the new loop.
15323dcaf296SArkady Shlykov   for (Loop *I : *L)
15333dcaf296SArkady Shlykov     cloneLoop(I, &New, VM, LI, LPM);
15343dcaf296SArkady Shlykov 
15353dcaf296SArkady Shlykov   return &New;
15363dcaf296SArkady Shlykov }
15378528186bSFlorian Hahn 
15388528186bSFlorian Hahn /// IR Values for the lower and upper bounds of a pointer evolution.  We
15398528186bSFlorian Hahn /// need to use value-handles because SCEV expansion can invalidate previously
15408528186bSFlorian Hahn /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
15418528186bSFlorian Hahn /// a previous one.
15428528186bSFlorian Hahn struct PointerBounds {
15438528186bSFlorian Hahn   TrackingVH<Value> Start;
15448528186bSFlorian Hahn   TrackingVH<Value> End;
15458528186bSFlorian Hahn };
15468528186bSFlorian Hahn 
15478528186bSFlorian Hahn /// Expand code for the lower and upper bound of the pointer group \p CG
15488528186bSFlorian Hahn /// in \p TheLoop.  \return the values for the bounds.
15498528186bSFlorian Hahn static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
15508528186bSFlorian Hahn                                   Loop *TheLoop, Instruction *Loc,
15518528186bSFlorian Hahn                                   SCEVExpander &Exp, ScalarEvolution *SE) {
15528528186bSFlorian Hahn   // TODO: Add helper to retrieve pointers to CG.
15538528186bSFlorian Hahn   Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue;
15548528186bSFlorian Hahn   const SCEV *Sc = SE->getSCEV(Ptr);
15558528186bSFlorian Hahn 
15568528186bSFlorian Hahn   unsigned AS = Ptr->getType()->getPointerAddressSpace();
15578528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
15588528186bSFlorian Hahn 
15598528186bSFlorian Hahn   // Use this type for pointer arithmetic.
15608528186bSFlorian Hahn   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
15618528186bSFlorian Hahn 
15628528186bSFlorian Hahn   if (SE->isLoopInvariant(Sc, TheLoop)) {
15638528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:"
15648528186bSFlorian Hahn                       << *Ptr << "\n");
15658528186bSFlorian Hahn     // Ptr could be in the loop body. If so, expand a new one at the correct
15668528186bSFlorian Hahn     // location.
15678528186bSFlorian Hahn     Instruction *Inst = dyn_cast<Instruction>(Ptr);
15688528186bSFlorian Hahn     Value *NewPtr = (Inst && TheLoop->contains(Inst))
15698528186bSFlorian Hahn                         ? Exp.expandCodeFor(Sc, PtrArithTy, Loc)
15708528186bSFlorian Hahn                         : Ptr;
15718528186bSFlorian Hahn     // We must return a half-open range, which means incrementing Sc.
15728528186bSFlorian Hahn     const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy));
15738528186bSFlorian Hahn     Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc);
15748528186bSFlorian Hahn     return {NewPtr, NewPtrPlusOne};
15758528186bSFlorian Hahn   } else {
15768528186bSFlorian Hahn     Value *Start = nullptr, *End = nullptr;
15778528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
15788528186bSFlorian Hahn     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
15798528186bSFlorian Hahn     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
15808528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High
15818528186bSFlorian Hahn                       << "\n");
15828528186bSFlorian Hahn     return {Start, End};
15838528186bSFlorian Hahn   }
15848528186bSFlorian Hahn }
15858528186bSFlorian Hahn 
15868528186bSFlorian Hahn /// Turns a collection of checks into a collection of expanded upper and
15878528186bSFlorian Hahn /// lower bounds for both pointers in the check.
15888528186bSFlorian Hahn static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
15898528186bSFlorian Hahn expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
15908528186bSFlorian Hahn              Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) {
15918528186bSFlorian Hahn   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
15928528186bSFlorian Hahn 
15938528186bSFlorian Hahn   // Here we're relying on the SCEV Expander's cache to only emit code for the
15948528186bSFlorian Hahn   // same bounds once.
15958528186bSFlorian Hahn   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
15968528186bSFlorian Hahn             [&](const RuntimePointerCheck &Check) {
15978528186bSFlorian Hahn               PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE),
15988528186bSFlorian Hahn                             Second =
15998528186bSFlorian Hahn                                 expandBounds(Check.second, L, Loc, Exp, SE);
16008528186bSFlorian Hahn               return std::make_pair(First, Second);
16018528186bSFlorian Hahn             });
16028528186bSFlorian Hahn 
16038528186bSFlorian Hahn   return ChecksWithBounds;
16048528186bSFlorian Hahn }
16058528186bSFlorian Hahn 
16068528186bSFlorian Hahn std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks(
16078528186bSFlorian Hahn     Instruction *Loc, Loop *TheLoop,
16088528186bSFlorian Hahn     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
16098528186bSFlorian Hahn     ScalarEvolution *SE) {
16108528186bSFlorian Hahn   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
16118528186bSFlorian Hahn   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
16128528186bSFlorian Hahn   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
16138528186bSFlorian Hahn   SCEVExpander Exp(*SE, DL, "induction");
16148528186bSFlorian Hahn   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp);
16158528186bSFlorian Hahn 
16168528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
16178528186bSFlorian Hahn   Instruction *FirstInst = nullptr;
16188528186bSFlorian Hahn   IRBuilder<> ChkBuilder(Loc);
16198528186bSFlorian Hahn   // Our instructions might fold to a constant.
16208528186bSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
16218528186bSFlorian Hahn 
16228528186bSFlorian Hahn   // FIXME: this helper is currently a duplicate of the one in
16238528186bSFlorian Hahn   // LoopVectorize.cpp.
16248528186bSFlorian Hahn   auto GetFirstInst = [](Instruction *FirstInst, Value *V,
16258528186bSFlorian Hahn                          Instruction *Loc) -> Instruction * {
16268528186bSFlorian Hahn     if (FirstInst)
16278528186bSFlorian Hahn       return FirstInst;
16288528186bSFlorian Hahn     if (Instruction *I = dyn_cast<Instruction>(V))
16298528186bSFlorian Hahn       return I->getParent() == Loc->getParent() ? I : nullptr;
16308528186bSFlorian Hahn     return nullptr;
16318528186bSFlorian Hahn   };
16328528186bSFlorian Hahn 
16338528186bSFlorian Hahn   for (const auto &Check : ExpandedChecks) {
16348528186bSFlorian Hahn     const PointerBounds &A = Check.first, &B = Check.second;
16358528186bSFlorian Hahn     // Check if two pointers (A and B) conflict where conflict is computed as:
16368528186bSFlorian Hahn     // start(A) <= end(B) && start(B) <= end(A)
16378528186bSFlorian Hahn     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
16388528186bSFlorian Hahn     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
16398528186bSFlorian Hahn 
16408528186bSFlorian Hahn     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
16418528186bSFlorian Hahn            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
16428528186bSFlorian Hahn            "Trying to bounds check pointers with different address spaces");
16438528186bSFlorian Hahn 
16448528186bSFlorian Hahn     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
16458528186bSFlorian Hahn     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
16468528186bSFlorian Hahn 
16478528186bSFlorian Hahn     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
16488528186bSFlorian Hahn     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
16498528186bSFlorian Hahn     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
16508528186bSFlorian Hahn     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
16518528186bSFlorian Hahn 
16528528186bSFlorian Hahn     // [A|B].Start points to the first accessed byte under base [A|B].
16538528186bSFlorian Hahn     // [A|B].End points to the last accessed byte, plus one.
16548528186bSFlorian Hahn     // There is no conflict when the intervals are disjoint:
16558528186bSFlorian Hahn     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
16568528186bSFlorian Hahn     //
16578528186bSFlorian Hahn     // bound0 = (B.Start < A.End)
16588528186bSFlorian Hahn     // bound1 = (A.Start < B.End)
16598528186bSFlorian Hahn     //  IsConflict = bound0 & bound1
16608528186bSFlorian Hahn     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
16618528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp0, Loc);
16628528186bSFlorian Hahn     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
16638528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp1, Loc);
16648528186bSFlorian Hahn     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16658528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
16668528186bSFlorian Hahn     if (MemoryRuntimeCheck) {
16678528186bSFlorian Hahn       IsConflict =
16688528186bSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
16698528186bSFlorian Hahn       FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
16708528186bSFlorian Hahn     }
16718528186bSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
16728528186bSFlorian Hahn   }
16738528186bSFlorian Hahn 
16748528186bSFlorian Hahn   if (!MemoryRuntimeCheck)
16758528186bSFlorian Hahn     return std::make_pair(nullptr, nullptr);
16768528186bSFlorian Hahn 
16778528186bSFlorian Hahn   // We have to do this trickery because the IRBuilder might fold the check to a
16788528186bSFlorian Hahn   // constant expression in which case there is no Instruction anchored in a
16798528186bSFlorian Hahn   // the block.
16808528186bSFlorian Hahn   Instruction *Check =
16818528186bSFlorian Hahn       BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx));
16828528186bSFlorian Hahn   ChkBuilder.Insert(Check, "memcheck.conflict");
16838528186bSFlorian Hahn   FirstInst = GetFirstInst(FirstInst, Check, Loc);
16848528186bSFlorian Hahn   return std::make_pair(FirstInst, Check);
16858528186bSFlorian Hahn }
1686