Coverage Report

Created: 2017-06-28 17:40

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/include/polly/ScopInfo.h
Line
Count
Source (jump to first uncovered line)
1
//===------ polly/ScopInfo.h -----------------------------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// Store the polyhedral model representation of a static control flow region,
11
// also called SCoP (Static Control Part).
12
//
13
// This representation is shared among several tools in the polyhedral
14
// community, which are e.g. CLooG, Pluto, Loopo, Graphite.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#ifndef POLLY_SCOP_INFO_H
19
#define POLLY_SCOP_INFO_H
20
21
#include "polly/ScopDetection.h"
22
#include "polly/Support/SCEVAffinator.h"
23
24
#include "llvm/ADT/MapVector.h"
25
#include "llvm/Analysis/RegionPass.h"
26
#include "llvm/IR/PassManager.h"
27
#include "isl/aff.h"
28
#include "isl/ctx.h"
29
#include "isl/set.h"
30
31
#include "isl-noexceptions.h"
32
33
#include <deque>
34
#include <forward_list>
35
36
using namespace llvm;
37
38
namespace llvm {
39
class AssumptionCache;
40
class Loop;
41
class LoopInfo;
42
class PHINode;
43
class ScalarEvolution;
44
class SCEV;
45
class SCEVAddRecExpr;
46
class Type;
47
} // namespace llvm
48
49
struct isl_ctx;
50
struct isl_map;
51
struct isl_basic_map;
52
struct isl_id;
53
struct isl_set;
54
struct isl_union_set;
55
struct isl_union_map;
56
struct isl_space;
57
struct isl_ast_build;
58
struct isl_constraint;
59
struct isl_pw_aff;
60
struct isl_pw_multi_aff;
61
struct isl_schedule;
62
63
namespace polly {
64
65
class MemoryAccess;
66
class Scop;
67
class ScopStmt;
68
class ScopBuilder;
69
70
//===---------------------------------------------------------------------===//
71
72
extern bool UseInstructionNames;
73
74
/// Enumeration of assumptions Polly can take.
75
enum AssumptionKind {
76
  ALIASING,
77
  INBOUNDS,
78
  WRAPPING,
79
  UNSIGNED,
80
  PROFITABLE,
81
  ERRORBLOCK,
82
  COMPLEXITY,
83
  INFINITELOOP,
84
  INVARIANTLOAD,
85
  DELINEARIZATION,
86
};
87
88
/// Enum to distinguish between assumptions and restrictions.
89
enum AssumptionSign { AS_ASSUMPTION, AS_RESTRICTION };
90
91
/// The different memory kinds used in Polly.
92
///
93
/// We distinguish between arrays and various scalar memory objects. We use
94
/// the term ``array'' to describe memory objects that consist of a set of
95
/// individual data elements arranged in a multi-dimensional grid. A scalar
96
/// memory object describes an individual data element and is used to model
97
/// the definition and uses of llvm::Values.
98
///
99
/// The polyhedral model does traditionally not reason about SSA values. To
100
/// reason about llvm::Values we model them "as if" they were zero-dimensional
101
/// memory objects, even though they were not actually allocated in (main)
102
/// memory.  Memory for such objects is only alloca[ed] at CodeGeneration
103
/// time. To relate the memory slots used during code generation with the
104
/// llvm::Values they belong to the new names for these corresponding stack
105
/// slots are derived by appending suffixes (currently ".s2a" and ".phiops")
106
/// to the name of the original llvm::Value. To describe how def/uses are
107
/// modeled exactly we use these suffixes here as well.
108
///
109
/// There are currently four different kinds of memory objects:
110
enum class MemoryKind {
111
  /// MemoryKind::Array: Models a one or multi-dimensional array
112
  ///
113
  /// A memory object that can be described by a multi-dimensional array.
114
  /// Memory objects of this type are used to model actual multi-dimensional
115
  /// arrays as they exist in LLVM-IR, but they are also used to describe
116
  /// other objects:
117
  ///   - A single data element allocated on the stack using 'alloca' is
118
  ///     modeled as a one-dimensional, single-element array.
119
  ///   - A single data element allocated as a global variable is modeled as
120
  ///     one-dimensional, single-element array.
121
  ///   - Certain multi-dimensional arrays with variable size, which in
122
  ///     LLVM-IR are commonly expressed as a single-dimensional access with a
123
  ///     complicated access function, are modeled as multi-dimensional
124
  ///     memory objects (grep for "delinearization").
125
  Array,
126
127
  /// MemoryKind::Value: Models an llvm::Value
128
  ///
129
  /// Memory objects of type MemoryKind::Value are used to model the data flow
130
  /// induced by llvm::Values. For each llvm::Value that is used across
131
  /// BasicBocks one ScopArrayInfo object is created. A single memory WRITE
132
  /// stores the llvm::Value at its definition into the memory object and at
133
  /// each use of the llvm::Value (ignoring trivial intra-block uses) a
134
  /// corresponding READ is added. For instance, the use/def chain of a
135
  /// llvm::Value %V depicted below
136
  ///              ______________________
137
  ///              |DefBB:              |
138
  ///              |  %V = float op ... |
139
  ///              ----------------------
140
  ///               |                  |
141
  /// _________________               _________________
142
  /// |UseBB1:        |               |UseBB2:        |
143
  /// |  use float %V |               |  use float %V |
144
  /// -----------------               -----------------
145
  ///
146
  /// is modeled as if the following memory accesses occurred:
147
  ///
148
  ///                        __________________________
149
  ///                        |entry:                  |
150
  ///                        |  %V.s2a = alloca float |
151
  ///                        --------------------------
152
  ///                                     |
153
  ///                    ___________________________________
154
  ///                    |DefBB:                           |
155
  ///                    |  store %float %V, float* %V.s2a |
156
  ///                    -----------------------------------
157
  ///                           |                   |
158
  /// ____________________________________ ___________________________________
159
  /// |UseBB1:                           | |UseBB2:                          |
160
  /// |  %V.reload1 = load float* %V.s2a | |  %V.reload2 = load float* %V.s2a|
161
  /// |  use float %V.reload1            | |  use float %V.reload2           |
162
  /// ------------------------------------ -----------------------------------
163
  ///
164
  Value,
165
166
  /// MemoryKind::PHI: Models PHI nodes within the SCoP
167
  ///
168
  /// Besides the MemoryKind::Value memory object used to model the normal
169
  /// llvm::Value dependences described above, PHI nodes require an additional
170
  /// memory object of type MemoryKind::PHI to describe the forwarding of values
171
  /// to
172
  /// the PHI node.
173
  ///
174
  /// As an example, a PHIInst instructions
175
  ///
176
  /// %PHI = phi float [ %Val1, %IncomingBlock1 ], [ %Val2, %IncomingBlock2 ]
177
  ///
178
  /// is modeled as if the accesses occurred this way:
179
  ///
180
  ///                    _______________________________
181
  ///                    |entry:                       |
182
  ///                    |  %PHI.phiops = alloca float |
183
  ///                    -------------------------------
184
  ///                           |              |
185
  /// __________________________________  __________________________________
186
  /// |IncomingBlock1:                 |  |IncomingBlock2:                 |
187
  /// |  ...                           |  |  ...                           |
188
  /// |  store float %Val1 %PHI.phiops |  |  store float %Val2 %PHI.phiops |
189
  /// |  br label % JoinBlock          |  |  br label %JoinBlock           |
190
  /// ----------------------------------  ----------------------------------
191
  ///                             \            /
192
  ///                              \          /
193
  ///               _________________________________________
194
  ///               |JoinBlock:                             |
195
  ///               |  %PHI = load float, float* PHI.phiops |
196
  ///               -----------------------------------------
197
  ///
198
  /// Note that there can also be a scalar write access for %PHI if used in a
199
  /// different BasicBlock, i.e. there can be a memory object %PHI.phiops as
200
  /// well as a memory object %PHI.s2a.
201
  PHI,
202
203
  /// MemoryKind::ExitPHI: Models PHI nodes in the SCoP's exit block
204
  ///
205
  /// For PHI nodes in the Scop's exit block a special memory object kind is
206
  /// used. The modeling used is identical to MemoryKind::PHI, with the
207
  /// exception
208
  /// that there are no READs from these memory objects. The PHINode's
209
  /// llvm::Value is treated as a value escaping the SCoP. WRITE accesses
210
  /// write directly to the escaping value's ".s2a" alloca.
211
  ExitPHI
212
};
213
214
/// Maps from a loop to the affine function expressing its backedge taken count.
215
/// The backedge taken count already enough to express iteration domain as we
216
/// only allow loops with canonical induction variable.
217
/// A canonical induction variable is:
218
/// an integer recurrence that starts at 0 and increments by one each time
219
/// through the loop.
220
typedef std::map<const Loop *, const SCEV *> LoopBoundMapType;
221
222
typedef std::vector<std::unique_ptr<MemoryAccess>> AccFuncVector;
223
224
/// A class to store information about arrays in the SCoP.
225
///
226
/// Objects are accessible via the ScoP, MemoryAccess or the id associated with
227
/// the MemoryAccess access function.
228
///
229
class ScopArrayInfo {
230
public:
231
  /// Construct a ScopArrayInfo object.
232
  ///
233
  /// @param BasePtr        The array base pointer.
234
  /// @param ElementType    The type of the elements stored in the array.
235
  /// @param IslCtx         The isl context used to create the base pointer id.
236
  /// @param DimensionSizes A vector containing the size of each dimension.
237
  /// @param Kind           The kind of the array object.
238
  /// @param DL             The data layout of the module.
239
  /// @param S              The scop this array object belongs to.
240
  /// @param BaseName       The optional name of this memory reference.
241
  ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *IslCtx,
242
                ArrayRef<const SCEV *> DimensionSizes, MemoryKind Kind,
243
                const DataLayout &DL, Scop *S, const char *BaseName = nullptr);
244
245
  ///  Update the element type of the ScopArrayInfo object.
246
  ///
247
  ///  Memory accesses referencing this ScopArrayInfo object may use
248
  ///  different element sizes. This function ensures the canonical element type
249
  ///  stored is small enough to model accesses to the current element type as
250
  ///  well as to @p NewElementType.
251
  ///
252
  ///  @param NewElementType An element type that is used to access this array.
253
  void updateElementType(Type *NewElementType);
254
255
  ///  Update the sizes of the ScopArrayInfo object.
256
  ///
257
  ///  A ScopArrayInfo object may be created without all outer dimensions being
258
  ///  available. This function is called when new memory accesses are added for
259
  ///  this ScopArrayInfo object. It verifies that sizes are compatible and adds
260
  ///  additional outer array dimensions, if needed.
261
  ///
262
  ///  @param Sizes       A vector of array sizes where the rightmost array
263
  ///                     sizes need to match the innermost array sizes already
264
  ///                     defined in SAI.
265
  ///  @param CheckConsistency Update sizes, even if new sizes are inconsistent
266
  ///                          with old sizes
267
  bool updateSizes(ArrayRef<const SCEV *> Sizes, bool CheckConsistency = true);
268
269
  /// Make the ScopArrayInfo model a Fortran array.
270
  /// It receives the Fortran array descriptor and stores this.
271
  /// It also adds a piecewise expression for the outermost dimension
272
  /// since this information is available for Fortran arrays at runtime.
273
  void applyAndSetFAD(Value *FAD);
274
275
  /// Destructor to free the isl id of the base pointer.
276
  ~ScopArrayInfo();
277
278
  /// Set the base pointer to @p BP.
279
5
  void setBasePtr(Value *BP) { BasePtr = BP; }
280
281
  /// Return the base pointer.
282
4.86k
  Value *getBasePtr() const { return BasePtr; }
283
284
  /// For indirect accesses return the origin SAI of the BP, else null.
285
2
  const ScopArrayInfo *getBasePtrOriginSAI() const { return BasePtrOriginSAI; }
286
287
  /// The set of derived indirect SAIs for this origin SAI.
288
110
  const SmallSetVector<ScopArrayInfo *, 2> &getDerivedSAIs() const {
289
110
    return DerivedSAIs;
290
110
  }
291
292
  /// Return the number of dimensions.
293
17.6k
  unsigned getNumberOfDimensions() const {
294
17.6k
    if (
Kind == MemoryKind::PHI || 17.6k
Kind == MemoryKind::ExitPHI16.6k
||
295
16.3k
        Kind == MemoryKind::Value)
296
3.12k
      return 0;
297
14.5k
    return DimensionSizes.size();
298
17.6k
  }
299
300
  /// Return the size of dimension @p dim as SCEV*.
301
  //
302
  //  Scalars do not have array dimensions and the first dimension of
303
  //  a (possibly multi-dimensional) array also does not carry any size
304
  //  information, in case the array is not newly created.
305
1.78k
  const SCEV *getDimensionSize(unsigned Dim) const {
306
1.78k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
307
1.78k
    return DimensionSizes[Dim];
308
1.78k
  }
309
310
  /// Return the size of dimension @p dim as isl_pw_aff.
311
  //
312
  //  Scalars do not have array dimensions and the first dimension of
313
  //  a (possibly multi-dimensional) array also does not carry any size
314
  //  information, in case the array is not newly created.
315
2.29k
  __isl_give isl_pw_aff *getDimensionSizePw(unsigned Dim) const {
316
2.29k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
317
2.29k
    return isl_pw_aff_copy(DimensionSizesPw[Dim]);
318
2.29k
  }
319
320
  /// Get the canonical element type of this array.
321
  ///
322
  /// @returns The canonical element type of this array.
323
2.91k
  Type *getElementType() const { return ElementType; }
324
325
  /// Get element size in bytes.
326
  int getElemSizeInBytes() const;
327
328
  /// Get the name of this memory reference.
329
  std::string getName() const;
330
331
  /// Return the isl id for the base pointer.
332
  __isl_give isl_id *getBasePtrId() const;
333
334
  /// Return what kind of memory this represents.
335
1.19k
  MemoryKind getKind() const { return Kind; }
336
337
  /// Is this array info modeling an llvm::Value?
338
141
  bool isValueKind() const { return Kind == MemoryKind::Value; }
339
340
  /// Is this array info modeling special PHI node memory?
341
  ///
342
  /// During code generation of PHI nodes, there is a need for two kinds of
343
  /// virtual storage. The normal one as it is used for all scalar dependences,
344
  /// where the result of the PHI node is stored and later loaded from as well
345
  /// as a second one where the incoming values of the PHI nodes are stored
346
  /// into and reloaded when the PHI is executed. As both memories use the
347
  /// original PHI node as virtual base pointer, we have this additional
348
  /// attribute to distinguish the PHI node specific array modeling from the
349
  /// normal scalar array modeling.
350
476
  bool isPHIKind() const { return Kind == MemoryKind::PHI; }
351
352
  /// Is this array info modeling an MemoryKind::ExitPHI?
353
124
  bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
354
355
  /// Is this array info modeling an array?
356
53
  bool isArrayKind() const { return Kind == MemoryKind::Array; }
357
358
  /// Dump a readable representation to stderr.
359
  void dump() const;
360
361
  /// Print a readable representation to @p OS.
362
  ///
363
  /// @param SizeAsPwAff Print the size as isl_pw_aff
364
  void print(raw_ostream &OS, bool SizeAsPwAff = false) const;
365
366
  /// Access the ScopArrayInfo associated with an access function.
367
  static const ScopArrayInfo *
368
  getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA);
369
370
  /// Access the ScopArrayInfo associated with an isl Id.
371
  static const ScopArrayInfo *getFromId(__isl_take isl_id *Id);
372
373
  /// Get the space of this array access.
374
  __isl_give isl_space *getSpace() const;
375
376
  /// If the array is read only
377
  bool isReadOnly();
378
379
  /// Verify that @p Array is compatible to this ScopArrayInfo.
380
  ///
381
  /// Two arrays are compatible if their dimensionality, the sizes of their
382
  /// dimensions, and their element sizes match.
383
  ///
384
  /// @param Array The array to compare against.
385
  ///
386
  /// @returns True, if the arrays are compatible, False otherwise.
387
  bool isCompatibleWith(const ScopArrayInfo *Array) const;
388
389
private:
390
88
  void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
391
88
    DerivedSAIs.insert(DerivedSAI);
392
88
  }
393
394
  /// For indirect accesses this is the SAI of the BP origin.
395
  const ScopArrayInfo *BasePtrOriginSAI;
396
397
  /// For origin SAIs the set of derived indirect SAIs.
398
  SmallSetVector<ScopArrayInfo *, 2> DerivedSAIs;
399
400
  /// The base pointer.
401
  AssertingVH<Value> BasePtr;
402
403
  /// The canonical element type of this array.
404
  ///
405
  /// The canonical element type describes the minimal accessible element in
406
  /// this array. Not all elements accessed, need to be of the very same type,
407
  /// but the allocation size of the type of the elements loaded/stored from/to
408
  /// this array needs to be a multiple of the allocation size of the canonical
409
  /// type.
410
  Type *ElementType;
411
412
  /// The isl id for the base pointer.
413
  isl_id *Id;
414
415
  /// The sizes of each dimension as SCEV*.
416
  SmallVector<const SCEV *, 4> DimensionSizes;
417
418
  /// The sizes of each dimension as isl_pw_aff.
419
  SmallVector<isl_pw_aff *, 4> DimensionSizesPw;
420
421
  /// The type of this scop array info object.
422
  ///
423
  /// We distinguish between SCALAR, PHI and ARRAY objects.
424
  MemoryKind Kind;
425
426
  /// The data layout of the module.
427
  const DataLayout &DL;
428
429
  /// The scop this SAI object belongs to.
430
  Scop &S;
431
432
  /// If this array models a Fortran array, then this points
433
  /// to the Fortran array descriptor.
434
  Value *FAD;
435
};
436
437
/// Represent memory accesses in statements.
438
class MemoryAccess {
439
  friend class Scop;
440
  friend class ScopStmt;
441
442
public:
443
  /// The access type of a memory access
444
  ///
445
  /// There are three kind of access types:
446
  ///
447
  /// * A read access
448
  ///
449
  /// A certain set of memory locations are read and may be used for internal
450
  /// calculations.
451
  ///
452
  /// * A must-write access
453
  ///
454
  /// A certain set of memory locations is definitely written. The old value is
455
  /// replaced by a newly calculated value. The old value is not read or used at
456
  /// all.
457
  ///
458
  /// * A may-write access
459
  ///
460
  /// A certain set of memory locations may be written. The memory location may
461
  /// contain a new value if there is actually a write or the old value may
462
  /// remain, if no write happens.
463
  enum AccessType {
464
    READ = 0x1,
465
    MUST_WRITE = 0x2,
466
    MAY_WRITE = 0x3,
467
  };
468
469
  /// Reduction access type
470
  ///
471
  /// Commutative and associative binary operations suitable for reductions
472
  enum ReductionType {
473
    RT_NONE, ///< Indicate no reduction at all
474
    RT_ADD,  ///< Addition
475
    RT_MUL,  ///< Multiplication
476
    RT_BOR,  ///< Bitwise Or
477
    RT_BXOR, ///< Bitwise XOr
478
    RT_BAND, ///< Bitwise And
479
  };
480
481
private:
482
  MemoryAccess(const MemoryAccess &) = delete;
483
  const MemoryAccess &operator=(const MemoryAccess &) = delete;
484
485
  /// A unique identifier for this memory access.
486
  ///
487
  /// The identifier is unique between all memory accesses belonging to the same
488
  /// scop statement.
489
  isl_id *Id;
490
491
  /// What is modeled by this MemoryAccess.
492
  /// @see MemoryKind
493
  MemoryKind Kind;
494
495
  /// Whether it a reading or writing access, and if writing, whether it
496
  /// is conditional (MAY_WRITE).
497
  enum AccessType AccType;
498
499
  /// Reduction type for reduction like accesses, RT_NONE otherwise
500
  ///
501
  /// An access is reduction like if it is part of a load-store chain in which
502
  /// both access the same memory location (use the same LLVM-IR value
503
  /// as pointer reference). Furthermore, between the load and the store there
504
  /// is exactly one binary operator which is known to be associative and
505
  /// commutative.
506
  ///
507
  /// TODO:
508
  ///
509
  /// We can later lift the constraint that the same LLVM-IR value defines the
510
  /// memory location to handle scops such as the following:
511
  ///
512
  ///    for i
513
  ///      for j
514
  ///        sum[i+j] = sum[i] + 3;
515
  ///
516
  /// Here not all iterations access the same memory location, but iterations
517
  /// for which j = 0 holds do. After lifting the equality check in ScopBuilder,
518
  /// subsequent transformations do not only need check if a statement is
519
  /// reduction like, but they also need to verify that that the reduction
520
  /// property is only exploited for statement instances that load from and
521
  /// store to the same data location. Doing so at dependence analysis time
522
  /// could allow us to handle the above example.
523
  ReductionType RedType = RT_NONE;
524
525
  /// Parent ScopStmt of this access.
526
  ScopStmt *Statement;
527
528
  /// The domain under which this access is not modeled precisely.
529
  ///
530
  /// The invalid domain for an access describes all parameter combinations
531
  /// under which the statement looks to be executed but is in fact not because
532
  /// some assumption/restriction makes the access invalid.
533
  isl_set *InvalidDomain;
534
535
  // Properties describing the accessed array.
536
  // TODO: It might be possible to move them to ScopArrayInfo.
537
  // @{
538
539
  /// The base address (e.g., A for A[i+j]).
540
  ///
541
  /// The #BaseAddr of a memory access of kind MemoryKind::Array is the base
542
  /// pointer of the memory access.
543
  /// The #BaseAddr of a memory access of kind MemoryKind::PHI or
544
  /// MemoryKind::ExitPHI is the PHI node itself.
545
  /// The #BaseAddr of a memory access of kind MemoryKind::Value is the
546
  /// instruction defining the value.
547
  AssertingVH<Value> BaseAddr;
548
549
  /// Type a single array element wrt. this access.
550
  Type *ElementType;
551
552
  /// Size of each dimension of the accessed array.
553
  SmallVector<const SCEV *, 4> Sizes;
554
  // @}
555
556
  // Properties describing the accessed element.
557
  // @{
558
559
  /// The access instruction of this memory access.
560
  ///
561
  /// For memory accesses of kind MemoryKind::Array the access instruction is
562
  /// the Load or Store instruction performing the access.
563
  ///
564
  /// For memory accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI the
565
  /// access instruction of a load access is the PHI instruction. The access
566
  /// instruction of a PHI-store is the incoming's block's terminator
567
  /// instruction.
568
  ///
569
  /// For memory accesses of kind MemoryKind::Value the access instruction of a
570
  /// load access is nullptr because generally there can be multiple
571
  /// instructions in the statement using the same llvm::Value. The access
572
  /// instruction of a write access is the instruction that defines the
573
  /// llvm::Value.
574
  Instruction *AccessInstruction;
575
576
  /// Incoming block and value of a PHINode.
577
  SmallVector<std::pair<BasicBlock *, Value *>, 4> Incoming;
578
579
  /// The value associated with this memory access.
580
  ///
581
  ///  - For array memory accesses (MemoryKind::Array) it is the loaded result
582
  ///    or the stored value. If the access instruction is a memory intrinsic it
583
  ///    the access value is also the memory intrinsic.
584
  ///  - For accesses of kind MemoryKind::Value it is the access instruction
585
  ///    itself.
586
  ///  - For accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI it is the
587
  ///    PHI node itself (for both, READ and WRITE accesses).
588
  ///
589
  AssertingVH<Value> AccessValue;
590
591
  /// Are all the subscripts affine expression?
592
  bool IsAffine;
593
594
  /// Subscript expression for each dimension.
595
  SmallVector<const SCEV *, 4> Subscripts;
596
597
  /// Relation from statement instances to the accessed array elements.
598
  ///
599
  /// In the common case this relation is a function that maps a set of loop
600
  /// indices to the memory address from which a value is loaded/stored:
601
  ///
602
  ///      for i
603
  ///        for j
604
  ///    S:     A[i + 3 j] = ...
605
  ///
606
  ///    => { S[i,j] -> A[i + 3j] }
607
  ///
608
  /// In case the exact access function is not known, the access relation may
609
  /// also be a one to all mapping { S[i,j] -> A[o] } describing that any
610
  /// element accessible through A might be accessed.
611
  ///
612
  /// In case of an access to a larger element belonging to an array that also
613
  /// contains smaller elements, the access relation models the larger access
614
  /// with multiple smaller accesses of the size of the minimal array element
615
  /// type:
616
  ///
617
  ///      short *A;
618
  ///
619
  ///      for i
620
  ///    S:     A[i] = *((double*)&A[4 * i]);
621
  ///
622
  ///    => { S[i] -> A[i]; S[i] -> A[o] : 4i <= o <= 4i + 3 }
623
  isl_map *AccessRelation;
624
625
  /// Updated access relation read from JSCOP file.
626
  isl_map *NewAccessRelation;
627
628
  /// Fortran arrays whose sizes are not statically known are stored in terms
629
  /// of a descriptor struct. This maintains a raw pointer to the memory,
630
  /// along with auxiliary fields with information such as dimensions.
631
  /// We hold a reference to the descriptor corresponding to a MemoryAccess
632
  /// into a Fortran array. FAD for "Fortran Array Descriptor"
633
  AssertingVH<Value> FAD;
634
  // @}
635
636
  __isl_give isl_basic_map *createBasicAccessMap(ScopStmt *Statement);
637
638
  void assumeNoOutOfBound();
639
640
  /// Compute bounds on an over approximated  access relation.
641
  ///
642
  /// @param ElementSize The size of one element accessed.
643
  void computeBoundsOnAccessRelation(unsigned ElementSize);
644
645
  /// Get the original access function as read from IR.
646
  __isl_give isl_map *getOriginalAccessRelation() const;
647
648
  /// Return the space in which the access relation lives in.
649
  __isl_give isl_space *getOriginalAccessRelationSpace() const;
650
651
  /// Get the new access function imported or set by a pass
652
  __isl_give isl_map *getNewAccessRelation() const;
653
654
  /// Fold the memory access to consider parametric offsets
655
  ///
656
  /// To recover memory accesses with array size parameters in the subscript
657
  /// expression we post-process the delinearization results.
658
  ///
659
  /// We would normally recover from an access A[exp0(i) * N + exp1(i)] into an
660
  /// array A[][N] the 2D access A[exp0(i)][exp1(i)]. However, another valid
661
  /// delinearization is A[exp0(i) - 1][exp1(i) + N] which - depending on the
662
  /// range of exp1(i) - may be preferable. Specifically, for cases where we
663
  /// know exp1(i) is negative, we want to choose the latter expression.
664
  ///
665
  /// As we commonly do not have any information about the range of exp1(i),
666
  /// we do not choose one of the two options, but instead create a piecewise
667
  /// access function that adds the (-1, N) offsets as soon as exp1(i) becomes
668
  /// negative. For a 2D array such an access function is created by applying
669
  /// the piecewise map:
670
  ///
671
  /// [i,j] -> [i, j] :      j >= 0
672
  /// [i,j] -> [i-1, j+N] :  j <  0
673
  ///
674
  /// We can generalize this mapping to arbitrary dimensions by applying this
675
  /// piecewise mapping pairwise from the rightmost to the leftmost access
676
  /// dimension. It would also be possible to cover a wider range by introducing
677
  /// more cases and adding multiple of Ns to these cases. However, this has
678
  /// not yet been necessary.
679
  /// The introduction of different cases necessarily complicates the memory
680
  /// access function, but cases that can be statically proven to not happen
681
  /// will be eliminated later on.
682
  void foldAccessRelation();
683
684
  /// Create the access relation for the underlying memory intrinsic.
685
  void buildMemIntrinsicAccessRelation();
686
687
  /// Assemble the access relation from all available information.
688
  ///
689
  /// In particular, used the information passes in the constructor and the
690
  /// parent ScopStmt set by setStatment().
691
  ///
692
  /// @param SAI Info object for the accessed array.
693
  void buildAccessRelation(const ScopArrayInfo *SAI);
694
695
  /// Carry index overflows of dimensions with constant size to the next higher
696
  /// dimension.
697
  ///
698
  /// For dimensions that have constant size, modulo the index by the size and
699
  /// add up the carry (floored division) to the next higher dimension. This is
700
  /// how overflow is defined in row-major order.
701
  /// It happens e.g. when ScalarEvolution computes the offset to the base
702
  /// pointer and would algebraically sum up all lower dimensions' indices of
703
  /// constant size.
704
  ///
705
  /// Example:
706
  ///   float (*A)[4];
707
  ///   A[1][6] -> A[2][2]
708
  void wrapConstantDimensions();
709
710
public:
711
  /// Create a new MemoryAccess.
712
  ///
713
  /// @param Stmt       The parent statement.
714
  /// @param AccessInst The instruction doing the access.
715
  /// @param BaseAddr   The accessed array's address.
716
  /// @param ElemType   The type of the accessed array elements.
717
  /// @param AccType    Whether read or write access.
718
  /// @param IsAffine   Whether the subscripts are affine expressions.
719
  /// @param Kind       The kind of memory accessed.
720
  /// @param Subscripts Subscript expressions
721
  /// @param Sizes      Dimension lengths of the accessed array.
722
  MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, AccessType AccType,
723
               Value *BaseAddress, Type *ElemType, bool Affine,
724
               ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
725
               Value *AccessValue, MemoryKind Kind);
726
727
  /// Create a new MemoryAccess that corresponds to @p AccRel.
728
  ///
729
  /// Along with @p Stmt and @p AccType it uses information about dimension
730
  /// lengths of the accessed array, the type of the accessed array elements,
731
  /// the name of the accessed array that is derived from the object accessible
732
  /// via @p AccRel.
733
  ///
734
  /// @param Stmt       The parent statement.
735
  /// @param AccType    Whether read or write access.
736
  /// @param AccRel     The access relation that describes the memory access.
737
  MemoryAccess(ScopStmt *Stmt, AccessType AccType, __isl_take isl_map *AccRel);
738
739
  ~MemoryAccess();
740
741
  /// Add a new incoming block/value pairs for this PHI/ExitPHI access.
742
  ///
743
  /// @param IncomingBlock The PHI's incoming block.
744
  /// @param IncomingValue The value when reaching the PHI from the @p
745
  ///                      IncomingBlock.
746
415
  void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
747
415
    assert(!isRead());
748
415
    assert(isAnyPHIKind());
749
415
    Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
750
415
  }
751
752
  /// Return the list of possible PHI/ExitPHI values.
753
  ///
754
  /// After code generation moves some PHIs around during region simplification,
755
  /// we cannot reliably locate the original PHI node and its incoming values
756
  /// anymore. For this reason we remember these explicitly for all PHI-kind
757
  /// accesses.
758
151
  ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
759
151
    assert(isAnyPHIKind());
760
151
    return Incoming;
761
151
  }
762
763
  /// Get the type of a memory access.
764
0
  enum AccessType getType() { return AccType; }
765
766
  /// Is this a reduction like access?
767
2.52k
  bool isReductionLike() const { return RedType != RT_NONE; }
768
769
  /// Is this a read memory access?
770
15.4k
  bool isRead() const { return AccType == MemoryAccess::READ; }
771
772
  /// Is this a must-write memory access?
773
4.38k
  bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
774
775
  /// Is this a may-write memory access?
776
3.62k
  bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
777
778
  /// Is this a write memory access?
779
4.24k
  bool isWrite() const 
{ return isMustWrite() || 4.24k
isMayWrite()2.61k
; }
780
781
  /// Is this a memory intrinsic access (memcpy, memset, memmove)?
782
541
  bool isMemoryIntrinsic() const {
783
541
    return isa<MemIntrinsic>(getAccessInstruction());
784
541
  }
785
786
  /// Check if a new access relation was imported or set by a pass.
787
18.2k
  bool hasNewAccessRelation() const { return NewAccessRelation; }
788
789
  /// Return the newest access relation of this access.
790
  ///
791
  /// There are two possibilities:
792
  ///   1) The original access relation read from the LLVM-IR.
793
  ///   2) A new access relation imported from a json file or set by another
794
  ///      pass (e.g., for privatization).
795
  ///
796
  /// As 2) is by construction "newer" than 1) we return the new access
797
  /// relation if present.
798
  ///
799
14.0k
  __isl_give isl_map *getLatestAccessRelation() const {
800
156
    return hasNewAccessRelation() ? getNewAccessRelation()
801
13.9k
                                  : getOriginalAccessRelation();
802
14.0k
  }
803
804
  /// Old name of getLatestAccessRelation().
805
13.9k
  __isl_give isl_map *getAccessRelation() const {
806
13.9k
    return getLatestAccessRelation();
807
13.9k
  }
808
809
  /// Get an isl map describing the memory address accessed.
810
  ///
811
  /// In most cases the memory address accessed is well described by the access
812
  /// relation obtained with getAccessRelation. However, in case of arrays
813
  /// accessed with types of different size the access relation maps one access
814
  /// to multiple smaller address locations. This method returns an isl map that
815
  /// relates each dynamic statement instance to the unique memory location
816
  /// that is loaded from / stored to.
817
  ///
818
  /// For an access relation { S[i] -> A[o] : 4i <= o <= 4i + 3 } this method
819
  /// will return the address function { S[i] -> A[4i] }.
820
  ///
821
  /// @returns The address function for this memory access.
822
  __isl_give isl_map *getAddressFunction() const;
823
824
  /// Return the access relation after the schedule was applied.
825
  __isl_give isl_pw_multi_aff *
826
  applyScheduleToAccessRelation(__isl_take isl_union_map *Schedule) const;
827
828
  /// Get an isl string representing the access function read from IR.
829
  std::string getOriginalAccessRelationStr() const;
830
831
  /// Get an isl string representing a new access function, if available.
832
  std::string getNewAccessRelationStr() const;
833
834
  /// Get the original base address of this access (e.g. A for A[i+j]) when
835
  /// detected.
836
  ///
837
  /// This adress may differ from the base address referenced by the Original
838
  /// ScopArrayInfo to which this array belongs, as this memory access may
839
  /// have been unified to a ScopArray which has a different but identically
840
  /// valued base pointer in case invariant load hoisting is enabled.
841
5.72k
  Value *getOriginalBaseAddr() const { return BaseAddr; }
842
843
  /// Get the detection-time base array isl_id for this access.
844
  __isl_give isl_id *getOriginalArrayId() const;
845
846
  /// Get the base array isl_id for this access, modifiable through
847
  /// setNewAccessRelation().
848
  __isl_give isl_id *getLatestArrayId() const;
849
850
  /// Old name of getOriginalArrayId().
851
16.3k
  __isl_give isl_id *getArrayId() const { return getOriginalArrayId(); }
852
853
  /// Get the detection-time ScopArrayInfo object for the base address.
854
  const ScopArrayInfo *getOriginalScopArrayInfo() const;
855
856
  /// Get the ScopArrayInfo object for the base address, or the one set
857
  /// by setNewAccessRelation().
858
  const ScopArrayInfo *getLatestScopArrayInfo() const;
859
860
  /// Legacy name of getOriginalScopArrayInfo().
861
16.3k
  const ScopArrayInfo *getScopArrayInfo() const {
862
16.3k
    return getOriginalScopArrayInfo();
863
16.3k
  }
864
865
  /// Return a string representation of the access's reduction type.
866
  const std::string getReductionOperatorStr() const;
867
868
  /// Return a string representation of the reduction type @p RT.
869
  static const std::string getReductionOperatorStr(ReductionType RT);
870
871
  /// Return the element type of the accessed array wrt. this access.
872
7.89k
  Type *getElementType() const { return ElementType; }
873
874
  /// Return the access value of this memory access.
875
1.96k
  Value *getAccessValue() const { return AccessValue; }
876
877
  /// Return the access instruction of this memory access.
878
38.0k
  Instruction *getAccessInstruction() const { return AccessInstruction; }
879
880
  /// Return the number of access function subscript.
881
5
  unsigned getNumSubscripts() const { return Subscripts.size(); }
882
883
  /// Return the access function subscript in the dimension @p Dim.
884
2.51k
  const SCEV *getSubscript(unsigned Dim) const { return Subscripts[Dim]; }
885
886
  /// Compute the isl representation for the SCEV @p E wrt. this access.
887
  ///
888
  /// Note that this function will also adjust the invalid context accordingly.
889
  __isl_give isl_pw_aff *getPwAff(const SCEV *E);
890
891
  /// Get the invalid domain for this access.
892
345
  __isl_give isl_set *getInvalidDomain() const {
893
345
    return isl_set_copy(InvalidDomain);
894
345
  }
895
896
  /// Get the invalid context for this access.
897
345
  __isl_give isl_set *getInvalidContext() const {
898
345
    return isl_set_params(getInvalidDomain());
899
345
  }
900
901
  /// Get the stride of this memory access in the specified Schedule. Schedule
902
  /// is a map from the statement to a schedule where the innermost dimension is
903
  /// the dimension of the innermost loop containing the statement.
904
  __isl_give isl_set *getStride(__isl_take const isl_map *Schedule) const;
905
906
  /// Get the FortranArrayDescriptor corresponding to this memory access if
907
  /// it exists, and nullptr otherwise.
908
4.40k
  Value *getFortranArrayDescriptor() const { return this->FAD; };
909
910
  /// Is the stride of the access equal to a certain width? Schedule is a map
911
  /// from the statement to a schedule where the innermost dimension is the
912
  /// dimension of the innermost loop containing the statement.
913
  bool isStrideX(__isl_take const isl_map *Schedule, int StrideWidth) const;
914
915
  /// Is consecutive memory accessed for a given statement instance set?
916
  /// Schedule is a map from the statement to a schedule where the innermost
917
  /// dimension is the dimension of the innermost loop containing the
918
  /// statement.
919
  bool isStrideOne(__isl_take const isl_map *Schedule) const;
920
921
  /// Is always the same memory accessed for a given statement instance set?
922
  /// Schedule is a map from the statement to a schedule where the innermost
923
  /// dimension is the dimension of the innermost loop containing the
924
  /// statement.
925
  bool isStrideZero(__isl_take const isl_map *Schedule) const;
926
927
  /// Return the kind when this access was first detected.
928
34.8k
  MemoryKind getOriginalKind() const {
929
34.8k
    assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
930
34.8k
           getOriginalScopArrayInfo()->getKind() == Kind);
931
34.8k
    return Kind;
932
34.8k
  }
933
934
  /// Return the kind considering a potential setNewAccessRelation.
935
1.19k
  MemoryKind getLatestKind() const {
936
1.19k
    return getLatestScopArrayInfo()->getKind();
937
1.19k
  }
938
939
  /// Whether this is an access of an explicit load or store in the IR.
940
12.7k
  bool isOriginalArrayKind() const {
941
12.7k
    return getOriginalKind() == MemoryKind::Array;
942
12.7k
  }
943
944
  /// Whether storage memory is either an custom .s2a/.phiops alloca
945
  /// (false) or an existing pointer into an array (true).
946
1.05k
  bool isLatestArrayKind() const {
947
1.05k
    return getLatestKind() == MemoryKind::Array;
948
1.05k
  }
949
950
  /// Old name of isOriginalArrayKind.
951
11.1k
  bool isArrayKind() const { return isOriginalArrayKind(); }
952
953
  /// Whether this access is an array to a scalar memory object, without
954
  /// considering changes by setNewAccessRelation.
955
  ///
956
  /// Scalar accesses are accesses to MemoryKind::Value, MemoryKind::PHI or
957
  /// MemoryKind::ExitPHI.
958
6.62k
  bool isOriginalScalarKind() const {
959
6.62k
    return getOriginalKind() != MemoryKind::Array;
960
6.62k
  }
961
962
  /// Whether this access is an array to a scalar memory object, also
963
  /// considering changes by setNewAccessRelation.
964
126
  bool isLatestScalarKind() const {
965
126
    return getLatestKind() != MemoryKind::Array;
966
126
  }
967
968
  /// Old name of isOriginalScalarKind.
969
6.58k
  bool isScalarKind() const { return isOriginalScalarKind(); }
970
971
  /// Was this MemoryAccess detected as a scalar dependences?
972
6.31k
  bool isOriginalValueKind() const {
973
6.31k
    return getOriginalKind() == MemoryKind::Value;
974
6.31k
  }
975
976
  /// Is this MemoryAccess currently modeling scalar dependences?
977
0
  bool isLatestValueKind() const {
978
0
    return getLatestKind() == MemoryKind::Value;
979
0
  }
980
981
  /// Old name of isOriginalValueKind().
982
5.43k
  bool isValueKind() const { return isOriginalValueKind(); }
983
984
  /// Was this MemoryAccess detected as a special PHI node access?
985
5.14k
  bool isOriginalPHIKind() const {
986
5.14k
    return getOriginalKind() == MemoryKind::PHI;
987
5.14k
  }
988
989
  /// Is this MemoryAccess modeling special PHI node accesses, also
990
  /// considering a potential change by setNewAccessRelation?
991
10
  bool isLatestPHIKind() const { return getLatestKind() == MemoryKind::PHI; }
992
993
  /// Old name of isOriginalPHIKind.
994
3.93k
  bool isPHIKind() const { return isOriginalPHIKind(); }
995
996
  /// Was this MemoryAccess detected as the accesses of a PHI node in the
997
  /// SCoP's exit block?
998
4.11k
  bool isOriginalExitPHIKind() const {
999
4.11k
    return getOriginalKind() == MemoryKind::ExitPHI;
1000
4.11k
  }
1001
1002
  /// Is this MemoryAccess modeling the accesses of a PHI node in the
1003
  /// SCoP's exit block? Can be changed to an array access using
1004
  /// setNewAccessRelation().
1005
7
  bool isLatestExitPHIKind() const {
1006
7
    return getLatestKind() == MemoryKind::ExitPHI;
1007
7
  }
1008
1009
  /// Old name of isOriginalExitPHIKind().
1010
3.55k
  bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
1011
1012
  /// Was this access detected as one of the two PHI types?
1013
1.21k
  bool isOriginalAnyPHIKind() const {
1014
557
    return isOriginalPHIKind() || isOriginalExitPHIKind();
1015
1.21k
  }
1016
1017
  /// Does this access originate from one of the two PHI types? Can be
1018
  /// changed to an array access using setNewAccessRelation().
1019
10
  bool isLatestAnyPHIKind() const {
1020
7
    return isLatestPHIKind() || isLatestExitPHIKind();
1021
10
  }
1022
1023
  /// Old name of isOriginalAnyPHIKind().
1024
676
  bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
1025
1026
  /// Get the statement that contains this memory access.
1027
18.5k
  ScopStmt *getStatement() const { return Statement; }
1028
1029
  /// Get the reduction type of this access
1030
1.86k
  ReductionType getReductionType() const { return RedType; }
1031
1032
  /// Set the array descriptor corresponding to the Array on which the
1033
  /// memory access is performed.
1034
  void setFortranArrayDescriptor(Value *FAD);
1035
1036
  /// Update the original access relation.
1037
  ///
1038
  /// We need to update the original access relation during scop construction,
1039
  /// when unifying the memory accesses that access the same scop array info
1040
  /// object. After the scop has been constructed, the original access relation
1041
  /// should not be changed any more. Instead setNewAccessRelation should
1042
  /// be called.
1043
  void setAccessRelation(__isl_take isl_map *AccessRelation);
1044
1045
  /// Set the updated access relation read from JSCOP file.
1046
  void setNewAccessRelation(__isl_take isl_map *NewAccessRelation);
1047
1048
  /// Return whether the MemoryyAccess is a partial access. That is, the access
1049
  /// is not executed in some instances of the parent statement's domain.
1050
  bool isLatestPartialAccess() const;
1051
1052
  /// Mark this a reduction like access
1053
564
  void markAsReductionLike(ReductionType RT) { RedType = RT; }
1054
1055
  /// Align the parameters in the access relation to the scop context
1056
  void realignParams();
1057
1058
  /// Update the dimensionality of the memory access.
1059
  ///
1060
  /// During scop construction some memory accesses may not be constructed with
1061
  /// their full dimensionality, but outer dimensions may have been omitted if
1062
  /// they took the value 'zero'. By updating the dimensionality of the
1063
  /// statement we add additional zero-valued dimensions to match the
1064
  /// dimensionality of the ScopArrayInfo object that belongs to this memory
1065
  /// access.
1066
  void updateDimensionality();
1067
1068
  /// Get identifier for the memory access.
1069
  ///
1070
  /// This identifier is unique for all accesses that belong to the same scop
1071
  /// statement.
1072
  __isl_give isl_id *getId() const;
1073
1074
  /// Print the MemoryAccess.
1075
  ///
1076
  /// @param OS The output stream the MemoryAccess is printed to.
1077
  void print(raw_ostream &OS) const;
1078
1079
  /// Print the MemoryAccess to stderr.
1080
  void dump() const;
1081
1082
  /// Is the memory access affine?
1083
9.07k
  bool isAffine() const { return IsAffine; }
1084
};
1085
1086
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1087
                              MemoryAccess::ReductionType RT);
1088
1089
/// Ordered list type to hold accesses.
1090
using MemoryAccessList = std::forward_list<MemoryAccess *>;
1091
1092
/// Helper structure for invariant memory accesses.
1093
struct InvariantAccess {
1094
  /// The memory access that is (partially) invariant.
1095
  MemoryAccess *MA;
1096
1097
  /// The context under which the access is not invariant.
1098
  isl_set *NonHoistableCtx;
1099
};
1100
1101
/// Ordered container type to hold invariant accesses.
1102
using InvariantAccessesTy = SmallVector<InvariantAccess, 8>;
1103
1104
/// Type for equivalent invariant accesses and their domain context.
1105
struct InvariantEquivClassTy {
1106
1107
  /// The pointer that identifies this equivalence class
1108
  const SCEV *IdentifyingPointer;
1109
1110
  /// Memory accesses now treated invariant
1111
  ///
1112
  /// These memory accesses access the pointer location that identifies
1113
  /// this equivalence class. They are treated as invariant and hoisted during
1114
  /// code generation.
1115
  MemoryAccessList InvariantAccesses;
1116
1117
  /// The execution context under which the memory location is accessed
1118
  ///
1119
  /// It is the union of the execution domains of the memory accesses in the
1120
  /// InvariantAccesses list.
1121
  isl_set *ExecutionContext;
1122
1123
  /// The type of the invariant access
1124
  ///
1125
  /// It is used to differentiate between differently typed invariant loads from
1126
  /// the same location.
1127
  Type *AccessType;
1128
};
1129
1130
/// Type for invariant accesses equivalence classes.
1131
using InvariantEquivClassesTy = SmallVector<InvariantEquivClassTy, 8>;
1132
1133
/// Statement of the Scop
1134
///
1135
/// A Scop statement represents an instruction in the Scop.
1136
///
1137
/// It is further described by its iteration domain, its schedule and its data
1138
/// accesses.
1139
/// At the moment every statement represents a single basic block of LLVM-IR.
1140
class ScopStmt {
1141
public:
1142
  ScopStmt(const ScopStmt &) = delete;
1143
  const ScopStmt &operator=(const ScopStmt &) = delete;
1144
1145
  /// Create the ScopStmt from a BasicBlock.
1146
  ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1147
           std::vector<Instruction *> Instructions);
1148
1149
  /// Create an overapproximating ScopStmt for the region @p R.
1150
  ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop);
1151
1152
  /// Create a copy statement.
1153
  ///
1154
  /// @param Stmt       The parent statement.
1155
  /// @param SourceRel  The source location.
1156
  /// @param TargetRel  The target location.
1157
  /// @param Domain     The original domain under which the copy statement would
1158
  ///                   be executed.
1159
  ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1160
           __isl_take isl_map *TargetRel, __isl_take isl_set *Domain);
1161
1162
  /// Initialize members after all MemoryAccesses have been added.
1163
  void init(LoopInfo &LI);
1164
1165
private:
1166
  /// Polyhedral description
1167
  //@{
1168
1169
  /// The Scop containing this ScopStmt.
1170
  Scop &Parent;
1171
1172
  /// The domain under which this statement is not modeled precisely.
1173
  ///
1174
  /// The invalid domain for a statement describes all parameter combinations
1175
  /// under which the statement looks to be executed but is in fact not because
1176
  /// some assumption/restriction makes the statement/scop invalid.
1177
  isl_set *InvalidDomain;
1178
1179
  /// The iteration domain describes the set of iterations for which this
1180
  /// statement is executed.
1181
  ///
1182
  /// Example:
1183
  ///     for (i = 0; i < 100 + b; ++i)
1184
  ///       for (j = 0; j < i; ++j)
1185
  ///         S(i,j);
1186
  ///
1187
  /// 'S' is executed for different values of i and j. A vector of all
1188
  /// induction variables around S (i, j) is called iteration vector.
1189
  /// The domain describes the set of possible iteration vectors.
1190
  ///
1191
  /// In this case it is:
1192
  ///
1193
  ///     Domain: 0 <= i <= 100 + b
1194
  ///             0 <= j <= i
1195
  ///
1196
  /// A pair of statement and iteration vector (S, (5,3)) is called statement
1197
  /// instance.
1198
  isl_set *Domain;
1199
1200
  /// The memory accesses of this statement.
1201
  ///
1202
  /// The only side effects of a statement are its memory accesses.
1203
  typedef SmallVector<MemoryAccess *, 8> MemoryAccessVec;
1204
  MemoryAccessVec MemAccs;
1205
1206
  /// Mapping from instructions to (scalar) memory accesses.
1207
  DenseMap<const Instruction *, MemoryAccessList> InstructionToAccess;
1208
1209
  /// The set of values defined elsewhere required in this ScopStmt and
1210
  ///        their MemoryKind::Value READ MemoryAccesses.
1211
  DenseMap<Value *, MemoryAccess *> ValueReads;
1212
1213
  /// The set of values defined in this ScopStmt that are required
1214
  ///        elsewhere, mapped to their MemoryKind::Value WRITE MemoryAccesses.
1215
  DenseMap<Instruction *, MemoryAccess *> ValueWrites;
1216
1217
  /// Map from PHI nodes to its incoming value when coming from this
1218
  ///        statement.
1219
  ///
1220
  /// Non-affine subregions can have multiple exiting blocks that are incoming
1221
  /// blocks of the PHI nodes. This map ensures that there is only one write
1222
  /// operation for the complete subregion. A PHI selecting the relevant value
1223
  /// will be inserted.
1224
  DenseMap<PHINode *, MemoryAccess *> PHIWrites;
1225
1226
  //@}
1227
1228
  /// A SCoP statement represents either a basic block (affine/precise case) or
1229
  /// a whole region (non-affine case).
1230
  ///
1231
  /// Only one of the following two members will therefore be set and indicate
1232
  /// which kind of statement this is.
1233
  ///
1234
  ///{
1235
1236
  /// The BasicBlock represented by this statement (in the affine case).
1237
  BasicBlock *BB;
1238
1239
  /// The region represented by this statement (in the non-affine case).
1240
  Region *R;
1241
1242
  ///}
1243
1244
  /// The isl AST build for the new generated AST.
1245
  isl_ast_build *Build;
1246
1247
  SmallVector<Loop *, 4> NestLoops;
1248
1249
  std::string BaseName;
1250
1251
  /// The closest loop that contains this statement.
1252
  Loop *SurroundingLoop;
1253
1254
  /// Vector for Instructions in a BB.
1255
  std::vector<Instruction *> Instructions;
1256
1257
  /// Build the statement.
1258
  //@{
1259
  void buildDomain();
1260
1261
  /// Fill NestLoops with loops surrounding this statement.
1262
  void collectSurroundingLoops();
1263
1264
  /// Build the access relation of all memory accesses.
1265
  void buildAccessRelations();
1266
1267
  /// Detect and mark reductions in the ScopStmt
1268
  void checkForReductions();
1269
1270
  /// Collect loads which might form a reduction chain with @p StoreMA
1271
  void
1272
  collectCandiateReductionLoads(MemoryAccess *StoreMA,
1273
                                llvm::SmallVectorImpl<MemoryAccess *> &Loads);
1274
  //@}
1275
1276
  /// Remove @p MA from dictionaries pointing to them.
1277
  void removeAccessData(MemoryAccess *MA);
1278
1279
public:
1280
  ~ScopStmt();
1281
1282
  /// Get an isl_ctx pointer.
1283
  isl_ctx *getIslCtx() const;
1284
1285
  /// Get the iteration domain of this ScopStmt.
1286
  ///
1287
  /// @return The iteration domain of this ScopStmt.
1288
  __isl_give isl_set *getDomain() const;
1289
1290
  /// Get the space of the iteration domain
1291
  ///
1292
  /// @return The space of the iteration domain
1293
  __isl_give isl_space *getDomainSpace() const;
1294
1295
  /// Get the id of the iteration domain space
1296
  ///
1297
  /// @return The id of the iteration domain space
1298
  __isl_give isl_id *getDomainId() const;
1299
1300
  /// Get an isl string representing this domain.
1301
  std::string getDomainStr() const;
1302
1303
  /// Get the schedule function of this ScopStmt.
1304
  ///
1305
  /// @return The schedule function of this ScopStmt, if it does not contain
1306
  /// extension nodes, and nullptr, otherwise.
1307
  __isl_give isl_map *getSchedule() const;
1308
1309
  /// Get an isl string representing this schedule.
1310
  ///
1311
  /// @return An isl string representing this schedule, if it does not contain
1312
  /// extension nodes, and an empty string, otherwise.
1313
  std::string getScheduleStr() const;
1314
1315
  /// Get the invalid domain for this statement.
1316
9.71k
  __isl_give isl_set *getInvalidDomain() const {
1317
9.71k
    return isl_set_copy(InvalidDomain);
1318
9.71k
  }
1319
1320
  /// Get the invalid context for this statement.
1321
228
  __isl_give isl_set *getInvalidContext() const {
1322
228
    return isl_set_params(getInvalidDomain());
1323
228
  }
1324
1325
  /// Set the invalid context for this statement to @p ID.
1326
  void setInvalidDomain(__isl_take isl_set *ID);
1327
1328
  /// Get the BasicBlock represented by this ScopStmt (if any).
1329
  ///
1330
  /// @return The BasicBlock represented by this ScopStmt, or null if the
1331
  ///         statement represents a region.
1332
33.0k
  BasicBlock *getBasicBlock() const { return BB; }
1333
1334
  /// Return true if this statement represents a single basic block.
1335
39.5k
  bool isBlockStmt() const { return BB != nullptr; }
1336
1337
  /// Return true if this is a copy statement.
1338
4.63k
  bool isCopyStmt() const 
{ return BB == nullptr && 4.63k
R == nullptr673
; }
1339
1340
  /// Get the region represented by this ScopStmt (if any).
1341
  ///
1342
  /// @return The region represented by this ScopStmt, or null if the statement
1343
  ///         represents a basic block.
1344
3.05k
  Region *getRegion() const { return R; }
1345
1346
  /// Return true if this statement represents a whole region.
1347
7.55k
  bool isRegionStmt() const { return R != nullptr; }
1348
1349
  /// Return a BasicBlock from this statement.
1350
  ///
1351
  /// For block statements, it returns the BasicBlock itself. For subregion
1352
  /// statements, return its entry block.
1353
  BasicBlock *getEntryBlock() const;
1354
1355
  /// Return whether @p L is boxed within this statement.
1356
1.60k
  bool contains(const Loop *L) const {
1357
1.60k
    // Block statements never contain loops.
1358
1.60k
    if (isBlockStmt())
1359
1.49k
      return false;
1360
1.60k
1361
102
    return getRegion()->contains(L);
1362
1.60k
  }
1363
1364
  /// Return whether this statement contains @p BB.
1365
3.88k
  bool contains(BasicBlock *BB) const {
1366
3.88k
    if (isCopyStmt())
1367
0
      return false;
1368
3.88k
    
if (3.88k
isBlockStmt()3.88k
)
1369
3.28k
      return BB == getBasicBlock();
1370
604
    return getRegion()->contains(BB);
1371
3.88k
  }
1372
1373
  /// Return whether this statement contains @p Inst.
1374
0
  bool contains(Instruction *Inst) const {
1375
0
    if (!Inst)
1376
0
      return false;
1377
0
    return contains(Inst->getParent());
1378
0
  }
1379
1380
  /// Return the closest innermost loop that contains this statement, but is not
1381
  /// contained in it.
1382
  ///
1383
  /// For block statement, this is just the loop that contains the block. Region
1384
  /// statements can contain boxed loops, so getting the loop of one of the
1385
  /// region's BBs might return such an inner loop. For instance, the region's
1386
  /// entry could be a header of a loop, but the region might extend to BBs
1387
  /// after the loop exit. Similarly, the region might only contain parts of the
1388
  /// loop body and still include the loop header.
1389
  ///
1390
  /// Most of the time the surrounding loop is the top element of #NestLoops,
1391
  /// except when it is empty. In that case it return the loop that the whole
1392
  /// SCoP is contained in. That can be nullptr if there is no such loop.
1393
41.2k
  Loop *getSurroundingLoop() const {
1394
41.2k
    assert(!isCopyStmt() &&
1395
41.2k
           "No surrounding loop for artificially created statements");
1396
41.2k
    return SurroundingLoop;
1397
41.2k
  }
1398
1399
  /// Return true if this statement does not contain any accesses.
1400
6.64k
  bool isEmpty() const { return MemAccs.empty(); }
1401
1402
  /// Return the only array access for @p Inst, if existing.
1403
  ///
1404
  /// @param Inst The instruction for which to look up the access.
1405
  /// @returns The unique array memory access related to Inst or nullptr if
1406
  ///          no array access exists
1407
2.06k
  MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
1408
2.06k
    auto It = InstructionToAccess.find(Inst);
1409
2.06k
    if (It == InstructionToAccess.end())
1410
213
      return nullptr;
1411
2.06k
1412
1.84k
    MemoryAccess *ArrayAccess = nullptr;
1413
1.84k
1414
1.84k
    for (auto Access : It->getSecond()) {
1415
1.84k
      if (!Access->isArrayKind())
1416
0
        continue;
1417
1.84k
1418
1.84k
      assert(!ArrayAccess && "More then one array access for instruction");
1419
1.84k
1420
1.84k
      ArrayAccess = Access;
1421
1.84k
    }
1422
1.84k
1423
1.84k
    return ArrayAccess;
1424
2.06k
  }
1425
1426
  /// Return the only array access for @p Inst.
1427
  ///
1428
  /// @param Inst The instruction for which to look up the access.
1429
  /// @returns The unique array memory access related to Inst.
1430
1.35k
  MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
1431
1.35k
    MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
1432
1.35k
1433
1.35k
    assert(ArrayAccess && "No array access found for instruction!");
1434
1.35k
    return *ArrayAccess;
1435
1.35k
  }
1436
1437
  /// Return the MemoryAccess that writes the value of an instruction
1438
  ///        defined in this statement, or nullptr if not existing, respectively
1439
  ///        not yet added.
1440
347
  MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
1441
347
    assert((isRegionStmt() && R->contains(Inst)) ||
1442
347
           (!isRegionStmt() && Inst->getParent() == BB));
1443
347
    return ValueWrites.lookup(Inst);
1444
347
  }
1445
1446
  /// Return the MemoryAccess that reloads a value, or nullptr if not
1447
  ///        existing, respectively not yet added.
1448
1.14k
  MemoryAccess *lookupValueReadOf(Value *Inst) const {
1449
1.14k
    return ValueReads.lookup(Inst);
1450
1.14k
  }
1451
1452
  /// Return the MemoryAccess that loads a PHINode value, or nullptr if not
1453
  /// existing, respectively not yet added.
1454
  MemoryAccess *lookupPHIReadOf(PHINode *PHI) const;
1455
1456
  /// Return the PHI write MemoryAccess for the incoming values from any
1457
  ///        basic block in this ScopStmt, or nullptr if not existing,
1458
  ///        respectively not yet added.
1459
415
  MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
1460
415
    assert(isBlockStmt() || R->getExit() == PHI->getParent());
1461
415
    return PHIWrites.lookup(PHI);
1462
415
  }
1463
1464
  /// Return the input access of the value, or null if no such MemoryAccess
1465
  /// exists.
1466
  ///
1467
  /// The input access is the MemoryAccess that makes an inter-statement value
1468
  /// available in this statement by reading it at the start of this statement.
1469
  /// This can be a MemoryKind::Value if defined in another statement or a
1470
  /// MemoryKind::PHI if the value is a PHINode in this statement.
1471
57
  MemoryAccess *lookupInputAccessOf(Value *Val) const {
1472
57
    if (isa<PHINode>(Val))
1473
10
      
if (auto 10
InputMA10
= lookupPHIReadOf(cast<PHINode>(Val)))
{3
1474
3
        assert(!lookupValueReadOf(Val) && "input accesses must be unique; a "
1475
3
                                          "statement cannot read a .s2a and "
1476
3
                                          ".phiops simultaneously");
1477
3
        return InputMA;
1478
3
      }
1479
57
1480
54
    
if (auto *54
InputMA54
= lookupValueReadOf(Val))
1481
31
      return InputMA;
1482
54
1483
23
    return nullptr;
1484
54
  }
1485
1486
  /// Add @p Access to this statement's list of accesses.
1487
  void addAccess(MemoryAccess *Access);
1488
1489
  /// Remove a MemoryAccess from this statement.
1490
  ///
1491
  /// Note that scalar accesses that are caused by MA will
1492
  /// be eliminated too.
1493
  void removeMemoryAccess(MemoryAccess *MA);
1494
1495
  /// Remove @p MA from this statement.
1496
  ///
1497
  /// In contrast to removeMemoryAccess(), no other access will be eliminated.
1498
  void removeSingleMemoryAccess(MemoryAccess *MA);
1499
1500
  typedef MemoryAccessVec::iterator iterator;
1501
  typedef MemoryAccessVec::const_iterator const_iterator;
1502
1503
20.7k
  iterator begin() { return MemAccs.begin(); }
1504
20.7k
  iterator end() { return MemAccs.end(); }
1505
425
  const_iterator begin() const { return MemAccs.begin(); }
1506
425
  const_iterator end() const { return MemAccs.end(); }
1507
4.42k
  size_t size() const { return MemAccs.size(); }
1508
1509
  unsigned getNumIterators() const;
1510
1511
49.7k
  Scop *getParent() { return &Parent; }
1512
1.00k
  const Scop *getParent() const { return &Parent; }
1513
1514
341
  const std::vector<Instruction *> &getInstructions() const {
1515
341
    return Instructions;
1516
341
  }
1517
1518
  const char *getBaseName() const;
1519
1520
  /// Set the isl AST build.
1521
396
  void setAstBuild(__isl_keep isl_ast_build *B) { Build = B; }
1522
1523
  /// Get the isl AST build.
1524
6
  __isl_keep isl_ast_build *getAstBuild() const { return Build; }
1525
1526
  /// Restrict the domain of the statement.
1527
  ///
1528
  /// @param NewDomain The new statement domain.
1529
  void restrictDomain(__isl_take isl_set *NewDomain);
1530
1531
  /// Compute the isl representation for the SCEV @p E in this stmt.
1532
  ///
1533
  /// @param E           The SCEV that should be translated.
1534
  /// @param NonNegative Flag to indicate the @p E has to be non-negative.
1535
  ///
1536
  /// Note that this function will also adjust the invalid context accordingly.
1537
  __isl_give isl_pw_aff *getPwAff(const SCEV *E, bool NonNegative = false);
1538
1539
  /// Get the loop for a dimension.
1540
  ///
1541
  /// @param Dimension The dimension of the induction variable
1542
  /// @return The loop at a certain dimension.
1543
  Loop *getLoopForDimension(unsigned Dimension) const;
1544
1545
  /// Align the parameters in the statement to the scop context
1546
  void realignParams();
1547
1548
  /// Print the ScopStmt.
1549
  ///
1550
  /// @param OS The output stream the ScopStmt is printed to.
1551
  void print(raw_ostream &OS) const;
1552
1553
  /// Print the instructions in ScopStmt.
1554
  ///
1555
  void printInstructions(raw_ostream &OS) const;
1556
1557
  /// Print the ScopStmt to stderr.
1558
  void dump() const;
1559
};
1560
1561
/// Print ScopStmt S to raw_ostream O.
1562
731
static inline raw_ostream &operator<<(raw_ostream &O, const ScopStmt &S) {
1563
731
  S.print(O);
1564
731
  return O;
1565
731
}
Unexecuted instantiation: DependenceInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: PolyhedralInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: ScopDetection.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
ScopInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Line
Count
Source
1562
731
static inline raw_ostream &operator<<(raw_ostream &O, const ScopStmt &S) {
1563
731
  S.print(O);
1564
731
  return O;
1565
731
}
Unexecuted instantiation: ScopBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: ScopPass.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: PruneUnprofitable.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: BlockGenerators.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: IslAst.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: IslExprBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: IslNodeBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: CodeGeneration.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: IRBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: Utils.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: PerfMonitor.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: JSONExporter.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: SCEVAffinator.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: SCEVValidator.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: RegisterPasses.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: ScopHelper.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: VirtualInstruction.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: DeadCodeElimination.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: ScheduleOptimizer.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: FlattenSchedule.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: DeLICM.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
Unexecuted instantiation: Simplify.cpp:polly::operator<<(llvm::raw_ostream&, polly::ScopStmt const&)
1566
1567
/// Static Control Part
1568
///
1569
/// A Scop is the polyhedral representation of a control flow region detected
1570
/// by the Scop detection. It is generated by translating the LLVM-IR and
1571
/// abstracting its effects.
1572
///
1573
/// A Scop consists of a set of:
1574
///
1575
///   * A set of statements executed in the Scop.
1576
///
1577
///   * A set of global parameters
1578
///   Those parameters are scalar integer values, which are constant during
1579
///   execution.
1580
///
1581
///   * A context
1582
///   This context contains information about the values the parameters
1583
///   can take and relations between different parameters.
1584
class Scop {
1585
public:
1586
  /// Type to represent a pair of minimal/maximal access to an array.
1587
  using MinMaxAccessTy = std::pair<isl_pw_multi_aff *, isl_pw_multi_aff *>;
1588
1589
  /// Vector of minimal/maximal accesses to different arrays.
1590
  using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
1591
1592
  /// Pair of minimal/maximal access vectors representing
1593
  /// read write and read only accesses
1594
  using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
1595
1596
  /// Vector of pair of minimal/maximal access vectors representing
1597
  /// non read only and read only accesses for each alias group.
1598
  using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
1599
1600
private:
1601
  Scop(const Scop &) = delete;
1602
  const Scop &operator=(const Scop &) = delete;
1603
1604
  ScalarEvolution *SE;
1605
1606
  /// The underlying Region.
1607
  Region &R;
1608
1609
  /// The name of the SCoP (identical to the regions name)
1610
  std::string name;
1611
1612
  // Access functions of the SCoP.
1613
  //
1614
  // This owns all the MemoryAccess objects of the Scop created in this pass.
1615
  AccFuncVector AccessFunctions;
1616
1617
  /// Flag to indicate that the scheduler actually optimized the SCoP.
1618
  bool IsOptimized;
1619
1620
  /// True if the underlying region has a single exiting block.
1621
  bool HasSingleExitEdge;
1622
1623
  /// Flag to remember if the SCoP contained an error block or not.
1624
  bool HasErrorBlock;
1625
1626
  /// Max loop depth.
1627
  unsigned MaxLoopDepth;
1628
1629
  /// Number of copy statements.
1630
  unsigned CopyStmtsNum;
1631
1632
  typedef std::list<ScopStmt> StmtSet;
1633
  /// The statements in this Scop.
1634
  StmtSet Stmts;
1635
1636
  /// Parameters of this Scop
1637
  ParameterSetTy Parameters;
1638
1639
  /// Mapping from parameters to their ids.
1640
  DenseMap<const SCEV *, isl_id *> ParameterIds;
1641
1642
  /// The context of the SCoP created during SCoP detection.
1643
  ScopDetection::DetectionContext &DC;
1644
1645
  /// Isl context.
1646
  ///
1647
  /// We need a shared_ptr with reference counter to delete the context when all
1648
  /// isl objects are deleted. We will distribute the shared_ptr to all objects
1649
  /// that use the context to create isl objects, and increase the reference
1650
  /// counter. By doing this, we guarantee that the context is deleted when we
1651
  /// delete the last object that creates isl objects with the context.
1652
  std::shared_ptr<isl_ctx> IslCtx;
1653
1654
  /// A map from basic blocks to SCoP statements.
1655
  DenseMap<BasicBlock *, ScopStmt *> StmtMap;
1656
1657
  /// A map from basic blocks to their domains.
1658
  DenseMap<BasicBlock *, isl_set *> DomainMap;
1659
1660
  /// Constraints on parameters.
1661
  isl_set *Context;
1662
1663
  /// The affinator used to translate SCEVs to isl expressions.
1664
  SCEVAffinator Affinator;
1665
1666
  typedef std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
1667
                   std::unique_ptr<ScopArrayInfo>>
1668
      ArrayInfoMapTy;
1669
1670
  typedef StringMap<std::unique_ptr<ScopArrayInfo>> ArrayNameMapTy;
1671
1672
  typedef SetVector<ScopArrayInfo *> ArrayInfoSetTy;
1673
1674
  /// A map to remember ScopArrayInfo objects for all base pointers.
1675
  ///
1676
  /// As PHI nodes may have two array info objects associated, we add a flag
1677
  /// that distinguishes between the PHI node specific ArrayInfo object
1678
  /// and the normal one.
1679
  ArrayInfoMapTy ScopArrayInfoMap;
1680
1681
  /// A map to remember ScopArrayInfo objects for all names of memory
1682
  ///        references.
1683
  ArrayNameMapTy ScopArrayNameMap;
1684
1685
  /// A set to remember ScopArrayInfo objects.
1686
  /// @see Scop::ScopArrayInfoMap
1687
  ArrayInfoSetTy ScopArrayInfoSet;
1688
1689
  /// The assumptions under which this scop was built.
1690
  ///
1691
  /// When constructing a scop sometimes the exact representation of a statement
1692
  /// or condition would be very complex, but there is a common case which is a
1693
  /// lot simpler, but which is only valid under certain assumptions. The
1694
  /// assumed context records the assumptions taken during the construction of
1695
  /// this scop and that need to be code generated as a run-time test.
1696
  isl_set *AssumedContext;
1697
1698
  /// The restrictions under which this SCoP was built.
1699
  ///
1700
  /// The invalid context is similar to the assumed context as it contains
1701
  /// constraints over the parameters. However, while we need the constraints
1702
  /// in the assumed context to be "true" the constraints in the invalid context
1703
  /// need to be "false". Otherwise they behave the same.
1704
  isl_set *InvalidContext;
1705
1706
  /// Helper struct to remember assumptions.
1707
  struct Assumption {
1708
1709
    /// The kind of the assumption (e.g., WRAPPING).
1710
    AssumptionKind Kind;
1711
1712
    /// Flag to distinguish assumptions and restrictions.
1713
    AssumptionSign Sign;
1714
1715
    /// The valid/invalid context if this is an assumption/restriction.
1716
    isl_set *Set;
1717
1718
    /// The location that caused this assumption.
1719
    DebugLoc Loc;
1720
1721
    /// An optional block whose domain can simplify the assumption.
1722
    BasicBlock *BB;
1723
  };
1724
1725
  /// Collection to hold taken assumptions.
1726
  ///
1727
  /// There are two reasons why we want to record assumptions first before we
1728
  /// add them to the assumed/invalid context:
1729
  ///   1) If the SCoP is not profitable or otherwise invalid without the
1730
  ///      assumed/invalid context we do not have to compute it.
1731
  ///   2) Information about the context are gathered rather late in the SCoP
1732
  ///      construction (basically after we know all parameters), thus the user
1733
  ///      might see overly complicated assumptions to be taken while they will
1734
  ///      only be simplified later on.
1735
  SmallVector<Assumption, 8> RecordedAssumptions;
1736
1737
  /// The schedule of the SCoP
1738
  ///
1739
  /// The schedule of the SCoP describes the execution order of the statements
1740
  /// in the scop by assigning each statement instance a possibly
1741
  /// multi-dimensional execution time. The schedule is stored as a tree of
1742
  /// schedule nodes.
1743
  ///
1744
  /// The most common nodes in a schedule tree are so-called band nodes. Band
1745
  /// nodes map statement instances into a multi dimensional schedule space.
1746
  /// This space can be seen as a multi-dimensional clock.
1747
  ///
1748
  /// Example:
1749
  ///
1750
  /// <S,(5,4)>  may be mapped to (5,4) by this schedule:
1751
  ///
1752
  /// s0 = i (Year of execution)
1753
  /// s1 = j (Day of execution)
1754
  ///
1755
  /// or to (9, 20) by this schedule:
1756
  ///
1757
  /// s0 = i + j (Year of execution)
1758
  /// s1 = 20 (Day of execution)
1759
  ///
1760
  /// The order statement instances are executed is defined by the
1761
  /// schedule vectors they are mapped to. A statement instance
1762
  /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
1763
  /// the schedule vector of A is lexicographic smaller than the schedule
1764
  /// vector of B.
1765
  ///
1766
  /// Besides band nodes, schedule trees contain additional nodes that specify
1767
  /// a textual ordering between two subtrees or filter nodes that filter the
1768
  /// set of statement instances that will be scheduled in a subtree. There
1769
  /// are also several other nodes. A full description of the different nodes
1770
  /// in a schedule tree is given in the isl manual.
1771
  isl_schedule *Schedule;
1772
1773
  /// The set of minimal/maximal accesses for each alias group.
1774
  ///
1775
  /// When building runtime alias checks we look at all memory instructions and
1776
  /// build so called alias groups. Each group contains a set of accesses to
1777
  /// different base arrays which might alias with each other. However, between
1778
  /// alias groups there is no aliasing possible.
1779
  ///
1780
  /// In a program with int and float pointers annotated with tbaa information
1781
  /// we would probably generate two alias groups, one for the int pointers and
1782
  /// one for the float pointers.
1783
  ///
1784
  /// During code generation we will create a runtime alias check for each alias
1785
  /// group to ensure the SCoP is executed in an alias free environment.
1786
  MinMaxVectorPairVectorTy MinMaxAliasGroups;
1787
1788
  /// Mapping from invariant loads to the representing invariant load of
1789
  ///        their equivalence class.
1790
  ValueToValueMap InvEquivClassVMap;
1791
1792
  /// List of invariant accesses.
1793
  InvariantEquivClassesTy InvariantEquivClasses;
1794
1795
  /// The smallest array index not yet assigned.
1796
  long ArrayIdx = 0;
1797
1798
  /// The smallest statement index not yet assigned.
1799
  long StmtIdx = 0;
1800
1801
  /// Scop constructor; invoked from ScopBuilder::buildScop.
1802
  Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI,
1803
       ScopDetection::DetectionContext &DC);
1804
1805
  //@}
1806
1807
  /// Initialize this ScopBuilder.
1808
  void init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
1809
            LoopInfo &LI);
1810
1811
  /// Propagate domains that are known due to graph properties.
1812
  ///
1813
  /// As a CFG is mostly structured we use the graph properties to propagate
1814
  /// domains without the need to compute all path conditions. In particular, if
1815
  /// a block A dominates a block B and B post-dominates A we know that the
1816
  /// domain of B is a superset of the domain of A. As we do not have
1817
  /// post-dominator information available here we use the less precise region
1818
  /// information. Given a region R, we know that the exit is always executed if
1819
  /// the entry was executed, thus the domain of the exit is a superset of the
1820
  /// domain of the entry. In case the exit can only be reached from within the
1821
  /// region the domains are in fact equal. This function will use this property
1822
  /// to avoid the generation of condition constraints that determine when a
1823
  /// branch is taken. If @p BB is a region entry block we will propagate its
1824
  /// domain to the region exit block. Additionally, we put the region exit
1825
  /// block in the @p FinishedExitBlocks set so we can later skip edges from
1826
  /// within the region to that block.
1827
  ///
1828
  /// @param BB The block for which the domain is currently propagated.
1829
  /// @param BBLoop The innermost affine loop surrounding @p BB.
1830
  /// @param FinishedExitBlocks Set of region exits the domain was set for.
1831
  /// @param LI The LoopInfo for the current function.
1832
  ///
1833
  void propagateDomainConstraintsToRegionExit(
1834
      BasicBlock *BB, Loop *BBLoop,
1835
      SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI);
1836
1837
  /// Compute the union of predecessor domains for @p BB.
1838
  ///
1839
  /// To compute the union of all domains of predecessors of @p BB this
1840
  /// function applies similar reasoning on the CFG structure as described for
1841
  ///   @see propagateDomainConstraintsToRegionExit
1842
  ///
1843
  /// @param BB     The block for which the predecessor domains are collected.
1844
  /// @param Domain The domain under which BB is executed.
1845
  /// @param DT     The DominatorTree for the current function.
1846
  /// @param LI     The LoopInfo for the current function.
1847
  ///
1848
  /// @returns The domain under which @p BB is executed.
1849
  __isl_give isl_set *
1850
  getPredecessorDomainConstraints(BasicBlock *BB, __isl_keep isl_set *Domain,
1851
                                  DominatorTree &DT, LoopInfo &LI);
1852
1853
  /// Add loop carried constraints to the header block of the loop @p L.
1854
  ///
1855
  /// @param L  The loop to process.
1856
  /// @param LI The LoopInfo for the current function.
1857
  ///
1858
  /// @returns True if there was no problem and false otherwise.
1859
  bool addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI);
1860
1861
  /// Compute the branching constraints for each basic block in @p R.
1862
  ///
1863
  /// @param R  The region we currently build branching conditions for.
1864
  /// @param DT The DominatorTree for the current function.
1865
  /// @param LI The LoopInfo for the current function.
1866
  ///
1867
  /// @returns True if there was no problem and false otherwise.
1868
  bool buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
1869
                                         LoopInfo &LI);
1870
1871
  /// Propagate the domain constraints through the region @p R.
1872
  ///
1873
  /// @param R  The region we currently build branching conditions for.
1874
  /// @param DT The DominatorTree for the current function.
1875
  /// @param LI The LoopInfo for the current function.
1876
  ///
1877
  /// @returns True if there was no problem and false otherwise.
1878
  bool propagateDomainConstraints(Region *R, DominatorTree &DT, LoopInfo &LI);
1879
1880
  /// Propagate invalid domains of statements through @p R.
1881
  ///
1882
  /// This method will propagate invalid statement domains through @p R and at
1883
  /// the same time add error block domains to them. Additionally, the domains
1884
  /// of error statements and those only reachable via error statements will be
1885
  /// replaced by an empty set. Later those will be removed completely.
1886
  ///
1887
  /// @param R  The currently traversed region.
1888
  /// @param DT The DominatorTree for the current function.
1889
  /// @param LI The LoopInfo for the current function.
1890
  ///
1891
  /// @returns True if there was no problem and false otherwise.
1892
  bool propagateInvalidStmtDomains(Region *R, DominatorTree &DT, LoopInfo &LI);
1893
1894
  /// Compute the domain for each basic block in @p R.
1895
  ///
1896
  /// @param R  The region we currently traverse.
1897
  /// @param DT The DominatorTree for the current function.
1898
  /// @param LI The LoopInfo for the current function.
1899
  ///
1900
  /// @returns True if there was no problem and false otherwise.
1901
  bool buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI);
1902
1903
  /// Add parameter constraints to @p C that imply a non-empty domain.
1904
  __isl_give isl_set *addNonEmptyDomainConstraints(__isl_take isl_set *C) const;
1905
1906
  /// Return the access for the base ptr of @p MA if any.
1907
  MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
1908
1909
  /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
1910
  bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
1911
1912
  /// Create equivalence classes for required invariant accesses.
1913
  ///
1914
  /// These classes will consolidate multiple required invariant loads from the
1915
  /// same address in order to keep the number of dimensions in the SCoP
1916
  /// description small. For each such class equivalence class only one
1917
  /// representing element, hence one required invariant load, will be chosen
1918
  /// and modeled as parameter. The method
1919
  /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
1920
  /// equivalence class with the representing element that is modeled. As a
1921
  /// consequence Scop::getIdForParam() will only return an id for the
1922
  /// representing element of each equivalence class, thus for each required
1923
  /// invariant location.
1924
  void buildInvariantEquivalenceClasses();
1925
1926
  /// Return the context under which the access cannot be hoisted.
1927
  ///
1928
  /// @param Access The access to check.
1929
  /// @param Writes The set of all memory writes in the scop.
1930
  ///
1931
  /// @return Return the context under which the access cannot be hoisted or a
1932
  ///         nullptr if it cannot be hoisted at all.
1933
  isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
1934
1935
  /// Verify that all required invariant loads have been hoisted.
1936
  ///
1937
  /// Invariant load hoisting is not guaranteed to hoist all loads that were
1938
  /// assumed to be scop invariant during scop detection. This function checks
1939
  /// for cases where the hoisting failed, but where it would have been
1940
  /// necessary for our scop modeling to be correct. In case of insufficient
1941
  /// hoisting the scop is marked as invalid.
1942
  ///
1943
  /// In the example below Bound[1] is required to be invariant:
1944
  ///
1945
  /// for (int i = 1; i < Bound[0]; i++)
1946
  ///   for (int j = 1; j < Bound[1]; j++)
1947
  ///     ...
1948
  ///
1949
  void verifyInvariantLoads();
1950
1951
  /// Hoist invariant memory loads and check for required ones.
1952
  ///
1953
  /// We first identify "common" invariant loads, thus loads that are invariant
1954
  /// and can be hoisted. Then we check if all required invariant loads have
1955
  /// been identified as (common) invariant. A load is a required invariant load
1956
  /// if it was assumed to be invariant during SCoP detection, e.g., to assume
1957
  /// loop bounds to be affine or runtime alias checks to be placeable. In case
1958
  /// a required invariant load was not identified as (common) invariant we will
1959
  /// drop this SCoP. An example for both "common" as well as required invariant
1960
  /// loads is given below:
1961
  ///
1962
  /// for (int i = 1; i < *LB[0]; i++)
1963
  ///   for (int j = 1; j < *LB[1]; j++)
1964
  ///     A[i][j] += A[0][0] + (*V);
1965
  ///
1966
  /// Common inv. loads: V, A[0][0], LB[0], LB[1]
1967
  /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
1968
  ///
1969
  void hoistInvariantLoads();
1970
1971
  /// Canonicalize arrays with base pointers from the same equivalence class.
1972
  ///
1973
  /// Some context: in our normal model we assume that each base pointer is
1974
  /// related to a single specific memory region, where memory regions
1975
  /// associated with different base pointers are disjoint. Consequently we do
1976
  /// not need to compute additional data dependences that model possible
1977
  /// overlaps of these memory regions. To verify our assumption we compute
1978
  /// alias checks that verify that modeled arrays indeed do not overlap. In
1979
  /// case an overlap is detected the runtime check fails and we fall back to
1980
  /// the original code.
1981
  ///
1982
  /// In case of arrays where the base pointers are know to be identical,
1983
  /// because they are dynamically loaded by accesses that are in the same
1984
  /// invariant load equivalence class, such run-time alias check would always
1985
  /// be false.
1986
  ///
1987
  /// This function makes sure that we do not generate consistently failing
1988
  /// run-time checks for code that contains distinct arrays with known
1989
  /// equivalent base pointers. It identifies for each invariant load
1990
  /// equivalence class a single canonical array and canonicalizes all memory
1991
  /// accesses that reference arrays that have base pointers that are known to
1992
  /// be equal to the base pointer of such a canonical array to this canonical
1993
  /// array.
1994
  ///
1995
  /// We currently do not canonicalize arrays for which certain memory accesses
1996
  /// have been hoisted as loop invariant.
1997
  void canonicalizeDynamicBasePtrs();
1998
1999
  /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
2000
  void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
2001
2002
  /// Create an id for @p Param and store it in the ParameterIds map.
2003
  void createParameterId(const SCEV *Param);
2004
2005
  /// Build the Context of the Scop.
2006
  void buildContext();
2007
2008
  /// Add user provided parameter constraints to context (source code).
2009
  void addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI);
2010
2011
  /// Add user provided parameter constraints to context (command line).
2012
  void addUserContext();
2013
2014
  /// Add the bounds of the parameters to the context.
2015
  void addParameterBounds();
2016
2017
  /// Simplify the assumed and invalid context.
2018
  void simplifyContexts();
2019
2020
  /// Get the representing SCEV for @p S if applicable, otherwise @p S.
2021
  ///
2022
  /// Invariant loads of the same location are put in an equivalence class and
2023
  /// only one of them is chosen as a representing element that will be
2024
  /// modeled as a parameter. The others have to be normalized, i.e.,
2025
  /// replaced by the representing element of their equivalence class, in order
2026
  /// to get the correct parameter value, e.g., in the SCEVAffinator.
2027
  ///
2028
  /// @param S The SCEV to normalize.
2029
  ///
2030
  /// @return The representing SCEV for invariant loads or @p S if none.
2031
  const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S);
2032
2033
  /// Create a new SCoP statement for @p BB.
2034
  ///
2035
  /// A new statement for @p BB will be created and added to the statement
2036
  /// vector
2037
  /// and map.
2038
  ///
2039
  /// @param BB              The basic block we build the statement for.
2040
  /// @param SurroundingLoop The loop the created statement is contained in.
2041
  /// @param Instructions    The instructions in the basic block.
2042
  void addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
2043
                   std::vector<Instruction *> Instructions);
2044
2045
  /// Create a new SCoP statement for @p R.
2046
  ///
2047
  /// A new statement for @p R will be created and added to the statement vector
2048
  /// and map.
2049
  ///
2050
  /// @param R               The region we build the statement for.
2051
  /// @param SurroundingLoop The loop the created statement is contained in.
2052
  void addScopStmt(Region *R, Loop *SurroundingLoop);
2053
2054
  /// Update access dimensionalities.
2055
  ///
2056
  /// When detecting memory accesses different accesses to the same array may
2057
  /// have built with different dimensionality, as outer zero-values dimensions
2058
  /// may not have been recognized as separate dimensions. This function goes
2059
  /// again over all memory accesses and updates their dimensionality to match
2060
  /// the dimensionality of the underlying ScopArrayInfo object.
2061
  void updateAccessDimensionality();
2062
2063
  /// Fold size constants to the right.
2064
  ///
2065
  /// In case all memory accesses in a given dimension are multiplied with a
2066
  /// common constant, we can remove this constant from the individual access
2067
  /// functions and move it to the size of the memory access. We do this as this
2068
  /// increases the size of the innermost dimension, consequently widens the
2069
  /// valid range the array subscript in this dimension can evaluate to, and
2070
  /// as a result increases the likelihood that our delinearization is
2071
  /// correct.
2072
  ///
2073
  /// Example:
2074
  ///
2075
  ///    A[][n]
2076
  ///    S[i,j] -> A[2i][2j+1]
2077
  ///    S[i,j] -> A[2i][2j]
2078
  ///
2079
  ///    =>
2080
  ///
2081
  ///    A[][2n]
2082
  ///    S[i,j] -> A[i][2j+1]
2083
  ///    S[i,j] -> A[i][2j]
2084
  ///
2085
  /// Constants in outer dimensions can arise when the elements of a parametric
2086
  /// multi-dimensional array are not elementary data types, but e.g.,
2087
  /// structures.
2088
  void foldSizeConstantsToRight();
2089
2090
  /// Fold memory accesses to handle parametric offset.
2091
  ///
2092
  /// As a post-processing step, we 'fold' memory accesses to parametric
2093
  /// offsets in the access functions. @see MemoryAccess::foldAccess for
2094
  /// details.
2095
  void foldAccessRelations();
2096
2097
  /// Assume that all memory accesses are within bounds.
2098
  ///
2099
  /// After we have built a model of all memory accesses, we need to assume
2100
  /// that the model we built matches reality -- aka. all modeled memory
2101
  /// accesses always remain within bounds. We do this as last step, after
2102
  /// all memory accesses have been modeled and canonicalized.
2103
  void assumeNoOutOfBounds();
2104
2105
  /// Mark arrays that have memory accesses with FortranArrayDescriptor.
2106
  void markFortranArrays();
2107
2108
  /// Finalize all access relations.
2109
  ///
2110
  /// When building up access relations, temporary access relations that
2111
  /// correctly represent each individual access are constructed. However, these
2112
  /// access relations can be inconsistent or non-optimal when looking at the
2113
  /// set of accesses as a whole. This function finalizes the memory accesses
2114
  /// and constructs a globally consistent state.
2115
  void finalizeAccesses();
2116
2117
  /// Construct the schedule of this SCoP.
2118
  ///
2119
  /// @param LI The LoopInfo for the current function.
2120
  void buildSchedule(LoopInfo &LI);
2121
2122
  /// A loop stack element to keep track of per-loop information during
2123
  ///        schedule construction.
2124
  typedef struct LoopStackElement {
2125
    // The loop for which we keep information.
2126
    Loop *L;
2127
2128
    // The (possibly incomplete) schedule for this loop.
2129
    isl_schedule *Schedule;
2130
2131
    // The number of basic blocks in the current loop, for which a schedule has
2132
    // already been constructed.
2133
    unsigned NumBlocksProcessed;
2134
2135
    LoopStackElement(Loop *L, __isl_give isl_schedule *S,
2136
                     unsigned NumBlocksProcessed)
2137
2.40k
        : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
2138
  } LoopStackElementTy;
2139
2140
  /// The loop stack used for schedule construction.
2141
  ///
2142
  /// The loop stack keeps track of schedule information for a set of nested
2143
  /// loops as well as an (optional) 'nullptr' loop that models the outermost
2144
  /// schedule dimension. The loops in a loop stack always have a parent-child
2145
  /// relation where the loop at position n is the parent of the loop at
2146
  /// position n + 1.
2147
  typedef SmallVector<LoopStackElementTy, 4> LoopStackTy;
2148
2149
  /// Construct schedule information for a given Region and add the
2150
  ///        derived information to @p LoopStack.
2151
  ///
2152
  /// Given a Region we derive schedule information for all RegionNodes
2153
  /// contained in this region ensuring that the assigned execution times
2154
  /// correctly model the existing control flow relations.
2155
  ///
2156
  /// @param R              The region which to process.
2157
  /// @param LoopStack      A stack of loops that are currently under
2158
  ///                       construction.
2159
  /// @param LI The LoopInfo for the current function.
2160
  void buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI);
2161
2162
  /// Build Schedule for the region node @p RN and add the derived
2163
  ///        information to @p LoopStack.
2164
  ///
2165
  /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
2166
  /// schedule for this @p RN and also finalize loop schedules in case the
2167
  /// current @p RN completes the loop.
2168
  ///
2169
  /// In case @p RN is a not-non-affine Region, we delegate the construction to
2170
  /// buildSchedule(Region *R, ...).
2171
  ///
2172
  /// @param RN             The RegionNode region traversed.
2173
  /// @param LoopStack      A stack of loops that are currently under
2174
  ///                       construction.
2175
  /// @param LI The LoopInfo for the current function.
2176
  void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI);
2177
2178
  /// Collect all memory access relations of a given type.
2179
  ///
2180
  /// @param Predicate A predicate function that returns true if an access is
2181
  ///                  of a given type.
2182
  ///
2183
  /// @returns The set of memory accesses in the scop that match the predicate.
2184
  __isl_give isl_union_map *
2185
  getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
2186
2187
  /// @name Helper functions for printing the Scop.
2188
  ///
2189
  //@{
2190
  void printContext(raw_ostream &OS) const;
2191
  void printArrayInfo(raw_ostream &OS) const;
2192
  void printStatements(raw_ostream &OS) const;
2193
  void printAliasAssumptions(raw_ostream &OS) const;
2194
  //@}
2195
2196
  friend class ScopBuilder;
2197
2198
public:
2199
  ~Scop();
2200
2201
  /// Get the count of copy statements added to this Scop.
2202
  ///
2203
  /// @return The count of copy statements added to this Scop.
2204
18
  unsigned getCopyStmtsNum() { return CopyStmtsNum; }
2205
2206
  /// Create a new copy statement.
2207
  ///
2208
  /// A new statement will be created and added to the statement vector.
2209
  ///
2210
  /// @param Stmt       The parent statement.
2211
  /// @param SourceRel  The source location.
2212
  /// @param TargetRel  The target location.
2213
  /// @param Domain     The original domain under which the copy statement would
2214
  ///                   be executed.
2215
  ScopStmt *addScopStmt(__isl_take isl_map *SourceRel,
2216
                        __isl_take isl_map *TargetRel,
2217
                        __isl_take isl_set *Domain);
2218
2219
  /// Add the access function to all MemoryAccess objects of the Scop
2220
  ///        created in this pass.
2221
4.32k
  void addAccessFunction(MemoryAccess *Access) {
2222
4.32k
    AccessFunctions.emplace_back(Access);
2223
4.32k
  }
2224
2225
  ScalarEvolution *getSE() const;
2226
2227
  /// Get the count of parameters used in this Scop.
2228
  ///
2229
  /// @return The count of parameters used in this Scop.
2230
1.05k
  size_t getNumParams() const { return Parameters.size(); }
2231
2232
  /// Take a list of parameters and add the new ones to the scop.
2233
  void addParams(const ParameterSetTy &NewParameters);
2234
2235
  /// Return an iterator range containing the scop parameters.
2236
275
  iterator_range<ParameterSetTy::iterator> parameters() const {
2237
275
    return make_range(Parameters.begin(), Parameters.end());
2238
275
  }
2239
2240
  /// Return whether this scop is empty, i.e. contains no statements that
2241
  /// could be executed.
2242
1.02k
  bool isEmpty() const { return Stmts.empty(); }
2243
2244
0
  const StringRef getName() const { return name; }
2245
2246
  typedef ArrayInfoSetTy::iterator array_iterator;
2247
  typedef ArrayInfoSetTy::const_iterator const_array_iterator;
2248
  typedef iterator_range<ArrayInfoSetTy::iterator> array_range;
2249
  typedef iterator_range<ArrayInfoSetTy::const_iterator> const_array_range;
2250
2251
3.87k
  inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
2252
2253
3.87k
  inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
2254
2255
844
  inline const_array_iterator array_begin() const {
2256
844
    return ScopArrayInfoSet.begin();
2257
844
  }
2258
2259
844
  inline const_array_iterator array_end() const {
2260
844
    return ScopArrayInfoSet.end();
2261
844
  }
2262
2263
3.59k
  inline array_range arrays() {
2264
3.59k
    return array_range(array_begin(), array_end());
2265
3.59k
  }
2266
2267
844
  inline const_array_range arrays() const {
2268
844
    return const_array_range(array_begin(), array_end());
2269
844
  }
2270
2271
  /// Return the isl_id that represents a certain parameter.
2272
  ///
2273
  /// @param Parameter A SCEV that was recognized as a Parameter.
2274
  ///
2275
  /// @return The corresponding isl_id or NULL otherwise.
2276
  __isl_give isl_id *getIdForParam(const SCEV *Parameter);
2277
2278
  /// Get the maximum region of this static control part.
2279
  ///
2280
  /// @return The maximum region of this static control part.
2281
30.4k
  inline const Region &getRegion() const { return R; }
2282
42.1k
  inline Region &getRegion() { return R; }
2283
2284
  /// Return the function this SCoP is in.
2285
7.74k
  Function &getFunction() const { return *R.getEntry()->getParent(); }
2286
2287
  /// Check if @p L is contained in the SCoP.
2288
10.3k
  bool contains(const Loop *L) const { return R.contains(L); }
2289
2290
  /// Check if @p BB is contained in the SCoP.
2291
18.6k
  bool contains(const BasicBlock *BB) const { return R.contains(BB); }
2292
2293
  /// Check if @p I is contained in the SCoP.
2294
5.34k
  bool contains(const Instruction *I) const { return R.contains(I); }
2295
2296
  /// Return the unique exit block of the SCoP.
2297
2.58k
  BasicBlock *getExit() const { return R.getExit(); }
2298
2299
  /// Return the unique exiting block of the SCoP if any.
2300
619
  BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
2301
2302
  /// Return the unique entry block of the SCoP.
2303
4.10k
  BasicBlock *getEntry() const { return R.getEntry(); }
2304
2305
  /// Return the unique entering block of the SCoP if any.
2306
835
  BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
2307
2308
  /// Return true if @p BB is the exit block of the SCoP.
2309
1.69k
  bool isExit(BasicBlock *BB) const { return getExit() == BB; }
2310
2311
  /// Return a range of all basic blocks in the SCoP.
2312
2.60k
  Region::block_range blocks() const { return R.blocks(); }
2313
2314
  /// Return true if and only if @p BB dominates the SCoP.
2315
  bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
2316
2317
  /// Get the maximum depth of the loop.
2318
  ///
2319
  /// @return The maximum depth of the loop.
2320
1.39k
  inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
2321
2322
  /// Return the invariant equivalence class for @p Val if any.
2323
  InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
2324
2325
  /// Return the set of invariant accesses.
2326
290
  InvariantEquivClassesTy &getInvariantAccesses() {
2327
290
    return InvariantEquivClasses;
2328
290
  }
2329
2330
  /// Check if the scop has any invariant access.
2331
0
  bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
2332
2333
  /// Mark the SCoP as optimized by the scheduler.
2334
30
  void markAsOptimized() { IsOptimized = true; }
2335
2336
  /// Check if the SCoP has been optimized by the scheduler.
2337
0
  bool isOptimized() const { return IsOptimized; }
2338
2339
  /// Get the name of the entry and exit blocks of this Scop.
2340
  ///
2341
  /// These along with the function name can uniquely identify a Scop.
2342
  ///
2343
  /// @return std::pair whose first element is the entry name & second element
2344
  ///         is the exit name.
2345
  std::pair<std::string, std::string> getEntryExitStr() const;
2346
2347
  /// Get the name of this Scop.
2348
  std::string getNameStr() const;
2349
2350
  /// Get the constraint on parameter of this Scop.
2351
  ///
2352
  /// @return The constraint on parameter of this Scop.
2353
  __isl_give isl_set *getContext() const;
2354
  __isl_give isl_space *getParamSpace() const;
2355
2356
  /// Get the assumed context for this Scop.
2357
  ///
2358
  /// @return The assumed context of this Scop.
2359
  __isl_give isl_set *getAssumedContext() const;
2360
2361
  /// Return true if the optimized SCoP can be executed.
2362
  ///
2363
  /// In addition to the runtime check context this will also utilize the domain
2364
  /// constraints to decide it the optimized version can actually be executed.
2365
  ///
2366
  /// @returns True if the optimized SCoP can be executed.
2367
  bool hasFeasibleRuntimeContext() const;
2368
2369
  /// Check if the assumption in @p Set is trivial or not.
2370
  ///
2371
  /// @param Set  The relations between parameters that are assumed to hold.
2372
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2373
  ///             (needed/assumptions) or negative (invalid/restrictions).
2374
  ///
2375
  /// @returns True if the assumption @p Set is not trivial.
2376
  bool isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign);
2377
2378
  /// Track and report an assumption.
2379
  ///
2380
  /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
2381
  /// -pass-remarks-analysis=polly-scops' to output the assumptions.
2382
  ///
2383
  /// @param Kind The assumption kind describing the underlying cause.
2384
  /// @param Set  The relations between parameters that are assumed to hold.
2385
  /// @param Loc  The location in the source that caused this assumption.
2386
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2387
  ///             (needed/assumptions) or negative (invalid/restrictions).
2388
  ///
2389
  /// @returns True if the assumption is not trivial.
2390
  bool trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2391
                       DebugLoc Loc, AssumptionSign Sign);
2392
2393
  /// Add assumptions to assumed context.
2394
  ///
2395
  /// The assumptions added will be assumed to hold during the execution of the
2396
  /// scop. However, as they are generally not statically provable, at code
2397
  /// generation time run-time checks will be generated that ensure the
2398
  /// assumptions hold.
2399
  ///
2400
  /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
2401
  ///          that assumptions do not change the set of statement instances
2402
  ///          executed.
2403
  ///
2404
  /// @param Kind The assumption kind describing the underlying cause.
2405
  /// @param Set  The relations between parameters that are assumed to hold.
2406
  /// @param Loc  The location in the source that caused this assumption.
2407
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2408
  ///             (needed/assumptions) or negative (invalid/restrictions).
2409
  void addAssumption(AssumptionKind Kind, __isl_take isl_set *Set, DebugLoc Loc,
2410
                     AssumptionSign Sign);
2411
2412
  /// Record an assumption for later addition to the assumed context.
2413
  ///
2414
  /// This function will add the assumption to the RecordedAssumptions. This
2415
  /// collection will be added (@see addAssumption) to the assumed context once
2416
  /// all paramaters are known and the context is fully build.
2417
  ///
2418
  /// @param Kind The assumption kind describing the underlying cause.
2419
  /// @param Set  The relations between parameters that are assumed to hold.
2420
  /// @param Loc  The location in the source that caused this assumption.
2421
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2422
  ///             (needed/assumptions) or negative (invalid/restrictions).
2423
  /// @param BB   The block in which this assumption was taken. If it is
2424
  ///             set, the domain of that block will be used to simplify the
2425
  ///             actual assumption in @p Set once it is added. This is useful
2426
  ///             if the assumption was created prior to the domain.
2427
  void recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
2428
                        DebugLoc Loc, AssumptionSign Sign,
2429
                        BasicBlock *BB = nullptr);
2430
2431
  /// Add all recorded assumptions to the assumed context.
2432
  void addRecordedAssumptions();
2433
2434
  /// Mark the scop as invalid.
2435
  ///
2436
  /// This method adds an assumption to the scop that is always invalid. As a
2437
  /// result, the scop will not be optimized later on. This function is commonly
2438
  /// called when a condition makes it impossible (or too compile time
2439
  /// expensive) to process this scop any further.
2440
  ///
2441
  /// @param Kind The assumption kind describing the underlying cause.
2442
  /// @param Loc  The location in the source that triggered .
2443
  void invalidate(AssumptionKind Kind, DebugLoc Loc);
2444
2445
  /// Get the invalid context for this Scop.
2446
  ///
2447
  /// @return The invalid context of this Scop.
2448
  __isl_give isl_set *getInvalidContext() const;
2449
2450
  /// Return true if and only if the InvalidContext is trivial (=empty).
2451
444
  bool hasTrivialInvalidContext() const {
2452
444
    return isl_set_is_empty(InvalidContext);
2453
444
  }
2454
2455
  /// A vector of memory accesses that belong to an alias group.
2456
  typedef SmallVector<MemoryAccess *, 4> AliasGroupTy;
2457
2458
  /// A vector of alias groups.
2459
  typedef SmallVector<Scop::AliasGroupTy, 4> AliasGroupVectorTy;
2460
2461
  /// Build the alias checks for this SCoP.
2462
  bool buildAliasChecks(AliasAnalysis &AA);
2463
2464
  /// Build all alias groups for this SCoP.
2465
  ///
2466
  /// @returns True if __no__ error occurred, false otherwise.
2467
  bool buildAliasGroups(AliasAnalysis &AA);
2468
2469
  /// Build alias groups for all memory accesses in the Scop.
2470
  ///
2471
  /// Using the alias analysis and an alias set tracker we build alias sets
2472
  /// for all memory accesses inside the Scop. For each alias set we then map
2473
  /// the aliasing pointers back to the memory accesses we know, thus obtain
2474
  /// groups of memory accesses which might alias. We also collect the set of
2475
  /// arrays through which memory is written.
2476
  ///
2477
  /// @param AA A reference to the alias analysis.
2478
  ///
2479
  /// @returns A pair consistent of a vector of alias groups and a set of arrays
2480
  ///          through which memory is written.
2481
  std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2482
  buildAliasGroupsForAccesses(AliasAnalysis &AA);
2483
2484
  ///  Split alias groups by iteration domains.
2485
  ///
2486
  ///  We split each group based on the domains of the minimal/maximal accesses.
2487
  ///  That means two minimal/maximal accesses are only in a group if their
2488
  ///  access domains intersect. Otherwise, they are in different groups.
2489
  ///
2490
  ///  @param AliasGroups The alias groups to split
2491
  void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
2492
2493
  /// Build a given alias group and its access data.
2494
  ///
2495
  /// @param AliasGroup     The alias group to build.
2496
  /// @param HasWriteAccess A set of arrays through which memory is not only
2497
  ///                       read, but also written.
2498
  ///
2499
  /// @returns True if __no__ error occurred, false otherwise.
2500
  bool buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2501
                       DenseSet<const ScopArrayInfo *> HasWriteAccess);
2502
2503
  /// Return all alias groups for this SCoP.
2504
444
  const MinMaxVectorPairVectorTy &getAliasGroups() const {
2505
444
    return MinMaxAliasGroups;
2506
444
  }
2507
2508
  /// Get an isl string representing the context.
2509
  std::string getContextStr() const;
2510
2511
  /// Get an isl string representing the assumed context.
2512
  std::string getAssumedContextStr() const;
2513
2514
  /// Get an isl string representing the invalid context.
2515
  std::string getInvalidContextStr() const;
2516
2517
  /// Return the ScopStmt for the given @p BB or nullptr if there is
2518
  ///        none.
2519
  ScopStmt *getStmtFor(BasicBlock *BB) const;
2520
2521
  /// Return the last statement representing @p BB.
2522
  ///
2523
  /// Of the sequence of statements that represent a @p BB, this is the last one
2524
  /// to be executed. It is typically used to determine which instruction to add
2525
  /// a MemoryKind::PHI WRITE to. For this purpose, it is not strictly required
2526
  /// to be executed last, only that the incoming value is available in it.
2527
489
  ScopStmt *getLastStmtFor(BasicBlock *BB) const { return getStmtFor(BB); }
2528
2529
  /// Return the ScopStmt that represents the Region @p R, or nullptr if
2530
  ///        it is not represented by any statement in this Scop.
2531
  ScopStmt *getStmtFor(Region *R) const;
2532
2533
  /// Return the ScopStmt that represents @p RN; can return nullptr if
2534
  ///        the RegionNode is not within the SCoP or has been removed due to
2535
  ///        simplifications.
2536
  ScopStmt *getStmtFor(RegionNode *RN) const;
2537
2538
  /// Return the ScopStmt an instruction belongs to, or nullptr if it
2539
  ///        does not belong to any statement in this Scop.
2540
832
  ScopStmt *getStmtFor(Instruction *Inst) const {
2541
832
    return getStmtFor(Inst->getParent());
2542
832
  }
2543
2544
  /// Return the number of statements in the SCoP.
2545
178
  size_t getSize() const { return Stmts.size(); }
2546
2547
  /// @name Statements Iterators
2548
  ///
2549
  /// These iterators iterate over all statements of this Scop.
2550
  //@{
2551
  typedef StmtSet::iterator iterator;
2552
  typedef StmtSet::const_iterator const_iterator;
2553
2554
11.5k
  iterator begin() { return Stmts.begin(); }
2555
11.5k
  iterator end() { return Stmts.end(); }
2556
11.1k
  const_iterator begin() const { return Stmts.begin(); }
2557
11.1k
  const_iterator end() const { return Stmts.end(); }
2558
2559
  typedef StmtSet::reverse_iterator reverse_iterator;
2560
  typedef StmtSet::const_reverse_iterator const_reverse_iterator;
2561
2562
0
  reverse_iterator rbegin() { return Stmts.rbegin(); }
2563
0
  reverse_iterator rend() { return Stmts.rend(); }
2564
0
  const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
2565
0
  const_reverse_iterator rend() const { return Stmts.rend(); }
2566
  //@}
2567
2568
  /// Return the set of required invariant loads.
2569
12.2k
  const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
2570
12.2k
    return DC.RequiredILS;
2571
12.2k
  }
2572
2573
  /// Add @p LI to the set of required invariant loads.
2574
72
  void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
2575
2576
  /// Return true if and only if @p LI is a required invariant load.
2577
55
  bool isRequiredInvariantLoad(LoadInst *LI) const {
2578
55
    return getRequiredInvariantLoads().count(LI);
2579
55
  }
2580
2581
  /// Return the set of boxed (thus overapproximated) loops.
2582
103
  const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
2583
2584
  /// Return true if and only if @p R is a non-affine subregion.
2585
8.61k
  bool isNonAffineSubRegion(const Region *R) {
2586
8.61k
    return DC.NonAffineSubRegionSet.count(R);
2587
8.61k
  }
2588
2589
2.92k
  const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
2590
2591
  /// Return the (possibly new) ScopArrayInfo object for @p Access.
2592
  ///
2593
  /// @param ElementType The type of the elements stored in this array.
2594
  /// @param Kind        The kind of the array info object.
2595
  /// @param BaseName    The optional name of this memory reference.
2596
  const ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr,
2597
                                                Type *ElementType,
2598
                                                ArrayRef<const SCEV *> Sizes,
2599
                                                MemoryKind Kind,
2600
                                                const char *BaseName = nullptr);
2601
2602
  /// Create an array and return the corresponding ScopArrayInfo object.
2603
  ///
2604
  /// @param ElementType The type of the elements stored in this array.
2605
  /// @param BaseName    The name of this memory reference.
2606
  /// @param Sizes       The sizes of dimensions.
2607
  const ScopArrayInfo *createScopArrayInfo(Type *ElementType,
2608
                                           const std::string &BaseName,
2609
                                           const std::vector<unsigned> &Sizes);
2610
2611
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2612
  ///
2613
  /// @param BasePtr   The base pointer the object has been stored for.
2614
  /// @param Kind      The kind of array info object.
2615
  ///
2616
  /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
2617
  ///          available.
2618
  const ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
2619
2620
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2621
  ///
2622
  /// @param BasePtr   The base pointer the object has been stored for.
2623
  /// @param Kind      The kind of array info object.
2624
  ///
2625
  /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
2626
  ///          available).
2627
  const ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
2628
2629
  /// Invalidate ScopArrayInfo object for base address.
2630
  ///
2631
  /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
2632
  /// @param Kind    The Kind of the ScopArrayInfo object.
2633
0
  void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
2634
0
    auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
2635
0
    if (It == ScopArrayInfoMap.end())
2636
0
      return;
2637
0
    ScopArrayInfoSet.remove(It->second.get());
2638
0
    ScopArrayInfoMap.erase(It);
2639
0
  }
2640
2641
  void setContext(__isl_take isl_set *NewContext);
2642
2643
  /// Align the parameters in the statement to the scop context
2644
  void realignParams();
2645
2646
  /// Return true if this SCoP can be profitably optimized.
2647
  ///
2648
  /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
2649
  ///                               as profitably optimizable.
2650
  ///
2651
  /// @return Whether this SCoP can be profitably optimized.
2652
  bool isProfitable(bool ScalarsAreUnprofitable) const;
2653
2654
  /// Return true if the SCoP contained at least one error block.
2655
988
  bool hasErrorBlock() const { return HasErrorBlock; }
2656
2657
  /// Return true if the underlying region has a single exiting block.
2658
1.37k
  bool hasSingleExitEdge() const { return HasSingleExitEdge; }
2659
2660
  /// Print the static control part.
2661
  ///
2662
  /// @param OS The output stream the static control part is printed to.
2663
  void print(raw_ostream &OS) const;
2664
2665
  /// Print the ScopStmt to stderr.
2666
  void dump() const;
2667
2668
  /// Get the isl context of this static control part.
2669
  ///
2670
  /// @return The isl context of this static control part.
2671
  isl_ctx *getIslCtx() const;
2672
2673
  /// Directly return the shared_ptr of the context.
2674
1.03k
  const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
2675
2676
  /// Compute the isl representation for the SCEV @p E
2677
  ///
2678
  /// @param E  The SCEV that should be translated.
2679
  /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
2680
  ///           SCEVs known to not reference any loops in the SCoP can be
2681
  ///           passed without a @p BB.
2682
  /// @param NonNegative Flag to indicate the @p E has to be non-negative.
2683
  ///
2684
  /// Note that this function will always return a valid isl_pw_aff. However, if
2685
  /// the translation of @p E was deemed to complex the SCoP is invalidated and
2686
  /// a dummy value of appropriate dimension is returned. This allows to bail
2687
  /// for complex cases without "error handling code" needed on the users side.
2688
  __isl_give PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
2689
                             bool NonNegative = false);
2690
2691
  /// Compute the isl representation for the SCEV @p E
2692
  ///
2693
  /// This function is like @see Scop::getPwAff() but strips away the invalid
2694
  /// domain part associated with the piecewise affine function.
2695
  __isl_give isl_pw_aff *getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr);
2696
2697
  /// Return the domain of @p Stmt.
2698
  ///
2699
  /// @param Stmt The statement for which the conditions should be returned.
2700
  __isl_give isl_set *getDomainConditions(const ScopStmt *Stmt) const;
2701
2702
  /// Return the domain of @p BB.
2703
  ///
2704
  /// @param BB The block for which the conditions should be returned.
2705
  __isl_give isl_set *getDomainConditions(BasicBlock *BB) const;
2706
2707
  /// Get a union set containing the iteration domains of all statements.
2708
  __isl_give isl_union_set *getDomains() const;
2709
2710
  /// Get a union map of all may-writes performed in the SCoP.
2711
  __isl_give isl_union_map *getMayWrites();
2712
2713
  /// Get a union map of all must-writes performed in the SCoP.
2714
  __isl_give isl_union_map *getMustWrites();
2715
2716
  /// Get a union map of all writes performed in the SCoP.
2717
  __isl_give isl_union_map *getWrites();
2718
2719
  /// Get a union map of all reads performed in the SCoP.
2720
  __isl_give isl_union_map *getReads();
2721
2722
  /// Get a union map of all memory accesses performed in the SCoP.
2723
  __isl_give isl_union_map *getAccesses();
2724
2725
  /// Get the schedule of all the statements in the SCoP.
2726
  ///
2727
  /// @return The schedule of all the statements in the SCoP, if the schedule of
2728
  /// the Scop does not contain extension nodes, and nullptr, otherwise.
2729
  __isl_give isl_union_map *getSchedule() const;
2730
2731
  /// Get a schedule tree describing the schedule of all statements.
2732
  __isl_give isl_schedule *getScheduleTree() const;
2733
2734
  /// Update the current schedule
2735
  ///
2736
  /// NewSchedule The new schedule (given as a flat union-map).
2737
  void setSchedule(__isl_take isl_union_map *NewSchedule);
2738
2739
  /// Update the current schedule
2740
  ///
2741
  /// NewSchedule The new schedule (given as schedule tree).
2742
  void setScheduleTree(__isl_take isl_schedule *NewSchedule);
2743
2744
  /// Intersects the domains of all statements in the SCoP.
2745
  ///
2746
  /// @return true if a change was made
2747
  bool restrictDomains(__isl_take isl_union_set *Domain);
2748
2749
  /// Get the depth of a loop relative to the outermost loop in the Scop.
2750
  ///
2751
  /// This will return
2752
  ///    0 if @p L is an outermost loop in the SCoP
2753
  ///   >0 for other loops in the SCoP
2754
  ///   -1 if @p L is nullptr or there is no outermost loop in the SCoP
2755
  int getRelativeLoopDepth(const Loop *L) const;
2756
2757
  /// Find the ScopArrayInfo associated with an isl Id
2758
  ///        that has name @p Name.
2759
  ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
2760
2761
  /// Check whether @p Schedule contains extension nodes.
2762
  ///
2763
  /// @return true if @p Schedule contains extension nodes.
2764
  static bool containsExtensionNode(__isl_keep isl_schedule *Schedule);
2765
2766
  /// Simplify the SCoP representation.
2767
  ///
2768
  /// @param AfterHoisting Whether it is called after invariant load hoisting.
2769
  ///                      When true, also removes statements without
2770
  ///                      side-effects.
2771
  void simplifySCoP(bool AfterHoisting);
2772
2773
  /// Get the next free array index.
2774
  ///
2775
  /// This function returns a unique index which can be used to identify an
2776
  /// array.
2777
2.06k
  long getNextArrayIdx() { return ArrayIdx++; }
2778
2779
  /// Get the next free statement index.
2780
  ///
2781
  /// This function returns a unique index which can be used to identify a
2782
  /// statement.
2783
4.93k
  long getNextStmtIdx() { return StmtIdx++; }
2784
};
2785
2786
/// Print Scop scop to raw_ostream O.
2787
0
static inline raw_ostream &operator<<(raw_ostream &O, const Scop &scop) {
2788
0
  scop.print(O);
2789
0
  return O;
2790
0
}
Unexecuted instantiation: DependenceInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: PolyhedralInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScopDetection.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScopInfo.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScopBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScopPass.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: PruneUnprofitable.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: BlockGenerators.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: IslAst.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: IslExprBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: IslNodeBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: CodeGeneration.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: IRBuilder.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: Utils.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: PerfMonitor.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: JSONExporter.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: SCEVAffinator.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: SCEVValidator.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: RegisterPasses.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScopHelper.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: VirtualInstruction.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: DeadCodeElimination.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: ScheduleOptimizer.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: FlattenSchedule.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: DeLICM.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
Unexecuted instantiation: Simplify.cpp:polly::operator<<(llvm::raw_ostream&, polly::Scop const&)
2791
2792
/// The legacy pass manager's analysis pass to compute scop information
2793
///        for a region.
2794
class ScopInfoRegionPass : public RegionPass {
2795
  /// The Scop pointer which is used to construct a Scop.
2796
  std::unique_ptr<Scop> S;
2797
2798
public:
2799
  static char ID; // Pass identification, replacement for typeid
2800
2801
960
  ScopInfoRegionPass() : RegionPass(ID) {}
2802
960
  ~ScopInfoRegionPass() {}
2803
2804
  /// Build Scop object, the Polly IR of static control
2805
  ///        part for the current SESE-Region.
2806
  ///
2807
  /// @return If the current region is a valid for a static control part,
2808
  ///         return the Polly IR representing this static control part,
2809
  ///         return null otherwise.
2810
5.46k
  Scop *getScop() { return S.get(); }
2811
0
  const Scop *getScop() const { return S.get(); }
2812
2813
  /// Calculate the polyhedral scop information for a given Region.
2814
  bool runOnRegion(Region *R, RGPassManager &RGM) override;
2815
2816
3.57k
  void releaseMemory() override { S.reset(); }
2817
2818
  void print(raw_ostream &O, const Module *M = nullptr) const override;
2819
2820
  void getAnalysisUsage(AnalysisUsage &AU) const override;
2821
};
2822
2823
class ScopInfo {
2824
public:
2825
  using RegionToScopMapTy = DenseMap<Region *, std::unique_ptr<Scop>>;
2826
  using iterator = RegionToScopMapTy::iterator;
2827
  using const_iterator = RegionToScopMapTy::const_iterator;
2828
2829
private:
2830
  /// A map of Region to its Scop object containing
2831
  ///        Polly IR of static control part.
2832
  RegionToScopMapTy RegionToScopMap;
2833
2834
public:
2835
  ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
2836
           LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
2837
           AssumptionCache &AC);
2838
2839
  /// Get the Scop object for the given Region.
2840
  ///
2841
  /// @return If the given region is the maximal region within a scop, return
2842
  ///         the scop object. If the given region is a subregion, return a
2843
  ///         nullptr. Top level region containing the entry block of a function
2844
  ///         is not considered in the scop creation.
2845
0
  Scop *getScop(Region *R) const {
2846
0
    auto MapIt = RegionToScopMap.find(R);
2847
0
    if (MapIt != RegionToScopMap.end())
2848
0
      return MapIt->second.get();
2849
0
    return nullptr;
2850
0
  }
2851
2852
82
  iterator begin() { return RegionToScopMap.begin(); }
2853
82
  iterator end() { return RegionToScopMap.end(); }
2854
0
  const_iterator begin() const { return RegionToScopMap.begin(); }
2855
0
  const_iterator end() const { return RegionToScopMap.end(); }
2856
0
  bool empty() const { return RegionToScopMap.empty(); }
2857
};
2858
2859
struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
2860
  static AnalysisKey Key;
2861
  using Result = ScopInfo;
2862
  Result run(Function &, FunctionAnalysisManager &);
2863
};
2864
2865
struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
2866
0
  ScopInfoPrinterPass(raw_ostream &O) : Stream(O) {}
2867
  PreservedAnalyses run(Function &, FunctionAnalysisManager &);
2868
  raw_ostream &Stream;
2869
};
2870
2871
//===----------------------------------------------------------------------===//
2872
/// The legacy pass manager's analysis pass to compute scop information
2873
///        for the whole function.
2874
///
2875
/// This pass will maintain a map of the maximal region within a scop to its
2876
/// scop object for all the feasible scops present in a function.
2877
/// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
2878
/// region pass manager.
2879
class ScopInfoWrapperPass : public FunctionPass {
2880
  std::unique_ptr<ScopInfo> Result;
2881
2882
public:
2883
44
  ScopInfoWrapperPass() : FunctionPass(ID) {}
2884
44
  ~ScopInfoWrapperPass() = default;
2885
2886
  static char ID; // Pass identification, replacement for typeid
2887
2888
45
  ScopInfo *getSI() { return Result.get(); }
2889
0
  const ScopInfo *getSI() const { return Result.get(); }
2890
2891
  /// Calculate all the polyhedral scops for a given function.
2892
  bool runOnFunction(Function &F) override;
2893
2894
49
  void releaseMemory() override { Result.reset(); }
2895
2896
  void print(raw_ostream &O, const Module *M = nullptr) const override;
2897
2898
  void getAnalysisUsage(AnalysisUsage &AU) const override;
2899
};
2900
2901
} // end namespace polly
2902
2903
namespace llvm {
2904
class PassRegistry;
2905
void initializeScopInfoRegionPassPass(llvm::PassRegistry &);
2906
void initializeScopInfoWrapperPassPass(llvm::PassRegistry &);
2907
} // namespace llvm
2908
2909
#endif