Coverage Report

Created: 2017-08-18 19:41

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