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