blob: 53b25e688e822e48083beb622cfa3c9df9d8afbc [file] [log] [blame]
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001//===- LoopVersioningLICM.cpp - LICM Loop Versioning ----------------------===//
Ashutosh Nemadf6763a2016-02-06 07:47:48 +00002//
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// When alias analysis is uncertain about the aliasing between any two accesses,
11// it will return MayAlias. This uncertainty from alias analysis restricts LICM
12// from proceeding further. In cases where alias analysis is uncertain we might
13// use loop versioning as an alternative.
14//
15// Loop Versioning will create a version of the loop with aggressive aliasing
16// assumptions in addition to the original with conservative (default) aliasing
17// assumptions. The version of the loop making aggressive aliasing assumptions
18// will have all the memory accesses marked as no-alias. These two versions of
19// loop will be preceded by a memory runtime check. This runtime check consists
20// of bound checks for all unique memory accessed in loop, and it ensures the
21// lack of memory aliasing. The result of the runtime check determines which of
22// the loop versions is executed: If the runtime check detects any memory
23// aliasing, then the original loop is executed. Otherwise, the version with
24// aggressive aliasing assumptions is used.
25//
26// Following are the top level steps:
27//
28// a) Perform LoopVersioningLICM's feasibility check.
29// b) If loop is a candidate for versioning then create a memory bound check,
30// by considering all the memory accesses in loop body.
31// c) Clone original loop and set all memory accesses as no-alias in new loop.
32// d) Set original loop & versioned loop as a branch target of the runtime check
33// result.
34//
35// It transforms loop as shown below:
36//
37// +----------------+
38// |Runtime Memcheck|
39// +----------------+
40// |
41// +----------+----------------+----------+
42// | |
43// +---------+----------+ +-----------+----------+
44// |Orig Loop Preheader | |Cloned Loop Preheader |
45// +--------------------+ +----------------------+
46// | |
47// +--------------------+ +----------------------+
48// |Orig Loop Body | |Cloned Loop Body |
49// +--------------------+ +----------------------+
50// | |
51// +--------------------+ +----------------------+
Ashutosh Nema2260a3a2016-02-11 09:23:53 +000052// |Orig Loop Exit Block| |Cloned Loop Exit Block|
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000053// +--------------------+ +-----------+----------+
54// | |
55// +----------+--------------+-----------+
56// |
57// +-----+----+
58// |Join Block|
59// +----------+
60//
61//===----------------------------------------------------------------------===//
62
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000063#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/StringRef.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000065#include "llvm/Analysis/AliasAnalysis.h"
66#include "llvm/Analysis/AliasSetTracker.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000067#include "llvm/Analysis/GlobalsModRef.h"
68#include "llvm/Analysis/LoopAccessAnalysis.h"
69#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Analysis/LoopPass.h"
71#include "llvm/Analysis/ScalarEvolution.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000072#include "llvm/IR/CallSite.h"
73#include "llvm/IR/Constants.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000074#include "llvm/IR/Dominators.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000075#include "llvm/IR/Instruction.h"
76#include "llvm/IR/Instructions.h"
77#include "llvm/IR/LLVMContext.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000078#include "llvm/IR/MDBuilder.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000079#include "llvm/IR/Metadata.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000080#include "llvm/IR/Type.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000081#include "llvm/IR/Value.h"
82#include "llvm/Pass.h"
83#include "llvm/Support/Casting.h"
84#include "llvm/Support/CommandLine.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000085#include "llvm/Support/Debug.h"
86#include "llvm/Support/raw_ostream.h"
87#include "llvm/Transforms/Scalar.h"
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000088#include "llvm/Transforms/Utils/LoopUtils.h"
89#include "llvm/Transforms/Utils/LoopVersioning.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000090#include <cassert>
91#include <memory>
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000092
93using namespace llvm;
94
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000095#define DEBUG_TYPE "loop-versioning-licm"
96
97static const char *LICMVersioningMetaData = "llvm.loop.licm_versioning.disable";
98
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000099/// Threshold minimum allowed percentage for possible
100/// invariant instructions in a loop.
101static cl::opt<float>
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000102 LVInvarThreshold("licm-versioning-invariant-threshold",
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000103 cl::desc("LoopVersioningLICM's minimum allowed percentage"
104 "of possible invariant instructions per loop"),
105 cl::init(25), cl::Hidden);
106
107/// Threshold for maximum allowed loop nest/depth
108static cl::opt<unsigned> LVLoopDepthThreshold(
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000109 "licm-versioning-max-depth-threshold",
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000110 cl::desc(
111 "LoopVersioningLICM's threshold for maximum allowed loop nest/depth"),
112 cl::init(2), cl::Hidden);
113
114/// \brief Create MDNode for input string.
115static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
116 LLVMContext &Context = TheLoop->getHeader()->getContext();
117 Metadata *MDs[] = {
118 MDString::get(Context, Name),
119 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
120 return MDNode::get(Context, MDs);
121}
122
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000123/// \brief Set input string into loop metadata by keeping other values intact.
124void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
125 unsigned V) {
126 SmallVector<Metadata *, 4> MDs(1);
127 // If the loop already has metadata, retain it.
128 MDNode *LoopID = TheLoop->getLoopID();
129 if (LoopID) {
130 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
131 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
132 MDs.push_back(Node);
133 }
134 }
135 // Add new metadata.
136 MDs.push_back(createStringMetadata(TheLoop, MDString, V));
137 // Replace current metadata node with new one.
138 LLVMContext &Context = TheLoop->getHeader()->getContext();
139 MDNode *NewLoopID = MDNode::get(Context, MDs);
140 // Set operand 0 to refer to the loop id itself.
141 NewLoopID->replaceOperandWith(0, NewLoopID);
142 TheLoop->setLoopID(NewLoopID);
143}
144
145namespace {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000146
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000147struct LoopVersioningLICM : public LoopPass {
148 static char ID;
149
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000150 LoopVersioningLICM()
151 : LoopPass(ID), LoopDepthThreshold(LVLoopDepthThreshold),
152 InvariantThreshold(LVInvarThreshold) {
153 initializeLoopVersioningLICMPass(*PassRegistry::getPassRegistry());
154 }
155
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000156 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
157
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.setPreservesCFG();
160 AU.addRequired<AAResultsWrapperPass>();
161 AU.addRequired<DominatorTreeWrapperPass>();
162 AU.addRequiredID(LCSSAID);
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000163 AU.addRequired<LoopAccessLegacyAnalysis>();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000164 AU.addRequired<LoopInfoWrapperPass>();
165 AU.addRequiredID(LoopSimplifyID);
166 AU.addRequired<ScalarEvolutionWrapperPass>();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000167 AU.addPreserved<AAResultsWrapperPass>();
168 AU.addPreserved<GlobalsAAWrapperPass>();
169 }
170
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000171 StringRef getPassName() const override { return "Loop Versioning for LICM"; }
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000172
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000173 void reset() {
174 AA = nullptr;
175 SE = nullptr;
176 LAA = nullptr;
177 CurLoop = nullptr;
178 LoadAndStoreCounter = 0;
179 InvariantCounter = 0;
180 IsReadOnlyLoop = true;
181 CurAST.reset();
182 }
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000183
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000184 class AutoResetter {
185 public:
186 AutoResetter(LoopVersioningLICM &LVLICM) : LVLICM(LVLICM) {}
187 ~AutoResetter() { LVLICM.reset(); }
188
189 private:
190 LoopVersioningLICM &LVLICM;
191 };
192
193private:
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000194 // Current AliasAnalysis information
195 AliasAnalysis *AA = nullptr;
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000196
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000197 // Current ScalarEvolution
198 ScalarEvolution *SE = nullptr;
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000199
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000200 // Current LoopAccessAnalysis
201 LoopAccessLegacyAnalysis *LAA = nullptr;
202
203 // Current Loop's LoopAccessInfo
204 const LoopAccessInfo *LAI = nullptr;
205
206 // The current loop we are working on.
207 Loop *CurLoop = nullptr;
208
209 // AliasSet information for the current loop.
210 std::unique_ptr<AliasSetTracker> CurAST;
211
212 // Maximum loop nest threshold
213 unsigned LoopDepthThreshold;
214
215 // Minimum invariant threshold
216 float InvariantThreshold;
217
218 // Counter to track num of load & store
219 unsigned LoadAndStoreCounter = 0;
220
221 // Counter to track num of invariant
222 unsigned InvariantCounter = 0;
223
224 // Read only loop marker.
225 bool IsReadOnlyLoop = true;
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000226
227 bool isLegalForVersioning();
228 bool legalLoopStructure();
229 bool legalLoopInstructions();
230 bool legalLoopMemoryAccesses();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000231 bool isLoopAlreadyVisited();
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000232 void setNoAliasToLoop(Loop *VerLoop);
233 bool instructionSafeForVersioning(Instruction *I);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000234};
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000235
236} // end anonymous namespace
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000237
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000238/// \brief Check loop structure and confirms it's good for LoopVersioningLICM.
239bool LoopVersioningLICM::legalLoopStructure() {
Florian Hahn2e032132016-12-19 17:13:37 +0000240 // Loop must be in loop simplify form.
241 if (!CurLoop->isLoopSimplifyForm()) {
242 DEBUG(
243 dbgs() << " loop is not in loop-simplify form.\n");
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000244 return false;
245 }
246 // Loop should be innermost loop, if not return false.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000247 if (!CurLoop->getSubLoops().empty()) {
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000248 DEBUG(dbgs() << " loop is not innermost\n");
249 return false;
250 }
251 // Loop should have a single backedge, if not return false.
252 if (CurLoop->getNumBackEdges() != 1) {
253 DEBUG(dbgs() << " loop has multiple backedges\n");
254 return false;
255 }
256 // Loop must have a single exiting block, if not return false.
257 if (!CurLoop->getExitingBlock()) {
258 DEBUG(dbgs() << " loop has multiple exiting block\n");
259 return false;
260 }
261 // We only handle bottom-tested loop, i.e. loop in which the condition is
262 // checked at the end of each iteration. With that we can assume that all
263 // instructions in the loop are executed the same number of times.
264 if (CurLoop->getExitingBlock() != CurLoop->getLoopLatch()) {
265 DEBUG(dbgs() << " loop is not bottom tested\n");
266 return false;
267 }
268 // Parallel loops must not have aliasing loop-invariant memory accesses.
269 // Hence we don't need to version anything in this case.
270 if (CurLoop->isAnnotatedParallel()) {
271 DEBUG(dbgs() << " Parallel loop is not worth versioning\n");
272 return false;
273 }
274 // Loop depth more then LoopDepthThreshold are not allowed
275 if (CurLoop->getLoopDepth() > LoopDepthThreshold) {
276 DEBUG(dbgs() << " loop depth is more then threshold\n");
277 return false;
278 }
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000279 // We need to be able to compute the loop trip count in order
280 // to generate the bound checks.
281 const SCEV *ExitCount = SE->getBackedgeTakenCount(CurLoop);
282 if (ExitCount == SE->getCouldNotCompute()) {
283 DEBUG(dbgs() << " loop does not has trip count\n");
284 return false;
285 }
286 return true;
287}
288
289/// \brief Check memory accesses in loop and confirms it's good for
290/// LoopVersioningLICM.
291bool LoopVersioningLICM::legalLoopMemoryAccesses() {
292 bool HasMayAlias = false;
293 bool TypeSafety = false;
294 bool HasMod = false;
295 // Memory check:
296 // Transform phase will generate a versioned loop and also a runtime check to
297 // ensure the pointers are independent and they don’t alias.
298 // In version variant of loop, alias meta data asserts that all access are
299 // mutually independent.
300 //
301 // Pointers aliasing in alias domain are avoided because with multiple
302 // aliasing domains we may not be able to hoist potential loop invariant
303 // access out of the loop.
304 //
305 // Iterate over alias tracker sets, and confirm AliasSets doesn't have any
306 // must alias set.
307 for (const auto &I : *CurAST) {
308 const AliasSet &AS = I;
309 // Skip Forward Alias Sets, as this should be ignored as part of
310 // the AliasSetTracker object.
311 if (AS.isForwardingAliasSet())
312 continue;
313 // With MustAlias its not worth adding runtime bound check.
314 if (AS.isMustAlias())
315 return false;
316 Value *SomePtr = AS.begin()->getValue();
317 bool TypeCheck = true;
318 // Check for Mod & MayAlias
319 HasMayAlias |= AS.isMayAlias();
320 HasMod |= AS.isMod();
321 for (const auto &A : AS) {
322 Value *Ptr = A.getValue();
323 // Alias tracker should have pointers of same data type.
324 TypeCheck = (TypeCheck && (SomePtr->getType() == Ptr->getType()));
325 }
326 // At least one alias tracker should have pointers of same data type.
327 TypeSafety |= TypeCheck;
328 }
329 // Ensure types should be of same type.
330 if (!TypeSafety) {
331 DEBUG(dbgs() << " Alias tracker type safety failed!\n");
332 return false;
333 }
334 // Ensure loop body shouldn't be read only.
335 if (!HasMod) {
336 DEBUG(dbgs() << " No memory modified in loop body\n");
337 return false;
338 }
339 // Make sure alias set has may alias case.
340 // If there no alias memory ambiguity, return false.
341 if (!HasMayAlias) {
342 DEBUG(dbgs() << " No ambiguity in memory access.\n");
343 return false;
344 }
345 return true;
346}
347
348/// \brief Check loop instructions safe for Loop versioning.
349/// It returns true if it's safe else returns false.
350/// Consider following:
351/// 1) Check all load store in loop body are non atomic & non volatile.
352/// 2) Check function call safety, by ensuring its not accessing memory.
353/// 3) Loop body shouldn't have any may throw instruction.
354bool LoopVersioningLICM::instructionSafeForVersioning(Instruction *I) {
355 assert(I != nullptr && "Null instruction found!");
356 // Check function call safety
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000357 if (isa<CallInst>(I) && !AA->doesNotAccessMemory(CallSite(I))) {
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000358 DEBUG(dbgs() << " Unsafe call site found.\n");
359 return false;
360 }
361 // Avoid loops with possiblity of throw
362 if (I->mayThrow()) {
363 DEBUG(dbgs() << " May throw instruction found in loop body\n");
364 return false;
365 }
366 // If current instruction is load instructions
367 // make sure it's a simple load (non atomic & non volatile)
368 if (I->mayReadFromMemory()) {
369 LoadInst *Ld = dyn_cast<LoadInst>(I);
370 if (!Ld || !Ld->isSimple()) {
371 DEBUG(dbgs() << " Found a non-simple load.\n");
372 return false;
373 }
374 LoadAndStoreCounter++;
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000375 Value *Ptr = Ld->getPointerOperand();
376 // Check loop invariant.
377 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
378 InvariantCounter++;
379 }
380 // If current instruction is store instruction
381 // make sure it's a simple store (non atomic & non volatile)
382 else if (I->mayWriteToMemory()) {
383 StoreInst *St = dyn_cast<StoreInst>(I);
384 if (!St || !St->isSimple()) {
385 DEBUG(dbgs() << " Found a non-simple store.\n");
386 return false;
387 }
388 LoadAndStoreCounter++;
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000389 Value *Ptr = St->getPointerOperand();
390 // Check loop invariant.
391 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
392 InvariantCounter++;
393
394 IsReadOnlyLoop = false;
395 }
396 return true;
397}
398
399/// \brief Check loop instructions and confirms it's good for
400/// LoopVersioningLICM.
401bool LoopVersioningLICM::legalLoopInstructions() {
402 // Resetting counters.
403 LoadAndStoreCounter = 0;
404 InvariantCounter = 0;
405 IsReadOnlyLoop = true;
406 // Iterate over loop blocks and instructions of each block and check
407 // instruction safety.
408 for (auto *Block : CurLoop->getBlocks())
409 for (auto &Inst : *Block) {
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000410 // If instruction is unsafe just return false.
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000411 if (!instructionSafeForVersioning(&Inst))
412 return false;
413 }
414 // Get LoopAccessInfo from current loop.
Adam Nemeta9f09c62016-06-17 22:35:41 +0000415 LAI = &LAA->getInfo(CurLoop);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000416 // Check LoopAccessInfo for need of runtime check.
417 if (LAI->getRuntimePointerChecking()->getChecks().empty()) {
418 DEBUG(dbgs() << " LAA: Runtime check not found !!\n");
419 return false;
420 }
421 // Number of runtime-checks should be less then RuntimeMemoryCheckThreshold
422 if (LAI->getNumRuntimePointerChecks() >
423 VectorizerParams::RuntimeMemoryCheckThreshold) {
424 DEBUG(dbgs() << " LAA: Runtime checks are more than threshold !!\n");
425 return false;
426 }
427 // Loop should have at least one invariant load or store instruction.
428 if (!InvariantCounter) {
429 DEBUG(dbgs() << " Invariant not found !!\n");
430 return false;
431 }
432 // Read only loop not allowed.
433 if (IsReadOnlyLoop) {
434 DEBUG(dbgs() << " Found a read-only loop!\n");
435 return false;
436 }
437 // Profitablity check:
438 // Check invariant threshold, should be in limit.
439 if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
440 DEBUG(dbgs()
441 << " Invariant load & store are less then defined threshold\n");
442 DEBUG(dbgs() << " Invariant loads & stores: "
443 << ((InvariantCounter * 100) / LoadAndStoreCounter) << "%\n");
444 DEBUG(dbgs() << " Invariant loads & store threshold: "
445 << InvariantThreshold << "%\n");
446 return false;
447 }
448 return true;
449}
450
451/// \brief It checks loop is already visited or not.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000452/// check loop meta data, if loop revisited return true
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000453/// else false.
454bool LoopVersioningLICM::isLoopAlreadyVisited() {
455 // Check LoopVersioningLICM metadata into loop
Adam Nemetf7878262016-04-21 17:33:12 +0000456 if (findStringMetadataForLoop(CurLoop, LICMVersioningMetaData)) {
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000457 return true;
458 }
459 return false;
460}
461
462/// \brief Checks legality for LoopVersioningLICM by considering following:
463/// a) loop structure legality b) loop instruction legality
464/// c) loop memory access legality.
465/// Return true if legal else returns false.
466bool LoopVersioningLICM::isLegalForVersioning() {
467 DEBUG(dbgs() << "Loop: " << *CurLoop);
468 // Make sure not re-visiting same loop again.
469 if (isLoopAlreadyVisited()) {
470 DEBUG(
471 dbgs() << " Revisiting loop in LoopVersioningLICM not allowed.\n\n");
472 return false;
473 }
474 // Check loop structure leagality.
475 if (!legalLoopStructure()) {
476 DEBUG(
477 dbgs() << " Loop structure not suitable for LoopVersioningLICM\n\n");
478 return false;
479 }
480 // Check loop instruction leagality.
481 if (!legalLoopInstructions()) {
482 DEBUG(dbgs()
483 << " Loop instructions not suitable for LoopVersioningLICM\n\n");
484 return false;
485 }
486 // Check loop memory access leagality.
487 if (!legalLoopMemoryAccesses()) {
488 DEBUG(dbgs()
489 << " Loop memory access not suitable for LoopVersioningLICM\n\n");
490 return false;
491 }
492 // Loop versioning is feasible, return true.
493 DEBUG(dbgs() << " Loop Versioning found to be beneficial\n\n");
494 return true;
495}
496
497/// \brief Update loop with aggressive aliasing assumptions.
498/// It marks no-alias to any pairs of memory operations by assuming
499/// loop should not have any must-alias memory accesses pairs.
500/// During LoopVersioningLICM legality we ignore loops having must
501/// aliasing memory accesses.
502void LoopVersioningLICM::setNoAliasToLoop(Loop *VerLoop) {
503 // Get latch terminator instruction.
504 Instruction *I = VerLoop->getLoopLatch()->getTerminator();
505 // Create alias scope domain.
506 MDBuilder MDB(I->getContext());
507 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain("LVDomain");
508 StringRef Name = "LVAliasScope";
509 SmallVector<Metadata *, 4> Scopes, NoAliases;
510 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
511 // Iterate over each instruction of loop.
512 // set no-alias for all load & store instructions.
513 for (auto *Block : CurLoop->getBlocks()) {
514 for (auto &Inst : *Block) {
515 // Only interested in instruction that may modify or read memory.
516 if (!Inst.mayReadFromMemory() && !Inst.mayWriteToMemory())
517 continue;
518 Scopes.push_back(NewScope);
519 NoAliases.push_back(NewScope);
520 // Set no-alias for current instruction.
521 Inst.setMetadata(
522 LLVMContext::MD_noalias,
523 MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_noalias),
524 MDNode::get(Inst.getContext(), NoAliases)));
525 // set alias-scope for current instruction.
526 Inst.setMetadata(
527 LLVMContext::MD_alias_scope,
528 MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_alias_scope),
529 MDNode::get(Inst.getContext(), Scopes)));
530 }
531 }
532}
533
534bool LoopVersioningLICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000535 // This will automatically release all resources hold by the current
536 // LoopVersioningLICM object.
537 AutoResetter Resetter(*this);
538
Andrew Kayloraa641a52016-04-22 22:06:11 +0000539 if (skipLoop(L))
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000540 return false;
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000541 // Get Analysis information.
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000542 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
543 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000544 LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000545 LAI = nullptr;
546 // Set Current Loop
547 CurLoop = L;
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000548 CurAST.reset(new AliasSetTracker(*AA));
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000549
550 // Loop over the body of this loop, construct AST.
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000551 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000552 for (auto *Block : L->getBlocks()) {
553 if (LI->getLoopFor(Block) == L) // Ignore blocks in subloop.
554 CurAST->add(*Block); // Incorporate the specified basic block
555 }
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000556
557 bool Changed = false;
558
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000559 // Check feasiblity of LoopVersioningLICM.
560 // If versioning found to be feasible and beneficial then proceed
561 // else simply return, by cleaning up memory.
562 if (isLegalForVersioning()) {
563 // Do loop versioning.
564 // Create memcheck for memory accessed inside loop.
565 // Clone original loop, and set blocks properly.
Evgeny Astigeevich48fd87e2016-10-14 23:00:36 +0000566 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000567 LoopVersioning LVer(*LAI, CurLoop, LI, DT, SE, true);
568 LVer.versionLoop();
569 // Set Loop Versioning metaData for original loop.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000570 addStringMetadataToLoop(LVer.getNonVersionedLoop(), LICMVersioningMetaData);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000571 // Set Loop Versioning metaData for version loop.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000572 addStringMetadataToLoop(LVer.getVersionedLoop(), LICMVersioningMetaData);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000573 // Set "llvm.mem.parallel_loop_access" metaData to versioned loop.
574 addStringMetadataToLoop(LVer.getVersionedLoop(),
575 "llvm.mem.parallel_loop_access");
576 // Update version loop with aggressive aliasing assumption.
577 setNoAliasToLoop(LVer.getVersionedLoop());
578 Changed = true;
579 }
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000580 return Changed;
581}
582
583char LoopVersioningLICM::ID = 0;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000584
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000585INITIALIZE_PASS_BEGIN(LoopVersioningLICM, "loop-versioning-licm",
586 "Loop Versioning For LICM", false, false)
587INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
588INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
589INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000590INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000591INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000592INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
593INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
594INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000595INITIALIZE_PASS_END(LoopVersioningLICM, "loop-versioning-licm",
596 "Loop Versioning For LICM", false, false)
597
598Pass *llvm::createLoopVersioningLICMPass() { return new LoopVersioningLICM(); }