Coverage Report

Created: 2018-08-20 19:24

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