Coverage Report

Created: 2018-02-20 23:11

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