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
15#include "llvm/Transforms/Utils/LoopVersioning.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/InstSimplifyFolder.h"
19#include "llvm/Analysis/LoopAccessAnalysis.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/Analysis/TargetLibraryInfo.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/PassManager.h"
26#include "llvm/IR/ProfDataUtils.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Cloning.h"
30#include "llvm/Transforms/Utils/LoopUtils.h"
31#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "loop-versioning"
36
37static cl::opt<bool>
38 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(Val: true),
39 cl::Hidden,
40 cl::desc("Add no-alias annotation for instructions that "
41 "are disambiguated by memchecks"));
42
43LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI,
44 ArrayRef<RuntimePointerCheck> Checks, Loop *L,
45 LoopInfo *LI, DominatorTree *DT,
46 ScalarEvolution *SE)
47 : VersionedLoop(L), AliasChecks(Checks), Preds(LAI.getPSE().getPredicate()),
48 LAI(LAI), LI(LI), DT(DT), SE(SE) {}
49
50void LoopVersioning::versionLoop(
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");
55
56 Value *MemRuntimeCheck;
57 Value *SCEVRuntimeCheck;
58 Value *RuntimeCheck = nullptr;
59
60 // Add the memcheck in the original preheader (this is empty initially).
61 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
62 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
63
64 SCEVExpander Exp2(*RtPtrChecking.getSE(), "induction");
65 MemRuntimeCheck = addRuntimeChecks(Loc: RuntimeCheckBB->getTerminator(),
66 TheLoop: VersionedLoop, PointerChecks: AliasChecks, Expander&: Exp2);
67
68 SCEVExpander Exp(*SE, "scev.check");
69 SCEVRuntimeCheck =
70 Exp.expandCodeForPredicate(Pred: &Preds, Loc: RuntimeCheckBB->getTerminator());
71
72 IRBuilder<InstSimplifyFolder> Builder(
73 RuntimeCheckBB->getContext(),
74 InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
75 if (MemRuntimeCheck && SCEVRuntimeCheck) {
76 Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());
77 RuntimeCheck =
78 Builder.CreateOr(LHS: MemRuntimeCheck, RHS: SCEVRuntimeCheck, Name: "lver.safe");
79 } else
80 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
81
82 Exp.eraseDeadInstructions(Root: 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(Old: RuntimeCheckBB, SplitPt: RuntimeCheckBB->getTerminator(), DT, LI,
95 MSSAU: nullptr, BBName: 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(Before: PH, LoopDomBB: RuntimeCheckBB, OrigLoop: VersionedLoop, VMap,
104 NameSuffix: ".lver.orig", LI, DT, Blocks&: NonVersionedLoopBlocks);
105 remapInstructionsInBlocks(Blocks: 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 auto *BI =
111 Builder.CreateCondBr(Cond: RuntimeCheck, True: NonVersionedLoop->getLoopPreheader(),
112 False: VersionedLoop->getLoopPreheader());
113 // We don't know what the probability of executing the versioned vs the
114 // unversioned variants is.
115 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *BI, DEBUG_TYPE);
116 OrigTerm->eraseFromParent();
117
118 // The loops merge in the original exit block. This is now dominated by the
119 // memchecking block.
120 DT->changeImmediateDominator(BB: VersionedLoop->getExitBlock(), NewBB: RuntimeCheckBB);
121
122 // Adds the necessary PHI nodes for the versioned loops based on the
123 // loop-defined values used outside of the loop.
124 addPHINodes(DefsUsedOutside);
125 formDedicatedExitBlocks(L: NonVersionedLoop, DT, LI, MSSAU: nullptr, PreserveLCSSA: true);
126 formDedicatedExitBlocks(L: VersionedLoop, DT, LI, MSSAU: nullptr, PreserveLCSSA: true);
127 assert(NonVersionedLoop->isLoopSimplifyForm() &&
128 VersionedLoop->isLoopSimplifyForm() &&
129 "The versioned loops should be in simplify form.");
130}
131
132void LoopVersioning::addPHINodes(
133 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
134 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
135 assert(PHIBlock && "No single successor to loop exit block");
136 PHINode *PN;
137
138 // First add a single-operand PHI for each DefsUsedOutside if one does not
139 // exists yet.
140 for (auto *Inst : DefsUsedOutside) {
141 // See if we have a single-operand PHI with the value defined by the
142 // original loop.
143 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(Val&: I)); ++I) {
144 if (PN->getIncomingValue(i: 0) == Inst) {
145 SE->forgetLcssaPhiWithNewPredecessor(L: VersionedLoop, V: PN);
146 break;
147 }
148 }
149 // If not create it.
150 if (!PN) {
151 PN = PHINode::Create(Ty: Inst->getType(), NumReservedValues: 2, NameStr: Inst->getName() + ".lver");
152 PN->insertBefore(InsertPos: PHIBlock->begin());
153 SmallVector<User*, 8> UsersToUpdate;
154 for (User *U : Inst->users())
155 if (!VersionedLoop->contains(BB: cast<Instruction>(Val: U)->getParent()))
156 UsersToUpdate.push_back(Elt: U);
157 for (User *U : UsersToUpdate)
158 U->replaceUsesOfWith(From: Inst, To: PN);
159 PN->addIncoming(V: Inst, BB: VersionedLoop->getExitingBlock());
160 }
161 }
162
163 // Then for each PHI add the operand for the edge from the cloned loop.
164 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(Val&: I)); ++I) {
165 assert(PN->getNumOperands() == 1 &&
166 "Exit block should only have on predecessor");
167
168 // If the definition was cloned used that otherwise use the same value.
169 Value *ClonedValue = PN->getIncomingValue(i: 0);
170 auto Mapped = VMap.find(Val: ClonedValue);
171 if (Mapped != VMap.end())
172 ClonedValue = Mapped->second;
173
174 PN->addIncoming(V: ClonedValue, BB: NonVersionedLoop->getExitingBlock());
175 }
176}
177
178void LoopVersioning::prepareNoAliasMetadata() {
179 // We need to turn the no-alias relation between pointer checking groups into
180 // no-aliasing annotations between instructions.
181 //
182 // We accomplish this by mapping each pointer checking group (a set of
183 // pointers memchecked together) to an alias scope and then also mapping each
184 // group to the list of scopes it can't alias.
185
186 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
187 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
188
189 // First allocate an aliasing scope for each pointer checking group.
190 //
191 // While traversing through the checking groups in the loop, also create a
192 // reverse map from pointers to the pointer checking group they were assigned
193 // to.
194 MDBuilder MDB(Context);
195 MDNode *Domain = MDB.createAnonymousAliasScopeDomain(Name: "LVerDomain");
196
197 for (const auto &Group : RtPtrChecking->CheckingGroups) {
198 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
199
200 for (unsigned PtrIdx : Group.Members)
201 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
202 }
203
204 // Go through the checks and for each pointer group, collect the scopes for
205 // each non-aliasing pointer group.
206 DenseMap<const RuntimeCheckingPtrGroup *, SmallVector<Metadata *, 4>>
207 GroupToNonAliasingScopes;
208
209 for (const auto &Check : AliasChecks)
210 GroupToNonAliasingScopes[Check.first].push_back(Elt: GroupToScope[Check.second]);
211
212 // Finally, transform the above to actually map to scope list which is what
213 // the metadata uses.
214
215 for (const auto &Pair : GroupToNonAliasingScopes)
216 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, MDs: Pair.second);
217}
218
219void LoopVersioning::annotateLoopWithNoAlias() {
220 if (!AnnotateNoAlias)
221 return;
222
223 // First prepare the maps.
224 prepareNoAliasMetadata();
225
226 // Add the scope and no-alias metadata to the instructions.
227 for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {
228 annotateInstWithNoAlias(I);
229 }
230}
231
232std::pair<MDNode *, MDNode *>
233LoopVersioning::getNoAliasMetadataFor(const Instruction *OrigInst) const {
234 if (!AnnotateNoAlias)
235 return {nullptr, nullptr};
236
237 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
238 const Value *Ptr = isa<LoadInst>(Val: OrigInst)
239 ? cast<LoadInst>(Val: OrigInst)->getPointerOperand()
240 : cast<StoreInst>(Val: OrigInst)->getPointerOperand();
241
242 MDNode *AliasScope = nullptr;
243 MDNode *NoAlias = nullptr;
244 // Find the group for the pointer and then add the scope metadata.
245 auto Group = PtrToGroup.find(Val: Ptr);
246 if (Group != PtrToGroup.end()) {
247 AliasScope = MDNode::concatenate(
248 A: OrigInst->getMetadata(KindID: LLVMContext::MD_alias_scope),
249 B: MDNode::get(Context, MDs: GroupToScope.lookup(Val: Group->second)));
250
251 // Add the no-alias metadata.
252 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Val: Group->second);
253 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
254 NoAlias =
255 MDNode::concatenate(A: OrigInst->getMetadata(KindID: LLVMContext::MD_noalias),
256 B: NonAliasingScopeList->second);
257 }
258 return {AliasScope, NoAlias};
259}
260
261void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst,
262 const Instruction *OrigInst) {
263 const auto &[AliasScopeMD, NoAliasMD] = getNoAliasMetadataFor(OrigInst);
264 if (AliasScopeMD)
265 VersionedInst->setMetadata(KindID: LLVMContext::MD_alias_scope, Node: AliasScopeMD);
266
267 if (NoAliasMD)
268 VersionedInst->setMetadata(KindID: LLVMContext::MD_noalias, Node: NoAliasMD);
269}
270
271namespace {
272bool runImpl(LoopInfo *LI, LoopAccessInfoManager &LAIs, DominatorTree *DT,
273 ScalarEvolution *SE) {
274 // Build up a worklist of inner-loops to version. This is necessary as the
275 // act of versioning a loop creates new loops and can invalidate iterators
276 // across the loops.
277 SmallVector<Loop *, 8> Worklist;
278
279 for (Loop *TopLevelLoop : *LI)
280 for (Loop *L : depth_first(G: TopLevelLoop))
281 // We only handle inner-most loops.
282 if (L->isInnermost())
283 Worklist.push_back(Elt: L);
284
285 // Now walk the identified inner loops.
286 bool Changed = false;
287 for (Loop *L : Worklist) {
288 if (!L->isLoopSimplifyForm() || !L->isRotatedForm() ||
289 !L->getExitingBlock())
290 continue;
291 const LoopAccessInfo &LAI = LAIs.getInfo(L&: *L);
292 if (!LAI.hasConvergentOp() &&
293 (LAI.getNumRuntimePointerChecks() ||
294 !LAI.getPSE().getPredicate().isAlwaysTrue())) {
295 if (!L->isLCSSAForm(DT: *DT))
296 formLCSSARecursively(L&: *L, DT: *DT, LI, SE);
297
298 LoopVersioning LVer(LAI, LAI.getRuntimePointerChecking()->getChecks(), L,
299 LI, DT, SE);
300 LVer.versionLoop();
301 LVer.annotateLoopWithNoAlias();
302 Changed = true;
303 LAIs.clear();
304 }
305 }
306
307 return Changed;
308}
309}
310
311PreservedAnalyses LoopVersioningPass::run(Function &F,
312 FunctionAnalysisManager &AM) {
313 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
314 auto &LI = AM.getResult<LoopAnalysis>(IR&: F);
315 LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(IR&: F);
316 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
317
318 if (runImpl(LI: &LI, LAIs, DT: &DT, SE: &SE))
319 return PreservedAnalyses::none();
320 return PreservedAnalyses::all();
321}
322