15a5ac124SDimitry Andric //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
25a5ac124SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65a5ac124SDimitry Andric //
75a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
85a5ac124SDimitry Andric //
95a5ac124SDimitry Andric // This file defines common loop utility functions.
105a5ac124SDimitry Andric //
115a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
125a5ac124SDimitry Andric
13b915e9e0SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
14cfca06d7SDimitry Andric #include "llvm/ADT/DenseSet.h"
15cfca06d7SDimitry Andric #include "llvm/ADT/PriorityWorklist.h"
1608bbd35aSDimitry Andric #include "llvm/ADT/ScopeExit.h"
17cfca06d7SDimitry Andric #include "llvm/ADT/SetVector.h"
18cfca06d7SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19cfca06d7SDimitry Andric #include "llvm/ADT/SmallVector.h"
2001095a5dSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
2101095a5dSDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
22e6d15924SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
2301095a5dSDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
246f8fc217SDimitry Andric #include "llvm/Analysis/InstSimplifyFolder.h"
25cfca06d7SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
26b915e9e0SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
27b915e9e0SDimitry Andric #include "llvm/Analysis/LoopPass.h"
281d5ae102SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
29e6d15924SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
30dd58ef01SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
31b915e9e0SDimitry Andric #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
32dd58ef01SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
33d8e91e46SDimitry Andric #include "llvm/IR/DIBuilder.h"
3401095a5dSDimitry Andric #include "llvm/IR/Dominators.h"
355a5ac124SDimitry Andric #include "llvm/IR/Instructions.h"
36d8e91e46SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
37cfca06d7SDimitry Andric #include "llvm/IR/MDBuilder.h"
38dd58ef01SDimitry Andric #include "llvm/IR/Module.h"
395a5ac124SDimitry Andric #include "llvm/IR/PatternMatch.h"
40e3b55780SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
415a5ac124SDimitry Andric #include "llvm/IR/ValueHandle.h"
42706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
4301095a5dSDimitry Andric #include "llvm/Pass.h"
445a5ac124SDimitry Andric #include "llvm/Support/Debug.h"
4508bbd35aSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
47cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
485a5ac124SDimitry Andric
495a5ac124SDimitry Andric using namespace llvm;
505a5ac124SDimitry Andric using namespace llvm::PatternMatch;
515a5ac124SDimitry Andric
525a5ac124SDimitry Andric #define DEBUG_TYPE "loop-utils"
535a5ac124SDimitry Andric
54d8e91e46SDimitry Andric static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
551d5ae102SDimitry Andric static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
56dd58ef01SDimitry Andric
formDedicatedExitBlocks(Loop * L,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)5708bbd35aSDimitry Andric bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
58e6d15924SDimitry Andric MemorySSAUpdater *MSSAU,
5908bbd35aSDimitry Andric bool PreserveLCSSA) {
6008bbd35aSDimitry Andric bool Changed = false;
6108bbd35aSDimitry Andric
6208bbd35aSDimitry Andric // We re-use a vector for the in-loop predecesosrs.
6308bbd35aSDimitry Andric SmallVector<BasicBlock *, 4> InLoopPredecessors;
6408bbd35aSDimitry Andric
6508bbd35aSDimitry Andric auto RewriteExit = [&](BasicBlock *BB) {
6608bbd35aSDimitry Andric assert(InLoopPredecessors.empty() &&
6708bbd35aSDimitry Andric "Must start with an empty predecessors list!");
6808bbd35aSDimitry Andric auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
6908bbd35aSDimitry Andric
7008bbd35aSDimitry Andric // See if there are any non-loop predecessors of this exit block and
7108bbd35aSDimitry Andric // keep track of the in-loop predecessors.
7208bbd35aSDimitry Andric bool IsDedicatedExit = true;
7308bbd35aSDimitry Andric for (auto *PredBB : predecessors(BB))
7408bbd35aSDimitry Andric if (L->contains(PredBB)) {
7508bbd35aSDimitry Andric if (isa<IndirectBrInst>(PredBB->getTerminator()))
7608bbd35aSDimitry Andric // We cannot rewrite exiting edges from an indirectbr.
7708bbd35aSDimitry Andric return false;
7808bbd35aSDimitry Andric
7908bbd35aSDimitry Andric InLoopPredecessors.push_back(PredBB);
8008bbd35aSDimitry Andric } else {
8108bbd35aSDimitry Andric IsDedicatedExit = false;
8208bbd35aSDimitry Andric }
8308bbd35aSDimitry Andric
8408bbd35aSDimitry Andric assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
8508bbd35aSDimitry Andric
8608bbd35aSDimitry Andric // Nothing to do if this is already a dedicated exit.
8708bbd35aSDimitry Andric if (IsDedicatedExit)
8808bbd35aSDimitry Andric return false;
8908bbd35aSDimitry Andric
9008bbd35aSDimitry Andric auto *NewExitBB = SplitBlockPredecessors(
91e6d15924SDimitry Andric BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
9208bbd35aSDimitry Andric
9308bbd35aSDimitry Andric if (!NewExitBB)
94eb11fae6SDimitry Andric LLVM_DEBUG(
95eb11fae6SDimitry Andric dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
9608bbd35aSDimitry Andric << *L << "\n");
9708bbd35aSDimitry Andric else
98eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
9908bbd35aSDimitry Andric << NewExitBB->getName() << "\n");
10008bbd35aSDimitry Andric return true;
10108bbd35aSDimitry Andric };
10208bbd35aSDimitry Andric
10308bbd35aSDimitry Andric // Walk the exit blocks directly rather than building up a data structure for
10408bbd35aSDimitry Andric // them, but only visit each one once.
10508bbd35aSDimitry Andric SmallPtrSet<BasicBlock *, 4> Visited;
10608bbd35aSDimitry Andric for (auto *BB : L->blocks())
10708bbd35aSDimitry Andric for (auto *SuccBB : successors(BB)) {
10808bbd35aSDimitry Andric // We're looking for exit blocks so skip in-loop successors.
10908bbd35aSDimitry Andric if (L->contains(SuccBB))
11008bbd35aSDimitry Andric continue;
11108bbd35aSDimitry Andric
11208bbd35aSDimitry Andric // Visit each exit block exactly once.
11308bbd35aSDimitry Andric if (!Visited.insert(SuccBB).second)
11408bbd35aSDimitry Andric continue;
11508bbd35aSDimitry Andric
11608bbd35aSDimitry Andric Changed |= RewriteExit(SuccBB);
11708bbd35aSDimitry Andric }
11808bbd35aSDimitry Andric
11908bbd35aSDimitry Andric return Changed;
12008bbd35aSDimitry Andric }
12108bbd35aSDimitry Andric
122eb11fae6SDimitry Andric /// Returns the instructions that use values defined in the loop.
findDefsUsedOutsideOfLoop(Loop * L)123dd58ef01SDimitry Andric SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
124dd58ef01SDimitry Andric SmallVector<Instruction *, 8> UsedOutside;
125dd58ef01SDimitry Andric
126dd58ef01SDimitry Andric for (auto *Block : L->getBlocks())
127dd58ef01SDimitry Andric // FIXME: I believe that this could use copy_if if the Inst reference could
128dd58ef01SDimitry Andric // be adapted into a pointer.
129dd58ef01SDimitry Andric for (auto &Inst : *Block) {
130dd58ef01SDimitry Andric auto Users = Inst.users();
131b915e9e0SDimitry Andric if (any_of(Users, [&](User *U) {
132dd58ef01SDimitry Andric auto *Use = cast<Instruction>(U);
133dd58ef01SDimitry Andric return !L->contains(Use->getParent());
134dd58ef01SDimitry Andric }))
135dd58ef01SDimitry Andric UsedOutside.push_back(&Inst);
136dd58ef01SDimitry Andric }
137dd58ef01SDimitry Andric
138dd58ef01SDimitry Andric return UsedOutside;
139dd58ef01SDimitry Andric }
14001095a5dSDimitry Andric
getLoopAnalysisUsage(AnalysisUsage & AU)14101095a5dSDimitry Andric void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
14201095a5dSDimitry Andric // By definition, all loop passes need the LoopInfo analysis and the
14301095a5dSDimitry Andric // Dominator tree it depends on. Because they all participate in the loop
14401095a5dSDimitry Andric // pass manager, they must also preserve these.
14501095a5dSDimitry Andric AU.addRequired<DominatorTreeWrapperPass>();
14601095a5dSDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
14701095a5dSDimitry Andric AU.addRequired<LoopInfoWrapperPass>();
14801095a5dSDimitry Andric AU.addPreserved<LoopInfoWrapperPass>();
14901095a5dSDimitry Andric
15001095a5dSDimitry Andric // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
15101095a5dSDimitry Andric // here because users shouldn't directly get them from this header.
15201095a5dSDimitry Andric extern char &LoopSimplifyID;
15301095a5dSDimitry Andric extern char &LCSSAID;
15401095a5dSDimitry Andric AU.addRequiredID(LoopSimplifyID);
15501095a5dSDimitry Andric AU.addPreservedID(LoopSimplifyID);
15601095a5dSDimitry Andric AU.addRequiredID(LCSSAID);
15701095a5dSDimitry Andric AU.addPreservedID(LCSSAID);
158b915e9e0SDimitry Andric // This is used in the LPPassManager to perform LCSSA verification on passes
159b915e9e0SDimitry Andric // which preserve lcssa form
160b915e9e0SDimitry Andric AU.addRequired<LCSSAVerificationPass>();
161b915e9e0SDimitry Andric AU.addPreserved<LCSSAVerificationPass>();
16201095a5dSDimitry Andric
16301095a5dSDimitry Andric // Loop passes are designed to run inside of a loop pass manager which means
16401095a5dSDimitry Andric // that any function analyses they require must be required by the first loop
16501095a5dSDimitry Andric // pass in the manager (so that it is computed before the loop pass manager
16601095a5dSDimitry Andric // runs) and preserved by all loop pasess in the manager. To make this
16701095a5dSDimitry Andric // reasonably robust, the set needed for most loop passes is maintained here.
16801095a5dSDimitry Andric // If your loop pass requires an analysis not listed here, you will need to
16901095a5dSDimitry Andric // carefully audit the loop pass manager nesting structure that results.
17001095a5dSDimitry Andric AU.addRequired<AAResultsWrapperPass>();
17101095a5dSDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
17201095a5dSDimitry Andric AU.addPreserved<BasicAAWrapperPass>();
17301095a5dSDimitry Andric AU.addPreserved<GlobalsAAWrapperPass>();
17401095a5dSDimitry Andric AU.addPreserved<SCEVAAWrapperPass>();
17501095a5dSDimitry Andric AU.addRequired<ScalarEvolutionWrapperPass>();
17601095a5dSDimitry Andric AU.addPreserved<ScalarEvolutionWrapperPass>();
1771d5ae102SDimitry Andric // FIXME: When all loop passes preserve MemorySSA, it can be required and
1781d5ae102SDimitry Andric // preserved here instead of the individual handling in each pass.
17901095a5dSDimitry Andric }
18001095a5dSDimitry Andric
18101095a5dSDimitry Andric /// Manually defined generic "LoopPass" dependency initialization. This is used
18201095a5dSDimitry Andric /// to initialize the exact set of passes from above in \c
18301095a5dSDimitry Andric /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
18401095a5dSDimitry Andric /// with:
18501095a5dSDimitry Andric ///
18601095a5dSDimitry Andric /// INITIALIZE_PASS_DEPENDENCY(LoopPass)
18701095a5dSDimitry Andric ///
18801095a5dSDimitry Andric /// As-if "LoopPass" were a pass.
initializeLoopPassPass(PassRegistry & Registry)18901095a5dSDimitry Andric void llvm::initializeLoopPassPass(PassRegistry &Registry) {
19001095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
19101095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
19201095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
19301095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
19401095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
19501095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
19601095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
19701095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
19801095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1991d5ae102SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2001d5ae102SDimitry Andric }
2011d5ae102SDimitry Andric
2021d5ae102SDimitry Andric /// Create MDNode for input string.
createStringMetadata(Loop * TheLoop,StringRef Name,unsigned V)2031d5ae102SDimitry Andric static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2041d5ae102SDimitry Andric LLVMContext &Context = TheLoop->getHeader()->getContext();
2051d5ae102SDimitry Andric Metadata *MDs[] = {
2061d5ae102SDimitry Andric MDString::get(Context, Name),
2071d5ae102SDimitry Andric ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2081d5ae102SDimitry Andric return MDNode::get(Context, MDs);
2091d5ae102SDimitry Andric }
2101d5ae102SDimitry Andric
2111d5ae102SDimitry Andric /// Set input string into loop metadata by keeping other values intact.
2121d5ae102SDimitry Andric /// If the string is already in loop metadata update value if it is
2131d5ae102SDimitry Andric /// different.
addStringMetadataToLoop(Loop * TheLoop,const char * StringMD,unsigned V)2141d5ae102SDimitry Andric void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2151d5ae102SDimitry Andric unsigned V) {
2161d5ae102SDimitry Andric SmallVector<Metadata *, 4> MDs(1);
2171d5ae102SDimitry Andric // If the loop already has metadata, retain it.
2181d5ae102SDimitry Andric MDNode *LoopID = TheLoop->getLoopID();
2191d5ae102SDimitry Andric if (LoopID) {
2201d5ae102SDimitry Andric for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2211d5ae102SDimitry Andric MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2221d5ae102SDimitry Andric // If it is of form key = value, try to parse it.
2231d5ae102SDimitry Andric if (Node->getNumOperands() == 2) {
2241d5ae102SDimitry Andric MDString *S = dyn_cast<MDString>(Node->getOperand(0));
225ac9a064cSDimitry Andric if (S && S->getString() == StringMD) {
2261d5ae102SDimitry Andric ConstantInt *IntMD =
2271d5ae102SDimitry Andric mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2281d5ae102SDimitry Andric if (IntMD && IntMD->getSExtValue() == V)
2291d5ae102SDimitry Andric // It is already in place. Do nothing.
2301d5ae102SDimitry Andric return;
2311d5ae102SDimitry Andric // We need to update the value, so just skip it here and it will
2321d5ae102SDimitry Andric // be added after copying other existed nodes.
2331d5ae102SDimitry Andric continue;
2341d5ae102SDimitry Andric }
2351d5ae102SDimitry Andric }
2361d5ae102SDimitry Andric MDs.push_back(Node);
2371d5ae102SDimitry Andric }
2381d5ae102SDimitry Andric }
2391d5ae102SDimitry Andric // Add new metadata.
2401d5ae102SDimitry Andric MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2411d5ae102SDimitry Andric // Replace current metadata node with new one.
2421d5ae102SDimitry Andric LLVMContext &Context = TheLoop->getHeader()->getContext();
2431d5ae102SDimitry Andric MDNode *NewLoopID = MDNode::get(Context, MDs);
2441d5ae102SDimitry Andric // Set operand 0 to refer to the loop id itself.
2451d5ae102SDimitry Andric NewLoopID->replaceOperandWith(0, NewLoopID);
2461d5ae102SDimitry Andric TheLoop->setLoopID(NewLoopID);
24701095a5dSDimitry Andric }
24801095a5dSDimitry Andric
249e3b55780SDimitry Andric std::optional<ElementCount>
getOptionalElementCountLoopAttribute(const Loop * TheLoop)250344a3780SDimitry Andric llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
251e3b55780SDimitry Andric std::optional<int> Width =
252b60736ecSDimitry Andric getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
253b60736ecSDimitry Andric
254145449b1SDimitry Andric if (Width) {
255e3b55780SDimitry Andric std::optional<int> IsScalable = getOptionalIntLoopAttribute(
256b60736ecSDimitry Andric TheLoop, "llvm.loop.vectorize.scalable.enable");
257145449b1SDimitry Andric return ElementCount::get(*Width, IsScalable.value_or(false));
258b60736ecSDimitry Andric }
259b60736ecSDimitry Andric
260e3b55780SDimitry Andric return std::nullopt;
261b60736ecSDimitry Andric }
262b60736ecSDimitry Andric
makeFollowupLoopID(MDNode * OrigLoopID,ArrayRef<StringRef> FollowupOptions,const char * InheritOptionsExceptPrefix,bool AlwaysNew)263e3b55780SDimitry Andric std::optional<MDNode *> llvm::makeFollowupLoopID(
264d8e91e46SDimitry Andric MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
265d8e91e46SDimitry Andric const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
266d8e91e46SDimitry Andric if (!OrigLoopID) {
267d8e91e46SDimitry Andric if (AlwaysNew)
268d8e91e46SDimitry Andric return nullptr;
269e3b55780SDimitry Andric return std::nullopt;
270d8e91e46SDimitry Andric }
271d8e91e46SDimitry Andric
272d8e91e46SDimitry Andric assert(OrigLoopID->getOperand(0) == OrigLoopID);
273d8e91e46SDimitry Andric
274d8e91e46SDimitry Andric bool InheritAllAttrs = !InheritOptionsExceptPrefix;
275d8e91e46SDimitry Andric bool InheritSomeAttrs =
276d8e91e46SDimitry Andric InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
277d8e91e46SDimitry Andric SmallVector<Metadata *, 8> MDs;
278d8e91e46SDimitry Andric MDs.push_back(nullptr);
279d8e91e46SDimitry Andric
280d8e91e46SDimitry Andric bool Changed = false;
281d8e91e46SDimitry Andric if (InheritAllAttrs || InheritSomeAttrs) {
282b60736ecSDimitry Andric for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
283d8e91e46SDimitry Andric MDNode *Op = cast<MDNode>(Existing.get());
284d8e91e46SDimitry Andric
285d8e91e46SDimitry Andric auto InheritThisAttribute = [InheritSomeAttrs,
286d8e91e46SDimitry Andric InheritOptionsExceptPrefix](MDNode *Op) {
287d8e91e46SDimitry Andric if (!InheritSomeAttrs)
288d8e91e46SDimitry Andric return false;
289d8e91e46SDimitry Andric
290d8e91e46SDimitry Andric // Skip malformatted attribute metadata nodes.
291d8e91e46SDimitry Andric if (Op->getNumOperands() == 0)
292d8e91e46SDimitry Andric return true;
293d8e91e46SDimitry Andric Metadata *NameMD = Op->getOperand(0).get();
294d8e91e46SDimitry Andric if (!isa<MDString>(NameMD))
295d8e91e46SDimitry Andric return true;
296d8e91e46SDimitry Andric StringRef AttrName = cast<MDString>(NameMD)->getString();
297d8e91e46SDimitry Andric
298d8e91e46SDimitry Andric // Do not inherit excluded attributes.
299b1c73532SDimitry Andric return !AttrName.starts_with(InheritOptionsExceptPrefix);
300d8e91e46SDimitry Andric };
301d8e91e46SDimitry Andric
302d8e91e46SDimitry Andric if (InheritThisAttribute(Op))
303d8e91e46SDimitry Andric MDs.push_back(Op);
304d8e91e46SDimitry Andric else
305d8e91e46SDimitry Andric Changed = true;
306d8e91e46SDimitry Andric }
307d8e91e46SDimitry Andric } else {
308d8e91e46SDimitry Andric // Modified if we dropped at least one attribute.
309d8e91e46SDimitry Andric Changed = OrigLoopID->getNumOperands() > 1;
310d8e91e46SDimitry Andric }
311d8e91e46SDimitry Andric
312d8e91e46SDimitry Andric bool HasAnyFollowup = false;
313d8e91e46SDimitry Andric for (StringRef OptionName : FollowupOptions) {
314d8e91e46SDimitry Andric MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
315d8e91e46SDimitry Andric if (!FollowupNode)
316d8e91e46SDimitry Andric continue;
317d8e91e46SDimitry Andric
318d8e91e46SDimitry Andric HasAnyFollowup = true;
319b60736ecSDimitry Andric for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
320d8e91e46SDimitry Andric MDs.push_back(Option.get());
321d8e91e46SDimitry Andric Changed = true;
322d8e91e46SDimitry Andric }
323d8e91e46SDimitry Andric }
324d8e91e46SDimitry Andric
325d8e91e46SDimitry Andric // Attributes of the followup loop not specified explicity, so signal to the
326d8e91e46SDimitry Andric // transformation pass to add suitable attributes.
327d8e91e46SDimitry Andric if (!AlwaysNew && !HasAnyFollowup)
328e3b55780SDimitry Andric return std::nullopt;
329d8e91e46SDimitry Andric
330d8e91e46SDimitry Andric // If no attributes were added or remove, the previous loop Id can be reused.
331d8e91e46SDimitry Andric if (!AlwaysNew && !Changed)
332d8e91e46SDimitry Andric return OrigLoopID;
333d8e91e46SDimitry Andric
334d8e91e46SDimitry Andric // No attributes is equivalent to having no !llvm.loop metadata at all.
335d8e91e46SDimitry Andric if (MDs.size() == 1)
336d8e91e46SDimitry Andric return nullptr;
337d8e91e46SDimitry Andric
338d8e91e46SDimitry Andric // Build the new loop ID.
339d8e91e46SDimitry Andric MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
340d8e91e46SDimitry Andric FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
341d8e91e46SDimitry Andric return FollowupLoopID;
342d8e91e46SDimitry Andric }
343d8e91e46SDimitry Andric
hasDisableAllTransformsHint(const Loop * L)344d8e91e46SDimitry Andric bool llvm::hasDisableAllTransformsHint(const Loop *L) {
345d8e91e46SDimitry Andric return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
346d8e91e46SDimitry Andric }
347d8e91e46SDimitry Andric
hasDisableLICMTransformsHint(const Loop * L)3481d5ae102SDimitry Andric bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
3491d5ae102SDimitry Andric return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
3501d5ae102SDimitry Andric }
3511d5ae102SDimitry Andric
hasUnrollTransformation(const Loop * L)352344a3780SDimitry Andric TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
353d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
354d8e91e46SDimitry Andric return TM_SuppressedByUser;
355d8e91e46SDimitry Andric
356e3b55780SDimitry Andric std::optional<int> Count =
357d8e91e46SDimitry Andric getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
358145449b1SDimitry Andric if (Count)
359e3b55780SDimitry Andric return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
360d8e91e46SDimitry Andric
361d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
362d8e91e46SDimitry Andric return TM_ForcedByUser;
363d8e91e46SDimitry Andric
364d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
365d8e91e46SDimitry Andric return TM_ForcedByUser;
366d8e91e46SDimitry Andric
367d8e91e46SDimitry Andric if (hasDisableAllTransformsHint(L))
368d8e91e46SDimitry Andric return TM_Disable;
369d8e91e46SDimitry Andric
370d8e91e46SDimitry Andric return TM_Unspecified;
371d8e91e46SDimitry Andric }
372d8e91e46SDimitry Andric
hasUnrollAndJamTransformation(const Loop * L)373344a3780SDimitry Andric TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
374d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
375d8e91e46SDimitry Andric return TM_SuppressedByUser;
376d8e91e46SDimitry Andric
377e3b55780SDimitry Andric std::optional<int> Count =
378d8e91e46SDimitry Andric getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
379145449b1SDimitry Andric if (Count)
380e3b55780SDimitry Andric return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
381d8e91e46SDimitry Andric
382d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
383d8e91e46SDimitry Andric return TM_ForcedByUser;
384d8e91e46SDimitry Andric
385d8e91e46SDimitry Andric if (hasDisableAllTransformsHint(L))
386d8e91e46SDimitry Andric return TM_Disable;
387d8e91e46SDimitry Andric
388d8e91e46SDimitry Andric return TM_Unspecified;
389d8e91e46SDimitry Andric }
390d8e91e46SDimitry Andric
hasVectorizeTransformation(const Loop * L)391344a3780SDimitry Andric TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
392e3b55780SDimitry Andric std::optional<bool> Enable =
393d8e91e46SDimitry Andric getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
394d8e91e46SDimitry Andric
395d8e91e46SDimitry Andric if (Enable == false)
396d8e91e46SDimitry Andric return TM_SuppressedByUser;
397d8e91e46SDimitry Andric
398e3b55780SDimitry Andric std::optional<ElementCount> VectorizeWidth =
399b60736ecSDimitry Andric getOptionalElementCountLoopAttribute(L);
400e3b55780SDimitry Andric std::optional<int> InterleaveCount =
401d8e91e46SDimitry Andric getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
402d8e91e46SDimitry Andric
403d8e91e46SDimitry Andric // 'Forcing' vector width and interleave count to one effectively disables
404d8e91e46SDimitry Andric // this tranformation.
405b60736ecSDimitry Andric if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
406b60736ecSDimitry Andric InterleaveCount == 1)
407d8e91e46SDimitry Andric return TM_SuppressedByUser;
408d8e91e46SDimitry Andric
409d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
410d8e91e46SDimitry Andric return TM_Disable;
411d8e91e46SDimitry Andric
412e6d15924SDimitry Andric if (Enable == true)
413e6d15924SDimitry Andric return TM_ForcedByUser;
414e6d15924SDimitry Andric
415b60736ecSDimitry Andric if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
416d8e91e46SDimitry Andric return TM_Disable;
417d8e91e46SDimitry Andric
418b60736ecSDimitry Andric if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
419d8e91e46SDimitry Andric return TM_Enable;
420d8e91e46SDimitry Andric
421d8e91e46SDimitry Andric if (hasDisableAllTransformsHint(L))
422d8e91e46SDimitry Andric return TM_Disable;
423d8e91e46SDimitry Andric
424d8e91e46SDimitry Andric return TM_Unspecified;
425d8e91e46SDimitry Andric }
426d8e91e46SDimitry Andric
hasDistributeTransformation(const Loop * L)427344a3780SDimitry Andric TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
428d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
429d8e91e46SDimitry Andric return TM_ForcedByUser;
430d8e91e46SDimitry Andric
431d8e91e46SDimitry Andric if (hasDisableAllTransformsHint(L))
432d8e91e46SDimitry Andric return TM_Disable;
433d8e91e46SDimitry Andric
434d8e91e46SDimitry Andric return TM_Unspecified;
435d8e91e46SDimitry Andric }
436d8e91e46SDimitry Andric
hasLICMVersioningTransformation(const Loop * L)437344a3780SDimitry Andric TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
438d8e91e46SDimitry Andric if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
439d8e91e46SDimitry Andric return TM_SuppressedByUser;
440d8e91e46SDimitry Andric
441d8e91e46SDimitry Andric if (hasDisableAllTransformsHint(L))
442d8e91e46SDimitry Andric return TM_Disable;
443d8e91e46SDimitry Andric
444d8e91e46SDimitry Andric return TM_Unspecified;
44501095a5dSDimitry Andric }
44601095a5dSDimitry Andric
447044eb2f6SDimitry Andric /// Does a BFS from a given node to all of its children inside a given loop.
448044eb2f6SDimitry Andric /// The returned vector of nodes includes the starting point.
449044eb2f6SDimitry Andric SmallVector<DomTreeNode *, 16>
collectChildrenInLoop(DomTreeNode * N,const Loop * CurLoop)450044eb2f6SDimitry Andric llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
451044eb2f6SDimitry Andric SmallVector<DomTreeNode *, 16> Worklist;
452044eb2f6SDimitry Andric auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
453044eb2f6SDimitry Andric // Only include subregions in the top level loop.
454044eb2f6SDimitry Andric BasicBlock *BB = DTN->getBlock();
455044eb2f6SDimitry Andric if (CurLoop->contains(BB))
456044eb2f6SDimitry Andric Worklist.push_back(DTN);
457044eb2f6SDimitry Andric };
458044eb2f6SDimitry Andric
459044eb2f6SDimitry Andric AddRegionToWorklist(N);
460044eb2f6SDimitry Andric
461cfca06d7SDimitry Andric for (size_t I = 0; I < Worklist.size(); I++) {
462cfca06d7SDimitry Andric for (DomTreeNode *Child : Worklist[I]->children())
463044eb2f6SDimitry Andric AddRegionToWorklist(Child);
464cfca06d7SDimitry Andric }
465044eb2f6SDimitry Andric
466044eb2f6SDimitry Andric return Worklist;
467044eb2f6SDimitry Andric }
468044eb2f6SDimitry Andric
isAlmostDeadIV(PHINode * PN,BasicBlock * LatchBlock,Value * Cond)4697fa27ce4SDimitry Andric bool llvm::isAlmostDeadIV(PHINode *PN, BasicBlock *LatchBlock, Value *Cond) {
4707fa27ce4SDimitry Andric int LatchIdx = PN->getBasicBlockIndex(LatchBlock);
471ac9a064cSDimitry Andric assert(LatchIdx != -1 && "LatchBlock is not a case in this PHINode");
4727fa27ce4SDimitry Andric Value *IncV = PN->getIncomingValue(LatchIdx);
4737fa27ce4SDimitry Andric
4747fa27ce4SDimitry Andric for (User *U : PN->users())
4757fa27ce4SDimitry Andric if (U != Cond && U != IncV) return false;
4767fa27ce4SDimitry Andric
4777fa27ce4SDimitry Andric for (User *U : IncV->users())
4787fa27ce4SDimitry Andric if (U != Cond && U != PN) return false;
4797fa27ce4SDimitry Andric return true;
4807fa27ce4SDimitry Andric }
4817fa27ce4SDimitry Andric
4827fa27ce4SDimitry Andric
deleteDeadLoop(Loop * L,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,MemorySSA * MSSA)483cfca06d7SDimitry Andric void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
484cfca06d7SDimitry Andric LoopInfo *LI, MemorySSA *MSSA) {
485044eb2f6SDimitry Andric assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
486044eb2f6SDimitry Andric auto *Preheader = L->getLoopPreheader();
487044eb2f6SDimitry Andric assert(Preheader && "Preheader should exist!");
488044eb2f6SDimitry Andric
489cfca06d7SDimitry Andric std::unique_ptr<MemorySSAUpdater> MSSAU;
490cfca06d7SDimitry Andric if (MSSA)
491cfca06d7SDimitry Andric MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
492cfca06d7SDimitry Andric
493044eb2f6SDimitry Andric // Now that we know the removal is safe, remove the loop by changing the
494044eb2f6SDimitry Andric // branch from the preheader to go to the single exit block.
495044eb2f6SDimitry Andric //
496044eb2f6SDimitry Andric // Because we're deleting a large chunk of code at once, the sequence in which
497044eb2f6SDimitry Andric // we remove things is very important to avoid invalidation issues.
498044eb2f6SDimitry Andric
499044eb2f6SDimitry Andric // Tell ScalarEvolution that the loop is deleted. Do this before
500044eb2f6SDimitry Andric // deleting the loop so that ScalarEvolution can look at the loop
501044eb2f6SDimitry Andric // to determine what it needs to clean up.
502e3b55780SDimitry Andric if (SE) {
503044eb2f6SDimitry Andric SE->forgetLoop(L);
504e3b55780SDimitry Andric SE->forgetBlockAndLoopDispositions();
505e3b55780SDimitry Andric }
506044eb2f6SDimitry Andric
507145449b1SDimitry Andric Instruction *OldTerm = Preheader->getTerminator();
508145449b1SDimitry Andric assert(!OldTerm->mayHaveSideEffects() &&
509145449b1SDimitry Andric "Preheader must end with a side-effect-free terminator");
510145449b1SDimitry Andric assert(OldTerm->getNumSuccessors() == 1 &&
511145449b1SDimitry Andric "Preheader must have a single successor");
512044eb2f6SDimitry Andric // Connect the preheader to the exit block. Keep the old edge to the header
513044eb2f6SDimitry Andric // around to perform the dominator tree update in two separate steps
514044eb2f6SDimitry Andric // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
515044eb2f6SDimitry Andric // preheader -> header.
516044eb2f6SDimitry Andric //
517044eb2f6SDimitry Andric //
518044eb2f6SDimitry Andric // 0. Preheader 1. Preheader 2. Preheader
519044eb2f6SDimitry Andric // | | | |
520044eb2f6SDimitry Andric // V | V |
521044eb2f6SDimitry Andric // Header <--\ | Header <--\ | Header <--\
522044eb2f6SDimitry Andric // | | | | | | | | | | |
523044eb2f6SDimitry Andric // | V | | | V | | | V |
524044eb2f6SDimitry Andric // | Body --/ | | Body --/ | | Body --/
525044eb2f6SDimitry Andric // V V V V V
526044eb2f6SDimitry Andric // Exit Exit Exit
527044eb2f6SDimitry Andric //
528044eb2f6SDimitry Andric // By doing this is two separate steps we can perform the dominator tree
529044eb2f6SDimitry Andric // update without using the batch update API.
530044eb2f6SDimitry Andric //
531044eb2f6SDimitry Andric // Even when the loop is never executed, we cannot remove the edge from the
532044eb2f6SDimitry Andric // source block to the exit block. Consider the case where the unexecuted loop
533044eb2f6SDimitry Andric // branches back to an outer loop. If we deleted the loop and removed the edge
534044eb2f6SDimitry Andric // coming to this inner loop, this will break the outer loop structure (by
535044eb2f6SDimitry Andric // deleting the backedge of the outer loop). If the outer loop is indeed a
536044eb2f6SDimitry Andric // non-loop, it will be deleted in a future iteration of loop deletion pass.
537145449b1SDimitry Andric IRBuilder<> Builder(OldTerm);
538b60736ecSDimitry Andric
539b60736ecSDimitry Andric auto *ExitBlock = L->getUniqueExitBlock();
540b60736ecSDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
541b60736ecSDimitry Andric if (ExitBlock) {
542b60736ecSDimitry Andric assert(ExitBlock && "Should have a unique exit block!");
543b60736ecSDimitry Andric assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
544b60736ecSDimitry Andric
545044eb2f6SDimitry Andric Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
546044eb2f6SDimitry Andric // Remove the old branch. The conditional branch becomes a new terminator.
547145449b1SDimitry Andric OldTerm->eraseFromParent();
548044eb2f6SDimitry Andric
549044eb2f6SDimitry Andric // Rewrite phis in the exit block to get their inputs from the Preheader
550044eb2f6SDimitry Andric // instead of the exiting block.
551eb11fae6SDimitry Andric for (PHINode &P : ExitBlock->phis()) {
552044eb2f6SDimitry Andric // Set the zero'th element of Phi to be from the preheader and remove all
553044eb2f6SDimitry Andric // other incoming values. Given the loop has dedicated exits, all other
554044eb2f6SDimitry Andric // incoming values must be from the exiting blocks.
555044eb2f6SDimitry Andric int PredIndex = 0;
556eb11fae6SDimitry Andric P.setIncomingBlock(PredIndex, Preheader);
557044eb2f6SDimitry Andric // Removes all incoming values from all other exiting blocks (including
558044eb2f6SDimitry Andric // duplicate values from an exiting block).
559044eb2f6SDimitry Andric // Nuke all entries except the zero'th entry which is the preheader entry.
560b1c73532SDimitry Andric P.removeIncomingValueIf([](unsigned Idx) { return Idx != 0; },
561b1c73532SDimitry Andric /* DeletePHIIfEmpty */ false);
562044eb2f6SDimitry Andric
563eb11fae6SDimitry Andric assert((P.getNumIncomingValues() == 1 &&
564eb11fae6SDimitry Andric P.getIncomingBlock(PredIndex) == Preheader) &&
565044eb2f6SDimitry Andric "Should have exactly one value and that's from the preheader!");
566044eb2f6SDimitry Andric }
567044eb2f6SDimitry Andric
568cfca06d7SDimitry Andric if (DT) {
569cfca06d7SDimitry Andric DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
570cfca06d7SDimitry Andric if (MSSA) {
571b60736ecSDimitry Andric MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
572b60736ecSDimitry Andric *DT);
573cfca06d7SDimitry Andric if (VerifyMemorySSA)
574cfca06d7SDimitry Andric MSSA->verifyMemorySSA();
575cfca06d7SDimitry Andric }
576cfca06d7SDimitry Andric }
577cfca06d7SDimitry Andric
578044eb2f6SDimitry Andric // Disconnect the loop body by branching directly to its exit.
579044eb2f6SDimitry Andric Builder.SetInsertPoint(Preheader->getTerminator());
580044eb2f6SDimitry Andric Builder.CreateBr(ExitBlock);
581044eb2f6SDimitry Andric // Remove the old branch.
582044eb2f6SDimitry Andric Preheader->getTerminator()->eraseFromParent();
583b60736ecSDimitry Andric } else {
584b60736ecSDimitry Andric assert(L->hasNoExitBlocks() &&
585b60736ecSDimitry Andric "Loop should have either zero or one exit blocks.");
586b60736ecSDimitry Andric
587145449b1SDimitry Andric Builder.SetInsertPoint(OldTerm);
588b60736ecSDimitry Andric Builder.CreateUnreachable();
589b60736ecSDimitry Andric Preheader->getTerminator()->eraseFromParent();
590b60736ecSDimitry Andric }
591044eb2f6SDimitry Andric
592044eb2f6SDimitry Andric if (DT) {
593cfca06d7SDimitry Andric DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
594cfca06d7SDimitry Andric if (MSSA) {
595cfca06d7SDimitry Andric MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
596cfca06d7SDimitry Andric *DT);
597cfca06d7SDimitry Andric SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
598cfca06d7SDimitry Andric L->block_end());
599cfca06d7SDimitry Andric MSSAU->removeBlocks(DeadBlockSet);
600cfca06d7SDimitry Andric if (VerifyMemorySSA)
601cfca06d7SDimitry Andric MSSA->verifyMemorySSA();
602cfca06d7SDimitry Andric }
603044eb2f6SDimitry Andric }
604044eb2f6SDimitry Andric
605d8e91e46SDimitry Andric // Use a map to unique and a vector to guarantee deterministic ordering.
606e3b55780SDimitry Andric llvm::SmallDenseSet<DebugVariable, 4> DeadDebugSet;
607d8e91e46SDimitry Andric llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
608ac9a064cSDimitry Andric llvm::SmallVector<DbgVariableRecord *, 4> DeadDbgVariableRecords;
609d8e91e46SDimitry Andric
610b60736ecSDimitry Andric if (ExitBlock) {
611eb11fae6SDimitry Andric // Given LCSSA form is satisfied, we should not have users of instructions
612eb11fae6SDimitry Andric // within the dead loop outside of the loop. However, LCSSA doesn't take
613eb11fae6SDimitry Andric // unreachable uses into account. We handle them here.
614eb11fae6SDimitry Andric // We could do it after drop all references (in this case all users in the
615eb11fae6SDimitry Andric // loop will be already eliminated and we have less work to do but according
616eb11fae6SDimitry Andric // to API doc of User::dropAllReferences only valid operation after dropping
617eb11fae6SDimitry Andric // references, is deletion. So let's substitute all usages of
6184b4fe385SDimitry Andric // instruction from the loop with poison value of corresponding type first.
619eb11fae6SDimitry Andric for (auto *Block : L->blocks())
620eb11fae6SDimitry Andric for (Instruction &I : *Block) {
6214b4fe385SDimitry Andric auto *Poison = PoisonValue::get(I.getType());
622c0981da4SDimitry Andric for (Use &U : llvm::make_early_inc_range(I.uses())) {
623eb11fae6SDimitry Andric if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
624eb11fae6SDimitry Andric if (L->contains(Usr->getParent()))
625eb11fae6SDimitry Andric continue;
626eb11fae6SDimitry Andric // If we have a DT then we can check that uses outside a loop only in
627eb11fae6SDimitry Andric // unreachable block.
628eb11fae6SDimitry Andric if (DT)
629eb11fae6SDimitry Andric assert(!DT->isReachableFromEntry(U) &&
630eb11fae6SDimitry Andric "Unexpected user in reachable block");
6314b4fe385SDimitry Andric U.set(Poison);
632eb11fae6SDimitry Andric }
633b1c73532SDimitry Andric
634ac9a064cSDimitry Andric // RemoveDIs: do the same as below for DbgVariableRecords.
635b1c73532SDimitry Andric if (Block->IsNewDbgInfoFormat) {
636ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
637ac9a064cSDimitry Andric filterDbgVars(I.getDbgRecordRange()))) {
638ac9a064cSDimitry Andric DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
639ac9a064cSDimitry Andric DVR.getDebugLoc().get());
640b1c73532SDimitry Andric if (!DeadDebugSet.insert(Key).second)
641b1c73532SDimitry Andric continue;
642ac9a064cSDimitry Andric // Unlinks the DVR from it's container, for later insertion.
643ac9a064cSDimitry Andric DVR.removeFromParent();
644ac9a064cSDimitry Andric DeadDbgVariableRecords.push_back(&DVR);
645b1c73532SDimitry Andric }
646b1c73532SDimitry Andric }
647b1c73532SDimitry Andric
648b1c73532SDimitry Andric // For one of each variable encountered, preserve a debug intrinsic (set
649b1c73532SDimitry Andric // to Poison) and transfer it to the loop exit. This terminates any
650b1c73532SDimitry Andric // variable locations that were set during the loop.
651d8e91e46SDimitry Andric auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
652d8e91e46SDimitry Andric if (!DVI)
653d8e91e46SDimitry Andric continue;
654e3b55780SDimitry Andric if (!DeadDebugSet.insert(DebugVariable(DVI)).second)
655d8e91e46SDimitry Andric continue;
656d8e91e46SDimitry Andric DeadDebugInst.push_back(DVI);
657eb11fae6SDimitry Andric }
658eb11fae6SDimitry Andric
659d8e91e46SDimitry Andric // After the loop has been deleted all the values defined and modified
6607fa27ce4SDimitry Andric // inside the loop are going to be unavailable. Values computed in the
6617fa27ce4SDimitry Andric // loop will have been deleted, automatically causing their debug uses
6627fa27ce4SDimitry Andric // be be replaced with undef. Loop invariant values will still be available.
6637fa27ce4SDimitry Andric // Move dbg.values out the loop so that earlier location ranges are still
6647fa27ce4SDimitry Andric // terminated and loop invariant assignments are preserved.
665b1c73532SDimitry Andric DIBuilder DIB(*ExitBlock->getModule());
666b1c73532SDimitry Andric BasicBlock::iterator InsertDbgValueBefore =
667b1c73532SDimitry Andric ExitBlock->getFirstInsertionPt();
668b1c73532SDimitry Andric assert(InsertDbgValueBefore != ExitBlock->end() &&
669e6d15924SDimitry Andric "There should be a non-PHI instruction in exit block, else these "
670e6d15924SDimitry Andric "instructions will have no parent.");
671b1c73532SDimitry Andric
6727fa27ce4SDimitry Andric for (auto *DVI : DeadDebugInst)
673b1c73532SDimitry Andric DVI->moveBefore(*ExitBlock, InsertDbgValueBefore);
674b1c73532SDimitry Andric
675b1c73532SDimitry Andric // Due to the "head" bit in BasicBlock::iterator, we're going to insert
676ac9a064cSDimitry Andric // each DbgVariableRecord right at the start of the block, wheras dbg.values
677ac9a064cSDimitry Andric // would be repeatedly inserted before the first instruction. To replicate
678ac9a064cSDimitry Andric // this behaviour, do it backwards.
679ac9a064cSDimitry Andric for (DbgVariableRecord *DVR : llvm::reverse(DeadDbgVariableRecords))
680ac9a064cSDimitry Andric ExitBlock->insertDbgRecordBefore(DVR, InsertDbgValueBefore);
681e3b55780SDimitry Andric }
682d8e91e46SDimitry Andric
683044eb2f6SDimitry Andric // Remove the block from the reference counting scheme, so that we can
684044eb2f6SDimitry Andric // delete it freely later.
685044eb2f6SDimitry Andric for (auto *Block : L->blocks())
686044eb2f6SDimitry Andric Block->dropAllReferences();
687044eb2f6SDimitry Andric
688cfca06d7SDimitry Andric if (MSSA && VerifyMemorySSA)
689cfca06d7SDimitry Andric MSSA->verifyMemorySSA();
690cfca06d7SDimitry Andric
691044eb2f6SDimitry Andric if (LI) {
692044eb2f6SDimitry Andric // Erase the instructions and the blocks without having to worry
693044eb2f6SDimitry Andric // about ordering because we already dropped the references.
694044eb2f6SDimitry Andric // NOTE: This iteration is safe because erasing the block does not remove
695044eb2f6SDimitry Andric // its entry from the loop's block list. We do that in the next section.
696846a2208SDimitry Andric for (BasicBlock *BB : L->blocks())
697846a2208SDimitry Andric BB->eraseFromParent();
698044eb2f6SDimitry Andric
699044eb2f6SDimitry Andric // Finally, the blocks from loopinfo. This has to happen late because
700044eb2f6SDimitry Andric // otherwise our loop iterators won't work.
701044eb2f6SDimitry Andric
702044eb2f6SDimitry Andric SmallPtrSet<BasicBlock *, 8> blocks;
703044eb2f6SDimitry Andric blocks.insert(L->block_begin(), L->block_end());
704044eb2f6SDimitry Andric for (BasicBlock *BB : blocks)
705044eb2f6SDimitry Andric LI->removeBlock(BB);
706044eb2f6SDimitry Andric
707044eb2f6SDimitry Andric // The last step is to update LoopInfo now that we've eliminated this loop.
708706b4fc4SDimitry Andric // Note: LoopInfo::erase remove the given loop and relink its subloops with
709706b4fc4SDimitry Andric // its parent. While removeLoop/removeChildLoop remove the given loop but
710706b4fc4SDimitry Andric // not relink its subloops, which is what we want.
711706b4fc4SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) {
712cfca06d7SDimitry Andric Loop::iterator I = find(*ParentLoop, L);
713706b4fc4SDimitry Andric assert(I != ParentLoop->end() && "Couldn't find loop");
714706b4fc4SDimitry Andric ParentLoop->removeChildLoop(I);
715706b4fc4SDimitry Andric } else {
716cfca06d7SDimitry Andric Loop::iterator I = find(*LI, L);
717706b4fc4SDimitry Andric assert(I != LI->end() && "Couldn't find loop");
718706b4fc4SDimitry Andric LI->removeLoop(I);
719706b4fc4SDimitry Andric }
720706b4fc4SDimitry Andric LI->destroy(L);
721044eb2f6SDimitry Andric }
722044eb2f6SDimitry Andric }
723044eb2f6SDimitry Andric
breakLoopBackedge(Loop * L,DominatorTree & DT,ScalarEvolution & SE,LoopInfo & LI,MemorySSA * MSSA)724b60736ecSDimitry Andric void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
725b60736ecSDimitry Andric LoopInfo &LI, MemorySSA *MSSA) {
726b60736ecSDimitry Andric auto *Latch = L->getLoopLatch();
727b60736ecSDimitry Andric assert(Latch && "multiple latches not yet supported");
728b60736ecSDimitry Andric auto *Header = L->getHeader();
729145449b1SDimitry Andric Loop *OutermostLoop = L->getOutermostLoop();
730b60736ecSDimitry Andric
731b60736ecSDimitry Andric SE.forgetLoop(L);
732e3b55780SDimitry Andric SE.forgetBlockAndLoopDispositions();
733b60736ecSDimitry Andric
734b60736ecSDimitry Andric std::unique_ptr<MemorySSAUpdater> MSSAU;
735b60736ecSDimitry Andric if (MSSA)
736b60736ecSDimitry Andric MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
737b60736ecSDimitry Andric
738c0981da4SDimitry Andric // Update the CFG and domtree. We chose to special case a couple of
739c0981da4SDimitry Andric // of common cases for code quality and test readability reasons.
740c0981da4SDimitry Andric [&]() -> void {
741c0981da4SDimitry Andric if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
742c0981da4SDimitry Andric if (!BI->isConditional()) {
743c0981da4SDimitry Andric DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
744c0981da4SDimitry Andric (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
745c0981da4SDimitry Andric MSSAU.get());
746c0981da4SDimitry Andric return;
747c0981da4SDimitry Andric }
748c0981da4SDimitry Andric
749c0981da4SDimitry Andric // Conditional latch/exit - note that latch can be shared by inner
750c0981da4SDimitry Andric // and outer loop so the other target doesn't need to an exit
751c0981da4SDimitry Andric if (L->isLoopExiting(Latch)) {
752c0981da4SDimitry Andric // TODO: Generalize ConstantFoldTerminator so that it can be used
753c0981da4SDimitry Andric // here without invalidating LCSSA or MemorySSA. (Tricky case for
754c0981da4SDimitry Andric // LCSSA: header is an exit block of a preceeding sibling loop w/o
755c0981da4SDimitry Andric // dedicated exits.)
756c0981da4SDimitry Andric const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
757c0981da4SDimitry Andric BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
758c0981da4SDimitry Andric
759c0981da4SDimitry Andric DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
760c0981da4SDimitry Andric Header->removePredecessor(Latch, true);
761c0981da4SDimitry Andric
762c0981da4SDimitry Andric IRBuilder<> Builder(BI);
763c0981da4SDimitry Andric auto *NewBI = Builder.CreateBr(ExitBB);
764c0981da4SDimitry Andric // Transfer the metadata to the new branch instruction (minus the
765c0981da4SDimitry Andric // loop info since this is no longer a loop)
766c0981da4SDimitry Andric NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
767c0981da4SDimitry Andric LLVMContext::MD_annotation});
768c0981da4SDimitry Andric
769c0981da4SDimitry Andric BI->eraseFromParent();
770c0981da4SDimitry Andric DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
771c0981da4SDimitry Andric if (MSSA)
772c0981da4SDimitry Andric MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
773c0981da4SDimitry Andric return;
774c0981da4SDimitry Andric }
775c0981da4SDimitry Andric }
776c0981da4SDimitry Andric
777c0981da4SDimitry Andric // General case. By splitting the backedge, and then explicitly making it
778c0981da4SDimitry Andric // unreachable we gracefully handle corner cases such as switch and invoke
779c0981da4SDimitry Andric // termiantors.
780b60736ecSDimitry Andric auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
781b60736ecSDimitry Andric
782b60736ecSDimitry Andric DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
783344a3780SDimitry Andric (void)changeToUnreachable(BackedgeBB->getTerminator(),
784b60736ecSDimitry Andric /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
785c0981da4SDimitry Andric }();
786b60736ecSDimitry Andric
787b60736ecSDimitry Andric // Erase (and destroy) this loop instance. Handles relinking sub-loops
788b60736ecSDimitry Andric // and blocks within the loop as needed.
789b60736ecSDimitry Andric LI.erase(L);
790b60736ecSDimitry Andric
791b60736ecSDimitry Andric // If the loop we broke had a parent, then changeToUnreachable might have
792b60736ecSDimitry Andric // caused a block to be removed from the parent loop (see loop_nest_lcssa
793b60736ecSDimitry Andric // test case in zero-btc.ll for an example), thus changing the parent's
794b60736ecSDimitry Andric // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
795b60736ecSDimitry Andric // loop which might have a had a block removed.
796b60736ecSDimitry Andric if (OutermostLoop != L)
797b60736ecSDimitry Andric formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
798b60736ecSDimitry Andric }
799b60736ecSDimitry Andric
800b60736ecSDimitry Andric
80177fc4c14SDimitry Andric /// Checks if \p L has an exiting latch branch. There may also be other
80277fc4c14SDimitry Andric /// exiting blocks. Returns branch instruction terminating the loop
803cfca06d7SDimitry Andric /// latch if above check is successful, nullptr otherwise.
getExpectedExitLoopLatchBranch(Loop * L)804cfca06d7SDimitry Andric static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
805e6d15924SDimitry Andric BasicBlock *Latch = L->getLoopLatch();
806e6d15924SDimitry Andric if (!Latch)
807cfca06d7SDimitry Andric return nullptr;
808cfca06d7SDimitry Andric
809e6d15924SDimitry Andric BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
810e6d15924SDimitry Andric if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
811cfca06d7SDimitry Andric return nullptr;
812b915e9e0SDimitry Andric
813b915e9e0SDimitry Andric assert((LatchBR->getSuccessor(0) == L->getHeader() ||
814b915e9e0SDimitry Andric LatchBR->getSuccessor(1) == L->getHeader()) &&
815b915e9e0SDimitry Andric "At least one edge out of the latch must go to the header");
816b915e9e0SDimitry Andric
817cfca06d7SDimitry Andric return LatchBR;
818cfca06d7SDimitry Andric }
819cfca06d7SDimitry Andric
82077fc4c14SDimitry Andric /// Return the estimated trip count for any exiting branch which dominates
82177fc4c14SDimitry Andric /// the loop latch.
getEstimatedTripCount(BranchInst * ExitingBranch,Loop * L,uint64_t & OrigExitWeight)822e3b55780SDimitry Andric static std::optional<uint64_t> getEstimatedTripCount(BranchInst *ExitingBranch,
823e3b55780SDimitry Andric Loop *L,
82477fc4c14SDimitry Andric uint64_t &OrigExitWeight) {
82577fc4c14SDimitry Andric // To estimate the number of times the loop body was executed, we want to
82677fc4c14SDimitry Andric // know the number of times the backedge was taken, vs. the number of times
82777fc4c14SDimitry Andric // we exited the loop.
82877fc4c14SDimitry Andric uint64_t LoopWeight, ExitWeight;
829e3b55780SDimitry Andric if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight))
830e3b55780SDimitry Andric return std::nullopt;
83177fc4c14SDimitry Andric
83277fc4c14SDimitry Andric if (L->contains(ExitingBranch->getSuccessor(1)))
83377fc4c14SDimitry Andric std::swap(LoopWeight, ExitWeight);
83477fc4c14SDimitry Andric
83577fc4c14SDimitry Andric if (!ExitWeight)
83677fc4c14SDimitry Andric // Don't have a way to return predicated infinite
837e3b55780SDimitry Andric return std::nullopt;
83877fc4c14SDimitry Andric
83977fc4c14SDimitry Andric OrigExitWeight = ExitWeight;
84077fc4c14SDimitry Andric
84177fc4c14SDimitry Andric // Estimated exit count is a ratio of the loop weight by the weight of the
84277fc4c14SDimitry Andric // edge exiting the loop, rounded to nearest.
84377fc4c14SDimitry Andric uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
84477fc4c14SDimitry Andric // Estimated trip count is one plus estimated exit count.
84577fc4c14SDimitry Andric return ExitCount + 1;
84677fc4c14SDimitry Andric }
84777fc4c14SDimitry Andric
848e3b55780SDimitry Andric std::optional<unsigned>
getLoopEstimatedTripCount(Loop * L,unsigned * EstimatedLoopInvocationWeight)849cfca06d7SDimitry Andric llvm::getLoopEstimatedTripCount(Loop *L,
850cfca06d7SDimitry Andric unsigned *EstimatedLoopInvocationWeight) {
85177fc4c14SDimitry Andric // Currently we take the estimate exit count only from the loop latch,
85277fc4c14SDimitry Andric // ignoring other exiting blocks. This can overestimate the trip count
85377fc4c14SDimitry Andric // if we exit through another exit, but can never underestimate it.
85477fc4c14SDimitry Andric // TODO: incorporate information from other exits
85577fc4c14SDimitry Andric if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) {
85677fc4c14SDimitry Andric uint64_t ExitWeight;
857e3b55780SDimitry Andric if (std::optional<uint64_t> EstTripCount =
85877fc4c14SDimitry Andric getEstimatedTripCount(LatchBranch, L, ExitWeight)) {
859cfca06d7SDimitry Andric if (EstimatedLoopInvocationWeight)
86077fc4c14SDimitry Andric *EstimatedLoopInvocationWeight = ExitWeight;
86177fc4c14SDimitry Andric return *EstTripCount;
86277fc4c14SDimitry Andric }
86377fc4c14SDimitry Andric }
864e3b55780SDimitry Andric return std::nullopt;
865cfca06d7SDimitry Andric }
866cfca06d7SDimitry Andric
setLoopEstimatedTripCount(Loop * L,unsigned EstimatedTripCount,unsigned EstimatedloopInvocationWeight)867cfca06d7SDimitry Andric bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
868cfca06d7SDimitry Andric unsigned EstimatedloopInvocationWeight) {
86977fc4c14SDimitry Andric // At the moment, we currently support changing the estimate trip count of
87077fc4c14SDimitry Andric // the latch branch only. We could extend this API to manipulate estimated
87177fc4c14SDimitry Andric // trip counts for any exit.
872cfca06d7SDimitry Andric BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
873cfca06d7SDimitry Andric if (!LatchBranch)
874cfca06d7SDimitry Andric return false;
875cfca06d7SDimitry Andric
876cfca06d7SDimitry Andric // Calculate taken and exit weights.
877cfca06d7SDimitry Andric unsigned LatchExitWeight = 0;
878cfca06d7SDimitry Andric unsigned BackedgeTakenWeight = 0;
879cfca06d7SDimitry Andric
880cfca06d7SDimitry Andric if (EstimatedTripCount > 0) {
881cfca06d7SDimitry Andric LatchExitWeight = EstimatedloopInvocationWeight;
882cfca06d7SDimitry Andric BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
883cfca06d7SDimitry Andric }
884cfca06d7SDimitry Andric
885cfca06d7SDimitry Andric // Make a swap if back edge is taken when condition is "false".
886cfca06d7SDimitry Andric if (LatchBranch->getSuccessor(0) != L->getHeader())
887cfca06d7SDimitry Andric std::swap(BackedgeTakenWeight, LatchExitWeight);
888cfca06d7SDimitry Andric
889cfca06d7SDimitry Andric MDBuilder MDB(LatchBranch->getContext());
890cfca06d7SDimitry Andric
891cfca06d7SDimitry Andric // Set/Update profile metadata.
892cfca06d7SDimitry Andric LatchBranch->setMetadata(
893cfca06d7SDimitry Andric LLVMContext::MD_prof,
894cfca06d7SDimitry Andric MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
895cfca06d7SDimitry Andric
896cfca06d7SDimitry Andric return true;
897b915e9e0SDimitry Andric }
8986b3f41edSDimitry Andric
hasIterationCountInvariantInParent(Loop * InnerLoop,ScalarEvolution & SE)899d8e91e46SDimitry Andric bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
900d8e91e46SDimitry Andric ScalarEvolution &SE) {
901d8e91e46SDimitry Andric Loop *OuterL = InnerLoop->getParentLoop();
902d8e91e46SDimitry Andric if (!OuterL)
903d8e91e46SDimitry Andric return true;
904d8e91e46SDimitry Andric
905d8e91e46SDimitry Andric // Get the backedge taken count for the inner loop
906d8e91e46SDimitry Andric BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
907d8e91e46SDimitry Andric const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
908d8e91e46SDimitry Andric if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
909d8e91e46SDimitry Andric !InnerLoopBECountSC->getType()->isIntegerTy())
910d8e91e46SDimitry Andric return false;
911d8e91e46SDimitry Andric
912d8e91e46SDimitry Andric // Get whether count is invariant to the outer loop
913d8e91e46SDimitry Andric ScalarEvolution::LoopDisposition LD =
914d8e91e46SDimitry Andric SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
915d8e91e46SDimitry Andric if (LD != ScalarEvolution::LoopInvariant)
916d8e91e46SDimitry Andric return false;
917d8e91e46SDimitry Andric
918d8e91e46SDimitry Andric return true;
919d8e91e46SDimitry Andric }
920d8e91e46SDimitry Andric
getReductionIntrinsicID(RecurKind RK)9219b950333SDimitry Andric constexpr Intrinsic::ID llvm::getReductionIntrinsicID(RecurKind RK) {
9229b950333SDimitry Andric switch (RK) {
9239b950333SDimitry Andric default:
9249b950333SDimitry Andric llvm_unreachable("Unexpected recurrence kind");
9259b950333SDimitry Andric case RecurKind::Add:
9269b950333SDimitry Andric return Intrinsic::vector_reduce_add;
9279b950333SDimitry Andric case RecurKind::Mul:
9289b950333SDimitry Andric return Intrinsic::vector_reduce_mul;
9299b950333SDimitry Andric case RecurKind::And:
9309b950333SDimitry Andric return Intrinsic::vector_reduce_and;
9319b950333SDimitry Andric case RecurKind::Or:
9329b950333SDimitry Andric return Intrinsic::vector_reduce_or;
9339b950333SDimitry Andric case RecurKind::Xor:
9349b950333SDimitry Andric return Intrinsic::vector_reduce_xor;
9359b950333SDimitry Andric case RecurKind::FMulAdd:
9369b950333SDimitry Andric case RecurKind::FAdd:
9379b950333SDimitry Andric return Intrinsic::vector_reduce_fadd;
9389b950333SDimitry Andric case RecurKind::FMul:
9399b950333SDimitry Andric return Intrinsic::vector_reduce_fmul;
9409b950333SDimitry Andric case RecurKind::SMax:
9419b950333SDimitry Andric return Intrinsic::vector_reduce_smax;
9429b950333SDimitry Andric case RecurKind::SMin:
9439b950333SDimitry Andric return Intrinsic::vector_reduce_smin;
9449b950333SDimitry Andric case RecurKind::UMax:
9459b950333SDimitry Andric return Intrinsic::vector_reduce_umax;
9469b950333SDimitry Andric case RecurKind::UMin:
9479b950333SDimitry Andric return Intrinsic::vector_reduce_umin;
9489b950333SDimitry Andric case RecurKind::FMax:
9499b950333SDimitry Andric return Intrinsic::vector_reduce_fmax;
9509b950333SDimitry Andric case RecurKind::FMin:
9519b950333SDimitry Andric return Intrinsic::vector_reduce_fmin;
9529b950333SDimitry Andric case RecurKind::FMaximum:
9539b950333SDimitry Andric return Intrinsic::vector_reduce_fmaximum;
9549b950333SDimitry Andric case RecurKind::FMinimum:
9559b950333SDimitry Andric return Intrinsic::vector_reduce_fminimum;
9569b950333SDimitry Andric }
9579b950333SDimitry Andric }
9589b950333SDimitry Andric
getArithmeticReductionInstruction(Intrinsic::ID RdxID)959ac9a064cSDimitry Andric unsigned llvm::getArithmeticReductionInstruction(Intrinsic::ID RdxID) {
960ac9a064cSDimitry Andric switch (RdxID) {
961ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fadd:
962ac9a064cSDimitry Andric return Instruction::FAdd;
963ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmul:
964ac9a064cSDimitry Andric return Instruction::FMul;
965ac9a064cSDimitry Andric case Intrinsic::vector_reduce_add:
966ac9a064cSDimitry Andric return Instruction::Add;
967ac9a064cSDimitry Andric case Intrinsic::vector_reduce_mul:
968ac9a064cSDimitry Andric return Instruction::Mul;
969ac9a064cSDimitry Andric case Intrinsic::vector_reduce_and:
970ac9a064cSDimitry Andric return Instruction::And;
971ac9a064cSDimitry Andric case Intrinsic::vector_reduce_or:
972ac9a064cSDimitry Andric return Instruction::Or;
973ac9a064cSDimitry Andric case Intrinsic::vector_reduce_xor:
974ac9a064cSDimitry Andric return Instruction::Xor;
975ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smax:
976ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smin:
977ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umax:
978ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umin:
979ac9a064cSDimitry Andric return Instruction::ICmp;
980ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmax:
981ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmin:
982ac9a064cSDimitry Andric return Instruction::FCmp;
983ac9a064cSDimitry Andric default:
984ac9a064cSDimitry Andric llvm_unreachable("Unexpected ID");
985ac9a064cSDimitry Andric }
986ac9a064cSDimitry Andric }
987ac9a064cSDimitry Andric
getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)988ac9a064cSDimitry Andric Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID) {
989ac9a064cSDimitry Andric switch (RdxID) {
990ac9a064cSDimitry Andric default:
991ac9a064cSDimitry Andric llvm_unreachable("Unknown min/max recurrence kind");
992ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umin:
993ac9a064cSDimitry Andric return Intrinsic::umin;
994ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umax:
995ac9a064cSDimitry Andric return Intrinsic::umax;
996ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smin:
997ac9a064cSDimitry Andric return Intrinsic::smin;
998ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smax:
999ac9a064cSDimitry Andric return Intrinsic::smax;
1000ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmin:
1001ac9a064cSDimitry Andric return Intrinsic::minnum;
1002ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmax:
1003ac9a064cSDimitry Andric return Intrinsic::maxnum;
1004ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fminimum:
1005ac9a064cSDimitry Andric return Intrinsic::minimum;
1006ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmaximum:
1007ac9a064cSDimitry Andric return Intrinsic::maximum;
1008ac9a064cSDimitry Andric }
1009ac9a064cSDimitry Andric }
1010ac9a064cSDimitry Andric
getMinMaxReductionIntrinsicOp(RecurKind RK)10117fa27ce4SDimitry Andric Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(RecurKind RK) {
10127fa27ce4SDimitry Andric switch (RK) {
10137fa27ce4SDimitry Andric default:
10147fa27ce4SDimitry Andric llvm_unreachable("Unknown min/max recurrence kind");
10157fa27ce4SDimitry Andric case RecurKind::UMin:
10167fa27ce4SDimitry Andric return Intrinsic::umin;
10177fa27ce4SDimitry Andric case RecurKind::UMax:
10187fa27ce4SDimitry Andric return Intrinsic::umax;
10197fa27ce4SDimitry Andric case RecurKind::SMin:
10207fa27ce4SDimitry Andric return Intrinsic::smin;
10217fa27ce4SDimitry Andric case RecurKind::SMax:
10227fa27ce4SDimitry Andric return Intrinsic::smax;
10237fa27ce4SDimitry Andric case RecurKind::FMin:
10247fa27ce4SDimitry Andric return Intrinsic::minnum;
10257fa27ce4SDimitry Andric case RecurKind::FMax:
10267fa27ce4SDimitry Andric return Intrinsic::maxnum;
10277fa27ce4SDimitry Andric case RecurKind::FMinimum:
10287fa27ce4SDimitry Andric return Intrinsic::minimum;
10297fa27ce4SDimitry Andric case RecurKind::FMaximum:
10307fa27ce4SDimitry Andric return Intrinsic::maximum;
10317fa27ce4SDimitry Andric }
10327fa27ce4SDimitry Andric }
10337fa27ce4SDimitry Andric
getMinMaxReductionRecurKind(Intrinsic::ID RdxID)1034ac9a064cSDimitry Andric RecurKind llvm::getMinMaxReductionRecurKind(Intrinsic::ID RdxID) {
1035ac9a064cSDimitry Andric switch (RdxID) {
1036ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smax:
1037ac9a064cSDimitry Andric return RecurKind::SMax;
1038ac9a064cSDimitry Andric case Intrinsic::vector_reduce_smin:
1039ac9a064cSDimitry Andric return RecurKind::SMin;
1040ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umax:
1041ac9a064cSDimitry Andric return RecurKind::UMax;
1042ac9a064cSDimitry Andric case Intrinsic::vector_reduce_umin:
1043ac9a064cSDimitry Andric return RecurKind::UMin;
1044ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmax:
1045ac9a064cSDimitry Andric return RecurKind::FMax;
1046ac9a064cSDimitry Andric case Intrinsic::vector_reduce_fmin:
1047ac9a064cSDimitry Andric return RecurKind::FMin;
1048ac9a064cSDimitry Andric default:
1049ac9a064cSDimitry Andric return RecurKind::None;
1050ac9a064cSDimitry Andric }
1051ac9a064cSDimitry Andric }
1052ac9a064cSDimitry Andric
getMinMaxReductionPredicate(RecurKind RK)1053c0981da4SDimitry Andric CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
1054d8e91e46SDimitry Andric switch (RK) {
1055d8e91e46SDimitry Andric default:
1056d8e91e46SDimitry Andric llvm_unreachable("Unknown min/max recurrence kind");
1057b60736ecSDimitry Andric case RecurKind::UMin:
1058c0981da4SDimitry Andric return CmpInst::ICMP_ULT;
1059b60736ecSDimitry Andric case RecurKind::UMax:
1060c0981da4SDimitry Andric return CmpInst::ICMP_UGT;
1061b60736ecSDimitry Andric case RecurKind::SMin:
1062c0981da4SDimitry Andric return CmpInst::ICMP_SLT;
1063b60736ecSDimitry Andric case RecurKind::SMax:
1064c0981da4SDimitry Andric return CmpInst::ICMP_SGT;
1065b60736ecSDimitry Andric case RecurKind::FMin:
1066c0981da4SDimitry Andric return CmpInst::FCMP_OLT;
1067b60736ecSDimitry Andric case RecurKind::FMax:
1068c0981da4SDimitry Andric return CmpInst::FCMP_OGT;
10697fa27ce4SDimitry Andric // We do not add FMinimum/FMaximum recurrence kind here since there is no
10707fa27ce4SDimitry Andric // equivalent predicate which compares signed zeroes according to the
10717fa27ce4SDimitry Andric // semantics of the intrinsics (llvm.minimum/maximum).
1072c0981da4SDimitry Andric }
1073d8e91e46SDimitry Andric }
1074d8e91e46SDimitry Andric
createMinMaxOp(IRBuilderBase & Builder,RecurKind RK,Value * Left,Value * Right)1075c0981da4SDimitry Andric Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
1076c0981da4SDimitry Andric Value *Right) {
10777fa27ce4SDimitry Andric Type *Ty = Left->getType();
10787fa27ce4SDimitry Andric if (Ty->isIntOrIntVectorTy() ||
10797fa27ce4SDimitry Andric (RK == RecurKind::FMinimum || RK == RecurKind::FMaximum)) {
10807fa27ce4SDimitry Andric // TODO: Add float minnum/maxnum support when FMF nnan is set.
10817fa27ce4SDimitry Andric Intrinsic::ID Id = getMinMaxReductionIntrinsicOp(RK);
10827fa27ce4SDimitry Andric return Builder.CreateIntrinsic(Ty, Id, {Left, Right}, nullptr,
10837fa27ce4SDimitry Andric "rdx.minmax");
10847fa27ce4SDimitry Andric }
1085c0981da4SDimitry Andric CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
1086b60736ecSDimitry Andric Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
1087d8e91e46SDimitry Andric Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1088d8e91e46SDimitry Andric return Select;
1089d8e91e46SDimitry Andric }
1090d8e91e46SDimitry Andric
1091eb11fae6SDimitry Andric // Helper to generate an ordered reduction.
getOrderedReduction(IRBuilderBase & Builder,Value * Acc,Value * Src,unsigned Op,RecurKind RdxKind)1092b60736ecSDimitry Andric Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
109377fc4c14SDimitry Andric unsigned Op, RecurKind RdxKind) {
1094cfca06d7SDimitry Andric unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1095eb11fae6SDimitry Andric
1096eb11fae6SDimitry Andric // Extract and apply reduction ops in ascending order:
1097eb11fae6SDimitry Andric // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
1098eb11fae6SDimitry Andric Value *Result = Acc;
1099eb11fae6SDimitry Andric for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1100eb11fae6SDimitry Andric Value *Ext =
1101eb11fae6SDimitry Andric Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
1102eb11fae6SDimitry Andric
1103eb11fae6SDimitry Andric if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1104eb11fae6SDimitry Andric Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
1105eb11fae6SDimitry Andric "bin.rdx");
1106eb11fae6SDimitry Andric } else {
1107b60736ecSDimitry Andric assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1108eb11fae6SDimitry Andric "Invalid min/max");
1109b60736ecSDimitry Andric Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
1110eb11fae6SDimitry Andric }
1111eb11fae6SDimitry Andric }
1112eb11fae6SDimitry Andric
1113eb11fae6SDimitry Andric return Result;
1114eb11fae6SDimitry Andric }
1115eb11fae6SDimitry Andric
11166b3f41edSDimitry Andric // Helper to generate a log2 shuffle reduction.
getShuffleReduction(IRBuilderBase & Builder,Value * Src,unsigned Op,TargetTransformInfo::ReductionShuffle RS,RecurKind RdxKind)1117b60736ecSDimitry Andric Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
1118ac9a064cSDimitry Andric unsigned Op,
1119ac9a064cSDimitry Andric TargetTransformInfo::ReductionShuffle RS,
1120ac9a064cSDimitry Andric RecurKind RdxKind) {
1121cfca06d7SDimitry Andric unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
11226b3f41edSDimitry Andric // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
11236b3f41edSDimitry Andric // and vector ops, reducing the set of values being computed by half each
11246b3f41edSDimitry Andric // round.
11256b3f41edSDimitry Andric assert(isPowerOf2_32(VF) &&
11266b3f41edSDimitry Andric "Reduction emission only supported for pow2 vectors!");
112777fc4c14SDimitry Andric // Note: fast-math-flags flags are controlled by the builder configuration
112877fc4c14SDimitry Andric // and are assumed to apply to all generated arithmetic instructions. Other
112977fc4c14SDimitry Andric // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
113077fc4c14SDimitry Andric // of the builder configuration, and since they're not passed explicitly,
113177fc4c14SDimitry Andric // will never be relevant here. Note that it would be generally unsound to
113277fc4c14SDimitry Andric // propagate these from an intrinsic call to the expansion anyways as we/
113377fc4c14SDimitry Andric // change the order of operations.
1134ac9a064cSDimitry Andric auto BuildShuffledOp = [&Builder, &Op,
1135ac9a064cSDimitry Andric &RdxKind](SmallVectorImpl<int> &ShuffleMask,
1136ac9a064cSDimitry Andric Value *&TmpVec) -> void {
1137ac9a064cSDimitry Andric Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
1138ac9a064cSDimitry Andric if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1139ac9a064cSDimitry Andric TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1140ac9a064cSDimitry Andric "bin.rdx");
1141ac9a064cSDimitry Andric } else {
1142ac9a064cSDimitry Andric assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1143ac9a064cSDimitry Andric "Invalid min/max");
1144ac9a064cSDimitry Andric TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
1145ac9a064cSDimitry Andric }
1146ac9a064cSDimitry Andric };
1147ac9a064cSDimitry Andric
11486b3f41edSDimitry Andric Value *TmpVec = Src;
1149ac9a064cSDimitry Andric if (TargetTransformInfo::ReductionShuffle::Pairwise == RS) {
1150ac9a064cSDimitry Andric SmallVector<int, 32> ShuffleMask(VF);
1151ac9a064cSDimitry Andric for (unsigned stride = 1; stride < VF; stride <<= 1) {
1152ac9a064cSDimitry Andric // Initialise the mask with undef.
1153ac9a064cSDimitry Andric std::fill(ShuffleMask.begin(), ShuffleMask.end(), -1);
1154ac9a064cSDimitry Andric for (unsigned j = 0; j < VF; j += stride << 1) {
1155ac9a064cSDimitry Andric ShuffleMask[j] = j + stride;
1156ac9a064cSDimitry Andric }
1157ac9a064cSDimitry Andric BuildShuffledOp(ShuffleMask, TmpVec);
1158ac9a064cSDimitry Andric }
1159ac9a064cSDimitry Andric } else {
1160cfca06d7SDimitry Andric SmallVector<int, 32> ShuffleMask(VF);
11616b3f41edSDimitry Andric for (unsigned i = VF; i != 1; i >>= 1) {
11626b3f41edSDimitry Andric // Move the upper half of the vector to the lower half.
11636b3f41edSDimitry Andric for (unsigned j = 0; j != i / 2; ++j)
1164cfca06d7SDimitry Andric ShuffleMask[j] = i / 2 + j;
11656b3f41edSDimitry Andric
11666b3f41edSDimitry Andric // Fill the rest of the mask with undef.
1167cfca06d7SDimitry Andric std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
1168ac9a064cSDimitry Andric BuildShuffledOp(ShuffleMask, TmpVec);
11696b3f41edSDimitry Andric }
11706b3f41edSDimitry Andric }
11716b3f41edSDimitry Andric // The result is in the first element of the vector.
11726b3f41edSDimitry Andric return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
11736b3f41edSDimitry Andric }
11746b3f41edSDimitry Andric
createAnyOfTargetReduction(IRBuilderBase & Builder,Value * Src,const RecurrenceDescriptor & Desc,PHINode * OrigPhi)1175b1c73532SDimitry Andric Value *llvm::createAnyOfTargetReduction(IRBuilderBase &Builder, Value *Src,
1176c0981da4SDimitry Andric const RecurrenceDescriptor &Desc,
1177c0981da4SDimitry Andric PHINode *OrigPhi) {
1178b1c73532SDimitry Andric assert(
1179b1c73532SDimitry Andric RecurrenceDescriptor::isAnyOfRecurrenceKind(Desc.getRecurrenceKind()) &&
1180c0981da4SDimitry Andric "Unexpected reduction kind");
1181c0981da4SDimitry Andric Value *InitVal = Desc.getRecurrenceStartValue();
1182c0981da4SDimitry Andric Value *NewVal = nullptr;
1183c0981da4SDimitry Andric
1184c0981da4SDimitry Andric // First use the original phi to determine the new value we're trying to
1185c0981da4SDimitry Andric // select from in the loop.
1186c0981da4SDimitry Andric SelectInst *SI = nullptr;
1187c0981da4SDimitry Andric for (auto *U : OrigPhi->users()) {
1188c0981da4SDimitry Andric if ((SI = dyn_cast<SelectInst>(U)))
1189c0981da4SDimitry Andric break;
1190c0981da4SDimitry Andric }
1191c0981da4SDimitry Andric assert(SI && "One user of the original phi should be a select");
1192c0981da4SDimitry Andric
1193c0981da4SDimitry Andric if (SI->getTrueValue() == OrigPhi)
1194c0981da4SDimitry Andric NewVal = SI->getFalseValue();
1195c0981da4SDimitry Andric else {
1196c0981da4SDimitry Andric assert(SI->getFalseValue() == OrigPhi &&
1197c0981da4SDimitry Andric "At least one input to the select should be the original Phi");
1198c0981da4SDimitry Andric NewVal = SI->getTrueValue();
1199c0981da4SDimitry Andric }
1200c0981da4SDimitry Andric
1201c0981da4SDimitry Andric // If any predicate is true it means that we want to select the new value.
1202ac9a064cSDimitry Andric Value *AnyOf =
1203ac9a064cSDimitry Andric Src->getType()->isVectorTy() ? Builder.CreateOrReduce(Src) : Src;
1204ac9a064cSDimitry Andric // The compares in the loop may yield poison, which propagates through the
1205ac9a064cSDimitry Andric // bitwise ORs. Freeze it here before the condition is used.
1206ac9a064cSDimitry Andric AnyOf = Builder.CreateFreeze(AnyOf);
1207ac9a064cSDimitry Andric return Builder.CreateSelect(AnyOf, NewVal, InitVal, "rdx.select");
1208c0981da4SDimitry Andric }
1209c0981da4SDimitry Andric
createSimpleTargetReduction(IRBuilderBase & Builder,Value * Src,RecurKind RdxKind)1210b1c73532SDimitry Andric Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder, Value *Src,
1211b1c73532SDimitry Andric RecurKind RdxKind) {
1212b60736ecSDimitry Andric auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
1213b60736ecSDimitry Andric switch (RdxKind) {
1214b60736ecSDimitry Andric case RecurKind::Add:
1215b60736ecSDimitry Andric return Builder.CreateAddReduce(Src);
1216b60736ecSDimitry Andric case RecurKind::Mul:
1217b60736ecSDimitry Andric return Builder.CreateMulReduce(Src);
1218b60736ecSDimitry Andric case RecurKind::And:
1219b60736ecSDimitry Andric return Builder.CreateAndReduce(Src);
1220b60736ecSDimitry Andric case RecurKind::Or:
1221b60736ecSDimitry Andric return Builder.CreateOrReduce(Src);
1222b60736ecSDimitry Andric case RecurKind::Xor:
1223b60736ecSDimitry Andric return Builder.CreateXorReduce(Src);
1224f65dcba8SDimitry Andric case RecurKind::FMulAdd:
1225b60736ecSDimitry Andric case RecurKind::FAdd:
1226b60736ecSDimitry Andric return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
1227b60736ecSDimitry Andric Src);
1228b60736ecSDimitry Andric case RecurKind::FMul:
1229b60736ecSDimitry Andric return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
1230b60736ecSDimitry Andric case RecurKind::SMax:
1231b60736ecSDimitry Andric return Builder.CreateIntMaxReduce(Src, true);
1232b60736ecSDimitry Andric case RecurKind::SMin:
1233b60736ecSDimitry Andric return Builder.CreateIntMinReduce(Src, true);
1234b60736ecSDimitry Andric case RecurKind::UMax:
1235b60736ecSDimitry Andric return Builder.CreateIntMaxReduce(Src, false);
1236b60736ecSDimitry Andric case RecurKind::UMin:
1237b60736ecSDimitry Andric return Builder.CreateIntMinReduce(Src, false);
1238b60736ecSDimitry Andric case RecurKind::FMax:
1239b60736ecSDimitry Andric return Builder.CreateFPMaxReduce(Src);
1240b60736ecSDimitry Andric case RecurKind::FMin:
1241b60736ecSDimitry Andric return Builder.CreateFPMinReduce(Src);
12427fa27ce4SDimitry Andric case RecurKind::FMinimum:
12437fa27ce4SDimitry Andric return Builder.CreateFPMinimumReduce(Src);
12447fa27ce4SDimitry Andric case RecurKind::FMaximum:
12457fa27ce4SDimitry Andric return Builder.CreateFPMaximumReduce(Src);
12466b3f41edSDimitry Andric default:
12476b3f41edSDimitry Andric llvm_unreachable("Unhandled opcode");
12486b3f41edSDimitry Andric }
12496b3f41edSDimitry Andric }
12506b3f41edSDimitry Andric
createSimpleTargetReduction(VectorBuilder & VBuilder,Value * Src,const RecurrenceDescriptor & Desc)1251ac9a064cSDimitry Andric Value *llvm::createSimpleTargetReduction(VectorBuilder &VBuilder, Value *Src,
1252ac9a064cSDimitry Andric const RecurrenceDescriptor &Desc) {
1253ac9a064cSDimitry Andric RecurKind Kind = Desc.getRecurrenceKind();
1254ac9a064cSDimitry Andric assert(!RecurrenceDescriptor::isAnyOfRecurrenceKind(Kind) &&
1255ac9a064cSDimitry Andric "AnyOf reduction is not supported.");
12569b950333SDimitry Andric Intrinsic::ID Id = getReductionIntrinsicID(Kind);
1257ac9a064cSDimitry Andric auto *SrcTy = cast<VectorType>(Src->getType());
1258ac9a064cSDimitry Andric Type *SrcEltTy = SrcTy->getElementType();
1259ac9a064cSDimitry Andric Value *Iden =
1260ac9a064cSDimitry Andric Desc.getRecurrenceIdentity(Kind, SrcEltTy, Desc.getFastMathFlags());
1261ac9a064cSDimitry Andric Value *Ops[] = {Iden, Src};
12629b950333SDimitry Andric return VBuilder.createSimpleTargetReduction(Id, SrcTy, Ops);
1263ac9a064cSDimitry Andric }
1264ac9a064cSDimitry Andric
createTargetReduction(IRBuilderBase & B,const RecurrenceDescriptor & Desc,Value * Src,PHINode * OrigPhi)1265cfca06d7SDimitry Andric Value *llvm::createTargetReduction(IRBuilderBase &B,
1266c0981da4SDimitry Andric const RecurrenceDescriptor &Desc, Value *Src,
1267c0981da4SDimitry Andric PHINode *OrigPhi) {
12686b3f41edSDimitry Andric // TODO: Support in-order reductions based on the recurrence descriptor.
1269e6d15924SDimitry Andric // All ops in the reduction inherit fast-math-flags from the recurrence
1270e6d15924SDimitry Andric // descriptor.
1271cfca06d7SDimitry Andric IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1272e6d15924SDimitry Andric B.setFastMathFlags(Desc.getFastMathFlags());
1273c0981da4SDimitry Andric
1274c0981da4SDimitry Andric RecurKind RK = Desc.getRecurrenceKind();
1275b1c73532SDimitry Andric if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RK))
1276b1c73532SDimitry Andric return createAnyOfTargetReduction(B, Src, Desc, OrigPhi);
1277c0981da4SDimitry Andric
1278b1c73532SDimitry Andric return createSimpleTargetReduction(B, Src, RK);
12796b3f41edSDimitry Andric }
12806b3f41edSDimitry Andric
createOrderedReduction(IRBuilderBase & B,const RecurrenceDescriptor & Desc,Value * Src,Value * Start)1281344a3780SDimitry Andric Value *llvm::createOrderedReduction(IRBuilderBase &B,
1282344a3780SDimitry Andric const RecurrenceDescriptor &Desc,
1283344a3780SDimitry Andric Value *Src, Value *Start) {
1284f65dcba8SDimitry Andric assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
1285f65dcba8SDimitry Andric Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
1286344a3780SDimitry Andric "Unexpected reduction kind");
1287344a3780SDimitry Andric assert(Src->getType()->isVectorTy() && "Expected a vector type");
1288344a3780SDimitry Andric assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1289344a3780SDimitry Andric
1290344a3780SDimitry Andric return B.CreateFAddReduce(Start, Src);
1291344a3780SDimitry Andric }
1292344a3780SDimitry Andric
createOrderedReduction(VectorBuilder & VBuilder,const RecurrenceDescriptor & Desc,Value * Src,Value * Start)1293ac9a064cSDimitry Andric Value *llvm::createOrderedReduction(VectorBuilder &VBuilder,
1294ac9a064cSDimitry Andric const RecurrenceDescriptor &Desc,
1295ac9a064cSDimitry Andric Value *Src, Value *Start) {
1296ac9a064cSDimitry Andric assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
1297ac9a064cSDimitry Andric Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
1298ac9a064cSDimitry Andric "Unexpected reduction kind");
1299ac9a064cSDimitry Andric assert(Src->getType()->isVectorTy() && "Expected a vector type");
1300ac9a064cSDimitry Andric assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1301ac9a064cSDimitry Andric
13029b950333SDimitry Andric Intrinsic::ID Id = getReductionIntrinsicID(RecurKind::FAdd);
1303ac9a064cSDimitry Andric auto *SrcTy = cast<VectorType>(Src->getType());
1304ac9a064cSDimitry Andric Value *Ops[] = {Start, Src};
13059b950333SDimitry Andric return VBuilder.createSimpleTargetReduction(Id, SrcTy, Ops);
1306ac9a064cSDimitry Andric }
1307ac9a064cSDimitry Andric
propagateIRFlags(Value * I,ArrayRef<Value * > VL,Value * OpValue,bool IncludeWrapFlags)1308145449b1SDimitry Andric void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue,
1309145449b1SDimitry Andric bool IncludeWrapFlags) {
13103ad6a4b4SDimitry Andric auto *VecOp = dyn_cast<Instruction>(I);
13113ad6a4b4SDimitry Andric if (!VecOp)
13123ad6a4b4SDimitry Andric return;
13133ad6a4b4SDimitry Andric auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
13143ad6a4b4SDimitry Andric : dyn_cast<Instruction>(OpValue);
13153ad6a4b4SDimitry Andric if (!Intersection)
13163ad6a4b4SDimitry Andric return;
13173ad6a4b4SDimitry Andric const unsigned Opcode = Intersection->getOpcode();
1318145449b1SDimitry Andric VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
13193ad6a4b4SDimitry Andric for (auto *V : VL) {
13203ad6a4b4SDimitry Andric auto *Instr = dyn_cast<Instruction>(V);
13213ad6a4b4SDimitry Andric if (!Instr)
13223ad6a4b4SDimitry Andric continue;
13233ad6a4b4SDimitry Andric if (OpValue == nullptr || Opcode == Instr->getOpcode())
13243ad6a4b4SDimitry Andric VecOp->andIRFlags(V);
13256b3f41edSDimitry Andric }
13266b3f41edSDimitry Andric }
1327d8e91e46SDimitry Andric
isKnownNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1328d8e91e46SDimitry Andric bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1329d8e91e46SDimitry Andric ScalarEvolution &SE) {
1330d8e91e46SDimitry Andric const SCEV *Zero = SE.getZero(S->getType());
1331d8e91e46SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
1332d8e91e46SDimitry Andric SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1333d8e91e46SDimitry Andric }
1334d8e91e46SDimitry Andric
isKnownNonNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1335d8e91e46SDimitry Andric bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1336d8e91e46SDimitry Andric ScalarEvolution &SE) {
1337d8e91e46SDimitry Andric const SCEV *Zero = SE.getZero(S->getType());
1338d8e91e46SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
1339d8e91e46SDimitry Andric SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1340d8e91e46SDimitry Andric }
1341d8e91e46SDimitry Andric
isKnownPositiveInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)13427fa27ce4SDimitry Andric bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L,
13437fa27ce4SDimitry Andric ScalarEvolution &SE) {
13447fa27ce4SDimitry Andric const SCEV *Zero = SE.getZero(S->getType());
13457fa27ce4SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
13467fa27ce4SDimitry Andric SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, S, Zero);
13477fa27ce4SDimitry Andric }
13487fa27ce4SDimitry Andric
isKnownNonPositiveInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)13497fa27ce4SDimitry Andric bool llvm::isKnownNonPositiveInLoop(const SCEV *S, const Loop *L,
13507fa27ce4SDimitry Andric ScalarEvolution &SE) {
13517fa27ce4SDimitry Andric const SCEV *Zero = SE.getZero(S->getType());
13527fa27ce4SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
13537fa27ce4SDimitry Andric SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLE, S, Zero);
13547fa27ce4SDimitry Andric }
13557fa27ce4SDimitry Andric
cannotBeMinInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1356d8e91e46SDimitry Andric bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1357d8e91e46SDimitry Andric bool Signed) {
1358d8e91e46SDimitry Andric unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1359d8e91e46SDimitry Andric APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1360d8e91e46SDimitry Andric APInt::getMinValue(BitWidth);
1361d8e91e46SDimitry Andric auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1362d8e91e46SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
1363d8e91e46SDimitry Andric SE.isLoopEntryGuardedByCond(L, Predicate, S,
1364d8e91e46SDimitry Andric SE.getConstant(Min));
1365d8e91e46SDimitry Andric }
1366d8e91e46SDimitry Andric
cannotBeMaxInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1367d8e91e46SDimitry Andric bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1368d8e91e46SDimitry Andric bool Signed) {
1369d8e91e46SDimitry Andric unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1370d8e91e46SDimitry Andric APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1371d8e91e46SDimitry Andric APInt::getMaxValue(BitWidth);
1372d8e91e46SDimitry Andric auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1373d8e91e46SDimitry Andric return SE.isAvailableAtLoopEntry(S, L) &&
1374d8e91e46SDimitry Andric SE.isLoopEntryGuardedByCond(L, Predicate, S,
1375d8e91e46SDimitry Andric SE.getConstant(Max));
1376d8e91e46SDimitry Andric }
1377cfca06d7SDimitry Andric
1378cfca06d7SDimitry Andric //===----------------------------------------------------------------------===//
1379cfca06d7SDimitry Andric // rewriteLoopExitValues - Optimize IV users outside the loop.
1380cfca06d7SDimitry Andric // As a side effect, reduces the amount of IV processing within the loop.
1381cfca06d7SDimitry Andric //===----------------------------------------------------------------------===//
1382cfca06d7SDimitry Andric
hasHardUserWithinLoop(const Loop * L,const Instruction * I)1383cfca06d7SDimitry Andric static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1384cfca06d7SDimitry Andric SmallPtrSet<const Instruction *, 8> Visited;
1385cfca06d7SDimitry Andric SmallVector<const Instruction *, 8> WorkList;
1386cfca06d7SDimitry Andric Visited.insert(I);
1387cfca06d7SDimitry Andric WorkList.push_back(I);
1388cfca06d7SDimitry Andric while (!WorkList.empty()) {
1389cfca06d7SDimitry Andric const Instruction *Curr = WorkList.pop_back_val();
1390cfca06d7SDimitry Andric // This use is outside the loop, nothing to do.
1391cfca06d7SDimitry Andric if (!L->contains(Curr))
1392cfca06d7SDimitry Andric continue;
1393cfca06d7SDimitry Andric // Do we assume it is a "hard" use which will not be eliminated easily?
1394cfca06d7SDimitry Andric if (Curr->mayHaveSideEffects())
1395cfca06d7SDimitry Andric return true;
1396cfca06d7SDimitry Andric // Otherwise, add all its users to worklist.
1397e3b55780SDimitry Andric for (const auto *U : Curr->users()) {
1398cfca06d7SDimitry Andric auto *UI = cast<Instruction>(U);
1399cfca06d7SDimitry Andric if (Visited.insert(UI).second)
1400cfca06d7SDimitry Andric WorkList.push_back(UI);
1401cfca06d7SDimitry Andric }
1402cfca06d7SDimitry Andric }
1403cfca06d7SDimitry Andric return false;
1404cfca06d7SDimitry Andric }
1405cfca06d7SDimitry Andric
1406cfca06d7SDimitry Andric // Collect information about PHI nodes which can be transformed in
1407cfca06d7SDimitry Andric // rewriteLoopExitValues.
1408cfca06d7SDimitry Andric struct RewritePhi {
1409cfca06d7SDimitry Andric PHINode *PN; // For which PHI node is this replacement?
1410cfca06d7SDimitry Andric unsigned Ith; // For which incoming value?
1411cfca06d7SDimitry Andric const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1412cfca06d7SDimitry Andric Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1413cfca06d7SDimitry Andric bool HighCost; // Is this expansion a high-cost?
1414cfca06d7SDimitry Andric
RewritePhiRewritePhi1415cfca06d7SDimitry Andric RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1416cfca06d7SDimitry Andric bool H)
1417cfca06d7SDimitry Andric : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1418cfca06d7SDimitry Andric HighCost(H) {}
1419cfca06d7SDimitry Andric };
1420cfca06d7SDimitry Andric
1421cfca06d7SDimitry Andric // Check whether it is possible to delete the loop after rewriting exit
1422cfca06d7SDimitry Andric // value. If it is possible, ignore ReplaceExitValue and do rewriting
1423cfca06d7SDimitry Andric // aggressively.
canLoopBeDeleted(Loop * L,SmallVector<RewritePhi,8> & RewritePhiSet)1424cfca06d7SDimitry Andric static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1425cfca06d7SDimitry Andric BasicBlock *Preheader = L->getLoopPreheader();
1426cfca06d7SDimitry Andric // If there is no preheader, the loop will not be deleted.
1427cfca06d7SDimitry Andric if (!Preheader)
1428cfca06d7SDimitry Andric return false;
1429cfca06d7SDimitry Andric
1430cfca06d7SDimitry Andric // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1431cfca06d7SDimitry Andric // We obviate multiple ExitingBlocks case for simplicity.
1432cfca06d7SDimitry Andric // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1433cfca06d7SDimitry Andric // after exit value rewriting, we can enhance the logic here.
1434cfca06d7SDimitry Andric SmallVector<BasicBlock *, 4> ExitingBlocks;
1435cfca06d7SDimitry Andric L->getExitingBlocks(ExitingBlocks);
1436cfca06d7SDimitry Andric SmallVector<BasicBlock *, 8> ExitBlocks;
1437cfca06d7SDimitry Andric L->getUniqueExitBlocks(ExitBlocks);
1438cfca06d7SDimitry Andric if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1439cfca06d7SDimitry Andric return false;
1440cfca06d7SDimitry Andric
1441cfca06d7SDimitry Andric BasicBlock *ExitBlock = ExitBlocks[0];
1442cfca06d7SDimitry Andric BasicBlock::iterator BI = ExitBlock->begin();
1443cfca06d7SDimitry Andric while (PHINode *P = dyn_cast<PHINode>(BI)) {
1444cfca06d7SDimitry Andric Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1445cfca06d7SDimitry Andric
1446cfca06d7SDimitry Andric // If the Incoming value of P is found in RewritePhiSet, we know it
1447cfca06d7SDimitry Andric // could be rewritten to use a loop invariant value in transformation
1448cfca06d7SDimitry Andric // phase later. Skip it in the loop invariant check below.
1449cfca06d7SDimitry Andric bool found = false;
1450cfca06d7SDimitry Andric for (const RewritePhi &Phi : RewritePhiSet) {
1451cfca06d7SDimitry Andric unsigned i = Phi.Ith;
1452cfca06d7SDimitry Andric if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1453cfca06d7SDimitry Andric found = true;
1454cfca06d7SDimitry Andric break;
1455cfca06d7SDimitry Andric }
1456cfca06d7SDimitry Andric }
1457cfca06d7SDimitry Andric
1458cfca06d7SDimitry Andric Instruction *I;
1459cfca06d7SDimitry Andric if (!found && (I = dyn_cast<Instruction>(Incoming)))
1460cfca06d7SDimitry Andric if (!L->hasLoopInvariantOperands(I))
1461cfca06d7SDimitry Andric return false;
1462cfca06d7SDimitry Andric
1463cfca06d7SDimitry Andric ++BI;
1464cfca06d7SDimitry Andric }
1465cfca06d7SDimitry Andric
1466cfca06d7SDimitry Andric for (auto *BB : L->blocks())
1467cfca06d7SDimitry Andric if (llvm::any_of(*BB, [](Instruction &I) {
1468cfca06d7SDimitry Andric return I.mayHaveSideEffects();
1469cfca06d7SDimitry Andric }))
1470cfca06d7SDimitry Andric return false;
1471cfca06d7SDimitry Andric
1472cfca06d7SDimitry Andric return true;
1473cfca06d7SDimitry Andric }
1474cfca06d7SDimitry Andric
14751f917f69SDimitry Andric /// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
14761f917f69SDimitry Andric /// and returns true if this Phi is an induction phi in the loop. When
14771f917f69SDimitry Andric /// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
checkIsIndPhi(PHINode * Phi,Loop * L,ScalarEvolution * SE,InductionDescriptor & ID)14781f917f69SDimitry Andric static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
14791f917f69SDimitry Andric InductionDescriptor &ID) {
14801f917f69SDimitry Andric if (!Phi)
14811f917f69SDimitry Andric return false;
14821f917f69SDimitry Andric if (!L->getLoopPreheader())
14831f917f69SDimitry Andric return false;
14841f917f69SDimitry Andric if (Phi->getParent() != L->getHeader())
14851f917f69SDimitry Andric return false;
14861f917f69SDimitry Andric return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
14871f917f69SDimitry Andric }
14881f917f69SDimitry Andric
rewriteLoopExitValues(Loop * L,LoopInfo * LI,TargetLibraryInfo * TLI,ScalarEvolution * SE,const TargetTransformInfo * TTI,SCEVExpander & Rewriter,DominatorTree * DT,ReplaceExitVal ReplaceExitValue,SmallVector<WeakTrackingVH,16> & DeadInsts)1489cfca06d7SDimitry Andric int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1490cfca06d7SDimitry Andric ScalarEvolution *SE,
1491cfca06d7SDimitry Andric const TargetTransformInfo *TTI,
1492cfca06d7SDimitry Andric SCEVExpander &Rewriter, DominatorTree *DT,
1493cfca06d7SDimitry Andric ReplaceExitVal ReplaceExitValue,
1494cfca06d7SDimitry Andric SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1495cfca06d7SDimitry Andric // Check a pre-condition.
1496cfca06d7SDimitry Andric assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1497cfca06d7SDimitry Andric "Indvars did not preserve LCSSA!");
1498cfca06d7SDimitry Andric
1499cfca06d7SDimitry Andric SmallVector<BasicBlock*, 8> ExitBlocks;
1500cfca06d7SDimitry Andric L->getUniqueExitBlocks(ExitBlocks);
1501cfca06d7SDimitry Andric
1502cfca06d7SDimitry Andric SmallVector<RewritePhi, 8> RewritePhiSet;
1503cfca06d7SDimitry Andric // Find all values that are computed inside the loop, but used outside of it.
1504cfca06d7SDimitry Andric // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
1505cfca06d7SDimitry Andric // the exit blocks of the loop to find them.
1506cfca06d7SDimitry Andric for (BasicBlock *ExitBB : ExitBlocks) {
1507cfca06d7SDimitry Andric // If there are no PHI nodes in this exit block, then no values defined
1508cfca06d7SDimitry Andric // inside the loop are used on this path, skip it.
1509cfca06d7SDimitry Andric PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1510cfca06d7SDimitry Andric if (!PN) continue;
1511cfca06d7SDimitry Andric
1512cfca06d7SDimitry Andric unsigned NumPreds = PN->getNumIncomingValues();
1513cfca06d7SDimitry Andric
1514cfca06d7SDimitry Andric // Iterate over all of the PHI nodes.
1515cfca06d7SDimitry Andric BasicBlock::iterator BBI = ExitBB->begin();
1516cfca06d7SDimitry Andric while ((PN = dyn_cast<PHINode>(BBI++))) {
1517cfca06d7SDimitry Andric if (PN->use_empty())
1518cfca06d7SDimitry Andric continue; // dead use, don't replace it
1519cfca06d7SDimitry Andric
1520cfca06d7SDimitry Andric if (!SE->isSCEVable(PN->getType()))
1521cfca06d7SDimitry Andric continue;
1522cfca06d7SDimitry Andric
1523cfca06d7SDimitry Andric // Iterate over all of the values in all the PHI nodes.
1524cfca06d7SDimitry Andric for (unsigned i = 0; i != NumPreds; ++i) {
1525cfca06d7SDimitry Andric // If the value being merged in is not integer or is not defined
1526cfca06d7SDimitry Andric // in the loop, skip it.
1527cfca06d7SDimitry Andric Value *InVal = PN->getIncomingValue(i);
1528cfca06d7SDimitry Andric if (!isa<Instruction>(InVal))
1529cfca06d7SDimitry Andric continue;
1530cfca06d7SDimitry Andric
1531cfca06d7SDimitry Andric // If this pred is for a subloop, not L itself, skip it.
1532cfca06d7SDimitry Andric if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1533cfca06d7SDimitry Andric continue; // The Block is in a subloop, skip it.
1534cfca06d7SDimitry Andric
1535cfca06d7SDimitry Andric // Check that InVal is defined in the loop.
1536cfca06d7SDimitry Andric Instruction *Inst = cast<Instruction>(InVal);
1537cfca06d7SDimitry Andric if (!L->contains(Inst))
1538cfca06d7SDimitry Andric continue;
1539cfca06d7SDimitry Andric
15401f917f69SDimitry Andric // Find exit values which are induction variables in the loop, and are
15411f917f69SDimitry Andric // unused in the loop, with the only use being the exit block PhiNode,
15421f917f69SDimitry Andric // and the induction variable update binary operator.
15431f917f69SDimitry Andric // The exit value can be replaced with the final value when it is cheap
15441f917f69SDimitry Andric // to do so.
15451f917f69SDimitry Andric if (ReplaceExitValue == UnusedIndVarInLoop) {
15461f917f69SDimitry Andric InductionDescriptor ID;
15471f917f69SDimitry Andric PHINode *IndPhi = dyn_cast<PHINode>(Inst);
15481f917f69SDimitry Andric if (IndPhi) {
15491f917f69SDimitry Andric if (!checkIsIndPhi(IndPhi, L, SE, ID))
15501f917f69SDimitry Andric continue;
15511f917f69SDimitry Andric // This is an induction PHI. Check that the only users are PHI
15521f917f69SDimitry Andric // nodes, and induction variable update binary operators.
15531f917f69SDimitry Andric if (llvm::any_of(Inst->users(), [&](User *U) {
15541f917f69SDimitry Andric if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
15551f917f69SDimitry Andric return true;
15561f917f69SDimitry Andric BinaryOperator *B = dyn_cast<BinaryOperator>(U);
15571f917f69SDimitry Andric if (B && B != ID.getInductionBinOp())
15581f917f69SDimitry Andric return true;
15591f917f69SDimitry Andric return false;
15601f917f69SDimitry Andric }))
15611f917f69SDimitry Andric continue;
15621f917f69SDimitry Andric } else {
15631f917f69SDimitry Andric // If it is not an induction phi, it must be an induction update
15641f917f69SDimitry Andric // binary operator with an induction phi user.
15651f917f69SDimitry Andric BinaryOperator *B = dyn_cast<BinaryOperator>(Inst);
15661f917f69SDimitry Andric if (!B)
15671f917f69SDimitry Andric continue;
15681f917f69SDimitry Andric if (llvm::any_of(Inst->users(), [&](User *U) {
15691f917f69SDimitry Andric PHINode *Phi = dyn_cast<PHINode>(U);
15701f917f69SDimitry Andric if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
15711f917f69SDimitry Andric return true;
15721f917f69SDimitry Andric return false;
15731f917f69SDimitry Andric }))
15741f917f69SDimitry Andric continue;
15751f917f69SDimitry Andric if (B != ID.getInductionBinOp())
15761f917f69SDimitry Andric continue;
15771f917f69SDimitry Andric }
15781f917f69SDimitry Andric }
15791f917f69SDimitry Andric
1580cfca06d7SDimitry Andric // Okay, this instruction has a user outside of the current loop
1581cfca06d7SDimitry Andric // and varies predictably *inside* the loop. Evaluate the value it
1582cfca06d7SDimitry Andric // contains when the loop exits, if possible. We prefer to start with
1583cfca06d7SDimitry Andric // expressions which are true for all exits (so as to maximize
1584cfca06d7SDimitry Andric // expression reuse by the SCEVExpander), but resort to per-exit
1585cfca06d7SDimitry Andric // evaluation if that fails.
1586cfca06d7SDimitry Andric const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1587cfca06d7SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitValue) ||
1588cfca06d7SDimitry Andric !SE->isLoopInvariant(ExitValue, L) ||
15894b4fe385SDimitry Andric !Rewriter.isSafeToExpand(ExitValue)) {
1590cfca06d7SDimitry Andric // TODO: This should probably be sunk into SCEV in some way; maybe a
1591cfca06d7SDimitry Andric // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for
1592cfca06d7SDimitry Andric // most SCEV expressions and other recurrence types (e.g. shift
1593cfca06d7SDimitry Andric // recurrences). Is there existing code we can reuse?
1594cfca06d7SDimitry Andric const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1595cfca06d7SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount))
1596cfca06d7SDimitry Andric continue;
1597cfca06d7SDimitry Andric if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1598cfca06d7SDimitry Andric if (AddRec->getLoop() == L)
1599cfca06d7SDimitry Andric ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1600cfca06d7SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitValue) ||
1601cfca06d7SDimitry Andric !SE->isLoopInvariant(ExitValue, L) ||
16024b4fe385SDimitry Andric !Rewriter.isSafeToExpand(ExitValue))
1603cfca06d7SDimitry Andric continue;
1604cfca06d7SDimitry Andric }
1605cfca06d7SDimitry Andric
1606cfca06d7SDimitry Andric // Computing the value outside of the loop brings no benefit if it is
1607cfca06d7SDimitry Andric // definitely used inside the loop in a way which can not be optimized
1608cfca06d7SDimitry Andric // away. Avoid doing so unless we know we have a value which computes
1609cfca06d7SDimitry Andric // the ExitValue already. TODO: This should be merged into SCEV
1610cfca06d7SDimitry Andric // expander to leverage its knowledge of existing expressions.
1611cfca06d7SDimitry Andric if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1612cfca06d7SDimitry Andric !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1613cfca06d7SDimitry Andric continue;
1614cfca06d7SDimitry Andric
1615cfca06d7SDimitry Andric // Check if expansions of this SCEV would count as being high cost.
1616cfca06d7SDimitry Andric bool HighCost = Rewriter.isHighCostExpansion(
1617cfca06d7SDimitry Andric ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1618cfca06d7SDimitry Andric
1619cfca06d7SDimitry Andric // Note that we must not perform expansions until after
1620cfca06d7SDimitry Andric // we query *all* the costs, because if we perform temporary expansion
1621cfca06d7SDimitry Andric // inbetween, one that we might not intend to keep, said expansion
1622b1c73532SDimitry Andric // *may* affect cost calculation of the next SCEV's we'll query,
1623cfca06d7SDimitry Andric // and next SCEV may errneously get smaller cost.
1624cfca06d7SDimitry Andric
1625cfca06d7SDimitry Andric // Collect all the candidate PHINodes to be rewritten.
1626e3b55780SDimitry Andric Instruction *InsertPt =
1627e3b55780SDimitry Andric (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ?
1628e3b55780SDimitry Andric &*Inst->getParent()->getFirstInsertionPt() : Inst;
1629e3b55780SDimitry Andric RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost);
1630cfca06d7SDimitry Andric }
1631cfca06d7SDimitry Andric }
1632cfca06d7SDimitry Andric }
1633cfca06d7SDimitry Andric
1634c0981da4SDimitry Andric // TODO: evaluate whether it is beneficial to change how we calculate
1635c0981da4SDimitry Andric // high-cost: if we have SCEV 'A' which we know we will expand, should we
1636c0981da4SDimitry Andric // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1637c0981da4SDimitry Andric // potentially giving cost bonus to those other SCEV's?
1638cfca06d7SDimitry Andric
1639cfca06d7SDimitry Andric bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1640cfca06d7SDimitry Andric int NumReplaced = 0;
1641cfca06d7SDimitry Andric
1642cfca06d7SDimitry Andric // Transformation.
1643cfca06d7SDimitry Andric for (const RewritePhi &Phi : RewritePhiSet) {
1644cfca06d7SDimitry Andric PHINode *PN = Phi.PN;
1645cfca06d7SDimitry Andric
1646cfca06d7SDimitry Andric // Only do the rewrite when the ExitValue can be expanded cheaply.
1647cfca06d7SDimitry Andric // If LoopCanBeDel is true, rewrite exit value aggressively.
16481f917f69SDimitry Andric if ((ReplaceExitValue == OnlyCheapRepl ||
16491f917f69SDimitry Andric ReplaceExitValue == UnusedIndVarInLoop) &&
16501f917f69SDimitry Andric !LoopCanBeDel && Phi.HighCost)
1651cfca06d7SDimitry Andric continue;
1652c0981da4SDimitry Andric
1653c0981da4SDimitry Andric Value *ExitVal = Rewriter.expandCodeFor(
1654c0981da4SDimitry Andric Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
1655c0981da4SDimitry Andric
1656c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1657c0981da4SDimitry Andric << '\n'
1658c0981da4SDimitry Andric << " LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1659c0981da4SDimitry Andric
1660c0981da4SDimitry Andric #ifndef NDEBUG
1661c0981da4SDimitry Andric // If we reuse an instruction from a loop which is neither L nor one of
1662c0981da4SDimitry Andric // its containing loops, we end up breaking LCSSA form for this loop by
1663c0981da4SDimitry Andric // creating a new use of its instruction.
1664c0981da4SDimitry Andric if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1665c0981da4SDimitry Andric if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1666c0981da4SDimitry Andric if (EVL != L)
1667c0981da4SDimitry Andric assert(EVL->contains(L) && "LCSSA breach detected!");
1668c0981da4SDimitry Andric #endif
1669cfca06d7SDimitry Andric
1670cfca06d7SDimitry Andric NumReplaced++;
1671cfca06d7SDimitry Andric Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1672cfca06d7SDimitry Andric PN->setIncomingValue(Phi.Ith, ExitVal);
1673c0981da4SDimitry Andric // It's necessary to tell ScalarEvolution about this explicitly so that
1674c0981da4SDimitry Andric // it can walk the def-use list and forget all SCEVs, as it may not be
1675c0981da4SDimitry Andric // watching the PHI itself. Once the new exit value is in place, there
1676c0981da4SDimitry Andric // may not be a def-use connection between the loop and every instruction
1677c0981da4SDimitry Andric // which got a SCEVAddRecExpr for that loop.
1678c0981da4SDimitry Andric SE->forgetValue(PN);
1679cfca06d7SDimitry Andric
1680cfca06d7SDimitry Andric // If this instruction is dead now, delete it. Don't do it now to avoid
1681cfca06d7SDimitry Andric // invalidating iterators.
1682cfca06d7SDimitry Andric if (isInstructionTriviallyDead(Inst, TLI))
1683cfca06d7SDimitry Andric DeadInsts.push_back(Inst);
1684cfca06d7SDimitry Andric
1685cfca06d7SDimitry Andric // Replace PN with ExitVal if that is legal and does not break LCSSA.
1686cfca06d7SDimitry Andric if (PN->getNumIncomingValues() == 1 &&
1687cfca06d7SDimitry Andric LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1688cfca06d7SDimitry Andric PN->replaceAllUsesWith(ExitVal);
1689cfca06d7SDimitry Andric PN->eraseFromParent();
1690cfca06d7SDimitry Andric }
1691cfca06d7SDimitry Andric }
1692cfca06d7SDimitry Andric
1693cfca06d7SDimitry Andric // The insertion point instruction may have been deleted; clear it out
1694cfca06d7SDimitry Andric // so that the rewriter doesn't trip over it later.
1695cfca06d7SDimitry Andric Rewriter.clearInsertPoint();
1696cfca06d7SDimitry Andric return NumReplaced;
1697cfca06d7SDimitry Andric }
1698cfca06d7SDimitry Andric
1699cfca06d7SDimitry Andric /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1700cfca06d7SDimitry Andric /// \p OrigLoop.
setProfileInfoAfterUnrolling(Loop * OrigLoop,Loop * UnrolledLoop,Loop * RemainderLoop,uint64_t UF)1701cfca06d7SDimitry Andric void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1702cfca06d7SDimitry Andric Loop *RemainderLoop, uint64_t UF) {
1703cfca06d7SDimitry Andric assert(UF > 0 && "Zero unrolled factor is not supported");
1704cfca06d7SDimitry Andric assert(UnrolledLoop != RemainderLoop &&
1705cfca06d7SDimitry Andric "Unrolled and Remainder loops are expected to distinct");
1706cfca06d7SDimitry Andric
1707cfca06d7SDimitry Andric // Get number of iterations in the original scalar loop.
1708cfca06d7SDimitry Andric unsigned OrigLoopInvocationWeight = 0;
1709e3b55780SDimitry Andric std::optional<unsigned> OrigAverageTripCount =
1710cfca06d7SDimitry Andric getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1711cfca06d7SDimitry Andric if (!OrigAverageTripCount)
1712cfca06d7SDimitry Andric return;
1713cfca06d7SDimitry Andric
1714cfca06d7SDimitry Andric // Calculate number of iterations in unrolled loop.
1715cfca06d7SDimitry Andric unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1716cfca06d7SDimitry Andric // Calculate number of iterations for remainder loop.
1717cfca06d7SDimitry Andric unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1718cfca06d7SDimitry Andric
1719cfca06d7SDimitry Andric setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1720cfca06d7SDimitry Andric OrigLoopInvocationWeight);
1721cfca06d7SDimitry Andric setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1722cfca06d7SDimitry Andric OrigLoopInvocationWeight);
1723cfca06d7SDimitry Andric }
1724cfca06d7SDimitry Andric
1725cfca06d7SDimitry Andric /// Utility that implements appending of loops onto a worklist.
1726cfca06d7SDimitry Andric /// Loops are added in preorder (analogous for reverse postorder for trees),
1727cfca06d7SDimitry Andric /// and the worklist is processed LIFO.
1728cfca06d7SDimitry Andric template <typename RangeT>
appendReversedLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1729cfca06d7SDimitry Andric void llvm::appendReversedLoopsToWorklist(
1730cfca06d7SDimitry Andric RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1731cfca06d7SDimitry Andric // We use an internal worklist to build up the preorder traversal without
1732cfca06d7SDimitry Andric // recursion.
1733cfca06d7SDimitry Andric SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1734cfca06d7SDimitry Andric
1735cfca06d7SDimitry Andric // We walk the initial sequence of loops in reverse because we generally want
1736cfca06d7SDimitry Andric // to visit defs before uses and the worklist is LIFO.
1737cfca06d7SDimitry Andric for (Loop *RootL : Loops) {
1738cfca06d7SDimitry Andric assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1739cfca06d7SDimitry Andric assert(PreOrderWorklist.empty() &&
1740cfca06d7SDimitry Andric "Must start with an empty preorder walk worklist.");
1741cfca06d7SDimitry Andric PreOrderWorklist.push_back(RootL);
1742cfca06d7SDimitry Andric do {
1743cfca06d7SDimitry Andric Loop *L = PreOrderWorklist.pop_back_val();
1744cfca06d7SDimitry Andric PreOrderWorklist.append(L->begin(), L->end());
1745cfca06d7SDimitry Andric PreOrderLoops.push_back(L);
1746cfca06d7SDimitry Andric } while (!PreOrderWorklist.empty());
1747cfca06d7SDimitry Andric
1748cfca06d7SDimitry Andric Worklist.insert(std::move(PreOrderLoops));
1749cfca06d7SDimitry Andric PreOrderLoops.clear();
1750cfca06d7SDimitry Andric }
1751cfca06d7SDimitry Andric }
1752cfca06d7SDimitry Andric
1753cfca06d7SDimitry Andric template <typename RangeT>
appendLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1754cfca06d7SDimitry Andric void llvm::appendLoopsToWorklist(RangeT &&Loops,
1755cfca06d7SDimitry Andric SmallPriorityWorklist<Loop *, 4> &Worklist) {
1756cfca06d7SDimitry Andric appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1757cfca06d7SDimitry Andric }
1758cfca06d7SDimitry Andric
1759cfca06d7SDimitry Andric template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1760cfca06d7SDimitry Andric ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1761cfca06d7SDimitry Andric
1762cfca06d7SDimitry Andric template void
1763cfca06d7SDimitry Andric llvm::appendLoopsToWorklist<Loop &>(Loop &L,
1764cfca06d7SDimitry Andric SmallPriorityWorklist<Loop *, 4> &Worklist);
1765cfca06d7SDimitry Andric
appendLoopsToWorklist(LoopInfo & LI,SmallPriorityWorklist<Loop *,4> & Worklist)1766cfca06d7SDimitry Andric void llvm::appendLoopsToWorklist(LoopInfo &LI,
1767cfca06d7SDimitry Andric SmallPriorityWorklist<Loop *, 4> &Worklist) {
1768cfca06d7SDimitry Andric appendReversedLoopsToWorklist(LI, Worklist);
1769cfca06d7SDimitry Andric }
1770cfca06d7SDimitry Andric
cloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)1771cfca06d7SDimitry Andric Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
1772cfca06d7SDimitry Andric LoopInfo *LI, LPPassManager *LPM) {
1773cfca06d7SDimitry Andric Loop &New = *LI->AllocateLoop();
1774cfca06d7SDimitry Andric if (PL)
1775cfca06d7SDimitry Andric PL->addChildLoop(&New);
1776cfca06d7SDimitry Andric else
1777cfca06d7SDimitry Andric LI->addTopLevelLoop(&New);
1778cfca06d7SDimitry Andric
1779cfca06d7SDimitry Andric if (LPM)
1780cfca06d7SDimitry Andric LPM->addLoop(New);
1781cfca06d7SDimitry Andric
1782cfca06d7SDimitry Andric // Add all of the blocks in L to the new loop.
1783846a2208SDimitry Andric for (BasicBlock *BB : L->blocks())
1784846a2208SDimitry Andric if (LI->getLoopFor(BB) == L)
1785846a2208SDimitry Andric New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
1786cfca06d7SDimitry Andric
1787cfca06d7SDimitry Andric // Add all of the subloops to the new loop.
1788cfca06d7SDimitry Andric for (Loop *I : *L)
1789cfca06d7SDimitry Andric cloneLoop(I, &New, VM, LI, LPM);
1790cfca06d7SDimitry Andric
1791cfca06d7SDimitry Andric return &New;
1792cfca06d7SDimitry Andric }
1793cfca06d7SDimitry Andric
1794cfca06d7SDimitry Andric /// IR Values for the lower and upper bounds of a pointer evolution. We
1795cfca06d7SDimitry Andric /// need to use value-handles because SCEV expansion can invalidate previously
1796cfca06d7SDimitry Andric /// expanded values. Thus expansion of a pointer can invalidate the bounds for
1797cfca06d7SDimitry Andric /// a previous one.
1798cfca06d7SDimitry Andric struct PointerBounds {
1799cfca06d7SDimitry Andric TrackingVH<Value> Start;
1800cfca06d7SDimitry Andric TrackingVH<Value> End;
1801b1c73532SDimitry Andric Value *StrideToCheck;
1802cfca06d7SDimitry Andric };
1803cfca06d7SDimitry Andric
1804cfca06d7SDimitry Andric /// Expand code for the lower and upper bound of the pointer group \p CG
1805cfca06d7SDimitry Andric /// in \p TheLoop. \return the values for the bounds.
expandBounds(const RuntimeCheckingPtrGroup * CG,Loop * TheLoop,Instruction * Loc,SCEVExpander & Exp,bool HoistRuntimeChecks)1806cfca06d7SDimitry Andric static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
1807cfca06d7SDimitry Andric Loop *TheLoop, Instruction *Loc,
1808b1c73532SDimitry Andric SCEVExpander &Exp, bool HoistRuntimeChecks) {
1809cfca06d7SDimitry Andric LLVMContext &Ctx = Loc->getContext();
1810b1c73532SDimitry Andric Type *PtrArithTy = PointerType::get(Ctx, CG->AddressSpace);
1811cfca06d7SDimitry Andric
1812cfca06d7SDimitry Andric Value *Start = nullptr, *End = nullptr;
1813cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1814b1c73532SDimitry Andric const SCEV *Low = CG->Low, *High = CG->High, *Stride = nullptr;
1815b1c73532SDimitry Andric
1816b1c73532SDimitry Andric // If the Low and High values are themselves loop-variant, then we may want
1817b1c73532SDimitry Andric // to expand the range to include those covered by the outer loop as well.
1818b1c73532SDimitry Andric // There is a trade-off here with the advantage being that creating checks
1819b1c73532SDimitry Andric // using the expanded range permits the runtime memory checks to be hoisted
1820b1c73532SDimitry Andric // out of the outer loop. This reduces the cost of entering the inner loop,
1821b1c73532SDimitry Andric // which can be significant for low trip counts. The disadvantage is that
1822b1c73532SDimitry Andric // there is a chance we may now never enter the vectorized inner loop,
1823b1c73532SDimitry Andric // whereas using a restricted range check could have allowed us to enter at
1824b1c73532SDimitry Andric // least once. This is why the behaviour is not currently the default and is
1825b1c73532SDimitry Andric // controlled by the parameter 'HoistRuntimeChecks'.
1826b1c73532SDimitry Andric if (HoistRuntimeChecks && TheLoop->getParentLoop() &&
1827b1c73532SDimitry Andric isa<SCEVAddRecExpr>(High) && isa<SCEVAddRecExpr>(Low)) {
1828b1c73532SDimitry Andric auto *HighAR = cast<SCEVAddRecExpr>(High);
1829b1c73532SDimitry Andric auto *LowAR = cast<SCEVAddRecExpr>(Low);
1830b1c73532SDimitry Andric const Loop *OuterLoop = TheLoop->getParentLoop();
1831ac9a064cSDimitry Andric ScalarEvolution &SE = *Exp.getSE();
1832ac9a064cSDimitry Andric const SCEV *Recur = LowAR->getStepRecurrence(SE);
1833ac9a064cSDimitry Andric if (Recur == HighAR->getStepRecurrence(SE) &&
1834b1c73532SDimitry Andric HighAR->getLoop() == OuterLoop && LowAR->getLoop() == OuterLoop) {
1835b1c73532SDimitry Andric BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1836ac9a064cSDimitry Andric const SCEV *OuterExitCount = SE.getExitCount(OuterLoop, OuterLoopLatch);
1837b1c73532SDimitry Andric if (!isa<SCEVCouldNotCompute>(OuterExitCount) &&
1838b1c73532SDimitry Andric OuterExitCount->getType()->isIntegerTy()) {
1839ac9a064cSDimitry Andric const SCEV *NewHigh =
1840ac9a064cSDimitry Andric cast<SCEVAddRecExpr>(High)->evaluateAtIteration(OuterExitCount, SE);
1841b1c73532SDimitry Andric if (!isa<SCEVCouldNotCompute>(NewHigh)) {
1842b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: Expanded RT check for range to include "
1843b1c73532SDimitry Andric "outer loop in order to permit hoisting\n");
1844b1c73532SDimitry Andric High = NewHigh;
1845b1c73532SDimitry Andric Low = cast<SCEVAddRecExpr>(Low)->getStart();
1846b1c73532SDimitry Andric // If there is a possibility that the stride is negative then we have
1847b1c73532SDimitry Andric // to generate extra checks to ensure the stride is positive.
1848ac9a064cSDimitry Andric if (!SE.isKnownNonNegative(
1849ac9a064cSDimitry Andric SE.applyLoopGuards(Recur, HighAR->getLoop()))) {
1850b1c73532SDimitry Andric Stride = Recur;
1851b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "LAA: ... but need to check stride is "
1852b1c73532SDimitry Andric "positive: "
1853b1c73532SDimitry Andric << *Stride << '\n');
1854b1c73532SDimitry Andric }
1855b1c73532SDimitry Andric }
1856b1c73532SDimitry Andric }
1857b1c73532SDimitry Andric }
1858b1c73532SDimitry Andric }
1859b1c73532SDimitry Andric
1860b1c73532SDimitry Andric Start = Exp.expandCodeFor(Low, PtrArithTy, Loc);
1861b1c73532SDimitry Andric End = Exp.expandCodeFor(High, PtrArithTy, Loc);
1862145449b1SDimitry Andric if (CG->NeedsFreeze) {
1863145449b1SDimitry Andric IRBuilder<> Builder(Loc);
1864145449b1SDimitry Andric Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
1865145449b1SDimitry Andric End = Builder.CreateFreeze(End, End->getName() + ".fr");
1866145449b1SDimitry Andric }
1867b1c73532SDimitry Andric Value *StrideVal =
1868b1c73532SDimitry Andric Stride ? Exp.expandCodeFor(Stride, Stride->getType(), Loc) : nullptr;
1869b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "Start: " << *Low << " End: " << *High << "\n");
1870b1c73532SDimitry Andric return {Start, End, StrideVal};
1871cfca06d7SDimitry Andric }
1872cfca06d7SDimitry Andric
1873cfca06d7SDimitry Andric /// Turns a collection of checks into a collection of expanded upper and
1874cfca06d7SDimitry Andric /// lower bounds for both pointers in the check.
1875cfca06d7SDimitry Andric static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
expandBounds(const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,Loop * L,Instruction * Loc,SCEVExpander & Exp,bool HoistRuntimeChecks)1876cfca06d7SDimitry Andric expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
1877b1c73532SDimitry Andric Instruction *Loc, SCEVExpander &Exp, bool HoistRuntimeChecks) {
1878cfca06d7SDimitry Andric SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1879cfca06d7SDimitry Andric
1880cfca06d7SDimitry Andric // Here we're relying on the SCEV Expander's cache to only emit code for the
1881cfca06d7SDimitry Andric // same bounds once.
1882cfca06d7SDimitry Andric transform(PointerChecks, std::back_inserter(ChecksWithBounds),
1883cfca06d7SDimitry Andric [&](const RuntimePointerCheck &Check) {
1884b1c73532SDimitry Andric PointerBounds First = expandBounds(Check.first, L, Loc, Exp,
1885b1c73532SDimitry Andric HoistRuntimeChecks),
1886b1c73532SDimitry Andric Second = expandBounds(Check.second, L, Loc, Exp,
1887b1c73532SDimitry Andric HoistRuntimeChecks);
1888cfca06d7SDimitry Andric return std::make_pair(First, Second);
1889cfca06d7SDimitry Andric });
1890cfca06d7SDimitry Andric
1891cfca06d7SDimitry Andric return ChecksWithBounds;
1892cfca06d7SDimitry Andric }
1893cfca06d7SDimitry Andric
addRuntimeChecks(Instruction * Loc,Loop * TheLoop,const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,SCEVExpander & Exp,bool HoistRuntimeChecks)1894c0981da4SDimitry Andric Value *llvm::addRuntimeChecks(
1895cfca06d7SDimitry Andric Instruction *Loc, Loop *TheLoop,
1896cfca06d7SDimitry Andric const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
1897b1c73532SDimitry Andric SCEVExpander &Exp, bool HoistRuntimeChecks) {
1898cfca06d7SDimitry Andric // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
1899cfca06d7SDimitry Andric // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
1900b1c73532SDimitry Andric auto ExpandedChecks =
1901b1c73532SDimitry Andric expandBounds(PointerChecks, TheLoop, Loc, Exp, HoistRuntimeChecks);
1902cfca06d7SDimitry Andric
1903cfca06d7SDimitry Andric LLVMContext &Ctx = Loc->getContext();
19046f8fc217SDimitry Andric IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1905ac9a064cSDimitry Andric Loc->getDataLayout());
19066f8fc217SDimitry Andric ChkBuilder.SetInsertPoint(Loc);
1907cfca06d7SDimitry Andric // Our instructions might fold to a constant.
1908cfca06d7SDimitry Andric Value *MemoryRuntimeCheck = nullptr;
1909cfca06d7SDimitry Andric
1910ac9a064cSDimitry Andric for (const auto &[A, B] : ExpandedChecks) {
1911cfca06d7SDimitry Andric // Check if two pointers (A and B) conflict where conflict is computed as:
1912cfca06d7SDimitry Andric // start(A) <= end(B) && start(B) <= end(A)
1913cfca06d7SDimitry Andric
1914b1c73532SDimitry Andric assert((A.Start->getType()->getPointerAddressSpace() ==
1915b1c73532SDimitry Andric B.End->getType()->getPointerAddressSpace()) &&
1916b1c73532SDimitry Andric (B.Start->getType()->getPointerAddressSpace() ==
1917b1c73532SDimitry Andric A.End->getType()->getPointerAddressSpace()) &&
1918cfca06d7SDimitry Andric "Trying to bounds check pointers with different address spaces");
1919cfca06d7SDimitry Andric
1920cfca06d7SDimitry Andric // [A|B].Start points to the first accessed byte under base [A|B].
1921cfca06d7SDimitry Andric // [A|B].End points to the last accessed byte, plus one.
1922cfca06d7SDimitry Andric // There is no conflict when the intervals are disjoint:
1923cfca06d7SDimitry Andric // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1924cfca06d7SDimitry Andric //
1925cfca06d7SDimitry Andric // bound0 = (B.Start < A.End)
1926cfca06d7SDimitry Andric // bound1 = (A.Start < B.End)
1927cfca06d7SDimitry Andric // IsConflict = bound0 & bound1
1928b1c73532SDimitry Andric Value *Cmp0 = ChkBuilder.CreateICmpULT(A.Start, B.End, "bound0");
1929b1c73532SDimitry Andric Value *Cmp1 = ChkBuilder.CreateICmpULT(B.Start, A.End, "bound1");
1930cfca06d7SDimitry Andric Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1931b1c73532SDimitry Andric if (A.StrideToCheck) {
1932b1c73532SDimitry Andric Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
1933b1c73532SDimitry Andric A.StrideToCheck, ConstantInt::get(A.StrideToCheck->getType(), 0),
1934b1c73532SDimitry Andric "stride.check");
1935b1c73532SDimitry Andric IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
1936b1c73532SDimitry Andric }
1937b1c73532SDimitry Andric if (B.StrideToCheck) {
1938b1c73532SDimitry Andric Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
1939b1c73532SDimitry Andric B.StrideToCheck, ConstantInt::get(B.StrideToCheck->getType(), 0),
1940b1c73532SDimitry Andric "stride.check");
1941b1c73532SDimitry Andric IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
1942b1c73532SDimitry Andric }
1943cfca06d7SDimitry Andric if (MemoryRuntimeCheck) {
1944cfca06d7SDimitry Andric IsConflict =
1945cfca06d7SDimitry Andric ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1946cfca06d7SDimitry Andric }
1947cfca06d7SDimitry Andric MemoryRuntimeCheck = IsConflict;
1948cfca06d7SDimitry Andric }
1949cfca06d7SDimitry Andric
1950c0981da4SDimitry Andric return MemoryRuntimeCheck;
1951cfca06d7SDimitry Andric }
1952344a3780SDimitry Andric
addDiffRuntimeChecks(Instruction * Loc,ArrayRef<PointerDiffInfo> Checks,SCEVExpander & Expander,function_ref<Value * (IRBuilderBase &,unsigned)> GetVF,unsigned IC)1953145449b1SDimitry Andric Value *llvm::addDiffRuntimeChecks(
1954e3b55780SDimitry Andric Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
1955145449b1SDimitry Andric function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
1956145449b1SDimitry Andric
1957145449b1SDimitry Andric LLVMContext &Ctx = Loc->getContext();
1958145449b1SDimitry Andric IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1959ac9a064cSDimitry Andric Loc->getDataLayout());
1960145449b1SDimitry Andric ChkBuilder.SetInsertPoint(Loc);
1961145449b1SDimitry Andric // Our instructions might fold to a constant.
1962145449b1SDimitry Andric Value *MemoryRuntimeCheck = nullptr;
1963145449b1SDimitry Andric
1964b1c73532SDimitry Andric auto &SE = *Expander.getSE();
1965b1c73532SDimitry Andric // Map to keep track of created compares, The key is the pair of operands for
1966b1c73532SDimitry Andric // the compare, to allow detecting and re-using redundant compares.
1967b1c73532SDimitry Andric DenseMap<std::pair<Value *, Value *>, Value *> SeenCompares;
1968ac9a064cSDimitry Andric for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
1969ac9a064cSDimitry Andric Type *Ty = SinkStart->getType();
1970145449b1SDimitry Andric // Compute VF * IC * AccessSize.
1971145449b1SDimitry Andric auto *VFTimesUFTimesSize =
1972145449b1SDimitry Andric ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
1973ac9a064cSDimitry Andric ConstantInt::get(Ty, IC * AccessSize));
1974ac9a064cSDimitry Andric Value *Diff =
1975ac9a064cSDimitry Andric Expander.expandCodeFor(SE.getMinusSCEV(SinkStart, SrcStart), Ty, Loc);
1976145449b1SDimitry Andric
1977b1c73532SDimitry Andric // Check if the same compare has already been created earlier. In that case,
1978b1c73532SDimitry Andric // there is no need to check it again.
1979b1c73532SDimitry Andric Value *IsConflict = SeenCompares.lookup({Diff, VFTimesUFTimesSize});
1980b1c73532SDimitry Andric if (IsConflict)
1981b1c73532SDimitry Andric continue;
1982b1c73532SDimitry Andric
1983b1c73532SDimitry Andric IsConflict =
1984b1c73532SDimitry Andric ChkBuilder.CreateICmpULT(Diff, VFTimesUFTimesSize, "diff.check");
1985b1c73532SDimitry Andric SeenCompares.insert({{Diff, VFTimesUFTimesSize}, IsConflict});
1986ac9a064cSDimitry Andric if (NeedsFreeze)
1987b1c73532SDimitry Andric IsConflict =
1988b1c73532SDimitry Andric ChkBuilder.CreateFreeze(IsConflict, IsConflict->getName() + ".fr");
1989145449b1SDimitry Andric if (MemoryRuntimeCheck) {
1990145449b1SDimitry Andric IsConflict =
1991145449b1SDimitry Andric ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1992145449b1SDimitry Andric }
1993145449b1SDimitry Andric MemoryRuntimeCheck = IsConflict;
1994145449b1SDimitry Andric }
1995145449b1SDimitry Andric
1996145449b1SDimitry Andric return MemoryRuntimeCheck;
1997145449b1SDimitry Andric }
1998145449b1SDimitry Andric
1999e3b55780SDimitry Andric std::optional<IVConditionInfo>
hasPartialIVCondition(const Loop & L,unsigned MSSAThreshold,const MemorySSA & MSSA,AAResults & AA)2000e3b55780SDimitry Andric llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
2001e3b55780SDimitry Andric const MemorySSA &MSSA, AAResults &AA) {
2002344a3780SDimitry Andric auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
2003344a3780SDimitry Andric if (!TI || !TI->isConditional())
2004344a3780SDimitry Andric return {};
2005344a3780SDimitry Andric
2006ac9a064cSDimitry Andric auto *CondI = dyn_cast<Instruction>(TI->getCondition());
2007344a3780SDimitry Andric // The case with the condition outside the loop should already be handled
2008344a3780SDimitry Andric // earlier.
2009ac9a064cSDimitry Andric // Allow CmpInst and TruncInsts as they may be users of load instructions
2010ac9a064cSDimitry Andric // and have potential for partial unswitching
2011ac9a064cSDimitry Andric if (!CondI || !isa<CmpInst, TruncInst>(CondI) || !L.contains(CondI))
2012344a3780SDimitry Andric return {};
2013344a3780SDimitry Andric
2014344a3780SDimitry Andric SmallVector<Instruction *> InstToDuplicate;
2015344a3780SDimitry Andric InstToDuplicate.push_back(CondI);
2016344a3780SDimitry Andric
2017344a3780SDimitry Andric SmallVector<Value *, 4> WorkList;
2018344a3780SDimitry Andric WorkList.append(CondI->op_begin(), CondI->op_end());
2019344a3780SDimitry Andric
2020344a3780SDimitry Andric SmallVector<MemoryAccess *, 4> AccessesToCheck;
2021344a3780SDimitry Andric SmallVector<MemoryLocation, 4> AccessedLocs;
2022344a3780SDimitry Andric while (!WorkList.empty()) {
2023344a3780SDimitry Andric Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
2024344a3780SDimitry Andric if (!I || !L.contains(I))
2025344a3780SDimitry Andric continue;
2026344a3780SDimitry Andric
2027344a3780SDimitry Andric // TODO: support additional instructions.
2028344a3780SDimitry Andric if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
2029344a3780SDimitry Andric return {};
2030344a3780SDimitry Andric
2031344a3780SDimitry Andric // Do not duplicate volatile and atomic loads.
2032344a3780SDimitry Andric if (auto *LI = dyn_cast<LoadInst>(I))
2033344a3780SDimitry Andric if (LI->isVolatile() || LI->isAtomic())
2034344a3780SDimitry Andric return {};
2035344a3780SDimitry Andric
2036344a3780SDimitry Andric InstToDuplicate.push_back(I);
2037344a3780SDimitry Andric if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
2038344a3780SDimitry Andric if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
2039344a3780SDimitry Andric // Queue the defining access to check for alias checks.
2040344a3780SDimitry Andric AccessesToCheck.push_back(MemUse->getDefiningAccess());
2041344a3780SDimitry Andric AccessedLocs.push_back(MemoryLocation::get(I));
2042344a3780SDimitry Andric } else {
2043344a3780SDimitry Andric // MemoryDefs may clobber the location or may be atomic memory
2044344a3780SDimitry Andric // operations. Bail out.
2045344a3780SDimitry Andric return {};
2046344a3780SDimitry Andric }
2047344a3780SDimitry Andric }
2048344a3780SDimitry Andric WorkList.append(I->op_begin(), I->op_end());
2049344a3780SDimitry Andric }
2050344a3780SDimitry Andric
2051344a3780SDimitry Andric if (InstToDuplicate.empty())
2052344a3780SDimitry Andric return {};
2053344a3780SDimitry Andric
2054344a3780SDimitry Andric SmallVector<BasicBlock *, 4> ExitingBlocks;
2055344a3780SDimitry Andric L.getExitingBlocks(ExitingBlocks);
2056344a3780SDimitry Andric auto HasNoClobbersOnPath =
2057344a3780SDimitry Andric [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
2058344a3780SDimitry Andric MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
2059344a3780SDimitry Andric SmallVector<MemoryAccess *, 4> AccessesToCheck)
2060e3b55780SDimitry Andric -> std::optional<IVConditionInfo> {
2061344a3780SDimitry Andric IVConditionInfo Info;
2062344a3780SDimitry Andric // First, collect all blocks in the loop that are on a patch from Succ
2063344a3780SDimitry Andric // to the header.
2064344a3780SDimitry Andric SmallVector<BasicBlock *, 4> WorkList;
2065344a3780SDimitry Andric WorkList.push_back(Succ);
2066344a3780SDimitry Andric WorkList.push_back(Header);
2067344a3780SDimitry Andric SmallPtrSet<BasicBlock *, 4> Seen;
2068344a3780SDimitry Andric Seen.insert(Header);
2069344a3780SDimitry Andric Info.PathIsNoop &=
2070344a3780SDimitry Andric all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2071344a3780SDimitry Andric
2072344a3780SDimitry Andric while (!WorkList.empty()) {
2073344a3780SDimitry Andric BasicBlock *Current = WorkList.pop_back_val();
2074344a3780SDimitry Andric if (!L.contains(Current))
2075344a3780SDimitry Andric continue;
2076344a3780SDimitry Andric const auto &SeenIns = Seen.insert(Current);
2077344a3780SDimitry Andric if (!SeenIns.second)
2078344a3780SDimitry Andric continue;
2079344a3780SDimitry Andric
2080344a3780SDimitry Andric Info.PathIsNoop &= all_of(
2081344a3780SDimitry Andric *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2082344a3780SDimitry Andric WorkList.append(succ_begin(Current), succ_end(Current));
2083344a3780SDimitry Andric }
2084344a3780SDimitry Andric
2085344a3780SDimitry Andric // Require at least 2 blocks on a path through the loop. This skips
2086344a3780SDimitry Andric // paths that directly exit the loop.
2087344a3780SDimitry Andric if (Seen.size() < 2)
2088344a3780SDimitry Andric return {};
2089344a3780SDimitry Andric
2090344a3780SDimitry Andric // Next, check if there are any MemoryDefs that are on the path through
2091344a3780SDimitry Andric // the loop (in the Seen set) and they may-alias any of the locations in
2092344a3780SDimitry Andric // AccessedLocs. If that is the case, they may modify the condition and
2093344a3780SDimitry Andric // partial unswitching is not possible.
2094344a3780SDimitry Andric SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
2095344a3780SDimitry Andric while (!AccessesToCheck.empty()) {
2096344a3780SDimitry Andric MemoryAccess *Current = AccessesToCheck.pop_back_val();
2097344a3780SDimitry Andric auto SeenI = SeenAccesses.insert(Current);
2098344a3780SDimitry Andric if (!SeenI.second || !Seen.contains(Current->getBlock()))
2099344a3780SDimitry Andric continue;
2100344a3780SDimitry Andric
2101344a3780SDimitry Andric // Bail out if exceeded the threshold.
2102344a3780SDimitry Andric if (SeenAccesses.size() >= MSSAThreshold)
2103344a3780SDimitry Andric return {};
2104344a3780SDimitry Andric
2105344a3780SDimitry Andric // MemoryUse are read-only accesses.
2106344a3780SDimitry Andric if (isa<MemoryUse>(Current))
2107344a3780SDimitry Andric continue;
2108344a3780SDimitry Andric
2109344a3780SDimitry Andric // For a MemoryDef, check if is aliases any of the location feeding
2110344a3780SDimitry Andric // the original condition.
2111344a3780SDimitry Andric if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
2112344a3780SDimitry Andric if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
2113344a3780SDimitry Andric return isModSet(
2114344a3780SDimitry Andric AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
2115344a3780SDimitry Andric }))
2116344a3780SDimitry Andric return {};
2117344a3780SDimitry Andric }
2118344a3780SDimitry Andric
2119344a3780SDimitry Andric for (Use &U : Current->uses())
2120344a3780SDimitry Andric AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
2121344a3780SDimitry Andric }
2122344a3780SDimitry Andric
2123344a3780SDimitry Andric // We could also allow loops with known trip counts without mustprogress,
2124344a3780SDimitry Andric // but ScalarEvolution may not be available.
2125344a3780SDimitry Andric Info.PathIsNoop &= isMustProgress(&L);
2126344a3780SDimitry Andric
2127344a3780SDimitry Andric // If the path is considered a no-op so far, check if it reaches a
2128344a3780SDimitry Andric // single exit block without any phis. This ensures no values from the
2129344a3780SDimitry Andric // loop are used outside of the loop.
2130344a3780SDimitry Andric if (Info.PathIsNoop) {
2131344a3780SDimitry Andric for (auto *Exiting : ExitingBlocks) {
2132344a3780SDimitry Andric if (!Seen.contains(Exiting))
2133344a3780SDimitry Andric continue;
2134344a3780SDimitry Andric for (auto *Succ : successors(Exiting)) {
2135344a3780SDimitry Andric if (L.contains(Succ))
2136344a3780SDimitry Andric continue;
2137344a3780SDimitry Andric
2138e3b55780SDimitry Andric Info.PathIsNoop &= Succ->phis().empty() &&
2139344a3780SDimitry Andric (!Info.ExitForPath || Info.ExitForPath == Succ);
2140344a3780SDimitry Andric if (!Info.PathIsNoop)
2141344a3780SDimitry Andric break;
2142344a3780SDimitry Andric assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
2143344a3780SDimitry Andric "cannot have multiple exit blocks");
2144344a3780SDimitry Andric Info.ExitForPath = Succ;
2145344a3780SDimitry Andric }
2146344a3780SDimitry Andric }
2147344a3780SDimitry Andric }
2148344a3780SDimitry Andric if (!Info.ExitForPath)
2149344a3780SDimitry Andric Info.PathIsNoop = false;
2150344a3780SDimitry Andric
2151344a3780SDimitry Andric Info.InstToDuplicate = InstToDuplicate;
2152344a3780SDimitry Andric return Info;
2153344a3780SDimitry Andric };
2154344a3780SDimitry Andric
2155344a3780SDimitry Andric // If we branch to the same successor, partial unswitching will not be
2156344a3780SDimitry Andric // beneficial.
2157344a3780SDimitry Andric if (TI->getSuccessor(0) == TI->getSuccessor(1))
2158344a3780SDimitry Andric return {};
2159344a3780SDimitry Andric
2160344a3780SDimitry Andric if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
2161344a3780SDimitry Andric AccessesToCheck)) {
2162344a3780SDimitry Andric Info->KnownValue = ConstantInt::getTrue(TI->getContext());
2163344a3780SDimitry Andric return Info;
2164344a3780SDimitry Andric }
2165344a3780SDimitry Andric if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
2166344a3780SDimitry Andric AccessesToCheck)) {
2167344a3780SDimitry Andric Info->KnownValue = ConstantInt::getFalse(TI->getContext());
2168344a3780SDimitry Andric return Info;
2169344a3780SDimitry Andric }
2170344a3780SDimitry Andric
2171344a3780SDimitry Andric return {};
2172344a3780SDimitry Andric }
2173