Coverage Report

Created: 2018-02-20 12:54

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Analysis/ScopInfo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ScopInfo.cpp -------------------------------------------------------===//
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
// Create a polyhedral description for a static control flow region.
11
//
12
// The pass creates a polyhedral description of the Scops detected by the Scop
13
// detection derived from their LLVM-IR code.
14
//
15
// This representation is shared among several tools in the polyhedral
16
// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17
//
18
//===----------------------------------------------------------------------===//
19
20
#include "polly/ScopInfo.h"
21
#include "polly/LinkAllPasses.h"
22
#include "polly/Options.h"
23
#include "polly/ScopBuilder.h"
24
#include "polly/ScopDetection.h"
25
#include "polly/Support/GICHelper.h"
26
#include "polly/Support/ISLOStream.h"
27
#include "polly/Support/SCEVAffinator.h"
28
#include "polly/Support/SCEVValidator.h"
29
#include "polly/Support/ScopHelper.h"
30
#include "llvm/ADT/APInt.h"
31
#include "llvm/ADT/ArrayRef.h"
32
#include "llvm/ADT/DenseMap.h"
33
#include "llvm/ADT/DenseSet.h"
34
#include "llvm/ADT/PostOrderIterator.h"
35
#include "llvm/ADT/STLExtras.h"
36
#include "llvm/ADT/SetVector.h"
37
#include "llvm/ADT/SmallPtrSet.h"
38
#include "llvm/ADT/SmallSet.h"
39
#include "llvm/ADT/SmallVector.h"
40
#include "llvm/ADT/Statistic.h"
41
#include "llvm/ADT/StringExtras.h"
42
#include "llvm/ADT/StringMap.h"
43
#include "llvm/Analysis/AliasAnalysis.h"
44
#include "llvm/Analysis/AliasSetTracker.h"
45
#include "llvm/Analysis/AssumptionCache.h"
46
#include "llvm/Analysis/Loads.h"
47
#include "llvm/Analysis/LoopInfo.h"
48
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
49
#include "llvm/Analysis/RegionInfo.h"
50
#include "llvm/Analysis/RegionIterator.h"
51
#include "llvm/Analysis/ScalarEvolution.h"
52
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
53
#include "llvm/IR/Argument.h"
54
#include "llvm/IR/BasicBlock.h"
55
#include "llvm/IR/CFG.h"
56
#include "llvm/IR/ConstantRange.h"
57
#include "llvm/IR/Constants.h"
58
#include "llvm/IR/DataLayout.h"
59
#include "llvm/IR/DebugLoc.h"
60
#include "llvm/IR/DerivedTypes.h"
61
#include "llvm/IR/DiagnosticInfo.h"
62
#include "llvm/IR/Dominators.h"
63
#include "llvm/IR/Function.h"
64
#include "llvm/IR/InstrTypes.h"
65
#include "llvm/IR/Instruction.h"
66
#include "llvm/IR/Instructions.h"
67
#include "llvm/IR/IntrinsicInst.h"
68
#include "llvm/IR/Module.h"
69
#include "llvm/IR/PassManager.h"
70
#include "llvm/IR/Type.h"
71
#include "llvm/IR/Use.h"
72
#include "llvm/IR/User.h"
73
#include "llvm/IR/Value.h"
74
#include "llvm/Pass.h"
75
#include "llvm/Support/Casting.h"
76
#include "llvm/Support/CommandLine.h"
77
#include "llvm/Support/Compiler.h"
78
#include "llvm/Support/Debug.h"
79
#include "llvm/Support/ErrorHandling.h"
80
#include "llvm/Support/MathExtras.h"
81
#include "llvm/Support/raw_ostream.h"
82
#include "isl/aff.h"
83
#include "isl/constraint.h"
84
#include "isl/local_space.h"
85
#include "isl/map.h"
86
#include "isl/options.h"
87
#include "isl/printer.h"
88
#include "isl/schedule.h"
89
#include "isl/schedule_node.h"
90
#include "isl/set.h"
91
#include "isl/union_map.h"
92
#include "isl/union_set.h"
93
#include "isl/val.h"
94
#include <algorithm>
95
#include <cassert>
96
#include <cstdlib>
97
#include <cstring>
98
#include <deque>
99
#include <iterator>
100
#include <memory>
101
#include <string>
102
#include <tuple>
103
#include <utility>
104
#include <vector>
105
106
using namespace llvm;
107
using namespace polly;
108
109
2.01k
#define DEBUG_TYPE "polly-scops"
110
111
STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
112
STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
113
STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
114
STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
115
STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
116
STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
117
STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
118
STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
119
STATISTIC(AssumptionsInvariantLoad,
120
          "Number of invariant loads assumptions taken.");
121
STATISTIC(AssumptionsDelinearization,
122
          "Number of delinearization assumptions taken.");
123
124
STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
125
STATISTIC(NumLoopsInScop, "Number of loops in scops");
126
STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
127
STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
128
129
STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
130
STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
131
STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
132
STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
133
STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
134
STATISTIC(NumScopsDepthLarger,
135
          "Number of scops with maximal loop depth 6 and larger");
136
STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
137
138
STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
139
STATISTIC(
140
    NumValueWritesInLoops,
141
    "Number of scalar value writes nested in affine loops after ScopInfo");
142
STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
143
STATISTIC(NumPHIWritesInLoops,
144
          "Number of scalar phi writes nested in affine loops after ScopInfo");
145
STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
146
STATISTIC(NumSingletonWritesInLoops,
147
          "Number of singleton writes nested in affine loops after ScopInfo");
148
149
// The maximal number of basic sets we allow during domain construction to
150
// be created. More complex scops will result in very high compile time and
151
// are also unlikely to result in good code
152
static int const MaxDisjunctsInDomain = 20;
153
154
// The number of disjunct in the context after which we stop to add more
155
// disjuncts. This parameter is there to avoid exponential growth in the
156
// number of disjunct when adding non-convex sets to the context.
157
static int const MaxDisjunctsInContext = 4;
158
159
// The maximal number of dimensions we allow during invariant load construction.
160
// More complex access ranges will result in very high compile time and are also
161
// unlikely to result in good code. This value is very high and should only
162
// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
163
static int const MaxDimensionsInAccessRange = 9;
164
165
static cl::opt<int>
166
    OptComputeOut("polly-analysis-computeout",
167
                  cl::desc("Bound the scop analysis by a maximal amount of "
168
                           "computational steps (0 means no bound)"),
169
                  cl::Hidden, cl::init(800000), cl::ZeroOrMore,
170
                  cl::cat(PollyCategory));
171
172
static cl::opt<bool> PollyRemarksMinimal(
173
    "polly-remarks-minimal",
174
    cl::desc("Do not emit remarks about assumptions that are known"),
175
    cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
176
177
static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
178
    "polly-rtc-max-array-disjuncts",
179
    cl::desc("The maximal number of disjunts allowed in memory accesses to "
180
             "to build RTCs."),
181
    cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
182
183
static cl::opt<unsigned> RunTimeChecksMaxParameters(
184
    "polly-rtc-max-parameters",
185
    cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
186
    cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
187
188
static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
189
    "polly-rtc-max-arrays-per-group",
190
    cl::desc("The maximal number of arrays to compare in each alias group."),
191
    cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
192
193
static cl::opt<std::string> UserContextStr(
194
    "polly-context", cl::value_desc("isl parameter set"),
195
    cl::desc("Provide additional constraints on the context parameters"),
196
    cl::init(""), cl::cat(PollyCategory));
197
198
static cl::opt<bool>
199
    IslOnErrorAbort("polly-on-isl-error-abort",
200
                    cl::desc("Abort if an isl error is encountered"),
201
                    cl::init(true), cl::cat(PollyCategory));
202
203
static cl::opt<bool> PollyPreciseInbounds(
204
    "polly-precise-inbounds",
205
    cl::desc("Take more precise inbounds assumptions (do not scale well)"),
206
    cl::Hidden, cl::init(false), cl::cat(PollyCategory));
207
208
static cl::opt<bool>
209
    PollyIgnoreInbounds("polly-ignore-inbounds",
210
                        cl::desc("Do not take inbounds assumptions at all"),
211
                        cl::Hidden, cl::init(false), cl::cat(PollyCategory));
212
213
static cl::opt<bool> PollyIgnoreParamBounds(
214
    "polly-ignore-parameter-bounds",
215
    cl::desc(
216
        "Do not add parameter bounds and do no gist simplify sets accordingly"),
217
    cl::Hidden, cl::init(false), cl::cat(PollyCategory));
218
219
static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
220
    "polly-allow-dereference-of-all-function-parameters",
221
    cl::desc(
222
        "Treat all parameters to functions that are pointers as dereferencible."
223
        " This is useful for invariant load hoisting, since we can generate"
224
        " less runtime checks. This is only valid if all pointers to functions"
225
        " are always initialized, so that Polly can choose to hoist"
226
        " their loads. "),
227
    cl::Hidden, cl::init(false), cl::cat(PollyCategory));
228
229
static cl::opt<bool> PollyPreciseFoldAccesses(
230
    "polly-precise-fold-accesses",
231
    cl::desc("Fold memory accesses to model more possible delinearizations "
232
             "(does not scale well)"),
233
    cl::Hidden, cl::init(false), cl::cat(PollyCategory));
234
235
bool polly::UseInstructionNames;
236
237
static cl::opt<bool, true> XUseInstructionNames(
238
    "polly-use-llvm-names",
239
    cl::desc("Use LLVM-IR names when deriving statement names"),
240
    cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
241
    cl::ZeroOrMore, cl::cat(PollyCategory));
242
243
static cl::opt<bool> PollyPrintInstructions(
244
    "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
245
    cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
246
247
//===----------------------------------------------------------------------===//
248
249
// Create a sequence of two schedules. Either argument may be null and is
250
// interpreted as the empty schedule. Can also return null if both schedules are
251
// empty.
252
3.87k
static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
253
3.87k
  if (!Prev)
254
2.75k
    return Succ;
255
1.12k
  if (!Succ)
256
0
    return Prev;
257
1.12k
258
1.12k
  return Prev.sequence(Succ);
259
1.12k
}
260
261
static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
262
1.21k
                                    int dim, isl::dim type) {
263
1.21k
  isl::val V;
264
1.21k
  isl::ctx Ctx = S.get_ctx();
265
1.21k
266
1.21k
  // The upper and lower bound for a parameter value is derived either from
267
1.21k
  // the data type of the parameter or from the - possibly more restrictive -
268
1.21k
  // range metadata.
269
1.21k
  V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
270
1.21k
  S = S.lower_bound_val(type, dim, V);
271
1.21k
  V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
272
1.21k
  S = S.upper_bound_val(type, dim, V);
273
1.21k
274
1.21k
  if (Range.isFullSet())
275
1.15k
    return S;
276
69
277
69
  if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
278
13
    return S;
279
56
280
56
  // In case of signed wrapping, we can refine the set of valid values by
281
56
  // excluding the part not covered by the wrapping range.
282
56
  if (Range.isSignWrappedSet()) {
283
7
    V = valFromAPInt(Ctx.get(), Range.getLower(), true);
284
7
    isl::set SLB = S.lower_bound_val(type, dim, V);
285
7
286
7
    V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
287
7
    V = V.sub_ui(1);
288
7
    isl::set SUB = S.upper_bound_val(type, dim, V);
289
7
    S = SLB.unite(SUB);
290
7
  }
291
56
292
56
  return S;
293
56
}
294
295
1.81k
static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
296
1.81k
  LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
297
1.81k
  if (!BasePtrLI)
298
1.65k
    return nullptr;
299
151
300
151
  if (!S->contains(BasePtrLI))
301
62
    return nullptr;
302
89
303
89
  ScalarEvolution &SE = *S->getSE();
304
89
305
89
  auto *OriginBaseSCEV =
306
89
      SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
307
89
  if (!OriginBaseSCEV)
308
0
    return nullptr;
309
89
310
89
  auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
311
89
  if (!OriginBaseSCEVUnknown)
312
0
    return nullptr;
313
89
314
89
  return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
315
89
                             MemoryKind::Array);
316
89
}
317
318
ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
319
                             ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
320
                             const DataLayout &DL, Scop *S,
321
                             const char *BaseName)
322
2.52k
    : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
323
2.52k
  std::string BasePtrName =
324
2.52k
      BaseName ? 
BaseName85
325
2.52k
               : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
326
2.44k
                                      Kind == MemoryKind::PHI ? 
"__phi"221
:
""2.22k
,
327
2.44k
                                      UseInstructionNames);
328
2.52k
  Id = isl::id::alloc(Ctx, BasePtrName, this);
329
2.52k
330
2.52k
  updateSizes(Sizes);
331
2.52k
332
2.52k
  if (!BasePtr || 
Kind != MemoryKind::Array2.44k
) {
333
719
    BasePtrOriginSAI = nullptr;
334
719
    return;
335
719
  }
336
1.81k
337
1.81k
  BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
338
1.81k
  if (BasePtrOriginSAI)
339
89
    const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
340
1.81k
}
341
342
2.49k
ScopArrayInfo::~ScopArrayInfo() = default;
343
344
5.20k
isl::space ScopArrayInfo::getSpace() const {
345
5.20k
  auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
346
5.20k
  Space = Space.set_tuple_id(isl::dim::set, Id);
347
5.20k
  return Space;
348
5.20k
}
349
350
0
bool ScopArrayInfo::isReadOnly() {
351
0
  isl::union_set WriteSet = S.getWrites().range();
352
0
  isl::space Space = getSpace();
353
0
  WriteSet = WriteSet.extract_set(Space);
354
0
355
0
  return bool(WriteSet.is_empty());
356
0
}
357
358
14
bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
359
14
  if (Array->getElementType() != getElementType())
360
1
    return false;
361
13
362
13
  if (Array->getNumberOfDimensions() != getNumberOfDimensions())
363
1
    return false;
364
12
365
24
  
for (unsigned i = 0; 12
i < getNumberOfDimensions();
i++12
)
366
13
    if (Array->getDimensionSize(i) != getDimensionSize(i))
367
1
      return false;
368
12
369
12
  
return true11
;
370
12
}
371
372
5.33k
void ScopArrayInfo::updateElementType(Type *NewElementType) {
373
5.33k
  if (NewElementType == ElementType)
374
4.17k
    return;
375
1.15k
376
1.15k
  auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
377
1.15k
  auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
378
1.15k
379
1.15k
  if (NewElementSize == OldElementSize || 
NewElementSize == 056
)
380
1.09k
    return;
381
56
382
56
  if (NewElementSize % OldElementSize == 0 && 
NewElementSize < OldElementSize28
) {
383
0
    ElementType = NewElementType;
384
56
  } else {
385
56
    auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
386
56
    ElementType = IntegerType::get(ElementType->getContext(), GCD);
387
56
  }
388
56
}
389
390
/// Make the ScopArrayInfo model a Fortran Array
391
10
void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
392
10
  assert(FAD && "got invalid Fortran array descriptor");
393
10
  if (this->FAD) {
394
3
    assert(this->FAD == FAD &&
395
3
           "receiving different array descriptors for same array");
396
3
    return;
397
3
  }
398
7
399
7
  assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
400
7
  assert(!this->FAD);
401
7
  this->FAD = FAD;
402
7
403
7
  isl::space Space(S.getIslCtx(), 1, 0);
404
7
405
7
  std::string param_name = getName();
406
7
  param_name += "_fortranarr_size";
407
7
  isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
408
7
409
7
  Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
410
7
  isl::pw_aff PwAff =
411
7
      isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
412
7
413
7
  DimensionSizesPw[0] = PwAff;
414
7
}
415
416
bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
417
4.92k
                                bool CheckConsistency) {
418
4.92k
  int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
419
4.92k
  int ExtraDimsNew = NewSizes.size() - SharedDims;
420
4.92k
  int ExtraDimsOld = DimensionSizes.size() - SharedDims;
421
4.92k
422
4.92k
  if (CheckConsistency) {
423
6.67k
    for (int i = 0; i < SharedDims; 
i++1.75k
) {
424
1.75k
      auto *NewSize = NewSizes[i + ExtraDimsNew];
425
1.75k
      auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
426
1.75k
      if (NewSize && 
KnownSize176
&&
NewSize != KnownSize170
)
427
0
        return false;
428
1.75k
    }
429
4.92k
430
4.92k
    if (DimensionSizes.size() >= NewSizes.size())
431
3.02k
      return true;
432
1.90k
  }
433
1.90k
434
1.90k
  DimensionSizes.clear();
435
1.90k
  DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
436
1.90k
                        NewSizes.end());
437
1.90k
  DimensionSizesPw.clear();
438
2.34k
  for (const SCEV *Expr : DimensionSizes) {
439
2.34k
    if (!Expr) {
440
1.81k
      DimensionSizesPw.push_back(nullptr);
441
1.81k
      continue;
442
1.81k
    }
443
530
    isl::pw_aff Size = S.getPwAffOnly(Expr);
444
530
    DimensionSizesPw.push_back(Size);
445
530
  }
446
1.90k
  return true;
447
1.90k
}
448
449
3.38k
std::string ScopArrayInfo::getName() const { return Id.get_name(); }
450
451
9.80k
int ScopArrayInfo::getElemSizeInBytes() const {
452
9.80k
  return DL.getTypeAllocSize(ElementType);
453
9.80k
}
454
455
5.23k
isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
456
457
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
458
LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
459
#endif
460
461
2.17k
void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
462
2.17k
  OS.indent(8) << *getElementType() << " " << getName();
463
2.17k
  unsigned u = 0;
464
2.17k
  // If this is a Fortran array, then we can print the outermost dimension
465
2.17k
  // as a isl_pw_aff even though there is no SCEV information.
466
2.17k
  bool IsOutermostSizeKnown = SizeAsPwAff && 
FAD1.08k
;
467
2.17k
468
2.17k
  if (!IsOutermostSizeKnown && 
getNumberOfDimensions() > 02.16k
&&
469
2.17k
      
!getDimensionSize(0)1.66k
) {
470
1.54k
    OS << "[*]";
471
1.54k
    u++;
472
1.54k
  }
473
2.81k
  for (; u < getNumberOfDimensions(); 
u++645
) {
474
645
    OS << "[";
475
645
476
645
    if (SizeAsPwAff) {
477
325
      isl::pw_aff Size = getDimensionSizePw(u);
478
325
      OS << " " << Size << " ";
479
325
    } else {
480
320
      OS << *getDimensionSize(u);
481
320
    }
482
645
483
645
    OS << "]";
484
645
  }
485
2.17k
486
2.17k
  OS << ";";
487
2.17k
488
2.17k
  if (BasePtrOriginSAI)
489
88
    OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
490
2.17k
491
2.17k
  OS << " // Element size " << getElemSizeInBytes() << "\n";
492
2.17k
}
493
494
const ScopArrayInfo *
495
0
ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
496
0
  isl::id Id = PMA.get_tuple_id(isl::dim::out);
497
0
  assert(!Id.is_null() && "Output dimension didn't have an ID");
498
0
  return getFromId(Id);
499
0
}
500
501
1.37k
const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
502
1.37k
  void *User = Id.get_user();
503
1.37k
  const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
504
1.37k
  return SAI;
505
1.37k
}
506
507
13
void MemoryAccess::wrapConstantDimensions() {
508
13
  auto *SAI = getScopArrayInfo();
509
13
  isl::space ArraySpace = SAI->getSpace();
510
13
  isl::ctx Ctx = ArraySpace.get_ctx();
511
13
  unsigned DimsArray = SAI->getNumberOfDimensions();
512
13
513
13
  isl::multi_aff DivModAff = isl::multi_aff::identity(
514
13
      ArraySpace.map_from_domain_and_range(ArraySpace));
515
13
  isl::local_space LArraySpace = isl::local_space(ArraySpace);
516
13
517
13
  // Begin with last dimension, to iteratively carry into higher dimensions.
518
30
  for (int i = DimsArray - 1; i > 0; 
i--17
) {
519
17
    auto *DimSize = SAI->getDimensionSize(i);
520
17
    auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
521
17
522
17
    // This transformation is not applicable to dimensions with dynamic size.
523
17
    if (!DimSizeCst)
524
0
      continue;
525
17
526
17
    // This transformation is not applicable to dimensions of size zero.
527
17
    if (DimSize->isZero())
528
0
      continue;
529
17
530
17
    isl::val DimSizeVal =
531
17
        valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
532
17
    isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
533
17
    isl::aff PrevVar =
534
17
        isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
535
17
536
17
    // Compute: index % size
537
17
    // Modulo must apply in the divide of the previous iteration, if any.
538
17
    isl::aff Modulo = Var.mod(DimSizeVal);
539
17
    Modulo = Modulo.pullback(DivModAff);
540
17
541
17
    // Compute: floor(index / size)
542
17
    isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
543
17
    Divide = Divide.floor();
544
17
    Divide = Divide.add(PrevVar);
545
17
    Divide = Divide.pullback(DivModAff);
546
17
547
17
    // Apply Modulo and Divide.
548
17
    DivModAff = DivModAff.set_aff(i, Modulo);
549
17
    DivModAff = DivModAff.set_aff(i - 1, Divide);
550
17
  }
551
13
552
13
  // Apply all modulo/divides on the accesses.
553
13
  isl::map Relation = AccessRelation;
554
13
  Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
555
13
  Relation = Relation.detect_equalities();
556
13
  AccessRelation = Relation;
557
13
}
558
559
4.64k
void MemoryAccess::updateDimensionality() {
560
4.64k
  auto *SAI = getScopArrayInfo();
561
4.64k
  isl::space ArraySpace = SAI->getSpace();
562
4.64k
  isl::space AccessSpace = AccessRelation.get_space().range();
563
4.64k
  isl::ctx Ctx = ArraySpace.get_ctx();
564
4.64k
565
4.64k
  auto DimsArray = ArraySpace.dim(isl::dim::set);
566
4.64k
  auto DimsAccess = AccessSpace.dim(isl::dim::set);
567
4.64k
  auto DimsMissing = DimsArray - DimsAccess;
568
4.64k
569
4.64k
  auto *BB = getStatement()->getEntryBlock();
570
4.64k
  auto &DL = BB->getModule()->getDataLayout();
571
4.64k
  unsigned ArrayElemSize = SAI->getElemSizeInBytes();
572
4.64k
  unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
573
4.64k
574
4.64k
  isl::map Map = isl::map::from_domain_and_range(
575
4.64k
      isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
576
4.64k
577
4.66k
  for (unsigned i = 0; i < DimsMissing; 
i++17
)
578
17
    Map = Map.fix_si(isl::dim::out, i, 0);
579
4.64k
580
8.52k
  for (unsigned i = DimsMissing; i < DimsArray; 
i++3.88k
)
581
3.88k
    Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
582
4.64k
583
4.64k
  AccessRelation = AccessRelation.apply_range(Map);
584
4.64k
585
4.64k
  // For the non delinearized arrays, divide the access function of the last
586
4.64k
  // subscript by the size of the elements in the array.
587
4.64k
  //
588
4.64k
  // A stride one array access in C expressed as A[i] is expressed in
589
4.64k
  // LLVM-IR as something like A[i * elementsize]. This hides the fact that
590
4.64k
  // two subsequent values of 'i' index two values that are stored next to
591
4.64k
  // each other in memory. By this division we make this characteristic
592
4.64k
  // obvious again. If the base pointer was accessed with offsets not divisible
593
4.64k
  // by the accesses element size, we will have chosen a smaller ArrayElemSize
594
4.64k
  // that divides the offsets of all accesses to this base pointer.
595
4.64k
  if (DimsAccess == 1) {
596
2.95k
    isl::val V = isl::val(Ctx, ArrayElemSize);
597
2.95k
    AccessRelation = AccessRelation.floordiv_val(V);
598
2.95k
  }
599
4.64k
600
4.64k
  // We currently do this only if we added at least one dimension, which means
601
4.64k
  // some dimension's indices have not been specified, an indicator that some
602
4.64k
  // index values have been added together.
603
4.64k
  // TODO: Investigate general usefulness; Effect on unit tests is to make index
604
4.64k
  // expressions more complicated.
605
4.64k
  if (DimsMissing)
606
13
    wrapConstantDimensions();
607
4.64k
608
4.64k
  if (!isAffine())
609
61
    computeBoundsOnAccessRelation(ArrayElemSize);
610
4.64k
611
4.64k
  // Introduce multi-element accesses in case the type loaded by this memory
612
4.64k
  // access is larger than the canonical element type of the array.
613
4.64k
  //
614
4.64k
  // An access ((float *)A)[i] to an array char *A is modeled as
615
4.64k
  // {[i] -> A[o] : 4 i <= o <= 4 i + 3
616
4.64k
  if (ElemBytes > ArrayElemSize) {
617
55
    assert(ElemBytes % ArrayElemSize == 0 &&
618
55
           "Loaded element size should be multiple of canonical element size");
619
55
    isl::map Map = isl::map::from_domain_and_range(
620
55
        isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
621
59
    for (unsigned i = 0; i < DimsArray - 1; 
i++4
)
622
4
      Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
623
55
624
55
    isl::constraint C;
625
55
    isl::local_space LS;
626
55
627
55
    LS = isl::local_space(Map.get_space());
628
55
    int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
629
55
630
55
    C = isl::constraint::alloc_inequality(LS);
631
55
    C = C.set_constant_val(isl::val(Ctx, Num - 1));
632
55
    C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
633
55
    C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
634
55
    Map = Map.add_constraint(C);
635
55
636
55
    C = isl::constraint::alloc_inequality(LS);
637
55
    C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
638
55
    C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
639
55
    C = C.set_constant_val(isl::val(Ctx, 0));
640
55
    Map = Map.add_constraint(C);
641
55
    AccessRelation = AccessRelation.apply_range(Map);
642
55
  }
643
4.64k
}
644
645
const std::string
646
293
MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
647
293
  switch (RT) {
648
293
  case MemoryAccess::RT_NONE:
649
0
    llvm_unreachable("Requested a reduction operator string for a memory "
650
293
                     "access which isn't a reduction");
651
293
  case MemoryAccess::RT_ADD:
652
275
    return "+";
653
293
  case MemoryAccess::RT_MUL:
654
14
    return "*";
655
293
  case MemoryAccess::RT_BOR:
656
1
    return "|";
657
293
  case MemoryAccess::RT_BXOR:
658
2
    return "^";
659
293
  case MemoryAccess::RT_BAND:
660
1
    return "&";
661
0
  }
662
0
  llvm_unreachable("Unknown reduction type");
663
0
}
664
665
23.1k
const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
666
23.1k
  isl::id ArrayId = getArrayId();
667
23.1k
  void *User = ArrayId.get_user();
668
23.1k
  const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
669
23.1k
  return SAI;
670
23.1k
}
671
672
2.92k
const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
673
2.92k
  isl::id ArrayId = getLatestArrayId();
674
2.92k
  void *User = ArrayId.get_user();
675
2.92k
  const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
676
2.92k
  return SAI;
677
2.92k
}
678
679
26.0k
isl::id MemoryAccess::getOriginalArrayId() const {
680
26.0k
  return AccessRelation.get_tuple_id(isl::dim::out);
681
26.0k
}
682
683
2.92k
isl::id MemoryAccess::getLatestArrayId() const {
684
2.92k
  if (!hasNewAccessRelation())
685
2.63k
    return getOriginalArrayId();
686
286
  return NewAccessRelation.get_tuple_id(isl::dim::out);
687
286
}
688
689
331
isl::map MemoryAccess::getAddressFunction() const {
690
331
  return getAccessRelation().lexmin();
691
331
}
692
693
isl::pw_multi_aff
694
223
MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
695
223
  isl::map Schedule, ScheduledAccRel;
696
223
  isl::union_set UDomain;
697
223
698
223
  UDomain = getStatement()->getDomain();
699
223
  USchedule = USchedule.intersect_domain(UDomain);
700
223
  Schedule = isl::map::from_union_map(USchedule);
701
223
  ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
702
223
  return isl::pw_multi_aff::from_map(ScheduledAccRel);
703
223
}
704
705
16.9k
isl::map MemoryAccess::getOriginalAccessRelation() const {
706
16.9k
  return AccessRelation;
707
16.9k
}
708
709
2.34k
std::string MemoryAccess::getOriginalAccessRelationStr() const {
710
2.34k
  return AccessRelation.to_str();
711
2.34k
}
712
713
4.55k
isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
714
4.55k
  return AccessRelation.get_space();
715
4.55k
}
716
717
527
isl::map MemoryAccess::getNewAccessRelation() const {
718
527
  return NewAccessRelation;
719
527
}
720
721
423
std::string MemoryAccess::getNewAccessRelationStr() const {
722
423
  return NewAccessRelation.to_str();
723
423
}
724
725
0
std::string MemoryAccess::getAccessRelationStr() const {
726
0
  return getAccessRelation().to_str();
727
0
}
728
729
62
isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
730
62
  isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
731
62
  Space = Space.align_params(Statement->getDomainSpace());
732
62
733
62
  return isl::basic_map::from_domain_and_range(
734
62
      isl::basic_set::universe(Statement->getDomainSpace()),
735
62
      isl::basic_set::universe(Space));
736
62
}
737
738
// Formalize no out-of-bound access assumption
739
//
740
// When delinearizing array accesses we optimistically assume that the
741
// delinearized accesses do not access out of bound locations (the subscript
742
// expression of each array evaluates for each statement instance that is
743
// executed to a value that is larger than zero and strictly smaller than the
744
// size of the corresponding dimension). The only exception is the outermost
745
// dimension for which we do not need to assume any upper bound.  At this point
746
// we formalize this assumption to ensure that at code generation time the
747
// relevant run-time checks can be generated.
748
//
749
// To find the set of constraints necessary to avoid out of bound accesses, we
750
// first build the set of data locations that are not within array bounds. We
751
// then apply the reverse access relation to obtain the set of iterations that
752
// may contain invalid accesses and reduce this set of iterations to the ones
753
// that are actually executed by intersecting them with the domain of the
754
// statement. If we now project out all loop dimensions, we obtain a set of
755
// parameters that may cause statement instances to be executed that may
756
// possibly yield out of bound memory accesses. The complement of these
757
// constraints is the set of constraints that needs to be assumed to ensure such
758
// statement instances are never executed.
759
4.64k
void MemoryAccess::assumeNoOutOfBound() {
760
4.64k
  if (PollyIgnoreInbounds)
761
93
    return;
762
4.55k
  auto *SAI = getScopArrayInfo();
763
4.55k
  isl::space Space = getOriginalAccessRelationSpace().range();
764
4.55k
  isl::set Outside = isl::set::empty(Space);
765
5.09k
  for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; 
++i542
) {
766
542
    isl::local_space LS(Space);
767
542
    isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
768
542
    isl::pw_aff Zero = isl::pw_aff(LS);
769
542
770
542
    isl::set DimOutside = Var.lt_set(Zero);
771
542
    isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
772
542
    SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
773
542
    SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
774
542
    DimOutside = DimOutside.unite(SizeE.le_set(Var));
775
542
776
542
    Outside = Outside.unite(DimOutside);
777
542
  }
778
4.55k
779
4.55k
  Outside = Outside.apply(getAccessRelation().reverse());
780
4.55k
  Outside = Outside.intersect(Statement->getDomain());
781
4.55k
  Outside = Outside.params();
782
4.55k
783
4.55k
  // Remove divs to avoid the construction of overly complicated assumptions.
784
4.55k
  // Doing so increases the set of parameter combinations that are assumed to
785
4.55k
  // not appear. This is always save, but may make the resulting run-time check
786
4.55k
  // bail out more often than strictly necessary.
787
4.55k
  Outside = Outside.remove_divs();
788
4.55k
  Outside = Outside.complement();
789
4.55k
  const auto &Loc = getAccessInstruction()
790
4.55k
                        ? 
getAccessInstruction()->getDebugLoc()4.21k
791
4.55k
                        : 
DebugLoc()340
;
792
4.55k
  if (!PollyPreciseInbounds)
793
4.53k
    Outside = Outside.gist_params(Statement->getDomain().params());
794
4.55k
  Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
795
4.55k
                                           AS_ASSUMPTION);
796
4.55k
}
797
798
24
void MemoryAccess::buildMemIntrinsicAccessRelation() {
799
24
  assert(isMemoryIntrinsic());
800
24
  assert(Subscripts.size() == 2 && Sizes.size() == 1);
801
24
802
24
  isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
803
24
  isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
804
24
805
24
  isl::map LengthMap;
806
24
  if (Subscripts[1] == nullptr) {
807
0
    LengthMap = isl::map::universe(SubscriptMap.get_space());
808
24
  } else {
809
24
    isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
810
24
    LengthMap = isl::map::from_pw_aff(LengthPWA);
811
24
    isl::space RangeSpace = LengthMap.get_space().range();
812
24
    LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
813
24
  }
814
24
  LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
815
24
  LengthMap = LengthMap.align_params(SubscriptMap.get_space());
816
24
  SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
817
24
  LengthMap = LengthMap.sum(SubscriptMap);
818
24
  AccessRelation =
819
24
      LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
820
24
}
821
822
61
void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
823
61
  ScalarEvolution *SE = Statement->getParent()->getSE();
824
61
825
61
  auto MAI = MemAccInst(getAccessInstruction());
826
61
  if (isa<MemIntrinsic>(MAI))
827
0
    return;
828
61
829
61
  Value *Ptr = MAI.getPointerOperand();
830
61
  if (!Ptr || 
!SE->isSCEVable(Ptr->getType())39
)
831
22
    return;
832
39
833
39
  auto *PtrSCEV = SE->getSCEV(Ptr);
834
39
  if (isa<SCEVCouldNotCompute>(PtrSCEV))
835
0
    return;
836
39
837
39
  auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
838
39
  if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
839
39
    PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
840
39
841
39
  const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
842
39
  if (Range.isFullSet())
843
2
    return;
844
37
845
37
  if (Range.isWrappedSet() || 
Range.isSignWrappedSet()13
)
846
26
    return;
847
11
848
11
  bool isWrapping = Range.isSignWrappedSet();
849
11
850
11
  unsigned BW = Range.getBitWidth();
851
11
  const auto One = APInt(BW, 1);
852
11
  const auto LB = isWrapping ? 
Range.getLower()0
: Range.getSignedMin();
853
11
  const auto UB = isWrapping ? 
(Range.getUpper() - One)0
: Range.getSignedMax();
854
11
855
11
  auto Min = LB.sdiv(APInt(BW, ElementSize));
856
11
  auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
857
11
858
11
  assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
859
11
860
11
  isl::map Relation = AccessRelation;
861
11
  isl::set AccessRange = Relation.range();
862
11
  AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
863
11
                                    isl::dim::set);
864
11
  AccessRelation = Relation.intersect_range(AccessRange);
865
11
}
866
867
4.64k
void MemoryAccess::foldAccessRelation() {
868
4.64k
  if (Sizes.size() < 2 || 
isa<SCEVConstant>(Sizes[1])410
)
869
4.47k
    return;
870
172
871
172
  int Size = Subscripts.size();
872
172
873
172
  isl::map NewAccessRelation = AccessRelation;
874
172
875
440
  for (int i = Size - 2; i >= 0; 
--i268
) {
876
268
    isl::space Space;
877
268
    isl::map MapOne, MapTwo;
878
268
    isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
879
268
880
268
    isl::space SpaceSize = DimSize.get_space();
881
268
    isl::id ParamId =
882
268
        give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
883
268
884
268
    Space = AccessRelation.get_space();
885
268
    Space = Space.range().map_from_set();
886
268
    Space = Space.align_params(SpaceSize);
887
268
888
268
    int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
889
268
890
268
    MapOne = isl::map::universe(Space);
891
1.03k
    for (int j = 0; j < Size; 
++j764
)
892
764
      MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
893
268
    MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
894
268
895
268
    MapTwo = isl::map::universe(Space);
896
1.03k
    for (int j = 0; j < Size; 
++j764
)
897
764
      if (j < i || 
j > i + 1650
)
898
228
        MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
899
268
900
268
    isl::local_space LS(Space);
901
268
    isl::constraint C;
902
268
    C = isl::constraint::alloc_equality(LS);
903
268
    C = C.set_constant_si(-1);
904
268
    C = C.set_coefficient_si(isl::dim::in, i, 1);
905
268
    C = C.set_coefficient_si(isl::dim::out, i, -1);
906
268
    MapTwo = MapTwo.add_constraint(C);
907
268
    C = isl::constraint::alloc_equality(LS);
908
268
    C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
909
268
    C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
910
268
    C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
911
268
    MapTwo = MapTwo.add_constraint(C);
912
268
    MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
913
268
914
268
    MapOne = MapOne.unite(MapTwo);
915
268
    NewAccessRelation = NewAccessRelation.apply_range(MapOne);
916
268
  }
917
172
918
172
  isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
919
172
  isl::space Space = Statement->getDomainSpace();
920
172
  NewAccessRelation = NewAccessRelation.set_tuple_id(
921
172
      isl::dim::in, Space.get_tuple_id(isl::dim::set));
922
172
  NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
923
172
  NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
924
172
925
172
  // Access dimension folding might in certain cases increase the number of
926
172
  // disjuncts in the memory access, which can possibly complicate the generated
927
172
  // run-time checks and can lead to costly compilation.
928
172
  if (!PollyPreciseFoldAccesses &&
929
172
      isl_map_n_basic_map(NewAccessRelation.get()) >
930
165
          isl_map_n_basic_map(AccessRelation.get())) {
931
169
  } else {
932
169
    AccessRelation = NewAccessRelation;
933
169
  }
934
172
}
935
936
/// Check if @p Expr is divisible by @p Size.
937
6.61k
static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
938
6.61k
  assert(Size != 0);
939
6.61k
  if (Size == 1)
940
141
    return true;
941
6.47k
942
6.47k
  // Only one factor needs to be divisible.
943
6.47k
  if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
944
381
    for (auto *FactorExpr : MulExpr->operands())
945
381
      if (isDivisible(FactorExpr, Size, SE))
946
381
        return true;
947
381
    
return false0
;
948
6.09k
  }
949
6.09k
950
6.09k
  // For other n-ary expressions (Add, AddRec, Max,...) all operands need
951
6.09k
  // to be divisible.
952
6.09k
  if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
953
1.64k
    for (auto *OpExpr : NAryExpr->operands())
954
3.29k
      if (!isDivisible(OpExpr, Size, SE))
955
0
        return false;
956
1.64k
    return true;
957
4.44k
  }
958
4.44k
959
4.44k
  auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
960
4.44k
  auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
961
4.44k
  auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
962
4.44k
  return MulSCEV == Expr;
963
4.44k
}
964
965
4.69k
void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
966
4.69k
  assert(AccessRelation.is_null() && "AccessRelation already built");
967
4.69k
968
4.69k
  // Initialize the invalid domain which describes all iterations for which the
969
4.69k
  // access relation is not modeled correctly.
970
4.69k
  isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
971
4.69k
  InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
972
4.69k
973
4.69k
  isl::ctx Ctx = Id.get_ctx();
974
4.69k
  isl::id BaseAddrId = SAI->getBasePtrId();
975
4.69k
976
4.69k
  if (getAccessInstruction() && 
isa<MemIntrinsic>(getAccessInstruction())4.35k
) {
977
24
    buildMemIntrinsicAccessRelation();
978
24
    AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
979
24
    return;
980
24
  }
981
4.67k
982
4.67k
  if (!isAffine()) {
983
62
    // We overapproximate non-affine accesses with a possible access to the
984
62
    // whole array. For read accesses it does not make a difference, if an
985
62
    // access must or may happen. However, for write accesses it is important to
986
62
    // differentiate between writes that must happen and writes that may happen.
987
62
    if (AccessRelation.is_null())
988
62
      AccessRelation = createBasicAccessMap(Statement);
989
62
990
62
    AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
991
62
    return;
992
62
  }
993
4.60k
994
4.60k
  isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
995
4.60k
  AccessRelation = isl::map::universe(Space);
996
4.60k
997
8.44k
  for (int i = 0, Size = Subscripts.size(); i < Size; 
++i3.83k
) {
998
3.83k
    isl::pw_aff Affine = getPwAff(Subscripts[i]);
999
3.83k
    isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1000
3.83k
    AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
1001
3.83k
  }
1002
4.60k
1003
4.60k
  Space = Statement->getDomainSpace();
1004
4.60k
  AccessRelation = AccessRelation.set_tuple_id(
1005
4.60k
      isl::dim::in, Space.get_tuple_id(isl::dim::set));
1006
4.60k
  AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
1007
4.60k
1008
4.60k
  AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
1009
4.60k
}
1010
1011
MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
1012
                           AccessType AccType, Value *BaseAddress,
1013
                           Type *ElementType, bool Affine,
1014
                           ArrayRef<const SCEV *> Subscripts,
1015
                           ArrayRef<const SCEV *> Sizes, Value *AccessValue,
1016
                           MemoryKind Kind)
1017
    : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1018
      BaseAddr(BaseAddress), ElementType(ElementType),
1019
      Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1020
      AccessValue(AccessValue), IsAffine(Affine),
1021
      Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
1022
5.03k
      NewAccessRelation(nullptr), FAD(nullptr) {
1023
5.03k
  static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
1024
5.03k
  const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
1025
5.03k
1026
5.03k
  std::string IdName = Stmt->getBaseName() + Access;
1027
5.03k
  Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
1028
5.03k
}
1029
1030
MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
1031
    : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1032
      InvalidDomain(nullptr), AccessRelation(nullptr),
1033
48
      NewAccessRelation(AccRel), FAD(nullptr) {
1034
48
  isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
1035
48
  auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1036
48
  Sizes.push_back(nullptr);
1037
120
  for (unsigned i = 1; i < SAI->getNumberOfDimensions(); 
i++72
)
1038
72
    Sizes.push_back(SAI->getDimensionSize(i));
1039
48
  ElementType = SAI->getElementType();
1040
48
  BaseAddr = SAI->getBasePtr();
1041
48
  static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
1042
48
  const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
1043
48
1044
48
  std::string IdName = Stmt->getBaseName() + Access;
1045
48
  Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
1046
48
}
1047
1048
5.01k
MemoryAccess::~MemoryAccess() = default;
1049
1050
4.64k
void MemoryAccess::realignParams() {
1051
4.64k
  isl::set Ctx = Statement->getParent()->getContext();
1052
4.64k
  InvalidDomain = InvalidDomain.gist_params(Ctx);
1053
4.64k
  AccessRelation = AccessRelation.gist_params(Ctx);
1054
4.64k
}
1055
1056
0
const std::string MemoryAccess::getReductionOperatorStr() const {
1057
0
  return MemoryAccess::getReductionOperatorStr(getReductionType());
1058
0
}
1059
1060
1.82k
isl::id MemoryAccess::getId() const { return Id; }
1061
1062
raw_ostream &polly::operator<<(raw_ostream &OS,
1063
2.34k
                               MemoryAccess::ReductionType RT) {
1064
2.34k
  if (RT == MemoryAccess::RT_NONE)
1065
2.08k
    OS << "NONE";
1066
268
  else
1067
268
    OS << MemoryAccess::getReductionOperatorStr(RT);
1068
2.34k
  return OS;
1069
2.34k
}
1070
1071
10
void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
1072
1073
2.34k
void MemoryAccess::print(raw_ostream &OS) const {
1074
2.34k
  switch (AccType) {
1075
2.34k
  case READ:
1076
1.07k
    OS.indent(12) << "ReadAccess :=\t";
1077
1.07k
    break;
1078
2.34k
  case MUST_WRITE:
1079
1.22k
    OS.indent(12) << "MustWriteAccess :=\t";
1080
1.22k
    break;
1081
2.34k
  case MAY_WRITE:
1082
45
    OS.indent(12) << "MayWriteAccess :=\t";
1083
45
    break;
1084
2.34k
  }
1085
2.34k
1086
2.34k
  OS << "[Reduction Type: " << getReductionType() << "] ";
1087
2.34k
1088
2.34k
  if (FAD) {
1089
8
    OS << "[Fortran array descriptor: " << FAD->getName();
1090
8
    OS << "] ";
1091
8
  };
1092
2.34k
1093
2.34k
  OS << "[Scalar: " << isScalarKind() << "]\n";
1094
2.34k
  OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
1095
2.34k
  if (hasNewAccessRelation())
1096
423
    OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
1097
2.34k
}
1098
1099
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1100
LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
1101
#endif
1102
1103
4.15k
isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
1104
4.15k
  auto *Stmt = getStatement();
1105
4.15k
  PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
1106
4.15k
  isl::set StmtDom = getStatement()->getDomain();
1107
4.15k
  StmtDom = StmtDom.reset_tuple_id();
1108
4.15k
  isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
1109
4.15k
  InvalidDomain = InvalidDomain.unite(NewInvalidDom);
1110
4.15k
  return PWAC.first;
1111
4.15k
}
1112
1113
// Create a map in the size of the provided set domain, that maps from the
1114
// one element of the provided set domain to another element of the provided
1115
// set domain.
1116
// The mapping is limited to all points that are equal in all but the last
1117
// dimension and for which the last dimension of the input is strict smaller
1118
// than the last dimension of the output.
1119
//
1120
//   getEqualAndLarger(set[i0, i1, ..., iX]):
1121
//
1122
//   set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1123
//     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1124
//
1125
47
static isl::map getEqualAndLarger(isl::space SetDomain) {
1126
47
  isl::space Space = SetDomain.map_from_set();
1127
47
  isl::map Map = isl::map::universe(Space);
1128
47
  unsigned lastDimension = Map.dim(isl::dim::in) - 1;
1129
47
1130
47
  // Set all but the last dimension to be equal for the input and output
1131
47
  //
1132
47
  //   input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1133
47
  //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
1134
75
  for (unsigned i = 0; i < lastDimension; 
++i28
)
1135
28
    Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
1136
47
1137
47
  // Set the last dimension of the input to be strict smaller than the
1138
47
  // last dimension of the output.
1139
47
  //
1140
47
  //   input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
1141
47
  Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
1142
47
  return Map;
1143
47
}
1144
1145
47
isl::set MemoryAccess::getStride(isl::map Schedule) const {
1146
47
  isl::map AccessRelation = getAccessRelation();
1147
47
  isl::space Space = Schedule.get_space().range();
1148
47
  isl::map NextScatt = getEqualAndLarger(Space);
1149
47
1150
47
  Schedule = Schedule.reverse();
1151
47
  NextScatt = NextScatt.lexmin();
1152
47
1153
47
  NextScatt = NextScatt.apply_range(Schedule);
1154
47
  NextScatt = NextScatt.apply_range(AccessRelation);
1155
47
  NextScatt = NextScatt.apply_domain(Schedule);
1156
47
  NextScatt = NextScatt.apply_domain(AccessRelation);
1157
47
1158
47
  isl::set Deltas = NextScatt.deltas();
1159
47
  return Deltas;
1160
47
}
1161
1162
47
bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1163
47
  isl::set Stride, StrideX;
1164
47
  bool IsStrideX;
1165
47
1166
47
  Stride = getStride(Schedule);
1167
47
  StrideX = isl::set::universe(Stride.get_space());
1168
57
  for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; 
i++10
)
1169
10
    StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1170
47
  StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1171
47
                           StrideWidth);
1172
47
  IsStrideX = Stride.is_subset(StrideX);
1173
47
1174
47
  return IsStrideX;
1175
47
}
1176
1177
15
bool MemoryAccess::isStrideZero(isl::map Schedule) const {
1178
15
  return isStrideX(Schedule, 0);
1179
15
}
1180
1181
28
bool MemoryAccess::isStrideOne(isl::map Schedule) const {
1182
28
  return isStrideX(Schedule, 1);
1183
28
}
1184
1185
17
void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1186
17
  AccessRelation = NewAccess;
1187
17
}
1188
1189
502
void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
1190
502
  assert(NewAccess);
1191
502
1192
#ifndef NDEBUG
1193
  // Check domain space compatibility.
1194
  isl::space NewSpace = NewAccess.get_space();
1195
  isl::space NewDomainSpace = NewSpace.domain();
1196
  isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
1197
  assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
1198
1199
  // Reads must be executed unconditionally. Writes might be executed in a
1200
  // subdomain only.
1201
  if (isRead()) {
1202
    // Check whether there is an access for every statement instance.
1203
    isl::set StmtDomain = getStatement()->getDomain();
1204
    StmtDomain =
1205
        StmtDomain.intersect_params(getStatement()->getParent()->getContext());
1206
    isl::set NewDomain = NewAccess.domain();
1207
    assert(StmtDomain.is_subset(NewDomain) &&
1208
           "Partial READ accesses not supported");
1209
  }
1210
1211
  isl::space NewAccessSpace = NewAccess.get_space();
1212
  assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
1213
         "Must specify the array that is accessed");
1214
  isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1215
  auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
1216
  assert(SAI && "Must set a ScopArrayInfo");
1217
1218
  if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1219
    InvariantEquivClassTy *EqClass =
1220
        getStatement()->getParent()->lookupInvariantEquivClass(
1221
            SAI->getBasePtr());
1222
    assert(EqClass &&
1223
           "Access functions to indirect arrays must have an invariant and "
1224
           "hoisted base pointer");
1225
  }
1226
1227
  // Check whether access dimensions correspond to number of dimensions of the
1228
  // accesses array.
1229
  auto Dims = SAI->getNumberOfDimensions();
1230
  assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
1231
         "Access dims must match array dims");
1232
#endif
1233
1234
502
  NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
1235
502
  NewAccessRelation = NewAccess;
1236
502
}
1237
1238
27
bool MemoryAccess::isLatestPartialAccess() const {
1239
27
  isl::set StmtDom = getStatement()->getDomain();
1240
27
  isl::set AccDom = getLatestAccessRelation().domain();
1241
27
1242
27
  return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1243
27
}
1244
1245
//===----------------------------------------------------------------------===//
1246
1247
1.27k
isl::map ScopStmt::getSchedule() const {
1248
1.27k
  isl::set Domain = getDomain();
1249
1.27k
  if (Domain.is_empty())
1250
4
    return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1251
1.27k
  auto Schedule = getParent()->getSchedule();
1252
1.27k
  if (!Schedule)
1253
4
    return nullptr;
1254
1.26k
  Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1255
1.26k
  if (Schedule.is_empty())
1256
0
    return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1257
1.26k
  isl::map M = M.from_union_map(Schedule);
1258
1.26k
  M = M.coalesce();
1259
1.26k
  M = M.gist_domain(Domain);
1260
1.26k
  M = M.coalesce();
1261
1.26k
  return M;
1262
1.26k
}
1263
1264
8
void ScopStmt::restrictDomain(isl::set NewDomain) {
1265
8
  assert(NewDomain.is_subset(Domain) &&
1266
8
         "New domain is not a subset of old domain!");
1267
8
  Domain = NewDomain;
1268
8
}
1269
1270
5.08k
void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
1271
5.08k
  Instruction *AccessInst = Access->getAccessInstruction();
1272
5.08k
1273
5.08k
  if (Access->isArrayKind()) {
1274
3.70k
    MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1275
3.70k
    MAL.emplace_front(Access);
1276
3.70k
  } else 
if (1.37k
Access->isValueKind()1.37k
&&
Access->isWrite()697
) {
1277
339
    Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
1278
339
    assert(!ValueWrites.lookup(AccessVal));
1279
339
1280
339
    ValueWrites[AccessVal] = Access;
1281
1.03k
  } else if (Access->isValueKind() && 
Access->isRead()358
) {
1282
358
    Value *AccessVal = Access->getAccessValue();
1283
358
    assert(!ValueReads.lookup(AccessVal));
1284
358
1285
358
    ValueReads[AccessVal] = Access;
1286
676
  } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1287
448
    PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1288
448
    assert(!PHIWrites.lookup(PHI));
1289
448
1290
448
    PHIWrites[PHI] = Access;
1291
448
  } else 
if (228
Access->isAnyPHIKind()228
&&
Access->isRead()228
) {
1292
228
    PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1293
228
    assert(!PHIReads.lookup(PHI));
1294
228
1295
228
    PHIReads[PHI] = Access;
1296
228
  }
1297
5.08k
1298
5.08k
  if (Prepend) {
1299
16
    MemAccs.insert(MemAccs.begin(), Access);
1300
16
    return;
1301
16
  }
1302
5.06k
  MemAccs.push_back(Access);
1303
5.06k
}
1304
1305
2.26k
void ScopStmt::realignParams() {
1306
2.26k
  for (MemoryAccess *MA : *this)
1307
4.64k
    MA->realignParams();
1308
2.26k
1309
2.26k
  isl::set Ctx = Parent.getContext();
1310
2.26k
  InvalidDomain = InvalidDomain.gist_params(Ctx);
1311
2.26k
  Domain = Domain.gist_params(Ctx);
1312
2.26k
}
1313
1314
/// Add @p BSet to the set @p User if @p BSet is bounded.
1315
static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1316
2.37k
                                    void *User) {
1317
2.37k
  isl_set **BoundedParts = static_cast<isl_set **>(User);
1318
2.37k
  if (isl_basic_set_is_bounded(BSet))
1319
2.11k
    *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1320
267
  else
1321
267
    isl_basic_set_free(BSet);
1322
2.37k
  return isl_stat_ok;
1323
2.37k
}
1324
1325
/// Return the bounded parts of @p S.
1326
1.67k
static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1327
1.67k
  isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1328
1.67k
  isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1329
1.67k
  isl_set_free(S);
1330
1.67k
  return BoundedParts;
1331
1.67k
}
1332
1333
/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1334
///
1335
/// @returns A separation of @p S into first an unbounded then a bounded subset,
1336
///          both with regards to the dimension @p Dim.
1337
static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1338
1.67k
partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1339
3.90k
  for (unsigned u = 0, e = isl_set_n_dim(S); u < e; 
u++2.23k
)
1340
2.23k
    S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
1341
1.67k
1342
1.67k
  unsigned NumDimsS = isl_set_n_dim(S);
1343
1.67k
  isl_set *OnlyDimS = isl_set_copy(S);
1344
1.67k
1345
1.67k
  // Remove dimensions that are greater than Dim as they are not interesting.
1346
1.67k
  assert(NumDimsS >= Dim + 1);
1347
1.67k
  OnlyDimS =
1348
1.67k
      isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1349
1.67k
1350
1.67k
  // Create artificial parametric upper bounds for dimensions smaller than Dim
1351
1.67k
  // as we are not interested in them.
1352
1.67k
  OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1353
2.23k
  for (unsigned u = 0; u < Dim; 
u++561
) {
1354
561
    isl_constraint *C = isl_inequality_alloc(
1355
561
        isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1356
561
    C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1357
561
    C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1358
561
    OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1359
561
  }
1360
1.67k
1361
1.67k
  // Collect all bounded parts of OnlyDimS.
1362
1.67k
  isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1363
1.67k
1364
1.67k
  // Create the dimensions greater than Dim again.
1365
1.67k
  BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1366
1.67k
                                     NumDimsS - Dim - 1);
1367
1.67k
1368
1.67k
  // Remove the artificial upper bound parameters again.
1369
1.67k
  BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1370
1.67k
1371
1.67k
  isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
1372
1.67k
  return std::make_pair(UnboundedParts, BoundedParts);
1373
1.67k
}
1374
1375
/// Set the dimension Ids from @p From in @p To.
1376
static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1377
2.75k
                                           __isl_take isl_set *To) {
1378
6.14k
  for (unsigned u = 0, e = isl_set_n_dim(From); u < e; 
u++3.38k
) {
1379
3.38k
    isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1380
3.38k
    To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1381
3.38k
  }
1382
2.75k
  return To;
1383
2.75k
}
1384
1385
/// Create the conditions under which @p L @p Pred @p R is true.
1386
static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1387
                                             __isl_take isl_pw_aff *L,
1388
2.70k
                                             __isl_take isl_pw_aff *R) {
1389
2.70k
  switch (Pred) {
1390
2.70k
  case ICmpInst::ICMP_EQ:
1391
725
    return isl_pw_aff_eq_set(L, R);
1392
2.70k
  case ICmpInst::ICMP_NE:
1393
1.05k
    return isl_pw_aff_ne_set(L, R);
1394
2.70k
  case ICmpInst::ICMP_SLT:
1395
723
    return isl_pw_aff_lt_set(L, R);
1396
2.70k
  case ICmpInst::ICMP_SLE:
1397
67
    return isl_pw_aff_le_set(L, R);
1398
2.70k
  case ICmpInst::ICMP_SGT:
1399
127
    return isl_pw_aff_gt_set(L, R);
1400
2.70k
  case ICmpInst::ICMP_SGE:
1401
15
    return isl_pw_aff_ge_set(L, R);
1402
2.70k
  case ICmpInst::ICMP_ULT:
1403
0
    return isl_pw_aff_lt_set(L, R);
1404
2.70k
  case ICmpInst::ICMP_UGT:
1405
0
    return isl_pw_aff_gt_set(L, R);
1406
2.70k
  case ICmpInst::ICMP_ULE:
1407
0
    return isl_pw_aff_le_set(L, R);
1408
2.70k
  case ICmpInst::ICMP_UGE:
1409
0
    return isl_pw_aff_ge_set(L, R);
1410
2.70k
  default:
1411
0
    llvm_unreachable("Non integer predicate not supported");
1412
0
  }
1413
0
}
1414
1415
/// Create the conditions under which @p L @p Pred @p R is true.
1416
///
1417
/// Helper function that will make sure the dimensions of the result have the
1418
/// same isl_id's as the @p Domain.
1419
static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1420
                                             __isl_take isl_pw_aff *L,
1421
                                             __isl_take isl_pw_aff *R,
1422
2.70k
                                             __isl_keep isl_set *Domain) {
1423
2.70k
  isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1424
2.70k
  return setDimensionIds(Domain, ConsequenceCondSet);
1425
2.70k
}
1426
1427
/// Compute the isl representation for the SCEV @p E in this BB.
1428
///
1429
/// @param S                The Scop in which @p BB resides in.
1430
/// @param BB               The BB for which isl representation is to be
1431
/// computed.
1432
/// @param InvalidDomainMap A map of BB to their invalid domains.
1433
/// @param E                The SCEV that should be translated.
1434
/// @param NonNegative      Flag to indicate the @p E has to be non-negative.
1435
///
1436
/// Note that this function will also adjust the invalid context accordingly.
1437
1438
__isl_give isl_pw_aff *
1439
getPwAff(Scop &S, BasicBlock *BB,
1440
         DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1441
5.44k
         bool NonNegative = false) {
1442
5.44k
  PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
1443
5.44k
  InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
1444
5.44k
  return PWAC.first.take();
1445
5.44k
}
1446
1447
/// Build the conditions sets for the switch @p SI in the @p Domain.
1448
///
1449
/// This will fill @p ConditionSets with the conditions under which control
1450
/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1451
/// have as many elements as @p SI has successors.
1452
bool buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1453
                        __isl_keep isl_set *Domain,
1454
                        DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1455
19
                        SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1456
19
  Value *Condition = getConditionFromTerminator(SI);
1457
19
  assert(Condition && "No condition for switch");
1458
19
1459
19
  ScalarEvolution &SE = *S.getSE();
1460
19
  isl_pw_aff *LHS, *RHS;
1461
19
  LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
1462
19
1463
19
  unsigned NumSuccessors = SI->getNumSuccessors();
1464
19
  ConditionSets.resize(NumSuccessors);
1465
56
  for (auto &Case : SI->cases()) {
1466
56
    unsigned Idx = Case.getSuccessorIndex();
1467
56
    ConstantInt *CaseValue = Case.getCaseValue();
1468
56
1469
56
    RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
1470
56
    isl_set *CaseConditionSet =
1471
56
        buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1472
56
    ConditionSets[Idx] = isl_set_coalesce(
1473
56
        isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1474
56
  }
1475
19
1476
19
  assert(ConditionSets[0] == nullptr && "Default condition set was set");
1477
19
  isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1478
56
  for (unsigned u = 2; u < NumSuccessors; 
u++37
)
1479
37
    ConditionSetUnion =
1480
37
        isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1481
19
  ConditionSets[0] = setDimensionIds(
1482
19
      Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1483
19
1484
19
  isl_pw_aff_free(LHS);
1485
19
1486
19
  return true;
1487
19
}
1488
1489
/// Build condition sets for unsigned ICmpInst(s).
1490
/// Special handling is required for unsigned operands to ensure that if
1491
/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1492
/// it should wrap around.
1493
///
1494
/// @param IsStrictUpperBound holds information on the predicate relation
1495
/// between TestVal and UpperBound, i.e,
1496
/// TestVal < UpperBound  OR  TestVal <= UpperBound
1497
__isl_give isl_set *
1498
buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1499
                           __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1500
                           const SCEV *SCEV_UpperBound,
1501
                           DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1502
30
                           bool IsStrictUpperBound) {
1503
30
  // Do not take NonNeg assumption on TestVal
1504
30
  // as it might have MSB (Sign bit) set.
1505
30
  isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1506
30
  // Take NonNeg assumption on UpperBound.
1507
30
  isl_pw_aff *UpperBound =
1508
30
      getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1509
30
1510
30
  // 0 <= TestVal
1511
30
  isl_set *First =
1512
30
      isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1513
30
                            isl_pw_aff_get_domain_space(TestVal))),
1514
30
                        isl_pw_aff_copy(TestVal));
1515
30
1516
30
  isl_set *Second;
1517
30
  if (IsStrictUpperBound)
1518
22
    // TestVal < UpperBound
1519
22
    Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1520
8
  else
1521
8
    // TestVal <= UpperBound
1522
8
    Second = isl_pw_aff_le_set(TestVal, UpperBound);
1523
30
1524
30
  isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1525
30
  ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1526
30
  return ConsequenceCondSet;
1527
30
}
1528
1529
/// Build the conditions sets for the branch condition @p Condition in
1530
/// the @p Domain.
1531
///
1532
/// This will fill @p ConditionSets with the conditions under which control
1533
/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1534
/// have as many elements as @p TI has successors. If @p TI is nullptr the
1535
/// context under which @p Condition is true/false will be returned as the
1536
/// new elements of @p ConditionSets.
1537
bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1538
                        TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1539
                        DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1540
2.92k
                        SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1541
2.92k
  ScalarEvolution &SE = *S.getSE();
1542
2.92k
  isl_set *ConsequenceCondSet = nullptr;
1543
2.92k
1544
2.92k
  if (auto Load = dyn_cast<LoadInst>(Condition)) {
1545
1
    const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
1546
1
    const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
1547
1
    bool NonNeg = false;
1548
1
    isl_pw_aff *LHS = getPwAff(S, BB, InvalidDomainMap, LHSSCEV, NonNeg);
1549
1
    isl_pw_aff *RHS = getPwAff(S, BB, InvalidDomainMap, RHSSCEV, NonNeg);
1550
1
    ConsequenceCondSet =
1551
1
        buildConditionSet(ICmpInst::ICMP_SLE, LHS, RHS, Domain);
1552
2.92k
  } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
1553
1
    auto *Unique = dyn_cast<ConstantInt>(
1554
1
        getUniqueNonErrorValue(PHI, &S.getRegion(), *S.getLI(), *S.getDT()));
1555
1
1556
1
    if (Unique->isZero())
1557
0
      ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1558
1
    else
1559
1
      ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1560
2.91k
  } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1561
195
    if (CCond->isZero())
1562
164
      ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1563
31
    else
1564
31
      ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1565
2.72k
  } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1566
42
    auto Opcode = BinOp->getOpcode();
1567
42
    assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1568
42
1569
42
    bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1570
42
                                    InvalidDomainMap, ConditionSets) &&
1571
42
                 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1572
23
                                    InvalidDomainMap, ConditionSets);
1573
42
    if (!Valid) {
1574
22
      while (!ConditionSets.empty())
1575
2
        isl_set_free(ConditionSets.pop_back_val());
1576
20
      return false;
1577
20
    }
1578
22
1579
22
    isl_set_free(ConditionSets.pop_back_val());
1580
22
    isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1581
22
    isl_set_free(ConditionSets.pop_back_val());
1582
22
    isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1583
22
1584
22
    if (Opcode == Instruction::And)
1585
10
      ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1586
12
    else
1587
12
      ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1588
2.68k
  } else {
1589
2.68k
    auto *ICond = dyn_cast<ICmpInst>(Condition);
1590
2.68k
    assert(ICond &&
1591
2.68k
           "Condition of exiting branch was neither constant nor ICmp!");
1592
2.68k
1593
2.68k
    LoopInfo &LI = *S.getLI();
1594
2.68k
    DominatorTree &DT = *S.getDT();
1595
2.68k
    Region &R = S.getRegion();
1596
2.68k
1597
2.68k
    isl_pw_aff *LHS, *RHS;
1598
2.68k
    // For unsigned comparisons we assumed the signed bit of neither operand
1599
2.68k
    // to be set. The comparison is equal to a signed comparison under this
1600
2.68k
    // assumption.
1601
2.68k
    bool NonNeg = ICond->isUnsigned();
1602
2.68k
    const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1603
2.68k
               *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1604
2.68k
1605
2.68k
    LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
1606
2.68k
    RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
1607
2.68k
1608
2.68k
    switch (ICond->getPredicate()) {
1609
2.68k
    case ICmpInst::ICMP_ULT:
1610
17
      ConsequenceCondSet =
1611
17
          buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1612
17
                                     RightOperand, InvalidDomainMap, true);
1613
17
      break;
1614
2.68k
    case ICmpInst::ICMP_ULE:
1615
3
      ConsequenceCondSet =
1616
3
          buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1617
3
                                     RightOperand, InvalidDomainMap, false);
1618
3
      break;
1619
2.68k
    case ICmpInst::ICMP_UGT:
1620
5
      ConsequenceCondSet =
1621
5
          buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1622
5
                                     LeftOperand, InvalidDomainMap, true);
1623
5
      break;
1624
2.68k
    case ICmpInst::ICMP_UGE:
1625
5
      ConsequenceCondSet =
1626
5
          buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1627
5
                                     LeftOperand, InvalidDomainMap, false);
1628
5
      break;
1629
2.68k
    default:
1630
2.65k
      LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1631
2.65k
      RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1632
2.65k
      ConsequenceCondSet =
1633
2.65k
          buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1634
2.65k
      break;
1635
2.90k
    }
1636
2.90k
  }
1637
2.90k
1638
2.90k
  // If no terminator was given we are only looking for parameter constraints
1639
2.90k
  // under which @p Condition is true/false.
1640
2.90k
  if (!TI)
1641
24
    ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1642
2.90k
  assert(ConsequenceCondSet);
1643
2.90k
  ConsequenceCondSet = isl_set_coalesce(
1644
2.90k
      isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
1645
2.90k
1646
2.90k
  isl_set *AlternativeCondSet = nullptr;
1647
2.90k
  bool TooComplex =
1648
2.90k
      isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
1649
2.90k
1650
2.90k
  if (!TooComplex) {
1651
2.90k
    AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1652
2.90k
                                          isl_set_copy(ConsequenceCondSet));
1653
2.90k
    TooComplex =
1654
2.90k
        isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
1655
2.90k
  }
1656
2.90k
1657
2.90k
  if (TooComplex) {
1658
5
    S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : 
DebugLoc()0
,
1659
5
                 TI ? TI->getParent() : 
nullptr0
/* BasicBlock */);
1660
5
    isl_set_free(AlternativeCondSet);
1661
5
    isl_set_free(ConsequenceCondSet);
1662
5
    return false;
1663
5
  }
1664
2.89k
1665
2.89k
  ConditionSets.push_back(ConsequenceCondSet);
1666
2.89k
  ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
1667
2.89k
1668
2.89k
  return true;
1669
2.89k
}
1670
1671
/// Build the conditions sets for the terminator @p TI in the @p Domain.
1672
///
1673
/// This will fill @p ConditionSets with the conditions under which control
1674
/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1675
/// have as many elements as @p TI has successors.
1676
bool buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1677
                        __isl_keep isl_set *Domain,
1678
                        DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1679
6.00k
                        SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1680
6.00k
  if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1681
19
    return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1682
19
                              ConditionSets);
1683
5.98k
1684
5.98k
  assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1685
5.98k
1686
5.98k
  if (TI->getNumSuccessors() == 1) {
1687
3.14k
    ConditionSets.push_back(isl_set_copy(Domain));
1688
3.14k
    return true;
1689
3.14k
  }
1690
2.83k
1691
2.83k
  Value *Condition = getConditionFromTerminator(TI);
1692
2.83k
  assert(Condition && "No condition for Terminator");
1693
2.83k
1694
2.83k
  return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1695
2.83k
                            ConditionSets);
1696
2.83k
}
1697
1698
ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1699
                   Loop *SurroundingLoop,
1700
                   std::vector<Instruction *> EntryBlockInstructions)
1701
    : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
1702
      Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1703
121
      Instructions(EntryBlockInstructions) {}
1704
1705
ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1706
                   Loop *SurroundingLoop,
1707
                   std::vector<Instruction *> Instructions)
1708
    : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1709
      Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1710
9.05k
      Instructions(Instructions) {}
1711
1712
ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1713
                   isl::set NewDomain)
1714
    : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1715
24
      Build(nullptr) {
1716
24
  BaseName = getIslCompatibleName("CopyStmt_", "",
1717
24
                                  std::to_string(parent.getCopyStmtsNum()));
1718
24
  isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1719
24
  Domain = Domain.set_tuple_id(Id);
1720
24
  TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1721
24
  auto *Access =
1722
24
      new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1723
24
  parent.addAccessFunction(Access);
1724
24
  addAccess(Access);
1725
24
  SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1726
24
  Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1727
24
  parent.addAccessFunction(Access);
1728
24
  addAccess(Access);
1729
24
}
1730
1731
9.16k
ScopStmt::~ScopStmt() = default;
1732
1733
868
std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
1734
1735
868
std::string ScopStmt::getScheduleStr() const {
1736
868
  auto *S = getSchedule().release();
1737
868
  if (!S)
1738
4
    return {};
1739
864
  auto Str = stringFromIslObj(S);
1740
864
  isl_map_free(S);
1741
864
  return Str;
1742
864
}
1743
1744
9.02k
void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
1745
1746
43.2k
BasicBlock *ScopStmt::getEntryBlock() const {
1747
43.2k
  if (isBlockStmt())
1748
41.2k
    return getBasicBlock();
1749
2.07k
  return getRegion()->getEntry();
1750
2.07k
}
1751
1752
5.20k
unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
1753
1754
8.48k
const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1755
1756
648
Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
1757
648
  return NestLoops[Dimension];
1758
648
}
1759
1760
86
isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
1761
1762
66.2k
isl::set ScopStmt::getDomain() const { return Domain; }
1763
1764
5.37k
isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
1765
1766
81
isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
1767
1768
94
void ScopStmt::printInstructions(raw_ostream &OS) const {
1769
94
  OS << "Instructions {\n";
1770
94
1771
94
  for (Instruction *Inst : Instructions)
1772
177
    OS.indent(16) << *Inst << "\n";
1773
94
1774
94
  OS.indent(12) << "}\n";
1775
94
}
1776
1777
868
void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
1778
868
  OS << "\t" << getBaseName() << "\n";
1779
868
  OS.indent(12) << "Domain :=\n";
1780
868
1781
868
  if (Domain) {
1782
868
    OS.indent(16) << getDomainStr() << ";\n";
1783
868
  } else
1784
0
    OS.indent(16) << "n/a\n";
1785
868
1786
868
  OS.indent(12) << "Schedule :=\n";
1787
868
1788
868
  if (Domain) {
1789
868
    OS.indent(16) << getScheduleStr() << ";\n";
1790
868
  } else
1791
0
    OS.indent(16) << "n/a\n";
1792
868
1793
868
  for (MemoryAccess *Access : MemAccs)
1794
1.76k
    Access->print(OS);
1795
868
1796
868
  if (PrintInstructions)
1797
32
    printInstructions(OS.indent(12));
1798
868
}
1799
1800
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1801
LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
1802
#endif
1803
1804
462
void ScopStmt::removeAccessData(MemoryAccess *MA) {
1805
462
  if (MA->isRead() && 
MA->isOriginalValueKind()409
) {
1806
37
    bool Found = ValueReads.erase(MA->getAccessValue());
1807
37
    (void)Found;
1808
37
    assert(Found && "Expected access data not found");
1809
37
  }
1810
462
  if (MA->isWrite() && 
MA->isOriginalValueKind()53
) {
1811
27
    bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1812
27
    (void)Found;
1813
27
    assert(Found && "Expected access data not found");
1814
27
  }
1815
462
  if (MA->isWrite() && 
MA->isOriginalAnyPHIKind()53
) {
1816
7
    bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1817
7
    (void)Found;
1818
7
    assert(Found && "Expected access data not found");
1819
7
  }
1820
462
  if (MA->isRead() && 
MA->isOriginalAnyPHIKind()409
) {
1821
3
    bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1822
3
    (void)Found;
1823
3
    assert(Found && "Expected access data not found");
1824
3
  }
1825
462
}
1826
1827
359
void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1828
359
  // Remove the memory accesses from this statement together with all scalar
1829
359
  // accesses that were caused by it. MemoryKind::Value READs have no access
1830
359
  // instruction, hence would not be removed by this function. However, it is
1831
359
  // only used for invariant LoadInst accesses, its arguments are always affine,
1832
359
  // hence synthesizable, and therefore there are no MemoryKind::Value READ
1833
359
  // accesses to be removed.
1834
3.80k
  auto Predicate = [&](MemoryAccess *Acc) {
1835
3.80k
    return Acc->getAccessInstruction() == MA->getAccessInstruction();
1836
3.80k
  };
1837
1.90k
  for (auto *MA : MemAccs) {
1838
1.90k
    if (Predicate(MA)) {
1839
378
      removeAccessData(MA);
1840
378
      Parent.removeAccessData(MA);
1841
378
    }
1842
1.90k
  }
1843
359
  MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1844
359
                MemAccs.end());
1845
359
  InstructionToAccess.erase(MA->getAccessInstruction());
1846
359
}
1847
1848
84
void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1849
84
  auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1850
84
  assert(MAIt != MemAccs.end());
1851
84
  MemAccs.erase(MAIt);
1852
84
1853
84
  removeAccessData(MA);
1854
84
  Parent.removeAccessData(MA);
1855
84
1856
84
  auto It = InstructionToAccess.find(MA->getAccessInstruction());
1857
84
  if (It != InstructionToAccess.end()) {
1858
33
    It->second.remove(MA);
1859
33
    if (It->second.empty())
1860
29
      InstructionToAccess.erase(MA->getAccessInstruction());
1861
33
  }
1862
84
}
1863
1864
1
MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1865
1
  MemoryAccess *Access = lookupInputAccessOf(V);
1866
1
  if (Access)
1867
0
    return Access;
1868
1
1869
1
  ScopArrayInfo *SAI =
1870
1
      Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1871
1
  Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1872
1
                            true, {}, {}, V, MemoryKind::Value);
1873
1
  Parent.addAccessFunction(Access);
1874
1
  Access->buildAccessRelation(SAI);
1875
1
  addAccess(Access);
1876
1
  Parent.addAccessData(Access);
1877
1
  return Access;
1878
1
}
1879
1880
0
raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1881
0
  S.print(OS, PollyPrintInstructions);
1882
0
  return OS;
1883
0
}
1884
1885
//===----------------------------------------------------------------------===//
1886
/// Scop class implement
1887
1888
92
void Scop::setContext(isl::set NewContext) {
1889
92
  Context = NewContext.align_params(Context.get_space());
1890
92
}
1891
1892
namespace {
1893
1894
/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
1895
struct SCEVSensitiveParameterRewriter
1896
    : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
1897
  const ValueToValueMap &VMap;
1898
1899
public:
1900
  SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1901
                                 ScalarEvolution &SE)
1902
11.5k
      : SCEVRewriteVisitor(SE), VMap(VMap) {}
1903
1904
  static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1905
11.5k
                             const ValueToValueMap &VMap) {
1906
11.5k
    SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1907
11.5k
    return SSPR.visit(E);
1908
11.5k
  }
1909
1910
277
  const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1911
277
    auto *Start = visit(E->getStart());
1912
277
    auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1913
277
                                    visit(E->getStepRecurrence(SE)),
1914
277
                                    E->getLoop(), SCEV::FlagAnyWrap);
1915
277
    return SE.getAddExpr(Start, AddRec);
1916
277
  }
1917
1918
6.18k
  const SCEV *visitUnknown(const SCEVUnknown *E) {
1919
6.18k
    if (auto *NewValue = VMap.lookup(E->getValue()))
1920
53
      return SE.getUnknown(NewValue);
1921
6.13k
    return E;
1922
6.13k
  }
1923
};
1924
1925
/// Check whether we should remap a SCEV expression.
1926
struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
1927
  const ValueToValueMap &VMap;
1928
  bool FoundInside = false;
1929
  const Scop *S;
1930
1931
public:
1932
  SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1933
                     const Scop *S)
1934
17.0k
      : SCEVTraversal(*this), VMap(VMap), S(S) {}
1935
1936
  static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
1937
17.0k
                         const ValueToValueMap &VMap, const Scop *S) {
1938
17.0k
    SCEVFindInsideScop SFIS(VMap, SE, S);
1939
17.0k
    SFIS.visitAll(E);
1940
17.0k
    return SFIS.FoundInside;
1941
17.0k
  }
1942
1943
20.1k
  bool follow(const SCEV *E) {
1944
20.1k
    if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1945
4.51k
      FoundInside |= S->getRegion().contains(AddRec->getLoop());
1946
15.6k
    } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1947
7.59k
      if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1948
2.70k
        FoundInside |= S->getRegion().contains(I) && 
!VMap.count(I)1.34k
;
1949
7.59k
    }
1950
20.1k
    return !FoundInside;
1951
20.1k
  }
1952
1953
14.5k
  bool isDone() { return FoundInside; }
1954
};
1955
1956
} // end anonymous namespace
1957
1958
17.0k
const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
1959
17.0k
  // Check whether it makes sense to rewrite the SCEV.  (ScalarEvolution
1960
17.0k
  // doesn't like addition between an AddRec and an expression that
1961
17.0k
  // doesn't have a dominance relationship with it.)
1962
17.0k
  if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1963
5.50k
    return E;
1964
11.5k
1965
11.5k
  // Rewrite SCEV.
1966
11.5k
  return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
1967
11.5k
}
1968
1969
// This table of function names is used to translate parameter names in more
1970
// human-readable names. This makes it easier to interpret Polly analysis
1971
// results.
1972
StringMap<std::string> KnownNames = {
1973
    {"_Z13get_global_idj", "global_id"},
1974
    {"_Z12get_local_idj", "local_id"},
1975
    {"_Z15get_global_sizej", "global_size"},
1976
    {"_Z14get_local_sizej", "local_size"},
1977
    {"_Z12get_work_dimv", "work_dim"},
1978
    {"_Z17get_global_offsetj", "global_offset"},
1979
    {"_Z12get_group_idj", "group_id"},
1980
    {"_Z14get_num_groupsj", "num_groups"},
1981
};
1982
1983
4
static std::string getCallParamName(CallInst *Call) {
1984
4
  std::string Result;
1985
4
  raw_string_ostream OS(Result);
1986
4
  std::string Name = Call->getCalledFunction()->getName();
1987
4
1988
4
  auto Iterator = KnownNames.find(Name);
1989
4
  if (Iterator != KnownNames.end())
1990
3
    Name = "__" + Iterator->getValue();
1991
4
  OS << Name;
1992
4
  for (auto &Operand : Call->arg_operands()) {
1993
3
    ConstantInt *Op = cast<ConstantInt>(&Operand);
1994
3
    OS << "_" << Op->getValue();
1995
3
  }
1996
4
  OS.flush();
1997
4
  return Result;
1998
4
}
1999
2000
1.26k
void Scop::createParameterId(const SCEV *Parameter) {
2001
1.26k
  assert(Parameters.count(Parameter));
2002
1.26k
  assert(!ParameterIds.count(Parameter));
2003
1.26k
2004
1.26k
  std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
2005
1.26k
2006
1.26k
  if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2007
1.19k
    Value *Val = ValueParameter->getValue();
2008
1.19k
    CallInst *Call = dyn_cast<CallInst>(Val);
2009
1.19k
2010
1.19k
    if (Call && 
isConstCall(Call)6
) {
2011
4
      ParameterName = getCallParamName(Call);
2012
1.19k
    } else if (UseInstructionNames) {
2013
1.18k
      // If this parameter references a specific Value and this value has a name
2014
1.18k
      // we use this name as it is likely to be unique and more useful than just
2015
1.18k
      // a number.
2016
1.18k
      if (Val->hasName())
2017
1.13k
        ParameterName = Val->getName();
2018
50
      else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2019
50
        auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2020
50
        if (LoadOrigin->hasName()) {
2021
43
          ParameterName += "_loaded_from_";
2022
43
          ParameterName +=
2023
43
              LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2024
43
        }
2025
50
      }
2026
1.18k
    }
2027
1.19k
2028
1.19k
    ParameterName = getIslCompatibleName("", ParameterName, "");
2029
1.19k
  }
2030
1.26k
2031
1.26k
  isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
2032
1.26k
                              const_cast<void *>((const void *)Parameter));
2033
1.26k
  ParameterIds[Parameter] = Id;
2034
1.26k
}
2035
2036
12.2k
void Scop::addParams(const ParameterSetTy &NewParameters) {
2037
12.2k
  for (const SCEV *Parameter : NewParameters) {
2038
3.13k
    // Normalize the SCEV to get the representing element for an invariant load.
2039
3.13k
    Parameter = extractConstantFactor(Parameter, *SE).second;
2040
3.13k
    Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2041
3.13k
2042
3.13k
    if (Parameters.insert(Parameter))
2043
1.26k
      createParameterId(Parameter);
2044
3.13k
  }
2045
12.2k
}
2046
2047
13.8k
isl::id Scop::getIdForParam(const SCEV *Parameter) const {
2048
13.8k
  // Normalize the SCEV to get the representing element for an invariant load.
2049
13.8k
  Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2050
13.8k
  return ParameterIds.lookup(Parameter);
2051
13.8k
}
2052
2053
3.84k
isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
2054
3.84k
  isl_set *DomainContext = isl_union_set_params(getDomains().release());
2055
3.84k
  return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
2056
3.84k
}
2057
2058
12
bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2059
12
  return DT.dominates(BB, getEntry());
2060
12
}
2061
2062
void Scop::addUserAssumptions(
2063
    AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
2064
1.17k
    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2065
1.17k
  for (auto &Assumption : AC.assumptions()) {
2066
20
    auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2067
20
    if (!CI || CI->getNumArgOperands() != 1)
2068
0
      continue;
2069
20
2070
20
    bool InScop = contains(CI);
2071
20
    if (!InScop && 
!isDominatedBy(DT, CI->getParent())12
)
2072
0
      continue;
2073
20
2074
20
    auto *L = LI.getLoopFor(CI->getParent());
2075
20
    auto *Val = CI->getArgOperand(0);
2076
20
    ParameterSetTy DetectedParams;
2077
20
    if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2078
0
      ORE.emit(
2079
0
          OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2080
0
          << "Non-affine user assumption ignored.");
2081
0
      continue;
2082
0
    }
2083
20
2084
20
    // Collect all newly introduced parameters.
2085
20
    ParameterSetTy NewParams;
2086
22
    for (auto *Param : DetectedParams) {
2087
22
      Param = extractConstantFactor(Param, *SE).second;
2088
22
      Param = getRepresentingInvariantLoadSCEV(Param);
2089
22
      if (Parameters.count(Param))
2090
18
        continue;
2091
4
      NewParams.insert(Param);
2092
4
    }
2093
20
2094
20
    SmallVector<isl_set *, 2> ConditionSets;
2095
20
    auto *TI = InScop ? 
CI->getParent()->getTerminator()8
:
nullptr12
;
2096
20
    BasicBlock *BB = InScop ? 
CI->getParent()8
:
getRegion().getEntry()12
;
2097
20
    auto *Dom = InScop ? 
DomainMap[BB].copy()8
:
Context.copy()12
;
2098
20
    assert(Dom && "Cannot propagate a nullptr.");
2099
20
    bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2100
20
                                    InvalidDomainMap, ConditionSets);
2101
20
    isl_set_free(Dom);
2102
20
2103
20
    if (!Valid)
2104
0
      continue;
2105
20
2106
20
    isl_set *AssumptionCtx = nullptr;
2107
20
    if (InScop) {
2108
8
      AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2109
8
      isl_set_free(ConditionSets[0]);
2110
12
    } else {
2111
12
      AssumptionCtx = isl_set_complement(ConditionSets[1]);
2112
12
      AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2113
12
    }
2114
20
2115
20
    // Project out newly introduced parameters as they are not otherwise useful.
2116
20
    if (!NewParams.empty()) {
2117
10
      for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); 
u++6
) {
2118
6
        auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2119
6
        auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2120
6
        isl_id_free(Id);
2121
6
2122
6
        if (!NewParams.count(Param))
2123
2
          continue;
2124
4
2125
4
        AssumptionCtx =
2126
4
            isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2127
4
      }
2128
4
    }
2129
20
    ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2130
20
             << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
2131
20
    Context = Context.intersect(isl::manage(AssumptionCtx));
2132
20
  }
2133
1.17k
}
2134
2135
1.14k
void Scop::addUserContext() {
2136
1.14k
  if (UserContextStr.empty())
2137
1.14k
    return;
2138
3
2139
3
  isl_set *UserContext =
2140
3
      isl_set_read_from_str(getIslCtx().get(), UserContextStr.c_str());
2141
3
  isl_space *Space = getParamSpace().release();
2142
3
  if (isl_space_dim(Space, isl_dim_param) !=
2143
3
      isl_set_dim(UserContext, isl_dim_param)) {
2144
2
    auto SpaceStr = isl_space_to_str(Space);
2145
2
    errs() << "Error: the context provided in -polly-context has not the same "
2146
2
           << "number of dimensions than the computed context. Due to this "
2147
2
           << "mismatch, the -polly-context option is ignored. Please provide "
2148
2
           << "the context in the parameter space: " << SpaceStr << ".\n";
2149
2
    free(SpaceStr);
2150
2
    isl_set_free(UserContext);
2151
2
    isl_space_free(Space);
2152
2
    return;
2153
2
  }
2154
1
2155
2
  
for (unsigned i = 0; 1
i < isl_space_dim(Space, isl_dim_param);
i++1
) {
2156
1
    std::string NameContext = Context.get_dim_name(isl::dim::param, i);
2157
1
    std::string NameUserContext =
2158
1
        isl_set_get_dim_name(UserContext, isl_dim_param, i);
2159
1
2160
1
    if (NameContext != NameUserContext) {
2161
0
      auto SpaceStr = isl_space_to_str(Space);
2162
0
      errs() << "Error: the name of dimension " << i
2163
0
             << " provided in -polly-context "
2164
0
             << "is '" << NameUserContext << "', but the name in the computed "
2165
0
             << "context is '" << NameContext
2166
0
             << "'. Due to this name mismatch, "
2167
0
             << "the -polly-context option is ignored. Please provide "
2168
0
             << "the context in the parameter space: " << SpaceStr << ".\n";
2169
0
      free(SpaceStr);
2170
0
      isl_set_free(UserContext);
2171
0
      isl_space_free(Space);
2172
0
      return;
2173
0
    }
2174
1
2175
1
    UserContext =
2176
1
        isl_set_set_dim_id(UserContext, isl_dim_param, i,
2177
1
                           isl_space_get_dim_id(Space, isl_dim_param, i));
2178
1
  }
2179
1
2180
1
  Context = Context.intersect(isl::manage(UserContext));
2181
1
  isl_space_free(Space);
2182
1
}
2183
2184
1.18k
void Scop::buildInvariantEquivalenceClasses() {
2185
1.18k
  DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
2186
1.18k
2187
1.18k
  const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
2188
1.18k
  for (LoadInst *LInst : RIL) {
2189
284
    const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2190
284
2191
284
    Type *Ty = LInst->getType();
2192
284
    LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
2193
284
    if (ClassRep) {
2194
36
      InvEquivClassVMap[LInst] = ClassRep;
2195
36
      continue;
2196
36
    }
2197
248
2198
248
    ClassRep = LInst;
2199
248
    InvariantEquivClasses.emplace_back(
2200
248
        InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
2201
248
  }
2202
1.18k
}
2203
2204
1.18k
void Scop::buildContext() {
2205
1.18k
  isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
2206
1.18k
  Context = isl::set::universe(Space);
2207
1.18k
  InvalidContext = isl::set::empty(Space);
2208
1.18k
  AssumedContext = isl::set::universe(Space);
2209
1.18k
}
2210
2211
1.14k
void Scop::addParameterBounds() {
2212
1.14k
  unsigned PDim = 0;
2213
1.20k
  for (auto *Parameter : Parameters) {
2214
1.20k
    ConstantRange SRange = SE->getSignedRange(Parameter);
2215
1.20k
    Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
2216
1.20k
  }
2217
1.14k
}
2218
2219
2.29k
static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2220
2.29k
  std::vector<isl::id> OutermostSizeIds;
2221
4.85k
  for (auto Array : Arrays) {
2222
4.85k
    // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2223
4.85k
    // for its outermost dimension. Fortran arrays will have this since the
2224
4.85k
    // outermost dimension size can be picked up from their runtime description.
2225
4.85k
    // TODO: actually need to check if it has a FAD, but for now this works.
2226
4.85k
    if (Array->getNumberOfDimensions() > 0) {
2227
3.60k
      isl::pw_aff PwAff = Array->getDimensionSizePw(0);
2228
3.60k
      if (!PwAff)
2229
3.59k
        continue;
2230
14
2231
14
      isl::id Id =
2232
14
          isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2233
14
      assert(!Id.is_null() &&
2234
14
             "Invalid Id for PwAff expression in Fortran array");
2235
14
      Id.dump();
2236
14
      OutermostSizeIds.push_back(Id);
2237
14
    }
2238
4.85k
  }
2239
2.29k
  return OutermostSizeIds;
2240
2.29k
}
2241
2242
// The FORTRAN array size parameters are known to be non-negative.
2243
static isl::set boundFortranArrayParams(isl::set Context,
2244
1.14k
                                        Scop::array_range Arrays) {
2245
1.14k
  std::vector<isl::id> OutermostSizeIds;
2246
1.14k
  OutermostSizeIds = getFortranArrayIds(Arrays);
2247
1.14k
2248
1.14k
  for (isl::id Id : OutermostSizeIds) {
2249
7
    int dim = Context.find_dim_by_id(isl::dim::param, Id);
2250
7
    Context = Context.lower_bound_si(isl::dim::param, dim, 0);
2251
7
  }
2252
1.14k
2253
1.14k
  return Context;
2254
1.14k
}
2255
2256
1.14k
void Scop::realignParams() {
2257
1.14k
  if (PollyIgnoreParamBounds)
2258
1
    return;
2259
1.14k
2260
1.14k
  // Add all parameters into a common model.
2261
1.14k
  isl::space Space = getFullParamSpace();
2262
1.14k
2263
1.14k
  // Align the parameters of all data structures to the model.
2264
1.14k
  Context = Context.align_params(Space);
2265
1.14k
2266
1.14k
  // Bound the size of the fortran array dimensions.
2267
1.14k
  Context = boundFortranArrayParams(Context, arrays());
2268
1.14k
2269
1.14k
  // As all parameters are known add bounds to them.
2270
1.14k
  addParameterBounds();
2271
1.14k
2272
1.14k
  for (ScopStmt &Stmt : *this)
2273
2.26k
    Stmt.realignParams();
2274
1.14k
  // Simplify the schedule according to the context too.
2275
1.14k
  Schedule = Schedule.gist_domain_params(getContext());
2276
1.14k
}
2277
2278
static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
2279
1.14k
                                          const Scop &S) {
2280
1.14k
  // If we have modeled all blocks in the SCoP that have side effects we can
2281
1.14k
  // simplify the context with the constraints that are needed for anything to
2282
1.14k
  // be executed at all. However, if we have error blocks in the SCoP we already
2283
1.14k
  // assumed some parameter combinations cannot occur and removed them from the
2284
1.14k
  // domains, thus we cannot use the remaining domain to simplify the
2285
1.14k
  // assumptions.
2286
1.14k
  if (!S.hasErrorBlock()) {
2287
1.12k
    auto DomainParameters = S.getDomains().params();
2288
1.12k
    AssumptionContext = AssumptionContext.gist_params(DomainParameters);
2289
1.12k
  }
2290
1.14k
2291
1.14k
  AssumptionContext = AssumptionContext.gist_params(S.getContext());
2292
1.14k
  return AssumptionContext;
2293
1.14k
}
2294
2295
1.14k
void Scop::simplifyContexts() {
2296
1.14k
  // The parameter constraints of the iteration domains give us a set of
2297
1.14k
  // constraints that need to hold for all cases where at least a single
2298
1.14k
  // statement iteration is executed in the whole scop. We now simplify the
2299
1.14k
  // assumed context under the assumption that such constraints hold and at
2300
1.14k
  // least a single statement iteration is executed. For cases where no
2301
1.14k
  // statement instances are executed, the assumptions we have taken about
2302
1.14k
  // the executed code do not matter and can be changed.
2303
1.14k
  //
2304
1.14k
  // WARNING: This only holds if the assumptions we have taken do not reduce
2305
1.14k
  //          the set of statement instances that are executed. Otherwise we
2306
1.14k
  //          may run into a case where the iteration domains suggest that
2307
1.14k
  //          for a certain set of parameter constraints no code is executed,
2308
1.14k
  //          but in the original program some computation would have been
2309
1.14k
  //          performed. In such a case, modifying the run-time conditions and
2310
1.14k
  //          possibly influencing the run-time check may cause certain scops
2311
1.14k
  //          to not be executed.
2312
1.14k
  //
2313
1.14k
  // Example:
2314
1.14k
  //
2315
1.14k
  //   When delinearizing the following code:
2316
1.14k
  //
2317
1.14k
  //     for (long i = 0; i < 100; i++)
2318
1.14k
  //       for (long j = 0; j < m; j++)
2319
1.14k
  //         A[i+p][j] = 1.0;
2320
1.14k
  //
2321
1.14k
  //   we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
2322
1.14k
  //   otherwise we would access out of bound data. Now, knowing that code is
2323
1.14k
  //   only executed for the case m >= 0, it is sufficient to assume p >= 0.
2324
1.14k
  AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
2325
1.14k
  InvalidContext = InvalidContext.align_params(getParamSpace());
2326
1.14k
}
2327
2328
/// Add the minimal/maximal access in @p Set to @p User.
2329
static isl::stat
2330
536
buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2331
536
  isl::pw_multi_aff MinPMA, MaxPMA;
2332
536
  isl::pw_aff LastDimAff;
2333
536
  isl::aff OneAff;
2334
536
  unsigned Pos;
2335
536
  isl::ctx Ctx = Set.get_ctx();
2336
536
2337
536
  Set = Set.remove_divs();
2338
536
2339
536
  if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2340
0
    return isl::stat::error;
2341
536
2342
536
  // Restrict the number of parameters involved in the access as the lexmin/
2343
536
  // lexmax computation will take too long if this number is high.
2344
536
  //
2345
536
  // Experiments with a simple test case using an i7 4800MQ:
2346
536
  //
2347
536
  //  #Parameters involved | Time (in sec)
2348
536
  //            6          |     0.01
2349
536
  //            7          |     0.04
2350
536
  //            8          |     0.12
2351
536
  //            9          |     0.40
2352
536
  //           10          |     1.54
2353
536
  //           11          |     6.78
2354
536
  //           12          |    30.38
2355
536
  //
2356
536
  if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
2357
7
    unsigned InvolvedParams = 0;
2358
81
    for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; 
u++74
)
2359
74
      if (Set.involves_dims(isl::dim::param, u, 1))
2360
35
        InvolvedParams++;
2361
7
2362
7
    if (InvolvedParams > RunTimeChecksMaxParameters)
2363
2
      return isl::stat::error;
2364
534
  }
2365
534
2366
534
  if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2367
2
    return isl::stat::error;
2368
532
2369
532
  MinPMA = Set.lexmin_pw_multi_aff();
2370
532
  MaxPMA = Set.lexmax_pw_multi_aff();
2371
532
2372
532
  if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
2373
0
    return isl::stat::error;
2374
532
2375
532
  MinPMA = MinPMA.coalesce();
2376
532
  MaxPMA = MaxPMA.coalesce();
2377
532
2378
532
  // Adjust the last dimension of the maximal access by one as we want to
2379
532
  // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2380
532
  // we test during code generation might now point after the end of the
2381
532
  // allocated array but we will never dereference it anyway.
2382
532
  assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2383
532
  Pos = MaxPMA.dim(isl::dim::out) - 1;
2384
532
  LastDimAff = MaxPMA.get_pw_aff(Pos);
2385
532
  OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2386
532
  OneAff = OneAff.add_constant_si(1);
2387
532
  LastDimAff = LastDimAff.add(OneAff);
2388
532
  MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
2389
532
2390
532
  MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
2391
532
2392
532
  return isl::stat::ok;
2393
532
}
2394
2395
1.73k
static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2396
1.73k
  isl_set *Domain = MA->getStatement()->getDomain().release();
2397
1.73k
  Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2398
1.73k
  return isl_set_reset_tuple_id(Domain);
2399
1.73k
}
2400
2401
/// Wrapper function to calculate minimal/maximal accesses to each array.
2402
static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
2403
417
                                  Scop::MinMaxVectorTy &MinMaxAccesses) {
2404
417
  MinMaxAccesses.reserve(AliasGroup.size());
2405
417
2406
417
  isl::union_set Domains = S.getDomains();
2407
417
  isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
2408
417
2409
417
  for (MemoryAccess *MA : AliasGroup)
2410
823
    Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
2411
417
2412
417
  Accesses = Accesses.intersect_domain(Domains);
2413
417
  isl::union_set Locations = Accesses.range();
2414
417
  Locations = Locations.coalesce();
2415
417
  Locations = Locations.detect_equalities();
2416
417
2417
536
  auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2418
536
    return buildMinMaxAccess(Set, MinMaxAccesses, S);
2419
536
  };
2420
417
  return Locations.foreach_set(Lambda) == isl::stat::ok;
2421
417
}
2422
2423
/// Helper to treat non-affine regions and basic blocks the same.
2424
///
2425
///{
2426
2427
/// Return the block that is the representing block for @p RN.
2428
16.9k
static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2429
16.9k
  return RN->isSubRegion() ? 
RN->getNodeAs<Region>()->getEntry()300
2430
16.9k
                           : 
RN->getNodeAs<BasicBlock>()16.6k
;
2431
16.9k
}
2432
2433
/// Return the @p idx'th block that is executed after @p RN.
2434
static inline BasicBlock *
2435
8.71k
getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
2436
8.71k
  if (RN->isSubRegion()) {
2437
109
    assert(idx == 0);
2438
109
    return RN->getNodeAs<Region>()->getExit();
2439
109
  }
2440
8.60k
  return TI->getSuccessor(idx);
2441
8.60k
}
2442
2443
/// Return the smallest loop surrounding @p RN.
2444
18.9k
static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2445
18.9k
  if (!RN->isSubRegion()) {
2446
17.3k
    BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2447
17.3k
    Loop *L = LI.getLoopFor(BB);
2448
17.3k
2449
17.3k
    // Unreachable statements are not considered to belong to a LLVM loop, as
2450
17.3k
    // they are not part of an actual loop in the control flow graph.
2451
17.3k
    // Nevertheless, we handle certain unreachable statements that are common
2452
17.3k
    // when modeling run-time bounds checks as being part of the loop to be
2453
17.3k
    // able to model them and to later eliminate the run-time bounds checks.
2454
17.3k
    //
2455
17.3k
    // Specifically, for basic blocks that terminate in an unreachable and
2456
17.3k
    // where the immediate predecessor is part of a loop, we assume these
2457
17.3k
    // basic blocks belong to the loop the predecessor belongs to. This
2458
17.3k
    // allows us to model the following code.
2459
17.3k
    //
2460
17.3k
    // for (i = 0; i < N; i++) {
2461
17.3k
    //   if (i > 1024)
2462
17.3k
    //     abort();            <- this abort might be translated to an
2463
17.3k
    //                            unreachable
2464
17.3k
    //
2465
17.3k
    //   A[i] = ...
2466
17.3k
    // }
2467
17.3k
    if (!L && 
isa<UnreachableInst>(BB->getTerminator())2.44k
&&
BB->getPrevNode()0
)
2468
0
      L = LI.getLoopFor(BB->getPrevNode());
2469
17.3k
    return L;
2470
17.3k
  }
2471
1.51k
2472
1.51k
  Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2473
1.51k
  Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2474
2.48k
  while (L && 
NonAffineSubRegion->contains(L)1.83k
)
2475
971
    L = L->getParentLoop();
2476
1.51k
  return L;
2477
1.51k
}
2478
2479
/// Get the number of blocks in @p L.
2480
///
2481
/// The number of blocks in a loop are the number of basic blocks actually
2482
/// belonging to the loop, as well as all single basic blocks that the loop
2483
/// exits to and which terminate in an unreachable instruction. We do not
2484
/// allow such basic blocks in the exit of a scop, hence they belong to the
2485
/// scop and represent run-time conditions which we want to model and
2486
/// subsequently speculate away.
2487
///
2488
/// @see getRegionNodeLoop for additional details.
2489
5.23k
unsigned getNumBlocksInLoop(Loop *L) {
2490
5.23k
  unsigned NumBlocks = L->getNumBlocks();
2491
5.23k
  SmallVector<BasicBlock *, 4> ExitBlocks;
2492
5.23k
  L->getExitBlocks(ExitBlocks);
2493
5.23k
2494
5.31k
  for (auto ExitBlock : ExitBlocks) {
2495
5.31k
    if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2496
60
      NumBlocks++;
2497
5.31k
  }
2498
5.23k
  return NumBlocks;
2499
5.23k
}
2500
2501
5.53k
static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2502
5.53k
  if (!RN->isSubRegion())
2503
5.42k
    return 1;
2504
106
2505
106
  Region *R = RN->getNodeAs<Region>();
2506
106
  return std::distance(R->block_begin(), R->block_end());
2507
106
}
2508
2509
static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2510
11.3k
                               const DominatorTree &DT) {
2511
11.3k
  if (!RN->isSubRegion())
2512
11.0k
    return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
2513
217
  for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
2514
596
    if (isErrorBlock(*BB, R, LI, DT))
2515
18
      return true;
2516
217
  
return false199
;
2517
217
}
2518
2519
///}
2520
2521
static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2522
2.40k
                                                 unsigned Dim, Loop *L) {
2523
2.40k
  Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
2524
2.40k
  isl_id *DimId =
2525
2.40k
      isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2526
2.40k
  return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2527
2.40k
}
2528
2529
2.28k
isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
2530
2.28k
  return getDomainConditions(Stmt->getEntryBlock());
2531
2.28k
}
2532
2533
19.3k
isl::set Scop::getDomainConditions(BasicBlock *BB) const {
2534
19.3k
  auto DIt = DomainMap.find(BB);
2535
19.3k
  if (DIt != DomainMap.end())
2536
19.3k
    return DIt->getSecond();
2537
16
2538
16
  auto &RI = *R.getRegionInfo();
2539
16
  auto *BBR = RI.getRegionFor(BB);
2540
32
  while (BBR->getEntry() == BB)
2541
16
    BBR = BBR->getParent();
2542
16
  return getDomainConditions(BBR->getEntry());
2543
16
}
2544
2545
bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2546
1.18k
                        DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2547
1.18k
  bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
2548
1.18k
  auto *EntryBB = R->getEntry();
2549
1.18k
  auto *L = IsOnlyNonAffineRegion ? 
nullptr17
:
LI.getLoopFor(EntryBB)1.16k
;
2550
1.18k
  int LD = getRelativeLoopDepth(L);
2551
1.18k
  auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx().get(), 0, LD + 1));
2552
1.18k
2553
2.19k
  while (LD-- >= 0) {
2554
1.00k
    S = addDomainDimId(S, LD + 1, L);
2555
1.00k
    L = L->getParentLoop();
2556
1.00k
  }
2557
1.18k
2558
1.18k
  InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
2559
1.18k
  DomainMap[EntryBB] = isl::manage(S);
2560
1.18k
2561
1.18k
  if (IsOnlyNonAffineRegion)
2562
17
    return !containsErrorBlock(R->getNode(), *R, LI, DT);
2563
1.16k
2564
1.16k
  if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
2565
5
    return false;
2566
1.16k
2567
1.16k
  if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
2568
0
    return false;
2569
1.16k
2570
1.16k
  // Error blocks and blocks dominated by them have been assumed to never be
2571
1.16k
  // executed. Representing them in the Scop does not add any value. In fact,
2572
1.16k
  // it is likely to cause issues during construction of the ScopStmts. The
2573
1.16k
  // contents of error blocks have not been verified to be expressible and
2574
1.16k
  // will cause problems when building up a ScopStmt for them.
2575
1.16k
  // Furthermore, basic blocks dominated by error blocks may reference
2576
1.16k
  // instructions in the error block which, if the error block is not modeled,
2577
1.16k
  // can themselves not be constructed properly. To this end we will replace
2578
1.16k
  // the domains of error blocks and those only reachable via error blocks
2579
1.16k
  // with an empty set. Additionally, we will record for each block under which
2580
1.16k
  // parameter combination it would be reached via an error block in its
2581
1.16k
  // InvalidDomain. This information is needed during load hoisting.
2582
1.16k
  if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
2583
0
    return false;
2584
1.16k
2585
1.16k
  return true;
2586
1.16k
}
2587
2588
/// Adjust the dimensions of @p Dom that was constructed for @p OldL
2589
///        to be compatible to domains constructed for loop @p NewL.
2590
///
2591
/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2592
/// edge from @p OldL to @p NewL.
2593
static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2594
                                                  __isl_take isl_set *Dom,
2595
9.80k
                                                  Loop *OldL, Loop *NewL) {
2596
9.80k
  // If the loops are the same there is nothing to do.
2597
9.80k
  if (NewL == OldL)
2598
6.54k
    return Dom;
2599
3.25k
2600
3.25k
  int OldDepth = S.getRelativeLoopDepth(OldL);
2601
3.25k
  int NewDepth = S.getRelativeLoopDepth(NewL);
2602
3.25k
  // If both loops are non-affine loops there is nothing to do.
2603
3.25k
  if (OldDepth == -1 && 
NewDepth == -1467
)
2604
0
    return Dom;
2605
3.25k
2606
3.25k
  // Distinguish three cases:
2607
3.25k
  //   1) The depth is the same but the loops are not.
2608
3.25k
  //      => One loop was left one was entered.
2609
3.25k
  //   2) The depth increased from OldL to NewL.
2610
3.25k
  //      => One loop was entered, none was left.
2611
3.25k
  //   3) The depth decreased from OldL to NewL.
2612
3.25k
  //      => Loops were left were difference of the depths defines how many.
2613
3.25k
  if (OldDepth == NewDepth) {
2614
12
    assert(OldL->getParentLoop() == NewL->getParentLoop());
2615
12
    Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2616
12
    Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2617
12
    Dom = addDomainDimId(Dom, NewDepth, NewL);
2618
3.24k
  } else if (OldDepth < NewDepth) {
2619
1.39k
    assert(OldDepth + 1 == NewDepth);
2620
1.39k
    auto &R = S.getRegion();
2621
1.39k
    (void)R;
2622
1.39k
    assert(NewL->getParentLoop() == OldL ||
2623
1.39k
           ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2624
1.39k
    Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2625
1.39k
    Dom = addDomainDimId(Dom, NewDepth, NewL);
2626
1.85k
  } else {
2627
1.85k
    assert(OldDepth > NewDepth);
2628
1.85k
    int Diff = OldDepth - NewDepth;
2629
1.85k
    int NumDim = isl_set_n_dim(Dom);
2630
1.85k
    assert(NumDim >= Diff);
2631
1.85k
    Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2632
1.85k
  }
2633
3.25k
2634
3.25k
  return Dom;
2635
3.25k
}
2636
2637
bool Scop::propagateInvalidStmtDomains(
2638
    Region *R, DominatorTree &DT, LoopInfo &LI,
2639
2.39k
    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2640
2.39k
  ReversePostOrderTraversal<Region *> RTraversal(R);
2641
6.86k
  for (auto *RN : RTraversal) {
2642
6.86k
2643
6.86k
    // Recurse for affine subregions but go on for basic blocks and non-affine
2644
6.86k
    // subregions.
2645
6.86k
    if (RN->isSubRegion()) {
2646
1.33k
      Region *SubRegion = RN->getNodeAs<Region>();
2647
1.33k
      if (!isNonAffineSubRegion(SubRegion)) {
2648
1.23k
        propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
2649
1.23k
        continue;
2650
1.23k
      }
2651
5.63k
    }
2652
5.63k
2653
5.63k
    bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2654
5.63k
    BasicBlock *BB = getRegionNodeBasicBlock(RN);
2655
5.63k
    isl::set &Domain = DomainMap[BB];
2656
5.63k
    assert(Domain && "Cannot propagate a nullptr");
2657
5.63k
2658
5.63k
    isl::set InvalidDomain = InvalidDomainMap[BB];
2659
5.63k
2660
5.63k
    bool IsInvalidBlock = ContainsErrorBlock || 
Domain.is_subset(InvalidDomain)5.59k
;
2661
5.63k
2662
5.63k
    if (!IsInvalidBlock) {
2663
5.46k
      InvalidDomain = InvalidDomain.intersect(Domain);
2664
5.46k
    } else {
2665
162
      InvalidDomain = Domain;
2666
162
      isl::set DomPar = Domain.params();
2667
162
      recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2668
162
                       AS_RESTRICTION);
2669
162
      Domain = nullptr;
2670
162
    }
2671
5.63k
2672
5.63k
    if (InvalidDomain.is_empty()) {
2673
4.77k
      InvalidDomainMap[BB] = InvalidDomain;
2674
4.77k
      continue;
2675
4.77k
    }
2676
852
2677
852
    auto *BBLoop = getRegionNodeLoop(RN, LI);
2678
852
    auto *TI = BB->getTerminator();
2679
852
    unsigned NumSuccs = RN->isSubRegion() ? 
19
:
TI->getNumSuccessors()843
;
2680
2.05k
    for (unsigned u = 0; u < NumSuccs; 
u++1.20k
) {
2681
1.20k
      auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2682
1.20k
2683
1.20k
      // Skip successors outside the SCoP.
2684
1.20k
      if (!contains(SuccBB))
2685
212
        continue;
2686
990
2687
990
      // Skip backedges.
2688
990
      if (DT.dominates(SuccBB, BB))
2689
267
        continue;
2690
723
2691
723
      Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2692
723
2693
723
      auto *AdjustedInvalidDomain = adjustDomainDimensions(
2694
723
          *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
2695
723
2696
723
      auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
2697
723
      SuccInvalidDomain =
2698
723
          isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2699
723
      SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2700
723
      unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2701
723
2702
723
      InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
2703
723
2704
723
      // Check if the maximal number of domain disjunctions was reached.
2705
723
      // In case this happens we will bail.
2706
723
      if (NumConjucts < MaxDisjunctsInDomain)
2707
723
        continue;
2708
0
2709
0
      InvalidDomainMap.erase(BB);
2710
0
      invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
2711
0
      return false;
2712
0
    }
2713
852
2714
852
    InvalidDomainMap[BB] = InvalidDomain;
2715
852
  }
2716
2.39k
2717
2.39k
  return true;
2718
2.39k
}
2719
2720
void Scop::propagateDomainConstraintsToRegionExit(
2721
    BasicBlock *BB, Loop *BBLoop,
2722
    SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
2723
5.66k
    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2724
5.66k
  // Check if the block @p BB is the entry of a region. If so we propagate it's
2725
5.66k
  // domain to the exit block of the region. Otherwise we are done.
2726
5.66k
  auto *RI = R.getRegionInfo();
2727
5.66k
  auto *BBReg = RI ? RI->getRegionFor(BB) : 
nullptr0
;
2728
5.66k
  auto *ExitBB = BBReg ? BBReg->getExit() : 
nullptr0
;
2729
5.66k
  if (!BBReg || BBReg->getEntry() != BB || 
!contains(ExitBB)2.11k
)
2730
4.52k
    return;
2731
1.14k
2732
1.14k
  // Do not propagate the domain if there is a loop backedge inside the region
2733
1.14k
  // that would prevent the exit block from being executed.
2734
1.14k
  auto *L = BBLoop;
2735
1.83k
  while (L && 
contains(L)1.26k
) {
2736
1.23k
    SmallVector<BasicBlock *, 4> LatchBBs;
2737
1.23k
    BBLoop->getLoopLatches(LatchBBs);
2738
1.23k
    for (auto *LatchBB : LatchBBs)
2739
1.23k
      if (BB != LatchBB && 
BBReg->contains(LatchBB)816
)
2740
548
        return;
2741
1.23k
    L = L->getParentLoop();
2742
691
  }
2743
1.14k
2744
1.14k
  isl::set Domain = DomainMap[BB];
2745
594
  assert(Domain && "Cannot propagate a nullptr");
2746
594
2747
594
  Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
2748
594
2749
594
  // Since the dimensions of @p BB and @p ExitBB might be different we have to
2750
594
  // adjust the domain before we can propagate it.
2751
594
  isl::set AdjustedDomain = isl::manage(
2752
594
      adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2753
594
  isl::set &ExitDomain = DomainMap[ExitBB];
2754
594
2755
594
  // If the exit domain is not yet created we set it otherwise we "add" the
2756
594
  // current domain.
2757
594
  ExitDomain = ExitDomain ? 
AdjustedDomain.unite(ExitDomain)30
:
AdjustedDomain564
;
2758
594
2759
594
  // Initialize the invalid domain.
2760
594
  InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
2761
594
2762
594
  FinishedExitBlocks.insert(ExitBB);
2763
594
}
2764
2765
bool Scop::buildDomainsWithBranchConstraints(
2766
    Region *R, DominatorTree &DT, LoopInfo &LI,
2767
2.41k
    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2768
2.41k
  // To create the domain for each block in R we iterate over all blocks and
2769
2.41k
  // subregions in R and propagate the conditions under which the current region
2770
2.41k
  // element is executed. To this end we iterate in reverse post order over R as
2771
2.41k
  // it ensures that we first visit all predecessors of a region node (either a
2772
2.41k
  // basic block or a subregion) before we visit the region node itself.
2773
2.41k
  // Initially, only the domain for the SCoP region entry block is set and from
2774
2.41k
  // there we propagate the current domain to all successors, however we add the
2775
2.41k
  // condition that the successor is actually executed next.
2776
2.41k
  // As we are only interested in non-loop carried constraints here we can
2777
2.41k
  // simply skip loop back edges.
2778
2.41k
2779
2.41k
  SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
2780
2.41k
  ReversePostOrderTraversal<Region *> RTraversal(R);
2781
6.91k
  for (auto *RN : RTraversal) {
2782
6.91k
    // Recurse for affine subregions but go on for basic blocks and non-affine
2783
6.91k
    // subregions.
2784
6.91k
    if (RN->isSubRegion()) {
2785
1.34k
      Region *SubRegion = RN->getNodeAs<Region>();
2786
1.34k
      if (!isNonAffineSubRegion(SubRegion)) {
2787
1.24k
        if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2788
1.24k
                                               InvalidDomainMap))
2789
5
          return false;
2790
1.24k
        continue;
2791
1.24k
      }
2792
1.34k
    }
2793
5.66k
2794
5.66k
    if (containsErrorBlock(RN, getRegion(), LI, DT))
2795
40
      HasErrorBlock = true;
2796
5.66k
2797
5.66k
    BasicBlock *BB = getRegionNodeBasicBlock(RN);
2798
5.66k
    TerminatorInst *TI = BB->getTerminator();
2799
5.66k
2800
5.66k
    if (isa<UnreachableInst>(TI))
2801
0
      continue;
2802
5.66k
2803
5.66k
    isl::set Domain = DomainMap.lookup(BB);
2804
5.66k
    if (!Domain)
2805
0
      continue;
2806
5.66k
    MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
2807
5.66k
2808
5.66k
    auto *BBLoop = getRegionNodeLoop(RN, LI);
2809
5.66k
    // Propagate the domain from BB directly to blocks that have a superset
2810
5.66k
    // domain, at the moment only region exit nodes of regions that start in BB.
2811
5.66k
    propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2812
5.66k
                                           InvalidDomainMap);
2813
5.66k
2814
5.66k
    // If all successors of BB have been set a domain through the propagation
2815
5.66k
    // above we do not need to build condition sets but can just skip this
2816
5.66k
    // block. However, it is important to note that this is a local property
2817
5.66k
    // with regards to the region @p R. To this end FinishedExitBlocks is a
2818
5.66k
    // local variable.
2819
5.83k
    auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2820
5.83k
      return FinishedExitBlocks.count(SuccBB);
2821
5.83k
    };
2822
5.66k
    if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2823
300
      continue;
2824
5.36k
2825
5.36k
    // Build the condition sets for the successor nodes of the current region
2826
5.36k
    // node. If it is a non-affine subregion we will always execute the single
2827
5.36k
    // exit node, hence the single entry node domain is the condition set. For
2828
5.36k
    // basic blocks we use the helper function buildConditionSets.
2829
5.36k
    SmallVector<isl_set *, 8> ConditionSets;
2830
5.36k
    if (RN->isSubRegion())
2831
100
      ConditionSets.push_back(Domain.copy());
2832
5.26k
    else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
2833
5.26k
                                 InvalidDomainMap, ConditionSets))
2834
5
      return false;
2835
5.35k
2836
5.35k
    // Now iterate over the successors and set their initial domain based on
2837
5.35k
    // their condition set. We skip back edges here and have to be careful when
2838
5.35k
    // we leave a loop not to keep constraints over a dimension that doesn't
2839
5.35k
    // exist anymore.
2840
5.35k
    assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
2841
12.8k
    for (unsigned u = 0, e = ConditionSets.size(); u < e; 
u++7.50k
) {
2842
7.50k
      isl::set CondSet = isl::manage(ConditionSets[u]);
2843
7.50k
      BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2844
7.50k
2845
7.50k
      // Skip blocks outside the region.
2846
7.50k
      if (!contains(SuccBB))
2847
1.34k
        continue;
2848
6.16k
2849
6.16k
      // If we propagate the domain of some block to "SuccBB" we do not have to
2850
6.16k
      // adjust the domain.
2851
6.16k
      if (FinishedExitBlocks.count(SuccBB))
2852
526
        continue;
2853
5.64k
2854
5.64k
      // Skip back edges.
2855
5.64k
      if (DT.dominates(SuccBB, BB))
2856
1.67k
        continue;
2857
3.96k
2858
3.96k
      Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2859
3.96k
2860
3.96k
      CondSet = isl::manage(
2861
3.96k
          adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
2862
3.96k
2863
3.96k
      // Set the domain for the successor or merge it with an existing domain in
2864
3.96k
      // case there are multiple paths (without loop back edges) to the
2865
3.96k
      // successor block.
2866
3.96k
      isl::set &SuccDomain = DomainMap[SuccBB];
2867
3.96k
2868
3.96k
      if (SuccDomain) {
2869
27
        SuccDomain = SuccDomain.unite(CondSet).coalesce();
2870
3.93k
      } else {
2871
3.93k
        // Initialize the invalid domain.
2872
3.93k
        InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
2873
3.93k
        SuccDomain = CondSet;
2874
3.93k
      }
2875
3.96k
2876
3.96k
      SuccDomain = SuccDomain.detect_equalities();
2877
3.96k
2878
3.96k
      // Check if the maximal number of domain disjunctions was reached.
2879
3.96k
      // In case this happens we will clean up and bail.
2880
3.96k
      if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
2881
3.96k
        continue;
2882
0
2883
0
      invalidate(COMPLEXITY, DebugLoc());
2884
0
      while (++u < ConditionSets.size())
2885
0
        isl_set_free(ConditionSets[u]);
2886
0
      return false;
2887
0
    }
2888
5.35k
  }
2889
2.41k
2890
2.41k
  
return true2.40k
;
2891
2.41k
}
2892
2893
isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2894
                                               DominatorTree &DT,
2895
5.63k
                                               LoopInfo &LI) {
2896
5.63k
  // If @p BB is the ScopEntry we are done
2897
5.63k
  if (R.getEntry() == BB)
2898
1.16k
    return isl::set::universe(Domain.get_space());
2899
4.46k
2900
4.46k
  // The region info of this function.
2901
4.46k
  auto &RI = *R.getRegionInfo();
2902
4.46k
2903
4.46k
  Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
2904
4.46k
2905
4.46k
  // A domain to collect all predecessor domains, thus all conditions under
2906
4.46k
  // which the block is executed. To this end we start with the empty domain.
2907
4.46k
  isl::set PredDom = isl::set::empty(Domain.get_space());
2908
4.46k
2909
4.46k
  // Set of regions of which the entry block domain has been propagated to BB.
2910
4.46k
  // all predecessors inside any of the regions can be skipped.
2911
4.46k
  SmallSet<Region *, 8> PropagatedRegions;
2912
4.46k
2913
5.52k
  for (auto *PredBB : predecessors(BB)) {
2914
5.52k
    // Skip backedges.
2915
5.52k
    if (DT.dominates(BB, PredBB))
2916
684
      continue;
2917
4.83k
2918
4.83k
    // If the predecessor is in a region we used for propagation we can skip it.
2919
4.83k
    auto PredBBInRegion = [PredBB](Region *PR) 
{ return PR->contains(PredBB); }364
;
2920
4.83k
    if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2921
4.83k
                    PredBBInRegion)) {
2922
315
      continue;
2923
315
    }
2924
4.52k
2925
4.52k
    // Check if there is a valid region we can use for propagation, thus look
2926
4.52k
    // for a region that contains the predecessor and has @p BB as exit block.
2927
4.52k
    auto *PredR = RI.getRegionFor(PredBB);
2928
4.52k
    while (PredR->getExit() != BB && 
!PredR->contains(BB)3.35k
)
2929
0
      PredR->getParent();
2930
4.52k
2931
4.52k
    // If a valid region for propagation was found use the entry of that region
2932
4.52k
    // for propagation, otherwise the PredBB directly.
2933
4.52k
    if (PredR->getExit() == BB) {
2934
1.16k
      PredBB = PredR->getEntry();
2935
1.16k
      PropagatedRegions.insert(PredR);
2936
1.16k
    }
2937
4.52k
2938
4.52k
    auto *PredBBDom = getDomainConditions(PredBB).release();
2939
4.52k
    Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
2940
4.52k
2941
4.52k
    PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2942
4.52k
2943
4.52k
    PredDom = PredDom.unite(isl::manage(PredBBDom));
2944
4.52k
  }
2945
4.46k
2946
4.46k
  return PredDom;
2947
4.46k
}
2948
2949
bool Scop::propagateDomainConstraints(
2950
    Region *R, DominatorTree &DT, LoopInfo &LI,
2951
2.39k
    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
2952
2.39k
  // Iterate over the region R and propagate the domain constrains from the
2953
2.39k
  // predecessors to the current node. In contrast to the
2954
2.39k
  // buildDomainsWithBranchConstraints function, this one will pull the domain
2955
2.39k
  // information from the predecessors instead of pushing it to the successors.
2956
2.39k
  // Additionally, we assume the domains to be already present in the domain
2957
2.39k
  // map here. However, we iterate again in reverse post order so we know all
2958
2.39k
  // predecessors have been visited before a block or non-affine subregion is
2959
2.39k
  // visited.
2960
2.39k
2961
2.39k
  ReversePostOrderTraversal<Region *> RTraversal(R);
2962
6.86k
  for (auto *RN : RTraversal) {
2963
6.86k
    // Recurse for affine subregions but go on for basic blocks and non-affine
2964
6.86k
    // subregions.
2965
6.86k
    if (RN->isSubRegion()) {
2966
1.33k
      Region *SubRegion = RN->getNodeAs<Region>();
2967
1.33k
      if (!isNonAffineSubRegion(SubRegion)) {
2968
1.23k
        if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
2969
0
          return false;
2970
1.23k
        continue;
2971
1.23k
      }
2972
1.33k
    }
2973
5.63k
2974
5.63k
    BasicBlock *BB = getRegionNodeBasicBlock(RN);
2975
5.63k
    isl::set &Domain = DomainMap[BB];
2976
5.63k
    assert(Domain);
2977
5.63k
2978
5.63k
    // Under the union of all predecessor conditions we can reach this block.
2979
5.63k
    isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
2980
5.63k
    Domain = Domain.intersect(PredDom).coalesce();
2981
5.63k
    Domain = Domain.align_params(getParamSpace());
2982
5.63k
2983
5.63k
    Loop *BBLoop = getRegionNodeLoop(RN, LI);
2984
5.63k
    if (BBLoop && 
BBLoop->getHeader() == BB4.84k
&&
contains(BBLoop)1.68k
)
2985
1.67k
      if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
2986
0
        return false;
2987
5.63k
  }
2988
2.39k
2989
2.39k
  return true;
2990
2.39k
}
2991
2992
/// Create a map to map from a given iteration to a subsequent iteration.
2993
///
2994
/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2995
/// is incremented by one and all other dimensions are equal, e.g.,
2996
///             [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2997
///
2998
/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2999
static __isl_give isl_map *
3000
1.67k
createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3001
1.67k
  auto *MapSpace = isl_space_map_from_set(SetSpace);
3002
1.67k
  auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
3003
3.90k
  for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); 
u++2.23k
)
3004
2.23k
    if (u != Dim)
3005
561
      NextIterationMap =
3006
561
          isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3007
1.67k
  auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3008
1.67k
  C = isl_constraint_set_constant_si(C, 1);
3009
1.67k
  C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3010
1.67k
  C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3011
1.67k
  NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3012
1.67k
  return NextIterationMap;
3013
1.67k
}
3014
3015
bool Scop::addLoopBoundsToHeaderDomain(
3016
1.67k
    Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
3017
1.67k
  int LoopDepth = getRelativeLoopDepth(L);
3018
1.67k
  assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
3019
1.67k
3020
1.67k
  BasicBlock *HeaderBB = L->getHeader();
3021
1.67k
  assert(DomainMap.count(HeaderBB));
3022
1.67k
  isl::set &HeaderBBDom = DomainMap[HeaderBB];
3023
1.67k
3024
1.67k
  isl::map NextIterationMap = isl::manage(
3025
1.67k
      createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
3026
1.67k
3027
1.67k
  isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
3028
1.67k
3029
1.67k
  SmallVector<BasicBlock *, 4> LatchBlocks;
3030
1.67k
  L->getLoopLatches(LatchBlocks);
3031
1.67k
3032
1.67k
  for (BasicBlock *LatchBB : LatchBlocks) {
3033
1.67k
    // If the latch is only reachable via error statements we skip it.
3034
1.67k
    isl::set LatchBBDom = DomainMap.lookup(LatchBB);
3035
1.67k
    if (!LatchBBDom)
3036
0
      continue;
3037
1.67k
3038
1.67k
    isl::set BackedgeCondition = nullptr;
3039
1.67k
3040
1.67k
    TerminatorInst *TI = LatchBB->getTerminator();
3041
1.67k
    BranchInst *BI = dyn_cast<BranchInst>(TI);
3042
1.67k
    assert(BI && "Only branch instructions allowed in loop latches");
3043
1.67k
3044
1.67k
    if (BI->isUnconditional())
3045
937
      BackedgeCondition = LatchBBDom;
3046
737
    else {
3047
737
      SmallVector<isl_set *, 8> ConditionSets;
3048
737
      int idx = BI->getSuccessor(0) != HeaderBB;
3049
737
      if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3050
737
                              InvalidDomainMap, ConditionSets))
3051
0
        return false;
3052
737
3053
737
      // Free the non back edge condition set as we do not need it.
3054
737
      isl_set_free(ConditionSets[1 - idx]);
3055
737
3056
737
      BackedgeCondition = isl::manage(ConditionSets[idx]);
3057
737
    }
3058
1.67k
3059
1.67k
    int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3060
1.67k
    assert(LatchLoopDepth >= LoopDepth);
3061
1.67k
    BackedgeCondition = BackedgeCondition.project_out(
3062
1.67k
        isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3063
1.67k
    UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
3064
1.67k
  }
3065
1.67k
3066
1.67k
  isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
3067
2.23k
  for (int i = 0; i < LoopDepth; 
i++561
)
3068
561
    ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
3069
1.67k
3070
1.67k
  isl::set UnionBackedgeConditionComplement =
3071
1.67k
      UnionBackedgeCondition.complement();
3072
1.67k
  UnionBackedgeConditionComplement =
3073
1.67k
      UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3074
1.67k
                                                      0);
3075
1.67k
  UnionBackedgeConditionComplement =
3076
1.67k
      UnionBackedgeConditionComplement.apply(ForwardMap);
3077
1.67k
  HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3078
1.67k
  HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
3079
1.67k
3080
1.67k
  auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3081
1.67k
  HeaderBBDom = isl::manage(Parts.second);
3082
1.67k
3083
1.67k
  // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3084
1.67k
  // the bounded assumptions to the context as they are already implied by the
3085
1.67k
  // <nsw> tag.
3086
1.67k
  if (Affinator.hasNSWAddRecForLoop(L)) {
3087
1.29k
    isl_set_free(Parts.first);
3088
1.29k
    return true;
3089
1.29k
  }
3090
378
3091
378
  isl::set UnboundedCtx = isl::manage(Parts.first).params();
3092
378
  recordAssumption(INFINITELOOP, UnboundedCtx,
3093
378
                   HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
3094
378
  return true;
3095
378
}
3096
3097
1.30k
MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
3098
1.30k
  Value *PointerBase = MA->getOriginalBaseAddr();
3099
1.30k
3100
1.30k
  auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
3101
1.30k
  if (!PointerBaseInst)
3102
1.09k
    return nullptr;
3103
213
3104
213
  auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3105
213
  if (!BasePtrStmt)
3106
213
    return nullptr;
3107
0
3108
0
  return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3109
0
}
3110
3111
bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3112
483
                                        isl::union_map Writes) {
3113
483
  if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3114
0
    return getNonHoistableCtx(BasePtrMA, Writes).is_null();
3115
0
  }
3116
483
3117
483
  Value *BaseAddr = MA->getOriginalBaseAddr();
3118
483
  if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
3119
113
    if (!isa<LoadInst>(BasePtrInst))
3120
36
      return contains(BasePtrInst);
3121
447
3122
447
  return false;
3123
447
}
3124
3125
1.14k
bool Scop::buildAliasChecks(AliasAnalysis &AA) {
3126
1.14k
  if (!PollyUseRuntimeAliasChecks)
3127
21
    return true;
3128
1.12k
3129
1.12k
  if (buildAliasGroups(AA)) {
3130
1.11k
    // Aliasing assumptions do not go through addAssumption but we still want to
3131
1.11k
    // collect statistics so we do it here explicitly.
3132
1.11k
    if (MinMaxAliasGroups.size())
3133
198
      AssumptionsAliasing++;
3134
1.11k
    return true;
3135
1.11k
  }
3136
6
3137
6
  // If a problem occurs while building the alias groups we need to delete
3138
6
  // this SCoP and pretend it wasn't valid in the first place. To this end
3139
6
  // we make the assumed context infeasible.
3140
6
  invalidate(ALIASING, DebugLoc());
3141
6
3142
6
  DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3143
6
               << " could not be created as the number of parameters involved "
3144
6
                  "is too high. The SCoP will be "
3145
6
                  "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3146
6
                  "the maximal number of parameters but be advised that the "
3147
6
                  "compile time might increase exponentially.\n\n");
3148
6
  return false;
3149
6
}
3150
3151
std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
3152
1.12k
Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
3153
1.12k
  AliasSetTracker AST(AA);
3154
1.12k
3155
1.12k
  DenseMap<Value *, MemoryAccess *> PtrToAcc;
3156
1.12k
  DenseSet<const ScopArrayInfo *> HasWriteAccess;
3157
2.21k
  for (ScopStmt &Stmt : *this) {
3158
2.21k
3159
2.21k
    isl_set *StmtDomain = Stmt.getDomain().release();
3160
2.21k
    bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3161
2.21k
    isl_set_free(StmtDomain);
3162
2.21k
3163
2.21k
    // Statements with an empty domain will never be executed.
3164
2.21k
    if (StmtDomainEmpty)
3165
3
      continue;
3166
2.21k
3167
4.49k
    
for (MemoryAccess *MA : Stmt)2.21k
{
3168
4.49k
      if (MA->isScalarKind())
3169
1.28k
        continue;
3170
3.21k
      if (!MA->isRead())
3171
1.67k
        HasWriteAccess.insert(MA->getScopArrayInfo());
3172
3.21k
      MemAccInst Acc(MA->getAccessInstruction());
3173
3.21k
      if (MA->isRead() && 
isa<MemTransferInst>(Acc)1.54k
)
3174
7
        PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
3175
3.21k
      else
3176
3.21k
        PtrToAcc[Acc.getPointerOperand()] = MA;
3177
3.21k
      AST.add(Acc);
3178
3.21k
    }
3179
2.21k
  }
3180
1.12k
3181
1.12k
  AliasGroupVectorTy AliasGroups;
3182
1.49k
  for (AliasSet &AS : AST) {
3183
1.49k
    if (AS.isMustAlias() || 
AS.isForwardingAliasSet()375
)
3184
1.11k
      continue;
3185
375
    AliasGroupTy AG;
3186
375
    for (auto &PR : AS)
3187
1.36k
      AG.push_back(PtrToAcc[PR.getValue()]);
3188
375
    if (AG.size() < 2)
3189
14
      continue;
3190
361
    AliasGroups.push_back(std::move(AG));
3191
361
  }
3192
1.12k
3193
1.12k
  return std::make_tuple(AliasGroups, HasWriteAccess);
3194
1.12k
}
3195
3196
1.12k
void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
3197
1.49k
  for (unsigned u = 0; u < AliasGroups.size(); 
u++369
) {
3198
369
    AliasGroupTy NewAG;
3199
369
    AliasGroupTy &AG = AliasGroups[u];
3200
369
    AliasGroupTy::iterator AGI = AG.begin();
3201
369
    isl_set *AGDomain = getAccessDomain(*AGI);
3202
1.73k
    while (AGI != AG.end()) {
3203
1.36k
      MemoryAccess *MA = *AGI;
3204
1.36k
      isl_set *MADomain = getAccessDomain(MA);
3205
1.36k
      if (isl_set_is_disjoint(AGDomain, MADomain)) {
3206
26
        NewAG.push_back(MA);
3207
26
        AGI = AG.erase(AGI);
3208
26
        isl_set_free(MADomain);
3209
1.34k
      } else {
3210
1.34k
        AGDomain = isl_set_union(AGDomain, MADomain);
3211
1.34k
        AGI++;
3212
1.34k
      }
3213
1.36k
    }
3214
369
    if (NewAG.size() > 1)
3215
8
      AliasGroups.push_back(std::move(NewAG));
3216
369
    isl_set_free(AGDomain);
3217
369
  }
3218
1.12k
}
3219
3220
1.12k
bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3221
1.12k
  // To create sound alias checks we perform the following steps:
3222
1.12k
  //   o) We partition each group into read only and non read only accesses.
3223
1.12k
  //   o) For each group with more than one base pointer we then compute minimal
3224
1.12k
  //      and maximal accesses to each array of a group in read only and non
3225
1.12k
  //      read only partitions separately.
3226
1.12k
  AliasGroupVectorTy AliasGroups;
3227
1.12k
  DenseSet<const ScopArrayInfo *> HasWriteAccess;
3228
1.12k
3229
1.12k
  std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3230
1.12k
3231
1.12k
  splitAliasGroupsByDomain(AliasGroups);
3232
1.12k
3233
1.12k
  for (AliasGroupTy &AG : AliasGroups) {
3234
368
    if (!hasFeasibleRuntimeContext())
3235
1
      return false;
3236
367
3237
367
    {
3238
367
      IslMaxOperationsGuard MaxOpGuard(getIslCtx().get(), OptComputeOut);
3239
367
      bool Valid = buildAliasGroup(AG, HasWriteAccess);
3240
367
      if (!Valid)
3241
5
        return false;
3242
362
    }
3243
362
    if (isl_ctx_last_error(getIslCtx().get()) == isl_error_quota) {
3244
0
      invalidate(COMPLEXITY, DebugLoc());
3245
0
      return false;
3246
0
    }
3247
362
  }
3248
1.12k
3249
1.12k
  
return true1.11k
;
3250
1.12k
}
3251
3252
bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
3253
367
                           DenseSet<const ScopArrayInfo *> HasWriteAccess) {
3254
367
  AliasGroupTy ReadOnlyAccesses;
3255
367
  AliasGroupTy ReadWriteAccesses;
3256
367
  SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
3257
367
  SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
3258
367
3259
367
  if (AliasGroup.size() < 2)
3260
4
    return true;
3261
363
3262
1.33k
  
for (MemoryAccess *Access : AliasGroup)363
{
3263
1.33k
    ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3264
1.33k
                                        Access->getAccessInstruction())
3265
1.33k
             << "Possibly aliasing pointer, use restrict keyword.");
3266
1.33k
    const ScopArrayInfo *Array = Access->getScopArrayInfo();
3267
1.33k
    if (HasWriteAccess.count(Array)) {
3268
883
      ReadWriteArrays.insert(Array);
3269
883
      ReadWriteAccesses.push_back(Access);
3270
883
    } else {
3271
451
      ReadOnlyArrays.insert(Array);
3272
451
      ReadOnlyAccesses.push_back(Access);
3273
451
    }
3274
1.33k
  }
3275
363
3276
363
  // If there are no read-only pointers, and less than two read-write pointers,
3277
363
  // no alias check is needed.
3278
363
  if (ReadOnlyAccesses.empty() && 
ReadWriteArrays.size() <= 1188
)
3279
146
    return true;
3280
217
3281
217
  // If there is no read-write pointer, no alias check is needed.
3282
217
  if (ReadWriteArrays.empty())
3283
8
    return true;
3284
209
3285
209
  // For non-affine accesses, no alias check can be generated as we cannot
3286
209
  // compute a sufficiently tight lower and upper bound: bail out.
3287
823
  
for (MemoryAccess *MA : AliasGroup)209
{
3288
823
    if (!MA->isAffine()) {
3289
0
      invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3290
0
                 MA->getAccessInstruction()->getParent());
3291
0
      return false;
3292
0
    }
3293
823
  }
3294
209
3295
209
  // Ensure that for all memory accesses for which we generate alias checks,
3296
209
  // their base pointers are available.
3297
823
  
for (MemoryAccess *MA : AliasGroup)209
{
3298
823
    if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3299
0
      addRequiredInvariantLoad(
3300
0
          cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3301
823
  }
3302
209
3303
209
  MinMaxAliasGroups.emplace_back();
3304
209
  MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3305
209
  MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3306
209
  MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3307
209
3308
209
  bool Valid;
3309
209
3310
209
  Valid =
3311
209
      calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3312
209
3313
209
  if (!Valid)
3314
0
    return false;
3315
209
3316
209
  // Bail out if the number of values we need to compare is too large.
3317
209
  // This is important as the number of comparisons grows quadratically with
3318
209
  // the number of values we need to compare.
3319
209
  if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
3320
209
      RunTimeChecksMaxArraysPerGroup)
3321
1
    return false;
3322
208
3323
208
  Valid =
3324
208
      calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3325
208
3326
208
  if (!Valid)
3327
4
    return false;
3328
204
3329
204
  return true;
3330
204
}
3331
3332
/// Get the smallest loop that contains @p S but is not in @p S.
3333
3.49k
static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
3334
3.49k
  // Start with the smallest loop containing the entry and expand that
3335
3.49k
  // loop until it contains all blocks in the region. If there is a loop
3336
3.49k
  // containing all blocks in the region check if it is itself contained
3337
3.49k
  // and if so take the parent loop as it will be the smallest containing
3338
3.49k
  // the region but not contained by it.
3339
3.49k
  Loop *L = LI.getLoopFor(S.getEntry());
3340
4.62k
  while (L) {
3341
3.07k
    bool AllContained = true;
3342
3.07k
    for (auto *BB : S.blocks())
3343
25.0k
      AllContained &= L->contains(BB);
3344
3.07k
    if (AllContained)
3345
1.94k
      break;
3346
1.13k
    L = L->getParentLoop();
3347
1.13k
  }
3348
3.49k
3349
3.49k
  return L ? 
(S.contains(L) 1.94k
?
L->getParentLoop()1.80k
:
L141
) :
nullptr1.55k
;
3350
3.49k
}
3351
3352
int Scop::NextScopID = 0;
3353
3354
std::string Scop::CurrentFunc;
3355
3356
1.18k
int Scop::getNextID(std::string ParentFunc) {
3357
1.18k
  if (ParentFunc != CurrentFunc) {
3358
1.16k
    CurrentFunc = ParentFunc;
3359
1.16k
    NextScopID = 0;
3360
1.16k
  }
3361
1.18k
  return NextScopID++;
3362
1.18k
}
3363
3364
Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3365
           DominatorTree &DT, ScopDetection::DetectionContext &DC,
3366
           OptimizationRemarkEmitter &ORE)
3367
    : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
3368
      R(R), name(R.getNameStr()), HasSingleExitEdge(R.getExitingBlock()),
3369
      DC(DC), ORE(ORE), Affinator(this, LI),
3370
1.18k
      ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
3371
1.18k
  if (IslOnErrorAbort)
3372
1.18k
    isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
3373
1.18k
  buildContext();
3374
1.18k
}
3375
3376
1.16k
Scop::~Scop() = default;
3377
3378
1.14k
void Scop::foldSizeConstantsToRight() {
3379
1.14k
  isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
3380
1.14k
3381
2.42k
  for (auto Array : arrays()) {
3382
2.42k
    if (Array->getNumberOfDimensions() <= 1)
3383
2.15k
      continue;
3384
273
3385
273
    isl_space *Space = Array->getSpace().release();
3386
273
3387
273
    Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3388
273
3389
273
    if (!isl_union_set_contains(Accessed, Space)) {
3390
0
      isl_space_free(Space);
3391
0
      continue;
3392
0
    }
3393
273
3394
273
    isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3395
273
3396
273
    isl_map *Transform =
3397
273
        isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
3398
273
3399
273
    std::vector<int> Int;
3400
273
3401
273
    int Dims = isl_set_dim(Elements, isl_dim_set);
3402
903
    for (int i = 0; i < Dims; 
i++630
) {
3403
630
      isl_set *DimOnly =
3404
630
          isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3405
630
      DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3406
630
      DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3407
630
3408
630
      isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3409
630
3410
630
      if (i == Dims - 1) {
3411
273
        Int.push_back(1);
3412
273
        Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3413
273
        isl_basic_set_free(DimHull);
3414
273
        continue;
3415
273
      }
3416
357
3417
357
      if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3418
4
        isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3419
4
        isl_val *Val = isl_aff_get_denominator_val(Diff);
3420
4
        isl_aff_free(Diff);
3421
4
3422
4
        int ValInt = 1;
3423
4
3424
4
        if (isl_val_is_int(Val)) {
3425
4
          auto ValAPInt = APIntFromVal(Val);
3426
4
          if (ValAPInt.isSignedIntN(32))
3427
3
            ValInt = ValAPInt.getSExtValue();
3428
4
        } else {
3429
0
          isl_val_free(Val);
3430
0
        }
3431
4
3432
4
        Int.push_back(ValInt);
3433
4
3434
4
        isl_constraint *C = isl_constraint_alloc_equality(
3435
4
            isl_local_space_from_space(isl_map_get_space(Transform)));
3436
4
        C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3437
4
        C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3438
4
        Transform = isl_map_add_constraint(Transform, C);
3439
4
        isl_basic_set_free(DimHull);
3440
4
        continue;
3441
4
      }
3442
353
3443
353
      isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3444
353
      ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3445
353
3446
353
      int ValInt = 1;
3447
353
      if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3448
11
        ValInt = 0;
3449
11
      }
3450
353
3451
353
      Int.push_back(ValInt);
3452
353
      Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3453
353
      isl_basic_set_free(DimHull);
3454
353
      isl_basic_set_free(ZeroSet);
3455
353
    }
3456
273
3457
273
    isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3458
273
3459
273
    if (!isl_set_is_subset(Elements, MappedElements)) {
3460
0
      isl_set_free(Elements);
3461
0
      isl_set_free(MappedElements);
3462
0
      isl_map_free(Transform);
3463
0
      continue;
3464
0
    }
3465
273
3466
273
    isl_set_free(MappedElements);
3467
273
3468
273
    bool CanFold = true;
3469
273
3470
273
    if (Int[0] <= 1)
3471
270
      CanFold = false;
3472
273
3473
273
    unsigned NumDims = Array->getNumberOfDimensions();
3474
357
    for (unsigned i = 1; i < NumDims - 1; 
i++84
)
3475
84
      if (Int[0] != Int[i] && 
Int[i]3
)
3476
1
        CanFold = false;
3477
273
3478
273
    if (!CanFold) {
3479
270
      isl_set_free(Elements);
3480
270
      isl_map_free(Transform);
3481
270
      continue;
3482
270
    }
3483
3
3484
3
    for (auto &Access : AccessFunctions)
3485
11
      if (Access->getScopArrayInfo() == Array)
3486
11
        Access->setAccessRelation(Access->getAccessRelation().apply_range(
3487
11
            isl::manage_copy(Transform)));
3488
3
3489
3
    isl_map_free(Transform);
3490
3
3491
3
    std::vector<const SCEV *> Sizes;
3492
9
    for (unsigned i = 0; i < NumDims; 
i++6
) {
3493
6
      auto Size = Array->getDimensionSize(i);
3494
6
3495
6
      if (i == NumDims - 1)
3496
3
        Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3497
6
      Sizes.push_back(Size);
3498
6
    }
3499
3
3500
3
    Array->updateSizes(Sizes, false /* CheckConsistency */);
3501
3
3502
3
    isl_set_free(Elements);
3503
3
  }
3504
1.14k
  isl_union_set_free(Accessed);
3505
1.14k
}
3506
3507
1.14k
void Scop::markFortranArrays() {
3508
2.26k
  for (ScopStmt &Stmt : Stmts) {
3509
4.64k
    for (MemoryAccess *MemAcc : Stmt) {
3510
4.64k
      Value *FAD = MemAcc->getFortranArrayDescriptor();
3511
4.64k
      if (!FAD)
3512
4.63k
        continue;
3513
10
3514
10
      // TODO: const_cast-ing to edit
3515
10
      ScopArrayInfo *SAI =
3516
10
          const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3517
10
      assert(SAI && "memory access into a Fortran array does not "
3518
10
                    "have an associated ScopArrayInfo");
3519
10
      SAI->applyAndSetFAD(FAD);
3520
10
    }
3521
2.26k
  }
3522
1.14k
}
3523
3524
1.14k
void Scop::finalizeAccesses() {
3525
1.14k
  updateAccessDimensionality();
3526
1.14k
  foldSizeConstantsToRight();
3527
1.14k
  foldAccessRelations();
3528
1.14k
  assumeNoOutOfBounds();
3529
1.14k
  markFortranArrays();
3530
1.14k
}
3531
3532
1.14k
void Scop::updateAccessDimensionality() {
3533
1.14k
  // Check all array accesses for each base pointer and find a (virtual) element
3534
1.14k
  // size for the base pointer that divides all access functions.
3535
1.14k
  for (ScopStmt &Stmt : *this)
3536
4.64k
    
for (MemoryAccess *Access : Stmt)2.26k
{
3537
4.64k
      if (!Access->isArrayKind())
3538
1.28k
        continue;
3539
3.36k
      ScopArrayInfo *Array =
3540
3.36k
          const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3541
3.36k
3542
3.36k
      if (Array->getNumberOfDimensions() != 1)
3543
423
        continue;
3544
2.93k
      unsigned DivisibleSize = Array->getElemSizeInBytes();
3545
2.93k
      const SCEV *Subscript = Access->getSubscript(0);
3546
2.93k
      while (!isDivisible(Subscript, DivisibleSize, *SE))
3547
2
        DivisibleSize /= 2;
3548
2.93k
      auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3549
2.93k
      Array->updateElementType(Ty);
3550
2.93k
    }
3551
1.14k
3552
1.14k
  for (auto &Stmt : *this)
3553
2.26k
    for (auto &Access : Stmt)
3554
4.64k
      Access->updateDimensionality();
3555
1.14k
}
3556
3557
1.14k
void Scop::foldAccessRelations() {
3558
1.14k
  for (auto &Stmt : *this)
3559
2.26k
    for (auto &Access : Stmt)
3560
4.64k
      Access->foldAccessRelation();
3561
1.14k
}
3562
3563
1.14k
void Scop::assumeNoOutOfBounds() {
3564
1.14k
  for (auto &Stmt : *this)
3565
2.26k
    for (auto &Access : Stmt)
3566
4.64k
      Access->assumeNoOutOfBound();
3567
1.14k
}
3568
3569
6.90k
void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3570
6.90k
  for (Instruction *Inst : Stmt.getInstructions())
3571
2.11k
    InstStmtMap.erase(Inst);
3572
6.90k
3573
6.90k
  if (Stmt.isRegionStmt()) {
3574
44
    for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
3575
44
      StmtMap.erase(BB);
3576
44
      // Skip entry basic block, as its instructions are already deleted as
3577
44
      // part of the statement's instruction list.
3578
44
      if (BB == Stmt.getEntryBlock())
3579
17
        continue;
3580
27
      for (Instruction &Inst : *BB)
3581
62
        InstStmtMap.erase(&Inst);
3582
27
    }
3583
6.88k
  } else {
3584
6.88k
    auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
3585
6.88k
    if (StmtMapIt != StmtMap.end())
3586
6.88k
      StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
3587
6.88k
                                          StmtMapIt->second.end(), &Stmt),
3588
6.88k
                              StmtMapIt->second.end());
3589
6.88k
    for (Instruction *Inst : Stmt.getInstructions())
3590
2.08k
      InstStmtMap.erase(Inst);
3591
6.88k
  }
3592
6.90k
}
3593
3594
3.54k
void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3595
23.7k
  for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3596
20.1k
    if (!ShouldDelete(*StmtIt)) {
3597
13.2k
      StmtIt++;
3598
13.2k
      continue;
3599
13.2k
    }
3600
6.90k
3601
6.90k
    removeFromStmtMap(*StmtIt);
3602
6.90k
    StmtIt = Stmts.erase(StmtIt);
3603
6.90k
  }
3604
3.54k
}
3605
3606
1.17k
void Scop::removeStmtNotInDomainMap() {
3607
9.02k
  auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
3608
9.02k
    return !this->DomainMap.lookup(Stmt.getEntryBlock());
3609
9.02k
  };
3610
1.17k
  removeStmts(ShouldDelete);
3611
1.17k
}
3612
3613
2.36k
void Scop::simplifySCoP(bool AfterHoisting) {
3614
11.1k
  auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
3615
11.1k
    bool RemoveStmt = Stmt.isEmpty();
3616
11.1k
3617
11.1k
    // Remove read only statements only after invariant load hoisting.
3618
11.1k
    if (!RemoveStmt && 
AfterHoisting4.51k
) {
3619
2.23k
      bool OnlyRead = true;
3620
3.66k
      for (MemoryAccess *MA : Stmt) {
3621
3.66k
        if (MA->isRead())
3622
1.47k
          continue;
3623
2.19k
3624
2.19k
        OnlyRead = false;
3625
2.19k
        break;
3626
2.19k
      }
3627
2.23k
3628
2.23k
      RemoveStmt = OnlyRead;
3629
2.23k
    }
3630
11.1k
    return RemoveStmt;
3631
11.1k
  };
3632
2.36k
3633
2.36k
  removeStmts(ShouldDelete);
3634
2.36k
}
3635
3636
5.74k
InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
3637
5.74k
  LoadInst *LInst = dyn_cast<LoadInst>(Val);
3638
5.74k
  if (!LInst)
3639
3.48k
    return nullptr;
3640
2.26k
3641
2.26k
  if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3642
2
    LInst = cast<LoadInst>(Rep);
3643
2.26k
3644
2.26k
  Type *Ty = LInst->getType();
3645
2.26k
  const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3646
2.26k
  for (auto &IAClass : InvariantEquivClasses) {
3647
276
    if (PointerSCEV != IAClass.IdentifyingPointer || 
Ty != IAClass.AccessType87
)
3648
191
      continue;
3649
85
3650
85
    auto &MAs = IAClass.InvariantAccesses;
3651
85
    for (auto *MA : MAs)
3652
91
      if (MA->getAccessInstruction() == Val)
3653
83
        return &IAClass;
3654
85
  }
3655
2.26k
3656
2.26k
  
return nullptr2.18k
;
3657
2.26k
}
3658
3659
6
bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3660
6
  for (const llvm::Argument &Arg : F.args())
3661
10
    if (&Arg == maybeParam)
3662
6
      return true;
3663
6
3664
6
  
return false0
;
3665
6
}
3666
3667
bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3668
                              bool MAInvalidCtxIsEmpty,
3669
358
                              bool NonHoistableCtxIsEmpty) {
3670
358
  LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3671
358
  const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3672
358
  if (PollyAllowDereferenceOfAllFunctionParams &&
3673
358
      
isAParameter(LInst->getPointerOperand(), getFunction())6
)
3674
6
    return true;
3675
352
3676
352
  // TODO: We can provide more information for better but more expensive
3677
352
  //       results.
3678
352
  if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3679
352
                                          LInst->getAlignment(), DL))
3680
296
    return false;
3681
56
3682
56
  // If the location might be overwritten we do not hoist it unconditionally.
3683
56
  //
3684
56
  // TODO: This is probably too conservative.
3685
56
  if (!NonHoistableCtxIsEmpty)
3686
1
    return false;
3687
55
3688
55
  // If a dereferenceable load is in a statement that is modeled precisely we
3689
55
  // can hoist it.
3690
55
  if (StmtInvalidCtxIsEmpty && 
MAInvalidCtxIsEmpty50
)
3691
50
    return true;
3692
5
3693
5
  // Even if the statement is not modeled precisely we can hoist the load if it
3694
5
  // does not involve any parameters that might have been specialized by the
3695
5
  // statement domain.
3696
10
  
for (unsigned u = 0, e = MA->getNumSubscripts(); 5
u < e;
u++5
)
3697
5
    if (!isa<SCEVConstant>(MA->getSubscript(u)))
3698
0
      return false;
3699
5
  return true;
3700
5
}
3701
3702
368
void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
3703
368
  if (InvMAs.empty())
3704
122
    return;
3705
246
3706
246
  isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3707
246
  bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
3708
246
3709
246
  // Get the context under which the statement is executed but remove the error
3710
246
  // context under which this statement is reached.
3711
246
  isl::set DomainCtx = Stmt.getDomain().params();
3712
246
  DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
3713
246
3714
246
  if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
3715
1
    auto *AccInst = InvMAs.front().MA->getAccessInstruction();
3716
1
    invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
3717
1
    return;
3718
1
  }
3719
245
3720
245
  // Project out all parameters that relate to loads in the statement. Otherwise
3721
245
  // we could have cyclic dependences on the constraints under which the
3722
245
  // hoisted loads are executed and we could not determine an order in which to
3723
245
  // pre-load them. This happens because not only lower bounds are part of the
3724
245
  // domain but also upper bounds.
3725
358
  
for (auto &InvMA : InvMAs)245
{
3726
358
    auto *MA = InvMA.MA;
3727
358
    Instruction *AccInst = MA->getAccessInstruction();
3728
358
    if (SE->isSCEVable(AccInst->getType())) {
3729
334
      SetVector<Value *> Values;
3730
583
      for (const SCEV *Parameter : Parameters) {
3731
583
        Values.clear();
3732
583
        findValues(Parameter, *SE, Values);
3733
583
        if (!Values.count(AccInst))
3734
472
          continue;
3735
111
3736
111
        if (isl::id ParamId = getIdForParam(Parameter)) {
3737
111
          int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
3738
111
          if (Dim >= 0)
3739
110
            DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
3740
111
        }
3741
111
      }
3742
334
    }
3743
358
  }
3744
245
3745
358
  for (auto &InvMA : InvMAs) {
3746
358
    auto *MA = InvMA.MA;
3747
358
    isl::set NHCtx = InvMA.NonHoistableCtx;
3748
358
3749
358
    // Check for another invariant access that accesses the same location as
3750
358
    // MA and if found consolidate them. Otherwise create a new equivalence
3751
358
    // class at the end of InvariantEquivClasses.
3752
358
    LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3753
358
    Type *Ty = LInst->getType();
3754
358
    const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3755
358
3756
358
    isl::set MAInvalidCtx = MA->getInvalidContext();
3757
358
    bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3758
358
    bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
3759
358
3760
358
    isl::set MACtx;
3761
358
    // Check if we know that this pointer can be speculatively accessed.
3762
358
    if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3763
358
                           NonHoistableCtxIsEmpty)) {
3764
61
      MACtx = isl::set::universe(DomainCtx.get_space());
3765
297
    } else {
3766
297
      MACtx = DomainCtx;
3767
297
      MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3768
297
      MACtx = MACtx.gist_params(getContext());
3769
297
    }
3770
358
3771
358
    bool Consolidated = false;
3772
921
    for (auto &IAClass : InvariantEquivClasses) {
3773
921
      if (PointerSCEV != IAClass.IdentifyingPointer || 
Ty != IAClass.AccessType238
)
3774
687
        continue;
3775
234
3776
234
      // If the pointer and the type is equal check if the access function wrt.
3777
234
      // to the domain is equal too. It can happen that the domain fixes
3778
234
      // parameter values and these can be different for distinct part of the
3779
234
      // SCoP. If this happens we cannot consolidate the loads but need to
3780
234
      // create a new invariant load equivalence class.
3781
234
      auto &MAs = IAClass.InvariantAccesses;
3782
234
      if (!MAs.empty()) {
3783
45
        auto *LastMA = MAs.front();
3784
45
3785
45
        isl::set AR = MA->getAccessRelation().range();
3786
45
        isl::set LastAR = LastMA->getAccessRelation().range();
3787
45
        bool SameAR = AR.is_equal(LastAR);
3788
45
3789
45
        if (!SameAR)
3790
4
          continue;
3791
230
      }
3792
230
3793
230
      // Add MA to the list of accesses that are in this class.
3794
230
      MAs.push_front(MA);
3795
230
3796
230
      Consolidated = true;
3797
230
3798
230
      // Unify the execution context of the class and this statement.
3799
230
      isl::set IAClassDomainCtx = IAClass.ExecutionContext;
3800
230
      if (IAClassDomainCtx)
3801
41
        IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
3802
189
      else
3803
189
        IAClassDomainCtx = MACtx;
3804
230
      IAClass.ExecutionContext = IAClassDomainCtx;
3805
230
      break;
3806
230
    }
3807
358
3808
358
    if (Consolidated)
3809
230
      continue;
3810
128
3811
128
    // If we did not consolidate MA, thus did not find an equivalence class
3812
128
    // for it, we create a new one.
3813
128
    InvariantEquivClasses.emplace_back(
3814
128
        InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
3815
128
  }
3816
245
}
3817
3818
/// Check if an access range is too complex.
3819
///
3820
/// An access range is too complex, if it contains either many disjuncts or
3821
/// very complex expressions. As a simple heuristic, we assume if a set to
3822
/// be too complex if the sum of existentially quantified dimensions and
3823
/// set dimensions is larger than a threshold. This reliably detects both
3824
/// sets with many disjuncts as well as sets with many divisions as they
3825
/// arise in h264.
3826
///
3827
/// @param AccessRange The range to check for complexity.
3828
///
3829
/// @returns True if the access range is too complex.
3830
408
static bool isAccessRangeTooComplex(isl::set AccessRange) {
3831
408
  unsigned NumTotalDims = 0;
3832
408
3833
454
  auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
3834
454
    NumTotalDims += BSet.dim(isl::dim::div);
3835
454
    NumTotalDims += BSet.dim(isl::dim::set);
3836
454
    return isl::stat::ok;
3837
454
  };
3838
408
3839
408
  AccessRange.foreach_basic_set(CountDimensions);
3840
408
3841
408
  if (NumTotalDims > MaxDimensionsInAccessRange)
3842
1
    return true;
3843
407
3844
407
  return false;
3845
407
}
3846
3847
899
isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
3848
899
  // TODO: Loads that are not loop carried, hence are in a statement with
3849
899
  //       zero iterators, are by construction invariant, though we
3850
899
  //       currently "hoist" them anyway. This is necessary because we allow
3851
899
  //       them to be treated as parameters (e.g., in conditions) and our code
3852
899
  //       generation would otherwise use the old value.
3853
899
3854
899
  auto &Stmt = *Access->getStatement();
3855
899
  BasicBlock *BB = Stmt.getEntryBlock();
3856
899
3857
899
  if (Access->isScalarKind() || 
Access->isWrite()758
||
!Access->isAffine()497
||
3858
899
      
Access->isMemoryIntrinsic()483
)
3859
416
    return nullptr;
3860
483
3861
483
  // Skip accesses that have an invariant base pointer which is defined but
3862
483
  // not loaded inside the SCoP. This can happened e.g., if a readnone call
3863
483
  // returns a pointer that is used as a base address. However, as we want
3864
483
  // to hoist indirect pointers, we allow the base pointer to be defined in
3865
483
  // the region if it is also a memory access. Each ScopArrayInfo object
3866
483
  // that has a base pointer origin has a base pointer that is loaded and
3867
483
  // that it is invariant, thus it will be hoisted too. However, if there is
3868
483
  // no base pointer origin we check that the base pointer is defined
3869
483
  // outside the region.
3870
483
  auto *LI = cast<LoadInst>(Access->getAccessInstruction());
3871
483
  if (hasNonHoistableBasePtrInScop(Access, Writes))
3872
0
    return nullptr;
3873
483
3874
483
  isl::map AccessRelation = give(Access->getAccessRelation().release());
3875
483
  assert(!AccessRelation.is_empty());
3876
483
3877
483
  if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
3878
74
    return nullptr;
3879
409
3880
409
  AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
3881
409
  isl::set SafeToLoad;
3882
409
3883
409
  auto &DL = getFunction().getParent()->getDataLayout();
3884
409
  if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3885
409
                                  DL)) {
3886
79
    SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
3887
330
  } else if (BB != LI->getParent()) {
3888
1
    // Skip accesses in non-affine subregions as they might not be executed
3889
1
    // under the same condition as the entry of the non-affine subregion.
3890
1
    return nullptr;
3891
329
  } else {
3892
329
    SafeToLoad = AccessRelation.range();
3893
329
  }
3894
409
3895
409
  
if (408
isAccessRangeTooComplex(AccessRelation.range())408
)
3896
1
    return nullptr;
3897
407
3898
407
  isl::union_map Written = Writes.intersect_range(SafeToLoad);
3899
407
  isl::set WrittenCtx = Written.params();
3900
407
  bool IsWritten = !WrittenCtx.is_empty();
3901
407
3902
407
  if (!IsWritten)
3903
345
    return WrittenCtx;
3904
62
3905
62
  WrittenCtx = WrittenCtx.remove_divs();
3906
62
  bool TooComplex =
3907
62
      isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
3908
62
  if (TooComplex || 
!isRequiredInvariantLoad(LI)56
)
3909
48
    return nullptr;
3910
14
3911
14
  addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), AS_RESTRICTION,
3912
14
                LI->getParent());
3913
14
  return WrittenCtx;
3914
14
}
3915
3916
1.14k
void Scop::verifyInvariantLoads() {
3917
1.14k
  auto &RIL = getRequiredInvariantLoads();
3918
1.14k
  for (LoadInst *LI : RIL) {
3919
226
    assert(LI && contains(LI));
3920
226
    // If there exists a statement in the scop which has a memory access for
3921
226
    // @p LI, then mark this scop as infeasible for optimization.
3922
226
    for (ScopStmt &Stmt : Stmts)
3923
883
      if (Stmt.getArrayAccessOrNULLFor(LI)) {
3924
2
        invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3925
2
        return;
3926
2
      }
3927
226
  }
3928
1.14k
}
3929
3930
1.14k
void Scop::hoistInvariantLoads() {
3931
1.14k
  if (!PollyInvariantLoadHoisting)
3932
975
    return;
3933
165
3934
165
  isl::union_map Writes = getWrites();
3935
368
  for (ScopStmt &Stmt : *this) {
3936
368
    InvariantAccessesTy InvariantAccesses;
3937
368
3938
368
    for (MemoryAccess *Access : Stmt)
3939
899
      if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
3940
359
        InvariantAccesses.push_back({Access, NHCtx});
3941
368
3942
368
    // Transfer the memory access from the statement to the SCoP.
3943
368
    for (auto InvMA : InvariantAccesses)
3944
359
      Stmt.removeMemoryAccess(InvMA.MA);
3945
368
    addInvariantLoads(Stmt, InvariantAccesses);
3946
368
  }
3947
165
}
3948
3949
/// Find the canonical scop array info object for a set of invariant load
3950
/// hoisted loads. The canonical array is the one that corresponds to the
3951
/// first load in the list of accesses which is used as base pointer of a
3952
/// scop array.
3953
static const ScopArrayInfo *findCanonicalArray(Scop *S,
3954
322
                                               MemoryAccessList &Accesses) {
3955
342
  for (MemoryAccess *Access : Accesses) {
3956
342
    const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3957
342
        Access->getAccessInstruction(), MemoryKind::Array);
3958
342
    if (CanonicalArray)
3959
73
      return CanonicalArray;
3960
342
  }
3961
322
  
return nullptr249
;
3962
322
}
3963
3964
/// Check if @p Array severs as base array in an invariant load.
3965
11
static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3966
11
  for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3967
23
    for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3968
38
      if (Access2->getScopArrayInfo() == Array)
3969
6
        return true;
3970
11
  
return false5
;
3971
11
}
3972
3973
/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3974
/// with a reference to @p New.
3975
static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3976
5
                                 const ScopArrayInfo *New) {
3977
5
  for (ScopStmt &Stmt : *S)
3978
17
    
for (MemoryAccess *Access : Stmt)14
{
3979
17
      if (Access->getLatestScopArrayInfo() != Old)
3980
11
        continue;
3981
6
3982
6
      isl::id Id = New->getBasePtrId();
3983
6
      isl::map Map = Access->getAccessRelation();
3984
6
      Map = Map.set_tuple_id(isl::dim::out, Id);
3985
6
      Access->setAccessRelation(Map);
3986
6
    }
3987
5
}
3988
3989
1.14k
void Scop::canonicalizeDynamicBasePtrs() {
3990
1.14k
  for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3991
322
    MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3992
322
3993
322
    const ScopArrayInfo *CanonicalBasePtrSAI =
3994
322
        findCanonicalArray(this, BasePtrAccesses);
3995
322
3996
322
    if (!CanonicalBasePtrSAI)
3997
249
      continue;
3998
73
3999
90
    
for (MemoryAccess *BasePtrAccess : BasePtrAccesses)73
{
4000
90
      const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4001
90
          BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4002
90
      if (!BasePtrSAI || 
BasePtrSAI == CanonicalBasePtrSAI87
||
4003
90
          
!BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI)14
)
4004
79
        continue;
4005
11
4006
11
      // we currently do not canonicalize arrays where some accesses are
4007
11
      // hoisted as invariant loads. If we would, we need to update the access
4008
11
      // function of the invariant loads as well. However, as this is not a
4009
11
      // very common situation, we leave this for now to avoid further
4010
11
      // complexity increases.
4011
11
      if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4012
6
        continue;
4013
5
4014
5
      replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4015
5
    }
4016
73
  }
4017
1.14k
}
4018
4019
ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4020
                                              ArrayRef<const SCEV *> Sizes,
4021
                                              MemoryKind Kind,
4022
4.92k
                                              const char *BaseName) {
4023
4.92k
  assert((BasePtr || BaseName) &&
4024
4.92k
         "BasePtr and BaseName can not be nullptr at the same time.");
4025
4.92k
  assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4026
4.92k
  auto &SAI = BasePtr ? 
ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]4.83k
4027
4.92k
                      : 
ScopArrayNameMap[BaseName]85
;
4028
4.92k
  if (!SAI) {
4029
2.52k
    auto &DL = getFunction().getParent()->getDataLayout();
4030
2.52k
    SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
4031
2.52k
                                DL, this, BaseName));
4032
2.52k
    ScopArrayInfoSet.insert(SAI.get());
4033
2.52k
  } else {
4034
2.39k
    SAI->updateElementType(ElementType);
4035
2.39k
    // In case of mismatching array sizes, we bail out by setting the run-time
4036
2.39k
    // context to false.
4037
2.39k
    if (!SAI->updateSizes(Sizes))
4038
0
      invalidate(DELINEARIZATION, DebugLoc());
4039
2.39k
  }
4040
4.92k
  return SAI.get();
4041
4.92k
}
4042
4043
ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4044
                                         const std::string &BaseName,
4045
85
                                         const std::vector<unsigned> &Sizes) {
4046
85
  auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4047
85
  std::vector<const SCEV *> SCEVSizes;
4048
85
4049
85
  for (auto size : Sizes)
4050
168
    if (size)
4051
168
      SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4052
0
    else
4053
0
      SCEVSizes.push_back(nullptr);
4054
85
4055
85
  auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4056
85
                                       MemoryKind::Array, BaseName.c_str());
4057
85
  return SAI;
4058
85
}
4059
4060
const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4061
521
                                                  MemoryKind Kind) {
4062
521
  auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
4063
521
  return SAI;
4064
521
}
4065
4066
89
const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4067
89
  auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
4068
89
  assert(SAI && "No ScopArrayInfo available for this base pointer");
4069
89
  return SAI;
4070
89
}
4071
4072
0
std::string Scop::getContextStr() const { return getContext().to_str(); }
4073
4074
0
std::string Scop::getAssumedContextStr() const {
4075
0
  assert(AssumedContext && "Assumed context not yet built");
4076
0
  return AssumedContext.to_str();
4077
0
}
4078
4079
0
std::string Scop::getInvalidContextStr() const {
4080
0
  return InvalidContext.to_str();
4081
0
}
4082
4083
839
std::string Scop::getNameStr() const {
4084
839
  std::string ExitName, EntryName;
4085
839
  std::tie(EntryName, ExitName) = getEntryExitStr();
4086
839
  return EntryName + "---" + ExitName;
4087
839
}
4088
4089
849
std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4090
849
  std::string ExitName, EntryName;
4091
849
  raw_string_ostream ExitStr(ExitName);
4092
849
  raw_string_ostream EntryStr(EntryName);
4093
849
4094
849
  R.getEntry()->printAsOperand(EntryStr, false);
4095
849
  EntryStr.str();
4096
849
4097
849
  if (R.getExit()) {
4098
845
    R.getExit()->printAsOperand(ExitStr, false);
4099
845
    ExitStr.str();
4100
845
  } else
4101
4
    ExitName = "FunctionExit";
4102
849
4103
849
  return std::make_pair(EntryName, ExitName);
4104
849
}
4105
4106
30.2k
isl::set Scop::getContext() const { return Context; }
4107
10.0k
isl::space Scop::getParamSpace() const { return getContext().get_space(); }
4108
4109
1.14k
isl::space Scop::getFullParamSpace() const {
4110
1.14k
  std::vector<isl::id> FortranIDs;
4111
1.14k
  FortranIDs = getFortranArrayIds(arrays());
4112
1.14k
4113
1.14k
  isl::space Space = isl::space::params_alloc(
4114
1.14k
      getIslCtx(), ParameterIds.size() + FortranIDs.size());
4115
1.14k
4116
1.14k
  unsigned PDim = 0;
4117
1.20k
  for (const SCEV *Parameter : Parameters) {
4118
1.20k
    isl::id Id = getIdForParam(Parameter);
4119
1.20k
    Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4120
1.20k
  }
4121
1.14k
4122
1.14k
  for (isl::id Id : FortranIDs)
4123
7
    Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4124
1.14k
4125
1.14k
  return Space;
4126
1.14k
}
4127
4128
4.89k
isl::set Scop::getAssumedContext() const {
4129
4.89k
  assert(AssumedContext && "Assumed context not yet built");
4130
4.89k
  return AssumedContext;
4131
4.89k
}
4132
4133
1.14k
bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
4134
1.14k
  if (PollyProcessUnprofitable)
4135
1.14k
    return true;
4136
3
4137
3
  if (isEmpty())
4138
0
    return false;
4139
3
4140
3
  unsigned OptimizableStmtsOrLoops = 0;
4141
14
  for (auto &Stmt : *this) {
4142
14
    if (Stmt.getNumIterators() == 0)
4143
0
      continue;
4144
14
4145
14
    bool ContainsArrayAccs = false;
4146
14
    bool ContainsScalarAccs = false;
4147
33
    for (auto *MA : Stmt) {
4148
33
      if (MA->isRead())
4149
15
        continue;
4150
18
      ContainsArrayAccs |= MA->isLatestArrayKind();
4151
18
      ContainsScalarAccs |= MA->isLatestScalarKind();
4152
18
    }
4153
14
4154
14
    if (!ScalarsAreUnprofitable || 
(9
ContainsArrayAccs9
&&
!ContainsScalarAccs4
))
4155
6
      OptimizableStmtsOrLoops += Stmt.getNumIterators();
4156
14
  }
4157
3
4158
3
  return OptimizableStmtsOrLoops > 1;
4159
3
}
4160
4161
3.84k
bool Scop::hasFeasibleRuntimeContext() const {
4162
3.84k
  auto PositiveContext = getAssumedContext();
4163
3.84k
  auto NegativeContext = getInvalidContext();
4164
3.84k
  PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4165
3.84k
  // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
4166
3.84k
  if (!PositiveContext)
4167
7
    return false;
4168
3.83k
4169
3.83k
  bool IsFeasible = !(PositiveContext.is_empty() ||
4170
3.83k
                      
PositiveContext.is_subset(NegativeContext)3.77k
);
4171
3.83k
  if (!IsFeasible)
4172
77
    return false;
4173
3.76k
4174
3.76k
  auto DomainContext = getDomains().params();
4175
3.76k
  IsFeasible = !DomainContext.is_subset(NegativeContext);
4176
3.76k
  IsFeasible &= !Context.is_subset(NegativeContext);
4177
3.76k
4178
3.76k
  return IsFeasible;
4179
3.76k
}
4180
4181
657
static std::string toString(AssumptionKind Kind) {
4182
657
  switch (Kind) {
4183
657
  case ALIASING:
4184
5
    return "No-aliasing";
4185
657
  case INBOUNDS:
4186
108
    return "Inbounds";
4187
657
  case WRAPPING:
4188
337
    return "No-overflows";
4189
657
  case UNSIGNED:
4190
87
    return "Signed-unsigned";
4191
657
  case COMPLEXITY:
4192
7
    return "Low complexity";
4193
657
  case PROFITABLE:
4194
2
    return "Profitable";
4195
657
  case ERRORBLOCK:
4196
28
    return "No-error";
4197
657
  case INFINITELOOP:
4198
72
    return "Finite loop";
4199
657
  case INVARIANTLOAD:
4200
9
    return "Invariant load";
4201
657
  case DELINEARIZATION:
4202
2
    return "Delinearization";
4203
0
  }
4204
0
  llvm_unreachable("Unknown AssumptionKind!");
4205
0
}
4206
4207
7.94k
bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
4208
7.94k
  if (Sign == AS_ASSUMPTION) {
4209
4.57k
    if (Context.is_subset(Set))
4210
4.40k
      return false;
4211
170
4212
170
    if (AssumedContext.is_subset(Set))
4213
44
      return false;
4214
3.37k
  } else {
4215
3.37k
    if (Set.is_disjoint(Context))
4216
2.35k
      return false;
4217
1.02k
4218
1.02k
    if (Set.is_subset(InvalidContext))
4219
490
      return false;
4220
657
  }
4221
657
  return true;
4222
657
}
4223
4224
bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4225
7.94k
                           AssumptionSign Sign, BasicBlock *BB) {
4226
7.94k
  if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4227
7.29k
    return false;
4228
657
4229
657
  // Do never emit trivial assumptions as they only clutter the output.
4230
657
  if (!PollyRemarksMinimal) {
4231
0
    isl::set Univ;
4232
0
    if (Sign == AS_ASSUMPTION)
4233
0
      Univ = isl::set::universe(Set.get_space());
4234
0
4235
0
    bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
4236
0
                     (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
4237
0
4238
0
    if (IsTrivial)
4239
0
      return false;
4240
657
  }
4241
657
4242
657
  switch (Kind) {
4243
657
  case ALIASING:
4244
5
    AssumptionsAliasing++;
4245
5
    break;
4246
657
  case INBOUNDS:
4247
108
    AssumptionsInbounds++;
4248
108
    break;
4249
657
  case WRAPPING:
4250
337
    AssumptionsWrapping++;
4251
337
    break;
4252
657
  case UNSIGNED:
4253
87
    AssumptionsUnsigned++;
4254
87
    break;
4255
657
  case COMPLEXITY:
4256
7
    AssumptionsComplexity++;
4257
7
    break;
4258
657
  case PROFITABLE:
4259
2
    AssumptionsUnprofitable++;
4260
2
    break;
4261
657
  case ERRORBLOCK:
4262
28
    AssumptionsErrorBlock++;
4263
28
    break;
4264
657
  case INFINITELOOP:
4265
72
    AssumptionsInfiniteLoop++;
4266
72
    break;
4267
657
  case INVARIANTLOAD:
4268
9
    AssumptionsInvariantLoad++;
4269
9
    break;
4270
657
  case DELINEARIZATION:
4271
2
    AssumptionsDelinearization++;
4272
2
    break;
4273
657
  }
4274
657
4275
657
  auto Suffix = Sign == AS_ASSUMPTION ? 
" assumption:\t"126
:
" restriction:\t"531
;
4276
657
  std::string Msg = toString(Kind) + Suffix + Set.to_str();
4277
657
  if (BB)
4278
436
    ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4279
436
             << Msg);
4280
221
  else
4281
221
    ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4282
221
                                        R.getEntry())
4283
221
             << Msg);
4284
657
  return true;
4285
657
}
4286
4287
void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4288
7.94k
                         AssumptionSign Sign, BasicBlock *BB) {
4289
7.94k
  // Simplify the assumptions/restrictions first.
4290
7.94k
  Set = Set.gist_params(getContext());
4291
7.94k
4292
7.94k
  if (!trackAssumption(Kind, Set, Loc, Sign, BB))
4293
7.29k
    return;
4294
657
4295
657
  if (Sign == AS_ASSUMPTION)
4296
126
    AssumedContext = AssumedContext.intersect(Set).coalesce();
4297
531
  else
4298
531
    InvalidContext = InvalidContext.unite(Set).coalesce();
4299
657
}
4300
4301
void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4302
8.11k
                            AssumptionSign Sign, BasicBlock *BB) {
4303
8.11k
  assert((Set.is_params() || BB) &&
4304
8.11k
         "Assumptions without a basic block must be parameter sets");
4305
8.11k
  RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
4306
8.11k
}
4307
4308
1.14k
void Scop::addRecordedAssumptions() {
4309
9.06k
  while (!RecordedAssumptions.empty()) {
4310
7.92k
    Assumption AS = RecordedAssumptions.pop_back_val();
4311
7.92k
4312
7.92k
    if (!AS.BB) {
4313
5.03k
      addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
4314
5.03k
      continue;
4315
5.03k
    }
4316
2.88k
4317
2.88k
    // If the domain was deleted the assumptions are void.
4318
2.88k
    isl_set *Dom = getDomainConditions(AS.BB).release();
4319
2.88k
    if (!Dom)
4320
7
      continue;
4321
2.87k
4322
2.87k
    // If a basic block was given use its domain to simplify the assumption.
4323
2.87k
    // In case of restrictions we know they only have to hold on the domain,
4324
2.87k
    // thus we can intersect them with the domain of the block. However, for
4325
2.87k
    // assumptions the domain has to imply them, thus:
4326
2.87k
    //                     _              _____
4327
2.87k
    //   Dom => S   <==>   A v B   <==>   A - B
4328
2.87k
    //
4329
2.87k
    // To avoid the complement we will register A - B as a restriction not an
4330
2.87k
    // assumption.
4331
2.87k
    isl_set *S = AS.Set.copy();
4332
2.87k
    if (AS.Sign == AS_RESTRICTION)
4333
2.87k
      S = isl_set_params(isl_set_intersect(S, Dom));
4334
0
    else /* (AS.Sign == AS_ASSUMPTION) */
4335
0
      S = isl_set_params(isl_set_subtract(Dom, S));
4336
2.87k
4337
2.87k
    addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
4338
2.87k
  }
4339
1.14k
}
4340
4341
19
void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4342
19
  DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
4343
19
  addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
4344
19
}
4345
4346
3.96k
isl::set Scop::getInvalidContext() const { return InvalidContext; }
4347
4348
494
void Scop::printContext(raw_ostream &OS) const {
4349
494
  OS << "Context:\n";
4350
494
  OS.indent(4) << Context << "\n";
4351
494
4352
494
  OS.indent(4) << "Assumed Context:\n";
4353
494
  OS.indent(4) << AssumedContext << "\n";
4354
494
4355
494
  OS.indent(4) << "Invalid Context:\n";
4356
494
  OS.indent(4) << InvalidContext << "\n";
4357
494
4358
494
  unsigned Dim = 0;
4359
494
  for (const SCEV *Parameter : Parameters)
4360
658
    OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
4361
494
}
4362
4363
494
void Scop::printAliasAssumptions(raw_ostream &OS) const {
4364
494
  int noOfGroups = 0;
4365
494
  for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
4366
90
    if (Pair.second.size() == 0)
4367
29
      noOfGroups += 1;
4368
61
    else
4369
61
      noOfGroups += Pair.second.size();
4370
90
  }
4371
494
4372
494
  OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
4373
494
  if (MinMaxAliasGroups.empty()) {
4374
408
    OS.indent(8) << "n/a\n";
4375
408
    return;
4376
408
  }
4377
86
4378
90
  
for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups)86
{
4379
90
4380
90
    // If the group has no read only accesses print the write accesses.
4381
90
    if (Pair.second.empty()) {
4382
29
      OS.indent(8) << "[[";
4383
68
      for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4384
68
        OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4385
68
           << ">";
4386
68
      }
4387
29
      OS << " ]]\n";
4388
29
    }
4389
90
4390
91
    for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
4391
91
      OS.indent(8) << "[[";
4392
91
      OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
4393
109
      for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4394
109
        OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4395
109
           << ">";
4396
109
      }
4397
91
      OS << " ]]\n";
4398
91
    }
4399
90
  }
4400
86
}
4401
4402
494
void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
4403
494
  OS << "Statements {\n";
4404
494
4405
868
  for (const ScopStmt &Stmt : *this) {
4406
868
    OS.indent(4);
4407
868
    Stmt.print(OS, PrintInstructions);
4408
868
  }
4409
494
4410
494
  OS.indent(4) << "}\n";
4411
494
}
4412
4413
494
void Scop::printArrayInfo(raw_ostream &OS) const {
4414
494
  OS << "Arrays {\n";
4415
494
4416
494
  for (auto &Array : arrays())
4417
1.08k
    Array->print(OS);
4418
494
4419
494
  OS.indent(4) << "}\n";
4420
494
4421
494
  OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4422
494
4423
494
  for (auto &Array : arrays())
4424
1.08k
    Array->print(OS, /* SizeAsPwAff */ true);
4425
494
4426
494
  OS.indent(4) << "}\n";
4427
494
}
4428
4429
494
void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
4430
494
  OS.indent(4) << "Function: " << getFunction().getName() << "\n";
4431
494
  OS.indent(4) << "Region: " << getNameStr() << "\n";
4432
494
  OS.indent(4) << "Max Loop Depth:  " << getMaxLoopDepth() << "\n";
4433
494
  OS.indent(4) << "Invariant Accesses: {\n";
4434
494
  for (const auto &IAClass : InvariantEquivClasses) {
4435
160
    const auto &MAs = IAClass.InvariantAccesses;
4436
160
    if (MAs.empty()) {
4437
1
      OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
4438
159
    } else {
4439
159
      MAs.front()->print(OS);
4440
159
      OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4441
159
                    << "\n";
4442
159
    }
4443
160
  }
4444
494
  OS.indent(4) << "}\n";
4445
494
  printContext(OS.indent(4));
4446
494
  printArrayInfo(OS.indent(4));
4447
494
  printAliasAssumptions(OS);
4448
494
  printStatements(OS.indent(4), PrintInstructions);
4449
494
}
4450
4451
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4452
LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
4453
#endif
4454
4455
32.5k
isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
4456
4457
__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4458
10.1k
                                 bool NonNegative) {
4459
10.1k
  // First try to use the SCEVAffinator to generate a piecewise defined
4460
10.1k
  // affine function from @p E in the context of @p BB. If that tasks becomes to
4461
10.1k
  // complex the affinator might return a nullptr. In such a case we invalidate
4462
10.1k
  // the SCoP and return a dummy value. This way we do not need to add error
4463
10.1k
  // handling code to all users of this function.
4464
10.1k
  auto PWAC = Affinator.getPwAff(E, BB);
4465
10.1k
  if (PWAC.first) {
4466
10.1k
    // TODO: We could use a heuristic and either use:
4467
10.1k
    //         SCEVAffinator::takeNonNegativeAssumption
4468
10.1k
    //       or
4469
10.1k
    //         SCEVAffinator::interpretAsUnsigned
4470
10.1k
    //       to deal with unsigned or "NonNegative" SCEVs.
4471
10.1k
    if (NonNegative)
4472
30
      Affinator.takeNonNegativeAssumption(PWAC);
4473
10.1k
    return PWAC;
4474
10.1k
  }
4475
1
4476
1
  auto DL = BB ? BB->getTerminator()->getDebugLoc() : 
DebugLoc()0
;
4477
1
  invalidate(COMPLEXITY, DL, BB);
4478
1
  return Affinator.getPwAff(SE->getZero(E->getType()), BB);
4479
1
}
4480
4481
12.5k
isl::union_set Scop::getDomains() const {
4482
12.5k
  isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
4483
12.5k
  isl_union_set *Domain = isl_union_set_empty(EmptySpace);
4484
12.5k
4485
12.5k
  for (const ScopStmt &Stmt : *this)
4486
26.9k
    Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
4487
12.5k
4488
12.5k
  return isl::manage(Domain);
4489
12.5k
}
4490
4491
530
isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4492
530
  PWACtx PWAC = getPwAff(E, BB);
4493
530
  return PWAC.first;
4494
530
}
4495
4496
isl::union_map
4497
1.32k
Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4498
1.32k
  isl::union_map Accesses = isl::union_map::empty(getParamSpace());
4499
1.32k
4500
2.67k
  for (ScopStmt &Stmt : *this) {
4501
5.58k
    for (MemoryAccess *MA : Stmt) {
4502
5.58k
      if (!Predicate(*MA))
4503
583
        continue;
4504
5.00k
4505
5.00k
      isl::set Domain = Stmt.getDomain();
4506
5.00k
      isl::map AccessDomain = MA->getAccessRelation();
4507
5.00k
      AccessDomain = AccessDomain.intersect_domain(Domain);
4508
5.00k
      Accesses = Accesses.add_map(AccessDomain);
4509
5.00k
    }
4510
2.67k
  }
4511
1.32k
4512
1.32k
  return Accesses.coalesce();
4513
1.32k
}
4514
4515
7
isl::union_map Scop::getMustWrites() {
4516
23
  return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
4517
7
}
4518
4519
7
isl::union_map Scop::getMayWrites() {
4520
23
  return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
4521
7
}
4522
4523
165
isl::union_map Scop::getWrites() {
4524
899
  return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
4525
165
}
4526
4527
0
isl::union_map Scop::getReads() {
4528
0
  return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
4529
0
}
4530
4531
1.14k
isl::union_map Scop::getAccesses() {
4532
4.64k
  return getAccessesOfType([](MemoryAccess &MA) { return true; });
4533
1.14k
}
4534
4535
0
isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4536
0
  return getAccessesOfType(
4537
0
      [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4538
0
}
4539
4540
// Check whether @p Node is an extension node.
4541
//
4542
// @return true if @p Node is an extension node.
4543
17.0k
isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4544
17.0k
  if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4545
16
    return isl_bool_error;
4546
17.0k
  else
4547
17.0k
    return isl_bool_true;
4548
17.0k
}
4549
4550
1.57k
bool Scop::containsExtensionNode(isl::schedule Schedule) {
4551
1.57k
  return isl_schedule_foreach_schedule_node_top_down(
4552
1.57k
             Schedule.keep(), isNotExtNode, nullptr) == isl_stat_error;
4553
1.57k
}
4554
4555
1.42k
isl::union_map Scop::getSchedule() const {
4556
1.42k
  auto Tree = getScheduleTree();
4557
1.42k
  if (containsExtensionNode(Tree))
4558
4
    return nullptr;
4559
1.42k
4560
1.42k
  return Tree.get_map();
4561
1.42k
}
4562
4563
3.10k
isl::schedule Scop::getScheduleTree() const {
4564
3.10k
  return Schedule.intersect_domain(getDomains());
4565
3.10k
}
4566
4567
104
void Scop::setSchedule(isl::union_map NewSchedule) {
4568
104
  auto S = isl::schedule::from_domain(getDomains());
4569
104
  Schedule = S.insert_partial_schedule(
4570
104
      isl::multi_union_pw_aff::from_union_map(NewSchedule));
4571
104
}
4572
4573
35
void Scop::setScheduleTree(isl::schedule NewSchedule) {
4574
35
  Schedule = NewSchedule;
4575
35
}
4576
4577
7
bool Scop::restrictDomains(isl::union_set Domain) {
4578
7
  bool Changed = false;
4579
19
  for (ScopStmt &Stmt : *this) {
4580
19
    isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4581
19
    isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
4582
19
4583
19
    if (StmtDomain.is_subset(NewStmtDomain))
4584
11
      continue;
4585
8
4586
8
    Changed = true;
4587
8
4588
8
    NewStmtDomain = NewStmtDomain.coalesce();
4589
8
4590
8
    if (NewStmtDomain.is_empty())
4591
7
      Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
4592
1
    else
4593
1
      Stmt.restrictDomain(isl::set(NewStmtDomain));
4594
8
  }
4595
7
  return Changed;
4596
7
}
4597
4598
18.6k
ScalarEvolution *Scop::getSE() const { return SE; }
4599
4600
// Create an isl_multi_union_aff that defines an identity mapping from the
4601
// elements of USet to their N-th dimension.
4602
//
4603
// # Example:
4604
//
4605
//            Domain: { A[i,j]; B[i,j,k] }
4606
//                 N: 1
4607
//
4608
// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4609
//
4610
// @param USet   A union set describing the elements for which to generate a
4611
//               mapping.
4612
// @param N      The dimension to map to.
4613
// @returns      A mapping from USet to its N-th dimension.
4614
1.60k
static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
4615
1.60k
  assert(N >= 0);
4616
1.60k
  assert(USet);
4617
1.60k
  assert(!USet.is_empty());
4618
1.60k
4619
1.60k
  auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
4620
1.60k
4621
2.51k
  auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4622
2.51k
    int Dim = S.dim(isl::dim::set);
4623
2.51k
    auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4624
2.51k
                                                  N, Dim - N);
4625
2.51k
    if (N > 1)
4626
607
      PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
4627
2.51k
4628
2.51k
    Result = Result.add_pw_multi_aff(PMA);
4629
2.51k
    return isl::stat::ok;
4630
2.51k
  };
4631
1.60k
4632
1.60k
  isl::stat Res = USet.foreach_set(Lambda);
4633
1.60k
  (void)Res;
4634
1.60k
4635
1.60k
  assert(Res == isl::stat::ok);
4636
1.60k
4637
1.60k
  return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
4638
1.60k
}
4639
4640
void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
4641
9.05k
                       std::vector<Instruction *> Instructions) {
4642
9.05k
  assert(BB && "Unexpected nullptr!");
4643
9.05k
  Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
4644
9.05k
  auto *Stmt = &Stmts.back();
4645
9.05k
  StmtMap[BB].push_back(Stmt);
4646
9.05k
  for (Instruction *Inst : Instructions) {
4647
6.99k
    assert(!InstStmtMap.count(Inst) &&
4648
6.99k
           "Unexpected statement corresponding to the instruction.");
4649
6.99k
    InstStmtMap[Inst] = Stmt;
4650
6.99k
  }
4651
9.05k
}
4652
4653
void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
4654
121
                       std::vector<Instruction *> Instructions) {
4655
121
  assert(R && "Unexpected nullptr!");
4656
121
  Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
4657
121
  auto *Stmt = &Stmts.back();
4658
121
4659
443
  for (Instruction *Inst : Instructions) {
4660
443
    assert(!InstStmtMap.count(Inst) &&
4661
443
           "Unexpected statement corresponding to the instruction.");
4662
443
    InstStmtMap[Inst] = Stmt;
4663
443
  }
4664
121
4665
336
  for (BasicBlock *BB : R->blocks()) {
4666
336
    StmtMap[BB].push_back(Stmt);
4667
336
    if (BB == R->getEntry())
4668
121
      continue;
4669
556
    
for (Instruction &Inst : *BB)215
{
4670
556
      assert(!InstStmtMap.count(&Inst) &&
4671
556
             "Unexpected statement corresponding to the instruction.");
4672
556
      InstStmtMap[&Inst] = Stmt;
4673
556
    }
4674
215
  }
4675
121
}
4676
4677
ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4678
24
                            isl::set Domain) {
4679
#ifndef NDEBUG
4680
  isl::set SourceDomain = SourceRel.domain();
4681
  isl::set TargetDomain = TargetRel.domain();
4682
  assert(Domain.is_subset(TargetDomain) &&
4683
         "Target access not defined for complete statement domain");
4684
  assert(Domain.is_subset(SourceDomain) &&
4685
         "Source access not defined for complete statement domain");
4686
#endif
4687
  Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4688
24
  CopyStmtsNum++;
4689
24
  return &(Stmts.back());
4690
24
}
4691
4692
1.14k
void Scop::buildSchedule(LoopInfo &LI) {
4693
1.14k
  Loop *L = getLoopSurroundingScop(*this, LI);
4694
1.14k
  LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
4695
1.14k
  buildSchedule(getRegion().getNode(), LoopStack, LI);
4696
1.14k
  assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4697
1.14k
  Schedule = LoopStack[0].Schedule;
4698
1.14k
}
4699
4700
/// To generate a schedule for the elements in a Region we traverse the Region
4701
/// in reverse-post-order and add the contained RegionNodes in traversal order
4702
/// to the schedule of the loop that is currently at the top of the LoopStack.
4703
/// For loop-free codes, this results in a correct sequential ordering.
4704
///
4705
/// Example:
4706
///           bb1(0)
4707
///         /     \.
4708
///      bb2(1)   bb3(2)
4709
///         \    /  \.
4710
///          bb4(3)  bb5(4)
4711
///             \   /
4712
///              bb6(5)
4713
///
4714
/// Including loops requires additional processing. Whenever a loop header is
4715
/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4716
/// from an empty schedule, we first process all RegionNodes that are within
4717
/// this loop and complete the sequential schedule at this loop-level before
4718
/// processing about any other nodes. To implement this
4719
/// loop-nodes-first-processing, the reverse post-order traversal is
4720
/// insufficient. Hence, we additionally check if the traversal yields
4721
/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4722
/// These region-nodes are then queue and only traverse after the all nodes
4723
/// within the current loop have been processed.
4724
2.34k
void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
4725
2.34k
  Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
4726
2.34k
4727
2.34k
  ReversePostOrderTraversal<Region *> RTraversal(R);
4728
2.34k
  std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4729
2.34k
  std::deque<RegionNode *> DelayList;
4730
2.34k
  bool LastRNWaiting = false;
4731
2.34k
4732
2.34k
  // Iterate over the region @p R in reverse post-order but queue
4733
2.34k
  // sub-regions/blocks iff they are not part of the last encountered but not
4734
2.34k
  // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4735
2.34k
  // that we queued the last sub-region/block from the reverse post-order
4736
2.34k
  // iterator. If it is set we have to explore the next sub-region/block from
4737
2.34k
  // the iterator (if any) to guarantee progress. If it is not set we first try
4738
2.34k
  // the next queued sub-region/blocks.
4739
9.10k
  while (!WorkList.empty() || 
!DelayList.empty()2.35k
) {
4740
6.75k
    RegionNode *RN;
4741
6.75k
4742
6.75k
    if ((LastRNWaiting && 
!WorkList.empty()31
) ||
DelayList.empty()6.73k
) {
4743
6.73k
      RN = WorkList.front();
4744
6.73k
      WorkList.pop_front();
4745
6.73k
      LastRNWaiting = false;
4746
6.73k
    } else {
4747
27
      RN = DelayList.front();
4748
27
      DelayList.pop_front();
4749
27
    }
4750
6.75k
4751
6.75k
    Loop *L = getRegionNodeLoop(RN, LI);
4752
6.75k
    if (!contains(L))
4753
1.50k
      L = OuterScopLoop;
4754
6.75k
4755
6.75k
    Loop *LastLoop = LoopStack.back().L;
4756
6.75k
    if (LastLoop != L) {
4757
1.66k
      if (LastLoop && 
!LastLoop->contains(L)502
) {
4758
27
        LastRNWaiting = true;
4759
27
        DelayList.push_back(RN);
4760
27
        continue;
4761
27
      }
4762
1.64k
      LoopStack.push_back({L, nullptr, 0});
4763
1.64k
    }
4764
6.75k
    buildSchedule(RN, LoopStack, LI);
4765
6.73k
  }
4766
2.34k
}
4767
4768
7.87k
void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
4769
7.87k
  if (RN->isSubRegion()) {
4770
2.45k
    auto *LocalRegion = RN->getNodeAs<Region>();
4771
2.45k
    if (!isNonAffineSubRegion(LocalRegion)) {
4772
2.34k
      buildSchedule(LocalRegion, LoopStack, LI);
4773
2.34k
      return;
4774
2.34k
    }
4775
5.53k
  }
4776
5.53k
4777
5.53k
  assert(LoopStack.rbegin() != LoopStack.rend());
4778
5.53k
  auto LoopData = LoopStack.rbegin();
4779
5.53k
  LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
4780
5.53k
4781
5.53k
  for (auto *Stmt : getStmtListFor(RN)) {
4782
2.26k
    isl::union_set UDomain{Stmt->getDomain()};
4783
2.26k
    auto StmtSchedule = isl::schedule::from_domain(UDomain);
4784
2.26k
    LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
4785
2.26k
  }
4786
5.53k
4787
5.53k
  // Check if we just processed the last node in this loop. If we did, finalize
4788
5.53k
  // the loop by:
4789
5.53k
  //
4790
5.53k
  //   - adding new schedule dimensions
4791
5.53k
  //   - folding the resulting schedule into the parent loop schedule
4792
5.53k
  //   - dropping the loop schedule from the LoopStack.
4793
5.53k
  //
4794
5.53k
  // Then continue to check surrounding loops, which might also have been
4795
5.53k
  // completed by this node.
4796
5.53k
  size_t Dimension = LoopStack.size();
4797
7.17k
  while (LoopData->L &&
4798
7.17k
         
LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)5.23k
) {
4799
1.64k
    isl::schedule Schedule = LoopData->Schedule;
4800
1.64k
    auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
4801
1.64k
4802
1.64k
    assert(std::next(LoopData) != LoopStack.rend());
4803
1.64k
    ++LoopData;
4804
1.64k
    --Dimension;
4805
1.64k
4806
1.64k
    if (Schedule) {
4807
1.60k
      isl::union_set Domain = Schedule.get_domain();
4808
1.60k
      isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
4809
1.60k
      Schedule = Schedule.insert_partial_schedule(MUPA);
4810
1.60k
      LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
4811
1.60k
    }
4812
1.64k
4813
1.64k
    LoopData->NumBlocksProcessed += NumBlocksProcessed;
4814
1.64k
  }
4815
5.53k
  // Now pop all loops processed up there from the LoopStack
4816
5.53k
  LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
4817
5.53k
}
4818
4819
6.29k
ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4820
6.29k
  auto StmtMapIt = StmtMap.find(BB);
4821
6.29k
  if (StmtMapIt == StmtMap.end())
4822
74
    return {};
4823
6.22k
  return StmtMapIt->second;
4824
6.22k
}
4825
4826
590
ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
4827
590
  auto *PHI = cast<PHINode>(U.getUser());
4828
590
  BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
4829
590
4830
590
  // If the value is a non-synthesizable from the incoming block, use the
4831
590
  // statement that contains it as user statement.
4832
590
  if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
4833
313
    if (IncomingInst->getParent() == IncomingBB) {
4834
172
      if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
4835
148
        return IncomingStmt;
4836
442
    }
4837
313
  }
4838
442
4839
442
  // Otherwise, use the epilogue/last statement.
4840
442
  return getLastStmtFor(IncomingBB);
4841
442
}
4842
4843
486
ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4844
486
  ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
4845
486
  if (!StmtList.empty())
4846
417
    return StmtList.back();
4847
69
  return nullptr;
4848
69
}
4849
4850
5.53k
ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
4851
5.53k
  if (RN->isSubRegion())
4852
106
    return getStmtListFor(RN->getNodeAs<Region>());
4853
5.42k
  return getStmtListFor(RN->getNodeAs<BasicBlock>());
4854
5.42k
}
4855
4856
106
ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4857
106
  return getStmtListFor(R->getEntry());
4858
106
}
4859
4860
14.1k
int Scop::getRelativeLoopDepth(const Loop *L) const {
4861
14.1k
  if (!L || 
!R.contains(L)12.7k
)
4862
1.53k
    return -1;
4863
12.6k
  // outermostLoopInRegion always returns nullptr for top level regions
4864
12.6k
  if (R.isTopLevelRegion()) {
4865
48
    // LoopInfo's depths start at 1, we start at 0
4866
48
    return L->getLoopDepth() - 1;
4867
12.5k
  } else {
4868
12.5k
    Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4869
12.5k
    assert(OuterLoop);
4870
12.5k
    return L->getLoopDepth() - OuterLoop->getLoopDepth();
4871
12.5k
  }
4872
12.6k
}
4873
4874
247
ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4875
493
  for (auto &SAI : arrays()) {
4876
493
    if (SAI->getName() == BaseName)
4877
246
      return SAI;
4878
493
  }
4879
247
  
return nullptr1
;
4880
247
}
4881
4882
4.69k
void Scop::addAccessData(MemoryAccess *Access) {
4883
4.69k
  const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4884
4.69k
  assert(SAI && "can only use after access relations have been constructed");
4885
4.69k
4886
4.69k
  if (Access->isOriginalValueKind() && 
Access->isRead()671
)
4887
345
    ValueUseAccs[SAI].push_back(Access);
4888
4.35k
  else if (Access->isOriginalAnyPHIKind() && 
Access->isWrite()631
)
4889
410
    PHIIncomingAccs[SAI].push_back(Access);
4890
4.69k
}
4891
4892
462
void Scop::removeAccessData(MemoryAccess *Access) {
4893
462
  if (Access->isOriginalValueKind() && 
Access->isWrite()64
) {
4894
27
    ValueDefAccs.erase(Access->getAccessValue());
4895
435
  } else if (Access->isOriginalValueKind() && 
Access->isRead()37
) {
4896
37
    auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
4897
37
    std::remove(Uses.begin(), Uses.end(), Access);
4898
398
  } else if (Access->isOriginalPHIKind() && 
Access->isRead()10
) {
4899
3
    PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
4900
3
    PHIReadAccs.erase(PHI);
4901
395
  } else if (Access->isOriginalAnyPHIKind() && 
Access->isWrite()7
) {
4902
7
    auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
4903
7
    std::remove(Incomings.begin(), Incomings.end(), Access);
4904
7
  }
4905
462
}
4906
4907
290
MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4908
290
  assert(SAI->isValueKind());
4909
290
4910
290
  Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4911
290
  if (!Val)
4912
3
    return nullptr;
4913
287
4914
287
  return ValueDefAccs.lookup(Val);
4915
287
}
4916
4917
108
ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4918
108
  assert(SAI->isValueKind());
4919
108
  auto It = ValueUseAccs.find(SAI);
4920
108
  if (It == ValueUseAccs.end())
4921
0
    return {};
4922
108
  return It->second;
4923
108
}
4924
4925
184
MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4926
184
  assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4927
184
4928
184
  if (SAI->isExitPHIKind())
4929
0
    return nullptr;
4930
184
4931
184
  PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
4932
184
  return PHIReadAccs.lookup(PHI);
4933
184
}
4934
4935
227
ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4936
227
  assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4937
227
  auto It = PHIIncomingAccs.find(SAI);
4938
227
  if (It == PHIIncomingAccs.end())
4939
0
    return {};
4940
227
  return It->second;
4941
227
}
4942
4943
21.6k
bool Scop::isEscaping(Instruction *Inst) {
4944
21.6k
  assert(contains(Inst) && "The concept of escaping makes only sense for "
4945
21.6k
                           "values defined inside the SCoP");
4946
21.6k
4947
21.6k
  for (Use &Use : Inst->uses()) {
4948
18.7k
    BasicBlock *UserBB = getUseBlock(Use);
4949
18.7k
    if (!contains(UserBB))
4950
61
      return true;
4951
18.7k
4952
18.7k
    // When the SCoP region exit needs to be simplified, PHIs in the region exit
4953
18.7k
    // move to a new basic block such that its incoming blocks are not in the
4954
18.7k
    // SCoP anymore.
4955
18.7k
    if (hasSingleExitEdge() && 
isa<PHINode>(Use.getUser())16.0k
&&
4956
18.7k
        
isExit(cast<PHINode>(Use.getUser())->getParent())1.80k
)
4957
34
      return true;
4958
18.7k
  }
4959
21.6k
  
return false21.5k
;
4960
21.6k
}
4961
4962
897
Scop::ScopStatistics Scop::getStatistics() const {
4963
897
  ScopStatistics Result;
4964
#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4965
  auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4966
4967
  int NumTotalLoops = LoopStat.NumLoops;
4968
  Result.NumBoxedLoops = getBoxedLoops().size();
4969
  Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4970
4971
  for (const ScopStmt &Stmt : *this) {
4972
    isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4973
    bool IsInLoop = Stmt.getNumIterators() >= 1;
4974
    for (MemoryAccess *MA : Stmt) {
4975
      if (!MA->isWrite())
4976
        continue;
4977
4978
      if (MA->isLatestValueKind()) {
4979
        Result.NumValueWrites += 1;
4980
        if (IsInLoop)
4981
          Result.NumValueWritesInLoops += 1;
4982
      }
4983
4984
      if (MA->isLatestAnyPHIKind()) {
4985
        Result.NumPHIWrites += 1;
4986
        if (IsInLoop)
4987
          Result.NumPHIWritesInLoops += 1;
4988
      }
4989
4990
      isl::set AccSet =
4991
          MA->getAccessRelation().intersect_domain(Domain).range();
4992
      if (AccSet.is_singleton()) {
4993
        Result.NumSingletonWrites += 1;
4994
        if (IsInLoop)
4995
          Result.NumSingletonWritesInLoops += 1;
4996
      }
4997
    }
4998
  }
4999
#endif
5000
  return Result;
5001
897
}
5002
5003
42
raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
5004
42
  scop.print(OS, PollyPrintInstructions);
5005
42
  return OS;
5006
42
}
5007
5008
//===----------------------------------------------------------------------===//
5009
1.11k
void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5010
1.11k
  AU.addRequired<LoopInfoWrapperPass>();
5011
1.11k
  AU.addRequired<RegionInfoPass>();
5012
1.11k
  AU.addRequired<DominatorTreeWrapperPass>();
5013
1.11k
  AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
5014
1.11k
  AU.addRequiredTransitive<ScopDetectionWrapperPass>();
5015
1.11k
  AU.addRequired<AAResultsWrapperPass>();
5016
1.11k
  AU.addRequired<AssumptionCacheTracker>();
5017
1.11k
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5018
1.11k
  AU.setPreservesAll();
5019
1.11k
}
5020
5021
void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5022
0
                              Scop::ScopStatistics ScopStats) {
5023
0
  assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5024
0
5025
0
  NumScops++;
5026
0
  NumLoopsInScop += Stats.NumLoops;
5027
0
  MaxNumLoopsInScop =
5028
0
      std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5029
0
5030
0
  if (Stats.MaxDepth == 1)
5031
0
    NumScopsDepthOne++;
5032
0
  else if (Stats.MaxDepth == 2)
5033
0
    NumScopsDepthTwo++;
5034
0
  else if (Stats.MaxDepth == 3)
5035
0
    NumScopsDepthThree++;
5036
0
  else if (Stats.MaxDepth == 4)
5037
0
    NumScopsDepthFour++;
5038
0
  else if (Stats.MaxDepth == 5)
5039
0
    NumScopsDepthFive++;
5040
0
  else
5041
0
    NumScopsDepthLarger++;
5042
0
5043
0
  NumAffineLoops += ScopStats.NumAffineLoops;
5044
0
  NumBoxedLoops += ScopStats.NumBoxedLoops;
5045
0
5046
0
  NumValueWrites += ScopStats.NumValueWrites;
5047
0
  NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5048
0
  NumPHIWrites += ScopStats.NumPHIWrites;
5049
0
  NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5050
0
  NumSingletonWrites += ScopStats.NumSingletonWrites;
5051
0
  NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
5052
0
}
5053
5054
4.09k
bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
5055
4.09k
  auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
5056
4.09k
5057
4.09k
  if (!SD.isMaxRegionInScop(*R))
5058
2.95k
    return false;
5059
1.13k
5060
1.13k
  Function *F = R->getEntry()->getParent();
5061
1.13k
  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5062
1.13k
  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5063
1.13k
  auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5064
1.13k
  auto const &DL = F->getParent()->getDataLayout();
5065
1.13k
  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5066
1.13k
  auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
5067
1.13k
  auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5068
1.13k
5069
1.13k
  ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
5070
1.13k
  S = SB.getScop(); // take ownership of scop object
5071
1.13k
5072
#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
5073
  if (S) {
5074
    ScopDetection::LoopStats Stats =
5075
        ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5076
    updateLoopCountStatistic(Stats, S->getStatistics());
5077
  }
5078
#endif
5079
5080
1.13k
  return false;
5081
1.13k
}
5082
5083
1.50k
void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
5084
1.50k
  if (S)
5085
414
    S->print(OS, PollyPrintInstructions);
5086
1.08k
  else
5087
1.08k
    OS << "Invalid Scop!\n";
5088
1.50k
}
5089
5090
char ScopInfoRegionPass::ID = 0;
5091
5092
0
Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5093
5094
42.1k
INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
5095
42.1k
                      "Polly - Create polyhedral description of Scops", false,
5096
42.1k
                      false);
5097
42.1k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
5098
42.1k
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
5099
42.1k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5100
42.1k
INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5101
42.1k
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
5102
42.1k
INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
5103
42.1k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5104
42.1k
INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
5105
                    "Polly - Create polyhedral description of Scops", false,
5106
                    false)
5107
5108
//===----------------------------------------------------------------------===//
5109
ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5110
                   LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5111
                   AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5112
49
    : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
5113
49
  recompute();
5114
49
}
5115
5116
49
void ScopInfo::recompute() {
5117
49
  RegionToScopMap.clear();
5118
49
  /// Create polyhedral description of scops for all the valid regions of a
5119
49
  /// function.
5120
49
  for (auto &It : SD) {
5121
49
    Region *R = const_cast<Region *>(It);
5122
49
    if (!SD.isMaxRegionInScop(*R))
5123
0
      continue;
5124
49
5125
49
    ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
5126
49
    std::unique_ptr<Scop> S = SB.getScop();
5127
49
    if (!S)
5128
3
      continue;
5129
#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
5130
    ScopDetection::LoopStats Stats =
5131
        ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5132
    updateLoopCountStatistic(Stats, S->getStatistics());
5133
#endif
5134
46
    bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5135
46
    assert(Inserted && "Building Scop for the same region twice!");
5136
46
    (void)Inserted;
5137
46
  }
5138
49
}
5139
5140
bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5141
0
                          FunctionAnalysisManager::Invalidator &Inv) {
5142
0
  // Check whether the analysis, all analyses on functions have been preserved
5143
0
  // or anything we're holding references to is being invalidated
5144
0
  auto PAC = PA.getChecker<ScopInfoAnalysis>();
5145
0
  return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5146
0
         Inv.invalidate<ScopAnalysis>(F, PA) ||
5147
0
         Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5148
0
         Inv.invalidate<LoopAnalysis>(F, PA) ||
5149
0
         Inv.invalidate<AAManager>(F, PA) ||
5150
0
         Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5151
0
         Inv.invalidate<AssumptionAnalysis>(F, PA);
5152
0
}
5153
5154
AnalysisKey ScopInfoAnalysis::Key;
5155
5156
ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5157
0
                                               FunctionAnalysisManager &FAM) {
5158
0
  auto &SD = FAM.getResult<ScopAnalysis>(F);
5159
0
  auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5160
0
  auto &LI = FAM.getResult<LoopAnalysis>(F);
5161
0
  auto &AA = FAM.getResult<AAManager>(F);
5162
0
  auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5163
0
  auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5164
0
  auto &DL = F.getParent()->getDataLayout();
5165
0
  auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5166
0
  return {DL, SD, SE, LI, AA, DT, AC, ORE};
5167
0
}
5168
5169
PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5170
0
                                           FunctionAnalysisManager &FAM) {
5171
0
  auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5172
0
  // Since the legacy PM processes Scops in bottom up, we print them in reverse
5173
0
  // order here to keep the output persistent
5174
0
  for (auto &It : reverse(SI)) {
5175
0
    if (It.second)
5176
0
      It.second->print(Stream, PollyPrintInstructions);
5177
0
    else
5178
0
      Stream << "Invalid Scop!\n";
5179
0
  }
5180
0
  return PreservedAnalyses::all();
5181
0
}
5182
5183
44
void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5184
44
  AU.addRequired<LoopInfoWrapperPass>();
5185
44
  AU.addRequired<RegionInfoPass>();
5186
44
  AU.addRequired<DominatorTreeWrapperPass>();
5187
44
  AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
5188
44
  AU.addRequiredTransitive<ScopDetectionWrapperPass>();
5189
44
  AU.addRequired<AAResultsWrapperPass>();
5190
44
  AU.addRequired<AssumptionCacheTracker>();
5191
44
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5192
44
  AU.setPreservesAll();
5193
44
}
5194
5195
49
bool ScopInfoWrapperPass::runOnFunction(Function &F) {
5196
49
  auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
5197
49
  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5198
49
  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5199