Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- LoopUnroll.cpp - Loop unroller 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 a simple loop unroller.  It works best when loops have
10
// been canonicalized by the -indvars pass, allowing it to determine the trip
11
// counts of loops easily.
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
15
#include "llvm/ADT/DenseMap.h"
16
#include "llvm/ADT/DenseMapInfo.h"
17
#include "llvm/ADT/DenseSet.h"
18
#include "llvm/ADT/None.h"
19
#include "llvm/ADT/Optional.h"
20
#include "llvm/ADT/STLExtras.h"
21
#include "llvm/ADT/SetVector.h"
22
#include "llvm/ADT/SmallPtrSet.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringRef.h"
25
#include "llvm/Analysis/AssumptionCache.h"
26
#include "llvm/Analysis/BlockFrequencyInfo.h"
27
#include "llvm/Analysis/CodeMetrics.h"
28
#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
29
#include "llvm/Analysis/LoopAnalysisManager.h"
30
#include "llvm/Analysis/LoopInfo.h"
31
#include "llvm/Analysis/LoopPass.h"
32
#include "llvm/Analysis/LoopUnrollAnalyzer.h"
33
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
34
#include "llvm/Analysis/ProfileSummaryInfo.h"
35
#include "llvm/Analysis/ScalarEvolution.h"
36
#include "llvm/Analysis/TargetTransformInfo.h"
37
#include "llvm/IR/BasicBlock.h"
38
#include "llvm/IR/CFG.h"
39
#include "llvm/IR/Constant.h"
40
#include "llvm/IR/Constants.h"
41
#include "llvm/IR/DiagnosticInfo.h"
42
#include "llvm/IR/Dominators.h"
43
#include "llvm/IR/Function.h"
44
#include "llvm/IR/Instruction.h"
45
#include "llvm/IR/Instructions.h"
46
#include "llvm/IR/IntrinsicInst.h"
47
#include "llvm/IR/Metadata.h"
48
#include "llvm/IR/PassManager.h"
49
#include "llvm/Pass.h"
50
#include "llvm/Support/Casting.h"
51
#include "llvm/Support/CommandLine.h"
52
#include "llvm/Support/Debug.h"
53
#include "llvm/Support/ErrorHandling.h"
54
#include "llvm/Support/raw_ostream.h"
55
#include "llvm/Transforms/Scalar.h"
56
#include "llvm/Transforms/Scalar/LoopPassManager.h"
57
#include "llvm/Transforms/Utils.h"
58
#include "llvm/Transforms/Utils/LoopSimplify.h"
59
#include "llvm/Transforms/Utils/LoopUtils.h"
60
#include "llvm/Transforms/Utils/SizeOpts.h"
61
#include "llvm/Transforms/Utils/UnrollLoop.h"
62
#include <algorithm>
63
#include <cassert>
64
#include <cstdint>
65
#include <limits>
66
#include <string>
67
#include <tuple>
68
#include <utility>
69
70
using namespace llvm;
71
72
0
#define DEBUG_TYPE "loop-unroll"
73
74
cl::opt<bool> llvm::ForgetSCEVInLoopUnroll(
75
    "forget-scev-loop-unroll", cl::init(false), cl::Hidden,
76
    cl::desc("Forget everything in SCEV when doing LoopUnroll, instead of just"
77
             " the current top-most loop. This is somtimes preferred to reduce"
78
             " compile time."));
79
80
static cl::opt<unsigned>
81
    UnrollThreshold("unroll-threshold", cl::Hidden,
82
                    cl::desc("The cost threshold for loop unrolling"));
83
84
static cl::opt<unsigned> UnrollPartialThreshold(
85
    "unroll-partial-threshold", cl::Hidden,
86
    cl::desc("The cost threshold for partial loop unrolling"));
87
88
static cl::opt<unsigned> UnrollMaxPercentThresholdBoost(
89
    "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden,
90
    cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied "
91
             "to the threshold when aggressively unrolling a loop due to the "
92
             "dynamic cost savings. If completely unrolling a loop will reduce "
93
             "the total runtime from X to Y, we boost the loop unroll "
94
             "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
95
             "X/Y). This limit avoids excessive code bloat."));
96
97
static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
98
    "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
99
    cl::desc("Don't allow loop unrolling to simulate more than this number of"
100
             "iterations when checking full unroll profitability"));
101
102
static cl::opt<unsigned> UnrollCount(
103
    "unroll-count", cl::Hidden,
104
    cl::desc("Use this unroll count for all loops including those with "
105
             "unroll_count pragma values, for testing purposes"));
106
107
static cl::opt<unsigned> UnrollMaxCount(
108
    "unroll-max-count", cl::Hidden,
109
    cl::desc("Set the max unroll count for partial and runtime unrolling, for"
110
             "testing purposes"));
111
112
static cl::opt<unsigned> UnrollFullMaxCount(
113
    "unroll-full-max-count", cl::Hidden,
114
    cl::desc(
115
        "Set the max unroll count for full unrolling, for testing purposes"));
116
117
static cl::opt<unsigned> UnrollPeelCount(
118
    "unroll-peel-count", cl::Hidden,
119
    cl::desc("Set the unroll peeling count, for testing purposes"));
120
121
static cl::opt<bool>
122
    UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
123
                       cl::desc("Allows loops to be partially unrolled until "
124
                                "-unroll-threshold loop size is reached."));
125
126
static cl::opt<bool> UnrollAllowRemainder(
127
    "unroll-allow-remainder", cl::Hidden,
128
    cl::desc("Allow generation of a loop remainder (extra iterations) "
129
             "when unrolling a loop."));
130
131
static cl::opt<bool>
132
    UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
133
                  cl::desc("Unroll loops with run-time trip counts"));
134
135
static cl::opt<unsigned> UnrollMaxUpperBound(
136
    "unroll-max-upperbound", cl::init(8), cl::Hidden,
137
    cl::desc(
138
        "The max of trip count upper bound that is considered in unrolling"));
139
140
static cl::opt<unsigned> PragmaUnrollThreshold(
141
    "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
142
    cl::desc("Unrolled size limit for loops with an unroll(full) or "
143
             "unroll_count pragma."));
144
145
static cl::opt<unsigned> FlatLoopTripCountThreshold(
146
    "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden,
147
    cl::desc("If the runtime tripcount for the loop is lower than the "
148
             "threshold, the loop is considered as flat and will be less "
149
             "aggressively unrolled."));
150
151
static cl::opt<bool>
152
    UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden,
153
                       cl::desc("Allows loops to be peeled when the dynamic "
154
                                "trip count is known to be low."));
155
156
static cl::opt<bool> UnrollUnrollRemainder(
157
  "unroll-remainder", cl::Hidden,
158
  cl::desc("Allow the loop remainder to be unrolled."));
159
160
// This option isn't ever intended to be enabled, it serves to allow
161
// experiments to check the assumptions about when this kind of revisit is
162
// necessary.
163
static cl::opt<bool> UnrollRevisitChildLoops(
164
    "unroll-revisit-child-loops", cl::Hidden,
165
    cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. "
166
             "This shouldn't typically be needed as child loops (or their "
167
             "clones) were already visited."));
168
169
/// A magic value for use with the Threshold parameter to indicate
170
/// that the loop unroll should be performed regardless of how much
171
/// code expansion would result.
172
static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
173
174
/// Gather the various unrolling parameters based on the defaults, compiler
175
/// flags, TTI overrides and user specified parameters.
176
TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences(
177
    Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
178
    BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, int OptLevel,
179
    Optional<unsigned> UserThreshold, Optional<unsigned> UserCount,
180
    Optional<bool> UserAllowPartial, Optional<bool> UserRuntime,
181
390k
    Optional<bool> UserUpperBound, Optional<bool> UserAllowPeeling) {
182
390k
  TargetTransformInfo::UnrollingPreferences UP;
183
390k
184
390k
  // Set up the defaults
185
390k
  UP.Threshold = OptLevel > 2 ? 
300389k
:
1501.04k
;
186
390k
  UP.MaxPercentThresholdBoost = 400;
187
390k
  UP.OptSizeThreshold = 0;
188
390k
  UP.PartialThreshold = 150;
189
390k
  UP.PartialOptSizeThreshold = 0;
190
390k
  UP.Count = 0;
191
390k
  UP.PeelCount = 0;
192
390k
  UP.DefaultUnrollRuntimeCount = 8;
193
390k
  UP.MaxCount = std::numeric_limits<unsigned>::max();
194
390k
  UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max();
195
390k
  UP.BEInsns = 2;
196
390k
  UP.Partial = false;
197
390k
  UP.Runtime = false;
198
390k
  UP.AllowRemainder = true;
199
390k
  UP.UnrollRemainder = false;
200
390k
  UP.AllowExpensiveTripCount = false;
201
390k
  UP.Force = false;
202
390k
  UP.UpperBound = false;
203
390k
  UP.AllowPeeling = true;
204
390k
  UP.UnrollAndJam = false;
205
390k
  UP.UnrollAndJamInnerLoopThreshold = 60;
206
390k
207
390k
  // Override with any target specific settings
208
390k
  TTI.getUnrollingPreferences(L, SE, UP);
209
390k
210
390k
  // Apply size attributes
211
390k
  bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
212
390k
                    
llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI)390k
;
213
390k
  if (OptForSize) {
214
135
    UP.Threshold = UP.OptSizeThreshold;
215
135
    UP.PartialThreshold = UP.PartialOptSizeThreshold;
216
135
    UP.MaxPercentThresholdBoost = 100;
217
135
  }
218
390k
219
390k
  // Apply any user values specified by cl::opt
220
390k
  if (UnrollThreshold.getNumOccurrences() > 0)
221
99
    UP.Threshold = UnrollThreshold;
222
390k
  if (UnrollPartialThreshold.getNumOccurrences() > 0)
223
9
    UP.PartialThreshold = UnrollPartialThreshold;
224
390k
  if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0)
225
54
    UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost;
226
390k
  if (UnrollMaxCount.getNumOccurrences() > 0)
227
1
    UP.MaxCount = UnrollMaxCount;
228
390k
  if (UnrollFullMaxCount.getNumOccurrences() > 0)
229
0
    UP.FullUnrollMaxCount = UnrollFullMaxCount;
230
390k
  if (UnrollPeelCount.getNumOccurrences() > 0)
231
7
    UP.PeelCount = UnrollPeelCount;
232
390k
  if (UnrollAllowPartial.getNumOccurrences() > 0)
233
71
    UP.Partial = UnrollAllowPartial;
234
390k
  if (UnrollAllowRemainder.getNumOccurrences() > 0)
235
14
    UP.AllowRemainder = UnrollAllowRemainder;
236
390k
  if (UnrollRuntime.getNumOccurrences() > 0)
237
131
    UP.Runtime = UnrollRuntime;
238
390k
  if (UnrollMaxUpperBound == 0)
239
1
    UP.UpperBound = false;
240
390k
  if (UnrollAllowPeeling.getNumOccurrences() > 0)
241
6
    UP.AllowPeeling = UnrollAllowPeeling;
242
390k
  if (UnrollUnrollRemainder.getNumOccurrences() > 0)
243
30
    UP.UnrollRemainder = UnrollUnrollRemainder;
244
390k
245
390k
  // Apply user values provided by argument
246
390k
  if (UserThreshold.hasValue()) {
247
0
    UP.Threshold = *UserThreshold;
248
0
    UP.PartialThreshold = *UserThreshold;
249
0
  }
250
390k
  if (UserCount.hasValue())
251
0
    UP.Count = *UserCount;
252
390k
  if (UserAllowPartial.hasValue())
253
204k
    UP.Partial = *UserAllowPartial;
254
390k
  if (UserRuntime.hasValue())
255
204k
    UP.Runtime = *UserRuntime;
256
390k
  if (UserUpperBound.hasValue())
257
204k
    UP.UpperBound = *UserUpperBound;
258
390k
  if (UserAllowPeeling.hasValue())
259
204k
    UP.AllowPeeling = *UserAllowPeeling;
260
390k
261
390k
  return UP;
262
390k
}
263
264
namespace {
265
266
/// A struct to densely store the state of an instruction after unrolling at
267
/// each iteration.
268
///
269
/// This is designed to work like a tuple of <Instruction *, int> for the
270
/// purposes of hashing and lookup, but to be able to associate two boolean
271
/// states with each key.
272
struct UnrolledInstState {
273
  Instruction *I;
274
  int Iteration : 30;
275
  unsigned IsFree : 1;
276
  unsigned IsCounted : 1;
277
};
278
279
/// Hashing and equality testing for a set of the instruction states.
280
struct UnrolledInstStateKeyInfo {
281
  using PtrInfo = DenseMapInfo<Instruction *>;
282
  using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
283
284
2.66M
  static inline UnrolledInstState getEmptyKey() {
285
2.66M
    return {PtrInfo::getEmptyKey(), 0, 0, 0};
286
2.66M
  }
287
288
2.08M
  static inline UnrolledInstState getTombstoneKey() {
289
2.08M
    return {PtrInfo::getTombstoneKey(), 0, 0, 0};
290
2.08M
  }
291
292
2.08M
  static inline unsigned getHashValue(const UnrolledInstState &S) {
293
2.08M
    return PairInfo::getHashValue({S.I, S.Iteration});
294
2.08M
  }
295
296
  static inline bool isEqual(const UnrolledInstState &LHS,
297
13.1M
                             const UnrolledInstState &RHS) {
298
13.1M
    return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
299
13.1M
  }
300
};
301
302
struct EstimatedUnrollCost {
303
  /// The estimated cost after unrolling.
304
  unsigned UnrolledCost;
305
306
  /// The estimated dynamic cost of executing the instructions in the
307
  /// rolled form.
308
  unsigned RolledDynamicCost;
309
};
310
311
} // end anonymous namespace
312
313
/// Figure out if the loop is worth full unrolling.
314
///
315
/// Complete loop unrolling can make some loads constant, and we need to know
316
/// if that would expose any further optimization opportunities.  This routine
317
/// estimates this optimization.  It computes cost of unrolled loop
318
/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
319
/// dynamic cost we mean that we won't count costs of blocks that are known not
320
/// to be executed (i.e. if we have a branch in the loop and we know that at the
321
/// given iteration its condition would be resolved to true, we won't add up the
322
/// cost of the 'false'-block).
323
/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
324
/// the analysis failed (no benefits expected from the unrolling, or the loop is
325
/// too big to analyze), the returned value is None.
326
static Optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
327
    const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
328
    const SmallPtrSetImpl<const Value *> &EphValues,
329
36.5k
    const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize) {
330
36.5k
  // We want to be able to scale offsets by the trip count and add more offsets
331
36.5k
  // to them without checking for overflows, and we already don't want to
332
36.5k
  // analyze *massive* trip counts, so we force the max to be reasonably small.
333
36.5k
  assert(UnrollMaxIterationsCountToAnalyze <
334
36.5k
             (unsigned)(std::numeric_limits<int>::max() / 2) &&
335
36.5k
         "The unroll iterations max is too large!");
336
36.5k
337
36.5k
  // Only analyze inner loops. We can't properly estimate cost of nested loops
338
36.5k
  // and we won't visit inner loops again anyway.
339
36.5k
  if (!L->empty())
340
6.88k
    return None;
341
29.6k
342
29.6k
  // Don't simulate loops with a big or unknown tripcount
343
29.6k
  if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
344
29.6k
      TripCount > UnrollMaxIterationsCountToAnalyze)
345
28.7k
    return None;
346
921
347
921
  SmallSetVector<BasicBlock *, 16> BBWorklist;
348
921
  SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
349
921
  DenseMap<Value *, Constant *> SimplifiedValues;
350
921
  SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
351
921
352
921
  // The estimated cost of the unrolled form of the loop. We try to estimate
353
921
  // this by simplifying as much as we can while computing the estimate.
354
921
  unsigned UnrolledCost = 0;
355
921
356
921
  // We also track the estimated dynamic (that is, actually executed) cost in
357
921
  // the rolled form. This helps identify cases when the savings from unrolling
358
921
  // aren't just exposing dead control flows, but actual reduced dynamic
359
921
  // instructions due to the simplifications which we expect to occur after
360
921
  // unrolling.
361
921
  unsigned RolledDynamicCost = 0;
362
921
363
921
  // We track the simplification of each instruction in each iteration. We use
364
921
  // this to recursively merge costs into the unrolled cost on-demand so that
365
921
  // we don't count the cost of any dead code. This is essentially a map from
366
921
  // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
367
921
  DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
368
921
369
921
  // A small worklist used to accumulate cost of instructions from each
370
921
  // observable and reached root in the loop.
371
921
  SmallVector<Instruction *, 16> CostWorklist;
372
921
373
921
  // PHI-used worklist used between iterations while accumulating cost.
374
921
  SmallVector<Instruction *, 4> PHIUsedList;
375
921
376
921
  // Helper function to accumulate cost for instructions in the loop.
377
73.0k
  auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
378
73.0k
    assert(Iteration >= 0 && "Cannot have a negative iteration!");
379
73.0k
    assert(CostWorklist.empty() && "Must start with an empty cost list");
380
73.0k
    assert(PHIUsedList.empty() && "Must start with an empty phi used list");
381
73.0k
    CostWorklist.push_back(&RootI);
382
79.5k
    for (;; 
--Iteration6.49k
) {
383
726k
      do {
384
726k
        Instruction *I = CostWorklist.pop_back_val();
385
726k
386
726k
        // InstCostMap only uses I and Iteration as a key, the other two values
387
726k
        // don't matter here.
388
726k
        auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
389
726k
        if (CostIter == InstCostMap.end())
390
1.00k
          // If an input to a PHI node comes from a dead path through the loop
391
1.00k
          // we may have no cost data for it here. What that actually means is
392
1.00k
          // that it is free.
393
1.00k
          continue;
394
725k
        auto &Cost = *CostIter;
395
725k
        if (Cost.IsCounted)
396
192k
          // Already counted this instruction.
397
192k
          continue;
398
532k
399
532k
        // Mark that we are counting the cost of this instruction now.
400
532k
        Cost.IsCounted = true;
401
532k
402
532k
        // If this is a PHI node in the loop header, just add it to the PHI set.
403
532k
        if (auto *PhiI = dyn_cast<PHINode>(I))
404
16.5k
          if (PhiI->getParent() == L->getHeader()) {
405
12.7k
            assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
406
12.7k
                                  "inherently simplify during unrolling.");
407
12.7k
            if (Iteration == 0)
408
1.40k
              continue;
409
11.3k
410
11.3k
            // Push the incoming value from the backedge into the PHI used list
411
11.3k
            // if it is an in-loop instruction. We'll use this to populate the
412
11.3k
            // cost worklist for the next iteration (as we count backwards).
413
11.3k
            if (auto *OpI = dyn_cast<Instruction>(
414
11.3k
                    PhiI->getIncomingValueForBlock(L->getLoopLatch())))
415
11.3k
              if (L->contains(OpI))
416
11.3k
                PHIUsedList.push_back(OpI);
417
11.3k
            continue;
418
11.3k
          }
419
519k
420
519k
        // First accumulate the cost of this instruction.
421
519k
        if (!Cost.IsFree) {
422
506k
          UnrolledCost += TTI.getUserCost(I);
423
506k
          LLVM_DEBUG(dbgs() << "Adding cost of instruction (iteration "
424
506k
                            << Iteration << "): ");
425
506k
          LLVM_DEBUG(I->dump());
426
506k
        }
427
519k
428
519k
        // We must count the cost of every operand which is not free,
429
519k
        // recursively. If we reach a loop PHI node, simply add it to the set
430
519k
        // to be considered on the next iteration (backwards!).
431
1.02M
        for (Value *Op : I->operands()) {
432
1.02M
          // Check whether this operand is free due to being a constant or
433
1.02M
          // outside the loop.
434
1.02M
          auto *OpI = dyn_cast<Instruction>(Op);
435
1.02M
          if (!OpI || 
!L->contains(OpI)703k
)
436
382k
            continue;
437
641k
438
641k
          // Otherwise accumulate its cost.
439
641k
          CostWorklist.push_back(OpI);
440
641k
        }
441
726k
      } while (!CostWorklist.empty());
442
79.5k
443
79.5k
      if (PHIUsedList.empty())
444
73.0k
        // We've exhausted the search.
445
73.0k
        break;
446
6.49k
447
6.49k
      assert(Iteration > 0 &&
448
6.49k
             "Cannot track PHI-used values past the first iteration!");
449
6.49k
      CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
450
6.49k
      PHIUsedList.clear();
451
6.49k
    }
452
73.0k
  };
453
921
454
921
  // Ensure that we don't violate the loop structure invariants relied on by
455
921
  // this analysis.
456
921
  assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
457
921
  assert(L->isLCSSAForm(DT) &&
458
921
         "Must have loops in LCSSA form to track live-out values.");
459
921
460
921
  LLVM_DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
461
921
462
921
  // Simulate execution of each iteration of the loop counting instructions,
463
921
  // which would be simplified.
464
921
  // Since the same load will take different values on different iterations,
465
921
  // we literally have to go through all loop's iterations.
466
11.4k
  for (unsigned Iteration = 0; Iteration < TripCount; 
++Iteration10.5k
) {
467
10.7k
    LLVM_DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
468
10.7k
469
10.7k
    // Prepare for the iteration by collecting any simplified entry or backedge
470
10.7k
    // inputs.
471
28.5k
    for (Instruction &I : *L->getHeader()) {
472
28.5k
      auto *PHI = dyn_cast<PHINode>(&I);
473
28.5k
      if (!PHI)
474
10.7k
        break;
475
17.7k
476
17.7k
      // The loop header PHI nodes must have exactly two input: one from the
477
17.7k
      // loop preheader and one from the loop latch.
478
17.7k
      assert(
479
17.7k
          PHI->getNumIncomingValues() == 2 &&
480
17.7k
          "Must have an incoming value only for the preheader and the latch.");
481
17.7k
482
17.7k
      Value *V = PHI->getIncomingValueForBlock(
483
17.7k
          Iteration == 0 ? 
L->getLoopPreheader()1.80k
:
L->getLoopLatch()15.9k
);
484
17.7k
      Constant *C = dyn_cast<Constant>(V);
485
17.7k
      if (Iteration != 0 && 
!C15.9k
)
486
15.9k
        C = SimplifiedValues.lookup(V);
487
17.7k
      if (C)
488
10.9k
        SimplifiedInputValues.push_back({PHI, C});
489
17.7k
    }
490
10.7k
491
10.7k
    // Now clear and re-populate the map for the next iteration.
492
10.7k
    SimplifiedValues.clear();
493
21.6k
    while (!SimplifiedInputValues.empty())
494
10.9k
      SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
495
10.7k
496
10.7k
    UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
497
10.7k
498
10.7k
    BBWorklist.clear();
499
10.7k
    BBWorklist.insert(L->getHeader());
500
10.7k
    // Note that we *must not* cache the size, this loop grows the worklist.
501
38.8k
    for (unsigned Idx = 0; Idx != BBWorklist.size(); 
++Idx28.0k
) {
502
28.3k
      BasicBlock *BB = BBWorklist[Idx];
503
28.3k
504
28.3k
      // Visit all instructions in the given basic block and try to simplify
505
28.3k
      // it.  We don't change the actual IR, just count optimization
506
28.3k
      // opportunities.
507
577k
      for (Instruction &I : *BB) {
508
577k
        // These won't get into the final code - don't even try calculating the
509
577k
        // cost for them.
510
577k
        if (isa<DbgInfoIntrinsic>(I) || EphValues.count(&I))
511
18
          continue;
512
577k
513
577k
        // Track this instruction's expected baseline cost when executing the
514
577k
        // rolled loop form.
515
577k
        RolledDynamicCost += TTI.getUserCost(&I);
516
577k
517
577k
        // Visit the instruction to analyze its loop cost after unrolling,
518
577k
        // and if the visitor returns true, mark the instruction as free after
519
577k
        // unrolling and continue.
520
577k
        bool IsFree = Analyzer.visit(I);
521
577k
        bool Inserted = InstCostMap.insert({&I, (int)Iteration,
522
577k
                                           (unsigned)IsFree,
523
577k
                                           /*IsCounted*/ false}).second;
524
577k
        (void)Inserted;
525
577k
        assert(Inserted && "Cannot have a state for an unvisited instruction!");
526
577k
527
577k
        if (IsFree)
528
47.5k
          continue;
529
529k
530
529k
        // Can't properly model a cost of a call.
531
529k
        // FIXME: With a proper cost model we should be able to do it.
532
529k
        if (auto *CI = dyn_cast<CallInst>(&I)) {
533
2.61k
          const Function *Callee = CI->getCalledFunction();
534
2.61k
          if (!Callee || 
TTI.isLoweredToCall(Callee)2.59k
) {
535
205
            LLVM_DEBUG(dbgs() << "Can't analyze cost of loop with call\n");
536
205
            return None;
537
205
          }
538
529k
        }
539
529k
540
529k
        // If the instruction might have a side-effect recursively account for
541
529k
        // the cost of it and all the instructions leading up to it.
542
529k
        if (I.mayHaveSideEffects())
543
54.3k
          AddCostRecursively(I, Iteration);
544
529k
545
529k
        // If unrolled body turns out to be too big, bail out.
546
529k
        if (UnrolledCost > MaxUnrolledLoopSize) {
547
35
          LLVM_DEBUG(dbgs() << "  Exceeded threshold.. exiting.\n"
548
35
                            << "  UnrolledCost: " << UnrolledCost
549
35
                            << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
550
35
                            << "\n");
551
35
          return None;
552
35
        }
553
529k
      }
554
28.3k
555
28.3k
      Instruction *TI = BB->getTerminator();
556
28.0k
557
28.0k
      // Add in the live successors by first checking whether we have terminator
558
28.0k
      // that may be simplified based on the values simplified by this call.
559
28.0k
      BasicBlock *KnownSucc = nullptr;
560
28.0k
      if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
561
27.6k
        if (BI->isConditional()) {
562
19.1k
          if (Constant *SimpleCond =
563
9.79k
                  SimplifiedValues.lookup(BI->getCondition())) {
564
9.79k
            // Just take the first successor if condition is undef
565
9.79k
            if (isa<UndefValue>(SimpleCond))
566
6
              KnownSucc = BI->getSuccessor(0);
567
9.79k
            else if (ConstantInt *SimpleCondVal =
568
9.78k
                         dyn_cast<ConstantInt>(SimpleCond))
569
9.78k
              KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 
12.35k
:
07.43k
);
570
9.79k
          }
571
19.1k
        }
572
27.6k
      } else 
if (SwitchInst *391
SI391
= dyn_cast<SwitchInst>(TI)) {
573
385
        if (Constant *SimpleCond =
574
50
                SimplifiedValues.lookup(SI->getCondition())) {
575
50
          // Just take the first successor if condition is undef
576
50
          if (isa<UndefValue>(SimpleCond))
577
0
            KnownSucc = SI->getSuccessor(0);
578
50
          else if (ConstantInt *SimpleCondVal =
579
50
                       dyn_cast<ConstantInt>(SimpleCond))
580
50
            KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
581
50
        }
582
385
      }
583
28.0k
      if (KnownSucc) {
584
9.84k
        if (L->contains(KnownSucc))
585
9.30k
          BBWorklist.insert(KnownSucc);
586
543
        else
587
543
          ExitWorklist.insert({BB, KnownSucc});
588
9.84k
        continue;
589
9.84k
      }
590
18.2k
591
18.2k
      // Add BB's successors to the worklist.
592
18.2k
      for (BasicBlock *Succ : successors(BB))
593
28.3k
        if (L->contains(Succ))
594
26.2k
          BBWorklist.insert(Succ);
595
2.07k
        else
596
2.07k
          ExitWorklist.insert({BB, Succ});
597
18.2k
      AddCostRecursively(*TI, Iteration);
598
18.2k
    }
599
10.7k
600
10.7k
    // If we found no optimization opportunities on the first iteration, we
601
10.7k
    // won't find them on later ones too.
602
10.7k
    
if (10.5k
UnrolledCost == RolledDynamicCost10.5k
) {
603
18
      LLVM_DEBUG(dbgs() << "  No opportunities found.. exiting.\n"
604
18
                        << "  UnrolledCost: " << UnrolledCost << "\n");
605
18
      return None;
606
18
    }
607
10.5k
  }
608
921
609
1.44k
  
while (663
!ExitWorklist.empty()) {
610
783
    BasicBlock *ExitingBB, *ExitBB;
611
783
    std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
612
783
613
1.30k
    for (Instruction &I : *ExitBB) {
614
1.30k
      auto *PN = dyn_cast<PHINode>(&I);
615
1.30k
      if (!PN)
616
783
        break;
617
518
618
518
      Value *Op = PN->getIncomingValueForBlock(ExitingBB);
619
518
      if (auto *OpI = dyn_cast<Instruction>(Op))
620
500
        if (L->contains(OpI))
621
471
          AddCostRecursively(*OpI, TripCount - 1);
622
518
    }
623
783
  }
624
663
625
663
  LLVM_DEBUG(dbgs() << "Analysis finished:\n"
626
663
                    << "UnrolledCost: " << UnrolledCost << ", "
627
663
                    << "RolledDynamicCost: " << RolledDynamicCost << "\n");
628
663
  return {{UnrolledCost, RolledDynamicCost}};
629
921
}
630
631
/// ApproximateLoopSize - Approximate the size of the loop.
632
unsigned llvm::ApproximateLoopSize(
633
    const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent,
634
    const TargetTransformInfo &TTI,
635
390k
    const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns) {
636
390k
  CodeMetrics Metrics;
637
390k
  for (BasicBlock *BB : L->blocks())
638
1.78M
    Metrics.analyzeBasicBlock(BB, TTI, EphValues);
639
390k
  NumCalls = Metrics.NumInlineCandidates;
640
390k
  NotDuplicatable = Metrics.notDuplicatable;
641
390k
  Convergent = Metrics.convergent;
642
390k
643
390k
  unsigned LoopSize = Metrics.NumInsts;
644
390k
645
390k
  // Don't allow an estimate of size zero.  This would allows unrolling of loops
646
390k
  // with huge iteration counts, which is a compile time problem even if it's
647
390k
  // not a problem for code quality. Also, the code using this size may assume
648
390k
  // that each loop has at least three instructions (likely a conditional
649
390k
  // branch, a comparison feeding that branch, and some kind of loop increment
650
390k
  // feeding that comparison instruction).
651
390k
  LoopSize = std::max(LoopSize, BEInsns + 1);
652
390k
653
390k
  return LoopSize;
654
390k
}
655
656
// Returns the loop hint metadata node with the given name (for example,
657
// "llvm.loop.unroll.count").  If no such metadata node exists, then nullptr is
658
// returned.
659
1.51M
static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
660
1.51M
  if (MDNode *LoopID = L->getLoopID())
661
246k
    return GetUnrollMetadata(LoopID, Name);
662
1.26M
  return nullptr;
663
1.26M
}
664
665
// Returns true if the loop has an unroll(full) pragma.
666
390k
static bool HasUnrollFullPragma(const Loop *L) {
667
390k
  return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
668
390k
}
669
670
// Returns true if the loop has an unroll(enable) pragma. This metadata is used
671
// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
672
390k
static bool HasUnrollEnablePragma(const Loop *L) {
673
390k
  return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
674
390k
}
675
676
// Returns true if the loop has an runtime unroll(disable) pragma.
677
344k
static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
678
344k
  return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
679
344k
}
680
681
// If loop has an unroll_count pragma return the (necessarily
682
// positive) value from the pragma.  Otherwise return 0.
683
390k
static unsigned UnrollCountPragmaValue(const Loop *L) {
684
390k
  MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
685
390k
  if (MD) {
686
21
    assert(MD->getNumOperands() == 2 &&
687
21
           "Unroll count hint metadata should have two operands.");
688
21
    unsigned Count =
689
21
        mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
690
21
    assert(Count >= 1 && "Unroll count must be positive.");
691
21
    return Count;
692
21
  }
693
390k
  return 0;
694
390k
}
695
696
// Computes the boosting factor for complete unrolling.
697
// If fully unrolling the loop would save a lot of RolledDynamicCost, it would
698
// be beneficial to fully unroll the loop even if unrolledcost is large. We
699
// use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
700
// the unroll threshold.
701
static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
702
663
                                            unsigned MaxPercentThresholdBoost) {
703
663
  if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
704
0
    return 100;
705
663
  else if (Cost.UnrolledCost != 0)
706
655
    // The boosting factor is RolledDynamicCost / UnrolledCost
707
655
    return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
708
655
                    MaxPercentThresholdBoost);
709
8
  else
710
8
    return MaxPercentThresholdBoost;
711
663
}
712
713
// Returns loop size estimation for unrolled loop.
714
static uint64_t getUnrolledLoopSize(
715
    unsigned LoopSize,
716
56.9k
    TargetTransformInfo::UnrollingPreferences &UP) {
717
56.9k
  assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
718
56.9k
  return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns;
719
56.9k
}
720
721
// Returns true if unroll count was set explicitly.
722
// Calculates unroll count and writes it to UP.Count.
723
// Unless IgnoreUser is true, will also use metadata and command-line options
724
// that are specific to to the LoopUnroll pass (which, for instance, are
725
// irrelevant for the LoopUnrollAndJam pass).
726
// FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
727
// many LoopUnroll-specific options. The shared functionality should be
728
// refactored into it own function.
729
bool llvm::computeUnrollCount(
730
    Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI,
731
    ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues,
732
    OptimizationRemarkEmitter *ORE, unsigned &TripCount, unsigned MaxTripCount,
733
    unsigned &TripMultiple, unsigned LoopSize,
734
390k
    TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) {
735
390k
736
390k
  // Check for explicit Count.
737
390k
  // 1st priority is unroll count set by "unroll-count" option.
738
390k
  bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
739
390k
  if (UserUnrollCount) {
740
44
    UP.Count = UnrollCount;
741
44
    UP.AllowExpensiveTripCount = true;
742
44
    UP.Force = true;
743
44
    if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold)
744
41
      return true;
745
390k
  }
746
390k
747
390k
  // 2nd priority is unroll count set by pragma.
748
390k
  unsigned PragmaCount = UnrollCountPragmaValue(L);
749
390k
  if (PragmaCount > 0) {
750
21
    UP.Count = PragmaCount;
751
21
    UP.Runtime = true;
752
21
    UP.AllowExpensiveTripCount = true;
753
21
    UP.Force = true;
754
21
    if ((UP.AllowRemainder || 
(TripMultiple % PragmaCount == 0)8
) &&
755
21
        
getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold16
)
756
16
      return true;
757
390k
  }
758
390k
  bool PragmaFullUnroll = HasUnrollFullPragma(L);
759
390k
  if (PragmaFullUnroll && 
TripCount != 014
) {
760
9
    UP.Count = TripCount;
761
9
    if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold)
762
6
      return false;
763
390k
  }
764
390k
765
390k
  bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
766
390k
  bool ExplicitUnroll = PragmaCount > 0 || 
PragmaFullUnroll390k
||
767
390k
                        
PragmaEnableUnroll390k
||
UserUnrollCount390k
;
768
390k
769
390k
  if (ExplicitUnroll && 
TripCount != 022
) {
770
8
    // If the loop has an unrolling pragma, we want to be more aggressive with
771
8
    // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
772
8
    // value which is larger than the default limits.
773
8
    UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
774
8
    UP.PartialThreshold =
775
8
        std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
776
8
  }
777
390k
778
390k
  // 3rd priority is full unroll count.
779
390k
  // Full unroll makes sense only when TripCount or its upper bound could be
780
390k
  // statically calculated.
781
390k
  // Also we need to check if we exceed FullUnrollMaxCount.
782
390k
  // If using the upper bound to unroll, TripMultiple should be set to 1 because
783
390k
  // we do not know when loop may exit.
784
390k
  // MaxTripCount and ExactTripCount cannot both be non zero since we only
785
390k
  // compute the former when the latter is zero.
786
390k
  unsigned ExactTripCount = TripCount;
787
390k
  assert((ExactTripCount == 0 || MaxTripCount == 0) &&
788
390k
         "ExtractTripCount and MaxTripCount cannot both be non zero.");
789
390k
  unsigned FullUnrollTripCount = ExactTripCount ? 
ExactTripCount45.6k
:
MaxTripCount344k
;
790
390k
  UP.Count = FullUnrollTripCount;
791
390k
  if (FullUnrollTripCount && 
FullUnrollTripCount <= UP.FullUnrollMaxCount45.7k
) {
792
45.7k
    // When computing the unrolled size, note that BEInsns are not replicated
793
45.7k
    // like the rest of the loop body.
794
45.7k
    if (getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) {
795
9.24k
      UseUpperBound = (MaxTripCount == FullUnrollTripCount);
796
9.24k
      TripCount = FullUnrollTripCount;
797
9.24k
      TripMultiple = UP.UpperBound ? 
173
:
TripMultiple9.16k
;
798
9.24k
      return ExplicitUnroll;
799
36.5k
    } else {
800
36.5k
      // The loop isn't that small, but we still can fully unroll it if that
801
36.5k
      // helps to remove a significant number of instructions.
802
36.5k
      // To check that, run additional analysis on the loop.
803
36.5k
      if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
804
663
              L, FullUnrollTripCount, DT, SE, EphValues, TTI,
805
663
              UP.Threshold * UP.MaxPercentThresholdBoost / 100)) {
806
663
        unsigned Boost =
807
663
            getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost);
808
663
        if (Cost->UnrolledCost < UP.Threshold * Boost / 100) {
809
127
          UseUpperBound = (MaxTripCount == FullUnrollTripCount);
810
127
          TripCount = FullUnrollTripCount;
811
127
          TripMultiple = UP.UpperBound ? 
10
: TripMultiple;
812
127
          return ExplicitUnroll;
813
127
        }
814
380k
      }
815
36.5k
    }
816
45.7k
  }
817
380k
818
380k
  // 4th priority is loop peeling.
819
380k
  computePeelCount(L, LoopSize, UP, TripCount, SE);
820
380k
  if (UP.PeelCount) {
821
118
    UP.Runtime = false;
822
118
    UP.Count = 1;
823
118
    return ExplicitUnroll;
824
118
  }
825
380k
826
380k
  // 5th priority is partial unrolling.
827
380k
  // Try partial unroll only when TripCount could be statically calculated.
828
380k
  if (TripCount) {
829
36.3k
    UP.Partial |= ExplicitUnroll;
830
36.3k
    if (!UP.Partial) {
831
36.1k
      LLVM_DEBUG(dbgs() << "  will not try to unroll partially because "
832
36.1k
                        << "-unroll-allow-partial not given\n");
833
36.1k
      UP.Count = 0;
834
36.1k
      return false;
835
36.1k
    }
836
283
    if (UP.Count == 0)
837
0
      UP.Count = TripCount;
838
283
    if (UP.PartialThreshold != NoThreshold) {
839
283
      // Reduce unroll count to be modulo of TripCount for partial unrolling.
840
283
      if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold)
841
283
        UP.Count =
842
283
            (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
843
283
            (LoopSize - UP.BEInsns);
844
283
      if (UP.Count > UP.MaxCount)
845
3
        UP.Count = UP.MaxCount;
846
626
      while (UP.Count != 0 && 
TripCount % UP.Count != 0559
)
847
343
        UP.Count--;
848
283
      if (UP.AllowRemainder && 
UP.Count <= 1282
) {
849
140
        // If there is no Count that is modulo of TripCount, set Count to
850
140
        // largest power-of-two factor that satisfies the threshold limit.
851
140
        // As we'll create fixup loop, do the type of unrolling only if
852
140
        // remainder loop is allowed.
853
140
        UP.Count = UP.DefaultUnrollRuntimeCount;
854
598
        while (UP.Count != 0 &&
855
598
               
getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold531
)
856
458
          UP.Count >>= 1;
857
140
      }
858
283
      if (UP.Count < 2) {
859
118
        if (PragmaEnableUnroll)
860
0
          ORE->emit([&]() {
861
0
            return OptimizationRemarkMissed(DEBUG_TYPE,
862
0
                                            "UnrollAsDirectedTooLarge",
863
0
                                            L->getStartLoc(), L->getHeader())
864
0
                   << "Unable to unroll loop as directed by unroll(enable) "
865
0
                      "pragma "
866
0
                      "because unrolled size is too large.";
867
0
          });
868
118
        UP.Count = 0;
869
118
      }
870
283
    } else {
871
0
      UP.Count = TripCount;
872
0
    }
873
283
    if (UP.Count > UP.MaxCount)
874
1
      UP.Count = UP.MaxCount;
875
283
    if ((PragmaFullUnroll || 
PragmaEnableUnroll280
) &&
TripCount3
&&
876
283
        
UP.Count != TripCount3
)
877
3
      ORE->emit([&]() {
878
0
        return OptimizationRemarkMissed(DEBUG_TYPE,
879
0
                                        "FullUnrollAsDirectedTooLarge",
880
0
                                        L->getStartLoc(), L->getHeader())
881
0
               << "Unable to fully unroll loop as directed by unroll pragma "
882
0
                  "because "
883
0
                  "unrolled size is too large.";
884
0
      });
885
283
    return ExplicitUnroll;
886
283
  }
887
344k
  assert(TripCount == 0 &&
888
344k
         "All cases when TripCount is constant should be covered here.");
889
344k
  if (PragmaFullUnroll)
890
5
    ORE->emit([&]() {
891
0
      return OptimizationRemarkMissed(
892
0
                 DEBUG_TYPE, "CantFullUnrollAsDirectedRuntimeTripCount",
893
0
                 L->getStartLoc(), L->getHeader())
894
0
             << "Unable to fully unroll loop as directed by unroll(full) "
895
0
                "pragma "
896
0
                "because loop has a runtime trip count.";
897
0
    });
898
344k
899
344k
  // 6th priority is runtime unrolling.
900
344k
  // Don't unroll a runtime trip count loop when it is disabled.
901
344k
  if (HasRuntimeUnrollDisablePragma(L)) {
902
3.22k
    UP.Count = 0;
903
3.22k
    return false;
904
3.22k
  }
905
341k
906
341k
  // Check if the runtime trip count is too small when profile is available.
907
341k
  if (L->getHeader()->getParent()->hasProfileData()) {
908
19
    if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
909
13
      if (*ProfileTripCount < FlatLoopTripCountThreshold)
910
4
        return false;
911
9
      else
912
9
        UP.AllowExpensiveTripCount = true;
913
13
    }
914
19
  }
915
341k
916
341k
  // Reduce count based on the type of unrolling and the threshold values.
917
341k
  
UP.Runtime |= 341k
PragmaEnableUnroll341k
||
PragmaCount > 0341k
||
UserUnrollCount341k
;
918
341k
  if (!UP.Runtime) {
919
336k
    LLVM_DEBUG(
920
336k
        dbgs() << "  will not try to unroll loop with runtime trip count "
921
336k
               << "-unroll-runtime not given\n");
922
336k
    UP.Count = 0;
923
336k
    return false;
924
336k
  }
925
4.69k
  if (UP.Count == 0)
926
4.69k
    UP.Count = UP.DefaultUnrollRuntimeCount;
927
4.69k
928
4.69k
  // Reduce unroll count to be the largest power-of-two factor of
929
4.69k
  // the original count which satisfies the threshold limit.
930
10.4k
  while (UP.Count != 0 &&
931
10.4k
         
getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold10.2k
)
932
5.77k
    UP.Count >>= 1;
933
4.69k
934
#ifndef NDEBUG
935
  unsigned OrigCount = UP.Count;
936
#endif
937
938
4.69k
  if (!UP.AllowRemainder && 
UP.Count != 06
&&
(TripMultiple % UP.Count) != 06
) {
939
18
    while (UP.Count != 0 && TripMultiple % UP.Count != 0)
940
13
      UP.Count >>= 1;
941
5
    LLVM_DEBUG(
942
5
        dbgs() << "Remainder loop is restricted (that could architecture "
943
5
                  "specific or because the loop contains a convergent "
944
5
                  "instruction), so unroll count must divide the trip "
945
5
                  "multiple, "
946
5
               << TripMultiple << ".  Reducing unroll count from " << OrigCount
947
5
               << " to " << UP.Count << ".\n");
948
5
949
5
    using namespace ore;
950
5
951
5
    if (PragmaCount > 0 && 
!UP.AllowRemainder3
)
952
3
      ORE->emit([&]() {
953
0
        return OptimizationRemarkMissed(DEBUG_TYPE,
954
0
                                        "DifferentUnrollCountFromDirected",
955
0
                                        L->getStartLoc(), L->getHeader())
956
0
               << "Unable to unroll loop the number of times directed by "
957
0
                  "unroll_count pragma because remainder loop is restricted "
958
0
                  "(that could architecture specific or because the loop "
959
0
                  "contains a convergent instruction) and so must have an "
960
0
                  "unroll "
961
0
                  "count that divides the loop trip multiple of "
962
0
               << NV("TripMultiple", TripMultiple) << ".  Unrolling instead "
963
0
               << NV("UnrollCount", UP.Count) << " time(s).";
964
0
      });
965
5
  }
966
4.69k
967
4.69k
  if (UP.Count > UP.MaxCount)
968
0
    UP.Count = UP.MaxCount;
969
4.69k
  LLVM_DEBUG(dbgs() << "  partially unrolling with count: " << UP.Count
970
4.69k
                    << "\n");
971
4.69k
  if (UP.Count < 2)
972
589
    UP.Count = 0;
973
4.69k
  return ExplicitUnroll;
974
4.69k
}
975
976
static LoopUnrollResult tryToUnrollLoop(
977
    Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE,
978
    const TargetTransformInfo &TTI, AssumptionCache &AC,
979
    OptimizationRemarkEmitter &ORE,
980
    BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
981
    bool PreserveLCSSA, int OptLevel,
982
    bool OnlyWhenForced, bool ForgetAllSCEV, Optional<unsigned> ProvidedCount,
983
    Optional<unsigned> ProvidedThreshold, Optional<bool> ProvidedAllowPartial,
984
    Optional<bool> ProvidedRuntime, Optional<bool> ProvidedUpperBound,
985
390k
    Optional<bool> ProvidedAllowPeeling) {
986
390k
  LLVM_DEBUG(dbgs() << "Loop Unroll: F["
987
390k
                    << L->getHeader()->getParent()->getName() << "] Loop %"
988
390k
                    << L->getHeader()->getName() << "\n");
989
390k
  TransformationMode TM = hasUnrollTransformation(L);
990
390k
  if (TM & TM_Disable)
991
22
    return LoopUnrollResult::Unmodified;
992
390k
  if (!L->isLoopSimplifyForm()) {
993
8
    LLVM_DEBUG(
994
8
        dbgs() << "  Not unrolling loop which is not in loop-simplify form.\n");
995
8
    return LoopUnrollResult::Unmodified;
996
8
  }
997
390k
998
390k
  // When automtatic unrolling is disabled, do not unroll unless overridden for
999
390k
  // this loop.
1000
390k
  if (OnlyWhenForced && 
!(TM & TM_Enable)117
)
1001
116
    return LoopUnrollResult::Unmodified;
1002
390k
1003
390k
  bool OptForSize = L->getHeader()->getParent()->hasOptSize();
1004
390k
  unsigned NumInlineCandidates;
1005
390k
  bool NotDuplicatable;
1006
390k
  bool Convergent;
1007
390k
  TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
1008
390k
      L, SE, TTI, BFI, PSI, OptLevel, ProvidedThreshold, ProvidedCount,
1009
390k
      ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1010
390k
      ProvidedAllowPeeling);
1011
390k
1012
390k
  // Exit early if unrolling is disabled. For OptForSize, we pick the loop size
1013
390k
  // as threshold later on.
1014
390k
  if (UP.Threshold == 0 && 
(133
!UP.Partial133
||
UP.PartialThreshold == 08
) &&
1015
390k
      
!OptForSize133
)
1016
1
    return LoopUnrollResult::Unmodified;
1017
390k
1018
390k
  SmallPtrSet<const Value *, 32> EphValues;
1019
390k
  CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1020
390k
1021
390k
  unsigned LoopSize =
1022
390k
      ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
1023
390k
                          TTI, EphValues, UP.BEInsns);
1024
390k
  LLVM_DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
1025
390k
  if (NotDuplicatable) {
1026
14
    LLVM_DEBUG(dbgs() << "  Not unrolling loop which contains non-duplicatable"
1027
14
                      << " instructions.\n");
1028
14
    return LoopUnrollResult::Unmodified;
1029
14
  }
1030
390k
1031
390k
  // When optimizing for size, use LoopSize as threshold, to (fully) unroll
1032
390k
  // loops, if it does not increase code size.
1033
390k
  if (OptForSize)
1034
134
    UP.Threshold = std::max(UP.Threshold, LoopSize);
1035
390k
1036
390k
  if (NumInlineCandidates != 0) {
1037
54
    LLVM_DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
1038
54
    return LoopUnrollResult::Unmodified;
1039
54
  }
1040
390k
1041
390k
  // Find trip count and trip multiple if count is not available
1042
390k
  unsigned TripCount = 0;
1043
390k
  unsigned MaxTripCount = 0;
1044
390k
  unsigned TripMultiple = 1;
1045
390k
  // If there are multiple exiting blocks but one of them is the latch, use the
1046
390k
  // latch for the trip count estimation. Otherwise insist on a single exiting
1047
390k
  // block for the trip count estimation.
1048
390k
  BasicBlock *ExitingBlock = L->getLoopLatch();
1049
390k
  if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1050
12.8k
    ExitingBlock = L->getExitingBlock();
1051
390k
  if (ExitingBlock) {
1052
387k
    TripCount = SE.getSmallConstantTripCount(L, ExitingBlock);
1053
387k
    TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
1054
387k
  }
1055
390k
1056
390k
  // If the loop contains a convergent operation, the prelude we'd add
1057
390k
  // to do the first few instructions before we hit the unrolled loop
1058
390k
  // is unsafe -- it adds a control-flow dependency to the convergent
1059
390k
  // operation.  Therefore restrict remainder loop (try unrollig without).
1060
390k
  //
1061
390k
  // TODO: This is quite conservative.  In practice, convergent_op()
1062
390k
  // is likely to be called unconditionally in the loop.  In this
1063
390k
  // case, the program would be ill-formed (on most architectures)
1064
390k
  // unless n were the same on all threads in a thread group.
1065
390k
  // Assuming n is the same on all threads, any kind of unrolling is
1066
390k
  // safe.  But currently llvm's notion of convergence isn't powerful
1067
390k
  // enough to express this.
1068
390k
  if (Convergent)
1069
10
    UP.AllowRemainder = false;
1070
390k
1071
390k
  // Try to find the trip count upper bound if we cannot find the exact trip
1072
390k
  // count.
1073
390k
  bool MaxOrZero = false;
1074
390k
  if (!TripCount) {
1075
344k
    MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1076
344k
    MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1077
344k
    // We can unroll by the upper bound amount if it's generally allowed or if
1078
344k
    // we know that the loop is executed either the upper bound or zero times.
1079
344k
    // (MaxOrZero unrolling keeps only the first loop test, so the number of
1080
344k
    // loop tests remains the same compared to the non-unrolled version, whereas
1081
344k
    // the generic upper bound unrolling keeps all but the last loop test so the
1082
344k
    // number of loop tests goes up which may end up being worse on targets with
1083
344k
    // constrained branch predictor resources so is controlled by an option.)
1084
344k
    // In addition we only unroll small upper bounds.
1085
344k
    if (!(UP.UpperBound || 
MaxOrZero339k
) ||
MaxTripCount > UnrollMaxUpperBound4.92k
) {
1086
340k
      MaxTripCount = 0;
1087
340k
    }
1088
344k
  }
1089
390k
1090
390k
  // computeUnrollCount() decides whether it is beneficial to use upper bound to
1091
390k
  // fully unroll the loop.
1092
390k
  bool UseUpperBound = false;
1093
390k
  bool IsCountSetExplicitly = computeUnrollCount(
1094
390k
      L, TTI, DT, LI, SE, EphValues, &ORE, TripCount, MaxTripCount,
1095
390k
      TripMultiple, LoopSize, UP, UseUpperBound);
1096
390k
  if (!UP.Count)
1097
376k
    return LoopUnrollResult::Unmodified;
1098
13.7k
  // Unroll factor (Count) must be less or equal to TripCount.
1099
13.7k
  if (TripCount && 
UP.Count > TripCount9.56k
)
1100
0
    UP.Count = TripCount;
1101
13.7k
1102
13.7k
  // Save loop properties before it is transformed.
1103
13.7k
  MDNode *OrigLoopID = L->getLoopID();
1104
13.7k
1105
13.7k
  // Unroll the loop.
1106
13.7k
  Loop *RemainderLoop = nullptr;
1107
13.7k
  LoopUnrollResult UnrollResult = UnrollLoop(
1108
13.7k
      L,
1109
13.7k
      {UP.Count, TripCount, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount,
1110
13.7k
       UseUpperBound, MaxOrZero, TripMultiple, UP.PeelCount, UP.UnrollRemainder,
1111
13.7k
       ForgetAllSCEV},
1112
13.7k
      LI, &SE, &DT, &AC, &ORE, PreserveLCSSA, &RemainderLoop);
1113
13.7k
  if (UnrollResult == LoopUnrollResult::Unmodified)
1114
2.67k
    return LoopUnrollResult::Unmodified;
1115
11.1k
1116
11.1k
  if (RemainderLoop) {
1117
1.05k
    Optional<MDNode *> RemainderLoopID =
1118
1.05k
        makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1119
1.05k
                                        LLVMLoopUnrollFollowupRemainder});
1120
1.05k
    if (RemainderLoopID.hasValue())
1121
2
      RemainderLoop->setLoopID(RemainderLoopID.getValue());
1122
1.05k
  }
1123
11.1k
1124
11.1k
  if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1125
1.77k
    Optional<MDNode *> NewLoopID =
1126
1.77k
        makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
1127
1.77k
                                        LLVMLoopUnrollFollowupUnrolled});
1128
1.77k
    if (NewLoopID.hasValue()) {
1129
3
      L->setLoopID(NewLoopID.getValue());
1130
3
1131
3
      // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1132
3
      // explicitly.
1133
3
      return UnrollResult;
1134
3
    }
1135
11.1k
  }
1136
11.1k
1137
11.1k
  // If loop has an unroll count pragma or unrolled by explicitly set count
1138
11.1k
  // mark loop as unrolled to prevent unrolling beyond that requested.
1139
11.1k
  // If the loop was peeled, we already "used up" the profile information
1140
11.1k
  // we had, so we don't want to unroll or peel again.
1141
11.1k
  if (UnrollResult != LoopUnrollResult::FullyUnrolled &&
1142
11.1k
      
(1.76k
IsCountSetExplicitly1.76k
||
UP.PeelCount1.70k
))
1143
179
    L->setLoopAlreadyUnrolled();
1144
11.1k
1145
11.1k
  return UnrollResult;
1146
11.1k
}
1147
1148
namespace {
1149
1150
class LoopUnroll : public LoopPass {
1151
public:
1152
  static char ID; // Pass ID, replacement for typeid
1153
1154
  int OptLevel;
1155
1156
  /// If false, use a cost model to determine whether unrolling of a loop is
1157
  /// profitable. If true, only loops that explicitly request unrolling via
1158
  /// metadata are considered. All other loops are skipped.
1159
  bool OnlyWhenForced;
1160
1161
  /// If false, when SCEV is invalidated, only forget everything in the
1162
  /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1163
  /// Otherwise, forgetAllLoops and rebuild when needed next.
1164
  bool ForgetAllSCEV;
1165
1166
  Optional<unsigned> ProvidedCount;
1167
  Optional<unsigned> ProvidedThreshold;
1168
  Optional<bool> ProvidedAllowPartial;
1169
  Optional<bool> ProvidedRuntime;
1170
  Optional<bool> ProvidedUpperBound;
1171
  Optional<bool> ProvidedAllowPeeling;
1172
1173
  LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
1174
             bool ForgetAllSCEV = false, Optional<unsigned> Threshold = None,
1175
             Optional<unsigned> Count = None,
1176
             Optional<bool> AllowPartial = None, Optional<bool> Runtime = None,
1177
             Optional<bool> UpperBound = None,
1178
             Optional<bool> AllowPeeling = None)
1179
      : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1180
        ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)),
1181
        ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
1182
        ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
1183
26.9k
        ProvidedAllowPeeling(AllowPeeling) {
1184
26.9k
    initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
1185
26.9k
  }
1186
1187
390k
  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1188
390k
    if (skipLoop(L))
1189
34
      return false;
1190
390k
1191
390k
    Function &F = *L->getHeader()->getParent();
1192
390k
1193
390k
    auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1194
390k
    LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1195
390k
    ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1196
390k
    const TargetTransformInfo &TTI =
1197
390k
        getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1198
390k
    auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1199
390k
    // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1200
390k
    // pass.  Function analyses need to be preserved across loop transformations
1201
390k
    // but ORE cannot be preserved (see comment before the pass definition).
1202
390k
    OptimizationRemarkEmitter ORE(&F);
1203
390k
    bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1204
390k
1205
390k
    LoopUnrollResult Result = tryToUnrollLoop(
1206
390k
        L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr,
1207
390k
        PreserveLCSSA, OptLevel, OnlyWhenForced,
1208
390k
        ForgetAllSCEV, ProvidedCount, ProvidedThreshold, ProvidedAllowPartial,
1209
390k
        ProvidedRuntime, ProvidedUpperBound, ProvidedAllowPeeling);
1210
390k
1211
390k
    if (Result == LoopUnrollResult::FullyUnrolled)
1212
9.31k
      LPM.markLoopAsDeleted(*L);
1213
390k
1214
390k
    return Result != LoopUnrollResult::Unmodified;
1215
390k
  }
1216
1217
  /// This transformation requires natural loop information & requires that
1218
  /// loop preheaders be inserted into the CFG...
1219
26.9k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
1220
26.9k
    AU.addRequired<AssumptionCacheTracker>();
1221
26.9k
    AU.addRequired<TargetTransformInfoWrapperPass>();
1222
26.9k
    // FIXME: Loop passes are required to preserve domtree, and for now we just
1223
26.9k
    // recreate dom info if anything gets unrolled.
1224
26.9k
    getLoopAnalysisUsage(AU);
1225
26.9k
  }
1226
};
1227
1228
} // end anonymous namespace
1229
1230
char LoopUnroll::ID = 0;
1231
1232
48.9k
INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1233
48.9k
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1234
48.9k
INITIALIZE_PASS_DEPENDENCY(LoopPass)
1235
48.9k
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1236
48.9k
INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1237
1238
Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1239
                                 bool ForgetAllSCEV, int Threshold, int Count,
1240
                                 int AllowPartial, int Runtime, int UpperBound,
1241
26.8k
                                 int AllowPeeling) {
1242
26.8k
  // TODO: It would make more sense for this function to take the optionals
1243
26.8k
  // directly, but that's dangerous since it would silently break out of tree
1244
26.8k
  // callers.
1245
26.8k
  return new LoopUnroll(
1246
26.8k
      OptLevel, OnlyWhenForced, ForgetAllSCEV,
1247
26.8k
      Threshold == -1 ? None : 
Optional<unsigned>(Threshold)0
,
1248
26.8k
      Count == -1 ? 
None26.8k
:
Optional<unsigned>(Count)1
,
1249
26.8k
      AllowPartial == -1 ? 
None13.4k
:
Optional<bool>(AllowPartial)13.4k
,
1250
26.8k
      Runtime == -1 ? 
None13.4k
:
Optional<bool>(Runtime)13.4k
,
1251
26.8k
      UpperBound == -1 ? 
None13.4k
:
Optional<bool>(UpperBound)13.4k
,
1252
26.8k
      AllowPeeling == -1 ? 
None13.4k
:
Optional<bool>(AllowPeeling)13.4k
);
1253
26.8k
}
1254
1255
Pass *llvm::createSimpleLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1256
13.4k
                                       bool ForgetAllSCEV) {
1257
13.4k
  return createLoopUnrollPass(OptLevel, OnlyWhenForced, ForgetAllSCEV, -1, -1,
1258
13.4k
                              0, 0, 0, 0);
1259
13.4k
}
1260
1261
PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM,
1262
                                          LoopStandardAnalysisResults &AR,
1263
136
                                          LPMUpdater &Updater) {
1264
136
  const auto &FAM =
1265
136
      AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1266
136
  Function *F = L.getHeader()->getParent();
1267
136
1268
136
  auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
1269
136
  // FIXME: This should probably be optional rather than required.
1270
136
  if (!ORE)
1271
0
    report_fatal_error(
1272
0
        "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not "
1273
0
        "cached at a higher level");
1274
136
1275
136
  // Keep track of the previous loop structure so we can identify new loops
1276
136
  // created by unrolling.
1277
136
  Loop *ParentL = L.getParentLoop();
1278
136
  SmallPtrSet<Loop *, 4> OldLoops;
1279
136
  if (ParentL)
1280
30
    OldLoops.insert(ParentL->begin(), ParentL->end());
1281
106
  else
1282
106
    OldLoops.insert(AR.LI.begin(), AR.LI.end());
1283
136
1284
136
  std::string LoopName = L.getName();
1285
136
1286
136
  bool Changed =
1287
136
      tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, *ORE,
1288
136
                      /*BFI*/ nullptr, /*PSI*/ nullptr,
1289
136
                      /*PreserveLCSSA*/ true, OptLevel, OnlyWhenForced,
1290
136
                      ForgetSCEV, /*Count*/ None,
1291
136
                      /*Threshold*/ None, /*AllowPartial*/ false,
1292
136
                      /*Runtime*/ false, /*UpperBound*/ false,
1293
136
                      /*AllowPeeling*/ false) != LoopUnrollResult::Unmodified;
1294
136
  if (!Changed)
1295
113
    return PreservedAnalyses::all();
1296
23
1297
23
  // The parent must not be damaged by unrolling!
1298
#ifndef NDEBUG
1299
  if (ParentL)
1300
    ParentL->verifyLoop();
1301
#endif
1302
1303
23
  // Unrolling can do several things to introduce new loops into a loop nest:
1304
23
  // - Full unrolling clones child loops within the current loop but then
1305
23
  //   removes the current loop making all of the children appear to be new
1306
23
  //   sibling loops.
1307
23
  //
1308
23
  // When a new loop appears as a sibling loop after fully unrolling,
1309
23
  // its nesting structure has fundamentally changed and we want to revisit
1310
23
  // it to reflect that.
1311
23
  //
1312
23
  // When unrolling has removed the current loop, we need to tell the
1313
23
  // infrastructure that it is gone.
1314
23
  //
1315
23
  // Finally, we support a debugging/testing mode where we revisit child loops
1316
23
  // as well. These are not expected to require further optimizations as either
1317
23
  // they or the loop they were cloned from have been directly visited already.
1318
23
  // But the debugging mode allows us to check this assumption.
1319
23
  bool IsCurrentLoopValid = false;
1320
23
  SmallVector<Loop *, 4> SibLoops;
1321
23
  if (ParentL)
1322
4
    SibLoops.append(ParentL->begin(), ParentL->end());
1323
19
  else
1324
19
    SibLoops.append(AR.LI.begin(), AR.LI.end());
1325
23
  erase_if(SibLoops, [&](Loop *SibLoop) {
1326
14
    if (SibLoop == &L) {
1327
2
      IsCurrentLoopValid = true;
1328
2
      return true;
1329
2
    }
1330
12
1331
12
    // Otherwise erase the loop from the list if it was in the old loops.
1332
12
    return OldLoops.count(SibLoop) != 0;
1333
12
  });
1334
23
  Updater.addSiblingLoops(SibLoops);
1335
23
1336
23
  if (!IsCurrentLoopValid) {
1337
21
    Updater.markLoopAsDeleted(L, LoopName);
1338
21
  } else {
1339
2
    // We can only walk child loops if the current loop remained valid.
1340
2
    if (UnrollRevisitChildLoops) {
1341
1
      // Walk *all* of the child loops.
1342
1
      SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1343
1
      Updater.addChildLoops(ChildLoops);
1344
1
    }
1345
2
  }
1346
23
1347
23
  return getLoopPassPreservedAnalyses();
1348
23
}
1349
1350
template <typename RangeT>
1351
520
static SmallVector<Loop *, 8> appendLoopsToWorklist(RangeT &&Loops) {
1352
520
  SmallVector<Loop *, 8> Worklist;
1353
520
  // We use an internal worklist to build up the preorder traversal without
1354
520
  // recursion.
1355
520
  SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1356
520
1357
520
  for (Loop *RootL : Loops) {
1358
103
    assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1359
103
    assert(PreOrderWorklist.empty() &&
1360
103
           "Must start with an empty preorder walk worklist.");
1361
103
    PreOrderWorklist.push_back(RootL);
1362
124
    do {
1363
124
      Loop *L = PreOrderWorklist.pop_back_val();
1364
124
      PreOrderWorklist.append(L->begin(), L->end());
1365
124
      PreOrderLoops.push_back(L);
1366
124
    } while (!PreOrderWorklist.empty());
1367
103
1368
103
    Worklist.append(PreOrderLoops.begin(), PreOrderLoops.end());
1369
103
    PreOrderLoops.clear();
1370
103
  }
1371
520
  return Worklist;
1372
520
}
1373
1374
PreservedAnalyses LoopUnrollPass::run(Function &F,
1375
520
                                      FunctionAnalysisManager &AM) {
1376
520
  auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1377
520
  auto &LI = AM.getResult<LoopAnalysis>(F);
1378
520
  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1379
520
  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1380
520
  auto &AC = AM.getResult<AssumptionAnalysis>(F);
1381
520
  auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1382
520
1383
520
  LoopAnalysisManager *LAM = nullptr;
1384
520
  if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1385
448
    LAM = &LAMProxy->getManager();
1386
520
1387
520
  const ModuleAnalysisManager &MAM =
1388
520
      AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
1389
520
  ProfileSummaryInfo *PSI =
1390
520
      MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1391
520
  auto *BFI = (PSI && 
PSI->hasProfileSummary()461
) ?
1392
490
      
&AM.getResult<BlockFrequencyAnalysis>(F)30
: nullptr;
1393
520
1394
520
  bool Changed = false;
1395
520
1396
520
  // The unroller requires loops to be in simplified form, and also needs LCSSA.
1397
520
  // Since simplification may add new inner loops, it has to run before the
1398
520
  // legality and profitability checks. This means running the loop unroller
1399
520
  // will simplify all loops, regardless of whether anything end up being
1400
520
  // unrolled.
1401
520
  for (auto &L : LI) {
1402
103
    Changed |=
1403
103
        simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
1404
103
    Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1405
103
  }
1406
520
1407
520
  SmallVector<Loop *, 8> Worklist = appendLoopsToWorklist(LI);
1408
520
1409
644
  while (!Worklist.empty()) {
1410
124
    // Because the LoopInfo stores the loops in RPO, we walk the worklist
1411
124
    // from back to front so that we work forward across the CFG, which
1412
124
    // for unrolling is only needed to get optimization remarks emitted in
1413
124
    // a forward order.
1414
124
    Loop &L = *Worklist.pop_back_val();
1415
#ifndef NDEBUG
1416
    Loop *ParentL = L.getParentLoop();
1417
#endif
1418
1419
124
    // Check if the profile summary indicates that the profiled application
1420
124
    // has a huge working set size, in which case we disable peeling to avoid
1421
124
    // bloating it further.
1422
124
    Optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
1423
124
    if (PSI && 
PSI->hasHugeWorkingSetSize()46
)
1424
0
      LocalAllowPeeling = false;
1425
124
    std::string LoopName = L.getName();
1426
124
    // The API here is quite complex to call and we allow to select some
1427
124
    // flavors of unrolling during construction time (by setting UnrollOpts).
1428
124
    LoopUnrollResult Result = tryToUnrollLoop(
1429
124
        &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1430
124
        /*PreserveLCSSA*/ true, UnrollOpts.OptLevel, UnrollOpts.OnlyWhenForced,
1431
124
        UnrollOpts.ForgetSCEV, /*Count*/ None,
1432
124
        /*Threshold*/ None, UnrollOpts.AllowPartial, UnrollOpts.AllowRuntime,
1433
124
        UnrollOpts.AllowUpperBound, LocalAllowPeeling);
1434
124
    Changed |= Result != LoopUnrollResult::Unmodified;
1435
124
1436
124
    // The parent must not be damaged by unrolling!
1437
#ifndef NDEBUG
1438
    if (Result != LoopUnrollResult::Unmodified && ParentL)
1439
      ParentL->verifyLoop();
1440
#endif
1441
1442
124
    // Clear any cached analysis results for L if we removed it completely.
1443
124
    if (LAM && 
Result == LoopUnrollResult::FullyUnrolled33
)
1444
2
      LAM->clear(L, LoopName);
1445
124
  }
1446
520
1447
520
  if (!Changed)
1448
470
    return PreservedAnalyses::all();
1449
50
1450
50
  return getLoopPassPreservedAnalyses();
1451
50
}