Coverage Report

Created: 2018-10-23 09:19

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Analysis/ScopDetection.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
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
// Detect the maximal Scops of a function.
11
//
12
// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13
// that only has statically known control flow and can therefore be described
14
// within the polyhedral model.
15
//
16
// Every Scop fulfills these restrictions:
17
//
18
// * It is a single entry single exit region
19
//
20
// * Only affine linear bounds in the loops
21
//
22
// Every natural loop in a Scop must have a number of loop iterations that can
23
// be described as an affine linear function in surrounding loop iterators or
24
// parameters. (A parameter is a scalar that does not change its value during
25
// execution of the Scop).
26
//
27
// * Only comparisons of affine linear expressions in conditions
28
//
29
// * All loops and conditions perfectly nested
30
//
31
// The control flow needs to be structured such that it could be written using
32
// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33
// 'continue'.
34
//
35
// * Side effect free functions call
36
//
37
// Function calls and intrinsics that do not have side effects (readnone)
38
// or memory intrinsics (memset, memcpy, memmove) are allowed.
39
//
40
// The Scop detection finds the largest Scops by checking if the largest
41
// region is a Scop. If this is not the case, its canonical subregions are
42
// checked until a region is a Scop. It is now tried to extend this Scop by
43
// creating a larger non canonical region.
44
//
45
//===----------------------------------------------------------------------===//
46
47
#include "polly/ScopDetection.h"
48
#include "polly/LinkAllPasses.h"
49
#include "polly/Options.h"
50
#include "polly/ScopDetectionDiagnostic.h"
51
#include "polly/Support/SCEVValidator.h"
52
#include "polly/Support/ScopHelper.h"
53
#include "polly/Support/ScopLocation.h"
54
#include "llvm/ADT/DenseMap.h"
55
#include "llvm/ADT/SetVector.h"
56
#include "llvm/ADT/SmallPtrSet.h"
57
#include "llvm/ADT/SmallVector.h"
58
#include "llvm/ADT/Statistic.h"
59
#include "llvm/ADT/StringRef.h"
60
#include "llvm/Analysis/AliasAnalysis.h"
61
#include "llvm/Analysis/Loads.h"
62
#include "llvm/Analysis/LoopInfo.h"
63
#include "llvm/Analysis/MemoryLocation.h"
64
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
65
#include "llvm/Analysis/RegionInfo.h"
66
#include "llvm/Analysis/ScalarEvolution.h"
67
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
68
#include "llvm/IR/BasicBlock.h"
69
#include "llvm/IR/Constants.h"
70
#include "llvm/IR/DebugLoc.h"
71
#include "llvm/IR/DerivedTypes.h"
72
#include "llvm/IR/DiagnosticInfo.h"
73
#include "llvm/IR/DiagnosticPrinter.h"
74
#include "llvm/IR/Dominators.h"
75
#include "llvm/IR/Function.h"
76
#include "llvm/IR/InstrTypes.h"
77
#include "llvm/IR/Instruction.h"
78
#include "llvm/IR/Instructions.h"
79
#include "llvm/IR/IntrinsicInst.h"
80
#include "llvm/IR/Intrinsics.h"
81
#include "llvm/IR/LLVMContext.h"
82
#include "llvm/IR/Metadata.h"
83
#include "llvm/IR/Module.h"
84
#include "llvm/IR/PassManager.h"
85
#include "llvm/IR/Type.h"
86
#include "llvm/IR/Value.h"
87
#include "llvm/Pass.h"
88
#include "llvm/Support/Casting.h"
89
#include "llvm/Support/CommandLine.h"
90
#include "llvm/Support/Debug.h"
91
#include "llvm/Support/ErrorHandling.h"
92
#include "llvm/Support/Regex.h"
93
#include "llvm/Support/raw_ostream.h"
94
#include <algorithm>
95
#include <cassert>
96
#include <memory>
97
#include <stack>
98
#include <string>
99
#include <utility>
100
#include <vector>
101
102
using namespace llvm;
103
using namespace polly;
104
105
#define DEBUG_TYPE "polly-detect"
106
107
// This option is set to a very high value, as analyzing such loops increases
108
// compile time on several cases. For experiments that enable this option,
109
// a value of around 40 has been working to avoid run-time regressions with
110
// Polly while still exposing interesting optimization opportunities.
111
static cl::opt<int> ProfitabilityMinPerLoopInstructions(
112
    "polly-detect-profitability-min-per-loop-insts",
113
    cl::desc("The minimal number of per-loop instructions before a single loop "
114
             "region is considered profitable"),
115
    cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
116
117
bool polly::PollyProcessUnprofitable;
118
119
static cl::opt<bool, true> XPollyProcessUnprofitable(
120
    "polly-process-unprofitable",
121
    cl::desc(
122
        "Process scops that are unlikely to benefit from Polly optimizations."),
123
    cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
124
    cl::cat(PollyCategory));
125
126
static cl::list<std::string> OnlyFunctions(
127
    "polly-only-func",
128
    cl::desc("Only run on functions that match a regex. "
129
             "Multiple regexes can be comma separated. "
130
             "Scop detection will run on all functions that match "
131
             "ANY of the regexes provided."),
132
    cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
133
134
static cl::list<std::string> IgnoredFunctions(
135
    "polly-ignore-func",
136
    cl::desc("Ignore functions that match a regex. "
137
             "Multiple regexes can be comma separated. "
138
             "Scop detection will ignore all functions that match "
139
             "ANY of the regexes provided."),
140
    cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
141
142
bool polly::PollyAllowFullFunction;
143
144
static cl::opt<bool, true>
145
    XAllowFullFunction("polly-detect-full-functions",
146
                       cl::desc("Allow the detection of full functions"),
147
                       cl::location(polly::PollyAllowFullFunction),
148
                       cl::init(false), cl::cat(PollyCategory));
149
150
static cl::opt<std::string> OnlyRegion(
151
    "polly-only-region",
152
    cl::desc("Only run on certain regions (The provided identifier must "
153
             "appear in the name of the region's entry block"),
154
    cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
155
    cl::cat(PollyCategory));
156
157
static cl::opt<bool>
158
    IgnoreAliasing("polly-ignore-aliasing",
159
                   cl::desc("Ignore possible aliasing of the array bases"),
160
                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
161
                   cl::cat(PollyCategory));
162
163
bool polly::PollyAllowUnsignedOperations;
164
165
static cl::opt<bool, true> XPollyAllowUnsignedOperations(
166
    "polly-allow-unsigned-operations",
167
    cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
168
    cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
169
    cl::init(true), cl::cat(PollyCategory));
170
171
bool polly::PollyUseRuntimeAliasChecks;
172
173
static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
174
    "polly-use-runtime-alias-checks",
175
    cl::desc("Use runtime alias checks to resolve possible aliasing."),
176
    cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
177
    cl::init(true), cl::cat(PollyCategory));
178
179
static cl::opt<bool>
180
    ReportLevel("polly-report",
181
                cl::desc("Print information about the activities of Polly"),
182
                cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
183
184
static cl::opt<bool> AllowDifferentTypes(
185
    "polly-allow-differing-element-types",
186
    cl::desc("Allow different element types for array accesses"), cl::Hidden,
187
    cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
188
189
static cl::opt<bool>
190
    AllowNonAffine("polly-allow-nonaffine",
191
                   cl::desc("Allow non affine access functions in arrays"),
192
                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
193
                   cl::cat(PollyCategory));
194
195
static cl::opt<bool>
196
    AllowModrefCall("polly-allow-modref-calls",
197
                    cl::desc("Allow functions with known modref behavior"),
198
                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
199
                    cl::cat(PollyCategory));
200
201
static cl::opt<bool> AllowNonAffineSubRegions(
202
    "polly-allow-nonaffine-branches",
203
    cl::desc("Allow non affine conditions for branches"), cl::Hidden,
204
    cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
205
206
static cl::opt<bool>
207
    AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
208
                           cl::desc("Allow non affine conditions for loops"),
209
                           cl::Hidden, cl::init(false), cl::ZeroOrMore,
210
                           cl::cat(PollyCategory));
211
212
static cl::opt<bool, true>
213
    TrackFailures("polly-detect-track-failures",
214
                  cl::desc("Track failure strings in detecting scop regions"),
215
                  cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
216
                  cl::init(true), cl::cat(PollyCategory));
217
218
static cl::opt<bool> KeepGoing("polly-detect-keep-going",
219
                               cl::desc("Do not fail on the first error."),
220
                               cl::Hidden, cl::ZeroOrMore, cl::init(false),
221
                               cl::cat(PollyCategory));
222
223
static cl::opt<bool, true>
224
    PollyDelinearizeX("polly-delinearize",
225
                      cl::desc("Delinearize array access functions"),
226
                      cl::location(PollyDelinearize), cl::Hidden,
227
                      cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
228
229
static cl::opt<bool>
230
    VerifyScops("polly-detect-verify",
231
                cl::desc("Verify the detected SCoPs after each transformation"),
232
                cl::Hidden, cl::init(false), cl::ZeroOrMore,
233
                cl::cat(PollyCategory));
234
235
bool polly::PollyInvariantLoadHoisting;
236
237
static cl::opt<bool, true> XPollyInvariantLoadHoisting(
238
    "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
239
    cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
240
    cl::init(false), cl::cat(PollyCategory));
241
242
/// The minimal trip count under which loops are considered unprofitable.
243
static const unsigned MIN_LOOP_TRIP_COUNT = 8;
244
245
bool polly::PollyTrackFailures = false;
246
bool polly::PollyDelinearize = false;
247
StringRef polly::PollySkipFnAttr = "polly.skip.fn";
248
249
//===----------------------------------------------------------------------===//
250
// Statistics.
251
252
STATISTIC(NumScopRegions, "Number of scops");
253
STATISTIC(NumLoopsInScop, "Number of loops in scops");
254
STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
255
STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
256
STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
257
STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
258
STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
259
STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
260
STATISTIC(NumScopsDepthLarger,
261
          "Number of scops with maximal loop depth 6 and larger");
262
STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
263
STATISTIC(NumLoopsInProfScop,
264
          "Number of loops in scops (profitable scops only)");
265
STATISTIC(NumLoopsOverall, "Number of total loops");
266
STATISTIC(NumProfScopsDepthZero,
267
          "Number of scops with maximal loop depth 0 (profitable scops only)");
268
STATISTIC(NumProfScopsDepthOne,
269
          "Number of scops with maximal loop depth 1 (profitable scops only)");
270
STATISTIC(NumProfScopsDepthTwo,
271
          "Number of scops with maximal loop depth 2 (profitable scops only)");
272
STATISTIC(NumProfScopsDepthThree,
273
          "Number of scops with maximal loop depth 3 (profitable scops only)");
274
STATISTIC(NumProfScopsDepthFour,
275
          "Number of scops with maximal loop depth 4 (profitable scops only)");
276
STATISTIC(NumProfScopsDepthFive,
277
          "Number of scops with maximal loop depth 5 (profitable scops only)");
278
STATISTIC(NumProfScopsDepthLarger,
279
          "Number of scops with maximal loop depth 6 and larger "
280
          "(profitable scops only)");
281
STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
282
STATISTIC(MaxNumLoopsInProfScop,
283
          "Maximal number of loops in scops (profitable scops only)");
284
285
static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
286
                                     bool OnlyProfitable);
287
288
namespace {
289
290
class DiagnosticScopFound : public DiagnosticInfo {
291
private:
292
  static int PluginDiagnosticKind;
293
294
  Function &F;
295
  std::string FileName;
296
  unsigned EntryLine, ExitLine;
297
298
public:
299
  DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
300
                      unsigned ExitLine)
301
      : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
302
2
        EntryLine(EntryLine), ExitLine(ExitLine) {}
303
304
  void print(DiagnosticPrinter &DP) const override;
305
306
0
  static bool classof(const DiagnosticInfo *DI) {
307
0
    return DI->getKind() == PluginDiagnosticKind;
308
0
  }
309
};
310
} // namespace
311
312
int DiagnosticScopFound::PluginDiagnosticKind =
313
    getNextAvailablePluginDiagnosticKind();
314
315
2
void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
316
2
  DP << "Polly detected an optimizable loop region (scop) in function '" << F
317
2
     << "'\n";
318
2
319
2
  if (FileName.empty()) {
320
0
    DP << "Scop location is unknown. Compile with debug info "
321
0
          "(-g) to get more precise information. ";
322
0
    return;
323
0
  }
324
2
325
2
  DP << FileName << ":" << EntryLine << ": Start of scop\n";
326
2
  DP << FileName << ":" << ExitLine << ": End of scop";
327
2
}
328
329
/// Check if a string matches any regex in a list of regexes.
330
/// @param Str the input string to match against.
331
/// @param RegexList a list of strings that are regular expressions.
332
static bool doesStringMatchAnyRegex(StringRef Str,
333
1.43k
                                    const cl::list<std::string> &RegexList) {
334
1.43k
  for (auto RegexStr : RegexList) {
335
17
    Regex R(RegexStr);
336
17
337
17
    std::string Err;
338
17
    if (!R.isValid(Err))
339
0
      report_fatal_error("invalid regex given as input to polly: " + Err, true);
340
17
341
17
    if (R.match(Str))
342
8
      return true;
343
17
  }
344
1.43k
  
return false1.42k
;
345
1.43k
}
346
//===----------------------------------------------------------------------===//
347
// ScopDetection.
348
349
ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
350
                             ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
351
                             AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
352
1.42k
    : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
353
1.42k
  if (!PollyProcessUnprofitable && 
LI.empty()22
)
354
0
    return;
355
1.42k
356
1.42k
  Region *TopRegion = RI.getTopLevelRegion();
357
1.42k
358
1.42k
  if (!OnlyFunctions.empty() &&
359
1.42k
      
!doesStringMatchAnyRegex(F.getName(), OnlyFunctions)7
)
360
2
    return;
361
1.42k
362
1.42k
  if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
363
3
    return;
364
1.42k
365
1.42k
  if (!isValidFunction(F))
366
31
    return;
367
1.38k
368
1.38k
  findScops(*TopRegion);
369
1.38k
370
1.38k
  NumScopRegions += ValidRegions.size();
371
1.38k
372
1.38k
  // Prune non-profitable regions.
373
3.66k
  for (auto &DIt : DetectionContextMap) {
374
3.66k
    auto &DC = DIt.getSecond();
375
3.66k
    if (DC.Log.hasErrors())
376
430
      continue;
377
3.23k
    if (!ValidRegions.count(&DC.CurRegion))
378
1.94k
      continue;
379
1.28k
    LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
380
1.28k
    updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
381
1.28k
    if (isProfitableRegion(DC)) {
382
1.27k
      updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
383
1.27k
      continue;
384
1.27k
    }
385
15
386
15
    ValidRegions.remove(&DC.CurRegion);
387
15
  }
388
1.38k
389
1.38k
  NumProfScopRegions += ValidRegions.size();
390
1.38k
  NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
391
1.38k
392
1.38k
  // Only makes sense when we tracked errors.
393
1.38k
  if (PollyTrackFailures)
394
1.38k
    emitMissedRemarks(F);
395
1.38k
396
1.38k
  if (ReportLevel)
397
2
    printLocations(F);
398
1.38k
399
1.38k
  assert(ValidRegions.size() <= DetectionContextMap.size() &&
400
1.38k
         "Cached more results than valid regions");
401
1.38k
}
402
403
template <class RR, typename... Args>
404
inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
405
602
                                   Args &&... Arguments) const {
406
602
  if (!Context.Verifying) {
407
602
    RejectLog &Log = Context.Log;
408
602
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
602
410
602
    if (PollyTrackFailures)
411
602
      Log.report(RejectReason);
412
602
413
602
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
602
    LLVM_DEBUG(dbgs() << "\n");
415
602
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
602
419
602
  return false;
420
602
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNonAffBranch, llvm::BasicBlock*, llvm::SCEV const*&, llvm::SCEV const*&, llvm::SwitchInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::SCEV const*&&&, llvm::SCEV const*&&&, llvm::SwitchInst*&&&) const
bool polly::ScopDetection::invalid<polly::ReportInvalidCond, llvm::BranchInst*&, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BranchInst*&&&, llvm::BasicBlock*&&) const
Line
Count
Source
405
1
                                   Args &&... Arguments) const {
406
1
  if (!Context.Verifying) {
407
1
    RejectLog &Log = Context.Log;
408
1
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
1
410
1
    if (PollyTrackFailures)
411
1
      Log.report(RejectReason);
412
1
413
1
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
1
    LLVM_DEBUG(dbgs() << "\n");
415
1
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
1
419
1
  return false;
420
1
}
bool polly::ScopDetection::invalid<polly::ReportUndefOperand, llvm::BasicBlock*, llvm::ICmpInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::ICmpInst*&&&) const
Line
Count
Source
405
5
                                   Args &&... Arguments) const {
406
5
  if (!Context.Verifying) {
407
5
    RejectLog &Log = Context.Log;
408
5
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
5
410
5
    if (PollyTrackFailures)
411
5
      Log.report(RejectReason);
412
5
413
5
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
5
    LLVM_DEBUG(dbgs() << "\n");
415
5
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
5
419
5
  return false;
420
5
}
bool polly::ScopDetection::invalid<polly::ReportNonAffBranch, llvm::BasicBlock*, llvm::SCEV const*&, llvm::SCEV const*&, llvm::ICmpInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::SCEV const*&&&, llvm::SCEV const*&&&, llvm::ICmpInst*&&&) const
Line
Count
Source
405
5
                                   Args &&... Arguments) const {
406
5
  if (!Context.Verifying) {
407
5
    RejectLog &Log = Context.Log;
408
5
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
5
410
5
    if (PollyTrackFailures)
411
5
      Log.report(RejectReason);
412
5
413
5
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
5
    LLVM_DEBUG(dbgs() << "\n");
415
5
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
5
419
5
  return false;
420
5
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportInvalidTerminator, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&) const
bool polly::ScopDetection::invalid<polly::ReportUndefCond, llvm::Instruction*&, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&, llvm::BasicBlock*&&) const
Line
Count
Source
405
154
                                   Args &&... Arguments) const {
406
154
  if (!Context.Verifying) {
407
154
    RejectLog &Log = Context.Log;
408
154
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
154
410
154
    if (PollyTrackFailures)
411
154
      Log.report(RejectReason);
412
154
413
154
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
154
    LLVM_DEBUG(dbgs() << "\n");
415
154
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
154
419
154
  return false;
420
154
}
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const*&, llvm::Instruction const*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const*&&&, llvm::Instruction const*&&&, llvm::Value*&&&) const
Line
Count
Source
405
10
                                   Args &&... Arguments) const {
406
10
  if (!Context.Verifying) {
407
10
    RejectLog &Log = Context.Log;
408
10
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
10
410
10
    if (PollyTrackFailures)
411
10
      Log.report(RejectReason);
412
10
413
10
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
10
    LLVM_DEBUG(dbgs() << "\n");
415
10
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
10
419
10
  return false;
420
10
}
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const* const&, llvm::Instruction const*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const* const&&&, llvm::Instruction const*&&&, llvm::Value*&&&) const
Line
Count
Source
405
23
                                   Args &&... Arguments) const {
406
23
  if (!Context.Verifying) {
407
23
    RejectLog &Log = Context.Log;
408
23
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
23
410
23
    if (PollyTrackFailures)
411
23
      Log.report(RejectReason);
412
23
413
23
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
23
    LLVM_DEBUG(dbgs() << "\n");
415
23
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
23
419
23
  return false;
420
23
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNoBasePtr, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&) const
bool polly::ScopDetection::invalid<polly::ReportUndefBasePtr, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&) const
Line
Count
Source
405
6
                                   Args &&... Arguments) const {
406
6
  if (!Context.Verifying) {
407
6
    RejectLog &Log = Context.Log;
408
6
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
6
410
6
    if (PollyTrackFailures)
411
6
      Log.report(RejectReason);
412
6
413
6
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
6
    LLVM_DEBUG(dbgs() << "\n");
415
6
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
6
419
6
  return false;
420
6
}
bool polly::ScopDetection::invalid<polly::ReportIntToPtr, llvm::IntToPtrInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::IntToPtrInst*&&&) const
Line
Count
Source
405
1
                                   Args &&... Arguments) const {
406
1
  if (!Context.Verifying) {
407
1
    RejectLog &Log = Context.Log;
408
1
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
1
410
1
    if (PollyTrackFailures)
411
1
      Log.report(RejectReason);
412
1
413
1
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
1
    LLVM_DEBUG(dbgs() << "\n");
415
1
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
1
419
1
  return false;
420
1
}
bool polly::ScopDetection::invalid<polly::ReportVariantBasePtr, llvm::Value*&, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Value*&&&, llvm::Instruction*&&&) const
Line
Count
Source
405
10
                                   Args &&... Arguments) const {
406
10
  if (!Context.Verifying) {
407
10
    RejectLog &Log = Context.Log;
408
10
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
10
410
10
    if (PollyTrackFailures)
411
10
      Log.report(RejectReason);
412
10
413
10
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
10
    LLVM_DEBUG(dbgs() << "\n");
415
10
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
10
419
10
  return false;
420
10
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportDifferentArrayElementSize, llvm::Instruction*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&, llvm::Value*&&&) const
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const*&, llvm::Instruction*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const*&&&, llvm::Instruction*&&&, llvm::Value*&&&) const
Line
Count
Source
405
22
                                   Args &&... Arguments) const {
406
22
  if (!Context.Verifying) {
407
22
    RejectLog &Log = Context.Log;
408
22
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
22
410
22
    if (PollyTrackFailures)
411
22
      Log.report(RejectReason);
412
22
413
22
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
22
    LLVM_DEBUG(dbgs() << "\n");
415
22
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
22
419
22
  return false;
420
22
}
bool polly::ScopDetection::invalid<polly::ReportAlias, llvm::Instruction*&, llvm::AliasSet&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&, llvm::AliasSet&&&) const
Line
Count
Source
405
3
                                   Args &&... Arguments) const {
406
3
  if (!Context.Verifying) {
407
3
    RejectLog &Log = Context.Log;
408
3
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
3
410
3
    if (PollyTrackFailures)
411
3
      Log.report(RejectReason);
412
3
413
3
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
3
    LLVM_DEBUG(dbgs() << "\n");
415
3
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
3
419
3
  return false;
420
3
}
bool polly::ScopDetection::invalid<polly::ReportFuncCall, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Line
Count
Source
405
11
                                   Args &&... Arguments) const {
406
11
  if (!Context.Verifying) {
407
11
    RejectLog &Log = Context.Log;
408
11
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
11
410
11
    if (PollyTrackFailures)
411
11
      Log.report(RejectReason);
412
11
413
11
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
11
    LLVM_DEBUG(dbgs() << "\n");
415
11
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
11
419
11
  return false;
420
11
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportAlloca, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNonSimpleMemoryAccess, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
bool polly::ScopDetection::invalid<polly::ReportUnknownInst, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Line
Count
Source
405
49
                                   Args &&... Arguments) const {
406
49
  if (!Context.Verifying) {
407
49
    RejectLog &Log = Context.Log;
408
49
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
49
410
49
    if (PollyTrackFailures)
411
49
      Log.report(RejectReason);
412
49
413
49
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
49
    LLVM_DEBUG(dbgs() << "\n");
415
49
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
49
419
49
  return false;
420
49
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportLoopHasNoExit, llvm::Loop*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&) const
bool polly::ScopDetection::invalid<polly::ReportLoopHasMultipleExits, llvm::Loop*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&) const
Line
Count
Source
405
35
                                   Args &&... Arguments) const {
406
35
  if (!Context.Verifying) {
407
35
    RejectLog &Log = Context.Log;
408
35
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
35
410
35
    if (PollyTrackFailures)
411
35
      Log.report(RejectReason);
412
35
413
35
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
35
    LLVM_DEBUG(dbgs() << "\n");
415
35
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
35
419
35
  return false;
420
35
}
bool polly::ScopDetection::invalid<polly::ReportLoopBound, llvm::Loop*&, llvm::SCEV const*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&, llvm::SCEV const*&&&) const
Line
Count
Source
405
134
                                   Args &&... Arguments) const {
406
134
  if (!Context.Verifying) {
407
134
    RejectLog &Log = Context.Log;
408
134
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
134
410
134
    if (PollyTrackFailures)
411
134
      Log.report(RejectReason);
412
134
413
134
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
134
    LLVM_DEBUG(dbgs() << "\n");
415
134
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
134
419
134
  return false;
420
134
}
bool polly::ScopDetection::invalid<polly::ReportUnprofitable, llvm::Region*>(polly::ScopDetection::DetectionContext&, bool, llvm::Region*&&) const
Line
Count
Source
405
16
                                   Args &&... Arguments) const {
406
16
  if (!Context.Verifying) {
407
16
    RejectLog &Log = Context.Log;
408
16
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
16
410
16
    if (PollyTrackFailures)
411
16
      Log.report(RejectReason);
412
16
413
16
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
16
    LLVM_DEBUG(dbgs() << "\n");
415
16
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
16
419
16
  return false;
420
16
}
bool polly::ScopDetection::invalid<polly::ReportLoopOnlySomeLatches, llvm::Loop*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&) const
Line
Count
Source
405
5
                                   Args &&... Arguments) const {
406
5
  if (!Context.Verifying) {
407
5
    RejectLog &Log = Context.Log;
408
5
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
5
410
5
    if (PollyTrackFailures)
411
5
      Log.report(RejectReason);
412
5
413
5
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
5
    LLVM_DEBUG(dbgs() << "\n");
415
5
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
5
419
5
  return false;
420
5
}
bool polly::ScopDetection::invalid<polly::ReportUnreachableInExit, llvm::BasicBlock*, llvm::DebugLoc&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::DebugLoc&&&) const
Line
Count
Source
405
25
                                   Args &&... Arguments) const {
406
25
  if (!Context.Verifying) {
407
25
    RejectLog &Log = Context.Log;
408
25
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
25
410
25
    if (PollyTrackFailures)
411
25
      Log.report(RejectReason);
412
25
413
25
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
25
    LLVM_DEBUG(dbgs() << "\n");
415
25
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
25
419
25
  return false;
420
25
}
bool polly::ScopDetection::invalid<polly::ReportEntry, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&) const
Line
Count
Source
405
84
                                   Args &&... Arguments) const {
406
84
  if (!Context.Verifying) {
407
84
    RejectLog &Log = Context.Log;
408
84
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
84
410
84
    if (PollyTrackFailures)
411
84
      Log.report(RejectReason);
412
84
413
84
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
84
    LLVM_DEBUG(dbgs() << "\n");
415
84
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
84
419
84
  return false;
420
84
}
bool polly::ScopDetection::invalid<polly::ReportIrreducibleRegion, llvm::Region*, llvm::DebugLoc&>(polly::ScopDetection::DetectionContext&, bool, llvm::Region*&&, llvm::DebugLoc&&&) const
Line
Count
Source
405
3
                                   Args &&... Arguments) const {
406
3
  if (!Context.Verifying) {
407
3
    RejectLog &Log = Context.Log;
408
3
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
409
3
410
3
    if (PollyTrackFailures)
411
3
      Log.report(RejectReason);
412
3
413
3
    LLVM_DEBUG(dbgs() << RejectReason->getMessage());
414
3
    LLVM_DEBUG(dbgs() << "\n");
415
3
  } else {
416
0
    assert(!Assert && "Verification of detected scop failed");
417
0
  }
418
3
419
3
  return false;
420
3
}
421
422
4.25k
bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
423
4.25k
  if (!ValidRegions.count(&R))
424
3.06k
    return false;
425
1.19k
426
1.19k
  if (Verify) {
427
1.19k
    DetectionContextMap.erase(getBBPairForRegion(&R));
428
1.19k
    const auto &It = DetectionContextMap.insert(std::make_pair(
429
1.19k
        getBBPairForRegion(&R),
430
1.19k
        DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
431
1.19k
    DetectionContext &Context = It.first->second;
432
1.19k
    return isValidRegion(Context);
433
1.19k
  }
434
0
435
0
  return true;
436
0
}
437
438
4
std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
439
4
  // Get the first error we found. Even in keep-going mode, this is the first
440
4
  // reason that caused the candidate to be rejected.
441
4
  auto *Log = lookupRejectionLog(R);
442
4
443
4
  // This can happen when we marked a region invalid, but didn't track
444
4
  // an error for it.
445
4
  if (!Log || 
!Log->hasErrors()3
)
446
4
    return "";
447
0
448
0
  RejectReasonPtr RR = *Log->begin();
449
0
  return RR->getMessage();
450
0
}
451
452
bool ScopDetection::addOverApproximatedRegion(Region *AR,
453
691
                                              DetectionContext &Context) const {
454
691
  // If we already know about Ar we can exit.
455
691
  if (!Context.NonAffineSubRegionSet.insert(AR))
456
63
    return true;
457
628
458
628
  // All loops in the region have to be overapproximated too if there
459
628
  // are accesses that depend on the iteration count.
460
628
461
1.55k
  
for (BasicBlock *BB : AR->blocks())628
{
462
1.55k
    Loop *L = LI.getLoopFor(BB);
463
1.55k
    if (AR->contains(L))
464
224
      Context.BoxedLoopsSet.insert(L);
465
1.55k
  }
466
628
467
628
  return (AllowNonAffineSubLoops || 
Context.BoxedLoopsSet.empty()539
);
468
628
}
469
470
bool ScopDetection::onlyValidRequiredInvariantLoads(
471
41.1k
    InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
472
41.1k
  Region &CurRegion = Context.CurRegion;
473
41.1k
  const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
474
41.1k
475
41.1k
  if (!PollyInvariantLoadHoisting && 
!RequiredILS.empty()33.3k
)
476
365
    return false;
477
40.8k
478
40.8k
  for (LoadInst *Load : RequiredILS) {
479
1.62k
    // If we already know a load has been accepted as required invariant, we
480
1.62k
    // already run the validation below once and consequently don't need to
481
1.62k
    // run it again. Hence, we return early. For certain test cases (e.g.,
482
1.62k
    // COSMO this avoids us spending 50% of scop-detection time in this
483
1.62k
    // very function (and its children).
484
1.62k
    if (Context.RequiredILS.count(Load))
485
843
      continue;
486
786
    if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
487
137
      return false;
488
649
489
649
    for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
490
320
      if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
491
320
                                      Load->getAlignment(), DL))
492
6
        continue;
493
314
494
314
      if (NonAffineRegion->contains(Load) &&
495
314
          
Load->getParent() != NonAffineRegion->getEntry()14
)
496
14
        return false;
497
314
    }
498
649
  }
499
40.8k
500
40.8k
  Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
501
40.6k
502
40.6k
  return true;
503
40.8k
}
504
505
bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
506
13.5k
                                         Loop *Scope) const {
507
13.5k
  SetVector<Value *> Values;
508
13.5k
  findValues(S0, SE, Values);
509
13.5k
  if (S1)
510
5.07k
    findValues(S1, SE, Values);
511
13.5k
512
13.5k
  SmallPtrSet<Value *, 8> PtrVals;
513
13.5k
  for (auto *V : Values) {
514
5.91k
    if (auto *P2I = dyn_cast<PtrToIntInst>(V))
515
2
      V = P2I->getOperand(0);
516
5.91k
517
5.91k
    if (!V->getType()->isPointerTy())
518
5.84k
      continue;
519
70
520
70
    auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
521
70
    if (isa<SCEVConstant>(PtrSCEV))
522
2
      continue;
523
68
524
68
    auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
525
68
    if (!BasePtr)
526
0
      return true;
527
68
528
68
    auto *BasePtrVal = BasePtr->getValue();
529
68
    if (PtrVals.insert(BasePtrVal).second) {
530
68
      for (auto *PtrVal : PtrVals)
531
68
        if (PtrVal != BasePtrVal && 
!AA.isNoAlias(PtrVal, BasePtrVal)0
)
532
0
          return true;
533
68
    }
534
68
  }
535
13.5k
536
13.5k
  return false;
537
13.5k
}
538
539
bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
540
42.0k
                             DetectionContext &Context) const {
541
42.0k
  InvariantLoadsSetTy AccessILS;
542
42.0k
  if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
543
877
    return false;
544
41.1k
545
41.1k
  if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
546
516
    return false;
547
40.6k
548
40.6k
  return true;
549
40.6k
}
550
551
bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
552
                                  Value *Condition, bool IsLoopBranch,
553
39
                                  DetectionContext &Context) const {
554
39
  Loop *L = LI.getLoopFor(&BB);
555
39
  const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
556
39
557
39
  if (IsLoopBranch && 
L->isLoopLatch(&BB)1
)
558
1
    return false;
559
38
560
38
  // Check for invalid usage of different pointers in one expression.
561
38
  if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
562
0
    return false;
563
38
564
38
  if (isAffine(ConditionSCEV, L, Context))
565
36
    return true;
566
2
567
2
  if (AllowNonAffineSubRegions &&
568
2
      addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
569
2
    return true;
570
0
571
0
  return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
572
0
                                     ConditionSCEV, ConditionSCEV, SI);
573
0
}
574
575
bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
576
                                  Value *Condition, bool IsLoopBranch,
577
29.2k
                                  DetectionContext &Context) const {
578
29.2k
  // Constant integer conditions are always affine.
579
29.2k
  if (isa<ConstantInt>(Condition))
580
15.5k
    return true;
581
13.7k
582
13.7k
  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
583
110
    auto Opcode = BinOp->getOpcode();
584
110
    if (Opcode == Instruction::And || 
Opcode == Instruction::Or95
) {
585
109
      Value *Op0 = BinOp->getOperand(0);
586
109
      Value *Op1 = BinOp->getOperand(1);
587
109
      return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
588
109
             isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
589
109
    }
590
13.6k
  }
591
13.6k
592
13.6k
  if (auto PHI = dyn_cast<PHINode>(Condition)) {
593
10
    auto *Unique = dyn_cast_or_null<ConstantInt>(
594
10
        getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT));
595
10
    if (Unique && 
(2
Unique->isZero()2
||
Unique->isOne()2
))
596
2
      return true;
597
13.6k
  }
598
13.6k
599
13.6k
  if (auto Load = dyn_cast<LoadInst>(Condition))
600
6
    if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
601
3
      Context.RequiredILS.insert(Load);
602
3
      return true;
603
3
    }
604
13.6k
605
13.6k
  // Non constant conditions of branches need to be ICmpInst.
606
13.6k
  if (!isa<ICmpInst>(Condition)) {
607
136
    if (!IsLoopBranch && AllowNonAffineSubRegions &&
608
136
        addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
609
135
      return true;
610
1
    return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
611
1
  }
612
13.4k
613
13.4k
  ICmpInst *ICmp = cast<ICmpInst>(Condition);
614
13.4k
615
13.4k
  // Are both operands of the ICmp affine?
616
13.4k
  if (isa<UndefValue>(ICmp->getOperand(0)) ||
617
13.4k
      isa<UndefValue>(ICmp->getOperand(1)))
618
5
    return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
619
13.4k
620
13.4k
  Loop *L = LI.getLoopFor(&BB);
621
13.4k
  const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
622
13.4k
  const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
623
13.4k
624
13.4k
  LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT);
625
13.4k
  RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT);
626
13.4k
627
13.4k
  // If unsigned operations are not allowed try to approximate the region.
628
13.4k
  if (ICmp->isUnsigned() && 
!PollyAllowUnsignedOperations167
)
629
0
    return !IsLoopBranch && AllowNonAffineSubRegions &&
630
0
           addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
631
13.4k
632
13.4k
  // Check for invalid usage of different pointers in one expression.
633
13.4k
  if (ICmp->isEquality() && 
involvesMultiplePtrs(LHS, nullptr, L)8.42k
&&
634
13.4k
      
involvesMultiplePtrs(RHS, nullptr, L)0
)
635
0
    return false;
636
13.4k
637
13.4k
  // Check for invalid usage of different pointers in a relational comparison.
638
13.4k
  if (ICmp->isRelational() && 
involvesMultiplePtrs(LHS, RHS, L)5.07k
)
639
0
    return false;
640
13.4k
641
13.4k
  if (isAffine(LHS, L, Context) && 
isAffine(RHS, L, Context)13.1k
)
642
12.9k
    return true;
643
590
644
590
  if (!IsLoopBranch && 
AllowNonAffineSubRegions489
&&
645
590
      
addOverApproximatedRegion(RI.getRegionFor(&BB), Context)487
)
646
484
    return true;
647
106
648
106
  if (IsLoopBranch)
649
101
    return false;
650
5
651
5
  return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
652
5
                                     ICmp);
653
5
}
654
655
bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
656
                               bool AllowUnreachable,
657
29.2k
                               DetectionContext &Context) const {
658
29.2k
  Region &CurRegion = Context.CurRegion;
659
29.2k
660
29.2k
  Instruction *TI = BB.getTerminator();
661
29.2k
662
29.2k
  if (AllowUnreachable && 
isa<UnreachableInst>(TI)138
)
663
0
    return true;
664
29.2k
665
29.2k
  // Return instructions are only valid if the region is the top level region.
666
29.2k
  if (isa<ReturnInst>(TI) && 
CurRegion.isTopLevelRegion()10
)
667
10
    return true;
668
29.2k
669
29.2k
  Value *Condition = getConditionFromTerminator(TI);
670
29.2k
671
29.2k
  if (!Condition)
672
0
    return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
673
29.2k
674
29.2k
  // UndefValue is not allowed as condition.
675
29.2k
  if (isa<UndefValue>(Condition))
676
154
    return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
677
29.0k
678
29.0k
  if (BranchInst *BI = dyn_cast<BranchInst>(TI))
679
29.0k
    return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
680
39
681
39
  SwitchInst *SI = dyn_cast<SwitchInst>(TI);
682
39
  assert(SI && "Terminator was neither branch nor switch");
683
39
684
39
  return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
685
39
}
686
687
bool ScopDetection::isValidCallInst(CallInst &CI,
688
239
                                    DetectionContext &Context) const {
689
239
  if (CI.doesNotReturn())
690
0
    return false;
691
239
692
239
  if (CI.doesNotAccessMemory())
693
112
    return true;
694
127
695
127
  if (auto *II = dyn_cast<IntrinsicInst>(&CI))
696
86
    if (isValidIntrinsicInst(*II, Context))
697
74
      return true;
698
53
699
53
  Function *CalledFunction = CI.getCalledFunction();
700
53
701
53
  // Indirect calls are not supported.
702
53
  if (CalledFunction == nullptr)
703
0
    return false;
704
53
705
53
  if (isDebugCall(&CI)) {
706
3
    LLVM_DEBUG(dbgs() << "Allow call to debug function: "
707
3
                      << CalledFunction->getName() << '\n');
708
3
    return true;
709
3
  }
710
50
711
50
  if (AllowModrefCall) {
712
39
    switch (AA.getModRefBehavior(CalledFunction)) {
713
39
    case FMRB_UnknownModRefBehavior:
714
0
      return false;
715
39
    case FMRB_DoesNotAccessMemory:
716
21
    case FMRB_OnlyReadsMemory:
717
21
      // Implicitly disable delinearization since we have an unknown
718
21
      // accesses with an unknown access function.
719
21
      Context.HasUnknownAccess = true;
720
21
      // Explicitly use addUnknown so we don't put a loop-variant
721
21
      // pointer into the alias set.
722
21
      Context.AST.addUnknown(&CI);
723
21
      return true;
724
21
    case FMRB_OnlyReadsArgumentPointees:
725
18
    case FMRB_OnlyAccessesArgumentPointees:
726
52
      for (const auto &Arg : CI.arg_operands()) {
727
52
        if (!Arg->getType()->isPointerTy())
728
24
          continue;
729
28
730
28
        // Bail if a pointer argument has a base address not known to
731
28
        // ScalarEvolution. Note that a zero pointer is acceptable.
732
28
        auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
733
28
        if (ArgSCEV->isZero())
734
14
          continue;
735
14
736
14
        auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
737
14
        if (!BP)
738
0
          return false;
739
14
740
14
        // Implicitly disable delinearization since we have an unknown
741
14
        // accesses with an unknown access function.
742
14
        Context.HasUnknownAccess = true;
743
14
      }
744
18
745
18
      // Explicitly use addUnknown so we don't put a loop-variant
746
18
      // pointer into the alias set.
747
18
      Context.AST.addUnknown(&CI);
748
18
      return true;
749
18
    case FMRB_DoesNotReadMemory:
750
0
    case FMRB_OnlyAccessesInaccessibleMem:
751
0
    case FMRB_OnlyAccessesInaccessibleOrArgMem:
752
0
      return false;
753
11
    }
754
11
  }
755
11
756
11
  return false;
757
11
}
758
759
bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
760
86
                                         DetectionContext &Context) const {
761
86
  if (isIgnoredIntrinsic(&II))
762
29
    return true;
763
57
764
57
  // The closest loop surrounding the call instruction.
765
57
  Loop *L = LI.getLoopFor(II.getParent());
766
57
767
57
  // The access function and base pointer for memory intrinsics.
768
57
  const SCEV *AF;
769
57
  const SCEVUnknown *BP;
770
57
771
57
  switch (II.getIntrinsicID()) {
772
57
  // Memory intrinsics that can be represented are supported.
773
57
  case Intrinsic::memmove:
774
19
  case Intrinsic::memcpy:
775
19
    AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
776
19
    if (!AF->isZero()) {
777
19
      BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
778
19
      // Bail if the source pointer is not valid.
779
19
      if (!isValidAccess(&II, AF, BP, Context))
780
0
        return false;
781
19
    }
782
19
  // Fall through
783
70
  case Intrinsic::memset:
784
70
    AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
785
70
    if (
!AF->isZero()51
) {
786
47
      BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
787
47
      // Bail if the destination pointer is not valid.
788
47
      if (!isValidAccess(&II, AF, BP, Context))
789
0
        return false;
790
51
    }
791
51
792
51
    // Bail if the length is not affine.
793
51
    if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
794
51
                  Context))
795
6
      return false;
796
45
797
45
    return true;
798
45
  default:
799
6
    break;
800
6
  }
801
6
802
6
  return false;
803
6
}
804
805
bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
806
12.4k
                                DetectionContext &Ctx) const {
807
12.4k
  // A reference to function argument or constant value is invariant.
808
12.4k
  if (isa<Argument>(Val) || 
isa<Constant>(Val)3.27k
)
809
9.95k
    return true;
810
2.53k
811
2.53k
  Instruction *I = dyn_cast<Instruction>(&Val);
812
2.53k
  if (!I)
813
0
    return false;
814
2.53k
815
2.53k
  if (!Reg.contains(I))
816
2.03k
    return true;
817
499
818
499
  // Loads within the SCoP may read arbitrary values, need to hoist them. If it
819
499
  // is not hoistable, it will be rejected later, but here we assume it is and
820
499
  // that makes the value invariant.
821
499
  if (auto LI = dyn_cast<LoadInst>(I)) {
822
489
    Ctx.RequiredILS.insert(LI);
823
489
    return true;
824
489
  }
825
10
826
10
  return false;
827
10
}
828
829
namespace {
830
831
/// Remove smax of smax(0, size) expressions from a SCEV expression and
832
/// register the '...' components.
833
///
834
/// Array access expressions as they are generated by GFortran contain smax(0,
835
/// size) expressions that confuse the 'normal' delinearization algorithm.
836
/// However, if we extract such expressions before the normal delinearization
837
/// takes place they can actually help to identify array size expressions in
838
/// Fortran accesses. For the subsequently following delinearization the smax(0,
839
/// size) component can be replaced by just 'size'. This is correct as we will
840
/// always add and verify the assumption that for all subscript expressions
841
/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
842
/// that 0 <= size, which means smax(0, size) == size.
843
class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
844
public:
845
  SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
846
1.43k
      : SCEVRewriteVisitor(SE), Terms(Terms) {}
847
848
  static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
849
1.43k
                             std::vector<const SCEV *> *Terms = nullptr) {
850
1.43k
    SCEVRemoveMax Rewriter(SE, Terms);
851
1.43k
    return Rewriter.visit(Scev);
852
1.43k
  }
853
854
68
  const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
855
68
    if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
856
68
      auto Res = visit(Expr->getOperand(1));
857
68
      if (Terms)
858
34
        (*Terms).push_back(Res);
859
68
      return Res;
860
68
    }
861
0
862
0
    return Expr;
863
0
  }
864
865
private:
866
  std::vector<const SCEV *> *Terms;
867
};
868
} // namespace
869
870
SmallVector<const SCEV *, 4>
871
ScopDetection::getDelinearizationTerms(DetectionContext &Context,
872
443
                                       const SCEVUnknown *BasePointer) const {
873
443
  SmallVector<const SCEV *, 4> Terms;
874
725
  for (const auto &Pair : Context.Accesses[BasePointer]) {
875
725
    std::vector<const SCEV *> MaxTerms;
876
725
    SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
877
725
    if (!MaxTerms.empty()) {
878
22
      Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
879
22
      continue;
880
22
    }
881
703
    // In case the outermost expression is a plain add, we check if any of its
882
703
    // terms has the form 4 * %inst * %param * %param ..., aka a term that
883
703
    // contains a product between a parameter and an instruction that is
884
703
    // inside the scop. Such instructions, if allowed at all, are instructions
885
703
    // SCEV can not represent, but Polly is still looking through. As a
886
703
    // result, these instructions can depend on induction variables and are
887
703
    // most likely no array sizes. However, terms that are multiplied with
888
703
    // them are likely candidates for array sizes.
889
703
    if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
890
17
      for (auto Op : AF->operands()) {
891
17
        if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
892
4
          SE.collectParametricTerms(AF2, Terms);
893
17
        if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
894
8
          SmallVector<const SCEV *, 0> Operands;
895
8
896
24
          for (auto *MulOp : AF2->operands()) {
897
24
            if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
898
6
              Operands.push_back(Const);
899
24
            if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
900
16
              if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
901
4
                if (!Context.CurRegion.contains(Inst))
902
0
                  Operands.push_back(MulOp);
903
4
904
12
              } else {
905
12
                Operands.push_back(MulOp);
906
12
              }
907
16
            }
908
24
          }
909
8
          if (Operands.size())
910
7
            Terms.push_back(SE.getMulExpr(Operands));
911
8
        }
912
17
      }
913
8
    }
914
703
    if (Terms.empty())
915
489
      SE.collectParametricTerms(Pair.second, Terms);
916
703
  }
917
443
  return Terms;
918
443
}
919
920
bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
921
                                       SmallVectorImpl<const SCEV *> &Sizes,
922
                                       const SCEVUnknown *BasePointer,
923
443
                                       Loop *Scope) const {
924
443
  // If no sizes were found, all sizes are trivially valid. We allow this case
925
443
  // to make it possible to pass known-affine accesses to the delinearization to
926
443
  // try to recover some interesting multi-dimensional accesses, but to still
927
443
  // allow the already known to be affine access in case the delinearization
928
443
  // fails. In such situations, the delinearization will just return a Sizes
929
443
  // array of size zero.
930
443
  if (Sizes.size() == 0)
931
65
    return true;
932
378
933
378
  Value *BaseValue = BasePointer->getValue();
934
378
  Region &CurRegion = Context.CurRegion;
935
1.05k
  for (const SCEV *DelinearizedSize : Sizes) {
936
1.05k
    if (!isAffine(DelinearizedSize, Scope, Context)) {
937
10
      Sizes.clear();
938
10
      break;
939
10
    }
940
1.04k
    if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
941
625
      auto *V = dyn_cast<Value>(Unknown->getValue());
942
625
      if (auto *Load = dyn_cast<LoadInst>(V)) {
943
178
        if (Context.CurRegion.contains(Load) &&
944
178
            
isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS)26
)
945
26
          Context.RequiredILS.insert(Load);
946
178
        continue;
947
178
      }
948
865
    }
949
865
    if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
950
865
                                  Context.RequiredILS))
951
0
      return invalid<ReportNonAffineAccess>(
952
0
          Context, /*Assert=*/true, DelinearizedSize,
953
0
          Context.Accesses[BasePointer].front().first, BaseValue);
954
865
  }
955
378
956
378
  // No array shape derived.
957
378
  if (Sizes.empty()) {
958
10
    if (AllowNonAffine)
959
0
      return true;
960
10
961
11
    
for (const auto &Pair : Context.Accesses[BasePointer])10
{
962
11
      const Instruction *Insn = Pair.first;
963
11
      const SCEV *AF = Pair.second;
964
11
965
11
      if (!isAffine(AF, Scope, Context)) {
966
10
        invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
967
10
                                       BaseValue);
968
10
        if (!KeepGoing)
969
10
          return false;
970
10
      }
971
11
    }
972
10
    
return false0
;
973
368
  }
974
368
  return true;
975
368
}
976
977
// We first store the resulting memory accesses in TempMemoryAccesses. Only
978
// if the access functions for all memory accesses have been successfully
979
// delinearized we continue. Otherwise, we either report a failure or, if
980
// non-affine accesses are allowed, we drop the information. In case the
981
// information is dropped the memory accesses need to be overapproximated
982
// when translated to a polyhedral representation.
983
bool ScopDetection::computeAccessFunctions(
984
    DetectionContext &Context, const SCEVUnknown *BasePointer,
985
433
    std::shared_ptr<ArrayShape> Shape) const {
986
433
  Value *BaseValue = BasePointer->getValue();
987
433
  bool BasePtrHasNonAffine = false;
988
433
  MapInsnToMemAcc TempMemoryAccesses;
989
705
  for (const auto &Pair : Context.Accesses[BasePointer]) {
990
705
    const Instruction *Insn = Pair.first;
991
705
    auto *AF = Pair.second;
992
705
    AF = SCEVRemoveMax::rewrite(AF, SE);
993
705
    bool IsNonAffine = false;
994
705
    TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
995
705
    MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
996
705
    auto *Scope = LI.getLoopFor(Insn->getParent());
997
705
998
705
    if (!AF) {
999
0
      if (isAffine(Pair.second, Scope, Context))
1000
0
        Acc->DelinearizedSubscripts.push_back(Pair.second);
1001
0
      else
1002
0
        IsNonAffine = true;
1003
705
    } else {
1004
705
      if (Shape->DelinearizedSizes.size() == 0) {
1005
109
        Acc->DelinearizedSubscripts.push_back(AF);
1006
596
      } else {
1007
596
        SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
1008
596
                                  Shape->DelinearizedSizes);
1009
596
        if (Acc->DelinearizedSubscripts.size() == 0)
1010
6
          IsNonAffine = true;
1011
596
      }
1012
705
      for (const SCEV *S : Acc->DelinearizedSubscripts)
1013
1.80k
        if (!isAffine(S, Scope, Context))
1014
92
          IsNonAffine = true;
1015
705
    }
1016
705
1017
705
    // (Possibly) report non affine access
1018
705
    if (IsNonAffine) {
1019
98
      BasePtrHasNonAffine = true;
1020
98
      if (!AllowNonAffine)
1021
23
        invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1022
23
                                       Insn, BaseValue);
1023
98
      if (!KeepGoing && 
!AllowNonAffine87
)
1024
16
        return false;
1025
98
    }
1026
705
  }
1027
433
1028
433
  
if (417
!BasePtrHasNonAffine417
)
1029
361
    Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1030
361
                                TempMemoryAccesses.end());
1031
417
1032
417
  return true;
1033
433
}
1034
1035
bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1036
                                          const SCEVUnknown *BasePointer,
1037
443
                                          Loop *Scope) const {
1038
443
  auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1039
443
1040
443
  auto Terms = getDelinearizationTerms(Context, BasePointer);
1041
443
1042
443
  SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1043
443
                         Context.ElementSize[BasePointer]);
1044
443
1045
443
  if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1046
443
                          Scope))
1047
10
    return false;
1048
433
1049
433
  return computeAccessFunctions(Context, BasePointer, Shape);
1050
433
}
1051
1052
3.32k
bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
1053
3.32k
  // TODO: If we have an unknown access and other non-affine accesses we do
1054
3.32k
  //       not try to delinearize them for now.
1055
3.32k
  if (Context.HasUnknownAccess && 
!Context.NonAffineAccesses.empty()35
)
1056
12
    return AllowNonAffine;
1057
3.31k
1058
3.31k
  for (auto &Pair : Context.NonAffineAccesses) {
1059
443
    auto *BasePointer = Pair.first;
1060
443
    auto *Scope = Pair.second;
1061
443
    if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
1062
26
      if (KeepGoing)
1063
0
        continue;
1064
26
      else
1065
26
        return false;
1066
26
    }
1067
443
  }
1068
3.31k
  
return true3.29k
;
1069
3.31k
}
1070
1071
bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1072
                                  const SCEVUnknown *BP,
1073
12.4k
                                  DetectionContext &Context) const {
1074
12.4k
1075
12.4k
  if (!BP)
1076
0
    return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
1077
12.4k
1078
12.4k
  auto *BV = BP->getValue();
1079
12.4k
  if (isa<UndefValue>(BV))
1080
6
    return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
1081
12.4k
1082
12.4k
  // FIXME: Think about allowing IntToPtrInst
1083
12.4k
  if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1084
1
    return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1085
12.4k
1086
12.4k
  // Check that the base address of the access is invariant in the current
1087
12.4k
  // region.
1088
12.4k
  if (!isInvariant(*BV, Context.CurRegion, Context))
1089
10
    return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
1090
12.4k
1091
12.4k
  AF = SE.getMinusSCEV(AF, BP);
1092
12.4k
1093
12.4k
  const SCEV *Size;
1094
12.4k
  if (!isa<MemIntrinsic>(Inst)) {
1095
12.4k
    Size = SE.getElementSize(Inst);
1096
12.4k
  } else {
1097
66
    auto *SizeTy =
1098
66
        SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1099
66
    Size = SE.getConstant(SizeTy, 8);
1100
66
  }
1101
12.4k
1102
12.4k
  if (Context.ElementSize[BP]) {
1103
6.97k
    if (!AllowDifferentTypes && 
Context.ElementSize[BP] != Size0
)
1104
0
      return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1105
0
                                                      Inst, BV);
1106
6.97k
1107
6.97k
    Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
1108
6.97k
  } else {
1109
5.50k
    Context.ElementSize[BP] = Size;
1110
5.50k
  }
1111
12.4k
1112
12.4k
  bool IsVariantInNonAffineLoop = false;
1113
12.4k
  SetVector<const Loop *> Loops;
1114
12.4k
  findLoops(AF, Loops);
1115
12.4k
  for (const Loop *L : Loops)
1116
7.31k
    if (Context.BoxedLoopsSet.count(L))
1117
39
      IsVariantInNonAffineLoop = true;
1118
12.4k
1119
12.4k
  auto *Scope = LI.getLoopFor(Inst->getParent());
1120
12.4k
  bool IsAffine = !IsVariantInNonAffineLoop && 
isAffine(AF, Scope, Context)12.4k
;
1121
12.4k
  // Do not try to delinearize memory intrinsics and force them to be affine.
1122
12.4k
  if (isa<MemIntrinsic>(Inst) && 
!IsAffine66
) {
1123
0
    return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1124
0
                                          BV);
1125
12.4k
  } else if (PollyDelinearize && 
!IsVariantInNonAffineLoop12.4k
) {
1126
12.4k
    Context.Accesses[BP].push_back({Inst, AF});
1127
12.4k
1128
12.4k
    if (!IsAffine || 
hasIVParams(AF)11.7k
)
1129
672
      Context.NonAffineAccesses.insert(
1130
672
          std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
1131
12.4k
  } else 
if (68
!AllowNonAffine68
&&
!IsAffine28
) {
1132
22
    return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1133
22
                                          BV);
1134
22
  }
1135
12.4k
1136
12.4k
  if (IgnoreAliasing)
1137
440
    return true;
1138
12.0k
1139
12.0k
  // Check if the base pointer of the memory access does alias with
1140
12.0k
  // any other pointer. This cannot be handled at the moment.
1141
12.0k
  AAMDNodes AATags;
1142
12.0k
  Inst->getAAMetadata(AATags);
1143
12.0k
  AliasSet &AS = Context.AST.getAliasSetFor(
1144
12.0k
      MemoryLocation(BP->getValue(), MemoryLocation::UnknownSize, AATags));
1145
12.0k
1146
12.0k
  if (!AS.isMustAlias()) {
1147
3.32k
    if (PollyUseRuntimeAliasChecks) {
1148
3.32k
      bool CanBuildRunTimeCheck = true;
1149
3.32k
      // The run-time alias check places code that involves the base pointer at
1150
3.32k
      // the beginning of the SCoP. This breaks if the base pointer is defined
1151
3.32k
      // inside the scop. Hence, we can only create a run-time check if we are
1152
3.32k
      // sure the base pointer is not an instruction defined inside the scop.
1153
3.32k
      // However, we can ignore loads that will be hoisted.
1154
3.32k
1155
3.32k
      InvariantLoadsSetTy VariantLS, InvariantLS;
1156
3.32k
      // In order to detect loads which are dependent on other invariant loads
1157
3.32k
      // as invariant, we use fixed-point iteration method here i.e we iterate
1158
3.32k
      // over the alias set for arbitrary number of times until it is safe to
1159
3.32k
      // assume that all the invariant loads have been detected
1160
3.90k
      while (1) {
1161
3.90k
        const unsigned int VariantSize = VariantLS.size(),
1162
3.90k
                           InvariantSize = InvariantLS.size();
1163
3.90k
1164
14.4k
        for (const auto &Ptr : AS) {
1165
14.4k
          Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1166
14.4k
          if (Inst && 
Context.CurRegion.contains(Inst)4.69k
) {
1167
4.41k
            auto *Load = dyn_cast<LoadInst>(Inst);
1168
4.41k
            if (Load && InvariantLS.count(Load))
1169
2.20k
              continue;
1170
2.21k
            if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT,
1171
2.21k
                                        InvariantLS)) {
1172
2.20k
              if (VariantLS.count(Load))
1173
0
                VariantLS.remove(Load);
1174
2.20k
              Context.RequiredILS.insert(Load);
1175
2.20k
              InvariantLS.insert(Load);
1176
2.20k
            } else {
1177
4
              CanBuildRunTimeCheck = false;
1178
4
              VariantLS.insert(Load);
1179
4
            }
1180
2.21k
          }
1181
14.4k
        }
1182
3.90k
1183
3.90k
        if (InvariantSize == InvariantLS.size() &&
1184
3.90k
            
VariantSize == VariantLS.size()3.32k
)
1185
3.32k
          break;
1186
3.90k
      }
1187
3.32k
1188
3.32k
      if (CanBuildRunTimeCheck)
1189
3.32k
        return true;
1190
3
    }
1191
3
    return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
1192
3
  }
1193
8.68k
1194
8.68k
  return true;
1195
8.68k
}
1196
1197
bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1198
12.4k
                                        DetectionContext &Context) const {
1199
12.4k
  Value *Ptr = Inst.getPointerOperand();
1200
12.4k
  Loop *L = LI.getLoopFor(Inst->getParent());
1201
12.4k
  const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
1202
12.4k
  const SCEVUnknown *BasePointer;
1203
12.4k
1204
12.4k
  BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1205
12.4k
1206
12.4k
  return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1207
12.4k
}
1208
1209
bool ScopDetection::isValidInstruction(Instruction &Inst,
1210
53.4k
                                       DetectionContext &Context) const {
1211
100k
  for (auto &Op : Inst.operands()) {
1212
100k
    auto *OpInst = dyn_cast<Instruction>(&Op);
1213
100k
1214
100k
    if (!OpInst)
1215
41.2k
      continue;
1216
58.8k
1217
58.8k
    if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) {
1218
2
      auto *PHI = dyn_cast<PHINode>(OpInst);
1219
2
      if (PHI) {
1220
0
        for (User *U : PHI->users()) {
1221
0
          auto *UI = dyn_cast<Instruction>(U);
1222
0
          if (!UI || !UI->isTerminator())
1223
0
            return false;
1224
0
        }
1225
2
      } else {
1226
2
        return false;
1227
2
      }
1228
2
    }
1229
58.8k
  }
1230
53.4k
1231
53.4k
  
if (53.4k
isa<LandingPadInst>(&Inst)53.4k
||
isa<ResumeInst>(&Inst)53.4k
)
1232
0
    return false;
1233
53.4k
1234
53.4k
  // We only check the call instruction but not invoke instruction.
1235
53.4k
  if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1236
239
    if (isValidCallInst(*CI, Context))
1237
228
      return true;
1238
11
1239
11
    return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
1240
11
  }
1241
53.2k
1242
53.2k
  if (!Inst.mayReadOrWriteMemory()) {
1243
40.7k
    if (!isa<AllocaInst>(Inst))
1244
40.7k
      return true;
1245
0
1246
0
    return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
1247
0
  }
1248
12.4k
1249
12.4k
  // Check the access function.
1250
12.4k
  if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
1251
12.4k
    Context.hasStores |= isa<StoreInst>(MemInst);
1252
12.4k
    Context.hasLoads |= isa<LoadInst>(MemInst);
1253
12.4k
    if (!MemInst.isSimple())
1254
0
      return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1255
0
                                                  &Inst);
1256
12.4k
1257
12.4k
    return isValidMemoryAccess(MemInst, Context);
1258
12.4k
  }
1259
49
1260
49
  // We do not know this instruction, therefore we assume it is invalid.
1261
49
  return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
1262
49
}
1263
1264
/// Check whether @p L has exiting blocks.
1265
///
1266
/// @param L The loop of interest
1267
///
1268
/// @return True if the loop has exiting blocks, false otherwise.
1269
5.37k
static bool hasExitingBlocks(Loop *L) {
1270
5.37k
  SmallVector<BasicBlock *, 4> ExitingBlocks;
1271
5.37k
  L->getExitingBlocks(ExitingBlocks);
1272
5.37k
  return !ExitingBlocks.empty();
1273
5.37k
}
1274
1275
bool ScopDetection::canUseISLTripCount(Loop *L,
1276
5.34k
                                       DetectionContext &Context) const {
1277
5.34k
  // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1278
5.34k
  // need to overapproximate it as a boxed loop.
1279
5.34k
  SmallVector<BasicBlock *, 4> LoopControlBlocks;
1280
5.34k
  L->getExitingBlocks(LoopControlBlocks);
1281
5.34k
  L->getLoopLatches(LoopControlBlocks);
1282
10.5k
  for (BasicBlock *ControlBB : LoopControlBlocks) {
1283
10.5k
    if (!isValidCFG(*ControlBB, true, false, Context))
1284
200
      return false;
1285
10.5k
  }
1286
5.34k
1287
5.34k
  // We can use ISL to compute the trip count of L.
1288
5.34k
  
return true5.14k
;
1289
5.34k
}
1290
1291
5.37k
bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
1292
5.37k
  // Loops that contain part but not all of the blocks of a region cannot be
1293
5.37k
  // handled by the schedule generation. Such loop constructs can happen
1294
5.37k
  // because a region can contain BBs that have no path to the exit block
1295
5.37k
  // (Infinite loops, UnreachableInst), but such blocks are never part of a
1296
5.37k
  // loop.
1297
5.37k
  //
1298
5.37k
  // _______________
1299
5.37k
  // | Loop Header | <-----------.
1300
5.37k
  // ---------------             |
1301
5.37k
  //        |                    |
1302
5.37k
  // _______________       ______________
1303
5.37k
  // | RegionEntry |-----> | RegionExit |----->
1304
5.37k
  // ---------------       --------------
1305
5.37k
  //        |
1306
5.37k
  // _______________
1307
5.37k
  // | EndlessLoop | <--.
1308
5.37k
  // ---------------    |
1309
5.37k
  //       |            |
1310
5.37k
  //       \------------/
1311
5.37k
  //
1312
5.37k
  // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1313
5.37k
  // neither entirely contained in the region RegionEntry->RegionExit
1314
5.37k
  // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1315
5.37k
  // in the loop.
1316
5.37k
  // The block EndlessLoop is contained in the region because Region::contains
1317
5.37k
  // tests whether it is not dominated by RegionExit. This is probably to not
1318
5.37k
  // having to query the PostdominatorTree. Instead of an endless loop, a dead
1319
5.37k
  // end can also be formed by an UnreachableInst. This case is already caught
1320
5.37k
  // by isErrorBlock(). We hence only have to reject endless loops here.
1321
5.37k
  if (!hasExitingBlocks(L))
1322
0
    return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1323
5.37k
1324
5.37k
  // The algorithm for domain construction assumes that loops has only a single
1325
5.37k
  // exit block (and hence corresponds to a subregion). Note that we cannot use
1326
5.37k
  // L->getExitBlock() because it does not check whether all exiting edges point
1327
5.37k
  // to the same BB.
1328
5.37k
  SmallVector<BasicBlock *, 4> ExitBlocks;
1329
5.37k
  L->getExitBlocks(ExitBlocks);
1330
5.37k
  BasicBlock *TheExitBlock = ExitBlocks[0];
1331
5.42k
  for (BasicBlock *ExitBB : ExitBlocks) {
1332
5.42k
    if (TheExitBlock != ExitBB)
1333
35
      return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L);
1334
5.42k
  }
1335
5.37k
1336
5.37k
  
if (5.34k
canUseISLTripCount(L, Context)5.34k
)
1337
5.14k
    return true;
1338
200
1339
200
  if (AllowNonAffineSubLoops && 
AllowNonAffineSubRegions66
) {
1340
66
    Region *R = RI.getRegionFor(L->getHeader());
1341
77
    while (R != &Context.CurRegion && 
!R->contains(L)62
)
1342
11
      R = R->getParent();
1343
66
1344
66
    if (addOverApproximatedRegion(R, Context))
1345
66
      return true;
1346
134
  }
1347
134
1348
134
  const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
1349
134
  return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
1350
134
}
1351
1352
/// Return the number of loops in @p L (incl. @p L) that have a trip
1353
///        count that is not known to be less than @MinProfitableTrips.
1354
ScopDetection::LoopStats
1355
ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1356
3.92k
                                       unsigned MinProfitableTrips) {
1357
3.92k
  auto *TripCount = SE.getBackedgeTakenCount(L);
1358
3.92k
1359
3.92k
  int NumLoops = 1;
1360
3.92k
  int MaxLoopDepth = 1;
1361
3.92k
  if (MinProfitableTrips > 0)
1362
38
    if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1363
17
      if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1364
17
        if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1365
4
          NumLoops -= 1;
1366
3.92k
1367
3.92k
  for (auto &SubLoop : *L) {
1368
1.09k
    LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1369
1.09k
    NumLoops += Stats.NumLoops;
1370
1.09k
    MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1371
1.09k
  }
1372
3.92k
1373
3.92k
  return {NumLoops, MaxLoopDepth};
1374
3.92k
}
1375
1376
ScopDetection::LoopStats
1377
ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1378
2.69k
                                    LoopInfo &LI, unsigned MinProfitableTrips) {
1379
2.69k
  int LoopNum = 0;
1380
2.69k
  int MaxLoopDepth = 0;
1381
2.69k
1382
2.69k
  auto L = LI.getLoopFor(R->getEntry());
1383
2.69k
1384
2.69k
  // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1385
2.69k
  // L is either nullptr or already surrounding R.
1386
2.69k
  if (L && 
R->contains(L)1.13k
) {
1387
1.09k
    L = R->outermostLoopInRegion(L);
1388
1.09k
    L = L->getParentLoop();
1389
1.09k
  }
1390
2.69k
1391
2.69k
  auto SubLoops =
1392
2.69k
      L ? 
L->getSubLoopsVector()82
:
std::vector<Loop *>(LI.begin(), LI.end())2.61k
;
1393
2.69k
1394
2.69k
  for (auto &SubLoop : SubLoops)
1395
2.90k
    if (R->contains(SubLoop)) {
1396
2.83k
      LoopStats Stats =
1397
2.83k
          countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1398
2.83k
      LoopNum += Stats.NumLoops;
1399
2.83k
      MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1400
2.83k
    }
1401
2.69k
1402
2.69k
  return {LoopNum, MaxLoopDepth};
1403
2.69k
}
1404
1405
1.28k
Region *ScopDetection::expandRegion(Region &R) {
1406
1.28k
  // Initial no valid region was found (greater than R)
1407
1.28k
  std::unique_ptr<Region> LastValidRegion;
1408
1.28k
  auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
1409
1.28k
1410
1.28k
  LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1411
1.28k
1412
1.88k
  while (ExpandedRegion) {
1413
653
    const auto &It = DetectionContextMap.insert(std::make_pair(
1414
653
        getBBPairForRegion(ExpandedRegion.get()),
1415
653
        DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
1416
653
    DetectionContext &Context = It.first->second;
1417
653
    LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
1418
653
    // Only expand when we did not collect errors.
1419
653
1420
653
    if (!Context.Log.hasErrors()) {
1421
653
      // If the exit is valid check all blocks
1422
653
      //  - if true, a valid region was found => store it + keep expanding
1423
653
      //  - if false, .tbd. => stop  (should this really end the loop?)
1424
653
      if (!allBlocksValid(Context) || 
Context.Log.hasErrors()607
) {
1425
47
        removeCachedResults(*ExpandedRegion);
1426
47
        DetectionContextMap.erase(It.first);
1427
47
        break;
1428
47
      }
1429
606
1430
606
      // Store this region, because it is the greatest valid (encountered so
1431
606
      // far).
1432
606
      if (LastValidRegion) {
1433
256
        removeCachedResults(*LastValidRegion);
1434
256
        DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1435
256
      }
1436
606
      LastValidRegion = std::move(ExpandedRegion);
1437
606
1438
606
      // Create and test the next greater region (if any)
1439
606
      ExpandedRegion =
1440
606
          std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
1441
606
1442
606
    } else {
1443
0
      // Create and test the next greater region (if any)
1444
0
      removeCachedResults(*ExpandedRegion);
1445
0
      DetectionContextMap.erase(It.first);
1446
0
      ExpandedRegion =
1447
0
          std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
1448
0
    }
1449
653
  }
1450
1.28k
1451
1.28k
  LLVM_DEBUG({
1452
1.28k
    if (LastValidRegion)
1453
1.28k
      dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1454
1.28k
    else
1455
1.28k
      dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1456
1.28k
  });
1457
1.28k
1458
1.28k
  return LastValidRegion.release();
1459
1.28k
}
1460
1461
47
static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
1462
47
  for (const BasicBlock *BB : R.blocks())
1463
53
    if (R.contains(LI.getLoopFor(BB)))
1464
46
      return false;
1465
47
1466
47
  
return true1
;
1467
47
}
1468
1469
865
void ScopDetection::removeCachedResultsRecursively(const Region &R) {
1470
865
  for (auto &SubRegion : R) {
1471
723
    if (ValidRegions.count(SubRegion.get())) {
1472
208
      removeCachedResults(*SubRegion.get());
1473
208
    } else
1474
515
      removeCachedResultsRecursively(*SubRegion);
1475
723
  }
1476
865
}
1477
1478
2.67k
void ScopDetection::removeCachedResults(const Region &R) {
1479
2.67k
  ValidRegions.remove(&R);
1480
2.67k
}
1481
1482
3.31k
void ScopDetection::findScops(Region &R) {
1483
3.31k
  const auto &It = DetectionContextMap.insert(std::make_pair(
1484
3.31k
      getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
1485
3.31k
  DetectionContext &Context = It.first->second;
1486
3.31k
1487
3.31k
  bool RegionIsValid = false;
1488
3.31k
  if (!PollyProcessUnprofitable && 
regionWithoutLoops(R, LI)47
)
1489
1
    invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
1490
3.31k
  else
1491
3.31k
    RegionIsValid = isValidRegion(Context);
1492
3.31k
1493
3.31k
  bool HasErrors = !RegionIsValid || 
Context.Log.size() > 01.49k
;
1494
3.31k
1495
3.31k
  if (HasErrors) {
1496
1.81k
    removeCachedResults(R);
1497
1.81k
  } else {
1498
1.49k
    ValidRegions.insert(&R);
1499
1.49k
    return;
1500
1.49k
  }
1501
1.81k
1502
1.81k
  for (auto &SubRegion : R)
1503
1.92k
    findScops(*SubRegion);
1504
1.81k
1505
1.81k
  // Try to expand regions.
1506
1.81k
  //
1507
1.81k
  // As the region tree normally only contains canonical regions, non canonical
1508
1.81k
  // regions that form a Scop are not found. Therefore, those non canonical
1509
1.81k
  // regions are checked by expanding the canonical ones.
1510
1.81k
1511
1.81k
  std::vector<Region *> ToExpand;
1512
1.81k
1513
1.81k
  for (auto &SubRegion : R)
1514
1.92k
    ToExpand.push_back(SubRegion.get());
1515
1.81k
1516
1.92k
  for (Region *CurrentRegion : ToExpand) {
1517
1.92k
    // Skip invalid regions. Regions may become invalid, if they are element of
1518
1.92k
    // an already expanded region.
1519
1.92k
    if (!ValidRegions.count(CurrentRegion))
1520
642
      continue;
1521
1.28k
1522
1.28k
    // Skip regions that had errors.
1523
1.28k
    bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1524
1.28k
    if (HadErrors)
1525
0
      continue;
1526
1.28k
1527
1.28k
    Region *ExpandedR = expandRegion(*CurrentRegion);
1528
1.28k
1529
1.28k
    if (!ExpandedR)
1530
930
      continue;
1531
350
1532
350
    R.addSubRegion(ExpandedR, true);
1533
350
    ValidRegions.insert(ExpandedR);
1534
350
    removeCachedResults(*CurrentRegion);
1535
350
    removeCachedResultsRecursively(*ExpandedR);
1536
350
  }
1537
1.81k
}
1538
1539
3.66k
bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
1540
3.66k
  Region &CurRegion = Context.CurRegion;
1541
3.66k
1542
19.4k
  for (const BasicBlock *BB : CurRegion.blocks()) {
1543
19.4k
    Loop *L = LI.getLoopFor(BB);
1544
19.4k
    if (L && 
L->getHeader() == BB15.7k
) {
1545
5.43k
      if (CurRegion.contains(L)) {
1546
5.37k
        if (!isValidLoop(L, Context) && 
!KeepGoing169
)
1547
169
          return false;
1548
52
      } else {
1549
52
        SmallVector<BasicBlock *, 1> Latches;
1550
52
        L->getLoopLatches(Latches);
1551
52
        for (BasicBlock *Latch : Latches)
1552
60
          if (CurRegion.contains(Latch))
1553
5
            return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1554
5
                                                      L);
1555
52
      }
1556
5.43k
    }
1557
19.4k
  }
1558
3.66k
1559
18.7k
  
for (BasicBlock *BB : CurRegion.blocks())3.49k
{
1560
18.7k
    bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
1561
18.7k
1562
18.7k
    // Also check exception blocks (and possibly register them as non-affine
1563
18.7k
    // regions). Even though exception blocks are not modeled, we use them
1564
18.7k
    // to forward-propagate domain constraints during ScopInfo construction.
1565
18.7k
    if (!isValidCFG(*BB, false, IsErrorBlock, Context) && 
!KeepGoing67
)
1566
67
      return false;
1567
18.6k
1568
18.6k
    if (IsErrorBlock)
1569
137
      continue;
1570
18.5k
1571
71.9k
    
for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); 18.5k
I != E;
++I53.3k
)
1572
53.4k
      if (!isValidInstruction(*I, Context) && 
!KeepGoing104
)
1573
95
        return false;
1574
18.5k
  }
1575
3.49k
1576
3.49k
  
if (3.32k
!hasAffineMemoryAccesses(Context)3.32k
)
1577
32
    return false;
1578
3.29k
1579
3.29k
  return true;
1580
3.29k
}
1581
1582
bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1583
8
                                         int NumLoops) const {
1584
8
  int InstCount = 0;
1585
8
1586
8
  if (NumLoops == 0)
1587
0
    return false;
1588
8
1589
8
  for (auto *BB : Context.CurRegion.blocks())
1590
36
    if (Context.CurRegion.contains(LI.getLoopFor(BB)))
1591
36
      InstCount += BB->size();
1592
8
1593
8
  InstCount = InstCount / NumLoops;
1594
8
1595
8
  return InstCount >= ProfitabilityMinPerLoopInstructions;
1596
8
}
1597
1598
bool ScopDetection::hasPossiblyDistributableLoop(
1599
10
    DetectionContext &Context) const {
1600
10
  for (auto *BB : Context.CurRegion.blocks()) {
1601
10
    auto *L = LI.getLoopFor(BB);
1602
10
    if (!Context.CurRegion.contains(L))
1603
0
      continue;
1604
10
    if (Context.BoxedLoopsSet.count(L))
1605
0
      continue;
1606
10
    unsigned StmtsWithStoresInLoops = 0;
1607
74
    for (auto *LBB : L->blocks()) {
1608
74
      bool MemStore = false;
1609
74
      for (auto &I : *LBB)
1610
303
        MemStore |= isa<StoreInst>(&I);
1611
74
      StmtsWithStoresInLoops += MemStore;
1612
74
    }
1613
10
    return (StmtsWithStoresInLoops > 1);
1614
10
  }
1615
10
  
return false0
;
1616
10
}
1617
1618
1.28k
bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1619
1.28k
  Region &CurRegion = Context.CurRegion;
1620
1.28k
1621
1.28k
  if (PollyProcessUnprofitable)
1622
1.26k
    return true;
1623
22
1624
22
  // We can probably not do a lot on scops that only write or only read
1625
22
  // data.
1626
22
  if (!Context.hasStores || 
!Context.hasLoads20
)
1627
4
    return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1628
18
1629
18
  int NumLoops =
1630
18
      countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
1631
18
  int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
1632
18
1633
18
  // Scops with at least two loops may allow either loop fusion or tiling and
1634
18
  // are consequently interesting to look at.
1635
18
  if (NumAffineLoops >= 2)
1636
4
    return true;
1637
14
1638
14
  // A loop with multiple non-trivial blocks might be amendable to distribution.
1639
14
  if (NumAffineLoops == 1 && 
hasPossiblyDistributableLoop(Context)10
)
1640
2
    return true;
1641
12
1642
12
  // Scops that contain a loop with a non-trivial amount of computation per
1643
12
  // loop-iteration are interesting as we may be able to parallelize such
1644
12
  // loops. Individual loops that have only a small amount of computation
1645
12
  // per-iteration are performance-wise very fragile as any change to the
1646
12
  // loop induction variables may affect performance. To not cause spurious
1647
12
  // performance regressions, we do not consider such loops.
1648
12
  if (NumAffineLoops == 1 && 
hasSufficientCompute(Context, NumLoops)8
)
1649
1
    return true;
1650
11
1651
11
  return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1652
11
}
1653
1654
4.50k
bool ScopDetection::isValidRegion(DetectionContext &Context) const {
1655
4.50k
  Region &CurRegion = Context.CurRegion;
1656
4.50k
1657
4.50k
  LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
1658
4.50k
1659
4.50k
  if (!PollyAllowFullFunction && 
CurRegion.isTopLevelRegion()4.49k
) {
1660
1.38k
    LLVM_DEBUG(dbgs() << "Top level region is invalid\n");
1661
1.38k
    return false;
1662
1.38k
  }
1663
3.12k
1664
3.12k
  DebugLoc DbgLoc;
1665
3.12k
  if (CurRegion.getExit() &&
1666
3.12k
      
isa<UnreachableInst>(CurRegion.getExit()->getTerminator())3.11k
) {
1667
25
    LLVM_DEBUG(dbgs() << "Unreachable in exit\n");
1668
25
    return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1669
25
                                            CurRegion.getExit(), DbgLoc);
1670
25
  }
1671
3.09k
1672
3.09k
  if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
1673
0
    LLVM_DEBUG({
1674
0
      dbgs() << "Region entry does not match -polly-region-only";
1675
0
      dbgs() << "\n";
1676
0
    });
1677
0
    return false;
1678
0
  }
1679
3.09k
1680
3.09k
  // SCoP cannot contain the entry block of the function, because we need
1681
3.09k
  // to insert alloca instruction there when translate scalar to array.
1682
3.09k
  if (!PollyAllowFullFunction &&
1683
3.09k
      CurRegion.getEntry() ==
1684
3.08k
          &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1685
84
    return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
1686
3.01k
1687
3.01k
  if (!allBlocksValid(Context))
1688
322
    return false;
1689
2.69k
1690
2.69k
  if (!isReducibleRegion(CurRegion, DbgLoc))
1691
3
    return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1692
3
                                            &CurRegion, DbgLoc);
1693
2.68k
1694
2.68k
  LLVM_DEBUG(dbgs() << "OK\n");
1695
2.68k
  return true;
1696
2.68k
}
1697
1698
0
void ScopDetection::markFunctionAsInvalid(Function *F) {
1699
0
  F->addFnAttr(PollySkipFnAttr);
1700
0
}
1701
1702
1.42k
bool ScopDetection::isValidFunction(Function &F) {
1703
1.42k
  return !F.hasFnAttribute(PollySkipFnAttr);
1704
1.42k
}
1705
1706
2
void ScopDetection::printLocations(Function &F) {
1707
2
  for (const Region *R : *this) {
1708
2
    unsigned LineEntry, LineExit;
1709
2
    std::string FileName;
1710
2
1711
2
    getDebugLocation(R, LineEntry, LineExit, FileName);
1712
2
    DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1713
2
    F.getContext().diagnose(Diagnostic);
1714
2
  }
1715
2
}
1716
1717
1.38k
void ScopDetection::emitMissedRemarks(const Function &F) {
1718
3.66k
  for (auto &DIt : DetectionContextMap) {
1719
3.66k
    auto &DC = DIt.getSecond();
1720
3.66k
    if (DC.Log.hasErrors())
1721
445
      emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
1722
3.66k
  }
1723
1.38k
}
1724
1725
2.69k
bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1726
2.69k
  /// Enum for coloring BBs in Region.
1727
2.69k
  ///
1728
2.69k
  /// WHITE - Unvisited BB in DFS walk.
1729
2.69k
  /// GREY - BBs which are currently on the DFS stack for processing.
1730
2.69k
  /// BLACK - Visited and completely processed BB.
1731
2.69k
  enum Color { WHITE, GREY, BLACK };
1732
2.69k
1733
2.69k
  BasicBlock *REntry = R.getEntry();
1734
2.69k
  BasicBlock *RExit = R.getExit();
1735
2.69k
  // Map to match the color of a BasicBlock during the DFS walk.
1736
2.69k
  DenseMap<const BasicBlock *, Color> BBColorMap;
1737
2.69k
  // Stack keeping track of current BB and index of next child to be processed.
1738
2.69k
  std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1739
2.69k
1740
2.69k
  unsigned AdjacentBlockIndex = 0;
1741
2.69k
  BasicBlock *CurrBB, *SuccBB;
1742
2.69k
  CurrBB = REntry;
1743
2.69k
1744
2.69k
  // Initialize the map for all BB with WHITE color.
1745
2.69k
  for (auto *BB : R.blocks())
1746
11.8k
    BBColorMap[BB] = WHITE;
1747
2.69k
1748
2.69k
  // Process the entry block of the Region.
1749
2.69k
  BBColorMap[CurrBB] = GREY;
1750
2.69k
  DFSStack.push(std::make_pair(CurrBB, 0));
1751
2.69k
1752
23.6k
  while (!DFSStack.empty()) {
1753
20.9k
    // Get next BB on stack to be processed.
1754
20.9k
    CurrBB = DFSStack.top().first;
1755
20.9k
    AdjacentBlockIndex = DFSStack.top().second;
1756
20.9k
    DFSStack.pop();
1757
20.9k
1758
20.9k
    // Loop to iterate over the successors of current BB.
1759
20.9k
    const Instruction *TInst = CurrBB->getTerminator();
1760
20.9k
    unsigned NSucc = TInst->getNumSuccessors();
1761
28.4k
    for (unsigned I = AdjacentBlockIndex; I < NSucc;
1762
20.9k
         
++I, ++AdjacentBlockIndex7.50k
) {
1763
16.6k
      SuccBB = TInst->getSuccessor(I);
1764
16.6k
1765
16.6k
      // Checks for region exit block and self-loops in BB.
1766
16.6k
      if (SuccBB == RExit || 
SuccBB == CurrBB13.4k
)
1767
4.16k
        continue;
1768
12.4k
1769
12.4k
      // WHITE indicates an unvisited BB in DFS walk.
1770
12.4k
      if (BBColorMap[SuccBB] == WHITE) {
1771
9.12k
        // Push the current BB and the index of the next child to be visited.
1772
9.12k
        DFSStack.push(std::make_pair(CurrBB, I + 1));
1773
9.12k
        // Push the next BB to be processed.
1774
9.12k
        DFSStack.push(std::make_pair(SuccBB, 0));
1775
9.12k
        // First time the BB is being processed.
1776
9.12k
        BBColorMap[SuccBB] = GREY;
1777
9.12k
        break;
1778
9.12k
      } else 
if (3.34k
BBColorMap[SuccBB] == GREY3.34k
) {
1779
2.59k
        // GREY indicates a loop in the control flow.
1780
2.59k
        // If the destination dominates the source, it is a natural loop
1781
2.59k
        // else, an irreducible control flow in the region is detected.
1782
2.59k
        if (!DT.dominates(SuccBB, CurrBB)) {
1783
3
          // Get debug info of instruction which causes irregular control flow.
1784
3
          DbgLoc = TInst->getDebugLoc();
1785
3
          return false;
1786
3
        }
1787
2.59k
      }
1788
12.4k
    }
1789
20.9k
1790
20.9k
    // If all children of current BB have been processed,
1791
20.9k
    // then mark that BB as fully processed.
1792
20.9k
    
if (20.9k
AdjacentBlockIndex == NSucc20.9k
)
1793
11.8k
      BBColorMap[CurrBB] = BLACK;
1794
20.9k
  }
1795
2.69k
1796
2.69k
  
return true2.68k
;
1797
2.69k
}
1798
1799
static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1800
2.55k
                                     bool OnlyProfitable) {
1801
2.55k
  if (!OnlyProfitable) {
1802
1.28k
    NumLoopsInScop += Stats.NumLoops;
1803
1.28k
    MaxNumLoopsInScop =
1804
1.28k
        std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
1805
1.28k
    if (Stats.MaxDepth == 0)
1806
104
      NumScopsDepthZero++;
1807
1.18k
    else if (Stats.MaxDepth == 1)
1808
836
      NumScopsDepthOne++;
1809
345
    else if (Stats.MaxDepth == 2)
1810
260
      NumScopsDepthTwo++;
1811
85
    else if (Stats.MaxDepth == 3)
1812
81
      NumScopsDepthThree++;
1813
4
    else if (Stats.MaxDepth == 4)
1814
4
      NumScopsDepthFour++;
1815
0
    else if (Stats.MaxDepth == 5)
1816
0
      NumScopsDepthFive++;
1817
0
    else
1818
0
      NumScopsDepthLarger++;
1819
1.28k
  } else {
1820
1.27k
    NumLoopsInProfScop += Stats.NumLoops;
1821
1.27k
    MaxNumLoopsInProfScop =
1822
1.27k
        std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
1823
1.27k
    if (Stats.MaxDepth == 0)
1824
104
      NumProfScopsDepthZero++;
1825
1.16k
    else if (Stats.MaxDepth == 1)
1826
828
      NumProfScopsDepthOne++;
1827
338
    else if (Stats.MaxDepth == 2)
1828
254
      NumProfScopsDepthTwo++;
1829
84
    else if (Stats.MaxDepth == 3)
1830
81
      NumProfScopsDepthThree++;
1831
3
    else if (Stats.MaxDepth == 4)
1832
3
      NumProfScopsDepthFour++;
1833
0
    else if (Stats.MaxDepth == 5)
1834
0
      NumProfScopsDepthFive++;
1835
0
    else
1836
0
      NumProfScopsDepthLarger++;
1837
1.27k
  }
1838
2.55k
}
1839
1840
ScopDetection::DetectionContext *
1841
2.47k
ScopDetection::getDetectionContext(const Region *R) const {
1842
2.47k
  auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
1843
2.47k
  if (DCMIt == DetectionContextMap.end())
1844
1
    return nullptr;
1845
2.47k
  return &DCMIt->second;
1846
2.47k
}
1847
1848
1.28k
const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1849
1.28k
  const DetectionContext *DC = getDetectionContext(R);
1850
1.28k
  return DC ? 
&DC->Log1.28k
:
nullptr1
;
1851
1.28k
}
1852
1853
0
void ScopDetection::verifyRegion(const Region &R) const {
1854
0
  assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1855
0
1856
0
  DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
1857
0
  isValidRegion(Context);
1858
0
}
1859
1860
0
void ScopDetection::verifyAnalysis() const {
1861
0
  if (!VerifyScops)
1862
0
    return;
1863
0
1864
0
  for (const Region *R : ValidRegions)
1865
0
    verifyRegion(*R);
1866
0
}
1867
1868
1.42k
bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
1869
1.42k
  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1870
1.42k
  auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1871
1.42k
  auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1872
1.42k
  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1873
1.42k
  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1874
1.42k
  auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1875
1.42k
  Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
1876
1.42k
  return false;
1877
1.42k
}
1878
1879
1.28k
void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1880
1.28k
  AU.addRequired<LoopInfoWrapperPass>();
1881
1.28k
  AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1882
1.28k
  AU.addRequired<DominatorTreeWrapperPass>();
1883
1.28k
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1884
1.28k
  // We also need AA and RegionInfo when we are verifying analysis.
1885
1.28k
  AU.addRequiredTransitive<AAResultsWrapperPass>();
1886
1.28k
  AU.addRequiredTransitive<RegionInfoPass>();
1887
1.28k
  AU.setPreservesAll();
1888
1.28k
}
1889
1890
128
void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1891
128
  for (const Region *R : Result->ValidRegions)
1892
76
    OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1893
128
1894
128
  OS << "\n";
1895
128
}
1896
1897
1.28k
ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1898
1.28k
  // Disable runtime alias checks if we ignore aliasing all together.
1899
1.28k
  if (IgnoreAliasing)
1900
20
    PollyUseRuntimeAliasChecks = false;
1901
1.28k
}
1902
1903
939
ScopAnalysis::ScopAnalysis() {
1904
939
  // Disable runtime alias checks if we ignore aliasing all together.
1905
939
  if (IgnoreAliasing)
1906
0
    PollyUseRuntimeAliasChecks = false;
1907
939
}
1908
1909
1.40k
void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
1910
1911
char ScopDetectionWrapperPass::ID;
1912
1913
AnalysisKey ScopAnalysis::Key;
1914
1915
3
ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1916
3
  auto &LI = FAM.getResult<LoopAnalysis>(F);
1917
3
  auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1918
3
  auto &AA = FAM.getResult<AAManager>(F);
1919
3
  auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1920
3
  auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1921
3
  auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1922
3
  return {F, DT, SE, LI, RI, AA, ORE};
1923
3
}
1924
1925
PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1926
0
                                               FunctionAnalysisManager &FAM) {
1927
0
  OS << "Detected Scops in Function " << F.getName() << "\n";
1928
0
  auto &SD = FAM.getResult<ScopAnalysis>(F);
1929
0
  for (const Region *R : SD.ValidRegions)
1930
0
    OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1931
0
1932
0
  OS << "\n";
1933
0
  return PreservedAnalyses::all();
1934
0
}
1935
1936
0
Pass *polly::createScopDetectionWrapperPassPass() {
1937
0
  return new ScopDetectionWrapperPass();
1938
0
}
1939
1940
45.1k
INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
1941
45.1k
                      "Polly - Detect static control parts (SCoPs)", false,
1942
45.1k
                      false);
1943
45.1k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
1944
45.1k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1945
45.1k
INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1946
45.1k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1947
45.1k
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1948
45.1k
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
1949
45.1k
INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
1950
                    "Polly - Detect static control parts (SCoPs)", false, false)