LLVM 18.0.0git
Go to the documentation of this file.
1//===- LoopVersioning.cpp - Utility to version a loop ---------------------===//
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
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.
16#include "llvm/ADT/ArrayRef.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/PassManager.h"
31using namespace llvm;
33#define DEBUG_TYPE "loop-versioning"
35static cl::opt<bool>
36 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
38 cl::desc("Add no-alias annotation for instructions that "
39 "are disambiguated by memchecks"));
43 LoopInfo *LI, DominatorTree *DT,
45 : VersionedLoop(L), AliasChecks(Checks.begin(), Checks.end()),
46 Preds(LAI.getPSE().getPredicate()), LAI(LAI), LI(LI), DT(DT),
47 SE(SE) {
51 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
52 assert(VersionedLoop->getUniqueExitBlock() && "No single exit block");
53 assert(VersionedLoop->isLoopSimplifyForm() &&
54 "Loop is not in loop-simplify form");
56 Value *MemRuntimeCheck;
57 Value *SCEVRuntimeCheck;
58 Value *RuntimeCheck = nullptr;
60 // Add the memcheck in the original preheader (this is empty initially).
61 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
62 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
64 SCEVExpander Exp2(*RtPtrChecking.getSE(),
65 VersionedLoop->getHeader()->getModule()->getDataLayout(),
66 "induction");
67 MemRuntimeCheck = addRuntimeChecks(RuntimeCheckBB->getTerminator(),
68 VersionedLoop, AliasChecks, Exp2);
70 SCEVExpander Exp(*SE, RuntimeCheckBB->getModule()->getDataLayout(),
71 "scev.check");
72 SCEVRuntimeCheck =
73 Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
76 RuntimeCheckBB->getContext(),
77 InstSimplifyFolder(RuntimeCheckBB->getModule()->getDataLayout()));
78 if (MemRuntimeCheck && SCEVRuntimeCheck) {
79 Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
80 RuntimeCheck =
81 Builder.CreateOr(MemRuntimeCheck, SCEVRuntimeCheck, "lver.safe");
82 } else
83 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
85 assert(RuntimeCheck && "called even though we don't need "
86 "any runtime checks");
88 // Rename the block to make the IR more readable.
89 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
90 ".lver.check");
92 // Create empty preheader for the loop (and after cloning for the
93 // non-versioned loop).
94 BasicBlock *PH =
95 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI,
96 nullptr, VersionedLoop->getHeader()->getName() + ".ph");
98 // Clone the loop including the preheader.
99 //
100 // FIXME: This does not currently preserve SimplifyLoop because the exit
101 // block is a join between the two loops.
102 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
103 NonVersionedLoop =
104 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
105 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
106 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
108 // Insert the conditional branch based on the result of the memchecks.
109 Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
110 Builder.SetInsertPoint(OrigTerm);
111 Builder.CreateCondBr(RuntimeCheck, NonVersionedLoop->getLoopPreheader(),
112 VersionedLoop->getLoopPreheader());
113 OrigTerm->eraseFromParent();
115 // The loops merge in the original exit block. This is now dominated by the
116 // memchecking block.
117 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
119 // Adds the necessary PHI nodes for the versioned loops based on the
120 // loop-defined values used outside of the loop.
121 addPHINodes(DefsUsedOutside);
122 formDedicatedExitBlocks(NonVersionedLoop, DT, LI, nullptr, true);
123 formDedicatedExitBlocks(VersionedLoop, DT, LI, nullptr, true);
124 assert(NonVersionedLoop->isLoopSimplifyForm() &&
125 VersionedLoop->isLoopSimplifyForm() &&
126 "The versioned loops should be in simplify form.");
129void LoopVersioning::addPHINodes(
130 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
131 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
132 assert(PHIBlock && "No single successor to loop exit block");
133 PHINode *PN;
135 // First add a single-operand PHI for each DefsUsedOutside if one does not
136 // exists yet.
137 for (auto *Inst : DefsUsedOutside) {
138 // See if we have a single-operand PHI with the value defined by the
139 // original loop.
140 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
141 if (PN->getIncomingValue(0) == Inst) {
142 SE->forgetValue(PN);
143 break;
144 }
145 }
146 // If not create it.
147 if (!PN) {
148 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver");
149 PN->insertBefore(PHIBlock->begin());
150 SmallVector<User*, 8> UsersToUpdate;
151 for (User *U : Inst->users())
152 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
153 UsersToUpdate.push_back(U);
154 for (User *U : UsersToUpdate)
155 U->replaceUsesOfWith(Inst, PN);
156 PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
157 }
158 }
160 // Then for each PHI add the operand for the edge from the cloned loop.
161 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
162 assert(PN->getNumOperands() == 1 &&
163 "Exit block should only have on predecessor");
165 // If the definition was cloned used that otherwise use the same value.
166 Value *ClonedValue = PN->getIncomingValue(0);
167 auto Mapped = VMap.find(ClonedValue);
168 if (Mapped != VMap.end())
169 ClonedValue = Mapped->second;
171 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
172 }
176 // We need to turn the no-alias relation between pointer checking groups into
177 // no-aliasing annotations between instructions.
178 //
179 // We accomplish this by mapping each pointer checking group (a set of
180 // pointers memchecked together) to an alias scope and then also mapping each
181 // group to the list of scopes it can't alias.
183 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
184 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
186 // First allocate an aliasing scope for each pointer checking group.
187 //
188 // While traversing through the checking groups in the loop, also create a
189 // reverse map from pointers to the pointer checking group they were assigned
190 // to.
191 MDBuilder MDB(Context);
192 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
194 for (const auto &Group : RtPtrChecking->CheckingGroups) {
195 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
197 for (unsigned PtrIdx : Group.Members)
198 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
199 }
201 // Go through the checks and for each pointer group, collect the scopes for
202 // each non-aliasing pointer group.
204 GroupToNonAliasingScopes;
206 for (const auto &Check : AliasChecks)
207 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
209 // Finally, transform the above to actually map to scope list which is what
210 // the metadata uses.
212 for (const auto &Pair : GroupToNonAliasingScopes)
213 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
217 if (!AnnotateNoAlias)
218 return;
220 // First prepare the maps.
223 // Add the scope and no-alias metadata to the instructions.
226 }
230 const Instruction *OrigInst) {
231 if (!AnnotateNoAlias)
232 return;
234 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
235 const Value *Ptr = isa<LoadInst>(OrigInst)
236 ? cast<LoadInst>(OrigInst)->getPointerOperand()
237 : cast<StoreInst>(OrigInst)->getPointerOperand();
239 // Find the group for the pointer and then add the scope metadata.
240 auto Group = PtrToGroup.find(Ptr);
241 if (Group != PtrToGroup.end()) {
242 VersionedInst->setMetadata(
243 LLVMContext::MD_alias_scope,
245 VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
246 MDNode::get(Context, GroupToScope[Group->second])));
248 // Add the no-alias metadata.
249 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
250 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
251 VersionedInst->setMetadata(
252 LLVMContext::MD_noalias,
254 VersionedInst->getMetadata(LLVMContext::MD_noalias),
255 NonAliasingScopeList->second));
256 }
259namespace {
261 ScalarEvolution *SE) {
262 // Build up a worklist of inner-loops to version. This is necessary as the
263 // act of versioning a loop creates new loops and can invalidate iterators
264 // across the loops.
265 SmallVector<Loop *, 8> Worklist;
267 for (Loop *TopLevelLoop : *LI)
268 for (Loop *L : depth_first(TopLevelLoop))
269 // We only handle inner-most loops.
270 if (L->isInnermost())
271 Worklist.push_back(L);
273 // Now walk the identified inner loops.
274 bool Changed = false;
275 for (Loop *L : Worklist) {
276 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
277 !L->getExitingBlock())
278 continue;
279 const LoopAccessInfo &LAI = LAIs.getInfo(*L);
280 if (!LAI.hasConvergentOp() &&
282 !LAI.getPSE().getPredicate().isAlwaysTrue())) {
284 LI, DT, SE);
285 LVer.versionLoop();
286 LVer.annotateLoopWithNoAlias();
287 Changed = true;
288 LAIs.clear();
289 }
290 }
292 return Changed;
298 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
299 auto &LI = AM.getResult<LoopAnalysis>(F);
301 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
303 if (runImpl(&LI, LAIs, &DT, &SE))
305 return PreservedAnalyses::all();
assume Assume Builder
static bool runImpl(Function &F, const TargetLowering &TLI)
#define Check(C,...)
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
LLVMContext & Context
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
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:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:335
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:35
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:127
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:145
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:166
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2625
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:89
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:302
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1521
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:83
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:569
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:47
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition: LoopInfo.cpp:479
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition: MDBuilder.h:159
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition: MDBuilder.h:152
Metadata node.
Definition: Metadata.h:950
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:1007
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1416
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:254
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
const SCEVPredicate & getPredicate() const
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
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 forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
unsigned getNumOperands() const
Definition: User.h:191
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:378
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:445
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:1719
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.