1 //===- LoopUnrollAndJam.cpp - Loop unroll and jam pass --------------------===//
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 pass implements an unroll and jam pass. Most of the work is done by
10 // Utils/UnrollLoopAndJam.cpp.
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/PriorityWorklist.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/CodeMetrics.h"
22 #include "llvm/Analysis/DependenceAnalysis.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopNestAnalysis.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Pass.h"
39 #include "llvm/PassRegistry.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Scalar/LoopPassManager.h"
47 #include "llvm/Transforms/Utils/LoopPeel.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
50 #include <cassert>
51 #include <cstdint>
52
53 namespace llvm {
54 class Instruction;
55 class Value;
56 } // namespace llvm
57
58 using namespace llvm;
59
60 #define DEBUG_TYPE "loop-unroll-and-jam"
61
62 /// @{
63 /// Metadata attribute names
64 static const char *const LLVMLoopUnrollAndJamFollowupAll =
65 "llvm.loop.unroll_and_jam.followup_all";
66 static const char *const LLVMLoopUnrollAndJamFollowupInner =
67 "llvm.loop.unroll_and_jam.followup_inner";
68 static const char *const LLVMLoopUnrollAndJamFollowupOuter =
69 "llvm.loop.unroll_and_jam.followup_outer";
70 static const char *const LLVMLoopUnrollAndJamFollowupRemainderInner =
71 "llvm.loop.unroll_and_jam.followup_remainder_inner";
72 static const char *const LLVMLoopUnrollAndJamFollowupRemainderOuter =
73 "llvm.loop.unroll_and_jam.followup_remainder_outer";
74 /// @}
75
76 static cl::opt<bool>
77 AllowUnrollAndJam("allow-unroll-and-jam", cl::Hidden,
78 cl::desc("Allows loops to be unroll-and-jammed."));
79
80 static cl::opt<unsigned> UnrollAndJamCount(
81 "unroll-and-jam-count", cl::Hidden,
82 cl::desc("Use this unroll count for all loops including those with "
83 "unroll_and_jam_count pragma values, for testing purposes"));
84
85 static cl::opt<unsigned> UnrollAndJamThreshold(
86 "unroll-and-jam-threshold", cl::init(60), cl::Hidden,
87 cl::desc("Threshold to use for inner loop when doing unroll and jam."));
88
89 static cl::opt<unsigned> PragmaUnrollAndJamThreshold(
90 "pragma-unroll-and-jam-threshold", cl::init(1024), cl::Hidden,
91 cl::desc("Unrolled size limit for loops with an unroll_and_jam(full) or "
92 "unroll_count pragma."));
93
94 // Returns the loop hint metadata node with the given name (for example,
95 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
96 // returned.
getUnrollMetadataForLoop(const Loop * L,StringRef Name)97 static MDNode *getUnrollMetadataForLoop(const Loop *L, StringRef Name) {
98 if (MDNode *LoopID = L->getLoopID())
99 return GetUnrollMetadata(LoopID, Name);
100 return nullptr;
101 }
102
103 // Returns true if the loop has any metadata starting with Prefix. For example a
104 // Prefix of "llvm.loop.unroll." returns true if we have any unroll metadata.
hasAnyUnrollPragma(const Loop * L,StringRef Prefix)105 static bool hasAnyUnrollPragma(const Loop *L, StringRef Prefix) {
106 if (MDNode *LoopID = L->getLoopID()) {
107 // First operand should refer to the loop id itself.
108 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
109 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
110
111 for (unsigned I = 1, E = LoopID->getNumOperands(); I < E; ++I) {
112 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(I));
113 if (!MD)
114 continue;
115
116 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
117 if (!S)
118 continue;
119
120 if (S->getString().startswith(Prefix))
121 return true;
122 }
123 }
124 return false;
125 }
126
127 // Returns true if the loop has an unroll_and_jam(enable) pragma.
hasUnrollAndJamEnablePragma(const Loop * L)128 static bool hasUnrollAndJamEnablePragma(const Loop *L) {
129 return getUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.enable");
130 }
131
132 // If loop has an unroll_and_jam_count pragma return the (necessarily
133 // positive) value from the pragma. Otherwise return 0.
unrollAndJamCountPragmaValue(const Loop * L)134 static unsigned unrollAndJamCountPragmaValue(const Loop *L) {
135 MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll_and_jam.count");
136 if (MD) {
137 assert(MD->getNumOperands() == 2 &&
138 "Unroll count hint metadata should have two operands.");
139 unsigned Count =
140 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
141 assert(Count >= 1 && "Unroll count must be positive.");
142 return Count;
143 }
144 return 0;
145 }
146
147 // Returns loop size estimation for unrolled loop.
148 static uint64_t
getUnrollAndJammedLoopSize(unsigned LoopSize,TargetTransformInfo::UnrollingPreferences & UP)149 getUnrollAndJammedLoopSize(unsigned LoopSize,
150 TargetTransformInfo::UnrollingPreferences &UP) {
151 assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
152 return static_cast<uint64_t>(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
153 }
154
155 // Calculates unroll and jam count and writes it to UP.Count. Returns true if
156 // unroll count was set explicitly.
computeUnrollAndJamCount(Loop * L,Loop * SubLoop,const TargetTransformInfo & TTI,DominatorTree & DT,LoopInfo * LI,ScalarEvolution & SE,const SmallPtrSetImpl<const Value * > & EphValues,OptimizationRemarkEmitter * ORE,unsigned OuterTripCount,unsigned OuterTripMultiple,unsigned OuterLoopSize,unsigned InnerTripCount,unsigned InnerLoopSize,TargetTransformInfo::UnrollingPreferences & UP,TargetTransformInfo::PeelingPreferences & PP)157 static bool computeUnrollAndJamCount(
158 Loop *L, Loop *SubLoop, const TargetTransformInfo &TTI, DominatorTree &DT,
159 LoopInfo *LI, ScalarEvolution &SE,
160 const SmallPtrSetImpl<const Value *> &EphValues,
161 OptimizationRemarkEmitter *ORE, unsigned OuterTripCount,
162 unsigned OuterTripMultiple, unsigned OuterLoopSize, unsigned InnerTripCount,
163 unsigned InnerLoopSize, TargetTransformInfo::UnrollingPreferences &UP,
164 TargetTransformInfo::PeelingPreferences &PP) {
165 // First up use computeUnrollCount from the loop unroller to get a count
166 // for unrolling the outer loop, plus any loops requiring explicit
167 // unrolling we leave to the unroller. This uses UP.Threshold /
168 // UP.PartialThreshold / UP.MaxCount to come up with sensible loop values.
169 // We have already checked that the loop has no unroll.* pragmas.
170 unsigned MaxTripCount = 0;
171 bool UseUpperBound = false;
172 bool ExplicitUnroll = computeUnrollCount(
173 L, TTI, DT, LI, SE, EphValues, ORE, OuterTripCount, MaxTripCount,
174 /*MaxOrZero*/ false, OuterTripMultiple, OuterLoopSize, UP, PP,
175 UseUpperBound);
176 if (ExplicitUnroll || UseUpperBound) {
177 // If the user explicitly set the loop as unrolled, dont UnJ it. Leave it
178 // for the unroller instead.
179 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; explicit count set by "
180 "computeUnrollCount\n");
181 UP.Count = 0;
182 return false;
183 }
184
185 // Override with any explicit Count from the "unroll-and-jam-count" option.
186 bool UserUnrollCount = UnrollAndJamCount.getNumOccurrences() > 0;
187 if (UserUnrollCount) {
188 UP.Count = UnrollAndJamCount;
189 UP.Force = true;
190 if (UP.AllowRemainder &&
191 getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
192 getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
193 UP.UnrollAndJamInnerLoopThreshold)
194 return true;
195 }
196
197 // Check for unroll_and_jam pragmas
198 unsigned PragmaCount = unrollAndJamCountPragmaValue(L);
199 if (PragmaCount > 0) {
200 UP.Count = PragmaCount;
201 UP.Runtime = true;
202 UP.Force = true;
203 if ((UP.AllowRemainder || (OuterTripMultiple % PragmaCount == 0)) &&
204 getUnrollAndJammedLoopSize(OuterLoopSize, UP) < UP.Threshold &&
205 getUnrollAndJammedLoopSize(InnerLoopSize, UP) <
206 UP.UnrollAndJamInnerLoopThreshold)
207 return true;
208 }
209
210 bool PragmaEnableUnroll = hasUnrollAndJamEnablePragma(L);
211 bool ExplicitUnrollAndJamCount = PragmaCount > 0 || UserUnrollCount;
212 bool ExplicitUnrollAndJam = PragmaEnableUnroll || ExplicitUnrollAndJamCount;
213
214 // If the loop has an unrolling pragma, we want to be more aggressive with
215 // unrolling limits.
216 if (ExplicitUnrollAndJam)
217 UP.UnrollAndJamInnerLoopThreshold = PragmaUnrollAndJamThreshold;
218
219 if (!UP.AllowRemainder && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
220 UP.UnrollAndJamInnerLoopThreshold) {
221 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't create remainder and "
222 "inner loop too large\n");
223 UP.Count = 0;
224 return false;
225 }
226
227 // We have a sensible limit for the outer loop, now adjust it for the inner
228 // loop and UP.UnrollAndJamInnerLoopThreshold. If the outer limit was set
229 // explicitly, we want to stick to it.
230 if (!ExplicitUnrollAndJamCount && UP.AllowRemainder) {
231 while (UP.Count != 0 && getUnrollAndJammedLoopSize(InnerLoopSize, UP) >=
232 UP.UnrollAndJamInnerLoopThreshold)
233 UP.Count--;
234 }
235
236 // If we are explicitly unroll and jamming, we are done. Otherwise there are a
237 // number of extra performance heuristics to check.
238 if (ExplicitUnrollAndJam)
239 return true;
240
241 // If the inner loop count is known and small, leave the entire loop nest to
242 // be the unroller
243 if (InnerTripCount && InnerLoopSize * InnerTripCount < UP.Threshold) {
244 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; small inner loop count is "
245 "being left for the unroller\n");
246 UP.Count = 0;
247 return false;
248 }
249
250 // Check for situations where UnJ is likely to be unprofitable. Including
251 // subloops with more than 1 block.
252 if (SubLoop->getBlocks().size() != 1) {
253 LLVM_DEBUG(
254 dbgs() << "Won't unroll-and-jam; More than one inner loop block\n");
255 UP.Count = 0;
256 return false;
257 }
258
259 // Limit to loops where there is something to gain from unrolling and
260 // jamming the loop. In this case, look for loads that are invariant in the
261 // outer loop and can become shared.
262 unsigned NumInvariant = 0;
263 for (BasicBlock *BB : SubLoop->getBlocks()) {
264 for (Instruction &I : *BB) {
265 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
266 Value *V = Ld->getPointerOperand();
267 const SCEV *LSCEV = SE.getSCEVAtScope(V, L);
268 if (SE.isLoopInvariant(LSCEV, L))
269 NumInvariant++;
270 }
271 }
272 }
273 if (NumInvariant == 0) {
274 LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; No loop invariant loads\n");
275 UP.Count = 0;
276 return false;
277 }
278
279 return false;
280 }
281
282 static LoopUnrollResult
tryToUnrollAndJamLoop(Loop * L,DominatorTree & DT,LoopInfo * LI,ScalarEvolution & SE,const TargetTransformInfo & TTI,AssumptionCache & AC,DependenceInfo & DI,OptimizationRemarkEmitter & ORE,int OptLevel)283 tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
284 ScalarEvolution &SE, const TargetTransformInfo &TTI,
285 AssumptionCache &AC, DependenceInfo &DI,
286 OptimizationRemarkEmitter &ORE, int OptLevel) {
287 TargetTransformInfo::UnrollingPreferences UP =
288 gatherUnrollingPreferences(L, SE, TTI, nullptr, nullptr, ORE, OptLevel,
289 None, None, None, None, None, None);
290 TargetTransformInfo::PeelingPreferences PP =
291 gatherPeelingPreferences(L, SE, TTI, None, None);
292
293 TransformationMode EnableMode = hasUnrollAndJamTransformation(L);
294 if (EnableMode & TM_Disable)
295 return LoopUnrollResult::Unmodified;
296 if (EnableMode & TM_ForcedByUser)
297 UP.UnrollAndJam = true;
298
299 if (AllowUnrollAndJam.getNumOccurrences() > 0)
300 UP.UnrollAndJam = AllowUnrollAndJam;
301 if (UnrollAndJamThreshold.getNumOccurrences() > 0)
302 UP.UnrollAndJamInnerLoopThreshold = UnrollAndJamThreshold;
303 // Exit early if unrolling is disabled.
304 if (!UP.UnrollAndJam || UP.UnrollAndJamInnerLoopThreshold == 0)
305 return LoopUnrollResult::Unmodified;
306
307 LLVM_DEBUG(dbgs() << "Loop Unroll and Jam: F["
308 << L->getHeader()->getParent()->getName() << "] Loop %"
309 << L->getHeader()->getName() << "\n");
310
311 // A loop with any unroll pragma (enabling/disabling/count/etc) is left for
312 // the unroller, so long as it does not explicitly have unroll_and_jam
313 // metadata. This means #pragma nounroll will disable unroll and jam as well
314 // as unrolling
315 if (hasAnyUnrollPragma(L, "llvm.loop.unroll.") &&
316 !hasAnyUnrollPragma(L, "llvm.loop.unroll_and_jam.")) {
317 LLVM_DEBUG(dbgs() << " Disabled due to pragma.\n");
318 return LoopUnrollResult::Unmodified;
319 }
320
321 if (!isSafeToUnrollAndJam(L, SE, DT, DI, *LI)) {
322 LLVM_DEBUG(dbgs() << " Disabled due to not being safe.\n");
323 return LoopUnrollResult::Unmodified;
324 }
325
326 // Approximate the loop size and collect useful info
327 unsigned NumInlineCandidates;
328 bool NotDuplicatable;
329 bool Convergent;
330 SmallPtrSet<const Value *, 32> EphValues;
331 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
332 Loop *SubLoop = L->getSubLoops()[0];
333 InstructionCost InnerLoopSizeIC =
334 ApproximateLoopSize(SubLoop, NumInlineCandidates, NotDuplicatable,
335 Convergent, TTI, EphValues, UP.BEInsns);
336 InstructionCost OuterLoopSizeIC =
337 ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
338 TTI, EphValues, UP.BEInsns);
339 LLVM_DEBUG(dbgs() << " Outer Loop Size: " << OuterLoopSizeIC << "\n");
340 LLVM_DEBUG(dbgs() << " Inner Loop Size: " << InnerLoopSizeIC << "\n");
341
342 if (!InnerLoopSizeIC.isValid() || !OuterLoopSizeIC.isValid()) {
343 LLVM_DEBUG(dbgs() << " Not unrolling loop which contains instructions"
344 << " with invalid cost.\n");
345 return LoopUnrollResult::Unmodified;
346 }
347 unsigned InnerLoopSize = *InnerLoopSizeIC.getValue();
348 unsigned OuterLoopSize = *OuterLoopSizeIC.getValue();
349
350 if (NotDuplicatable) {
351 LLVM_DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable "
352 "instructions.\n");
353 return LoopUnrollResult::Unmodified;
354 }
355 if (NumInlineCandidates != 0) {
356 LLVM_DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
357 return LoopUnrollResult::Unmodified;
358 }
359 if (Convergent) {
360 LLVM_DEBUG(
361 dbgs() << " Not unrolling loop with convergent instructions.\n");
362 return LoopUnrollResult::Unmodified;
363 }
364
365 // Save original loop IDs for after the transformation.
366 MDNode *OrigOuterLoopID = L->getLoopID();
367 MDNode *OrigSubLoopID = SubLoop->getLoopID();
368
369 // To assign the loop id of the epilogue, assign it before unrolling it so it
370 // is applied to every inner loop of the epilogue. We later apply the loop ID
371 // for the jammed inner loop.
372 Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
373 OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
374 LLVMLoopUnrollAndJamFollowupRemainderInner});
375 if (NewInnerEpilogueLoopID)
376 SubLoop->setLoopID(NewInnerEpilogueLoopID.value());
377
378 // Find trip count and trip multiple
379 BasicBlock *Latch = L->getLoopLatch();
380 BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
381 unsigned OuterTripCount = SE.getSmallConstantTripCount(L, Latch);
382 unsigned OuterTripMultiple = SE.getSmallConstantTripMultiple(L, Latch);
383 unsigned InnerTripCount = SE.getSmallConstantTripCount(SubLoop, SubLoopLatch);
384
385 // Decide if, and by how much, to unroll
386 bool IsCountSetExplicitly = computeUnrollAndJamCount(
387 L, SubLoop, TTI, DT, LI, SE, EphValues, &ORE, OuterTripCount,
388 OuterTripMultiple, OuterLoopSize, InnerTripCount, InnerLoopSize, UP, PP);
389 if (UP.Count <= 1)
390 return LoopUnrollResult::Unmodified;
391 // Unroll factor (Count) must be less or equal to TripCount.
392 if (OuterTripCount && UP.Count > OuterTripCount)
393 UP.Count = OuterTripCount;
394
395 Loop *EpilogueOuterLoop = nullptr;
396 LoopUnrollResult UnrollResult = UnrollAndJamLoop(
397 L, UP.Count, OuterTripCount, OuterTripMultiple, UP.UnrollRemainder, LI,
398 &SE, &DT, &AC, &TTI, &ORE, &EpilogueOuterLoop);
399
400 // Assign new loop attributes.
401 if (EpilogueOuterLoop) {
402 Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
403 OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
404 LLVMLoopUnrollAndJamFollowupRemainderOuter});
405 if (NewOuterEpilogueLoopID)
406 EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.value());
407 }
408
409 Optional<MDNode *> NewInnerLoopID =
410 makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
411 LLVMLoopUnrollAndJamFollowupInner});
412 if (NewInnerLoopID)
413 SubLoop->setLoopID(NewInnerLoopID.value());
414 else
415 SubLoop->setLoopID(OrigSubLoopID);
416
417 if (UnrollResult == LoopUnrollResult::PartiallyUnrolled) {
418 Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
419 OrigOuterLoopID,
420 {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
421 if (NewOuterLoopID) {
422 L->setLoopID(NewOuterLoopID.value());
423
424 // Do not setLoopAlreadyUnrolled if a followup was given.
425 return UnrollResult;
426 }
427 }
428
429 // If loop has an unroll count pragma or unrolled by explicitly set count
430 // mark loop as unrolled to prevent unrolling beyond that requested.
431 if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly)
432 L->setLoopAlreadyUnrolled();
433
434 return UnrollResult;
435 }
436
tryToUnrollAndJamLoop(LoopNest & LN,DominatorTree & DT,LoopInfo & LI,ScalarEvolution & SE,const TargetTransformInfo & TTI,AssumptionCache & AC,DependenceInfo & DI,OptimizationRemarkEmitter & ORE,int OptLevel,LPMUpdater & U)437 static bool tryToUnrollAndJamLoop(LoopNest &LN, DominatorTree &DT, LoopInfo &LI,
438 ScalarEvolution &SE,
439 const TargetTransformInfo &TTI,
440 AssumptionCache &AC, DependenceInfo &DI,
441 OptimizationRemarkEmitter &ORE, int OptLevel,
442 LPMUpdater &U) {
443 bool DidSomething = false;
444 ArrayRef<Loop *> Loops = LN.getLoops();
445 Loop *OutmostLoop = &LN.getOutermostLoop();
446
447 // Add the loop nests in the reverse order of LN. See method
448 // declaration.
449 SmallPriorityWorklist<Loop *, 4> Worklist;
450 appendLoopsToWorklist(Loops, Worklist);
451 while (!Worklist.empty()) {
452 Loop *L = Worklist.pop_back_val();
453 std::string LoopName = std::string(L->getName());
454 LoopUnrollResult Result =
455 tryToUnrollAndJamLoop(L, DT, &LI, SE, TTI, AC, DI, ORE, OptLevel);
456 if (Result != LoopUnrollResult::Unmodified)
457 DidSomething = true;
458 if (L == OutmostLoop && Result == LoopUnrollResult::FullyUnrolled)
459 U.markLoopAsDeleted(*L, LoopName);
460 }
461
462 return DidSomething;
463 }
464
465 namespace {
466
467 class LoopUnrollAndJam : public LoopPass {
468 public:
469 static char ID; // Pass ID, replacement for typeid
470 unsigned OptLevel;
471
LoopUnrollAndJam(int OptLevel=2)472 LoopUnrollAndJam(int OptLevel = 2) : LoopPass(ID), OptLevel(OptLevel) {
473 initializeLoopUnrollAndJamPass(*PassRegistry::getPassRegistry());
474 }
475
runOnLoop(Loop * L,LPPassManager & LPM)476 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
477 if (skipLoop(L))
478 return false;
479
480 auto *F = L->getHeader()->getParent();
481 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
482 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
483 auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
484 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
485 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F);
486 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
487 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
488
489 LoopUnrollResult Result =
490 tryToUnrollAndJamLoop(L, DT, LI, SE, TTI, AC, DI, ORE, OptLevel);
491
492 if (Result == LoopUnrollResult::FullyUnrolled)
493 LPM.markLoopAsDeleted(*L);
494
495 return Result != LoopUnrollResult::Unmodified;
496 }
497
498 /// This transformation requires natural loop information & requires that
499 /// loop preheaders be inserted into the CFG...
getAnalysisUsage(AnalysisUsage & AU) const500 void getAnalysisUsage(AnalysisUsage &AU) const override {
501 AU.addRequired<DominatorTreeWrapperPass>();
502 AU.addRequired<LoopInfoWrapperPass>();
503 AU.addRequired<ScalarEvolutionWrapperPass>();
504 AU.addRequired<TargetTransformInfoWrapperPass>();
505 AU.addRequired<AssumptionCacheTracker>();
506 AU.addRequired<DependenceAnalysisWrapperPass>();
507 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
508 getLoopAnalysisUsage(AU);
509 }
510 };
511
512 } // end anonymous namespace
513
514 char LoopUnrollAndJam::ID = 0;
515
516 INITIALIZE_PASS_BEGIN(LoopUnrollAndJam, "loop-unroll-and-jam",
517 "Unroll and Jam loops", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)518 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
519 INITIALIZE_PASS_DEPENDENCY(LoopPass)
520 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
521 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
522 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
523 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
524 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
525 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
526 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
527 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
528 INITIALIZE_PASS_END(LoopUnrollAndJam, "loop-unroll-and-jam",
529 "Unroll and Jam loops", false, false)
530
531 Pass *llvm::createLoopUnrollAndJamPass(int OptLevel) {
532 return new LoopUnrollAndJam(OptLevel);
533 }
534
run(LoopNest & LN,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)535 PreservedAnalyses LoopUnrollAndJamPass::run(LoopNest &LN,
536 LoopAnalysisManager &AM,
537 LoopStandardAnalysisResults &AR,
538 LPMUpdater &U) {
539 Function &F = *LN.getParent();
540
541 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
542 OptimizationRemarkEmitter ORE(&F);
543
544 if (!tryToUnrollAndJamLoop(LN, AR.DT, AR.LI, AR.SE, AR.TTI, AR.AC, DI, ORE,
545 OptLevel, U))
546 return PreservedAnalyses::all();
547
548 auto PA = getLoopPassPreservedAnalyses();
549 PA.preserve<LoopNestAnalysis>();
550 return PA;
551 }
552