LLVM 20.0.0git
LoopVersioning.cpp
Go to the documentation of this file.
1//===- LoopVersioning.cpp - Utility to version a loop ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a utility class to perform loop versioning. The versioned
10// loop speculates that otherwise may-aliasing memory accesses don't overlap and
11// emits checks to prove this.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/ArrayRef.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/PassManager.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "loop-versioning"
35
36static cl::opt<bool>
37 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
39 cl::desc("Add no-alias annotation for instructions that "
40 "are disambiguated by memchecks"));
41
44 LoopInfo *LI, DominatorTree *DT,
46 : VersionedLoop(L), AliasChecks(Checks), Preds(LAI.getPSE().getPredicate()),
47 LAI(LAI), LI(LI), DT(DT), SE(SE) {}
48
50 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
51 assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
52 assert(VersionedLoop->isLoopSimplifyForm() &&
53 "Loop is not in loop-simplify form");
54
55 Value *MemRuntimeCheck;
56 Value *SCEVRuntimeCheck;
57 Value *RuntimeCheck = nullptr;
58
59 // Add the memcheck in the original preheader (this is empty initially).
60 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
61 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
62
63 SCEVExpander Exp2(*RtPtrChecking.getSE(),
64 VersionedLoop->getHeader()->getDataLayout(),
65 "induction");
66 MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
67 VersionedLoop, AliasChecks, Exp2);
68
69 SCEVExpander Exp(*SE, RuntimeCheckBB->getDataLayout(),
70 "scev.check");
71 SCEVRuntimeCheck =
72 Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
73
75 RuntimeCheckBB->getContext(),
76 InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
77 if (MemRuntimeCheck && SCEVRuntimeCheck) {
78 Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
79 RuntimeCheck =
80 Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
81 } else
82 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
83
84 assert(RuntimeCheck && "called even though we don't need "
85 "any runtime checks");
86
87 // Rename the block to make the IR more readable.
88 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
89 ".lver.check");
90
91 // Create empty preheader for the loop (and after cloning for the
92 // non-versioned loop).
93 BasicBlock *PH =
94 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
95 nullptr, VersionedLoop->getHeader()->getName() + ".ph");
96
97 // Clone the loop including the preheader.
98 //
99 // FIXME: This does not currently preserve SimplifyLoop because the exit
100 // block is a join between the two loops.
101 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
102 NonVersionedLoop =
103 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
104 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
105 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
106
107 // Insert the conditional branch based on the result of the memchecks.
108 Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
109 Builder.SetInsertPoint(OrigTerm);
110 Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
111 VersionedLoop->getLoopPreheader());
112 OrigTerm->eraseFromParent();
113
114 // The loops merge in the original exit block. This is now dominated by the
115 // memchecking block.
116 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
117
118 // Adds the necessary PHI nodes for the versioned loops based on the
119 // loop-defined values used outside of the loop.
120 addPHINodes(DefsUsedOutside);
121 formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
122 formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
123 assert(NonVersionedLoop->isLoopSimplifyForm() &&
124 VersionedLoop->isLoopSimplifyForm() &&
125 "The versioned loops should be in simplify form.");
126}
127
128void LoopVersioning::addPHINodes(
129 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
130 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
131 assert(PHIBlock && "No single successor to loop exit block");
132 PHINode *PN;
133
134 // First add a single-operand PHI for each DefsUsedOutside if one does not
135 // exists yet.
136 for (auto *Inst : DefsUsedOutside) {
137 // See if we have a single-operand PHI with the value defined by the
138 // original loop.
139 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
140 if (PN->getIncomingValue(0) == Inst) {
141 SE->forgetLcssaPhiWithNewPredecessor(VersionedLoop, PN);
142 break;
143 }
144 }
145 // If not create it.
146 if (!PN) {
147 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");
148 PN->insertBefore(PHIBlock->begin());
149 SmallVector<User*, 8> UsersToUpdate;
150 for (User *U : Inst->users())
151 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
152 UsersToUpdate.push_back(U);
153 for (User *U : UsersToUpdate)
154 U->replaceUsesOfWith(Inst, PN);
155 PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
156 }
157 }
158
159 // Then for each PHI add the operand for the edge from the cloned loop.
160 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
161 assert(PN->getNumOperands() == 1 &&
162 "Exit block should only have on predecessor");
163
164 // If the definition was cloned used that otherwise use the same value.
165 Value *ClonedValue = PN->getIncomingValue(0);
166 auto Mapped = VMap.find(ClonedValue);
167 if (Mapped != VMap.end())
168 ClonedValue = Mapped->second;
169
170 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
171 }
172}
173
175 // We need to turn the no-alias relation between pointer checking groups into
176 // no-aliasing annotations between instructions.
177 //
178 // We accomplish this by mapping each pointer checking group (a set of
179 // pointers memchecked together) to an alias scope and then also mapping each
180 // group to the list of scopes it can't alias.
181
182 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
183 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
184
185 // First allocate an aliasing scope for each pointer checking group.
186 //
187 // While traversing through the checking groups in the loop, also create a
188 // reverse map from pointers to the pointer checking group they were assigned
189 // to.
190 MDBuilder MDB(Context);
191 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
192
193 for (const auto &Group : RtPtrChecking->CheckingGroups) {
194 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
195
196 for (unsigned PtrIdx : Group.Members)
197 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
198 }
199
200 // Go through the checks and for each pointer group, collect the scopes for
201 // each non-aliasing pointer group.
203 GroupToNonAliasingScopes;
204
205 for (const auto &Check : AliasChecks)
206 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
207
208 // Finally, transform the above to actually map to scope list which is what
209 // the metadata uses.
210
211 for (const auto &Pair : GroupToNonAliasingScopes)
212 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
213}
214
216 if (!AnnotateNoAlias)
217 return;
218
219 // First prepare the maps.
221
222 // Add the scope and no-alias metadata to the instructions.
225 }
226}
227
229 const Instruction *OrigInst) {
230 if (!AnnotateNoAlias)
231 return;
232
233 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
234 const Value *Ptr = isa<LoadInst>(OrigInst)
235 ? cast<LoadInst>(OrigInst)->getPointerOperand()
236 : cast<StoreInst>(OrigInst)->getPointerOperand();
237
238 // Find the group for the pointer and then add the scope metadata.
239 auto Group = PtrToGroup.find(Ptr);
240 if (Group != PtrToGroup.end()) {
241 VersionedInst->setMetadata(
242 LLVMContext::MD_alias_scope,
244 VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
245 MDNode::get(Context, GroupToScope[Group->second])));
246
247 // Add the no-alias metadata.
248 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
249 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
250 VersionedInst->setMetadata(
251 LLVMContext::MD_noalias,
253 VersionedInst->getMetadata(LLVMContext::MD_noalias),
254 NonAliasingScopeList->second));
255 }
256}
257
258namespace {
260 ScalarEvolution *SE) {
261 // Build up a worklist of inner-loops to version. This is necessary as the
262 // act of versioning a loop creates new loops and can invalidate iterators
263 // across the loops.
264 SmallVector<Loop *, 8> Worklist;
265
266 for (Loop *TopLevelLoop : *LI)
267 for (Loop *L : depth_first(TopLevelLoop))
268 // We only handle inner-most loops.
269 if (L->isInnermost())
270 Worklist.push_back(L);
271
272 // Now walk the identified inner loops.
273 bool Changed = false;
274 for (Loop *L : Worklist) {
275 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
276 !L->getExitingBlock())
277 continue;
278 const LoopAccessInfo &LAI = LAIs.getInfo(*L);
279 if (!LAI.hasConvergentOp() &&
281 !LAI.getPSE().getPredicate().isAlwaysTrue())) {
282 if (!L->isLCSSAForm(*DT))
283 formLCSSARecursively(*L, *DT, LI, SE);
284
286 LI, DT, SE);
287 LVer.versionLoop();
288 LVer.annotateLoopWithNoAlias();
289 Changed = true;
290 LAIs.clear();
291 }
292 }
293
294 return Changed;
295}
296}
297
300 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
301 auto &LI = AM.getResult<LoopAnalysis>(F);
303 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
304
305 if (runImpl(&LI, LAIs, &DT, &SE))
307 return PreservedAnalyses::all();
308}
static bool runImpl(Function &F, const TargetLowering &TLI)
#define Check(C,...)
This header defines various interfaces for pass management in LLVM.
static cl::opt< bool > AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true), cl::Hidden, cl::desc("Add no-alias annotation for instructions that " "are disambiguated by memchecks"))
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:296
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:168
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1144
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1520
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:97
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:386
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1679
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
This analysis provides dependence information for the memory accesses of a loop.
const LoopAccessInfo & getInfo(Loop &L)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
void annotateLoopWithNoAlias()
Annotate memory instructions in the versioned loop with no-alias metadata based on the memchecks issu...
void prepareNoAliasMetadata()
Set up the aliasing scopes based on the memchecks.
void annotateInstWithNoAlias(Instruction *VersionedInst, const Instruction *OrigInst)
Add the noalias annotations to VersionedInst.
void versionLoop()
Performs the CFG manipulation part of versioning the loop including the DominatorTree and LoopInfo up...
LoopVersioning(const LoopAccessInfo &LAI, ArrayRef< RuntimePointerCheck > Checks, Loop *L, LoopInfo *LI, DominatorTree *DT, ScalarEvolution *SE)
Expects LoopAccessInfo, Loop, LoopInfo, DominatorTree as input.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition: LoopInfo.cpp:480
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition: MDBuilder.h:174
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition: MDBuilder.h:167
Metadata node.
Definition: Metadata.h:1069
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:1114
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1543
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
const SCEVPredicate & getPredicate() const
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
SmallVector< RuntimeCheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This class uses information about analyze scalars to rewrite expressions in canonical form.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
unsigned getNumOperands() const
Definition: User.h:250
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator end()
Definition: ValueMap.h:135
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
iterator_range< user_iterator > users()
Definition: Value.h:421
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
Definition: LoopUtils.cpp:1954
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:465
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition: LoopUtils.cpp:57
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.