Coverage Report

Created: 2017-10-03 07:32

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