Coverage Report

Created: 2019-02-23 12:57

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