bd9da14f66931e4835c0f18a9c84a5fb3ed9b68a
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnrollPass.cpp
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
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 pass implements a simple loop unroller.  It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/UnrollLoop.h"
31 #include "llvm/IR/InstVisitor.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include <climits>
34
35 using namespace llvm;
36
37 #define DEBUG_TYPE "loop-unroll"
38
39 static cl::opt<unsigned>
40 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
41   cl::desc("The cut-off point for automatic loop unrolling"));
42
43 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
44     "unroll-max-iteration-count-to-analyze", cl::init(1000), cl::Hidden,
45     cl::desc("Don't allow loop unrolling to simulate more than this number of"
46              "iterations when checking full unroll profitability"));
47
48 static cl::opt<unsigned>
49 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
50   cl::desc("Use this unroll count for all loops including those with "
51            "unroll_count pragma values, for testing purposes"));
52
53 static cl::opt<bool>
54 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
55   cl::desc("Allows loops to be partially unrolled until "
56            "-unroll-threshold loop size is reached."));
57
58 static cl::opt<bool>
59 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
60   cl::desc("Unroll loops with run-time trip counts"));
61
62 static cl::opt<unsigned>
63 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
64   cl::desc("Unrolled size limit for loops with an unroll(full) or "
65            "unroll_count pragma."));
66
67 namespace {
68   class LoopUnroll : public LoopPass {
69   public:
70     static char ID; // Pass ID, replacement for typeid
71     LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
72       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
73       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
74       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
75       CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
76
77       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
78       UserAllowPartial = (P != -1) ||
79                          (UnrollAllowPartial.getNumOccurrences() > 0);
80       UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
81       UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
82
83       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
84     }
85
86     /// A magic value for use with the Threshold parameter to indicate
87     /// that the loop unroll should be performed regardless of how much
88     /// code expansion would result.
89     static const unsigned NoThreshold = UINT_MAX;
90
91     // Threshold to use when optsize is specified (and there is no
92     // explicit -unroll-threshold).
93     static const unsigned OptSizeUnrollThreshold = 50;
94
95     // Default unroll count for loops with run-time trip count if
96     // -unroll-count is not set
97     static const unsigned UnrollRuntimeCount = 8;
98
99     unsigned CurrentCount;
100     unsigned CurrentThreshold;
101     bool     CurrentAllowPartial;
102     bool     CurrentRuntime;
103     bool     UserCount;            // CurrentCount is user-specified.
104     bool     UserThreshold;        // CurrentThreshold is user-specified.
105     bool     UserAllowPartial;     // CurrentAllowPartial is user-specified.
106     bool     UserRuntime;          // CurrentRuntime is user-specified.
107
108     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
109
110     /// This transformation requires natural loop information & requires that
111     /// loop preheaders be inserted into the CFG...
112     ///
113     void getAnalysisUsage(AnalysisUsage &AU) const override {
114       AU.addRequired<AssumptionCacheTracker>();
115       AU.addRequired<LoopInfoWrapperPass>();
116       AU.addPreserved<LoopInfoWrapperPass>();
117       AU.addRequiredID(LoopSimplifyID);
118       AU.addPreservedID(LoopSimplifyID);
119       AU.addRequiredID(LCSSAID);
120       AU.addPreservedID(LCSSAID);
121       AU.addRequired<ScalarEvolution>();
122       AU.addPreserved<ScalarEvolution>();
123       AU.addRequired<TargetTransformInfoWrapperPass>();
124       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
125       // If loop unroll does not preserve dom info then LCSSA pass on next
126       // loop will receive invalid dom info.
127       // For now, recreate dom info, if loop is unrolled.
128       AU.addPreserved<DominatorTreeWrapperPass>();
129     }
130
131     // Fill in the UnrollingPreferences parameter with values from the
132     // TargetTransformationInfo.
133     void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
134                                  TargetTransformInfo::UnrollingPreferences &UP) {
135       UP.Threshold = CurrentThreshold;
136       UP.OptSizeThreshold = OptSizeUnrollThreshold;
137       UP.PartialThreshold = CurrentThreshold;
138       UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
139       UP.Count = CurrentCount;
140       UP.MaxCount = UINT_MAX;
141       UP.Partial = CurrentAllowPartial;
142       UP.Runtime = CurrentRuntime;
143       TTI.getUnrollingPreferences(L, UP);
144     }
145
146     // Select and return an unroll count based on parameters from
147     // user, unroll preferences, unroll pragmas, or a heuristic.
148     // SetExplicitly is set to true if the unroll count is is set by
149     // the user or a pragma rather than selected heuristically.
150     unsigned
151     selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
152                       unsigned PragmaCount,
153                       const TargetTransformInfo::UnrollingPreferences &UP,
154                       bool &SetExplicitly);
155
156     // Select threshold values used to limit unrolling based on a
157     // total unrolled size.  Parameters Threshold and PartialThreshold
158     // are set to the maximum unrolled size for fully and partially
159     // unrolled loops respectively.
160     void selectThresholds(const Loop *L, bool HasPragma,
161                           const TargetTransformInfo::UnrollingPreferences &UP,
162                           unsigned &Threshold, unsigned &PartialThreshold,
163                           unsigned NumberOfSimplifiedInstructions) {
164       // Determine the current unrolling threshold.  While this is
165       // normally set from UnrollThreshold, it is overridden to a
166       // smaller value if the current function is marked as
167       // optimize-for-size, and the unroll threshold was not user
168       // specified.
169       Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
170       PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
171       if (!UserThreshold &&
172           L->getHeader()->getParent()->getAttributes().
173               hasAttribute(AttributeSet::FunctionIndex,
174                            Attribute::OptimizeForSize)) {
175         Threshold = UP.OptSizeThreshold;
176         PartialThreshold = UP.PartialOptSizeThreshold;
177       }
178       if (HasPragma) {
179         // If the loop has an unrolling pragma, we want to be more
180         // aggressive with unrolling limits.  Set thresholds to at
181         // least the PragmaTheshold value which is larger than the
182         // default limits.
183         if (Threshold != NoThreshold)
184           Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
185         if (PartialThreshold != NoThreshold)
186           PartialThreshold =
187               std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
188       }
189       Threshold += NumberOfSimplifiedInstructions;
190     }
191   };
192 }
193
194 char LoopUnroll::ID = 0;
195 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
196 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
197 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
198 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
199 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
200 INITIALIZE_PASS_DEPENDENCY(LCSSA)
201 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
202 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
203
204 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
205                                  int Runtime) {
206   return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
207 }
208
209 Pass *llvm::createSimpleLoopUnrollPass() {
210   return llvm::createLoopUnrollPass(-1, -1, 0, 0);
211 }
212
213 static bool IsLoadFromConstantInitializer(Value *V) {
214   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
215     if (GV->isConstant() && GV->hasDefinitiveInitializer())
216       return GV->getInitializer();
217   return false;
218 }
219
220 struct FindConstantPointers {
221   bool LoadCanBeConstantFolded;
222   bool IndexIsConstant;
223   APInt Step;
224   APInt StartValue;
225   Value *BaseAddress;
226   const Loop *L;
227   ScalarEvolution &SE;
228   FindConstantPointers(const Loop *loop, ScalarEvolution &SE)
229       : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {}
230
231   bool follow(const SCEV *S) {
232     if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) {
233       // We've reached the leaf node of SCEV, it's most probably just a
234       // variable. Now it's time to see if it corresponds to a global constant
235       // global (in which case we can eliminate the load), or not.
236       BaseAddress = SC->getValue();
237       LoadCanBeConstantFolded =
238           IndexIsConstant && IsLoadFromConstantInitializer(BaseAddress);
239       return false;
240     }
241     if (isa<SCEVConstant>(S))
242       return true;
243     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
244       // If the current SCEV expression is AddRec, and its loop isn't the loop
245       // we are about to unroll, then we won't get a constant address after
246       // unrolling, and thus, won't be able to eliminate the load.
247       if (AR->getLoop() != L)
248         return IndexIsConstant = false;
249       // If the step isn't constant, we won't get constant addresses in unrolled
250       // version. Bail out.
251       if (const SCEVConstant *StepSE =
252               dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
253         Step = StepSE->getValue()->getValue();
254       else
255         return IndexIsConstant = false;
256
257       return IndexIsConstant;
258     }
259     // If Result is true, continue traversal.
260     // Otherwise, we have found something that prevents us from (possible) load
261     // elimination.
262     return IndexIsConstant;
263   }
264   bool isDone() const { return !IndexIsConstant; }
265 };
266
267 // This class is used to get an estimate of the optimization effects that we
268 // could get from complete loop unrolling. It comes from the fact that some
269 // loads might be replaced with concrete constant values and that could trigger
270 // a chain of instruction simplifications.
271 //
272 // E.g. we might have:
273 //   int a[] = {0, 1, 0};
274 //   v = 0;
275 //   for (i = 0; i < 3; i ++)
276 //     v += b[i]*a[i];
277 // If we completely unroll the loop, we would get:
278 //   v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
279 // Which then will be simplified to:
280 //   v = b[0]* 0 + b[1]* 1 + b[2]* 0
281 // And finally:
282 //   v = b[1]
283 class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> {
284   typedef InstVisitor<UnrollAnalyzer, bool> Base;
285   friend class InstVisitor<UnrollAnalyzer, bool>;
286
287   const Loop *L;
288   unsigned TripCount;
289   ScalarEvolution &SE;
290   const TargetTransformInfo &TTI;
291   unsigned NumberOfOptimizedInstructions;
292
293   DenseMap<Value *, Constant *> SimplifiedValues;
294   DenseMap<LoadInst *, Value *> LoadBaseAddresses;
295   SmallPtrSet<Instruction *, 32> CountedInsns;
296
297   // Provide base case for our instruction visit.
298   bool visitInstruction(Instruction &I) { return false; };
299   // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt,
300   // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select,
301   // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue.
302   //
303   // Probaly it's worth to hoist the code for estimating the simplifications
304   // effects to a separate class, since we have a very similar code in
305   // InlineCost already.
306   bool visitBinaryOperator(BinaryOperator &I) {
307     Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
308     if (!isa<Constant>(LHS))
309       if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
310         LHS = SimpleLHS;
311     if (!isa<Constant>(RHS))
312       if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
313         RHS = SimpleRHS;
314     Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS);
315
316     if (SimpleV && CountedInsns.insert(&I).second)
317       NumberOfOptimizedInstructions += TTI.getUserCost(&I);
318
319     if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
320       SimplifiedValues[&I] = C;
321       return true;
322     }
323     return false;
324   }
325
326   Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
327     if (!LI)
328       return nullptr;
329     Value *BaseAddr = LoadBaseAddresses[LI];
330     if (!BaseAddr)
331       return nullptr;
332
333     auto GV = dyn_cast<GlobalVariable>(BaseAddr);
334     if (!GV)
335       return nullptr;
336
337     ConstantDataSequential *CDS =
338         dyn_cast<ConstantDataSequential>(GV->getInitializer());
339     if (!CDS)
340       return nullptr;
341
342     const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
343     const SCEV *S = SE.getSCEV(LI->getPointerOperand());
344     const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
345
346     APInt StepC, StartC;
347     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
348     if (!AR)
349       return nullptr;
350
351     if (const SCEVConstant *StepSE =
352             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
353       StepC = StepSE->getValue()->getValue();
354     else
355       return nullptr;
356
357     if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
358       StartC = StartSE->getValue()->getValue();
359     else
360       return nullptr;
361
362     unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
363     unsigned Start = StartC.getLimitedValue();
364     unsigned Step = StepC.getLimitedValue();
365
366     unsigned Index = (Start + Step * Iteration) / ElemSize;
367     if (Index >= CDS->getNumElements())
368       return nullptr;
369
370     Constant *CV = CDS->getElementAsConstant(Index);
371
372     return CV;
373   }
374
375 public:
376   UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
377                  const TargetTransformInfo &TTI)
378       : L(L), TripCount(TripCount), SE(SE), TTI(TTI),
379         NumberOfOptimizedInstructions(0) {}
380
381   // Visit all loads the loop L, and for those that, after complete loop
382   // unrolling, would have a constant address and it will point to a known
383   // constant initializer, record its base address for future use.  It is used
384   // when we estimate number of potentially simplified instructions.
385   void FindConstFoldableLoads() {
386     for (auto BB : L->getBlocks()) {
387       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
388         if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
389           if (!LI->isSimple())
390             continue;
391           Value *AddrOp = LI->getPointerOperand();
392           const SCEV *S = SE.getSCEV(AddrOp);
393           FindConstantPointers Visitor(L, SE);
394           SCEVTraversal<FindConstantPointers> T(Visitor);
395           T.visitAll(S);
396           if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
397             LoadBaseAddresses[LI] = Visitor.BaseAddress;
398           }
399         }
400       }
401     }
402   }
403
404   // Given a list of loads that could be constant-folded (LoadBaseAddresses),
405   // estimate number of optimized instructions after substituting the concrete
406   // values for the given Iteration.
407   // Fill in SimplifiedInsns map for future use in DCE-estimation.
408   unsigned EstimateNumberOfSimplifiedInsns(unsigned Iteration) {
409     SmallVector<Instruction *, 8> Worklist;
410     SimplifiedValues.clear();
411     CountedInsns.clear();
412
413     NumberOfOptimizedInstructions = 0;
414     // We start by adding all loads to the worklist.
415     for (auto LoadDescr : LoadBaseAddresses) {
416       LoadInst *LI = LoadDescr.first;
417       SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
418       if (CountedInsns.insert(LI).second)
419         NumberOfOptimizedInstructions += TTI.getUserCost(LI);
420
421       for (auto U : LI->users()) {
422         Instruction *UI = dyn_cast<Instruction>(U);
423         if (!UI)
424           continue;
425         if (!L->contains(UI))
426           continue;
427         Worklist.push_back(UI);
428       }
429     }
430
431     // And then we try to simplify every user of every instruction from the
432     // worklist. If we do simplify a user, add it to the worklist to process
433     // its users as well.
434     while (!Worklist.empty()) {
435       Instruction *I = Worklist.pop_back_val();
436       if (!visit(I))
437         continue;
438       for (auto U : I->users()) {
439         Instruction *UI = dyn_cast<Instruction>(U);
440         if (!UI)
441           continue;
442         if (!L->contains(UI))
443           continue;
444         Worklist.push_back(UI);
445       }
446     }
447     return NumberOfOptimizedInstructions;
448   }
449
450   // Given a list of potentially simplifed instructions, estimate number of
451   // instructions that would become dead if we do perform the simplification.
452   unsigned EstimateNumberOfDeadInsns() {
453     NumberOfOptimizedInstructions = 0;
454     SmallVector<Instruction *, 8> Worklist;
455     DenseMap<Instruction *, bool> DeadInstructions;
456     // Start by initializing worklist with simplified instructions.
457     for (auto Folded : SimplifiedValues) {
458       if (auto FoldedInsn = dyn_cast<Instruction>(Folded.first)) {
459         Worklist.push_back(FoldedInsn);
460         DeadInstructions[FoldedInsn] = true;
461       }
462     }
463     // If a definition of an insn is only used by simplified or dead
464     // instructions, it's also dead. Check defs of all instructions from the
465     // worklist.
466     while (!Worklist.empty()) {
467       Instruction *FoldedInsn = Worklist.pop_back_val();
468       for (Value *Op : FoldedInsn->operands()) {
469         if (auto I = dyn_cast<Instruction>(Op)) {
470           if (!L->contains(I))
471             continue;
472           if (SimplifiedValues[I])
473             continue; // This insn has been counted already.
474           if (I->getNumUses() == 0)
475             continue;
476           bool AllUsersFolded = true;
477           for (auto U : I->users()) {
478             Instruction *UI = dyn_cast<Instruction>(U);
479             if (!SimplifiedValues[UI] && !DeadInstructions[UI]) {
480               AllUsersFolded = false;
481               break;
482             }
483           }
484           if (AllUsersFolded) {
485             NumberOfOptimizedInstructions += TTI.getUserCost(I);
486             Worklist.push_back(I);
487             DeadInstructions[I] = true;
488           }
489         }
490       }
491     }
492     return NumberOfOptimizedInstructions;
493   }
494 };
495
496 // Complete loop unrolling can make some loads constant, and we need to know if
497 // that would expose any further optimization opportunities.
498 // This routine estimates this optimization effect and returns the number of
499 // instructions, that potentially might be optimized away.
500 static unsigned
501 ApproximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
502                                          unsigned TripCount,
503                                          const TargetTransformInfo &TTI) {
504   if (!TripCount)
505     return 0;
506
507   UnrollAnalyzer UA(L, TripCount, SE, TTI);
508   UA.FindConstFoldableLoads();
509
510   // Estimate number of instructions, that could be simplified if we replace a
511   // load with the corresponding constant. Since the same load will take
512   // different values on different iterations, we have to go through all loop's
513   // iterations here. To limit ourselves here, we check only first N
514   // iterations, and then scale the found number, if necessary.
515   unsigned IterationsNumberForEstimate =
516       std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
517   unsigned NumberOfOptimizedInstructions = 0;
518   for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) {
519     NumberOfOptimizedInstructions += UA.EstimateNumberOfSimplifiedInsns(i);
520     NumberOfOptimizedInstructions += UA.EstimateNumberOfDeadInsns();
521   }
522   NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
523
524   return NumberOfOptimizedInstructions;
525 }
526
527 /// ApproximateLoopSize - Approximate the size of the loop.
528 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
529                                     bool &NotDuplicatable,
530                                     const TargetTransformInfo &TTI,
531                                     AssumptionCache *AC) {
532   SmallPtrSet<const Value *, 32> EphValues;
533   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
534
535   CodeMetrics Metrics;
536   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
537        I != E; ++I)
538     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
539   NumCalls = Metrics.NumInlineCandidates;
540   NotDuplicatable = Metrics.notDuplicatable;
541
542   unsigned LoopSize = Metrics.NumInsts;
543
544   // Don't allow an estimate of size zero.  This would allows unrolling of loops
545   // with huge iteration counts, which is a compile time problem even if it's
546   // not a problem for code quality. Also, the code using this size may assume
547   // that each loop has at least three instructions (likely a conditional
548   // branch, a comparison feeding that branch, and some kind of loop increment
549   // feeding that comparison instruction).
550   LoopSize = std::max(LoopSize, 3u);
551
552   return LoopSize;
553 }
554
555 // Returns the loop hint metadata node with the given name (for example,
556 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
557 // returned.
558 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
559   if (MDNode *LoopID = L->getLoopID())
560     return GetUnrollMetadata(LoopID, Name);
561   return nullptr;
562 }
563
564 // Returns true if the loop has an unroll(full) pragma.
565 static bool HasUnrollFullPragma(const Loop *L) {
566   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
567 }
568
569 // Returns true if the loop has an unroll(disable) pragma.
570 static bool HasUnrollDisablePragma(const Loop *L) {
571   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
572 }
573
574 // If loop has an unroll_count pragma return the (necessarily
575 // positive) value from the pragma.  Otherwise return 0.
576 static unsigned UnrollCountPragmaValue(const Loop *L) {
577   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
578   if (MD) {
579     assert(MD->getNumOperands() == 2 &&
580            "Unroll count hint metadata should have two operands.");
581     unsigned Count =
582         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
583     assert(Count >= 1 && "Unroll count must be positive.");
584     return Count;
585   }
586   return 0;
587 }
588
589 // Remove existing unroll metadata and add unroll disable metadata to
590 // indicate the loop has already been unrolled.  This prevents a loop
591 // from being unrolled more than is directed by a pragma if the loop
592 // unrolling pass is run more than once (which it generally is).
593 static void SetLoopAlreadyUnrolled(Loop *L) {
594   MDNode *LoopID = L->getLoopID();
595   if (!LoopID) return;
596
597   // First remove any existing loop unrolling metadata.
598   SmallVector<Metadata *, 4> MDs;
599   // Reserve first location for self reference to the LoopID metadata node.
600   MDs.push_back(nullptr);
601   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
602     bool IsUnrollMetadata = false;
603     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
604     if (MD) {
605       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
606       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
607     }
608     if (!IsUnrollMetadata)
609       MDs.push_back(LoopID->getOperand(i));
610   }
611
612   // Add unroll(disable) metadata to disable future unrolling.
613   LLVMContext &Context = L->getHeader()->getContext();
614   SmallVector<Metadata *, 1> DisableOperands;
615   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
616   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
617   MDs.push_back(DisableNode);
618
619   MDNode *NewLoopID = MDNode::get(Context, MDs);
620   // Set operand 0 to refer to the loop id itself.
621   NewLoopID->replaceOperandWith(0, NewLoopID);
622   L->setLoopID(NewLoopID);
623 }
624
625 unsigned LoopUnroll::selectUnrollCount(
626     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
627     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
628     bool &SetExplicitly) {
629   SetExplicitly = true;
630
631   // User-specified count (either as a command-line option or
632   // constructor parameter) has highest precedence.
633   unsigned Count = UserCount ? CurrentCount : 0;
634
635   // If there is no user-specified count, unroll pragmas have the next
636   // highest precendence.
637   if (Count == 0) {
638     if (PragmaCount) {
639       Count = PragmaCount;
640     } else if (PragmaFullUnroll) {
641       Count = TripCount;
642     }
643   }
644
645   if (Count == 0)
646     Count = UP.Count;
647
648   if (Count == 0) {
649     SetExplicitly = false;
650     if (TripCount == 0)
651       // Runtime trip count.
652       Count = UnrollRuntimeCount;
653     else
654       // Conservative heuristic: if we know the trip count, see if we can
655       // completely unroll (subject to the threshold, checked below); otherwise
656       // try to find greatest modulo of the trip count which is still under
657       // threshold value.
658       Count = TripCount;
659   }
660   if (TripCount && Count > TripCount)
661     return TripCount;
662   return Count;
663 }
664
665 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
666   if (skipOptnoneFunction(L))
667     return false;
668
669   Function &F = *L->getHeader()->getParent();
670
671   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
672   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
673   const TargetTransformInfo &TTI =
674       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
675   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
676
677   BasicBlock *Header = L->getHeader();
678   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
679         << "] Loop %" << Header->getName() << "\n");
680
681   if (HasUnrollDisablePragma(L)) {
682     return false;
683   }
684   bool PragmaFullUnroll = HasUnrollFullPragma(L);
685   unsigned PragmaCount = UnrollCountPragmaValue(L);
686   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
687
688   TargetTransformInfo::UnrollingPreferences UP;
689   getUnrollingPreferences(L, TTI, UP);
690
691   // Find trip count and trip multiple if count is not available
692   unsigned TripCount = 0;
693   unsigned TripMultiple = 1;
694   // If there are multiple exiting blocks but one of them is the latch, use the
695   // latch for the trip count estimation. Otherwise insist on a single exiting
696   // block for the trip count estimation.
697   BasicBlock *ExitingBlock = L->getLoopLatch();
698   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
699     ExitingBlock = L->getExitingBlock();
700   if (ExitingBlock) {
701     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
702     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
703   }
704
705   // Select an initial unroll count.  This may be reduced later based
706   // on size thresholds.
707   bool CountSetExplicitly;
708   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
709                                      PragmaCount, UP, CountSetExplicitly);
710
711   unsigned NumInlineCandidates;
712   bool notDuplicatable;
713   unsigned LoopSize =
714       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
715   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
716
717   // When computing the unrolled size, note that the conditional branch on the
718   // backedge and the comparison feeding it are not replicated like the rest of
719   // the loop body (which is why 2 is subtracted).
720   uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
721   if (notDuplicatable) {
722     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
723                  << " instructions.\n");
724     return false;
725   }
726   if (NumInlineCandidates != 0) {
727     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
728     return false;
729   }
730
731   unsigned NumberOfOptimizedInstructions =
732       ApproximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
733   DEBUG(dbgs() << "  Complete unrolling could save: "
734                << NumberOfOptimizedInstructions << "\n");
735
736   unsigned Threshold, PartialThreshold;
737   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
738                    NumberOfOptimizedInstructions);
739
740   // Given Count, TripCount and thresholds determine the type of
741   // unrolling which is to be performed.
742   enum { Full = 0, Partial = 1, Runtime = 2 };
743   int Unrolling;
744   if (TripCount && Count == TripCount) {
745     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
746       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
747                    << " because size: " << UnrolledSize << ">" << Threshold
748                    << "\n");
749       Unrolling = Partial;
750     } else {
751       Unrolling = Full;
752     }
753   } else if (TripCount && Count < TripCount) {
754     Unrolling = Partial;
755   } else {
756     Unrolling = Runtime;
757   }
758
759   // Reduce count based on the type of unrolling and the threshold values.
760   unsigned OriginalCount = Count;
761   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
762   if (Unrolling == Partial) {
763     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
764     if (!AllowPartial && !CountSetExplicitly) {
765       DEBUG(dbgs() << "  will not try to unroll partially because "
766                    << "-unroll-allow-partial not given\n");
767       return false;
768     }
769     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
770       // Reduce unroll count to be modulo of TripCount for partial unrolling.
771       Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
772       while (Count != 0 && TripCount % Count != 0)
773         Count--;
774     }
775   } else if (Unrolling == Runtime) {
776     if (!AllowRuntime && !CountSetExplicitly) {
777       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
778                    << "-unroll-runtime not given\n");
779       return false;
780     }
781     // Reduce unroll count to be the largest power-of-two factor of
782     // the original count which satisfies the threshold limit.
783     while (Count != 0 && UnrolledSize > PartialThreshold) {
784       Count >>= 1;
785       UnrolledSize = (LoopSize-2) * Count + 2;
786     }
787     if (Count > UP.MaxCount)
788       Count = UP.MaxCount;
789     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
790   }
791
792   if (HasPragma) {
793     if (PragmaCount != 0)
794       // If loop has an unroll count pragma mark loop as unrolled to prevent
795       // unrolling beyond that requested by the pragma.
796       SetLoopAlreadyUnrolled(L);
797
798     // Emit optimization remarks if we are unable to unroll the loop
799     // as directed by a pragma.
800     DebugLoc LoopLoc = L->getStartLoc();
801     Function *F = Header->getParent();
802     LLVMContext &Ctx = F->getContext();
803     if (PragmaFullUnroll && PragmaCount == 0) {
804       if (TripCount && Count != TripCount) {
805         emitOptimizationRemarkMissed(
806             Ctx, DEBUG_TYPE, *F, LoopLoc,
807             "Unable to fully unroll loop as directed by unroll(full) pragma "
808             "because unrolled size is too large.");
809       } else if (!TripCount) {
810         emitOptimizationRemarkMissed(
811             Ctx, DEBUG_TYPE, *F, LoopLoc,
812             "Unable to fully unroll loop as directed by unroll(full) pragma "
813             "because loop has a runtime trip count.");
814       }
815     } else if (PragmaCount > 0 && Count != OriginalCount) {
816       emitOptimizationRemarkMissed(
817           Ctx, DEBUG_TYPE, *F, LoopLoc,
818           "Unable to unroll loop the number of times directed by "
819           "unroll_count pragma because unrolled size is too large.");
820     }
821   }
822
823   if (Unrolling != Full && Count < 2) {
824     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
825     // of 1 makes sense because loop control can be eliminated.
826     return false;
827   }
828
829   // Unroll the loop.
830   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
831                   &LPM, &AC))
832     return false;
833
834   return true;
835 }