[InstSimplify] Add SimplifyFPBinOp function.
[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 = nullptr;
315     if (auto FI = dyn_cast<FPMathOperator>(&I))
316       SimpleV =
317           SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags());
318     else
319       SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS);
320
321     if (SimpleV && CountedInsns.insert(&I).second)
322       NumberOfOptimizedInstructions += TTI.getUserCost(&I);
323
324     if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
325       SimplifiedValues[&I] = C;
326       return true;
327     }
328     return false;
329   }
330
331   Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) {
332     if (!LI)
333       return nullptr;
334     Value *BaseAddr = LoadBaseAddresses[LI];
335     if (!BaseAddr)
336       return nullptr;
337
338     auto GV = dyn_cast<GlobalVariable>(BaseAddr);
339     if (!GV)
340       return nullptr;
341
342     ConstantDataSequential *CDS =
343         dyn_cast<ConstantDataSequential>(GV->getInitializer());
344     if (!CDS)
345       return nullptr;
346
347     const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr);
348     const SCEV *S = SE.getSCEV(LI->getPointerOperand());
349     const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE);
350
351     APInt StepC, StartC;
352     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE);
353     if (!AR)
354       return nullptr;
355
356     if (const SCEVConstant *StepSE =
357             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
358       StepC = StepSE->getValue()->getValue();
359     else
360       return nullptr;
361
362     if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()))
363       StartC = StartSE->getValue()->getValue();
364     else
365       return nullptr;
366
367     unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
368     unsigned Start = StartC.getLimitedValue();
369     unsigned Step = StepC.getLimitedValue();
370
371     unsigned Index = (Start + Step * Iteration) / ElemSize;
372     if (Index >= CDS->getNumElements())
373       return nullptr;
374
375     Constant *CV = CDS->getElementAsConstant(Index);
376
377     return CV;
378   }
379
380 public:
381   UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
382                  const TargetTransformInfo &TTI)
383       : L(L), TripCount(TripCount), SE(SE), TTI(TTI),
384         NumberOfOptimizedInstructions(0) {}
385
386   // Visit all loads the loop L, and for those that, after complete loop
387   // unrolling, would have a constant address and it will point to a known
388   // constant initializer, record its base address for future use.  It is used
389   // when we estimate number of potentially simplified instructions.
390   void FindConstFoldableLoads() {
391     for (auto BB : L->getBlocks()) {
392       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
393         if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
394           if (!LI->isSimple())
395             continue;
396           Value *AddrOp = LI->getPointerOperand();
397           const SCEV *S = SE.getSCEV(AddrOp);
398           FindConstantPointers Visitor(L, SE);
399           SCEVTraversal<FindConstantPointers> T(Visitor);
400           T.visitAll(S);
401           if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) {
402             LoadBaseAddresses[LI] = Visitor.BaseAddress;
403           }
404         }
405       }
406     }
407   }
408
409   // Given a list of loads that could be constant-folded (LoadBaseAddresses),
410   // estimate number of optimized instructions after substituting the concrete
411   // values for the given Iteration.
412   // Fill in SimplifiedInsns map for future use in DCE-estimation.
413   unsigned EstimateNumberOfSimplifiedInsns(unsigned Iteration) {
414     SmallVector<Instruction *, 8> Worklist;
415     SimplifiedValues.clear();
416     CountedInsns.clear();
417
418     NumberOfOptimizedInstructions = 0;
419     // We start by adding all loads to the worklist.
420     for (auto LoadDescr : LoadBaseAddresses) {
421       LoadInst *LI = LoadDescr.first;
422       SimplifiedValues[LI] = computeLoadValue(LI, Iteration);
423       if (CountedInsns.insert(LI).second)
424         NumberOfOptimizedInstructions += TTI.getUserCost(LI);
425
426       for (auto U : LI->users()) {
427         Instruction *UI = dyn_cast<Instruction>(U);
428         if (!UI)
429           continue;
430         if (!L->contains(UI))
431           continue;
432         Worklist.push_back(UI);
433       }
434     }
435
436     // And then we try to simplify every user of every instruction from the
437     // worklist. If we do simplify a user, add it to the worklist to process
438     // its users as well.
439     while (!Worklist.empty()) {
440       Instruction *I = Worklist.pop_back_val();
441       if (!visit(I))
442         continue;
443       for (auto U : I->users()) {
444         Instruction *UI = dyn_cast<Instruction>(U);
445         if (!UI)
446           continue;
447         if (!L->contains(UI))
448           continue;
449         Worklist.push_back(UI);
450       }
451     }
452     return NumberOfOptimizedInstructions;
453   }
454
455   // Given a list of potentially simplifed instructions, estimate number of
456   // instructions that would become dead if we do perform the simplification.
457   unsigned EstimateNumberOfDeadInsns() {
458     NumberOfOptimizedInstructions = 0;
459     SmallVector<Instruction *, 8> Worklist;
460     DenseMap<Instruction *, bool> DeadInstructions;
461     // Start by initializing worklist with simplified instructions.
462     for (auto Folded : SimplifiedValues) {
463       if (auto FoldedInsn = dyn_cast<Instruction>(Folded.first)) {
464         Worklist.push_back(FoldedInsn);
465         DeadInstructions[FoldedInsn] = true;
466       }
467     }
468     // If a definition of an insn is only used by simplified or dead
469     // instructions, it's also dead. Check defs of all instructions from the
470     // worklist.
471     while (!Worklist.empty()) {
472       Instruction *FoldedInsn = Worklist.pop_back_val();
473       for (Value *Op : FoldedInsn->operands()) {
474         if (auto I = dyn_cast<Instruction>(Op)) {
475           if (!L->contains(I))
476             continue;
477           if (SimplifiedValues[I])
478             continue; // This insn has been counted already.
479           if (I->getNumUses() == 0)
480             continue;
481           bool AllUsersFolded = true;
482           for (auto U : I->users()) {
483             Instruction *UI = dyn_cast<Instruction>(U);
484             if (!SimplifiedValues[UI] && !DeadInstructions[UI]) {
485               AllUsersFolded = false;
486               break;
487             }
488           }
489           if (AllUsersFolded) {
490             NumberOfOptimizedInstructions += TTI.getUserCost(I);
491             Worklist.push_back(I);
492             DeadInstructions[I] = true;
493           }
494         }
495       }
496     }
497     return NumberOfOptimizedInstructions;
498   }
499 };
500
501 // Complete loop unrolling can make some loads constant, and we need to know if
502 // that would expose any further optimization opportunities.
503 // This routine estimates this optimization effect and returns the number of
504 // instructions, that potentially might be optimized away.
505 static unsigned
506 ApproximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE,
507                                          unsigned TripCount,
508                                          const TargetTransformInfo &TTI) {
509   if (!TripCount)
510     return 0;
511
512   UnrollAnalyzer UA(L, TripCount, SE, TTI);
513   UA.FindConstFoldableLoads();
514
515   // Estimate number of instructions, that could be simplified if we replace a
516   // load with the corresponding constant. Since the same load will take
517   // different values on different iterations, we have to go through all loop's
518   // iterations here. To limit ourselves here, we check only first N
519   // iterations, and then scale the found number, if necessary.
520   unsigned IterationsNumberForEstimate =
521       std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount);
522   unsigned NumberOfOptimizedInstructions = 0;
523   for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) {
524     NumberOfOptimizedInstructions += UA.EstimateNumberOfSimplifiedInsns(i);
525     NumberOfOptimizedInstructions += UA.EstimateNumberOfDeadInsns();
526   }
527   NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate;
528
529   return NumberOfOptimizedInstructions;
530 }
531
532 /// ApproximateLoopSize - Approximate the size of the loop.
533 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
534                                     bool &NotDuplicatable,
535                                     const TargetTransformInfo &TTI,
536                                     AssumptionCache *AC) {
537   SmallPtrSet<const Value *, 32> EphValues;
538   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
539
540   CodeMetrics Metrics;
541   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
542        I != E; ++I)
543     Metrics.analyzeBasicBlock(*I, TTI, EphValues);
544   NumCalls = Metrics.NumInlineCandidates;
545   NotDuplicatable = Metrics.notDuplicatable;
546
547   unsigned LoopSize = Metrics.NumInsts;
548
549   // Don't allow an estimate of size zero.  This would allows unrolling of loops
550   // with huge iteration counts, which is a compile time problem even if it's
551   // not a problem for code quality. Also, the code using this size may assume
552   // that each loop has at least three instructions (likely a conditional
553   // branch, a comparison feeding that branch, and some kind of loop increment
554   // feeding that comparison instruction).
555   LoopSize = std::max(LoopSize, 3u);
556
557   return LoopSize;
558 }
559
560 // Returns the loop hint metadata node with the given name (for example,
561 // "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
562 // returned.
563 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
564   if (MDNode *LoopID = L->getLoopID())
565     return GetUnrollMetadata(LoopID, Name);
566   return nullptr;
567 }
568
569 // Returns true if the loop has an unroll(full) pragma.
570 static bool HasUnrollFullPragma(const Loop *L) {
571   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
572 }
573
574 // Returns true if the loop has an unroll(disable) pragma.
575 static bool HasUnrollDisablePragma(const Loop *L) {
576   return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
577 }
578
579 // If loop has an unroll_count pragma return the (necessarily
580 // positive) value from the pragma.  Otherwise return 0.
581 static unsigned UnrollCountPragmaValue(const Loop *L) {
582   MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
583   if (MD) {
584     assert(MD->getNumOperands() == 2 &&
585            "Unroll count hint metadata should have two operands.");
586     unsigned Count =
587         mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
588     assert(Count >= 1 && "Unroll count must be positive.");
589     return Count;
590   }
591   return 0;
592 }
593
594 // Remove existing unroll metadata and add unroll disable metadata to
595 // indicate the loop has already been unrolled.  This prevents a loop
596 // from being unrolled more than is directed by a pragma if the loop
597 // unrolling pass is run more than once (which it generally is).
598 static void SetLoopAlreadyUnrolled(Loop *L) {
599   MDNode *LoopID = L->getLoopID();
600   if (!LoopID) return;
601
602   // First remove any existing loop unrolling metadata.
603   SmallVector<Metadata *, 4> MDs;
604   // Reserve first location for self reference to the LoopID metadata node.
605   MDs.push_back(nullptr);
606   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
607     bool IsUnrollMetadata = false;
608     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
609     if (MD) {
610       const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
611       IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
612     }
613     if (!IsUnrollMetadata)
614       MDs.push_back(LoopID->getOperand(i));
615   }
616
617   // Add unroll(disable) metadata to disable future unrolling.
618   LLVMContext &Context = L->getHeader()->getContext();
619   SmallVector<Metadata *, 1> DisableOperands;
620   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
621   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
622   MDs.push_back(DisableNode);
623
624   MDNode *NewLoopID = MDNode::get(Context, MDs);
625   // Set operand 0 to refer to the loop id itself.
626   NewLoopID->replaceOperandWith(0, NewLoopID);
627   L->setLoopID(NewLoopID);
628 }
629
630 unsigned LoopUnroll::selectUnrollCount(
631     const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
632     unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
633     bool &SetExplicitly) {
634   SetExplicitly = true;
635
636   // User-specified count (either as a command-line option or
637   // constructor parameter) has highest precedence.
638   unsigned Count = UserCount ? CurrentCount : 0;
639
640   // If there is no user-specified count, unroll pragmas have the next
641   // highest precendence.
642   if (Count == 0) {
643     if (PragmaCount) {
644       Count = PragmaCount;
645     } else if (PragmaFullUnroll) {
646       Count = TripCount;
647     }
648   }
649
650   if (Count == 0)
651     Count = UP.Count;
652
653   if (Count == 0) {
654     SetExplicitly = false;
655     if (TripCount == 0)
656       // Runtime trip count.
657       Count = UnrollRuntimeCount;
658     else
659       // Conservative heuristic: if we know the trip count, see if we can
660       // completely unroll (subject to the threshold, checked below); otherwise
661       // try to find greatest modulo of the trip count which is still under
662       // threshold value.
663       Count = TripCount;
664   }
665   if (TripCount && Count > TripCount)
666     return TripCount;
667   return Count;
668 }
669
670 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
671   if (skipOptnoneFunction(L))
672     return false;
673
674   Function &F = *L->getHeader()->getParent();
675
676   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
677   ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
678   const TargetTransformInfo &TTI =
679       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
680   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
681
682   BasicBlock *Header = L->getHeader();
683   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
684         << "] Loop %" << Header->getName() << "\n");
685
686   if (HasUnrollDisablePragma(L)) {
687     return false;
688   }
689   bool PragmaFullUnroll = HasUnrollFullPragma(L);
690   unsigned PragmaCount = UnrollCountPragmaValue(L);
691   bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
692
693   TargetTransformInfo::UnrollingPreferences UP;
694   getUnrollingPreferences(L, TTI, UP);
695
696   // Find trip count and trip multiple if count is not available
697   unsigned TripCount = 0;
698   unsigned TripMultiple = 1;
699   // If there are multiple exiting blocks but one of them is the latch, use the
700   // latch for the trip count estimation. Otherwise insist on a single exiting
701   // block for the trip count estimation.
702   BasicBlock *ExitingBlock = L->getLoopLatch();
703   if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
704     ExitingBlock = L->getExitingBlock();
705   if (ExitingBlock) {
706     TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
707     TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
708   }
709
710   // Select an initial unroll count.  This may be reduced later based
711   // on size thresholds.
712   bool CountSetExplicitly;
713   unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
714                                      PragmaCount, UP, CountSetExplicitly);
715
716   unsigned NumInlineCandidates;
717   bool notDuplicatable;
718   unsigned LoopSize =
719       ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
720   DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
721
722   // When computing the unrolled size, note that the conditional branch on the
723   // backedge and the comparison feeding it are not replicated like the rest of
724   // the loop body (which is why 2 is subtracted).
725   uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
726   if (notDuplicatable) {
727     DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
728                  << " instructions.\n");
729     return false;
730   }
731   if (NumInlineCandidates != 0) {
732     DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
733     return false;
734   }
735
736   unsigned NumberOfOptimizedInstructions =
737       ApproximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI);
738   DEBUG(dbgs() << "  Complete unrolling could save: "
739                << NumberOfOptimizedInstructions << "\n");
740
741   unsigned Threshold, PartialThreshold;
742   selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
743                    NumberOfOptimizedInstructions);
744
745   // Given Count, TripCount and thresholds determine the type of
746   // unrolling which is to be performed.
747   enum { Full = 0, Partial = 1, Runtime = 2 };
748   int Unrolling;
749   if (TripCount && Count == TripCount) {
750     if (Threshold != NoThreshold && UnrolledSize > Threshold) {
751       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
752                    << " because size: " << UnrolledSize << ">" << Threshold
753                    << "\n");
754       Unrolling = Partial;
755     } else {
756       Unrolling = Full;
757     }
758   } else if (TripCount && Count < TripCount) {
759     Unrolling = Partial;
760   } else {
761     Unrolling = Runtime;
762   }
763
764   // Reduce count based on the type of unrolling and the threshold values.
765   unsigned OriginalCount = Count;
766   bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime;
767   if (Unrolling == Partial) {
768     bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
769     if (!AllowPartial && !CountSetExplicitly) {
770       DEBUG(dbgs() << "  will not try to unroll partially because "
771                    << "-unroll-allow-partial not given\n");
772       return false;
773     }
774     if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
775       // Reduce unroll count to be modulo of TripCount for partial unrolling.
776       Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
777       while (Count != 0 && TripCount % Count != 0)
778         Count--;
779     }
780   } else if (Unrolling == Runtime) {
781     if (!AllowRuntime && !CountSetExplicitly) {
782       DEBUG(dbgs() << "  will not try to unroll loop with runtime trip count "
783                    << "-unroll-runtime not given\n");
784       return false;
785     }
786     // Reduce unroll count to be the largest power-of-two factor of
787     // the original count which satisfies the threshold limit.
788     while (Count != 0 && UnrolledSize > PartialThreshold) {
789       Count >>= 1;
790       UnrolledSize = (LoopSize-2) * Count + 2;
791     }
792     if (Count > UP.MaxCount)
793       Count = UP.MaxCount;
794     DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
795   }
796
797   if (HasPragma) {
798     if (PragmaCount != 0)
799       // If loop has an unroll count pragma mark loop as unrolled to prevent
800       // unrolling beyond that requested by the pragma.
801       SetLoopAlreadyUnrolled(L);
802
803     // Emit optimization remarks if we are unable to unroll the loop
804     // as directed by a pragma.
805     DebugLoc LoopLoc = L->getStartLoc();
806     Function *F = Header->getParent();
807     LLVMContext &Ctx = F->getContext();
808     if (PragmaFullUnroll && PragmaCount == 0) {
809       if (TripCount && Count != TripCount) {
810         emitOptimizationRemarkMissed(
811             Ctx, DEBUG_TYPE, *F, LoopLoc,
812             "Unable to fully unroll loop as directed by unroll(full) pragma "
813             "because unrolled size is too large.");
814       } else if (!TripCount) {
815         emitOptimizationRemarkMissed(
816             Ctx, DEBUG_TYPE, *F, LoopLoc,
817             "Unable to fully unroll loop as directed by unroll(full) pragma "
818             "because loop has a runtime trip count.");
819       }
820     } else if (PragmaCount > 0 && Count != OriginalCount) {
821       emitOptimizationRemarkMissed(
822           Ctx, DEBUG_TYPE, *F, LoopLoc,
823           "Unable to unroll loop the number of times directed by "
824           "unroll_count pragma because unrolled size is too large.");
825     }
826   }
827
828   if (Unrolling != Full && Count < 2) {
829     // Partial unrolling by 1 is a nop.  For full unrolling, a factor
830     // of 1 makes sense because loop control can be eliminated.
831     return false;
832   }
833
834   // Unroll the loop.
835   if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this,
836                   &LPM, &AC))
837     return false;
838
839   return true;
840 }