blob: abbcd5f9e3b8b286015fa7fa75a9ee4c331e7dc2 [file] [log] [blame]
Adam Nemet215746b2015-07-10 18:55:13 +00001//===- LoopVersioning.cpp - Utility to version a loop ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a utility class to perform loop versioning. The versioned
11// loop speculates that otherwise may-aliasing memory accesses don't overlap and
12// emits checks to prove this.
13//
14//===----------------------------------------------------------------------===//
15
David Blaikie94c83372015-10-26 18:40:56 +000016#include "llvm/Transforms/Utils/LoopVersioning.h"
Adam Nemet215746b2015-07-10 18:55:13 +000017#include "llvm/Analysis/LoopAccessAnalysis.h"
18#include "llvm/Analysis/LoopInfo.h"
Silviu Baranga2910a4f2015-11-09 13:26:09 +000019#include "llvm/Analysis/ScalarEvolutionExpander.h"
Adam Nemet215746b2015-07-10 18:55:13 +000020#include "llvm/IR/Dominators.h"
Adam Nemet5eccf072016-03-17 20:32:32 +000021#include "llvm/IR/MDBuilder.h"
Adam Nemet215746b2015-07-10 18:55:13 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Cloning.h"
Adam Nemet215746b2015-07-10 18:55:13 +000024
25using namespace llvm;
26
Adam Nemet5eccf072016-03-17 20:32:32 +000027static cl::opt<bool>
28 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true),
29 cl::Hidden,
30 cl::desc("Add no-alias annotation for instructions that "
31 "are disambiguated by memchecks"));
32
Silviu Baranga2910a4f2015-11-09 13:26:09 +000033LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI, Loop *L, LoopInfo *LI,
34 DominatorTree *DT, ScalarEvolution *SE,
35 bool UseLAIChecks)
36 : VersionedLoop(L), NonVersionedLoop(nullptr), LAI(LAI), LI(LI), DT(DT),
37 SE(SE) {
Adam Nemet215746b2015-07-10 18:55:13 +000038 assert(L->getExitBlock() && "No single exit block");
Florian Hahn2e032132016-12-19 17:13:37 +000039 assert(L->isLoopSimplifyForm() && "Loop is not in loop-simplify form");
Silviu Baranga2910a4f2015-11-09 13:26:09 +000040 if (UseLAIChecks) {
41 setAliasChecks(LAI.getRuntimePointerChecking()->getChecks());
Xinliang David Li94734ee2016-07-01 05:59:55 +000042 setSCEVChecks(LAI.getPSE().getUnionPredicate());
Silviu Baranga2910a4f2015-11-09 13:26:09 +000043 }
Adam Nemet215746b2015-07-10 18:55:13 +000044}
45
Silviu Baranga2910a4f2015-11-09 13:26:09 +000046void LoopVersioning::setAliasChecks(
Benjamin Kramer728f4442016-05-29 10:46:35 +000047 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks) {
Silviu Baranga2910a4f2015-11-09 13:26:09 +000048 AliasChecks = std::move(Checks);
49}
50
51void LoopVersioning::setSCEVChecks(SCEVUnionPredicate Check) {
52 Preds = std::move(Check);
Adam Nemetdfaeb332015-08-12 16:51:19 +000053}
54
Adam Nemete4813402015-08-20 17:22:29 +000055void LoopVersioning::versionLoop(
56 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
Adam Nemet215746b2015-07-10 18:55:13 +000057 Instruction *FirstCheckInst;
58 Instruction *MemRuntimeCheck;
Silviu Baranga2910a4f2015-11-09 13:26:09 +000059 Value *SCEVRuntimeCheck;
60 Value *RuntimeCheck = nullptr;
61
Adam Nemet215746b2015-07-10 18:55:13 +000062 // Add the memcheck in the original preheader (this is empty initially).
Silviu Baranga2910a4f2015-11-09 13:26:09 +000063 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader();
Adam Nemet215746b2015-07-10 18:55:13 +000064 std::tie(FirstCheckInst, MemRuntimeCheck) =
Silviu Baranga2910a4f2015-11-09 13:26:09 +000065 LAI.addRuntimeChecks(RuntimeCheckBB->getTerminator(), AliasChecks);
Adam Nemet215746b2015-07-10 18:55:13 +000066
Xinliang David Li94734ee2016-07-01 05:59:55 +000067 const SCEVUnionPredicate &Pred = LAI.getPSE().getUnionPredicate();
Silviu Baranga2910a4f2015-11-09 13:26:09 +000068 SCEVExpander Exp(*SE, RuntimeCheckBB->getModule()->getDataLayout(),
69 "scev.check");
70 SCEVRuntimeCheck =
71 Exp.expandCodeForPredicate(&Pred, RuntimeCheckBB->getTerminator());
72 auto *CI = dyn_cast<ConstantInt>(SCEVRuntimeCheck);
73
74 // Discard the SCEV runtime check if it is always true.
75 if (CI && CI->isZero())
76 SCEVRuntimeCheck = nullptr;
77
78 if (MemRuntimeCheck && SCEVRuntimeCheck) {
79 RuntimeCheck = BinaryOperator::Create(Instruction::Or, MemRuntimeCheck,
Vikram TV299abc12016-06-13 10:49:28 +000080 SCEVRuntimeCheck, "lver.safe");
Silviu Baranga2910a4f2015-11-09 13:26:09 +000081 if (auto *I = dyn_cast<Instruction>(RuntimeCheck))
82 I->insertBefore(RuntimeCheckBB->getTerminator());
83 } else
84 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck;
85
86 assert(RuntimeCheck && "called even though we don't need "
87 "any runtime checks");
88
Adam Nemet215746b2015-07-10 18:55:13 +000089 // Rename the block to make the IR more readable.
Silviu Baranga2910a4f2015-11-09 13:26:09 +000090 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() +
91 ".lver.check");
Adam Nemet215746b2015-07-10 18:55:13 +000092
93 // Create empty preheader for the loop (and after cloning for the
94 // non-versioned loop).
Silviu Baranga2910a4f2015-11-09 13:26:09 +000095 BasicBlock *PH =
96 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI);
Adam Nemet215746b2015-07-10 18:55:13 +000097 PH->setName(VersionedLoop->getHeader()->getName() + ".ph");
98
99 // Clone the loop including the preheader.
100 //
101 // FIXME: This does not currently preserve SimplifyLoop because the exit
102 // block is a join between the two loops.
103 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks;
104 NonVersionedLoop =
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000105 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap,
106 ".lver.orig", LI, DT, NonVersionedLoopBlocks);
Adam Nemet215746b2015-07-10 18:55:13 +0000107 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap);
108
109 // Insert the conditional branch based on the result of the memchecks.
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000110 Instruction *OrigTerm = RuntimeCheckBB->getTerminator();
Adam Nemet215746b2015-07-10 18:55:13 +0000111 BranchInst::Create(NonVersionedLoop->getLoopPreheader(),
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000112 VersionedLoop->getLoopPreheader(), RuntimeCheck, OrigTerm);
Adam Nemet215746b2015-07-10 18:55:13 +0000113 OrigTerm->eraseFromParent();
114
115 // The loops merge in the original exit block. This is now dominated by the
116 // memchecking block.
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000117 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB);
Adam Nemete4813402015-08-20 17:22:29 +0000118
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);
Adam Nemet215746b2015-07-10 18:55:13 +0000122}
123
124void LoopVersioning::addPHINodes(
125 const SmallVectorImpl<Instruction *> &DefsUsedOutside) {
126 BasicBlock *PHIBlock = VersionedLoop->getExitBlock();
127 assert(PHIBlock && "No single successor to loop exit block");
Adam Nemet73a26952016-06-14 09:38:54 +0000128 PHINode *PN;
Adam Nemet215746b2015-07-10 18:55:13 +0000129
Adam Nemet73a26952016-06-14 09:38:54 +0000130 // First add a single-operand PHI for each DefsUsedOutside if one does not
131 // exists yet.
Adam Nemet215746b2015-07-10 18:55:13 +0000132 for (auto *Inst : DefsUsedOutside) {
Adam Nemet73a26952016-06-14 09:38:54 +0000133 // See if we have a single-operand PHI with the value defined by the
Adam Nemet215746b2015-07-10 18:55:13 +0000134 // original loop.
135 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
Adam Nemet57fb8982016-06-14 09:39:01 +0000136 if (PN->getIncomingValue(0) == Inst)
Adam Nemet215746b2015-07-10 18:55:13 +0000137 break;
138 }
139 // If not create it.
140 if (!PN) {
141 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000142 &PHIBlock->front());
Bjorn Petterssonfecef6b2018-05-22 08:33:02 +0000143 SmallVector<User*, 8> UsersToUpdate;
144 for (User *U : Inst->users())
145 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent()))
146 UsersToUpdate.push_back(U);
147 for (User *U : UsersToUpdate)
148 U->replaceUsesOfWith(Inst, PN);
Adam Nemet215746b2015-07-10 18:55:13 +0000149 PN->addIncoming(Inst, VersionedLoop->getExitingBlock());
150 }
Adam Nemet73a26952016-06-14 09:38:54 +0000151 }
152
153 // Then for each PHI add the operand for the edge from the cloned loop.
154 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) {
155 assert(PN->getNumOperands() == 1 &&
156 "Exit block should only have on predecessor");
157
158 // If the definition was cloned used that otherwise use the same value.
159 Value *ClonedValue = PN->getIncomingValue(0);
160 auto Mapped = VMap.find(ClonedValue);
161 if (Mapped != VMap.end())
162 ClonedValue = Mapped->second;
163
164 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock());
Adam Nemet215746b2015-07-10 18:55:13 +0000165 }
166}
Adam Nemetd52ed842016-02-03 00:06:10 +0000167
Adam Nemet5eccf072016-03-17 20:32:32 +0000168void LoopVersioning::prepareNoAliasMetadata() {
169 // We need to turn the no-alias relation between pointer checking groups into
170 // no-aliasing annotations between instructions.
171 //
172 // We accomplish this by mapping each pointer checking group (a set of
173 // pointers memchecked together) to an alias scope and then also mapping each
174 // group to the list of scopes it can't alias.
175
176 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking();
177 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
178
179 // First allocate an aliasing scope for each pointer checking group.
180 //
181 // While traversing through the checking groups in the loop, also create a
182 // reverse map from pointers to the pointer checking group they were assigned
183 // to.
184 MDBuilder MDB(Context);
185 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain");
186
187 for (const auto &Group : RtPtrChecking->CheckingGroups) {
188 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain);
189
190 for (unsigned PtrIdx : Group.Members)
191 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group;
192 }
193
194 // Go through the checks and for each pointer group, collect the scopes for
195 // each non-aliasing pointer group.
196 DenseMap<const RuntimePointerChecking::CheckingPtrGroup *,
197 SmallVector<Metadata *, 4>>
198 GroupToNonAliasingScopes;
199
200 for (const auto &Check : AliasChecks)
201 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]);
202
203 // Finally, transform the above to actually map to scope list which is what
204 // the metadata uses.
205
206 for (auto Pair : GroupToNonAliasingScopes)
207 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second);
208}
209
210void LoopVersioning::annotateLoopWithNoAlias() {
211 if (!AnnotateNoAlias)
212 return;
213
214 // First prepare the maps.
215 prepareNoAliasMetadata();
216
217 // Add the scope and no-alias metadata to the instructions.
218 for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) {
219 annotateInstWithNoAlias(I);
220 }
221}
222
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000223void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst,
224 const Instruction *OrigInst) {
Adam Nemet5eccf072016-03-17 20:32:32 +0000225 if (!AnnotateNoAlias)
226 return;
227
228 LLVMContext &Context = VersionedLoop->getHeader()->getContext();
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000229 const Value *Ptr = isa<LoadInst>(OrigInst)
230 ? cast<LoadInst>(OrigInst)->getPointerOperand()
231 : cast<StoreInst>(OrigInst)->getPointerOperand();
Adam Nemet5eccf072016-03-17 20:32:32 +0000232
233 // Find the group for the pointer and then add the scope metadata.
234 auto Group = PtrToGroup.find(Ptr);
235 if (Group != PtrToGroup.end()) {
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000236 VersionedInst->setMetadata(
Adam Nemet5eccf072016-03-17 20:32:32 +0000237 LLVMContext::MD_alias_scope,
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000238 MDNode::concatenate(
239 VersionedInst->getMetadata(LLVMContext::MD_alias_scope),
240 MDNode::get(Context, GroupToScope[Group->second])));
Adam Nemet5eccf072016-03-17 20:32:32 +0000241
242 // Add the no-alias metadata.
243 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second);
244 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end())
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000245 VersionedInst->setMetadata(
Adam Nemet5eccf072016-03-17 20:32:32 +0000246 LLVMContext::MD_noalias,
Adam Nemetb0c4eae2016-03-17 20:32:37 +0000247 MDNode::concatenate(
248 VersionedInst->getMetadata(LLVMContext::MD_noalias),
249 NonAliasingScopeList->second));
Adam Nemet5eccf072016-03-17 20:32:32 +0000250 }
251}
252
Adam Nemetd52ed842016-02-03 00:06:10 +0000253namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254/// Also expose this is a pass. Currently this is only used for
Adam Nemetd52ed842016-02-03 00:06:10 +0000255/// unit-testing. It adds all memchecks necessary to remove all may-aliasing
256/// array accesses from the loop.
257class LoopVersioningPass : public FunctionPass {
258public:
259 LoopVersioningPass() : FunctionPass(ID) {
260 initializeLoopVersioningPassPass(*PassRegistry::getPassRegistry());
261 }
262
263 bool runOnFunction(Function &F) override {
264 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000265 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
Adam Nemetd52ed842016-02-03 00:06:10 +0000266 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
267 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
268
269 // Build up a worklist of inner-loops to version. This is necessary as the
270 // act of versioning a loop creates new loops and can invalidate iterators
271 // across the loops.
272 SmallVector<Loop *, 8> Worklist;
273
274 for (Loop *TopLevelLoop : *LI)
275 for (Loop *L : depth_first(TopLevelLoop))
276 // We only handle inner-most loops.
277 if (L->empty())
278 Worklist.push_back(L);
279
280 // Now walk the identified inner loops.
281 bool Changed = false;
282 for (Loop *L : Worklist) {
Adam Nemetbdbc5222016-06-16 08:26:56 +0000283 const LoopAccessInfo &LAI = LAA->getInfo(L);
Florian Hahn2e032132016-12-19 17:13:37 +0000284 if (L->isLoopSimplifyForm() && (LAI.getNumRuntimePointerChecks() ||
285 !LAI.getPSE().getUnionPredicate().isAlwaysTrue())) {
Adam Nemetd52ed842016-02-03 00:06:10 +0000286 LoopVersioning LVer(LAI, L, LI, DT, SE);
287 LVer.versionLoop();
Adam Nemet5eccf072016-03-17 20:32:32 +0000288 LVer.annotateLoopWithNoAlias();
Adam Nemetd52ed842016-02-03 00:06:10 +0000289 Changed = true;
290 }
291 }
292
293 return Changed;
294 }
295
296 void getAnalysisUsage(AnalysisUsage &AU) const override {
297 AU.addRequired<LoopInfoWrapperPass>();
298 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000299 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemetd52ed842016-02-03 00:06:10 +0000300 AU.addRequired<DominatorTreeWrapperPass>();
301 AU.addPreserved<DominatorTreeWrapperPass>();
302 AU.addRequired<ScalarEvolutionWrapperPass>();
303 }
304
305 static char ID;
306};
307}
308
309#define LVER_OPTION "loop-versioning"
310#define DEBUG_TYPE LVER_OPTION
311
312char LoopVersioningPass::ID;
313static const char LVer_name[] = "Loop Versioning";
314
315INITIALIZE_PASS_BEGIN(LoopVersioningPass, LVER_OPTION, LVer_name, false, false)
316INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000317INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemetd52ed842016-02-03 00:06:10 +0000318INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
319INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
320INITIALIZE_PASS_END(LoopVersioningPass, LVER_OPTION, LVer_name, false, false)
321
322namespace llvm {
323FunctionPass *createLoopVersioningPass() {
324 return new LoopVersioningPass();
325}
326}