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" 144a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h" 1531088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h" 1631088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h" 175f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.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" 226da79ce1SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h" 2397468e92SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h" 2423aed5efSPhilip Reames #include "llvm/Analysis/MustExecute.h" 2545d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h" 262f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 27c434d091SElena Demikhovsky #include "llvm/Analysis/ScalarEvolutionExpander.h" 2845d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h" 296bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h" 30a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h" 31744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h" 3231088a9dSChandler Carruth #include "llvm/IR/Dominators.h" 3376aa662cSKarthik Bhat #include "llvm/IR/Instructions.h" 34744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h" 3545d4cb9aSWeiming Zhao #include "llvm/IR/Module.h" 3676aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h" 3776aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h" 38*05da2fe5SReid Kleckner #include "llvm/InitializePasses.h" 3931088a9dSChandler Carruth #include "llvm/Pass.h" 4076aa662cSKarthik Bhat #include "llvm/Support/Debug.h" 41a097bc69SChad Rosier #include "llvm/Support/KnownBits.h" 424a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h" 4376aa662cSKarthik Bhat 4476aa662cSKarthik Bhat using namespace llvm; 4576aa662cSKarthik Bhat using namespace llvm::PatternMatch; 4676aa662cSKarthik Bhat 4776aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils" 4876aa662cSKarthik Bhat 4972448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 504f64f1baSTim Corringham static const char *LLVMLoopDisableLICM = "llvm.licm.disable"; 5172448525SMichael Kruse 524a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 5397468e92SAlina Sbirlea MemorySSAUpdater *MSSAU, 544a000883SChandler Carruth bool PreserveLCSSA) { 554a000883SChandler Carruth bool Changed = false; 564a000883SChandler Carruth 574a000883SChandler Carruth // We re-use a vector for the in-loop predecesosrs. 584a000883SChandler Carruth SmallVector<BasicBlock *, 4> InLoopPredecessors; 594a000883SChandler Carruth 604a000883SChandler Carruth auto RewriteExit = [&](BasicBlock *BB) { 614a000883SChandler Carruth assert(InLoopPredecessors.empty() && 624a000883SChandler Carruth "Must start with an empty predecessors list!"); 634a000883SChandler Carruth auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 644a000883SChandler Carruth 654a000883SChandler Carruth // See if there are any non-loop predecessors of this exit block and 664a000883SChandler Carruth // keep track of the in-loop predecessors. 674a000883SChandler Carruth bool IsDedicatedExit = true; 684a000883SChandler Carruth for (auto *PredBB : predecessors(BB)) 694a000883SChandler Carruth if (L->contains(PredBB)) { 704a000883SChandler Carruth if (isa<IndirectBrInst>(PredBB->getTerminator())) 714a000883SChandler Carruth // We cannot rewrite exiting edges from an indirectbr. 724a000883SChandler Carruth return false; 73784929d0SCraig Topper if (isa<CallBrInst>(PredBB->getTerminator())) 74784929d0SCraig Topper // We cannot rewrite exiting edges from a callbr. 75784929d0SCraig Topper return false; 764a000883SChandler Carruth 774a000883SChandler Carruth InLoopPredecessors.push_back(PredBB); 784a000883SChandler Carruth } else { 794a000883SChandler Carruth IsDedicatedExit = false; 804a000883SChandler Carruth } 814a000883SChandler Carruth 824a000883SChandler Carruth assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!"); 834a000883SChandler Carruth 844a000883SChandler Carruth // Nothing to do if this is already a dedicated exit. 854a000883SChandler Carruth if (IsDedicatedExit) 864a000883SChandler Carruth return false; 874a000883SChandler Carruth 884a000883SChandler Carruth auto *NewExitBB = SplitBlockPredecessors( 8997468e92SAlina Sbirlea BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA); 904a000883SChandler Carruth 914a000883SChandler Carruth if (!NewExitBB) 92d34e60caSNicola Zaghen LLVM_DEBUG( 93d34e60caSNicola Zaghen dbgs() << "WARNING: Can't create a dedicated exit block for loop: " 944a000883SChandler Carruth << *L << "\n"); 954a000883SChandler Carruth else 96d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 974a000883SChandler Carruth << NewExitBB->getName() << "\n"); 984a000883SChandler Carruth return true; 994a000883SChandler Carruth }; 1004a000883SChandler Carruth 1014a000883SChandler Carruth // Walk the exit blocks directly rather than building up a data structure for 1024a000883SChandler Carruth // them, but only visit each one once. 1034a000883SChandler Carruth SmallPtrSet<BasicBlock *, 4> Visited; 1044a000883SChandler Carruth for (auto *BB : L->blocks()) 1054a000883SChandler Carruth for (auto *SuccBB : successors(BB)) { 1064a000883SChandler Carruth // We're looking for exit blocks so skip in-loop successors. 1074a000883SChandler Carruth if (L->contains(SuccBB)) 1084a000883SChandler Carruth continue; 1094a000883SChandler Carruth 1104a000883SChandler Carruth // Visit each exit block exactly once. 1114a000883SChandler Carruth if (!Visited.insert(SuccBB).second) 1124a000883SChandler Carruth continue; 1134a000883SChandler Carruth 1144a000883SChandler Carruth Changed |= RewriteExit(SuccBB); 1154a000883SChandler Carruth } 1164a000883SChandler Carruth 1174a000883SChandler Carruth return Changed; 1184a000883SChandler Carruth } 1194a000883SChandler Carruth 1205f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop. 121c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 122c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> UsedOutside; 123c5b7b555SAshutosh Nema 124c5b7b555SAshutosh Nema for (auto *Block : L->getBlocks()) 125c5b7b555SAshutosh Nema // FIXME: I believe that this could use copy_if if the Inst reference could 126c5b7b555SAshutosh Nema // be adapted into a pointer. 127c5b7b555SAshutosh Nema for (auto &Inst : *Block) { 128c5b7b555SAshutosh Nema auto Users = Inst.users(); 1290a16c228SDavid Majnemer if (any_of(Users, [&](User *U) { 130c5b7b555SAshutosh Nema auto *Use = cast<Instruction>(U); 131c5b7b555SAshutosh Nema return !L->contains(Use->getParent()); 132c5b7b555SAshutosh Nema })) 133c5b7b555SAshutosh Nema UsedOutside.push_back(&Inst); 134c5b7b555SAshutosh Nema } 135c5b7b555SAshutosh Nema 136c5b7b555SAshutosh Nema return UsedOutside; 137c5b7b555SAshutosh Nema } 13831088a9dSChandler Carruth 13931088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 14031088a9dSChandler Carruth // By definition, all loop passes need the LoopInfo analysis and the 14131088a9dSChandler Carruth // Dominator tree it depends on. Because they all participate in the loop 14231088a9dSChandler Carruth // pass manager, they must also preserve these. 14331088a9dSChandler Carruth AU.addRequired<DominatorTreeWrapperPass>(); 14431088a9dSChandler Carruth AU.addPreserved<DominatorTreeWrapperPass>(); 14531088a9dSChandler Carruth AU.addRequired<LoopInfoWrapperPass>(); 14631088a9dSChandler Carruth AU.addPreserved<LoopInfoWrapperPass>(); 14731088a9dSChandler Carruth 14831088a9dSChandler Carruth // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 14931088a9dSChandler Carruth // here because users shouldn't directly get them from this header. 15031088a9dSChandler Carruth extern char &LoopSimplifyID; 15131088a9dSChandler Carruth extern char &LCSSAID; 15231088a9dSChandler Carruth AU.addRequiredID(LoopSimplifyID); 15331088a9dSChandler Carruth AU.addPreservedID(LoopSimplifyID); 15431088a9dSChandler Carruth AU.addRequiredID(LCSSAID); 15531088a9dSChandler Carruth AU.addPreservedID(LCSSAID); 156c3ccf5d7SIgor Laevsky // This is used in the LPPassManager to perform LCSSA verification on passes 157c3ccf5d7SIgor Laevsky // which preserve lcssa form 158c3ccf5d7SIgor Laevsky AU.addRequired<LCSSAVerificationPass>(); 159c3ccf5d7SIgor Laevsky AU.addPreserved<LCSSAVerificationPass>(); 16031088a9dSChandler Carruth 16131088a9dSChandler Carruth // Loop passes are designed to run inside of a loop pass manager which means 16231088a9dSChandler Carruth // that any function analyses they require must be required by the first loop 16331088a9dSChandler Carruth // pass in the manager (so that it is computed before the loop pass manager 16431088a9dSChandler Carruth // runs) and preserved by all loop pasess in the manager. To make this 16531088a9dSChandler Carruth // reasonably robust, the set needed for most loop passes is maintained here. 16631088a9dSChandler Carruth // If your loop pass requires an analysis not listed here, you will need to 16731088a9dSChandler Carruth // carefully audit the loop pass manager nesting structure that results. 16831088a9dSChandler Carruth AU.addRequired<AAResultsWrapperPass>(); 16931088a9dSChandler Carruth AU.addPreserved<AAResultsWrapperPass>(); 17031088a9dSChandler Carruth AU.addPreserved<BasicAAWrapperPass>(); 17131088a9dSChandler Carruth AU.addPreserved<GlobalsAAWrapperPass>(); 17231088a9dSChandler Carruth AU.addPreserved<SCEVAAWrapperPass>(); 17331088a9dSChandler Carruth AU.addRequired<ScalarEvolutionWrapperPass>(); 17431088a9dSChandler Carruth AU.addPreserved<ScalarEvolutionWrapperPass>(); 1756da79ce1SAlina Sbirlea // FIXME: When all loop passes preserve MemorySSA, it can be required and 1766da79ce1SAlina Sbirlea // preserved here instead of the individual handling in each pass. 17731088a9dSChandler Carruth } 17831088a9dSChandler Carruth 17931088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used 18031088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c 18131088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 18231088a9dSChandler Carruth /// with: 18331088a9dSChandler Carruth /// 18431088a9dSChandler Carruth /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 18531088a9dSChandler Carruth /// 18631088a9dSChandler Carruth /// As-if "LoopPass" were a pass. 18731088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) { 18831088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 18931088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 19031088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 191e12c487bSEaswaran Raman INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 19231088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 19331088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 19431088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 19531088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 19631088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1976da79ce1SAlina Sbirlea INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 19831088a9dSChandler Carruth } 199963341c8SAdam Nemet 2003c3a7652SSerguei Katkov /// Create MDNode for input string. 2013c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) { 2023c3a7652SSerguei Katkov LLVMContext &Context = TheLoop->getHeader()->getContext(); 2033c3a7652SSerguei Katkov Metadata *MDs[] = { 2043c3a7652SSerguei Katkov MDString::get(Context, Name), 2053c3a7652SSerguei Katkov ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))}; 2063c3a7652SSerguei Katkov return MDNode::get(Context, MDs); 2073c3a7652SSerguei Katkov } 2083c3a7652SSerguei Katkov 2093c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact. 2107f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is 2117f8c8095SSerguei Katkov /// different. 2127f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD, 2133c3a7652SSerguei Katkov unsigned V) { 2143c3a7652SSerguei Katkov SmallVector<Metadata *, 4> MDs(1); 2153c3a7652SSerguei Katkov // If the loop already has metadata, retain it. 2163c3a7652SSerguei Katkov MDNode *LoopID = TheLoop->getLoopID(); 2173c3a7652SSerguei Katkov if (LoopID) { 2183c3a7652SSerguei Katkov for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 2193c3a7652SSerguei Katkov MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 2207f8c8095SSerguei Katkov // If it is of form key = value, try to parse it. 2217f8c8095SSerguei Katkov if (Node->getNumOperands() == 2) { 2227f8c8095SSerguei Katkov MDString *S = dyn_cast<MDString>(Node->getOperand(0)); 2237f8c8095SSerguei Katkov if (S && S->getString().equals(StringMD)) { 2247f8c8095SSerguei Katkov ConstantInt *IntMD = 2257f8c8095SSerguei Katkov mdconst::extract_or_null<ConstantInt>(Node->getOperand(1)); 2267f8c8095SSerguei Katkov if (IntMD && IntMD->getSExtValue() == V) 2277f8c8095SSerguei Katkov // It is already in place. Do nothing. 2287f8c8095SSerguei Katkov return; 2297f8c8095SSerguei Katkov // We need to update the value, so just skip it here and it will 2307f8c8095SSerguei Katkov // be added after copying other existed nodes. 2317f8c8095SSerguei Katkov continue; 2327f8c8095SSerguei Katkov } 2337f8c8095SSerguei Katkov } 2343c3a7652SSerguei Katkov MDs.push_back(Node); 2353c3a7652SSerguei Katkov } 2363c3a7652SSerguei Katkov } 2373c3a7652SSerguei Katkov // Add new metadata. 2387f8c8095SSerguei Katkov MDs.push_back(createStringMetadata(TheLoop, StringMD, V)); 2393c3a7652SSerguei Katkov // Replace current metadata node with new one. 2403c3a7652SSerguei Katkov LLVMContext &Context = TheLoop->getHeader()->getContext(); 2413c3a7652SSerguei Katkov MDNode *NewLoopID = MDNode::get(Context, MDs); 2423c3a7652SSerguei Katkov // Set operand 0 to refer to the loop id itself. 2433c3a7652SSerguei Katkov NewLoopID->replaceOperandWith(0, NewLoopID); 2443c3a7652SSerguei Katkov TheLoop->setLoopID(NewLoopID); 2453c3a7652SSerguei Katkov } 2463c3a7652SSerguei Katkov 24772448525SMichael Kruse /// Find string metadata for loop 24872448525SMichael Kruse /// 24972448525SMichael Kruse /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 25072448525SMichael Kruse /// operand or null otherwise. If the string metadata is not found return 25172448525SMichael Kruse /// Optional's not-a-value. 252978ba615SMichael Kruse Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, 25372448525SMichael Kruse StringRef Name) { 254978ba615SMichael Kruse MDNode *MD = findOptionMDForLoop(TheLoop, Name); 25572448525SMichael Kruse if (!MD) 25672448525SMichael Kruse return None; 257fe3def7cSAdam Nemet switch (MD->getNumOperands()) { 258fe3def7cSAdam Nemet case 1: 259fe3def7cSAdam Nemet return nullptr; 260fe3def7cSAdam Nemet case 2: 261fe3def7cSAdam Nemet return &MD->getOperand(1); 262fe3def7cSAdam Nemet default: 263fe3def7cSAdam Nemet llvm_unreachable("loop metadata has 0 or 1 operand"); 264963341c8SAdam Nemet } 265fe3def7cSAdam Nemet } 26672448525SMichael Kruse 26772448525SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, 26872448525SMichael Kruse StringRef Name) { 269978ba615SMichael Kruse MDNode *MD = findOptionMDForLoop(TheLoop, Name); 270978ba615SMichael Kruse if (!MD) 271fe3def7cSAdam Nemet return None; 272978ba615SMichael Kruse switch (MD->getNumOperands()) { 27372448525SMichael Kruse case 1: 27472448525SMichael Kruse // When the value is absent it is interpreted as 'attribute set'. 27572448525SMichael Kruse return true; 27672448525SMichael Kruse case 2: 277f9027e55SAlina Sbirlea if (ConstantInt *IntMD = 278f9027e55SAlina Sbirlea mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) 279f9027e55SAlina Sbirlea return IntMD->getZExtValue(); 280f9027e55SAlina Sbirlea return true; 28172448525SMichael Kruse } 28272448525SMichael Kruse llvm_unreachable("unexpected number of options"); 28372448525SMichael Kruse } 28472448525SMichael Kruse 28572448525SMichael Kruse static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 28672448525SMichael Kruse return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 28772448525SMichael Kruse } 28872448525SMichael Kruse 28972448525SMichael Kruse llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 29072448525SMichael Kruse StringRef Name) { 29172448525SMichael Kruse const MDOperand *AttrMD = 29272448525SMichael Kruse findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 29372448525SMichael Kruse if (!AttrMD) 29472448525SMichael Kruse return None; 29572448525SMichael Kruse 29672448525SMichael Kruse ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 29772448525SMichael Kruse if (!IntMD) 29872448525SMichael Kruse return None; 29972448525SMichael Kruse 30072448525SMichael Kruse return IntMD->getSExtValue(); 30172448525SMichael Kruse } 30272448525SMichael Kruse 30372448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID( 30472448525SMichael Kruse MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 30572448525SMichael Kruse const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 30672448525SMichael Kruse if (!OrigLoopID) { 30772448525SMichael Kruse if (AlwaysNew) 30872448525SMichael Kruse return nullptr; 30972448525SMichael Kruse return None; 31072448525SMichael Kruse } 31172448525SMichael Kruse 31272448525SMichael Kruse assert(OrigLoopID->getOperand(0) == OrigLoopID); 31372448525SMichael Kruse 31472448525SMichael Kruse bool InheritAllAttrs = !InheritOptionsExceptPrefix; 31572448525SMichael Kruse bool InheritSomeAttrs = 31672448525SMichael Kruse InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 31772448525SMichael Kruse SmallVector<Metadata *, 8> MDs; 31872448525SMichael Kruse MDs.push_back(nullptr); 31972448525SMichael Kruse 32072448525SMichael Kruse bool Changed = false; 32172448525SMichael Kruse if (InheritAllAttrs || InheritSomeAttrs) { 32272448525SMichael Kruse for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 32372448525SMichael Kruse MDNode *Op = cast<MDNode>(Existing.get()); 32472448525SMichael Kruse 32572448525SMichael Kruse auto InheritThisAttribute = [InheritSomeAttrs, 32672448525SMichael Kruse InheritOptionsExceptPrefix](MDNode *Op) { 32772448525SMichael Kruse if (!InheritSomeAttrs) 32872448525SMichael Kruse return false; 32972448525SMichael Kruse 33072448525SMichael Kruse // Skip malformatted attribute metadata nodes. 33172448525SMichael Kruse if (Op->getNumOperands() == 0) 33272448525SMichael Kruse return true; 33372448525SMichael Kruse Metadata *NameMD = Op->getOperand(0).get(); 33472448525SMichael Kruse if (!isa<MDString>(NameMD)) 33572448525SMichael Kruse return true; 33672448525SMichael Kruse StringRef AttrName = cast<MDString>(NameMD)->getString(); 33772448525SMichael Kruse 33872448525SMichael Kruse // Do not inherit excluded attributes. 33972448525SMichael Kruse return !AttrName.startswith(InheritOptionsExceptPrefix); 34072448525SMichael Kruse }; 34172448525SMichael Kruse 34272448525SMichael Kruse if (InheritThisAttribute(Op)) 34372448525SMichael Kruse MDs.push_back(Op); 34472448525SMichael Kruse else 34572448525SMichael Kruse Changed = true; 34672448525SMichael Kruse } 34772448525SMichael Kruse } else { 34872448525SMichael Kruse // Modified if we dropped at least one attribute. 34972448525SMichael Kruse Changed = OrigLoopID->getNumOperands() > 1; 35072448525SMichael Kruse } 35172448525SMichael Kruse 35272448525SMichael Kruse bool HasAnyFollowup = false; 35372448525SMichael Kruse for (StringRef OptionName : FollowupOptions) { 354978ba615SMichael Kruse MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 35572448525SMichael Kruse if (!FollowupNode) 35672448525SMichael Kruse continue; 35772448525SMichael Kruse 35872448525SMichael Kruse HasAnyFollowup = true; 35972448525SMichael Kruse for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 36072448525SMichael Kruse MDs.push_back(Option.get()); 36172448525SMichael Kruse Changed = true; 36272448525SMichael Kruse } 36372448525SMichael Kruse } 36472448525SMichael Kruse 36572448525SMichael Kruse // Attributes of the followup loop not specified explicity, so signal to the 36672448525SMichael Kruse // transformation pass to add suitable attributes. 36772448525SMichael Kruse if (!AlwaysNew && !HasAnyFollowup) 36872448525SMichael Kruse return None; 36972448525SMichael Kruse 37072448525SMichael Kruse // If no attributes were added or remove, the previous loop Id can be reused. 37172448525SMichael Kruse if (!AlwaysNew && !Changed) 37272448525SMichael Kruse return OrigLoopID; 37372448525SMichael Kruse 37472448525SMichael Kruse // No attributes is equivalent to having no !llvm.loop metadata at all. 37572448525SMichael Kruse if (MDs.size() == 1) 37672448525SMichael Kruse return nullptr; 37772448525SMichael Kruse 37872448525SMichael Kruse // Build the new loop ID. 37972448525SMichael Kruse MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 38072448525SMichael Kruse FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 38172448525SMichael Kruse return FollowupLoopID; 38272448525SMichael Kruse } 38372448525SMichael Kruse 38472448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) { 38572448525SMichael Kruse return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 38672448525SMichael Kruse } 38772448525SMichael Kruse 3884f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) { 3894f64f1baSTim Corringham return getBooleanLoopAttribute(L, LLVMLoopDisableLICM); 3904f64f1baSTim Corringham } 3914f64f1baSTim Corringham 39272448525SMichael Kruse TransformationMode llvm::hasUnrollTransformation(Loop *L) { 39372448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 39472448525SMichael Kruse return TM_SuppressedByUser; 39572448525SMichael Kruse 39672448525SMichael Kruse Optional<int> Count = 39772448525SMichael Kruse getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 39872448525SMichael Kruse if (Count.hasValue()) 39972448525SMichael Kruse return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 40072448525SMichael Kruse 40172448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 40272448525SMichael Kruse return TM_ForcedByUser; 40372448525SMichael Kruse 40472448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 40572448525SMichael Kruse return TM_ForcedByUser; 40672448525SMichael Kruse 40772448525SMichael Kruse if (hasDisableAllTransformsHint(L)) 40872448525SMichael Kruse return TM_Disable; 40972448525SMichael Kruse 41072448525SMichael Kruse return TM_Unspecified; 41172448525SMichael Kruse } 41272448525SMichael Kruse 41372448525SMichael Kruse TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 41472448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 41572448525SMichael Kruse return TM_SuppressedByUser; 41672448525SMichael Kruse 41772448525SMichael Kruse Optional<int> Count = 41872448525SMichael Kruse getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 41972448525SMichael Kruse if (Count.hasValue()) 42072448525SMichael Kruse return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 42172448525SMichael Kruse 42272448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 42372448525SMichael Kruse return TM_ForcedByUser; 42472448525SMichael Kruse 42572448525SMichael Kruse if (hasDisableAllTransformsHint(L)) 42672448525SMichael Kruse return TM_Disable; 42772448525SMichael Kruse 42872448525SMichael Kruse return TM_Unspecified; 42972448525SMichael Kruse } 43072448525SMichael Kruse 43172448525SMichael Kruse TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 43272448525SMichael Kruse Optional<bool> Enable = 43372448525SMichael Kruse getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 43472448525SMichael Kruse 43572448525SMichael Kruse if (Enable == false) 43672448525SMichael Kruse return TM_SuppressedByUser; 43772448525SMichael Kruse 43872448525SMichael Kruse Optional<int> VectorizeWidth = 43972448525SMichael Kruse getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 44072448525SMichael Kruse Optional<int> InterleaveCount = 44172448525SMichael Kruse getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 44272448525SMichael Kruse 44372448525SMichael Kruse // 'Forcing' vector width and interleave count to one effectively disables 44472448525SMichael Kruse // this tranformation. 44570560a0aSMichael Kruse if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1) 44672448525SMichael Kruse return TM_SuppressedByUser; 44772448525SMichael Kruse 44872448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 44972448525SMichael Kruse return TM_Disable; 45072448525SMichael Kruse 45170560a0aSMichael Kruse if (Enable == true) 45270560a0aSMichael Kruse return TM_ForcedByUser; 45370560a0aSMichael Kruse 45472448525SMichael Kruse if (VectorizeWidth == 1 && InterleaveCount == 1) 45572448525SMichael Kruse return TM_Disable; 45672448525SMichael Kruse 45772448525SMichael Kruse if (VectorizeWidth > 1 || InterleaveCount > 1) 45872448525SMichael Kruse return TM_Enable; 45972448525SMichael Kruse 46072448525SMichael Kruse if (hasDisableAllTransformsHint(L)) 46172448525SMichael Kruse return TM_Disable; 46272448525SMichael Kruse 46372448525SMichael Kruse return TM_Unspecified; 46472448525SMichael Kruse } 46572448525SMichael Kruse 46672448525SMichael Kruse TransformationMode llvm::hasDistributeTransformation(Loop *L) { 46772448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 46872448525SMichael Kruse return TM_ForcedByUser; 46972448525SMichael Kruse 47072448525SMichael Kruse if (hasDisableAllTransformsHint(L)) 47172448525SMichael Kruse return TM_Disable; 47272448525SMichael Kruse 47372448525SMichael Kruse return TM_Unspecified; 47472448525SMichael Kruse } 47572448525SMichael Kruse 47672448525SMichael Kruse TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 47772448525SMichael Kruse if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 47872448525SMichael Kruse return TM_SuppressedByUser; 47972448525SMichael Kruse 48072448525SMichael Kruse if (hasDisableAllTransformsHint(L)) 48172448525SMichael Kruse return TM_Disable; 48272448525SMichael Kruse 48372448525SMichael Kruse return TM_Unspecified; 484963341c8SAdam Nemet } 485122f984aSEvgeniy Stepanov 4867ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop. 4877ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point. 4887ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16> 4897ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 4907ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16> Worklist; 4917ed5856aSAlina Sbirlea auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 4927ed5856aSAlina Sbirlea // Only include subregions in the top level loop. 4937ed5856aSAlina Sbirlea BasicBlock *BB = DTN->getBlock(); 4947ed5856aSAlina Sbirlea if (CurLoop->contains(BB)) 4957ed5856aSAlina Sbirlea Worklist.push_back(DTN); 4967ed5856aSAlina Sbirlea }; 4977ed5856aSAlina Sbirlea 4987ed5856aSAlina Sbirlea AddRegionToWorklist(N); 4997ed5856aSAlina Sbirlea 5007ed5856aSAlina Sbirlea for (size_t I = 0; I < Worklist.size(); I++) 5017ed5856aSAlina Sbirlea for (DomTreeNode *Child : Worklist[I]->getChildren()) 5027ed5856aSAlina Sbirlea AddRegionToWorklist(Child); 5037ed5856aSAlina Sbirlea 5047ed5856aSAlina Sbirlea return Worklist; 5057ed5856aSAlina Sbirlea } 5067ed5856aSAlina Sbirlea 507df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr, 508df3e71e0SMarcello Maggioni ScalarEvolution *SE = nullptr, 509df3e71e0SMarcello Maggioni LoopInfo *LI = nullptr) { 510899809d5SHans Wennborg assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 511df3e71e0SMarcello Maggioni auto *Preheader = L->getLoopPreheader(); 512df3e71e0SMarcello Maggioni assert(Preheader && "Preheader should exist!"); 513df3e71e0SMarcello Maggioni 514df3e71e0SMarcello Maggioni // Now that we know the removal is safe, remove the loop by changing the 515df3e71e0SMarcello Maggioni // branch from the preheader to go to the single exit block. 516df3e71e0SMarcello Maggioni // 517df3e71e0SMarcello Maggioni // Because we're deleting a large chunk of code at once, the sequence in which 518df3e71e0SMarcello Maggioni // we remove things is very important to avoid invalidation issues. 519df3e71e0SMarcello Maggioni 520df3e71e0SMarcello Maggioni // Tell ScalarEvolution that the loop is deleted. Do this before 521df3e71e0SMarcello Maggioni // deleting the loop so that ScalarEvolution can look at the loop 522df3e71e0SMarcello Maggioni // to determine what it needs to clean up. 523df3e71e0SMarcello Maggioni if (SE) 524df3e71e0SMarcello Maggioni SE->forgetLoop(L); 525df3e71e0SMarcello Maggioni 526df3e71e0SMarcello Maggioni auto *ExitBlock = L->getUniqueExitBlock(); 527df3e71e0SMarcello Maggioni assert(ExitBlock && "Should have a unique exit block!"); 528df3e71e0SMarcello Maggioni assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 529df3e71e0SMarcello Maggioni 530df3e71e0SMarcello Maggioni auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 531df3e71e0SMarcello Maggioni assert(OldBr && "Preheader must end with a branch"); 532df3e71e0SMarcello Maggioni assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 533df3e71e0SMarcello Maggioni // Connect the preheader to the exit block. Keep the old edge to the header 534df3e71e0SMarcello Maggioni // around to perform the dominator tree update in two separate steps 535df3e71e0SMarcello Maggioni // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 536df3e71e0SMarcello Maggioni // preheader -> header. 537df3e71e0SMarcello Maggioni // 538df3e71e0SMarcello Maggioni // 539df3e71e0SMarcello Maggioni // 0. Preheader 1. Preheader 2. Preheader 540df3e71e0SMarcello Maggioni // | | | | 541df3e71e0SMarcello Maggioni // V | V | 542df3e71e0SMarcello Maggioni // Header <--\ | Header <--\ | Header <--\ 543df3e71e0SMarcello Maggioni // | | | | | | | | | | | 544df3e71e0SMarcello Maggioni // | V | | | V | | | V | 545df3e71e0SMarcello Maggioni // | Body --/ | | Body --/ | | Body --/ 546df3e71e0SMarcello Maggioni // V V V V V 547df3e71e0SMarcello Maggioni // Exit Exit Exit 548df3e71e0SMarcello Maggioni // 549df3e71e0SMarcello Maggioni // By doing this is two separate steps we can perform the dominator tree 550df3e71e0SMarcello Maggioni // update without using the batch update API. 551df3e71e0SMarcello Maggioni // 552df3e71e0SMarcello Maggioni // Even when the loop is never executed, we cannot remove the edge from the 553df3e71e0SMarcello Maggioni // source block to the exit block. Consider the case where the unexecuted loop 554df3e71e0SMarcello Maggioni // branches back to an outer loop. If we deleted the loop and removed the edge 555df3e71e0SMarcello Maggioni // coming to this inner loop, this will break the outer loop structure (by 556df3e71e0SMarcello Maggioni // deleting the backedge of the outer loop). If the outer loop is indeed a 557df3e71e0SMarcello Maggioni // non-loop, it will be deleted in a future iteration of loop deletion pass. 558df3e71e0SMarcello Maggioni IRBuilder<> Builder(OldBr); 559df3e71e0SMarcello Maggioni Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 560df3e71e0SMarcello Maggioni // Remove the old branch. The conditional branch becomes a new terminator. 561df3e71e0SMarcello Maggioni OldBr->eraseFromParent(); 562df3e71e0SMarcello Maggioni 563df3e71e0SMarcello Maggioni // Rewrite phis in the exit block to get their inputs from the Preheader 564df3e71e0SMarcello Maggioni // instead of the exiting block. 565c7fc81e6SBenjamin Kramer for (PHINode &P : ExitBlock->phis()) { 566df3e71e0SMarcello Maggioni // Set the zero'th element of Phi to be from the preheader and remove all 567df3e71e0SMarcello Maggioni // other incoming values. Given the loop has dedicated exits, all other 568df3e71e0SMarcello Maggioni // incoming values must be from the exiting blocks. 569df3e71e0SMarcello Maggioni int PredIndex = 0; 570c7fc81e6SBenjamin Kramer P.setIncomingBlock(PredIndex, Preheader); 571df3e71e0SMarcello Maggioni // Removes all incoming values from all other exiting blocks (including 572df3e71e0SMarcello Maggioni // duplicate values from an exiting block). 573df3e71e0SMarcello Maggioni // Nuke all entries except the zero'th entry which is the preheader entry. 574df3e71e0SMarcello Maggioni // NOTE! We need to remove Incoming Values in the reverse order as done 575df3e71e0SMarcello Maggioni // below, to keep the indices valid for deletion (removeIncomingValues 576df3e71e0SMarcello Maggioni // updates getNumIncomingValues and shifts all values down into the operand 577df3e71e0SMarcello Maggioni // being deleted). 578c7fc81e6SBenjamin Kramer for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 579c7fc81e6SBenjamin Kramer P.removeIncomingValue(e - i, false); 580df3e71e0SMarcello Maggioni 581c7fc81e6SBenjamin Kramer assert((P.getNumIncomingValues() == 1 && 582c7fc81e6SBenjamin Kramer P.getIncomingBlock(PredIndex) == Preheader) && 583df3e71e0SMarcello Maggioni "Should have exactly one value and that's from the preheader!"); 584df3e71e0SMarcello Maggioni } 585df3e71e0SMarcello Maggioni 586df3e71e0SMarcello Maggioni // Disconnect the loop body by branching directly to its exit. 587df3e71e0SMarcello Maggioni Builder.SetInsertPoint(Preheader->getTerminator()); 588df3e71e0SMarcello Maggioni Builder.CreateBr(ExitBlock); 589df3e71e0SMarcello Maggioni // Remove the old branch. 590df3e71e0SMarcello Maggioni Preheader->getTerminator()->eraseFromParent(); 591df3e71e0SMarcello Maggioni 59221a8b605SChijun Sima DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 593df3e71e0SMarcello Maggioni if (DT) { 594df3e71e0SMarcello Maggioni // Update the dominator tree by informing it about the new edge from the 595f131d611SChijun Sima // preheader to the exit and the removed edge. 596f131d611SChijun Sima DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}, 597f131d611SChijun Sima {DominatorTree::Delete, Preheader, L->getHeader()}}); 598df3e71e0SMarcello Maggioni } 599df3e71e0SMarcello Maggioni 600744c3c32SDavide Italiano // Use a map to unique and a vector to guarantee deterministic ordering. 6018ee59ca6SDavide Italiano llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 602744c3c32SDavide Italiano llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 603744c3c32SDavide Italiano 604a757d65cSSerguei Katkov // Given LCSSA form is satisfied, we should not have users of instructions 605a757d65cSSerguei Katkov // within the dead loop outside of the loop. However, LCSSA doesn't take 606a757d65cSSerguei Katkov // unreachable uses into account. We handle them here. 607a757d65cSSerguei Katkov // We could do it after drop all references (in this case all users in the 608a757d65cSSerguei Katkov // loop will be already eliminated and we have less work to do but according 609a757d65cSSerguei Katkov // to API doc of User::dropAllReferences only valid operation after dropping 610a757d65cSSerguei Katkov // references, is deletion. So let's substitute all usages of 611a757d65cSSerguei Katkov // instruction from the loop with undef value of corresponding type first. 612a757d65cSSerguei Katkov for (auto *Block : L->blocks()) 613a757d65cSSerguei Katkov for (Instruction &I : *Block) { 614a757d65cSSerguei Katkov auto *Undef = UndefValue::get(I.getType()); 615a757d65cSSerguei Katkov for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 616a757d65cSSerguei Katkov Use &U = *UI; 617a757d65cSSerguei Katkov ++UI; 618a757d65cSSerguei Katkov if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 619a757d65cSSerguei Katkov if (L->contains(Usr->getParent())) 620a757d65cSSerguei Katkov continue; 621a757d65cSSerguei Katkov // If we have a DT then we can check that uses outside a loop only in 622a757d65cSSerguei Katkov // unreachable block. 623a757d65cSSerguei Katkov if (DT) 624a757d65cSSerguei Katkov assert(!DT->isReachableFromEntry(U) && 625a757d65cSSerguei Katkov "Unexpected user in reachable block"); 626a757d65cSSerguei Katkov U.set(Undef); 627a757d65cSSerguei Katkov } 628744c3c32SDavide Italiano auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 629744c3c32SDavide Italiano if (!DVI) 630744c3c32SDavide Italiano continue; 6318ee59ca6SDavide Italiano auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 6328ee59ca6SDavide Italiano if (Key != DeadDebugSet.end()) 633744c3c32SDavide Italiano continue; 6348ee59ca6SDavide Italiano DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 635744c3c32SDavide Italiano DeadDebugInst.push_back(DVI); 636a757d65cSSerguei Katkov } 637a757d65cSSerguei Katkov 638744c3c32SDavide Italiano // After the loop has been deleted all the values defined and modified 639744c3c32SDavide Italiano // inside the loop are going to be unavailable. 640744c3c32SDavide Italiano // Since debug values in the loop have been deleted, inserting an undef 641744c3c32SDavide Italiano // dbg.value truncates the range of any dbg.value before the loop where the 642744c3c32SDavide Italiano // loop used to be. This is particularly important for constant values. 643744c3c32SDavide Italiano DIBuilder DIB(*ExitBlock->getModule()); 644e5be660eSRoman Lebedev Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 645e5be660eSRoman Lebedev assert(InsertDbgValueBefore && 646e5be660eSRoman Lebedev "There should be a non-PHI instruction in exit block, else these " 647e5be660eSRoman Lebedev "instructions will have no parent."); 648744c3c32SDavide Italiano for (auto *DVI : DeadDebugInst) 649e5be660eSRoman Lebedev DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), 650e5be660eSRoman Lebedev DVI->getVariable(), DVI->getExpression(), 651e5be660eSRoman Lebedev DVI->getDebugLoc(), InsertDbgValueBefore); 652744c3c32SDavide Italiano 653df3e71e0SMarcello Maggioni // Remove the block from the reference counting scheme, so that we can 654df3e71e0SMarcello Maggioni // delete it freely later. 655df3e71e0SMarcello Maggioni for (auto *Block : L->blocks()) 656df3e71e0SMarcello Maggioni Block->dropAllReferences(); 657df3e71e0SMarcello Maggioni 658df3e71e0SMarcello Maggioni if (LI) { 659df3e71e0SMarcello Maggioni // Erase the instructions and the blocks without having to worry 660df3e71e0SMarcello Maggioni // about ordering because we already dropped the references. 661df3e71e0SMarcello Maggioni // NOTE: This iteration is safe because erasing the block does not remove 662df3e71e0SMarcello Maggioni // its entry from the loop's block list. We do that in the next section. 663df3e71e0SMarcello Maggioni for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 664df3e71e0SMarcello Maggioni LpI != LpE; ++LpI) 665df3e71e0SMarcello Maggioni (*LpI)->eraseFromParent(); 666df3e71e0SMarcello Maggioni 667df3e71e0SMarcello Maggioni // Finally, the blocks from loopinfo. This has to happen late because 668df3e71e0SMarcello Maggioni // otherwise our loop iterators won't work. 669df3e71e0SMarcello Maggioni 670df3e71e0SMarcello Maggioni SmallPtrSet<BasicBlock *, 8> blocks; 671df3e71e0SMarcello Maggioni blocks.insert(L->block_begin(), L->block_end()); 672df3e71e0SMarcello Maggioni for (BasicBlock *BB : blocks) 673df3e71e0SMarcello Maggioni LI->removeBlock(BB); 674df3e71e0SMarcello Maggioni 675df3e71e0SMarcello Maggioni // The last step is to update LoopInfo now that we've eliminated this loop. 676df3e71e0SMarcello Maggioni LI->erase(L); 677df3e71e0SMarcello Maggioni } 678df3e71e0SMarcello Maggioni } 679df3e71e0SMarcello Maggioni 68041d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { 68145c43e7dSSerguei Katkov // Support loops with an exiting latch and other existing exists only 68245c43e7dSSerguei Katkov // deoptimize. 68341d72a86SDehao Chen 684d24ddcd6SHiroshi Inoue // Get the branch weights for the loop's backedge. 68545c43e7dSSerguei Katkov BasicBlock *Latch = L->getLoopLatch(); 68645c43e7dSSerguei Katkov if (!Latch) 68745c43e7dSSerguei Katkov return None; 68845c43e7dSSerguei Katkov BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 68945c43e7dSSerguei Katkov if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 69041d72a86SDehao Chen return None; 69141d72a86SDehao Chen 69241d72a86SDehao Chen assert((LatchBR->getSuccessor(0) == L->getHeader() || 69341d72a86SDehao Chen LatchBR->getSuccessor(1) == L->getHeader()) && 69441d72a86SDehao Chen "At least one edge out of the latch must go to the header"); 69541d72a86SDehao Chen 69645c43e7dSSerguei Katkov SmallVector<BasicBlock *, 4> ExitBlocks; 69745c43e7dSSerguei Katkov L->getUniqueNonLatchExitBlocks(ExitBlocks); 69845c43e7dSSerguei Katkov if (any_of(ExitBlocks, [](const BasicBlock *EB) { 69945c43e7dSSerguei Katkov return !EB->getTerminatingDeoptimizeCall(); 70045c43e7dSSerguei Katkov })) 70145c43e7dSSerguei Katkov return None; 70245c43e7dSSerguei Katkov 70341d72a86SDehao Chen // To estimate the number of times the loop body was executed, we want to 70441d72a86SDehao Chen // know the number of times the backedge was taken, vs. the number of times 70541d72a86SDehao Chen // we exited the loop. 70641d72a86SDehao Chen uint64_t TrueVal, FalseVal; 707b151a641SMichael Kuperstein if (!LatchBR->extractProfMetadata(TrueVal, FalseVal)) 70841d72a86SDehao Chen return None; 70941d72a86SDehao Chen 710b151a641SMichael Kuperstein if (!TrueVal || !FalseVal) 711b151a641SMichael Kuperstein return 0; 71241d72a86SDehao Chen 713b151a641SMichael Kuperstein // Divide the count of the backedge by the count of the edge exiting the loop, 714b151a641SMichael Kuperstein // rounding to nearest. 71541d72a86SDehao Chen if (LatchBR->getSuccessor(0) == L->getHeader()) 716b151a641SMichael Kuperstein return (TrueVal + (FalseVal / 2)) / FalseVal; 71741d72a86SDehao Chen else 718b151a641SMichael Kuperstein return (FalseVal + (TrueVal / 2)) / TrueVal; 71941d72a86SDehao Chen } 720cf9daa33SAmara Emerson 7216cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 722395b80cdSDavid Green ScalarEvolution &SE) { 723395b80cdSDavid Green Loop *OuterL = InnerLoop->getParentLoop(); 724395b80cdSDavid Green if (!OuterL) 725395b80cdSDavid Green return true; 726395b80cdSDavid Green 727395b80cdSDavid Green // Get the backedge taken count for the inner loop 728395b80cdSDavid Green BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 729395b80cdSDavid Green const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 730395b80cdSDavid Green if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 731395b80cdSDavid Green !InnerLoopBECountSC->getType()->isIntegerTy()) 732395b80cdSDavid Green return false; 733395b80cdSDavid Green 734395b80cdSDavid Green // Get whether count is invariant to the outer loop 735395b80cdSDavid Green ScalarEvolution::LoopDisposition LD = 736395b80cdSDavid Green SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 737395b80cdSDavid Green if (LD != ScalarEvolution::LoopInvariant) 738395b80cdSDavid Green return false; 739395b80cdSDavid Green 740395b80cdSDavid Green return true; 741395b80cdSDavid Green } 742395b80cdSDavid Green 7436594dc37SVikram TV Value *llvm::createMinMaxOp(IRBuilder<> &Builder, 7446594dc37SVikram TV RecurrenceDescriptor::MinMaxRecurrenceKind RK, 7456594dc37SVikram TV Value *Left, Value *Right) { 7466594dc37SVikram TV CmpInst::Predicate P = CmpInst::ICMP_NE; 7476594dc37SVikram TV switch (RK) { 7486594dc37SVikram TV default: 7496594dc37SVikram TV llvm_unreachable("Unknown min/max recurrence kind"); 7506594dc37SVikram TV case RecurrenceDescriptor::MRK_UIntMin: 7516594dc37SVikram TV P = CmpInst::ICMP_ULT; 7526594dc37SVikram TV break; 7536594dc37SVikram TV case RecurrenceDescriptor::MRK_UIntMax: 7546594dc37SVikram TV P = CmpInst::ICMP_UGT; 7556594dc37SVikram TV break; 7566594dc37SVikram TV case RecurrenceDescriptor::MRK_SIntMin: 7576594dc37SVikram TV P = CmpInst::ICMP_SLT; 7586594dc37SVikram TV break; 7596594dc37SVikram TV case RecurrenceDescriptor::MRK_SIntMax: 7606594dc37SVikram TV P = CmpInst::ICMP_SGT; 7616594dc37SVikram TV break; 7626594dc37SVikram TV case RecurrenceDescriptor::MRK_FloatMin: 7636594dc37SVikram TV P = CmpInst::FCMP_OLT; 7646594dc37SVikram TV break; 7656594dc37SVikram TV case RecurrenceDescriptor::MRK_FloatMax: 7666594dc37SVikram TV P = CmpInst::FCMP_OGT; 7676594dc37SVikram TV break; 7686594dc37SVikram TV } 7696594dc37SVikram TV 7706594dc37SVikram TV // We only match FP sequences that are 'fast', so we can unconditionally 7716594dc37SVikram TV // set it on any generated instructions. 7726594dc37SVikram TV IRBuilder<>::FastMathFlagGuard FMFG(Builder); 7736594dc37SVikram TV FastMathFlags FMF; 7746594dc37SVikram TV FMF.setFast(); 7756594dc37SVikram TV Builder.setFastMathFlags(FMF); 7766594dc37SVikram TV 7776594dc37SVikram TV Value *Cmp; 7786594dc37SVikram TV if (RK == RecurrenceDescriptor::MRK_FloatMin || 7796594dc37SVikram TV RK == RecurrenceDescriptor::MRK_FloatMax) 7806594dc37SVikram TV Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 7816594dc37SVikram TV else 7826594dc37SVikram TV Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 7836594dc37SVikram TV 7846594dc37SVikram TV Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 7856594dc37SVikram TV return Select; 7866594dc37SVikram TV } 7876594dc37SVikram TV 78823c2182cSSimon Pilgrim // Helper to generate an ordered reduction. 78923c2182cSSimon Pilgrim Value * 79023c2182cSSimon Pilgrim llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src, 79123c2182cSSimon Pilgrim unsigned Op, 79223c2182cSSimon Pilgrim RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 79323c2182cSSimon Pilgrim ArrayRef<Value *> RedOps) { 79423c2182cSSimon Pilgrim unsigned VF = Src->getType()->getVectorNumElements(); 79523c2182cSSimon Pilgrim 79623c2182cSSimon Pilgrim // Extract and apply reduction ops in ascending order: 79723c2182cSSimon Pilgrim // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 79823c2182cSSimon Pilgrim Value *Result = Acc; 79923c2182cSSimon Pilgrim for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 80023c2182cSSimon Pilgrim Value *Ext = 80123c2182cSSimon Pilgrim Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 80223c2182cSSimon Pilgrim 80323c2182cSSimon Pilgrim if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 80423c2182cSSimon Pilgrim Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 80523c2182cSSimon Pilgrim "bin.rdx"); 80623c2182cSSimon Pilgrim } else { 80723c2182cSSimon Pilgrim assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 80823c2182cSSimon Pilgrim "Invalid min/max"); 8096594dc37SVikram TV Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 81023c2182cSSimon Pilgrim } 81123c2182cSSimon Pilgrim 81223c2182cSSimon Pilgrim if (!RedOps.empty()) 81323c2182cSSimon Pilgrim propagateIRFlags(Result, RedOps); 81423c2182cSSimon Pilgrim } 81523c2182cSSimon Pilgrim 81623c2182cSSimon Pilgrim return Result; 81723c2182cSSimon Pilgrim } 81823c2182cSSimon Pilgrim 819cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction. 820836b0f48SAmara Emerson Value * 821836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, 822836b0f48SAmara Emerson RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 823ad62a3a2SSanjay Patel ArrayRef<Value *> RedOps) { 824cf9daa33SAmara Emerson unsigned VF = Src->getType()->getVectorNumElements(); 825cf9daa33SAmara Emerson // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 826cf9daa33SAmara Emerson // and vector ops, reducing the set of values being computed by half each 827cf9daa33SAmara Emerson // round. 828cf9daa33SAmara Emerson assert(isPowerOf2_32(VF) && 829cf9daa33SAmara Emerson "Reduction emission only supported for pow2 vectors!"); 830cf9daa33SAmara Emerson Value *TmpVec = Src; 831cf9daa33SAmara Emerson SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 832cf9daa33SAmara Emerson for (unsigned i = VF; i != 1; i >>= 1) { 833cf9daa33SAmara Emerson // Move the upper half of the vector to the lower half. 834cf9daa33SAmara Emerson for (unsigned j = 0; j != i / 2; ++j) 835cf9daa33SAmara Emerson ShuffleMask[j] = Builder.getInt32(i / 2 + j); 836cf9daa33SAmara Emerson 837cf9daa33SAmara Emerson // Fill the rest of the mask with undef. 838cf9daa33SAmara Emerson std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 839cf9daa33SAmara Emerson UndefValue::get(Builder.getInt32Ty())); 840cf9daa33SAmara Emerson 841cf9daa33SAmara Emerson Value *Shuf = Builder.CreateShuffleVector( 842cf9daa33SAmara Emerson TmpVec, UndefValue::get(TmpVec->getType()), 843cf9daa33SAmara Emerson ConstantVector::get(ShuffleMask), "rdx.shuf"); 844cf9daa33SAmara Emerson 845cf9daa33SAmara Emerson if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 846ad62a3a2SSanjay Patel // The builder propagates its fast-math-flags setting. 847ad62a3a2SSanjay Patel TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 848ad62a3a2SSanjay Patel "bin.rdx"); 849cf9daa33SAmara Emerson } else { 850cf9daa33SAmara Emerson assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 851cf9daa33SAmara Emerson "Invalid min/max"); 8526594dc37SVikram TV TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 853cf9daa33SAmara Emerson } 854cf9daa33SAmara Emerson if (!RedOps.empty()) 855cf9daa33SAmara Emerson propagateIRFlags(TmpVec, RedOps); 856cf9daa33SAmara Emerson } 857cf9daa33SAmara Emerson // The result is in the first element of the vector. 858cf9daa33SAmara Emerson return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 859cf9daa33SAmara Emerson } 860cf9daa33SAmara Emerson 861cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some 862cf9daa33SAmara Emerson /// flags (if generating min/max reductions). 863cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction( 864cf9daa33SAmara Emerson IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 865ad62a3a2SSanjay Patel Value *Src, TargetTransformInfo::ReductionFlags Flags, 866cf9daa33SAmara Emerson ArrayRef<Value *> RedOps) { 867cf9daa33SAmara Emerson assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); 868cf9daa33SAmara Emerson 869cf9daa33SAmara Emerson std::function<Value *()> BuildFunc; 870cf9daa33SAmara Emerson using RD = RecurrenceDescriptor; 871cf9daa33SAmara Emerson RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 872cf9daa33SAmara Emerson 873cf9daa33SAmara Emerson switch (Opcode) { 874cf9daa33SAmara Emerson case Instruction::Add: 875cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 876cf9daa33SAmara Emerson break; 877cf9daa33SAmara Emerson case Instruction::Mul: 878cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 879cf9daa33SAmara Emerson break; 880cf9daa33SAmara Emerson case Instruction::And: 881cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 882cf9daa33SAmara Emerson break; 883cf9daa33SAmara Emerson case Instruction::Or: 884cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 885cf9daa33SAmara Emerson break; 886cf9daa33SAmara Emerson case Instruction::Xor: 887cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 888cf9daa33SAmara Emerson break; 889cf9daa33SAmara Emerson case Instruction::FAdd: 890cf9daa33SAmara Emerson BuildFunc = [&]() { 891cbeb563cSSander de Smalen auto Rdx = Builder.CreateFAddReduce( 892cbeb563cSSander de Smalen Constant::getNullValue(Src->getType()->getVectorElementType()), Src); 893cf9daa33SAmara Emerson return Rdx; 894cf9daa33SAmara Emerson }; 895cf9daa33SAmara Emerson break; 896cf9daa33SAmara Emerson case Instruction::FMul: 897cf9daa33SAmara Emerson BuildFunc = [&]() { 898cbeb563cSSander de Smalen Type *Ty = Src->getType()->getVectorElementType(); 899cbeb563cSSander de Smalen auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); 900cf9daa33SAmara Emerson return Rdx; 901cf9daa33SAmara Emerson }; 902cf9daa33SAmara Emerson break; 903cf9daa33SAmara Emerson case Instruction::ICmp: 904cf9daa33SAmara Emerson if (Flags.IsMaxOp) { 905cf9daa33SAmara Emerson MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 906cf9daa33SAmara Emerson BuildFunc = [&]() { 907cf9daa33SAmara Emerson return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 908cf9daa33SAmara Emerson }; 909cf9daa33SAmara Emerson } else { 910cf9daa33SAmara Emerson MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 911cf9daa33SAmara Emerson BuildFunc = [&]() { 912cf9daa33SAmara Emerson return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 913cf9daa33SAmara Emerson }; 914cf9daa33SAmara Emerson } 915cf9daa33SAmara Emerson break; 916cf9daa33SAmara Emerson case Instruction::FCmp: 917cf9daa33SAmara Emerson if (Flags.IsMaxOp) { 918cf9daa33SAmara Emerson MinMaxKind = RD::MRK_FloatMax; 919cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 920cf9daa33SAmara Emerson } else { 921cf9daa33SAmara Emerson MinMaxKind = RD::MRK_FloatMin; 922cf9daa33SAmara Emerson BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 923cf9daa33SAmara Emerson } 924cf9daa33SAmara Emerson break; 925cf9daa33SAmara Emerson default: 926cf9daa33SAmara Emerson llvm_unreachable("Unhandled opcode"); 927cf9daa33SAmara Emerson break; 928cf9daa33SAmara Emerson } 929cf9daa33SAmara Emerson if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 930cf9daa33SAmara Emerson return BuildFunc(); 931ad62a3a2SSanjay Patel return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 932cf9daa33SAmara Emerson } 933cf9daa33SAmara Emerson 934cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor. 9353e069f57SSanjay Patel Value *llvm::createTargetReduction(IRBuilder<> &B, 936cf9daa33SAmara Emerson const TargetTransformInfo *TTI, 937cf9daa33SAmara Emerson RecurrenceDescriptor &Desc, Value *Src, 938cf9daa33SAmara Emerson bool NoNaN) { 939cf9daa33SAmara Emerson // TODO: Support in-order reductions based on the recurrence descriptor. 9403e069f57SSanjay Patel using RD = RecurrenceDescriptor; 9413e069f57SSanjay Patel RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 942cf9daa33SAmara Emerson TargetTransformInfo::ReductionFlags Flags; 943cf9daa33SAmara Emerson Flags.NoNaN = NoNaN; 944ad62a3a2SSanjay Patel 945ad62a3a2SSanjay Patel // All ops in the reduction inherit fast-math-flags from the recurrence 946ad62a3a2SSanjay Patel // descriptor. 947ad62a3a2SSanjay Patel IRBuilder<>::FastMathFlagGuard FMFGuard(B); 948ad62a3a2SSanjay Patel B.setFastMathFlags(Desc.getFastMathFlags()); 949ad62a3a2SSanjay Patel 950cf9daa33SAmara Emerson switch (RecKind) { 9513e069f57SSanjay Patel case RD::RK_FloatAdd: 952ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 9533e069f57SSanjay Patel case RD::RK_FloatMult: 954ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 9553e069f57SSanjay Patel case RD::RK_IntegerAdd: 956ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 9573e069f57SSanjay Patel case RD::RK_IntegerMult: 958ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 9593e069f57SSanjay Patel case RD::RK_IntegerAnd: 960ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 9613e069f57SSanjay Patel case RD::RK_IntegerOr: 962ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 9633e069f57SSanjay Patel case RD::RK_IntegerXor: 964ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 9653e069f57SSanjay Patel case RD::RK_IntegerMinMax: { 9663e069f57SSanjay Patel RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 9673e069f57SSanjay Patel Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 9683e069f57SSanjay Patel Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 969ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 970cf9daa33SAmara Emerson } 9713e069f57SSanjay Patel case RD::RK_FloatMinMax: { 9723e069f57SSanjay Patel Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 973ad62a3a2SSanjay Patel return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 974cf9daa33SAmara Emerson } 975cf9daa33SAmara Emerson default: 976cf9daa33SAmara Emerson llvm_unreachable("Unhandled RecKind"); 977cf9daa33SAmara Emerson } 978cf9daa33SAmara Emerson } 979cf9daa33SAmara Emerson 980a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 981a61f4b89SDinar Temirbulatov auto *VecOp = dyn_cast<Instruction>(I); 982a61f4b89SDinar Temirbulatov if (!VecOp) 983a61f4b89SDinar Temirbulatov return; 984a61f4b89SDinar Temirbulatov auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 985a61f4b89SDinar Temirbulatov : dyn_cast<Instruction>(OpValue); 986a61f4b89SDinar Temirbulatov if (!Intersection) 987a61f4b89SDinar Temirbulatov return; 988a61f4b89SDinar Temirbulatov const unsigned Opcode = Intersection->getOpcode(); 989a61f4b89SDinar Temirbulatov VecOp->copyIRFlags(Intersection); 990a61f4b89SDinar Temirbulatov for (auto *V : VL) { 991a61f4b89SDinar Temirbulatov auto *Instr = dyn_cast<Instruction>(V); 992a61f4b89SDinar Temirbulatov if (!Instr) 993a61f4b89SDinar Temirbulatov continue; 994a61f4b89SDinar Temirbulatov if (OpValue == nullptr || Opcode == Instr->getOpcode()) 995a61f4b89SDinar Temirbulatov VecOp->andIRFlags(V); 996cf9daa33SAmara Emerson } 997cf9daa33SAmara Emerson } 998a78dc4d6SMax Kazantsev 999a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1000a78dc4d6SMax Kazantsev ScalarEvolution &SE) { 1001a78dc4d6SMax Kazantsev const SCEV *Zero = SE.getZero(S->getType()); 1002a78dc4d6SMax Kazantsev return SE.isAvailableAtLoopEntry(S, L) && 1003a78dc4d6SMax Kazantsev SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1004a78dc4d6SMax Kazantsev } 1005a78dc4d6SMax Kazantsev 1006a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1007a78dc4d6SMax Kazantsev ScalarEvolution &SE) { 1008a78dc4d6SMax Kazantsev const SCEV *Zero = SE.getZero(S->getType()); 1009a78dc4d6SMax Kazantsev return SE.isAvailableAtLoopEntry(S, L) && 1010a78dc4d6SMax Kazantsev SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1011a78dc4d6SMax Kazantsev } 1012a78dc4d6SMax Kazantsev 1013a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1014a78dc4d6SMax Kazantsev bool Signed) { 1015a78dc4d6SMax Kazantsev unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1016a78dc4d6SMax Kazantsev APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1017a78dc4d6SMax Kazantsev APInt::getMinValue(BitWidth); 1018a78dc4d6SMax Kazantsev auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1019a78dc4d6SMax Kazantsev return SE.isAvailableAtLoopEntry(S, L) && 1020a78dc4d6SMax Kazantsev SE.isLoopEntryGuardedByCond(L, Predicate, S, 1021a78dc4d6SMax Kazantsev SE.getConstant(Min)); 1022a78dc4d6SMax Kazantsev } 1023a78dc4d6SMax Kazantsev 1024a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1025a78dc4d6SMax Kazantsev bool Signed) { 1026a78dc4d6SMax Kazantsev unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1027a78dc4d6SMax Kazantsev APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1028a78dc4d6SMax Kazantsev APInt::getMaxValue(BitWidth); 1029a78dc4d6SMax Kazantsev auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1030a78dc4d6SMax Kazantsev return SE.isAvailableAtLoopEntry(S, L) && 1031a78dc4d6SMax Kazantsev SE.isLoopEntryGuardedByCond(L, Predicate, S, 1032a78dc4d6SMax Kazantsev SE.getConstant(Max)); 1033a78dc4d6SMax Kazantsev } 1034