176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
276aa662cSKarthik Bhat //
376aa662cSKarthik Bhat //                     The LLVM Compiler Infrastructure
476aa662cSKarthik Bhat //
576aa662cSKarthik Bhat // This file is distributed under the University of Illinois Open Source
676aa662cSKarthik Bhat // License. See LICENSE.TXT for details.
776aa662cSKarthik Bhat //
876aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
976aa662cSKarthik Bhat //
1076aa662cSKarthik Bhat // This file defines common loop utility functions.
1176aa662cSKarthik Bhat //
1276aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
1376aa662cSKarthik Bhat 
142f2bd8caSAdam Nemet #include "llvm/Transforms/Utils/LoopUtils.h"
154a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h"
1631088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
1731088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
1831088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
19a21d5f1eSPhilip Reames #include "llvm/Analysis/InstructionSimplify.h"
202f2bd8caSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
21c3ccf5d7SIgor Laevsky #include "llvm/Analysis/LoopPass.h"
2223aed5efSPhilip Reames #include "llvm/Analysis/MustExecute.h"
2345d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
242f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25c434d091SElena Demikhovsky #include "llvm/Analysis/ScalarEvolutionExpander.h"
2645d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
276bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
28a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h"
29744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h"
3021a8b605SChijun Sima #include "llvm/IR/DomTreeUpdater.h"
3131088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3276aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
33744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h"
3445d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
3576aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
3676aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
3731088a9dSChandler Carruth #include "llvm/Pass.h"
3876aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
39a097bc69SChad Rosier #include "llvm/Support/KnownBits.h"
404a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
4176aa662cSKarthik Bhat 
4276aa662cSKarthik Bhat using namespace llvm;
4376aa662cSKarthik Bhat using namespace llvm::PatternMatch;
4476aa662cSKarthik Bhat 
4576aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
4676aa662cSKarthik Bhat 
4772448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
4872448525SMichael Kruse 
494a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
504a000883SChandler Carruth                                    bool PreserveLCSSA) {
514a000883SChandler Carruth   bool Changed = false;
524a000883SChandler Carruth 
534a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
544a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
554a000883SChandler Carruth 
564a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
574a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
584a000883SChandler Carruth            "Must start with an empty predecessors list!");
594a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
604a000883SChandler Carruth 
614a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
624a000883SChandler Carruth     // keep track of the in-loop predecessors.
634a000883SChandler Carruth     bool IsDedicatedExit = true;
644a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
654a000883SChandler Carruth       if (L->contains(PredBB)) {
664a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
674a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
684a000883SChandler Carruth           return false;
694a000883SChandler Carruth 
704a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
714a000883SChandler Carruth       } else {
724a000883SChandler Carruth         IsDedicatedExit = false;
734a000883SChandler Carruth       }
744a000883SChandler Carruth 
754a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
764a000883SChandler Carruth 
774a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
784a000883SChandler Carruth     if (IsDedicatedExit)
794a000883SChandler Carruth       return false;
804a000883SChandler Carruth 
814a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
82ab6f84f7SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA);
834a000883SChandler Carruth 
844a000883SChandler Carruth     if (!NewExitBB)
85d34e60caSNicola Zaghen       LLVM_DEBUG(
86d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
874a000883SChandler Carruth                  << *L << "\n");
884a000883SChandler Carruth     else
89d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
904a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
914a000883SChandler Carruth     return true;
924a000883SChandler Carruth   };
934a000883SChandler Carruth 
944a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
954a000883SChandler Carruth   // them, but only visit each one once.
964a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
974a000883SChandler Carruth   for (auto *BB : L->blocks())
984a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
994a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1004a000883SChandler Carruth       if (L->contains(SuccBB))
1014a000883SChandler Carruth         continue;
1024a000883SChandler Carruth 
1034a000883SChandler Carruth       // Visit each exit block exactly once.
1044a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1054a000883SChandler Carruth         continue;
1064a000883SChandler Carruth 
1074a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1084a000883SChandler Carruth     }
1094a000883SChandler Carruth 
1104a000883SChandler Carruth   return Changed;
1114a000883SChandler Carruth }
1124a000883SChandler Carruth 
1135f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
114c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
115c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
116c5b7b555SAshutosh Nema 
117c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
118c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
119c5b7b555SAshutosh Nema     // be adapted into a pointer.
120c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
121c5b7b555SAshutosh Nema       auto Users = Inst.users();
1220a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
123c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
124c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
125c5b7b555SAshutosh Nema           }))
126c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
127c5b7b555SAshutosh Nema     }
128c5b7b555SAshutosh Nema 
129c5b7b555SAshutosh Nema   return UsedOutside;
130c5b7b555SAshutosh Nema }
13131088a9dSChandler Carruth 
13231088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
13331088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
13431088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
13531088a9dSChandler Carruth   // pass manager, they must also preserve these.
13631088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
13731088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
13831088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
13931088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
14031088a9dSChandler Carruth 
14131088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
14231088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
14331088a9dSChandler Carruth   extern char &LoopSimplifyID;
14431088a9dSChandler Carruth   extern char &LCSSAID;
14531088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
14631088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
14731088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
14831088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
149c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
150c3ccf5d7SIgor Laevsky   // which preserve lcssa form
151c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
152c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
15331088a9dSChandler Carruth 
15431088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
15531088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
15631088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
15731088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
15831088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
15931088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
16031088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
16131088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
16231088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
16331088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
16431088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
16531088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
16631088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
16731088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
16831088a9dSChandler Carruth }
16931088a9dSChandler Carruth 
17031088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
17131088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
17231088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
17331088a9dSChandler Carruth /// with:
17431088a9dSChandler Carruth ///
17531088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
17631088a9dSChandler Carruth ///
17731088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
17831088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
17931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
18031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
18131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
182e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
18331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
18431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
18531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
18631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
18731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
18831088a9dSChandler Carruth }
189963341c8SAdam Nemet 
19072448525SMichael Kruse static Optional<MDNode *> findOptionMDForLoopID(MDNode *LoopID,
191fe3def7cSAdam Nemet                                                 StringRef Name) {
192fe3def7cSAdam Nemet   // Return none if LoopID is false.
193963341c8SAdam Nemet   if (!LoopID)
194fe3def7cSAdam Nemet     return None;
195293be666SAdam Nemet 
196293be666SAdam Nemet   // First operand should refer to the loop id itself.
197293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
198293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
199293be666SAdam Nemet 
200963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
201963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
202963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
203963341c8SAdam Nemet     if (!MD)
204963341c8SAdam Nemet       continue;
205963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
206963341c8SAdam Nemet     if (!S)
207963341c8SAdam Nemet       continue;
208963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
209963341c8SAdam Nemet     if (Name.equals(S->getString()))
21072448525SMichael Kruse       return MD;
21172448525SMichael Kruse   }
21272448525SMichael Kruse   return None;
21372448525SMichael Kruse }
21472448525SMichael Kruse 
21572448525SMichael Kruse static Optional<MDNode *> findOptionMDForLoop(const Loop *TheLoop,
21672448525SMichael Kruse                                               StringRef Name) {
21772448525SMichael Kruse   return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
21872448525SMichael Kruse }
21972448525SMichael Kruse 
22072448525SMichael Kruse /// Find string metadata for loop
22172448525SMichael Kruse ///
22272448525SMichael Kruse /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
22372448525SMichael Kruse /// operand or null otherwise.  If the string metadata is not found return
22472448525SMichael Kruse /// Optional's not-a-value.
22572448525SMichael Kruse Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
22672448525SMichael Kruse                                                             StringRef Name) {
22772448525SMichael Kruse   auto MD = findOptionMDForLoop(TheLoop, Name).getValueOr(nullptr);
22872448525SMichael Kruse   if (!MD)
22972448525SMichael Kruse     return None;
230fe3def7cSAdam Nemet   switch (MD->getNumOperands()) {
231fe3def7cSAdam Nemet   case 1:
232fe3def7cSAdam Nemet     return nullptr;
233fe3def7cSAdam Nemet   case 2:
234fe3def7cSAdam Nemet     return &MD->getOperand(1);
235fe3def7cSAdam Nemet   default:
236fe3def7cSAdam Nemet     llvm_unreachable("loop metadata has 0 or 1 operand");
237963341c8SAdam Nemet   }
238fe3def7cSAdam Nemet }
23972448525SMichael Kruse 
24072448525SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
24172448525SMichael Kruse                                                    StringRef Name) {
24272448525SMichael Kruse   Optional<MDNode *> MD = findOptionMDForLoop(TheLoop, Name);
24372448525SMichael Kruse   if (!MD.hasValue())
244fe3def7cSAdam Nemet     return None;
24572448525SMichael Kruse   MDNode *OptionNode = MD.getValue();
24672448525SMichael Kruse   if (OptionNode == nullptr)
24772448525SMichael Kruse     return None;
24872448525SMichael Kruse   switch (OptionNode->getNumOperands()) {
24972448525SMichael Kruse   case 1:
25072448525SMichael Kruse     // When the value is absent it is interpreted as 'attribute set'.
25172448525SMichael Kruse     return true;
25272448525SMichael Kruse   case 2:
25372448525SMichael Kruse     return mdconst::extract_or_null<ConstantInt>(
25472448525SMichael Kruse         OptionNode->getOperand(1).get());
25572448525SMichael Kruse   }
25672448525SMichael Kruse   llvm_unreachable("unexpected number of options");
25772448525SMichael Kruse }
25872448525SMichael Kruse 
25972448525SMichael Kruse static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
26072448525SMichael Kruse   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
26172448525SMichael Kruse }
26272448525SMichael Kruse 
26372448525SMichael Kruse llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
26472448525SMichael Kruse                                                       StringRef Name) {
26572448525SMichael Kruse   const MDOperand *AttrMD =
26672448525SMichael Kruse       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
26772448525SMichael Kruse   if (!AttrMD)
26872448525SMichael Kruse     return None;
26972448525SMichael Kruse 
27072448525SMichael Kruse   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
27172448525SMichael Kruse   if (!IntMD)
27272448525SMichael Kruse     return None;
27372448525SMichael Kruse 
27472448525SMichael Kruse   return IntMD->getSExtValue();
27572448525SMichael Kruse }
27672448525SMichael Kruse 
27772448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
27872448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
27972448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
28072448525SMichael Kruse   if (!OrigLoopID) {
28172448525SMichael Kruse     if (AlwaysNew)
28272448525SMichael Kruse       return nullptr;
28372448525SMichael Kruse     return None;
28472448525SMichael Kruse   }
28572448525SMichael Kruse 
28672448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
28772448525SMichael Kruse 
28872448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
28972448525SMichael Kruse   bool InheritSomeAttrs =
29072448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
29172448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
29272448525SMichael Kruse   MDs.push_back(nullptr);
29372448525SMichael Kruse 
29472448525SMichael Kruse   bool Changed = false;
29572448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
29672448525SMichael Kruse     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
29772448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
29872448525SMichael Kruse 
29972448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
30072448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
30172448525SMichael Kruse         if (!InheritSomeAttrs)
30272448525SMichael Kruse           return false;
30372448525SMichael Kruse 
30472448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
30572448525SMichael Kruse         if (Op->getNumOperands() == 0)
30672448525SMichael Kruse           return true;
30772448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
30872448525SMichael Kruse         if (!isa<MDString>(NameMD))
30972448525SMichael Kruse           return true;
31072448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
31172448525SMichael Kruse 
31272448525SMichael Kruse         // Do not inherit excluded attributes.
31372448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
31472448525SMichael Kruse       };
31572448525SMichael Kruse 
31672448525SMichael Kruse       if (InheritThisAttribute(Op))
31772448525SMichael Kruse         MDs.push_back(Op);
31872448525SMichael Kruse       else
31972448525SMichael Kruse         Changed = true;
32072448525SMichael Kruse     }
32172448525SMichael Kruse   } else {
32272448525SMichael Kruse     // Modified if we dropped at least one attribute.
32372448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
32472448525SMichael Kruse   }
32572448525SMichael Kruse 
32672448525SMichael Kruse   bool HasAnyFollowup = false;
32772448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
32872448525SMichael Kruse     MDNode *FollowupNode =
32972448525SMichael Kruse         findOptionMDForLoopID(OrigLoopID, OptionName).getValueOr(nullptr);
33072448525SMichael Kruse     if (!FollowupNode)
33172448525SMichael Kruse       continue;
33272448525SMichael Kruse 
33372448525SMichael Kruse     HasAnyFollowup = true;
33472448525SMichael Kruse     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
33572448525SMichael Kruse       MDs.push_back(Option.get());
33672448525SMichael Kruse       Changed = true;
33772448525SMichael Kruse     }
33872448525SMichael Kruse   }
33972448525SMichael Kruse 
34072448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
34172448525SMichael Kruse   // transformation pass to add suitable attributes.
34272448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
34372448525SMichael Kruse     return None;
34472448525SMichael Kruse 
34572448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
34672448525SMichael Kruse   if (!AlwaysNew && !Changed)
34772448525SMichael Kruse     return OrigLoopID;
34872448525SMichael Kruse 
34972448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
35072448525SMichael Kruse   if (MDs.size() == 1)
35172448525SMichael Kruse     return nullptr;
35272448525SMichael Kruse 
35372448525SMichael Kruse   // Build the new loop ID.
35472448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
35572448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
35672448525SMichael Kruse   return FollowupLoopID;
35772448525SMichael Kruse }
35872448525SMichael Kruse 
35972448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
36072448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
36172448525SMichael Kruse }
36272448525SMichael Kruse 
36372448525SMichael Kruse TransformationMode llvm::hasUnrollTransformation(Loop *L) {
36472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
36572448525SMichael Kruse     return TM_SuppressedByUser;
36672448525SMichael Kruse 
36772448525SMichael Kruse   Optional<int> Count =
36872448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
36972448525SMichael Kruse   if (Count.hasValue())
37072448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
37172448525SMichael Kruse 
37272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
37372448525SMichael Kruse     return TM_ForcedByUser;
37472448525SMichael Kruse 
37572448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
37672448525SMichael Kruse     return TM_ForcedByUser;
37772448525SMichael Kruse 
37872448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
37972448525SMichael Kruse     return TM_Disable;
38072448525SMichael Kruse 
38172448525SMichael Kruse   return TM_Unspecified;
38272448525SMichael Kruse }
38372448525SMichael Kruse 
38472448525SMichael Kruse TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
38572448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
38672448525SMichael Kruse     return TM_SuppressedByUser;
38772448525SMichael Kruse 
38872448525SMichael Kruse   Optional<int> Count =
38972448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
39072448525SMichael Kruse   if (Count.hasValue())
39172448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
39272448525SMichael Kruse 
39372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
39472448525SMichael Kruse     return TM_ForcedByUser;
39572448525SMichael Kruse 
39672448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
39772448525SMichael Kruse     return TM_Disable;
39872448525SMichael Kruse 
39972448525SMichael Kruse   return TM_Unspecified;
40072448525SMichael Kruse }
40172448525SMichael Kruse 
40272448525SMichael Kruse TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
40372448525SMichael Kruse   Optional<bool> Enable =
40472448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
40572448525SMichael Kruse 
40672448525SMichael Kruse   if (Enable == false)
40772448525SMichael Kruse     return TM_SuppressedByUser;
40872448525SMichael Kruse 
40972448525SMichael Kruse   Optional<int> VectorizeWidth =
41072448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
41172448525SMichael Kruse   Optional<int> InterleaveCount =
41272448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
41372448525SMichael Kruse 
41472448525SMichael Kruse   if (Enable == true) {
41572448525SMichael Kruse     // 'Forcing' vector width and interleave count to one effectively disables
41672448525SMichael Kruse     // this tranformation.
41772448525SMichael Kruse     if (VectorizeWidth == 1 && InterleaveCount == 1)
41872448525SMichael Kruse       return TM_SuppressedByUser;
41972448525SMichael Kruse     return TM_ForcedByUser;
42072448525SMichael Kruse   }
42172448525SMichael Kruse 
42272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
42372448525SMichael Kruse     return TM_Disable;
42472448525SMichael Kruse 
42572448525SMichael Kruse   if (VectorizeWidth == 1 && InterleaveCount == 1)
42672448525SMichael Kruse     return TM_Disable;
42772448525SMichael Kruse 
42872448525SMichael Kruse   if (VectorizeWidth > 1 || InterleaveCount > 1)
42972448525SMichael Kruse     return TM_Enable;
43072448525SMichael Kruse 
43172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
43272448525SMichael Kruse     return TM_Disable;
43372448525SMichael Kruse 
43472448525SMichael Kruse   return TM_Unspecified;
43572448525SMichael Kruse }
43672448525SMichael Kruse 
43772448525SMichael Kruse TransformationMode llvm::hasDistributeTransformation(Loop *L) {
43872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
43972448525SMichael Kruse     return TM_ForcedByUser;
44072448525SMichael Kruse 
44172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
44272448525SMichael Kruse     return TM_Disable;
44372448525SMichael Kruse 
44472448525SMichael Kruse   return TM_Unspecified;
44572448525SMichael Kruse }
44672448525SMichael Kruse 
44772448525SMichael Kruse TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
44872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
44972448525SMichael Kruse     return TM_SuppressedByUser;
45072448525SMichael Kruse 
45172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
45272448525SMichael Kruse     return TM_Disable;
45372448525SMichael Kruse 
45472448525SMichael Kruse   return TM_Unspecified;
455963341c8SAdam Nemet }
456122f984aSEvgeniy Stepanov 
4577ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
4587ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
4597ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
4607ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
4617ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
4627ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
4637ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
4647ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
4657ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
4667ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
4677ed5856aSAlina Sbirlea   };
4687ed5856aSAlina Sbirlea 
4697ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
4707ed5856aSAlina Sbirlea 
4717ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
4727ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
4737ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
4747ed5856aSAlina Sbirlea 
4757ed5856aSAlina Sbirlea   return Worklist;
4767ed5856aSAlina Sbirlea }
4777ed5856aSAlina Sbirlea 
478df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
479df3e71e0SMarcello Maggioni                           ScalarEvolution *SE = nullptr,
480df3e71e0SMarcello Maggioni                           LoopInfo *LI = nullptr) {
481899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
482df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
483df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
484df3e71e0SMarcello Maggioni 
485df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
486df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
487df3e71e0SMarcello Maggioni   //
488df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
489df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
490df3e71e0SMarcello Maggioni 
491df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
492df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
493df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
494df3e71e0SMarcello Maggioni   if (SE)
495df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
496df3e71e0SMarcello Maggioni 
497df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
498df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
499df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
500df3e71e0SMarcello Maggioni 
501df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
502df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
503df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
504df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
505df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
506df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
507df3e71e0SMarcello Maggioni   // preheader -> header.
508df3e71e0SMarcello Maggioni   //
509df3e71e0SMarcello Maggioni   //
510df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
511df3e71e0SMarcello Maggioni   //        |                    |   |                   |
512df3e71e0SMarcello Maggioni   //        V                    |   V                   |
513df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
514df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
515df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
516df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
517df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
518df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
519df3e71e0SMarcello Maggioni   //
520df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
521df3e71e0SMarcello Maggioni   // update without using the batch update API.
522df3e71e0SMarcello Maggioni   //
523df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
524df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
525df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
526df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
527df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
528df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
529df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
530df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
531df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
532df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
533df3e71e0SMarcello Maggioni 
534df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
535df3e71e0SMarcello Maggioni   // instead of the exiting block.
536c7fc81e6SBenjamin Kramer   for (PHINode &P : ExitBlock->phis()) {
537df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
538df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
539df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
540df3e71e0SMarcello Maggioni     int PredIndex = 0;
541c7fc81e6SBenjamin Kramer     P.setIncomingBlock(PredIndex, Preheader);
542df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
543df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
544df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
545df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
546df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
547df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
548df3e71e0SMarcello Maggioni     // being deleted).
549c7fc81e6SBenjamin Kramer     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
550c7fc81e6SBenjamin Kramer       P.removeIncomingValue(e - i, false);
551df3e71e0SMarcello Maggioni 
552c7fc81e6SBenjamin Kramer     assert((P.getNumIncomingValues() == 1 &&
553c7fc81e6SBenjamin Kramer             P.getIncomingBlock(PredIndex) == Preheader) &&
554df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
555df3e71e0SMarcello Maggioni   }
556df3e71e0SMarcello Maggioni 
557df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
558df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
559df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
560df3e71e0SMarcello Maggioni   // Remove the old branch.
561df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
562df3e71e0SMarcello Maggioni 
56321a8b605SChijun Sima   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
564df3e71e0SMarcello Maggioni   if (DT) {
565df3e71e0SMarcello Maggioni     // Update the dominator tree by informing it about the new edge from the
566df3e71e0SMarcello Maggioni     // preheader to the exit.
56721a8b605SChijun Sima     DTU.insertEdge(Preheader, ExitBlock);
568df3e71e0SMarcello Maggioni     // Inform the dominator tree about the removed edge.
56921a8b605SChijun Sima     DTU.deleteEdge(Preheader, L->getHeader());
570df3e71e0SMarcello Maggioni   }
571df3e71e0SMarcello Maggioni 
572744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
5738ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
574744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
575744c3c32SDavide Italiano 
576a757d65cSSerguei Katkov   // Given LCSSA form is satisfied, we should not have users of instructions
577a757d65cSSerguei Katkov   // within the dead loop outside of the loop. However, LCSSA doesn't take
578a757d65cSSerguei Katkov   // unreachable uses into account. We handle them here.
579a757d65cSSerguei Katkov   // We could do it after drop all references (in this case all users in the
580a757d65cSSerguei Katkov   // loop will be already eliminated and we have less work to do but according
581a757d65cSSerguei Katkov   // to API doc of User::dropAllReferences only valid operation after dropping
582a757d65cSSerguei Katkov   // references, is deletion. So let's substitute all usages of
583a757d65cSSerguei Katkov   // instruction from the loop with undef value of corresponding type first.
584a757d65cSSerguei Katkov   for (auto *Block : L->blocks())
585a757d65cSSerguei Katkov     for (Instruction &I : *Block) {
586a757d65cSSerguei Katkov       auto *Undef = UndefValue::get(I.getType());
587a757d65cSSerguei Katkov       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
588a757d65cSSerguei Katkov         Use &U = *UI;
589a757d65cSSerguei Katkov         ++UI;
590a757d65cSSerguei Katkov         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
591a757d65cSSerguei Katkov           if (L->contains(Usr->getParent()))
592a757d65cSSerguei Katkov             continue;
593a757d65cSSerguei Katkov         // If we have a DT then we can check that uses outside a loop only in
594a757d65cSSerguei Katkov         // unreachable block.
595a757d65cSSerguei Katkov         if (DT)
596a757d65cSSerguei Katkov           assert(!DT->isReachableFromEntry(U) &&
597a757d65cSSerguei Katkov                  "Unexpected user in reachable block");
598a757d65cSSerguei Katkov         U.set(Undef);
599a757d65cSSerguei Katkov       }
600744c3c32SDavide Italiano       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
601744c3c32SDavide Italiano       if (!DVI)
602744c3c32SDavide Italiano         continue;
6038ee59ca6SDavide Italiano       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
6048ee59ca6SDavide Italiano       if (Key != DeadDebugSet.end())
605744c3c32SDavide Italiano         continue;
6068ee59ca6SDavide Italiano       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
607744c3c32SDavide Italiano       DeadDebugInst.push_back(DVI);
608a757d65cSSerguei Katkov     }
609a757d65cSSerguei Katkov 
610744c3c32SDavide Italiano   // After the loop has been deleted all the values defined and modified
611744c3c32SDavide Italiano   // inside the loop are going to be unavailable.
612744c3c32SDavide Italiano   // Since debug values in the loop have been deleted, inserting an undef
613744c3c32SDavide Italiano   // dbg.value truncates the range of any dbg.value before the loop where the
614744c3c32SDavide Italiano   // loop used to be. This is particularly important for constant values.
615744c3c32SDavide Italiano   DIBuilder DIB(*ExitBlock->getModule());
616744c3c32SDavide Italiano   for (auto *DVI : DeadDebugInst)
617744c3c32SDavide Italiano     DIB.insertDbgValueIntrinsic(
618*9737096bSDavide Italiano         UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(),
619744c3c32SDavide Italiano         DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI());
620744c3c32SDavide Italiano 
621df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
622df3e71e0SMarcello Maggioni   // delete it freely later.
623df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
624df3e71e0SMarcello Maggioni     Block->dropAllReferences();
625df3e71e0SMarcello Maggioni 
626df3e71e0SMarcello Maggioni   if (LI) {
627df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
628df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
629df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
630df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
631df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
632df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
633df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
634df3e71e0SMarcello Maggioni 
635df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
636df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
637df3e71e0SMarcello Maggioni 
638df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
639df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
640df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
641df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
642df3e71e0SMarcello Maggioni 
643df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
644df3e71e0SMarcello Maggioni     LI->erase(L);
645df3e71e0SMarcello Maggioni   }
646df3e71e0SMarcello Maggioni }
647df3e71e0SMarcello Maggioni 
64841d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
64941d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
65041d72a86SDehao Chen   if (!L->getExitingBlock())
65141d72a86SDehao Chen     return None;
65241d72a86SDehao Chen 
653d24ddcd6SHiroshi Inoue   // Get the branch weights for the loop's backedge.
65441d72a86SDehao Chen   BranchInst *LatchBR =
65541d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
65641d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
65741d72a86SDehao Chen     return None;
65841d72a86SDehao Chen 
65941d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
66041d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
66141d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
66241d72a86SDehao Chen 
66341d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
66441d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
66541d72a86SDehao Chen   // we exited the loop.
66641d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
667b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
66841d72a86SDehao Chen     return None;
66941d72a86SDehao Chen 
670b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
671b151a641SMichael Kuperstein     return 0;
67241d72a86SDehao Chen 
673b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
674b151a641SMichael Kuperstein   // rounding to nearest.
67541d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
676b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
67741d72a86SDehao Chen   else
678b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
67941d72a86SDehao Chen }
680cf9daa33SAmara Emerson 
6816cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
682395b80cdSDavid Green                                               ScalarEvolution &SE) {
683395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
684395b80cdSDavid Green   if (!OuterL)
685395b80cdSDavid Green     return true;
686395b80cdSDavid Green 
687395b80cdSDavid Green   // Get the backedge taken count for the inner loop
688395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
689395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
690395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
691395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
692395b80cdSDavid Green     return false;
693395b80cdSDavid Green 
694395b80cdSDavid Green   // Get whether count is invariant to the outer loop
695395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
696395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
697395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
698395b80cdSDavid Green     return false;
699395b80cdSDavid Green 
700395b80cdSDavid Green   return true;
701395b80cdSDavid Green }
702395b80cdSDavid Green 
7035f8f34e4SAdrian Prantl /// Adds a 'fast' flag to floating point operations.
704cf9daa33SAmara Emerson static Value *addFastMathFlag(Value *V) {
705cf9daa33SAmara Emerson   if (isa<FPMathOperator>(V)) {
706cf9daa33SAmara Emerson     FastMathFlags Flags;
707629c4115SSanjay Patel     Flags.setFast();
708cf9daa33SAmara Emerson     cast<Instruction>(V)->setFastMathFlags(Flags);
709cf9daa33SAmara Emerson   }
710cf9daa33SAmara Emerson   return V;
711cf9daa33SAmara Emerson }
712cf9daa33SAmara Emerson 
7136594dc37SVikram TV Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
7146594dc37SVikram TV                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
7156594dc37SVikram TV                             Value *Left, Value *Right) {
7166594dc37SVikram TV   CmpInst::Predicate P = CmpInst::ICMP_NE;
7176594dc37SVikram TV   switch (RK) {
7186594dc37SVikram TV   default:
7196594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
7206594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMin:
7216594dc37SVikram TV     P = CmpInst::ICMP_ULT;
7226594dc37SVikram TV     break;
7236594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMax:
7246594dc37SVikram TV     P = CmpInst::ICMP_UGT;
7256594dc37SVikram TV     break;
7266594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMin:
7276594dc37SVikram TV     P = CmpInst::ICMP_SLT;
7286594dc37SVikram TV     break;
7296594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMax:
7306594dc37SVikram TV     P = CmpInst::ICMP_SGT;
7316594dc37SVikram TV     break;
7326594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMin:
7336594dc37SVikram TV     P = CmpInst::FCMP_OLT;
7346594dc37SVikram TV     break;
7356594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMax:
7366594dc37SVikram TV     P = CmpInst::FCMP_OGT;
7376594dc37SVikram TV     break;
7386594dc37SVikram TV   }
7396594dc37SVikram TV 
7406594dc37SVikram TV   // We only match FP sequences that are 'fast', so we can unconditionally
7416594dc37SVikram TV   // set it on any generated instructions.
7426594dc37SVikram TV   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
7436594dc37SVikram TV   FastMathFlags FMF;
7446594dc37SVikram TV   FMF.setFast();
7456594dc37SVikram TV   Builder.setFastMathFlags(FMF);
7466594dc37SVikram TV 
7476594dc37SVikram TV   Value *Cmp;
7486594dc37SVikram TV   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
7496594dc37SVikram TV       RK == RecurrenceDescriptor::MRK_FloatMax)
7506594dc37SVikram TV     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
7516594dc37SVikram TV   else
7526594dc37SVikram TV     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
7536594dc37SVikram TV 
7546594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
7556594dc37SVikram TV   return Select;
7566594dc37SVikram TV }
7576594dc37SVikram TV 
75823c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
75923c2182cSSimon Pilgrim Value *
76023c2182cSSimon Pilgrim llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
76123c2182cSSimon Pilgrim                           unsigned Op,
76223c2182cSSimon Pilgrim                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
76323c2182cSSimon Pilgrim                           ArrayRef<Value *> RedOps) {
76423c2182cSSimon Pilgrim   unsigned VF = Src->getType()->getVectorNumElements();
76523c2182cSSimon Pilgrim 
76623c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
76723c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
76823c2182cSSimon Pilgrim   Value *Result = Acc;
76923c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
77023c2182cSSimon Pilgrim     Value *Ext =
77123c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
77223c2182cSSimon Pilgrim 
77323c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
77423c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
77523c2182cSSimon Pilgrim                                    "bin.rdx");
77623c2182cSSimon Pilgrim     } else {
77723c2182cSSimon Pilgrim       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
77823c2182cSSimon Pilgrim              "Invalid min/max");
7796594dc37SVikram TV       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
78023c2182cSSimon Pilgrim     }
78123c2182cSSimon Pilgrim 
78223c2182cSSimon Pilgrim     if (!RedOps.empty())
78323c2182cSSimon Pilgrim       propagateIRFlags(Result, RedOps);
78423c2182cSSimon Pilgrim   }
78523c2182cSSimon Pilgrim 
78623c2182cSSimon Pilgrim   return Result;
78723c2182cSSimon Pilgrim }
78823c2182cSSimon Pilgrim 
789cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
790836b0f48SAmara Emerson Value *
791836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
792836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
793836b0f48SAmara Emerson                           ArrayRef<Value *> RedOps) {
794cf9daa33SAmara Emerson   unsigned VF = Src->getType()->getVectorNumElements();
795cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
796cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
797cf9daa33SAmara Emerson   // round.
798cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
799cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
800cf9daa33SAmara Emerson   Value *TmpVec = Src;
801cf9daa33SAmara Emerson   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
802cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
803cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
804cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
805cf9daa33SAmara Emerson       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
806cf9daa33SAmara Emerson 
807cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
808cf9daa33SAmara Emerson     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
809cf9daa33SAmara Emerson               UndefValue::get(Builder.getInt32Ty()));
810cf9daa33SAmara Emerson 
811cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
812cf9daa33SAmara Emerson         TmpVec, UndefValue::get(TmpVec->getType()),
813cf9daa33SAmara Emerson         ConstantVector::get(ShuffleMask), "rdx.shuf");
814cf9daa33SAmara Emerson 
815cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
816cf9daa33SAmara Emerson       // Floating point operations had to be 'fast' to enable the reduction.
817cf9daa33SAmara Emerson       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
818cf9daa33SAmara Emerson                                                    TmpVec, Shuf, "bin.rdx"));
819cf9daa33SAmara Emerson     } else {
820cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
821cf9daa33SAmara Emerson              "Invalid min/max");
8226594dc37SVikram TV       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
823cf9daa33SAmara Emerson     }
824cf9daa33SAmara Emerson     if (!RedOps.empty())
825cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
826cf9daa33SAmara Emerson   }
827cf9daa33SAmara Emerson   // The result is in the first element of the vector.
828cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
829cf9daa33SAmara Emerson }
830cf9daa33SAmara Emerson 
831cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
832cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
833cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
834cf9daa33SAmara Emerson     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
835cf9daa33SAmara Emerson     Value *Src, TargetTransformInfo::ReductionFlags Flags,
836cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
837cf9daa33SAmara Emerson   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
838cf9daa33SAmara Emerson 
839cf9daa33SAmara Emerson   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
840cf9daa33SAmara Emerson   std::function<Value *()> BuildFunc;
841cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
842cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
843cf9daa33SAmara Emerson   // TODO: Support creating ordered reductions.
8441ea7b6f7SSanjay Patel   FastMathFlags FMFFast;
8451ea7b6f7SSanjay Patel   FMFFast.setFast();
846cf9daa33SAmara Emerson 
847cf9daa33SAmara Emerson   switch (Opcode) {
848cf9daa33SAmara Emerson   case Instruction::Add:
849cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
850cf9daa33SAmara Emerson     break;
851cf9daa33SAmara Emerson   case Instruction::Mul:
852cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
853cf9daa33SAmara Emerson     break;
854cf9daa33SAmara Emerson   case Instruction::And:
855cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
856cf9daa33SAmara Emerson     break;
857cf9daa33SAmara Emerson   case Instruction::Or:
858cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
859cf9daa33SAmara Emerson     break;
860cf9daa33SAmara Emerson   case Instruction::Xor:
861cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
862cf9daa33SAmara Emerson     break;
863cf9daa33SAmara Emerson   case Instruction::FAdd:
864cf9daa33SAmara Emerson     BuildFunc = [&]() {
865cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
8661ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
867cf9daa33SAmara Emerson       return Rdx;
868cf9daa33SAmara Emerson     };
869cf9daa33SAmara Emerson     break;
870cf9daa33SAmara Emerson   case Instruction::FMul:
871cf9daa33SAmara Emerson     BuildFunc = [&]() {
872cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
8731ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
874cf9daa33SAmara Emerson       return Rdx;
875cf9daa33SAmara Emerson     };
876cf9daa33SAmara Emerson     break;
877cf9daa33SAmara Emerson   case Instruction::ICmp:
878cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
879cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
880cf9daa33SAmara Emerson       BuildFunc = [&]() {
881cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
882cf9daa33SAmara Emerson       };
883cf9daa33SAmara Emerson     } else {
884cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
885cf9daa33SAmara Emerson       BuildFunc = [&]() {
886cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
887cf9daa33SAmara Emerson       };
888cf9daa33SAmara Emerson     }
889cf9daa33SAmara Emerson     break;
890cf9daa33SAmara Emerson   case Instruction::FCmp:
891cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
892cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
893cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
894cf9daa33SAmara Emerson     } else {
895cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
896cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
897cf9daa33SAmara Emerson     }
898cf9daa33SAmara Emerson     break;
899cf9daa33SAmara Emerson   default:
900cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
901cf9daa33SAmara Emerson     break;
902cf9daa33SAmara Emerson   }
903cf9daa33SAmara Emerson   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
904cf9daa33SAmara Emerson     return BuildFunc();
905cf9daa33SAmara Emerson   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
906cf9daa33SAmara Emerson }
907cf9daa33SAmara Emerson 
908cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
9093e069f57SSanjay Patel Value *llvm::createTargetReduction(IRBuilder<> &B,
910cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
911cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
912cf9daa33SAmara Emerson                                    bool NoNaN) {
913cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
9143e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
9153e069f57SSanjay Patel   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
916cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
917cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
918cf9daa33SAmara Emerson   switch (RecKind) {
9193e069f57SSanjay Patel   case RD::RK_FloatAdd:
9203e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
9213e069f57SSanjay Patel   case RD::RK_FloatMult:
9223e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
9233e069f57SSanjay Patel   case RD::RK_IntegerAdd:
9243e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
9253e069f57SSanjay Patel   case RD::RK_IntegerMult:
9263e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
9273e069f57SSanjay Patel   case RD::RK_IntegerAnd:
9283e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
9293e069f57SSanjay Patel   case RD::RK_IntegerOr:
9303e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
9313e069f57SSanjay Patel   case RD::RK_IntegerXor:
9323e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
9333e069f57SSanjay Patel   case RD::RK_IntegerMinMax: {
9343e069f57SSanjay Patel     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
9353e069f57SSanjay Patel     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
9363e069f57SSanjay Patel     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
9373e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
938cf9daa33SAmara Emerson   }
9393e069f57SSanjay Patel   case RD::RK_FloatMinMax: {
9403e069f57SSanjay Patel     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
9413e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
942cf9daa33SAmara Emerson   }
943cf9daa33SAmara Emerson   default:
944cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
945cf9daa33SAmara Emerson   }
946cf9daa33SAmara Emerson }
947cf9daa33SAmara Emerson 
948a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
949a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
950a61f4b89SDinar Temirbulatov   if (!VecOp)
951a61f4b89SDinar Temirbulatov     return;
952a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
953a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
954a61f4b89SDinar Temirbulatov   if (!Intersection)
955a61f4b89SDinar Temirbulatov     return;
956a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
957a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
958a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
959a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
960a61f4b89SDinar Temirbulatov     if (!Instr)
961a61f4b89SDinar Temirbulatov       continue;
962a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
963a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
964cf9daa33SAmara Emerson   }
965cf9daa33SAmara Emerson }
966