Post-commit fix of a comment
[polly-mirror.git] / include / polly / ScopInfo.h
blobc6b47c134ae5a6728c4ecfb86bd594974a7e509b
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).
13 // This representation is shared among several tools in the polyhedral
14 // community, which are e.g. CLooG, Pluto, Loopo, Graphite.
16 //===----------------------------------------------------------------------===//
18 #ifndef POLLY_SCOP_INFO_H
19 #define POLLY_SCOP_INFO_H
21 #include "polly/ScopDetection.h"
22 #include "polly/Support/SCEVAffinator.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/Analysis/RegionPass.h"
26 #include "llvm/IR/PassManager.h"
27 #include "isl/aff.h"
28 #include "isl/ctx.h"
29 #include "isl/set.h"
31 #include <deque>
32 #include <forward_list>
34 using namespace llvm;
36 namespace llvm {
37 class AssumptionCache;
38 class Loop;
39 class LoopInfo;
40 class PHINode;
41 class ScalarEvolution;
42 class SCEV;
43 class SCEVAddRecExpr;
44 class Type;
45 } // namespace llvm
47 struct isl_ctx;
48 struct isl_map;
49 struct isl_basic_map;
50 struct isl_id;
51 struct isl_set;
52 struct isl_union_set;
53 struct isl_union_map;
54 struct isl_space;
55 struct isl_ast_build;
56 struct isl_constraint;
57 struct isl_pw_aff;
58 struct isl_pw_multi_aff;
59 struct isl_schedule;
61 namespace polly {
63 class MemoryAccess;
64 class Scop;
65 class ScopStmt;
66 class ScopBuilder;
68 //===---------------------------------------------------------------------===//
70 extern bool UseInstructionNames;
72 /// Enumeration of assumptions Polly can take.
73 enum AssumptionKind {
74 ALIASING,
75 INBOUNDS,
76 WRAPPING,
77 UNSIGNED,
78 PROFITABLE,
79 ERRORBLOCK,
80 COMPLEXITY,
81 INFINITELOOP,
82 INVARIANTLOAD,
83 DELINEARIZATION,
86 /// Enum to distinguish between assumptions and restrictions.
87 enum AssumptionSign { AS_ASSUMPTION, AS_RESTRICTION };
89 /// The different memory kinds used in Polly.
90 ///
91 /// We distinguish between arrays and various scalar memory objects. We use
92 /// the term ``array'' to describe memory objects that consist of a set of
93 /// individual data elements arranged in a multi-dimensional grid. A scalar
94 /// memory object describes an individual data element and is used to model
95 /// the definition and uses of llvm::Values.
96 ///
97 /// The polyhedral model does traditionally not reason about SSA values. To
98 /// reason about llvm::Values we model them "as if" they were zero-dimensional
99 /// memory objects, even though they were not actually allocated in (main)
100 /// memory. Memory for such objects is only alloca[ed] at CodeGeneration
101 /// time. To relate the memory slots used during code generation with the
102 /// llvm::Values they belong to the new names for these corresponding stack
103 /// slots are derived by appending suffixes (currently ".s2a" and ".phiops")
104 /// to the name of the original llvm::Value. To describe how def/uses are
105 /// modeled exactly we use these suffixes here as well.
107 /// There are currently four different kinds of memory objects:
108 enum class MemoryKind {
109 /// MemoryKind::Array: Models a one or multi-dimensional array
111 /// A memory object that can be described by a multi-dimensional array.
112 /// Memory objects of this type are used to model actual multi-dimensional
113 /// arrays as they exist in LLVM-IR, but they are also used to describe
114 /// other objects:
115 /// - A single data element allocated on the stack using 'alloca' is
116 /// modeled as a one-dimensional, single-element array.
117 /// - A single data element allocated as a global variable is modeled as
118 /// one-dimensional, single-element array.
119 /// - Certain multi-dimensional arrays with variable size, which in
120 /// LLVM-IR are commonly expressed as a single-dimensional access with a
121 /// complicated access function, are modeled as multi-dimensional
122 /// memory objects (grep for "delinearization").
123 Array,
125 /// MemoryKind::Value: Models an llvm::Value
127 /// Memory objects of type MemoryKind::Value are used to model the data flow
128 /// induced by llvm::Values. For each llvm::Value that is used across
129 /// BasicBocks one ScopArrayInfo object is created. A single memory WRITE
130 /// stores the llvm::Value at its definition into the memory object and at
131 /// each use of the llvm::Value (ignoring trivial intra-block uses) a
132 /// corresponding READ is added. For instance, the use/def chain of a
133 /// llvm::Value %V depicted below
134 /// ______________________
135 /// |DefBB: |
136 /// | %V = float op ... |
137 /// ----------------------
138 /// | |
139 /// _________________ _________________
140 /// |UseBB1: | |UseBB2: |
141 /// | use float %V | | use float %V |
142 /// ----------------- -----------------
144 /// is modeled as if the following memory accesses occured:
146 /// __________________________
147 /// |entry: |
148 /// | %V.s2a = alloca float |
149 /// --------------------------
150 /// |
151 /// ___________________________________
152 /// |DefBB: |
153 /// | store %float %V, float* %V.s2a |
154 /// -----------------------------------
155 /// | |
156 /// ____________________________________ ___________________________________
157 /// |UseBB1: | |UseBB2: |
158 /// | %V.reload1 = load float* %V.s2a | | %V.reload2 = load float* %V.s2a|
159 /// | use float %V.reload1 | | use float %V.reload2 |
160 /// ------------------------------------ -----------------------------------
162 Value,
164 /// MemoryKind::PHI: Models PHI nodes within the SCoP
166 /// Besides the MemoryKind::Value memory object used to model the normal
167 /// llvm::Value dependences described above, PHI nodes require an additional
168 /// memory object of type MemoryKind::PHI to describe the forwarding of values
169 /// to
170 /// the PHI node.
172 /// As an example, a PHIInst instructions
174 /// %PHI = phi float [ %Val1, %IncomingBlock1 ], [ %Val2, %IncomingBlock2 ]
176 /// is modeled as if the accesses occured this way:
178 /// _______________________________
179 /// |entry: |
180 /// | %PHI.phiops = alloca float |
181 /// -------------------------------
182 /// | |
183 /// __________________________________ __________________________________
184 /// |IncomingBlock1: | |IncomingBlock2: |
185 /// | ... | | ... |
186 /// | store float %Val1 %PHI.phiops | | store float %Val2 %PHI.phiops |
187 /// | br label % JoinBlock | | br label %JoinBlock |
188 /// ---------------------------------- ----------------------------------
189 /// \ /
190 /// \ /
191 /// _________________________________________
192 /// |JoinBlock: |
193 /// | %PHI = load float, float* PHI.phiops |
194 /// -----------------------------------------
196 /// Note that there can also be a scalar write access for %PHI if used in a
197 /// different BasicBlock, i.e. there can be a memory object %PHI.phiops as
198 /// well as a memory object %PHI.s2a.
199 PHI,
201 /// MemoryKind::ExitPHI: Models PHI nodes in the SCoP's exit block
203 /// For PHI nodes in the Scop's exit block a special memory object kind is
204 /// used. The modeling used is identical to MemoryKind::PHI, with the
205 /// exception
206 /// that there are no READs from these memory objects. The PHINode's
207 /// llvm::Value is treated as a value escaping the SCoP. WRITE accesses
208 /// write directly to the escaping value's ".s2a" alloca.
209 ExitPHI
212 /// Maps from a loop to the affine function expressing its backedge taken count.
213 /// The backedge taken count already enough to express iteration domain as we
214 /// only allow loops with canonical induction variable.
215 /// A canonical induction variable is:
216 /// an integer recurrence that starts at 0 and increments by one each time
217 /// through the loop.
218 typedef std::map<const Loop *, const SCEV *> LoopBoundMapType;
220 typedef std::vector<std::unique_ptr<MemoryAccess>> AccFuncVector;
222 /// A class to store information about arrays in the SCoP.
224 /// Objects are accessible via the ScoP, MemoryAccess or the id associated with
225 /// the MemoryAccess access function.
227 class ScopArrayInfo {
228 public:
229 /// Construct a ScopArrayInfo object.
231 /// @param BasePtr The array base pointer.
232 /// @param ElementType The type of the elements stored in the array.
233 /// @param IslCtx The isl context used to create the base pointer id.
234 /// @param DimensionSizes A vector containing the size of each dimension.
235 /// @param Kind The kind of the array object.
236 /// @param DL The data layout of the module.
237 /// @param S The scop this array object belongs to.
238 /// @param BaseName The optional name of this memory reference.
239 ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *IslCtx,
240 ArrayRef<const SCEV *> DimensionSizes, MemoryKind Kind,
241 const DataLayout &DL, Scop *S, const char *BaseName = nullptr);
243 /// Update the element type of the ScopArrayInfo object.
245 /// Memory accesses referencing this ScopArrayInfo object may use
246 /// different element sizes. This function ensures the canonical element type
247 /// stored is small enough to model accesses to the current element type as
248 /// well as to @p NewElementType.
250 /// @param NewElementType An element type that is used to access this array.
251 void updateElementType(Type *NewElementType);
253 /// Update the sizes of the ScopArrayInfo object.
255 /// A ScopArrayInfo object may be created without all outer dimensions being
256 /// available. This function is called when new memory accesses are added for
257 /// this ScopArrayInfo object. It verifies that sizes are compatible and adds
258 /// additional outer array dimensions, if needed.
260 /// @param Sizes A vector of array sizes where the rightmost array
261 /// sizes need to match the innermost array sizes already
262 /// defined in SAI.
263 /// @param CheckConsistency Update sizes, even if new sizes are inconsistent
264 /// with old sizes
265 bool updateSizes(ArrayRef<const SCEV *> Sizes, bool CheckConsistency = true);
267 /// Make the ScopArrayInfo model a Fortran array.
268 /// It receives the Fortran array descriptor and stores this.
269 /// It also adds a piecewise expression for the outermost dimension
270 /// since this information is available for Fortran arrays at runtime.
271 void applyAndSetFAD(Value *FAD);
273 /// Destructor to free the isl id of the base pointer.
274 ~ScopArrayInfo();
276 /// Set the base pointer to @p BP.
277 void setBasePtr(Value *BP) { BasePtr = BP; }
279 /// Return the base pointer.
280 Value *getBasePtr() const { return BasePtr; }
282 /// For indirect accesses return the origin SAI of the BP, else null.
283 const ScopArrayInfo *getBasePtrOriginSAI() const { return BasePtrOriginSAI; }
285 /// The set of derived indirect SAIs for this origin SAI.
286 const SmallSetVector<ScopArrayInfo *, 2> &getDerivedSAIs() const {
287 return DerivedSAIs;
290 /// Return the number of dimensions.
291 unsigned getNumberOfDimensions() const {
292 if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI ||
293 Kind == MemoryKind::Value)
294 return 0;
295 return DimensionSizes.size();
298 /// Return the size of dimension @p dim as SCEV*.
300 // Scalars do not have array dimensions and the first dimension of
301 // a (possibly multi-dimensional) array also does not carry any size
302 // information, in case the array is not newly created.
303 const SCEV *getDimensionSize(unsigned Dim) const {
304 assert(Dim < getNumberOfDimensions() && "Invalid dimension");
305 return DimensionSizes[Dim];
308 /// Return the size of dimension @p dim as isl_pw_aff.
310 // Scalars do not have array dimensions and the first dimension of
311 // a (possibly multi-dimensional) array also does not carry any size
312 // information, in case the array is not newly created.
313 __isl_give isl_pw_aff *getDimensionSizePw(unsigned Dim) const {
314 assert(Dim < getNumberOfDimensions() && "Invalid dimension");
315 return isl_pw_aff_copy(DimensionSizesPw[Dim]);
318 /// Get the canonical element type of this array.
320 /// @returns The canonical element type of this array.
321 Type *getElementType() const { return ElementType; }
323 /// Get element size in bytes.
324 int getElemSizeInBytes() const;
326 /// Get the name of this memory reference.
327 std::string getName() const;
329 /// Return the isl id for the base pointer.
330 __isl_give isl_id *getBasePtrId() const;
332 /// Return what kind of memory this represents.
333 MemoryKind getKind() const { return Kind; }
335 /// Is this array info modeling an llvm::Value?
336 bool isValueKind() const { return Kind == MemoryKind::Value; }
338 /// Is this array info modeling special PHI node memory?
340 /// During code generation of PHI nodes, there is a need for two kinds of
341 /// virtual storage. The normal one as it is used for all scalar dependences,
342 /// where the result of the PHI node is stored and later loaded from as well
343 /// as a second one where the incoming values of the PHI nodes are stored
344 /// into and reloaded when the PHI is executed. As both memories use the
345 /// original PHI node as virtual base pointer, we have this additional
346 /// attribute to distinguish the PHI node specific array modeling from the
347 /// normal scalar array modeling.
348 bool isPHIKind() const { return Kind == MemoryKind::PHI; }
350 /// Is this array info modeling an MemoryKind::ExitPHI?
351 bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
353 /// Is this array info modeling an array?
354 bool isArrayKind() const { return Kind == MemoryKind::Array; }
356 /// Dump a readable representation to stderr.
357 void dump() const;
359 /// Print a readable representation to @p OS.
361 /// @param SizeAsPwAff Print the size as isl_pw_aff
362 void print(raw_ostream &OS, bool SizeAsPwAff = false) const;
364 /// Access the ScopArrayInfo associated with an access function.
365 static const ScopArrayInfo *
366 getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA);
368 /// Access the ScopArrayInfo associated with an isl Id.
369 static const ScopArrayInfo *getFromId(__isl_take isl_id *Id);
371 /// Get the space of this array access.
372 __isl_give isl_space *getSpace() const;
374 /// If the array is read only
375 bool isReadOnly();
377 /// Verify that @p Array is compatible to this ScopArrayInfo.
379 /// Two arrays are compatible if their dimensionality, the sizes of their
380 /// dimensions, and their element sizes match.
382 /// @param Array The array to compare against.
384 /// @returns True, if the arrays are compatible, False otherwise.
385 bool isCompatibleWith(const ScopArrayInfo *Array) const;
387 private:
388 void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
389 DerivedSAIs.insert(DerivedSAI);
392 /// For indirect accesses this is the SAI of the BP origin.
393 const ScopArrayInfo *BasePtrOriginSAI;
395 /// For origin SAIs the set of derived indirect SAIs.
396 SmallSetVector<ScopArrayInfo *, 2> DerivedSAIs;
398 /// The base pointer.
399 AssertingVH<Value> BasePtr;
401 /// The canonical element type of this array.
403 /// The canonical element type describes the minimal accessible element in
404 /// this array. Not all elements accessed, need to be of the very same type,
405 /// but the allocation size of the type of the elements loaded/stored from/to
406 /// this array needs to be a multiple of the allocation size of the canonical
407 /// type.
408 Type *ElementType;
410 /// The isl id for the base pointer.
411 isl_id *Id;
413 /// The sizes of each dimension as SCEV*.
414 SmallVector<const SCEV *, 4> DimensionSizes;
416 /// The sizes of each dimension as isl_pw_aff.
417 SmallVector<isl_pw_aff *, 4> DimensionSizesPw;
419 /// The type of this scop array info object.
421 /// We distinguish between SCALAR, PHI and ARRAY objects.
422 MemoryKind Kind;
424 /// The data layout of the module.
425 const DataLayout &DL;
427 /// The scop this SAI object belongs to.
428 Scop &S;
430 /// If this array models a Fortran array, then this points
431 /// to the Fortran array descriptor.
432 Value *FAD;
435 /// Represent memory accesses in statements.
436 class MemoryAccess {
437 friend class Scop;
438 friend class ScopStmt;
440 public:
441 /// The access type of a memory access
443 /// There are three kind of access types:
445 /// * A read access
447 /// A certain set of memory locations are read and may be used for internal
448 /// calculations.
450 /// * A must-write access
452 /// A certain set of memory locations is definitely written. The old value is
453 /// replaced by a newly calculated value. The old value is not read or used at
454 /// all.
456 /// * A may-write access
458 /// A certain set of memory locations may be written. The memory location may
459 /// contain a new value if there is actually a write or the old value may
460 /// remain, if no write happens.
461 enum AccessType {
462 READ = 0x1,
463 MUST_WRITE = 0x2,
464 MAY_WRITE = 0x3,
467 /// Reduction access type
469 /// Commutative and associative binary operations suitable for reductions
470 enum ReductionType {
471 RT_NONE, ///< Indicate no reduction at all
472 RT_ADD, ///< Addition
473 RT_MUL, ///< Multiplication
474 RT_BOR, ///< Bitwise Or
475 RT_BXOR, ///< Bitwise XOr
476 RT_BAND, ///< Bitwise And
479 private:
480 MemoryAccess(const MemoryAccess &) = delete;
481 const MemoryAccess &operator=(const MemoryAccess &) = delete;
483 /// A unique identifier for this memory access.
485 /// The identifier is unique between all memory accesses belonging to the same
486 /// scop statement.
487 isl_id *Id;
489 /// What is modeled by this MemoryAccess.
490 /// @see MemoryKind
491 MemoryKind Kind;
493 /// Whether it a reading or writing access, and if writing, whether it
494 /// is conditional (MAY_WRITE).
495 enum AccessType AccType;
497 /// Reduction type for reduction like accesses, RT_NONE otherwise
499 /// An access is reduction like if it is part of a load-store chain in which
500 /// both access the same memory location (use the same LLVM-IR value
501 /// as pointer reference). Furthermore, between the load and the store there
502 /// is exactly one binary operator which is known to be associative and
503 /// commutative.
505 /// TODO:
507 /// We can later lift the constraint that the same LLVM-IR value defines the
508 /// memory location to handle scops such as the following:
510 /// for i
511 /// for j
512 /// sum[i+j] = sum[i] + 3;
514 /// Here not all iterations access the same memory location, but iterations
515 /// for which j = 0 holds do. After lifting the equality check in ScopBuilder,
516 /// subsequent transformations do not only need check if a statement is
517 /// reduction like, but they also need to verify that that the reduction
518 /// property is only exploited for statement instances that load from and
519 /// store to the same data location. Doing so at dependence analysis time
520 /// could allow us to handle the above example.
521 ReductionType RedType = RT_NONE;
523 /// Parent ScopStmt of this access.
524 ScopStmt *Statement;
526 /// The domain under which this access is not modeled precisely.
528 /// The invalid domain for an access describes all parameter combinations
529 /// under which the statement looks to be executed but is in fact not because
530 /// some assumption/restriction makes the access invalid.
531 isl_set *InvalidDomain;
533 // Properties describing the accessed array.
534 // TODO: It might be possible to move them to ScopArrayInfo.
535 // @{
537 /// The base address (e.g., A for A[i+j]).
539 /// The #BaseAddr of a memory access of kind MemoryKind::Array is the base
540 /// pointer of the memory access.
541 /// The #BaseAddr of a memory access of kind MemoryKind::PHI or
542 /// MemoryKind::ExitPHI is the PHI node itself.
543 /// The #BaseAddr of a memory access of kind MemoryKind::Value is the
544 /// instruction defining the value.
545 AssertingVH<Value> BaseAddr;
547 /// Type a single array element wrt. this access.
548 Type *ElementType;
550 /// Size of each dimension of the accessed array.
551 SmallVector<const SCEV *, 4> Sizes;
552 // @}
554 // Properties describing the accessed element.
555 // @{
557 /// The access instruction of this memory access.
559 /// For memory accesses of kind MemoryKind::Array the access instruction is
560 /// the Load or Store instruction performing the access.
562 /// For memory accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI the
563 /// access instruction of a load access is the PHI instruction. The access
564 /// instruction of a PHI-store is the incoming's block's terminator
565 /// instruction.
567 /// For memory accesses of kind MemoryKind::Value the access instruction of a
568 /// load access is nullptr because generally there can be multiple
569 /// instructions in the statement using the same llvm::Value. The access
570 /// instruction of a write access is the instruction that defines the
571 /// llvm::Value.
572 Instruction *AccessInstruction;
574 /// Incoming block and value of a PHINode.
575 SmallVector<std::pair<BasicBlock *, Value *>, 4> Incoming;
577 /// The value associated with this memory access.
579 /// - For array memory accesses (MemoryKind::Array) it is the loaded result
580 /// or the stored value. If the access instruction is a memory intrinsic it
581 /// the access value is also the memory intrinsic.
582 /// - For accesses of kind MemoryKind::Value it is the access instruction
583 /// itself.
584 /// - For accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI it is the
585 /// PHI node itself (for both, READ and WRITE accesses).
587 AssertingVH<Value> AccessValue;
589 /// Are all the subscripts affine expression?
590 bool IsAffine;
592 /// Subscript expression for each dimension.
593 SmallVector<const SCEV *, 4> Subscripts;
595 /// Relation from statement instances to the accessed array elements.
597 /// In the common case this relation is a function that maps a set of loop
598 /// indices to the memory address from which a value is loaded/stored:
600 /// for i
601 /// for j
602 /// S: A[i + 3 j] = ...
604 /// => { S[i,j] -> A[i + 3j] }
606 /// In case the exact access function is not known, the access relation may
607 /// also be a one to all mapping { S[i,j] -> A[o] } describing that any
608 /// element accessible through A might be accessed.
610 /// In case of an access to a larger element belonging to an array that also
611 /// contains smaller elements, the access relation models the larger access
612 /// with multiple smaller accesses of the size of the minimal array element
613 /// type:
615 /// short *A;
617 /// for i
618 /// S: A[i] = *((double*)&A[4 * i]);
620 /// => { S[i] -> A[i]; S[i] -> A[o] : 4i <= o <= 4i + 3 }
621 isl_map *AccessRelation;
623 /// Updated access relation read from JSCOP file.
624 isl_map *NewAccessRelation;
626 /// Fortran arrays whose sizes are not statically known are stored in terms
627 /// of a descriptor struct. This maintains a raw pointer to the memory,
628 /// along with auxiliary fields with information such as dimensions.
629 /// We hold a reference to the descriptor corresponding to a MemoryAccess
630 /// into a Fortran array. FAD for "Fortran Array Descriptor"
631 AssertingVH<Value> FAD;
632 // @}
634 __isl_give isl_basic_map *createBasicAccessMap(ScopStmt *Statement);
636 void assumeNoOutOfBound();
638 /// Compute bounds on an over approximated access relation.
640 /// @param ElementSize The size of one element accessed.
641 void computeBoundsOnAccessRelation(unsigned ElementSize);
643 /// Get the original access function as read from IR.
644 __isl_give isl_map *getOriginalAccessRelation() const;
646 /// Return the space in which the access relation lives in.
647 __isl_give isl_space *getOriginalAccessRelationSpace() const;
649 /// Get the new access function imported or set by a pass
650 __isl_give isl_map *getNewAccessRelation() const;
652 /// Fold the memory access to consider parameteric offsets
654 /// To recover memory accesses with array size parameters in the subscript
655 /// expression we post-process the delinearization results.
657 /// We would normally recover from an access A[exp0(i) * N + exp1(i)] into an
658 /// array A[][N] the 2D access A[exp0(i)][exp1(i)]. However, another valid
659 /// delinearization is A[exp0(i) - 1][exp1(i) + N] which - depending on the
660 /// range of exp1(i) - may be preferrable. Specifically, for cases where we
661 /// know exp1(i) is negative, we want to choose the latter expression.
663 /// As we commonly do not have any information about the range of exp1(i),
664 /// we do not choose one of the two options, but instead create a piecewise
665 /// access function that adds the (-1, N) offsets as soon as exp1(i) becomes
666 /// negative. For a 2D array such an access function is created by applying
667 /// the piecewise map:
669 /// [i,j] -> [i, j] : j >= 0
670 /// [i,j] -> [i-1, j+N] : j < 0
672 /// We can generalize this mapping to arbitrary dimensions by applying this
673 /// piecewise mapping pairwise from the rightmost to the leftmost access
674 /// dimension. It would also be possible to cover a wider range by introducing
675 /// more cases and adding multiple of Ns to these cases. However, this has
676 /// not yet been necessary.
677 /// The introduction of different cases necessarily complicates the memory
678 /// access function, but cases that can be statically proven to not happen
679 /// will be eliminated later on.
680 void foldAccessRelation();
682 /// Create the access relation for the underlying memory intrinsic.
683 void buildMemIntrinsicAccessRelation();
685 /// Assemble the access relation from all available information.
687 /// In particular, used the information passes in the constructor and the
688 /// parent ScopStmt set by setStatment().
690 /// @param SAI Info object for the accessed array.
691 void buildAccessRelation(const ScopArrayInfo *SAI);
693 /// Carry index overflows of dimensions with constant size to the next higher
694 /// dimension.
696 /// For dimensions that have constant size, modulo the index by the size and
697 /// add up the carry (floored division) to the next higher dimension. This is
698 /// how overflow is defined in row-major order.
699 /// It happens e.g. when ScalarEvolution computes the offset to the base
700 /// pointer and would algebraically sum up all lower dimensions' indices of
701 /// constant size.
703 /// Example:
704 /// float (*A)[4];
705 /// A[1][6] -> A[2][2]
706 void wrapConstantDimensions();
708 public:
709 /// Create a new MemoryAccess.
711 /// @param Stmt The parent statement.
712 /// @param AccessInst The instruction doing the access.
713 /// @param BaseAddr The accessed array's address.
714 /// @param ElemType The type of the accessed array elements.
715 /// @param AccType Whether read or write access.
716 /// @param IsAffine Whether the subscripts are affine expressions.
717 /// @param Kind The kind of memory accessed.
718 /// @param Subscripts Subscipt expressions
719 /// @param Sizes Dimension lengths of the accessed array.
720 MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, AccessType AccType,
721 Value *BaseAddress, Type *ElemType, bool Affine,
722 ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
723 Value *AccessValue, MemoryKind Kind);
725 /// Create a new MemoryAccess that corresponds to @p AccRel.
727 /// Along with @p Stmt and @p AccType it uses information about dimension
728 /// lengths of the accessed array, the type of the accessed array elements,
729 /// the name of the accessed array that is derived from the object accessible
730 /// via @p AccRel.
732 /// @param Stmt The parent statement.
733 /// @param AccType Whether read or write access.
734 /// @param AccRel The access relation that describes the memory access.
735 MemoryAccess(ScopStmt *Stmt, AccessType AccType, __isl_take isl_map *AccRel);
737 ~MemoryAccess();
739 /// Add a new incoming block/value pairs for this PHI/ExitPHI access.
741 /// @param IncomingBlock The PHI's incoming block.
742 /// @param IncomingValue The value when reacing the PHI from the @p
743 /// IncomingBlock.
744 void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
745 assert(!isRead());
746 assert(isAnyPHIKind());
747 Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
750 /// Return the list of possible PHI/ExitPHI values.
752 /// After code generation moves some PHIs around during region simplification,
753 /// we cannot reliably locate the original PHI node and its incoming values
754 /// anymore. For this reason we remember these explicitly for all PHI-kind
755 /// accesses.
756 ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
757 assert(isAnyPHIKind());
758 return Incoming;
761 /// Get the type of a memory access.
762 enum AccessType getType() { return AccType; }
764 /// Is this a reduction like access?
765 bool isReductionLike() const { return RedType != RT_NONE; }
767 /// Is this a read memory access?
768 bool isRead() const { return AccType == MemoryAccess::READ; }
770 /// Is this a must-write memory access?
771 bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
773 /// Is this a may-write memory access?
774 bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
776 /// Is this a write memory access?
777 bool isWrite() const { return isMustWrite() || isMayWrite(); }
779 /// Is this a memory intrinsic access (memcpy, memset, memmove)?
780 bool isMemoryIntrinsic() const {
781 return isa<MemIntrinsic>(getAccessInstruction());
784 /// Check if a new access relation was imported or set by a pass.
785 bool hasNewAccessRelation() const { return NewAccessRelation; }
787 /// Return the newest access relation of this access.
789 /// There are two possibilities:
790 /// 1) The original access relation read from the LLVM-IR.
791 /// 2) A new access relation imported from a json file or set by another
792 /// pass (e.g., for privatization).
794 /// As 2) is by construction "newer" than 1) we return the new access
795 /// relation if present.
797 __isl_give isl_map *getLatestAccessRelation() const {
798 return hasNewAccessRelation() ? getNewAccessRelation()
799 : getOriginalAccessRelation();
802 /// Old name of getLatestAccessRelation().
803 __isl_give isl_map *getAccessRelation() const {
804 return getLatestAccessRelation();
807 /// Get an isl map describing the memory address accessed.
809 /// In most cases the memory address accessed is well described by the access
810 /// relation obtained with getAccessRelation. However, in case of arrays
811 /// accessed with types of different size the access relation maps one access
812 /// to multiple smaller address locations. This method returns an isl map that
813 /// relates each dynamic statement instance to the unique memory location
814 /// that is loaded from / stored to.
816 /// For an access relation { S[i] -> A[o] : 4i <= o <= 4i + 3 } this method
817 /// will return the address function { S[i] -> A[4i] }.
819 /// @returns The address function for this memory access.
820 __isl_give isl_map *getAddressFunction() const;
822 /// Return the access relation after the schedule was applied.
823 __isl_give isl_pw_multi_aff *
824 applyScheduleToAccessRelation(__isl_take isl_union_map *Schedule) const;
826 /// Get an isl string representing the access function read from IR.
827 std::string getOriginalAccessRelationStr() const;
829 /// Get an isl string representing a new access function, if available.
830 std::string getNewAccessRelationStr() const;
832 /// Get the original base address of this access (e.g. A for A[i+j]) when
833 /// detected.
835 /// This adress may differ from the base address referenced by the Original
836 /// ScopArrayInfo to which this array belongs, as this memory access may
837 /// have been unified to a ScopArray which has a different but identically
838 /// valued base pointer in case invariant load hoisting is enabled.
839 Value *getOriginalBaseAddr() const { return BaseAddr; }
841 /// Get the detection-time base array isl_id for this access.
842 __isl_give isl_id *getOriginalArrayId() const;
844 /// Get the base array isl_id for this access, modifiable through
845 /// setNewAccessRelation().
846 __isl_give isl_id *getLatestArrayId() const;
848 /// Old name of getOriginalArrayId().
849 __isl_give isl_id *getArrayId() const { return getOriginalArrayId(); }
851 /// Get the detection-time ScopArrayInfo object for the base address.
852 const ScopArrayInfo *getOriginalScopArrayInfo() const;
854 /// Get the ScopArrayInfo object for the base address, or the one set
855 /// by setNewAccessRelation().
856 const ScopArrayInfo *getLatestScopArrayInfo() const;
858 /// Legacy name of getOriginalScopArrayInfo().
859 const ScopArrayInfo *getScopArrayInfo() const {
860 return getOriginalScopArrayInfo();
863 /// Return a string representation of the access's reduction type.
864 const std::string getReductionOperatorStr() const;
866 /// Return a string representation of the reduction type @p RT.
867 static const std::string getReductionOperatorStr(ReductionType RT);
869 /// Return the element type of the accessed array wrt. this access.
870 Type *getElementType() const { return ElementType; }
872 /// Return the access value of this memory access.
873 Value *getAccessValue() const { return AccessValue; }
875 /// Return the access instruction of this memory access.
876 Instruction *getAccessInstruction() const { return AccessInstruction; }
878 /// Return the number of access function subscript.
879 unsigned getNumSubscripts() const { return Subscripts.size(); }
881 /// Return the access function subscript in the dimension @p Dim.
882 const SCEV *getSubscript(unsigned Dim) const { return Subscripts[Dim]; }
884 /// Compute the isl representation for the SCEV @p E wrt. this access.
886 /// Note that this function will also adjust the invalid context accordingly.
887 __isl_give isl_pw_aff *getPwAff(const SCEV *E);
889 /// Get the invalid domain for this access.
890 __isl_give isl_set *getInvalidDomain() const {
891 return isl_set_copy(InvalidDomain);
894 /// Get the invalid context for this access.
895 __isl_give isl_set *getInvalidContext() const {
896 return isl_set_params(getInvalidDomain());
899 /// Get the stride of this memory access in the specified Schedule. Schedule
900 /// is a map from the statement to a schedule where the innermost dimension is
901 /// the dimension of the innermost loop containing the statement.
902 __isl_give isl_set *getStride(__isl_take const isl_map *Schedule) const;
904 /// Get the FortranArrayDescriptor corresponding to this memory access if
905 /// it exists, and nullptr otherwise.
906 Value *getFortranArrayDescriptor() const { return this->FAD; };
908 /// Is the stride of the access equal to a certain width? Schedule is a map
909 /// from the statement to a schedule where the innermost dimension is the
910 /// dimension of the innermost loop containing the statement.
911 bool isStrideX(__isl_take const isl_map *Schedule, int StrideWidth) const;
913 /// Is consecutive memory accessed for a given statement instance set?
914 /// Schedule is a map from the statement to a schedule where the innermost
915 /// dimension is the dimension of the innermost loop containing the
916 /// statement.
917 bool isStrideOne(__isl_take const isl_map *Schedule) const;
919 /// Is always the same memory accessed for a given statement instance set?
920 /// Schedule is a map from the statement to a schedule where the innermost
921 /// dimension is the dimension of the innermost loop containing the
922 /// statement.
923 bool isStrideZero(__isl_take const isl_map *Schedule) const;
925 /// Return the kind when this access was first detected.
926 MemoryKind getOriginalKind() const {
927 assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
928 getOriginalScopArrayInfo()->getKind() == Kind);
929 return Kind;
932 /// Return the kind considering a potential setNewAccessRelation.
933 MemoryKind getLatestKind() const {
934 return getLatestScopArrayInfo()->getKind();
937 /// Whether this is an access of an explicit load or store in the IR.
938 bool isOriginalArrayKind() const {
939 return getOriginalKind() == MemoryKind::Array;
942 /// Whether storage memory is either an custom .s2a/.phiops alloca
943 /// (false) or an existing pointer into an array (true).
944 bool isLatestArrayKind() const {
945 return getLatestKind() == MemoryKind::Array;
948 /// Old name of isOriginalArrayKind.
949 bool isArrayKind() const { return isOriginalArrayKind(); }
951 /// Whether this access is an array to a scalar memory object, without
952 /// considering changes by setNewAccessRelation.
954 /// Scalar accesses are accesses to MemoryKind::Value, MemoryKind::PHI or
955 /// MemoryKind::ExitPHI.
956 bool isOriginalScalarKind() const {
957 return getOriginalKind() != MemoryKind::Array;
960 /// Whether this access is an array to a scalar memory object, also
961 /// considering changes by setNewAccessRelation.
962 bool isLatestScalarKind() const {
963 return getLatestKind() != MemoryKind::Array;
966 /// Old name of isOriginalScalarKind.
967 bool isScalarKind() const { return isOriginalScalarKind(); }
969 /// Was this MemoryAccess detected as a scalar dependences?
970 bool isOriginalValueKind() const {
971 return getOriginalKind() == MemoryKind::Value;
974 /// Is this MemoryAccess currently modeling scalar dependences?
975 bool isLatestValueKind() const {
976 return getLatestKind() == MemoryKind::Value;
979 /// Old name of isOriginalValueKind().
980 bool isValueKind() const { return isOriginalValueKind(); }
982 /// Was this MemoryAccess detected as a special PHI node access?
983 bool isOriginalPHIKind() const {
984 return getOriginalKind() == MemoryKind::PHI;
987 /// Is this MemoryAccess modeling special PHI node accesses, also
988 /// considering a potential change by setNewAccessRelation?
989 bool isLatestPHIKind() const { return getLatestKind() == MemoryKind::PHI; }
991 /// Old name of isOriginalPHIKind.
992 bool isPHIKind() const { return isOriginalPHIKind(); }
994 /// Was this MemoryAccess detected as the accesses of a PHI node in the
995 /// SCoP's exit block?
996 bool isOriginalExitPHIKind() const {
997 return getOriginalKind() == MemoryKind::ExitPHI;
1000 /// Is this MemoryAccess modeling the accesses of a PHI node in the
1001 /// SCoP's exit block? Can be changed to an array access using
1002 /// setNewAccessRelation().
1003 bool isLatestExitPHIKind() const {
1004 return getLatestKind() == MemoryKind::ExitPHI;
1007 /// Old name of isOriginalExitPHIKind().
1008 bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
1010 /// Was this access detected as one of the two PHI types?
1011 bool isOriginalAnyPHIKind() const {
1012 return isOriginalPHIKind() || isOriginalExitPHIKind();
1015 /// Does this access orginate from one of the two PHI types? Can be
1016 /// changed to an array access using setNewAccessRelation().
1017 bool isLatestAnyPHIKind() const {
1018 return isLatestPHIKind() || isLatestExitPHIKind();
1021 /// Old name of isOriginalAnyPHIKind().
1022 bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
1024 /// Get the statement that contains this memory access.
1025 ScopStmt *getStatement() const { return Statement; }
1027 /// Get the reduction type of this access
1028 ReductionType getReductionType() const { return RedType; }
1030 /// Set the array descriptor corresponding to the Array on which the
1031 /// memory access is performed.
1032 void setFortranArrayDescriptor(Value *FAD);
1034 /// Update the original access relation.
1036 /// We need to update the original access relation during scop construction,
1037 /// when unifying the memory accesses that access the same scop array info
1038 /// object. After the scop has been constructed, the original access relation
1039 /// should not be changed any more. Instead setNewAccessRelation should
1040 /// be called.
1041 void setAccessRelation(__isl_take isl_map *AccessRelation);
1043 /// Set the updated access relation read from JSCOP file.
1044 void setNewAccessRelation(__isl_take isl_map *NewAccessRelation);
1046 /// Return whether the MemoryyAccess is a partial access. That is, the access
1047 /// is not executed in some instances of the parent statement's domain.
1048 bool isLatestPartialAccess() const;
1050 /// Mark this a reduction like access
1051 void markAsReductionLike(ReductionType RT) { RedType = RT; }
1053 /// Align the parameters in the access relation to the scop context
1054 void realignParams();
1056 /// Update the dimensionality of the memory access.
1058 /// During scop construction some memory accesses may not be constructed with
1059 /// their full dimensionality, but outer dimensions may have been omitted if
1060 /// they took the value 'zero'. By updating the dimensionality of the
1061 /// statement we add additional zero-valued dimensions to match the
1062 /// dimensionality of the ScopArrayInfo object that belongs to this memory
1063 /// access.
1064 void updateDimensionality();
1066 /// Get identifier for the memory access.
1068 /// This identifier is unique for all accesses that belong to the same scop
1069 /// statement.
1070 __isl_give isl_id *getId() const;
1072 /// Print the MemoryAccess.
1074 /// @param OS The output stream the MemoryAccess is printed to.
1075 void print(raw_ostream &OS) const;
1077 /// Print the MemoryAccess to stderr.
1078 void dump() const;
1080 /// Is the memory access affine?
1081 bool isAffine() const { return IsAffine; }
1084 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1085 MemoryAccess::ReductionType RT);
1087 /// Ordered list type to hold accesses.
1088 using MemoryAccessList = std::forward_list<MemoryAccess *>;
1090 /// Helper structure for invariant memory accesses.
1091 struct InvariantAccess {
1092 /// The memory access that is (partially) invariant.
1093 MemoryAccess *MA;
1095 /// The context under which the access is not invariant.
1096 isl_set *NonHoistableCtx;
1099 /// Ordered container type to hold invariant accesses.
1100 using InvariantAccessesTy = SmallVector<InvariantAccess, 8>;
1102 /// Type for equivalent invariant accesses and their domain context.
1103 struct InvariantEquivClassTy {
1105 /// The pointer that identifies this equivalence class
1106 const SCEV *IdentifyingPointer;
1108 /// Memory accesses now treated invariant
1110 /// These memory accesses access the pointer location that identifies
1111 /// this equivalence class. They are treated as invariant and hoisted during
1112 /// code generation.
1113 MemoryAccessList InvariantAccesses;
1115 /// The execution context under which the memory location is accessed
1117 /// It is the union of the execution domains of the memory accesses in the
1118 /// InvariantAccesses list.
1119 isl_set *ExecutionContext;
1121 /// The type of the invariant access
1123 /// It is used to differentiate between differently typed invariant loads from
1124 /// the same location.
1125 Type *AccessType;
1128 /// Type for invariant accesses equivalence classes.
1129 using InvariantEquivClassesTy = SmallVector<InvariantEquivClassTy, 8>;
1131 /// Statement of the Scop
1133 /// A Scop statement represents an instruction in the Scop.
1135 /// It is further described by its iteration domain, its schedule and its data
1136 /// accesses.
1137 /// At the moment every statement represents a single basic block of LLVM-IR.
1138 class ScopStmt {
1139 public:
1140 ScopStmt(const ScopStmt &) = delete;
1141 const ScopStmt &operator=(const ScopStmt &) = delete;
1143 /// Create the ScopStmt from a BasicBlock.
1144 ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop);
1146 /// Create an overapproximating ScopStmt for the region @p R.
1147 ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop);
1149 /// Create a copy statement.
1151 /// @param Stmt The parent statement.
1152 /// @param SourceRel The source location.
1153 /// @param TargetRel The target location.
1154 /// @param Domain The original domain under which copy statement whould
1155 /// be executed.
1156 ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1157 __isl_take isl_map *TargetRel, __isl_take isl_set *Domain);
1159 /// Initialize members after all MemoryAccesses have been added.
1160 void init(LoopInfo &LI);
1162 private:
1163 /// Polyhedral description
1164 //@{
1166 /// The Scop containing this ScopStmt
1167 Scop &Parent;
1169 /// The domain under which this statement is not modeled precisely.
1171 /// The invalid domain for a statement describes all parameter combinations
1172 /// under which the statement looks to be executed but is in fact not because
1173 /// some assumption/restriction makes the statement/scop invalid.
1174 isl_set *InvalidDomain;
1176 /// The iteration domain describes the set of iterations for which this
1177 /// statement is executed.
1179 /// Example:
1180 /// for (i = 0; i < 100 + b; ++i)
1181 /// for (j = 0; j < i; ++j)
1182 /// S(i,j);
1184 /// 'S' is executed for different values of i and j. A vector of all
1185 /// induction variables around S (i, j) is called iteration vector.
1186 /// The domain describes the set of possible iteration vectors.
1188 /// In this case it is:
1190 /// Domain: 0 <= i <= 100 + b
1191 /// 0 <= j <= i
1193 /// A pair of statement and iteration vector (S, (5,3)) is called statement
1194 /// instance.
1195 isl_set *Domain;
1197 /// The memory accesses of this statement.
1199 /// The only side effects of a statement are its memory accesses.
1200 typedef SmallVector<MemoryAccess *, 8> MemoryAccessVec;
1201 MemoryAccessVec MemAccs;
1203 /// Mapping from instructions to (scalar) memory accesses.
1204 DenseMap<const Instruction *, MemoryAccessList> InstructionToAccess;
1206 /// The set of values defined elsewhere required in this ScopStmt and
1207 /// their MemoryKind::Value READ MemoryAccesses.
1208 DenseMap<Value *, MemoryAccess *> ValueReads;
1210 /// The set of values defined in this ScopStmt that are required
1211 /// elsewhere, mapped to their MemoryKind::Value WRITE MemoryAccesses.
1212 DenseMap<Instruction *, MemoryAccess *> ValueWrites;
1214 /// Map from PHI nodes to its incoming value when coming from this
1215 /// statement.
1217 /// Non-affine subregions can have multiple exiting blocks that are incoming
1218 /// blocks of the PHI nodes. This map ensures that there is only one write
1219 /// operation for the complete subregion. A PHI selecting the relevant value
1220 /// will be inserted.
1221 DenseMap<PHINode *, MemoryAccess *> PHIWrites;
1223 //@}
1225 /// A SCoP statement represents either a basic block (affine/precise case) or
1226 /// a whole region (non-affine case).
1228 /// Only one of the following two members will therefore be set and indicate
1229 /// which kind of statement this is.
1231 ///{
1233 /// The BasicBlock represented by this statement (in the affine case).
1234 BasicBlock *BB;
1236 /// The region represented by this statement (in the non-affine case).
1237 Region *R;
1239 ///}
1241 /// The isl AST build for the new generated AST.
1242 isl_ast_build *Build;
1244 SmallVector<Loop *, 4> NestLoops;
1246 std::string BaseName;
1248 /// The closest loop that contains this statement.
1249 Loop *SurroundingLoop;
1251 /// Build the statement.
1252 //@{
1253 void buildDomain();
1255 /// Fill NestLoops with loops surrounding this statement.
1256 void collectSurroundingLoops();
1258 /// Build the access relation of all memory accesses.
1259 void buildAccessRelations();
1261 /// Detect and mark reductions in the ScopStmt
1262 void checkForReductions();
1264 /// Collect loads which might form a reduction chain with @p StoreMA
1265 void
1266 collectCandiateReductionLoads(MemoryAccess *StoreMA,
1267 llvm::SmallVectorImpl<MemoryAccess *> &Loads);
1268 //@}
1270 /// Remove @p MA from dictionaries pointing to them.
1271 void removeAccessData(MemoryAccess *MA);
1273 public:
1274 ~ScopStmt();
1276 /// Get an isl_ctx pointer.
1277 isl_ctx *getIslCtx() const;
1279 /// Get the iteration domain of this ScopStmt.
1281 /// @return The iteration domain of this ScopStmt.
1282 __isl_give isl_set *getDomain() const;
1284 /// Get the space of the iteration domain
1286 /// @return The space of the iteration domain
1287 __isl_give isl_space *getDomainSpace() const;
1289 /// Get the id of the iteration domain space
1291 /// @return The id of the iteration domain space
1292 __isl_give isl_id *getDomainId() const;
1294 /// Get an isl string representing this domain.
1295 std::string getDomainStr() const;
1297 /// Get the schedule function of this ScopStmt.
1299 /// @return The schedule function of this ScopStmt, if it does not contain
1300 /// extension nodes, and nullptr, otherwise.
1301 __isl_give isl_map *getSchedule() const;
1303 /// Get an isl string representing this schedule.
1305 /// @return An isl string representing this schedule, if it does not contain
1306 /// extension nodes, and an empty string, otherwise.
1307 std::string getScheduleStr() const;
1309 /// Get the invalid domain for this statement.
1310 __isl_give isl_set *getInvalidDomain() const {
1311 return isl_set_copy(InvalidDomain);
1314 /// Get the invalid context for this statement.
1315 __isl_give isl_set *getInvalidContext() const {
1316 return isl_set_params(getInvalidDomain());
1319 /// Set the invalid context for this statement to @p ID.
1320 void setInvalidDomain(__isl_take isl_set *ID);
1322 /// Get the BasicBlock represented by this ScopStmt (if any).
1324 /// @return The BasicBlock represented by this ScopStmt, or null if the
1325 /// statement represents a region.
1326 BasicBlock *getBasicBlock() const { return BB; }
1328 /// Return true if this statement represents a single basic block.
1329 bool isBlockStmt() const { return BB != nullptr; }
1331 /// Return true if this is a copy statement.
1332 bool isCopyStmt() const { return BB == nullptr && R == nullptr; }
1334 /// Get the region represented by this ScopStmt (if any).
1336 /// @return The region represented by this ScopStmt, or null if the statement
1337 /// represents a basic block.
1338 Region *getRegion() const { return R; }
1340 /// Return true if this statement represents a whole region.
1341 bool isRegionStmt() const { return R != nullptr; }
1343 /// Return a BasicBlock from this statement.
1345 /// For block statements, it returns the BasicBlock itself. For subregion
1346 /// statements, return its entry block.
1347 BasicBlock *getEntryBlock() const;
1349 /// Return whether @p L is boxed within this statement.
1350 bool contains(const Loop *L) const {
1351 // Block statements never contain loops.
1352 if (isBlockStmt())
1353 return false;
1355 return getRegion()->contains(L);
1358 /// Return whether this statement contains @p BB.
1359 bool contains(BasicBlock *BB) const {
1360 if (isCopyStmt())
1361 return false;
1362 if (isBlockStmt())
1363 return BB == getBasicBlock();
1364 return getRegion()->contains(BB);
1367 /// Return the closest innermost loop that contains this statement, but is not
1368 /// contained in it.
1370 /// For block statement, this is just the loop that contains the block. Region
1371 /// statements can contain boxed loops, so getting the loop of one of the
1372 /// region's BBs might return such an inner loop. For instance, the region's
1373 /// entry could be a header of a loop, but the region might extend to BBs
1374 /// after the loop exit. Similarly, the region might only contain parts of the
1375 /// loop body and still include the loop header.
1377 /// Most of the time the surrounding loop is the top element of #NestLoops,
1378 /// except when it is empty. In that case it return the loop that the whole
1379 /// SCoP is contained in. That can be nullptr if there is no such loop.
1380 Loop *getSurroundingLoop() const {
1381 assert(!isCopyStmt() &&
1382 "No surrounding loop for artificially created statements");
1383 return SurroundingLoop;
1386 /// Return true if this statement does not contain any accesses.
1387 bool isEmpty() const { return MemAccs.empty(); }
1389 /// Return the only array access for @p Inst, if existing.
1391 /// @param Inst The instruction for which to look up the access.
1392 /// @returns The unique array memory access related to Inst or nullptr if
1393 /// no array access exists
1394 MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
1395 auto It = InstructionToAccess.find(Inst);
1396 if (It == InstructionToAccess.end())
1397 return nullptr;
1399 MemoryAccess *ArrayAccess = nullptr;
1401 for (auto Access : It->getSecond()) {
1402 if (!Access->isArrayKind())
1403 continue;
1405 assert(!ArrayAccess && "More then one array access for instruction");
1407 ArrayAccess = Access;
1410 return ArrayAccess;
1413 /// Return the only array access for @p Inst.
1415 /// @param Inst The instruction for which to look up the access.
1416 /// @returns The unique array memory access related to Inst.
1417 MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
1418 MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
1420 assert(ArrayAccess && "No array access found for instruction!");
1421 return *ArrayAccess;
1424 /// Return the MemoryAccess that writes the value of an instruction
1425 /// defined in this statement, or nullptr if not existing, respectively
1426 /// not yet added.
1427 MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
1428 assert((isRegionStmt() && R->contains(Inst)) ||
1429 (!isRegionStmt() && Inst->getParent() == BB));
1430 return ValueWrites.lookup(Inst);
1433 /// Return the MemoryAccess that reloads a value, or nullptr if not
1434 /// existing, respectively not yet added.
1435 MemoryAccess *lookupValueReadOf(Value *Inst) const {
1436 return ValueReads.lookup(Inst);
1439 /// Return the MemoryAccess that loads a PHINode value, or nullptr if not
1440 /// existing, respectively not yet added.
1441 MemoryAccess *lookupPHIReadOf(PHINode *PHI) const;
1443 /// Return the PHI write MemoryAccess for the incoming values from any
1444 /// basic block in this ScopStmt, or nullptr if not existing,
1445 /// respectively not yet added.
1446 MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
1447 assert(isBlockStmt() || R->getExit() == PHI->getParent());
1448 return PHIWrites.lookup(PHI);
1451 /// Return the input access of the value, or null if no such MemoryAccess
1452 /// exists.
1454 /// The input access is the MemoryAccess that makes an inter-statement value
1455 /// available in this statement by reading it at the start of this statement.
1456 /// This can be a MemoryKind::Value if defined in another statement or a
1457 /// MemoryKind::PHI if the value is a PHINode in this statement.
1458 MemoryAccess *lookupInputAccessOf(Value *Val) const {
1459 if (isa<PHINode>(Val))
1460 if (auto InputMA = lookupPHIReadOf(cast<PHINode>(Val))) {
1461 assert(!lookupValueReadOf(Val) && "input accesses must be unique; a "
1462 "statement cannot read a .s2a and "
1463 ".phiops simultaneously");
1464 return InputMA;
1467 if (auto *InputMA = lookupValueReadOf(Val))
1468 return InputMA;
1470 return nullptr;
1473 /// Add @p Access to this statement's list of accesses.
1474 void addAccess(MemoryAccess *Access);
1476 /// Remove a MemoryAccess from this statement.
1478 /// Note that scalar accesses that are caused by MA will
1479 /// be eliminated too.
1480 void removeMemoryAccess(MemoryAccess *MA);
1482 /// Remove @p MA from this statement.
1484 /// In contrast to removeMemoryAccess(), no other access will be eliminated.
1485 void removeSingleMemoryAccess(MemoryAccess *MA);
1487 typedef MemoryAccessVec::iterator iterator;
1488 typedef MemoryAccessVec::const_iterator const_iterator;
1490 iterator begin() { return MemAccs.begin(); }
1491 iterator end() { return MemAccs.end(); }
1492 const_iterator begin() const { return MemAccs.begin(); }
1493 const_iterator end() const { return MemAccs.end(); }
1494 size_t size() const { return MemAccs.size(); }
1496 unsigned getNumIterators() const;
1498 Scop *getParent() { return &Parent; }
1499 const Scop *getParent() const { return &Parent; }
1501 const char *getBaseName() const;
1503 /// Set the isl AST build.
1504 void setAstBuild(__isl_keep isl_ast_build *B) { Build = B; }
1506 /// Get the isl AST build.
1507 __isl_keep isl_ast_build *getAstBuild() const { return Build; }
1509 /// Restrict the domain of the statement.
1511 /// @param NewDomain The new statement domain.
1512 void restrictDomain(__isl_take isl_set *NewDomain);
1514 /// Compute the isl representation for the SCEV @p E in this stmt.
1516 /// @param E The SCEV that should be translated.
1517 /// @param NonNegative Flag to indicate the @p E has to be non-negative.
1519 /// Note that this function will also adjust the invalid context accordingly.
1520 __isl_give isl_pw_aff *getPwAff(const SCEV *E, bool NonNegative = false);
1522 /// Get the loop for a dimension.
1524 /// @param Dimension The dimension of the induction variable
1525 /// @return The loop at a certain dimension.
1526 Loop *getLoopForDimension(unsigned Dimension) const;
1528 /// Align the parameters in the statement to the scop context
1529 void realignParams();
1531 /// Print the ScopStmt.
1533 /// @param OS The output stream the ScopStmt is printed to.
1534 void print(raw_ostream &OS) const;
1536 /// Print the ScopStmt to stderr.
1537 void dump() const;
1540 /// Print ScopStmt S to raw_ostream O.
1541 static inline raw_ostream &operator<<(raw_ostream &O, const ScopStmt &S) {
1542 S.print(O);
1543 return O;
1546 /// Static Control Part
1548 /// A Scop is the polyhedral representation of a control flow region detected
1549 /// by the Scop detection. It is generated by translating the LLVM-IR and
1550 /// abstracting its effects.
1552 /// A Scop consists of a set of:
1554 /// * A set of statements executed in the Scop.
1556 /// * A set of global parameters
1557 /// Those parameters are scalar integer values, which are constant during
1558 /// execution.
1560 /// * A context
1561 /// This context contains information about the values the parameters
1562 /// can take and relations between different parameters.
1563 class Scop {
1564 public:
1565 /// Type to represent a pair of minimal/maximal access to an array.
1566 using MinMaxAccessTy = std::pair<isl_pw_multi_aff *, isl_pw_multi_aff *>;
1568 /// Vector of minimal/maximal accesses to different arrays.
1569 using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
1571 /// Pair of minimal/maximal access vectors representing
1572 /// read write and read only accesses
1573 using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
1575 /// Vector of pair of minimal/maximal access vectors representing
1576 /// non read only and read only accesses for each alias group.
1577 using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
1579 private:
1580 Scop(const Scop &) = delete;
1581 const Scop &operator=(const Scop &) = delete;
1583 ScalarEvolution *SE;
1585 /// The underlying Region.
1586 Region &R;
1588 /// The name of the SCoP (identical to the regions name)
1589 std::string name;
1591 // Access functions of the SCoP.
1593 // This owns all the MemoryAccess objects of the Scop created in this pass.
1594 AccFuncVector AccessFunctions;
1596 /// Flag to indicate that the scheduler actually optimized the SCoP.
1597 bool IsOptimized;
1599 /// True if the underlying region has a single exiting block.
1600 bool HasSingleExitEdge;
1602 /// Flag to remember if the SCoP contained an error block or not.
1603 bool HasErrorBlock;
1605 /// Max loop depth.
1606 unsigned MaxLoopDepth;
1608 /// Number of copy statements.
1609 unsigned CopyStmtsNum;
1611 typedef std::list<ScopStmt> StmtSet;
1612 /// The statements in this Scop.
1613 StmtSet Stmts;
1615 /// Parameters of this Scop
1616 ParameterSetTy Parameters;
1618 /// Mapping from parameters to their ids.
1619 DenseMap<const SCEV *, isl_id *> ParameterIds;
1621 /// The context of the SCoP created during SCoP detection.
1622 ScopDetection::DetectionContext &DC;
1624 /// Isl context.
1626 /// We need a shared_ptr with reference counter to delete the context when all
1627 /// isl objects are deleted. We will distribute the shared_ptr to all objects
1628 /// that use the context to create isl objects, and increase the reference
1629 /// counter. By doing this, we guarantee that the context is deleted when we
1630 /// delete the last object that creates isl objects with the context.
1631 std::shared_ptr<isl_ctx> IslCtx;
1633 /// A map from basic blocks to SCoP statements.
1634 DenseMap<BasicBlock *, ScopStmt *> StmtMap;
1636 /// A map from basic blocks to their domains.
1637 DenseMap<BasicBlock *, isl_set *> DomainMap;
1639 /// Constraints on parameters.
1640 isl_set *Context;
1642 /// The affinator used to translate SCEVs to isl expressions.
1643 SCEVAffinator Affinator;
1645 typedef std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
1646 std::unique_ptr<ScopArrayInfo>>
1647 ArrayInfoMapTy;
1649 typedef StringMap<std::unique_ptr<ScopArrayInfo>> ArrayNameMapTy;
1651 typedef SetVector<ScopArrayInfo *> ArrayInfoSetTy;
1653 /// A map to remember ScopArrayInfo objects for all base pointers.
1655 /// As PHI nodes may have two array info objects associated, we add a flag
1656 /// that distinguishes between the PHI node specific ArrayInfo object
1657 /// and the normal one.
1658 ArrayInfoMapTy ScopArrayInfoMap;
1660 /// A map to remember ScopArrayInfo objects for all names of memory
1661 /// references.
1662 ArrayNameMapTy ScopArrayNameMap;
1664 /// A set to remember ScopArrayInfo objects.
1665 /// @see Scop::ScopArrayInfoMap
1666 ArrayInfoSetTy ScopArrayInfoSet;
1668 /// The assumptions under which this scop was built.
1670 /// When constructing a scop sometimes the exact representation of a statement
1671 /// or condition would be very complex, but there is a common case which is a
1672 /// lot simpler, but which is only valid under certain assumptions. The
1673 /// assumed context records the assumptions taken during the construction of
1674 /// this scop and that need to be code generated as a run-time test.
1675 isl_set *AssumedContext;
1677 /// The restrictions under which this SCoP was built.
1679 /// The invalid context is similar to the assumed context as it contains
1680 /// constraints over the parameters. However, while we need the constraints
1681 /// in the assumed context to be "true" the constraints in the invalid context
1682 /// need to be "false". Otherwise they behave the same.
1683 isl_set *InvalidContext;
1685 /// Helper struct to remember assumptions.
1686 struct Assumption {
1688 /// The kind of the assumption (e.g., WRAPPING).
1689 AssumptionKind Kind;
1691 /// Flag to distinguish assumptions and restrictions.
1692 AssumptionSign Sign;
1694 /// The valid/invalid context if this is an assumption/restriction.
1695 isl_set *Set;
1697 /// The location that caused this assumption.
1698 DebugLoc Loc;
1700 /// An optional block whose domain can simplify the assumption.
1701 BasicBlock *BB;
1704 /// Collection to hold taken assumptions.
1706 /// There are two reasons why we want to record assumptions first before we
1707 /// add them to the assumed/invalid context:
1708 /// 1) If the SCoP is not profitable or otherwise invalid without the
1709 /// assumed/invalid context we do not have to compute it.
1710 /// 2) Information about the context are gathered rather late in the SCoP
1711 /// construction (basically after we know all parameters), thus the user
1712 /// might see overly complicated assumptions to be taken while they will
1713 /// only be simplified later on.
1714 SmallVector<Assumption, 8> RecordedAssumptions;
1716 /// The schedule of the SCoP
1718 /// The schedule of the SCoP describes the execution order of the statements
1719 /// in the scop by assigning each statement instance a possibly
1720 /// multi-dimensional execution time. The schedule is stored as a tree of
1721 /// schedule nodes.
1723 /// The most common nodes in a schedule tree are so-called band nodes. Band
1724 /// nodes map statement instances into a multi dimensional schedule space.
1725 /// This space can be seen as a multi-dimensional clock.
1727 /// Example:
1729 /// <S,(5,4)> may be mapped to (5,4) by this schedule:
1731 /// s0 = i (Year of execution)
1732 /// s1 = j (Day of execution)
1734 /// or to (9, 20) by this schedule:
1736 /// s0 = i + j (Year of execution)
1737 /// s1 = 20 (Day of execution)
1739 /// The order statement instances are executed is defined by the
1740 /// schedule vectors they are mapped to. A statement instance
1741 /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
1742 /// the schedule vector of A is lexicographic smaller than the schedule
1743 /// vector of B.
1745 /// Besides band nodes, schedule trees contain additional nodes that specify
1746 /// a textual ordering between two subtrees or filter nodes that filter the
1747 /// set of statement instances that will be scheduled in a subtree. There
1748 /// are also several other nodes. A full description of the different nodes
1749 /// in a schedule tree is given in the isl manual.
1750 isl_schedule *Schedule;
1752 /// The set of minimal/maximal accesses for each alias group.
1754 /// When building runtime alias checks we look at all memory instructions and
1755 /// build so called alias groups. Each group contains a set of accesses to
1756 /// different base arrays which might alias with each other. However, between
1757 /// alias groups there is no aliasing possible.
1759 /// In a program with int and float pointers annotated with tbaa information
1760 /// we would probably generate two alias groups, one for the int pointers and
1761 /// one for the float pointers.
1763 /// During code generation we will create a runtime alias check for each alias
1764 /// group to ensure the SCoP is executed in an alias free environment.
1765 MinMaxVectorPairVectorTy MinMaxAliasGroups;
1767 /// Mapping from invariant loads to the representing invariant load of
1768 /// their equivalence class.
1769 ValueToValueMap InvEquivClassVMap;
1771 /// List of invariant accesses.
1772 InvariantEquivClassesTy InvariantEquivClasses;
1774 /// The smallest array index not yet assigned.
1775 long ArrayIdx = 0;
1777 /// The smallest statement index not yet assigned.
1778 long StmtIdx = 0;
1780 /// Scop constructor; invoked from ScopBuilder::buildScop.
1781 Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI,
1782 ScopDetection::DetectionContext &DC);
1784 //@}
1786 /// Initialize this ScopBuilder.
1787 void init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
1788 LoopInfo &LI);
1790 /// Propagate domains that are known due to graph properties.
1792 /// As a CFG is mostly structured we use the graph properties to propagate
1793 /// domains without the need to compute all path conditions. In particular, if
1794 /// a block A dominates a block B and B post-dominates A we know that the
1795 /// domain of B is a superset of the domain of A. As we do not have
1796 /// post-dominator information available here we use the less precise region
1797 /// information. Given a region R, we know that the exit is always executed if
1798 /// the entry was executed, thus the domain of the exit is a superset of the
1799 /// domain of the entry. In case the exit can only be reached from within the
1800 /// region the domains are in fact equal. This function will use this property
1801 /// to avoid the generation of condition constraints that determine when a
1802 /// branch is taken. If @p BB is a region entry block we will propagate its
1803 /// domain to the region exit block. Additionally, we put the region exit
1804 /// block in the @p FinishedExitBlocks set so we can later skip edges from
1805 /// within the region to that block.
1807 /// @param BB The block for which the domain is currently propagated.
1808 /// @param BBLoop The innermost affine loop surrounding @p BB.
1809 /// @param FinishedExitBlocks Set of region exits the domain was set for.
1810 /// @param LI The LoopInfo for the current function.
1812 void propagateDomainConstraintsToRegionExit(
1813 BasicBlock *BB, Loop *BBLoop,
1814 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI);
1816 /// Compute the union of predecessor domains for @p BB.
1818 /// To compute the union of all domains of predecessors of @p BB this
1819 /// function applies similar reasoning on the CFG structure as described for
1820 /// @see propagateDomainConstraintsToRegionExit
1822 /// @param BB The block for which the predecessor domains are collected.
1823 /// @param Domain The domain under which BB is executed.
1824 /// @param DT The DominatorTree for the current function.
1825 /// @param LI The LoopInfo for the current function.
1827 /// @returns The domain under which @p BB is executed.
1828 __isl_give isl_set *
1829 getPredecessorDomainConstraints(BasicBlock *BB, __isl_keep isl_set *Domain,
1830 DominatorTree &DT, LoopInfo &LI);
1832 /// Add loop carried constraints to the header block of the loop @p L.
1834 /// @param L The loop to process.
1835 /// @param LI The LoopInfo for the current function.
1837 /// @returns True if there was no problem and false otherwise.
1838 bool addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI);
1840 /// Compute the branching constraints for each basic block in @p R.
1842 /// @param R The region we currently build branching conditions for.
1843 /// @param DT The DominatorTree for the current function.
1844 /// @param LI The LoopInfo for the current function.
1846 /// @returns True if there was no problem and false otherwise.
1847 bool buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
1848 LoopInfo &LI);
1850 /// Propagate the domain constraints through the region @p R.
1852 /// @param R The region we currently build branching conditions for.
1853 /// @param DT The DominatorTree for the current function.
1854 /// @param LI The LoopInfo for the current function.
1856 /// @returns True if there was no problem and false otherwise.
1857 bool propagateDomainConstraints(Region *R, DominatorTree &DT, LoopInfo &LI);
1859 /// Propagate invalid domains of statements through @p R.
1861 /// This method will propagate invalid statement domains through @p R and at
1862 /// the same time add error block domains to them. Additionally, the domains
1863 /// of error statements and those only reachable via error statements will be
1864 /// replaced by an empty set. Later those will be removed completely.
1866 /// @param R The currently traversed region.
1867 /// @param DT The DominatorTree for the current function.
1868 /// @param LI The LoopInfo for the current function.
1870 /// @returns True if there was no problem and false otherwise.
1871 bool propagateInvalidStmtDomains(Region *R, DominatorTree &DT, LoopInfo &LI);
1873 /// Compute the domain for each basic block in @p R.
1875 /// @param R The region we currently traverse.
1876 /// @param DT The DominatorTree for the current function.
1877 /// @param LI The LoopInfo for the current function.
1879 /// @returns True if there was no problem and false otherwise.
1880 bool buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI);
1882 /// Add parameter constraints to @p C that imply a non-empty domain.
1883 __isl_give isl_set *addNonEmptyDomainConstraints(__isl_take isl_set *C) const;
1885 /// Return the access for the base ptr of @p MA if any.
1886 MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
1888 /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
1889 bool hasNonHoistableBasePtrInScop(MemoryAccess *MA,
1890 __isl_keep isl_union_map *Writes);
1892 /// Create equivalence classes for required invariant accesses.
1894 /// These classes will consolidate multiple required invariant loads from the
1895 /// same address in order to keep the number of dimensions in the SCoP
1896 /// description small. For each such class equivalence class only one
1897 /// representing element, hence one required invariant load, will be chosen
1898 /// and modeled as parameter. The method
1899 /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
1900 /// equivalence class with the representing element that is modeled. As a
1901 /// consequence Scop::getIdForParam() will only return an id for the
1902 /// representing element of each equivalence class, thus for each required
1903 /// invariant location.
1904 void buildInvariantEquivalenceClasses();
1906 /// Return the context under which the access cannot be hoisted.
1908 /// @param Access The access to check.
1909 /// @param Writes The set of all memory writes in the scop.
1911 /// @return Return the context under which the access cannot be hoisted or a
1912 /// nullptr if it cannot be hoisted at all.
1913 __isl_give isl_set *getNonHoistableCtx(MemoryAccess *Access,
1914 __isl_keep isl_union_map *Writes);
1916 /// Verify that all required invariant loads have been hoisted.
1918 /// Invariant load hoisting is not guaranteed to hoist all loads that were
1919 /// assumed to be scop invariant during scop detection. This function checks
1920 /// for cases where the hoisting failed, but where it would have been
1921 /// necessary for our scop modeling to be correct. In case of insufficent
1922 /// hoisting the scop is marked as invalid.
1924 /// In the example below Bound[1] is required to be invariant:
1926 /// for (int i = 1; i < Bound[0]; i++)
1927 /// for (int j = 1; j < Bound[1]; j++)
1928 /// ...
1930 void verifyInvariantLoads();
1932 /// Hoist invariant memory loads and check for required ones.
1934 /// We first identify "common" invariant loads, thus loads that are invariant
1935 /// and can be hoisted. Then we check if all required invariant loads have
1936 /// been identified as (common) invariant. A load is a required invariant load
1937 /// if it was assumed to be invariant during SCoP detection, e.g., to assume
1938 /// loop bounds to be affine or runtime alias checks to be placeable. In case
1939 /// a required invariant load was not identified as (common) invariant we will
1940 /// drop this SCoP. An example for both "common" as well as required invariant
1941 /// loads is given below:
1943 /// for (int i = 1; i < *LB[0]; i++)
1944 /// for (int j = 1; j < *LB[1]; j++)
1945 /// A[i][j] += A[0][0] + (*V);
1947 /// Common inv. loads: V, A[0][0], LB[0], LB[1]
1948 /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
1950 void hoistInvariantLoads();
1952 /// Canonicalize arrays with base pointers from the same equivalence class.
1954 /// Some context: in our normal model we assume that each base pointer is
1955 /// related to a single specific memory region, where memory regions
1956 /// associated with different base pointers are disjoint. Consequently we do
1957 /// not need to compute additional data dependences that model possible
1958 /// overlaps of these memory regions. To verify our assumption we compute
1959 /// alias checks that verify that modeled arrays indeed do not overlap. In
1960 /// case an overlap is detected the runtime check fails and we fall back to
1961 /// the original code.
1963 /// In case of arrays where the base pointers are know to be identical,
1964 /// because they are dynamically loaded by accesses that are in the same
1965 /// invariant load equivalence class, such run-time alias check would always
1966 /// be false.
1968 /// This function makes sure that we do not generate consistently failing
1969 /// run-time checks for code that contains distinct arrays with known
1970 /// equivalent base pointers. It identifies for each invariant load
1971 /// equivalence class a single canonical array and canonicalizes all memory
1972 /// accesses that reference arrays that have base pointers that are known to
1973 /// be equal to the base pointer of such a canonical array to this canonical
1974 /// array.
1976 /// We currently do not canonicalize arrays for which certain memory accesses
1977 /// have been hoisted as loop invariant.
1978 void canonicalizeDynamicBasePtrs();
1980 /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
1981 void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
1983 /// Create an id for @p Param and store it in the ParameterIds map.
1984 void createParameterId(const SCEV *Param);
1986 /// Build the Context of the Scop.
1987 void buildContext();
1989 /// Add user provided parameter constraints to context (source code).
1990 void addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI);
1992 /// Add user provided parameter constraints to context (command line).
1993 void addUserContext();
1995 /// Add the bounds of the parameters to the context.
1996 void addParameterBounds();
1998 /// Simplify the assumed and invalid context.
1999 void simplifyContexts();
2001 /// Get the representing SCEV for @p S if applicable, otherwise @p S.
2003 /// Invariant loads of the same location are put in an equivalence class and
2004 /// only one of them is chosen as a representing element that will be
2005 /// modeled as a parameter. The others have to be normalized, i.e.,
2006 /// replaced by the representing element of their equivalence class, in order
2007 /// to get the correct parameter value, e.g., in the SCEVAffinator.
2009 /// @param S The SCEV to normalize.
2011 /// @return The representing SCEV for invariant loads or @p S if none.
2012 const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S);
2014 /// Create a new SCoP statement for @p BB.
2016 /// A new statement for @p BB will be created and added to the statement
2017 /// vector
2018 /// and map.
2020 /// @param BB The basic block we build the statement for.
2021 /// @param SurroundingLoop The loop the created statement is contained in.
2022 void addScopStmt(BasicBlock *BB, Loop *SurroundingLoop);
2024 /// Create a new SCoP statement for @p R.
2026 /// A new statement for @p R will be created and added to the statement vector
2027 /// and map.
2029 /// @param R The region we build the statement for.
2030 /// @param SurroundingLoop The loop the created statement is contained in.
2031 void addScopStmt(Region *R, Loop *SurroundingLoop);
2033 /// Update access dimensionalities.
2035 /// When detecting memory accesses different accesses to the same array may
2036 /// have built with different dimensionality, as outer zero-values dimensions
2037 /// may not have been recognized as separate dimensions. This function goes
2038 /// again over all memory accesses and updates their dimensionality to match
2039 /// the dimensionality of the underlying ScopArrayInfo object.
2040 void updateAccessDimensionality();
2042 /// Fold size constants to the right.
2044 /// In case all memory accesses in a given dimension are multiplied with a
2045 /// common constant, we can remove this constant from the individual access
2046 /// functions and move it to the size of the memory access. We do this as this
2047 /// increases the size of the innermost dimension, consequently widens the
2048 /// valid range the array subscript in this dimension can evaluate to, and
2049 /// as a result increases the likelyhood that our delinearization is
2050 /// correct.
2052 /// Example:
2054 /// A[][n]
2055 /// S[i,j] -> A[2i][2j+1]
2056 /// S[i,j] -> A[2i][2j]
2058 /// =>
2060 /// A[][2n]
2061 /// S[i,j] -> A[i][2j+1]
2062 /// S[i,j] -> A[i][2j]
2064 /// Constants in outer dimensions can arise when the elements of a parametric
2065 /// multi-dimensional array are not elementar data types, but e.g.,
2066 /// structures.
2067 void foldSizeConstantsToRight();
2069 /// Fold memory accesses to handle parametric offset.
2071 /// As a post-processing step, we 'fold' memory accesses to parameteric
2072 /// offsets in the access functions. @see MemoryAccess::foldAccess for
2073 /// details.
2074 void foldAccessRelations();
2076 /// Assume that all memory accesses are within bounds.
2078 /// After we have built a model of all memory accesses, we need to assume
2079 /// that the model we built matches reality -- aka. all modeled memory
2080 /// accesses always remain within bounds. We do this as last step, after
2081 /// all memory accesses have been modeled and canonicalized.
2082 void assumeNoOutOfBounds();
2084 /// Mark arrays that have memory accesses with FortranArrayDescriptor.
2085 void markFortranArrays();
2087 /// Finalize all access relations.
2089 /// When building up access relations, temporary access relations that
2090 /// correctly represent each individual access are constructed. However, these
2091 /// access relations can be inconsistent or non-optimal when looking at the
2092 /// set of accesses as a whole. This function finalizes the memory accesses
2093 /// and constructs a globally consistent state.
2094 void finalizeAccesses();
2096 /// Construct the schedule of this SCoP.
2098 /// @param LI The LoopInfo for the current function.
2099 void buildSchedule(LoopInfo &LI);
2101 /// A loop stack element to keep track of per-loop information during
2102 /// schedule construction.
2103 typedef struct LoopStackElement {
2104 // The loop for which we keep information.
2105 Loop *L;
2107 // The (possibly incomplete) schedule for this loop.
2108 isl_schedule *Schedule;
2110 // The number of basic blocks in the current loop, for which a schedule has
2111 // already been constructed.
2112 unsigned NumBlocksProcessed;
2114 LoopStackElement(Loop *L, __isl_give isl_schedule *S,
2115 unsigned NumBlocksProcessed)
2116 : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
2117 } LoopStackElementTy;
2119 /// The loop stack used for schedule construction.
2121 /// The loop stack keeps track of schedule information for a set of nested
2122 /// loops as well as an (optional) 'nullptr' loop that models the outermost
2123 /// schedule dimension. The loops in a loop stack always have a parent-child
2124 /// relation where the loop at position n is the parent of the loop at
2125 /// position n + 1.
2126 typedef SmallVector<LoopStackElementTy, 4> LoopStackTy;
2128 /// Construct schedule information for a given Region and add the
2129 /// derived information to @p LoopStack.
2131 /// Given a Region we derive schedule information for all RegionNodes
2132 /// contained in this region ensuring that the assigned execution times
2133 /// correctly model the existing control flow relations.
2135 /// @param R The region which to process.
2136 /// @param LoopStack A stack of loops that are currently under
2137 /// construction.
2138 /// @param LI The LoopInfo for the current function.
2139 void buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI);
2141 /// Build Schedule for the region node @p RN and add the derived
2142 /// information to @p LoopStack.
2144 /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
2145 /// schedule for this @p RN and also finalize loop schedules in case the
2146 /// current @p RN completes the loop.
2148 /// In case @p RN is a not-non-affine Region, we delegate the construction to
2149 /// buildSchedule(Region *R, ...).
2151 /// @param RN The RegionNode region traversed.
2152 /// @param LoopStack A stack of loops that are currently under
2153 /// construction.
2154 /// @param LI The LoopInfo for the current function.
2155 void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI);
2157 /// Collect all memory access relations of a given type.
2159 /// @param Predicate A predicate function that returns true if an access is
2160 /// of a given type.
2162 /// @returns The set of memory accesses in the scop that match the predicate.
2163 __isl_give isl_union_map *
2164 getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
2166 /// @name Helper functions for printing the Scop.
2168 //@{
2169 void printContext(raw_ostream &OS) const;
2170 void printArrayInfo(raw_ostream &OS) const;
2171 void printStatements(raw_ostream &OS) const;
2172 void printAliasAssumptions(raw_ostream &OS) const;
2173 //@}
2175 friend class ScopBuilder;
2177 public:
2178 ~Scop();
2180 /// Get the count of copy statements added to this Scop.
2182 /// @return The count of copy statements added to this Scop.
2183 unsigned getCopyStmtsNum() { return CopyStmtsNum; }
2185 /// Create a new copy statement.
2187 /// A new statement will be created and added to the statement vector.
2189 /// @param Stmt The parent statement.
2190 /// @param SourceRel The source location.
2191 /// @param TargetRel The target location.
2192 /// @param Domain The original domain under which copy statement whould
2193 /// be executed.
2194 ScopStmt *addScopStmt(__isl_take isl_map *SourceRel,
2195 __isl_take isl_map *TargetRel,
2196 __isl_take isl_set *Domain);
2198 /// Add the access function to all MemoryAccess objects of the Scop
2199 /// created in this pass.
2200 void addAccessFunction(MemoryAccess *Access) {
2201 AccessFunctions.emplace_back(Access);
2204 ScalarEvolution *getSE() const;
2206 /// Get the count of parameters used in this Scop.
2208 /// @return The count of parameters used in this Scop.
2209 size_t getNumParams() const { return Parameters.size(); }
2211 /// Take a list of parameters and add the new ones to the scop.
2212 void addParams(const ParameterSetTy &NewParameters);
2214 /// Return an iterator range containing the scop parameters.
2215 iterator_range<ParameterSetTy::iterator> parameters() const {
2216 return make_range(Parameters.begin(), Parameters.end());
2219 /// Return whether this scop is empty, i.e. contains no statements that
2220 /// could be executed.
2221 bool isEmpty() const { return Stmts.empty(); }
2223 const StringRef getName() const { return name; }
2225 typedef ArrayInfoSetTy::iterator array_iterator;
2226 typedef ArrayInfoSetTy::const_iterator const_array_iterator;
2227 typedef iterator_range<ArrayInfoSetTy::iterator> array_range;
2228 typedef iterator_range<ArrayInfoSetTy::const_iterator> const_array_range;
2230 inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
2232 inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
2234 inline const_array_iterator array_begin() const {
2235 return ScopArrayInfoSet.begin();
2238 inline const_array_iterator array_end() const {
2239 return ScopArrayInfoSet.end();
2242 inline array_range arrays() {
2243 return array_range(array_begin(), array_end());
2246 inline const_array_range arrays() const {
2247 return const_array_range(array_begin(), array_end());
2250 /// Return the isl_id that represents a certain parameter.
2252 /// @param Parameter A SCEV that was recognized as a Parameter.
2254 /// @return The corresponding isl_id or NULL otherwise.
2255 __isl_give isl_id *getIdForParam(const SCEV *Parameter);
2257 /// Get the maximum region of this static control part.
2259 /// @return The maximum region of this static control part.
2260 inline const Region &getRegion() const { return R; }
2261 inline Region &getRegion() { return R; }
2263 /// Return the function this SCoP is in.
2264 Function &getFunction() const { return *R.getEntry()->getParent(); }
2266 /// Check if @p L is contained in the SCoP.
2267 bool contains(const Loop *L) const { return R.contains(L); }
2269 /// Check if @p BB is contained in the SCoP.
2270 bool contains(const BasicBlock *BB) const { return R.contains(BB); }
2272 /// Check if @p I is contained in the SCoP.
2273 bool contains(const Instruction *I) const { return R.contains(I); }
2275 /// Return the unique exit block of the SCoP.
2276 BasicBlock *getExit() const { return R.getExit(); }
2278 /// Return the unique exiting block of the SCoP if any.
2279 BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
2281 /// Return the unique entry block of the SCoP.
2282 BasicBlock *getEntry() const { return R.getEntry(); }
2284 /// Return the unique entering block of the SCoP if any.
2285 BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
2287 /// Return true if @p BB is the exit block of the SCoP.
2288 bool isExit(BasicBlock *BB) const { return getExit() == BB; }
2290 /// Return a range of all basic blocks in the SCoP.
2291 Region::block_range blocks() const { return R.blocks(); }
2293 /// Return true if and only if @p BB dominates the SCoP.
2294 bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
2296 /// Get the maximum depth of the loop.
2298 /// @return The maximum depth of the loop.
2299 inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
2301 /// Return the invariant equivalence class for @p Val if any.
2302 InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
2304 /// Return the set of invariant accesses.
2305 InvariantEquivClassesTy &getInvariantAccesses() {
2306 return InvariantEquivClasses;
2309 /// Check if the scop has any invariant access.
2310 bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
2312 /// Mark the SCoP as optimized by the scheduler.
2313 void markAsOptimized() { IsOptimized = true; }
2315 /// Check if the SCoP has been optimized by the scheduler.
2316 bool isOptimized() const { return IsOptimized; }
2318 /// Get the name of this Scop.
2319 std::string getNameStr() const;
2321 /// Get the constraint on parameter of this Scop.
2323 /// @return The constraint on parameter of this Scop.
2324 __isl_give isl_set *getContext() const;
2325 __isl_give isl_space *getParamSpace() const;
2327 /// Get the assumed context for this Scop.
2329 /// @return The assumed context of this Scop.
2330 __isl_give isl_set *getAssumedContext() const;
2332 /// Return true if the optimized SCoP can be executed.
2334 /// In addition to the runtime check context this will also utilize the domain
2335 /// constraints to decide it the optimized version can actually be executed.
2337 /// @returns True if the optimized SCoP can be executed.
2338 bool hasFeasibleRuntimeContext() const;
2340 /// Check if the assumption in @p Set is trivial or not.
2342 /// @param Set The relations between parameters that are assumed to hold.
2343 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2344 /// (needed/assumptions) or negative (invalid/restrictions).
2346 /// @returns True if the assumption @p Set is not trivial.
2347 bool isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign);
2349 /// Track and report an assumption.
2351 /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
2352 /// -pass-remarks-analysis=polly-scops' to output the assumptions.
2354 /// @param Kind The assumption kind describing the underlying cause.
2355 /// @param Set The relations between parameters that are assumed to hold.
2356 /// @param Loc The location in the source that caused this assumption.
2357 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2358 /// (needed/assumptions) or negative (invalid/restrictions).
2360 /// @returns True if the assumption is not trivial.
2361 bool trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2362 DebugLoc Loc, AssumptionSign Sign);
2364 /// Add assumptions to assumed context.
2366 /// The assumptions added will be assumed to hold during the execution of the
2367 /// scop. However, as they are generally not statically provable, at code
2368 /// generation time run-time checks will be generated that ensure the
2369 /// assumptions hold.
2371 /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
2372 /// that assumptions do not change the set of statement instances
2373 /// executed.
2375 /// @param Kind The assumption kind describing the underlying cause.
2376 /// @param Set The relations between parameters that are assumed to hold.
2377 /// @param Loc The location in the source that caused this assumption.
2378 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2379 /// (needed/assumptions) or negative (invalid/restrictions).
2380 void addAssumption(AssumptionKind Kind, __isl_take isl_set *Set, DebugLoc Loc,
2381 AssumptionSign Sign);
2383 /// Record an assumption for later addition to the assumed context.
2385 /// This function will add the assumption to the RecordedAssumptions. This
2386 /// collection will be added (@see addAssumption) to the assumed context once
2387 /// all paramaters are known and the context is fully build.
2389 /// @param Kind The assumption kind describing the underlying cause.
2390 /// @param Set The relations between parameters that are assumed to hold.
2391 /// @param Loc The location in the source that caused this assumption.
2392 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2393 /// (needed/assumptions) or negative (invalid/restrictions).
2394 /// @param BB The block in which this assumption was taken. If it is
2395 /// set, the domain of that block will be used to simplify the
2396 /// actual assumption in @p Set once it is added. This is useful
2397 /// if the assumption was created prior to the domain.
2398 void recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
2399 DebugLoc Loc, AssumptionSign Sign,
2400 BasicBlock *BB = nullptr);
2402 /// Add all recorded assumptions to the assumed context.
2403 void addRecordedAssumptions();
2405 /// Mark the scop as invalid.
2407 /// This method adds an assumption to the scop that is always invalid. As a
2408 /// result, the scop will not be optimized later on. This function is commonly
2409 /// called when a condition makes it impossible (or too compile time
2410 /// expensive) to process this scop any further.
2412 /// @param Kind The assumption kind describing the underlying cause.
2413 /// @param Loc The location in the source that triggered .
2414 void invalidate(AssumptionKind Kind, DebugLoc Loc);
2416 /// Get the invalid context for this Scop.
2418 /// @return The invalid context of this Scop.
2419 __isl_give isl_set *getInvalidContext() const;
2421 /// Return true if and only if the InvalidContext is trivial (=empty).
2422 bool hasTrivialInvalidContext() const {
2423 return isl_set_is_empty(InvalidContext);
2426 /// A vector of memory accesses that belong to an alias group.
2427 typedef SmallVector<MemoryAccess *, 4> AliasGroupTy;
2429 /// A vector of alias groups.
2430 typedef SmallVector<Scop::AliasGroupTy, 4> AliasGroupVectorTy;
2432 /// Build the alias checks for this SCoP.
2433 bool buildAliasChecks(AliasAnalysis &AA);
2435 /// Build all alias groups for this SCoP.
2437 /// @returns True if __no__ error occurred, false otherwise.
2438 bool buildAliasGroups(AliasAnalysis &AA);
2440 /// Build alias groups for all memory accesses in the Scop.
2442 /// Using the alias analysis and an alias set tracker we build alias sets
2443 /// for all memory accesses inside the Scop. For each alias set we then map
2444 /// the aliasing pointers back to the memory accesses we know, thus obtain
2445 /// groups of memory accesses which might alias. We also collect the set of
2446 /// arrays through which memory is written.
2448 /// @param AA A reference to the alias analysis.
2450 /// @returns A pair consistent of a vector of alias groups and a set of arrays
2451 /// through which memory is written.
2452 std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2453 buildAliasGroupsForAccesses(AliasAnalysis &AA);
2455 /// Split alias groups by iteration domains.
2457 /// We split each group based on the domains of the minimal/maximal accesses.
2458 /// That means two minimal/maximal accesses are only in a group if their
2459 /// access domains intersect. Otherwise, they are in different groups.
2461 /// @param AliasGroups The alias groups to split
2462 void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
2464 /// Build a given alias group and its access data.
2466 /// @param AliasGroup The alias group to build.
2467 /// @param HasWriteAccess A set of arrays through which memory is not only
2468 /// read, but also written.
2470 /// @returns True if __no__ error occurred, false otherwise.
2471 bool buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2472 DenseSet<const ScopArrayInfo *> HasWriteAccess);
2474 /// Return all alias groups for this SCoP.
2475 const MinMaxVectorPairVectorTy &getAliasGroups() const {
2476 return MinMaxAliasGroups;
2479 /// Get an isl string representing the context.
2480 std::string getContextStr() const;
2482 /// Get an isl string representing the assumed context.
2483 std::string getAssumedContextStr() const;
2485 /// Get an isl string representing the invalid context.
2486 std::string getInvalidContextStr() const;
2488 /// Return the ScopStmt for the given @p BB or nullptr if there is
2489 /// none.
2490 ScopStmt *getStmtFor(BasicBlock *BB) const;
2492 /// Return the ScopStmt that represents the Region @p R, or nullptr if
2493 /// it is not represented by any statement in this Scop.
2494 ScopStmt *getStmtFor(Region *R) const;
2496 /// Return the ScopStmt that represents @p RN; can return nullptr if
2497 /// the RegionNode is not within the SCoP or has been removed due to
2498 /// simplifications.
2499 ScopStmt *getStmtFor(RegionNode *RN) const;
2501 /// Return the ScopStmt an instruction belongs to, or nullptr if it
2502 /// does not belong to any statement in this Scop.
2503 ScopStmt *getStmtFor(Instruction *Inst) const {
2504 return getStmtFor(Inst->getParent());
2507 /// Return the number of statements in the SCoP.
2508 size_t getSize() const { return Stmts.size(); }
2510 /// @name Statements Iterators
2512 /// These iterators iterate over all statements of this Scop.
2513 //@{
2514 typedef StmtSet::iterator iterator;
2515 typedef StmtSet::const_iterator const_iterator;
2517 iterator begin() { return Stmts.begin(); }
2518 iterator end() { return Stmts.end(); }
2519 const_iterator begin() const { return Stmts.begin(); }
2520 const_iterator end() const { return Stmts.end(); }
2522 typedef StmtSet::reverse_iterator reverse_iterator;
2523 typedef StmtSet::const_reverse_iterator const_reverse_iterator;
2525 reverse_iterator rbegin() { return Stmts.rbegin(); }
2526 reverse_iterator rend() { return Stmts.rend(); }
2527 const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
2528 const_reverse_iterator rend() const { return Stmts.rend(); }
2529 //@}
2531 /// Return the set of required invariant loads.
2532 const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
2533 return DC.RequiredILS;
2536 /// Add @p LI to the set of required invariant loads.
2537 void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
2539 /// Return true if and only if @p LI is a required invariant load.
2540 bool isRequiredInvariantLoad(LoadInst *LI) const {
2541 return getRequiredInvariantLoads().count(LI);
2544 /// Return the set of boxed (thus overapproximated) loops.
2545 const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
2547 /// Return true if and only if @p R is a non-affine subregion.
2548 bool isNonAffineSubRegion(const Region *R) {
2549 return DC.NonAffineSubRegionSet.count(R);
2552 const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
2554 /// Return the (possibly new) ScopArrayInfo object for @p Access.
2556 /// @param ElementType The type of the elements stored in this array.
2557 /// @param Kind The kind of the array info object.
2558 /// @param BaseName The optional name of this memory reference.
2559 const ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr,
2560 Type *ElementType,
2561 ArrayRef<const SCEV *> Sizes,
2562 MemoryKind Kind,
2563 const char *BaseName = nullptr);
2565 /// Create an array and return the corresponding ScopArrayInfo object.
2567 /// @param ElementType The type of the elements stored in this array.
2568 /// @param BaseName The name of this memory reference.
2569 /// @param Sizes The sizes of dimensions.
2570 const ScopArrayInfo *createScopArrayInfo(Type *ElementType,
2571 const std::string &BaseName,
2572 const std::vector<unsigned> &Sizes);
2574 /// Return the cached ScopArrayInfo object for @p BasePtr.
2576 /// @param BasePtr The base pointer the object has been stored for.
2577 /// @param Kind The kind of array info object.
2579 /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
2580 /// available.
2581 const ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
2583 /// Return the cached ScopArrayInfo object for @p BasePtr.
2585 /// @param BasePtr The base pointer the object has been stored for.
2586 /// @param Kind The kind of array info object.
2588 /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
2589 /// available).
2590 const ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
2592 /// Invalidate ScopArrayInfo object for base address.
2594 /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
2595 /// @param Kind The Kind of the ScopArrayInfo object.
2596 void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
2597 auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
2598 if (It == ScopArrayInfoMap.end())
2599 return;
2600 ScopArrayInfoSet.remove(It->second.get());
2601 ScopArrayInfoMap.erase(It);
2604 void setContext(__isl_take isl_set *NewContext);
2606 /// Align the parameters in the statement to the scop context
2607 void realignParams();
2609 /// Return true if this SCoP can be profitably optimized.
2611 /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
2612 /// as profitably optimizable.
2614 /// @return Whether this SCoP can be profitably optimized.
2615 bool isProfitable(bool ScalarsAreUnprofitable) const;
2617 /// Return true if the SCoP contained at least one error block.
2618 bool hasErrorBlock() const { return HasErrorBlock; }
2620 /// Return true if the underlying region has a single exiting block.
2621 bool hasSingleExitEdge() const { return HasSingleExitEdge; }
2623 /// Print the static control part.
2625 /// @param OS The output stream the static control part is printed to.
2626 void print(raw_ostream &OS) const;
2628 /// Print the ScopStmt to stderr.
2629 void dump() const;
2631 /// Get the isl context of this static control part.
2633 /// @return The isl context of this static control part.
2634 isl_ctx *getIslCtx() const;
2636 /// Directly return the shared_ptr of the context.
2637 const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
2639 /// Compute the isl representation for the SCEV @p E
2641 /// @param E The SCEV that should be translated.
2642 /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
2643 /// SCEVs known to not reference any loops in the SCoP can be
2644 /// passed without a @p BB.
2645 /// @param NonNegative Flag to indicate the @p E has to be non-negative.
2647 /// Note that this function will always return a valid isl_pw_aff. However, if
2648 /// the translation of @p E was deemed to complex the SCoP is invalidated and
2649 /// a dummy value of appropriate dimension is returned. This allows to bail
2650 /// for complex cases without "error handling code" needed on the users side.
2651 __isl_give PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
2652 bool NonNegative = false);
2654 /// Compute the isl representation for the SCEV @p E
2656 /// This function is like @see Scop::getPwAff() but strips away the invalid
2657 /// domain part associated with the piecewise affine function.
2658 __isl_give isl_pw_aff *getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr);
2660 /// Return the domain of @p Stmt.
2662 /// @param Stmt The statement for which the conditions should be returned.
2663 __isl_give isl_set *getDomainConditions(const ScopStmt *Stmt) const;
2665 /// Return the domain of @p BB.
2667 /// @param BB The block for which the conditions should be returned.
2668 __isl_give isl_set *getDomainConditions(BasicBlock *BB) const;
2670 /// Get a union set containing the iteration domains of all statements.
2671 __isl_give isl_union_set *getDomains() const;
2673 /// Get a union map of all may-writes performed in the SCoP.
2674 __isl_give isl_union_map *getMayWrites();
2676 /// Get a union map of all must-writes performed in the SCoP.
2677 __isl_give isl_union_map *getMustWrites();
2679 /// Get a union map of all writes performed in the SCoP.
2680 __isl_give isl_union_map *getWrites();
2682 /// Get a union map of all reads performed in the SCoP.
2683 __isl_give isl_union_map *getReads();
2685 /// Get a union map of all memory accesses performed in the SCoP.
2686 __isl_give isl_union_map *getAccesses();
2688 /// Get the schedule of all the statements in the SCoP.
2690 /// @return The schedule of all the statements in the SCoP, if the schedule of
2691 /// the Scop does not contain extension nodes, and nullptr, otherwise.
2692 __isl_give isl_union_map *getSchedule() const;
2694 /// Get a schedule tree describing the schedule of all statements.
2695 __isl_give isl_schedule *getScheduleTree() const;
2697 /// Update the current schedule
2699 /// NewSchedule The new schedule (given as a flat union-map).
2700 void setSchedule(__isl_take isl_union_map *NewSchedule);
2702 /// Update the current schedule
2704 /// NewSchedule The new schedule (given as schedule tree).
2705 void setScheduleTree(__isl_take isl_schedule *NewSchedule);
2707 /// Intersects the domains of all statements in the SCoP.
2709 /// @return true if a change was made
2710 bool restrictDomains(__isl_take isl_union_set *Domain);
2712 /// Get the depth of a loop relative to the outermost loop in the Scop.
2714 /// This will return
2715 /// 0 if @p L is an outermost loop in the SCoP
2716 /// >0 for other loops in the SCoP
2717 /// -1 if @p L is nullptr or there is no outermost loop in the SCoP
2718 int getRelativeLoopDepth(const Loop *L) const;
2720 /// Find the ScopArrayInfo associated with an isl Id
2721 /// that has name @p Name.
2722 ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
2724 /// Check whether @p Schedule contains extension nodes.
2726 /// @return true if @p Schedule contains extension nodes.
2727 static bool containsExtensionNode(__isl_keep isl_schedule *Schedule);
2729 /// Simplify the SCoP representation.
2731 /// @param AfterHoisting Whether it is called after invariant load hoisting.
2732 /// When true, also removes statements without
2733 /// side-effects.
2734 void simplifySCoP(bool AfterHoisting);
2736 /// Get the next free array index.
2738 /// This function returns a unique index which can be used to identify an
2739 /// array.
2740 long getNextArrayIdx() { return ArrayIdx++; }
2742 /// Get the next free statement index.
2744 /// This function returns a unique index which can be used to identify a
2745 /// statement.
2746 long getNextStmtIdx() { return StmtIdx++; }
2749 /// Print Scop scop to raw_ostream O.
2750 static inline raw_ostream &operator<<(raw_ostream &O, const Scop &scop) {
2751 scop.print(O);
2752 return O;
2755 /// The legacy pass manager's analysis pass to compute scop information
2756 /// for a region.
2757 class ScopInfoRegionPass : public RegionPass {
2758 /// The Scop pointer which is used to construct a Scop.
2759 std::unique_ptr<Scop> S;
2761 public:
2762 static char ID; // Pass identification, replacement for typeid
2764 ScopInfoRegionPass() : RegionPass(ID) {}
2765 ~ScopInfoRegionPass() {}
2767 /// Build Scop object, the Polly IR of static control
2768 /// part for the current SESE-Region.
2770 /// @return If the current region is a valid for a static control part,
2771 /// return the Polly IR representing this static control part,
2772 /// return null otherwise.
2773 Scop *getScop() { return S.get(); }
2774 const Scop *getScop() const { return S.get(); }
2776 /// Calculate the polyhedral scop information for a given Region.
2777 bool runOnRegion(Region *R, RGPassManager &RGM) override;
2779 void releaseMemory() override { S.reset(); }
2781 void print(raw_ostream &O, const Module *M = nullptr) const override;
2783 void getAnalysisUsage(AnalysisUsage &AU) const override;
2786 class ScopInfo {
2787 public:
2788 using RegionToScopMapTy = DenseMap<Region *, std::unique_ptr<Scop>>;
2789 using iterator = RegionToScopMapTy::iterator;
2790 using const_iterator = RegionToScopMapTy::const_iterator;
2792 private:
2793 /// A map of Region to its Scop object containing
2794 /// Polly IR of static control part
2795 RegionToScopMapTy RegionToScopMap;
2797 public:
2798 ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
2799 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
2800 AssumptionCache &AC);
2802 /// Get the Scop object for the given Region
2804 /// @return If the given region is the maximal region within a scop, return
2805 /// the scop object. If the given region is a subregion, return a
2806 /// nullptr. Top level region containing the entry block of a function
2807 /// is not considered in the scop creation.
2808 Scop *getScop(Region *R) const {
2809 auto MapIt = RegionToScopMap.find(R);
2810 if (MapIt != RegionToScopMap.end())
2811 return MapIt->second.get();
2812 return nullptr;
2815 iterator begin() { return RegionToScopMap.begin(); }
2816 iterator end() { return RegionToScopMap.end(); }
2817 const_iterator begin() const { return RegionToScopMap.begin(); }
2818 const_iterator end() const { return RegionToScopMap.end(); }
2819 bool empty() const { return RegionToScopMap.empty(); }
2822 struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
2823 static AnalysisKey Key;
2824 using Result = ScopInfo;
2825 Result run(Function &, FunctionAnalysisManager &);
2828 struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
2829 ScopInfoPrinterPass(raw_ostream &O) : Stream(O) {}
2830 PreservedAnalyses run(Function &, FunctionAnalysisManager &);
2831 raw_ostream &Stream;
2834 //===----------------------------------------------------------------------===//
2835 /// The legacy pass manager's analysis pass to compute scop information
2836 /// for the whole function.
2838 /// This pass will maintain a map of the maximal region within a scop to its
2839 /// scop object for all the feasible scops present in a function.
2840 /// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
2841 /// region pass manager.
2842 class ScopInfoWrapperPass : public FunctionPass {
2843 std::unique_ptr<ScopInfo> Result;
2845 public:
2846 ScopInfoWrapperPass() : FunctionPass(ID) {}
2847 ~ScopInfoWrapperPass() = default;
2849 static char ID; // Pass identification, replacement for typeid
2851 ScopInfo *getSI() { return Result.get(); }
2852 const ScopInfo *getSI() const { return Result.get(); }
2854 /// Calculate all the polyhedral scops for a given function.
2855 bool runOnFunction(Function &F) override;
2857 void releaseMemory() override { Result.reset(); }
2859 void print(raw_ostream &O, const Module *M = nullptr) const override;
2861 void getAnalysisUsage(AnalysisUsage &AU) const override;
2864 } // end namespace polly
2866 namespace llvm {
2867 class PassRegistry;
2868 void initializeScopInfoRegionPassPass(llvm::PassRegistry &);
2869 void initializeScopInfoWrapperPassPass(llvm::PassRegistry &);
2870 } // namespace llvm
2872 #endif