1 //===- polly/ScopBuilder.h --------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Create a polyhedral description for a static control flow region.
10 //
11 // The pass creates a polyhedral description of the Scops detected by the SCoP
12 // detection derived from their LLVM-IR code.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef POLLY_SCOPBUILDER_H
17 #define POLLY_SCOPBUILDER_H
18 
19 #include "polly/ScopInfo.h"
20 #include "polly/Support/ScopHelper.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SetVector.h"
23 
24 namespace polly {
25 using llvm::SmallSetVector;
26 
27 class ScopDetection;
28 
29 /// Command line switch whether to model read-only accesses.
30 extern bool ModelReadOnlyScalars;
31 
32 /// Build the Polly IR (Scop and ScopStmt) on a Region.
33 class ScopBuilder {
34 
35   /// The AAResults to build AliasSetTracker.
36   AAResults &AA;
37 
38   /// Target data for element size computing.
39   const DataLayout &DL;
40 
41   /// DominatorTree to reason about guaranteed execution.
42   DominatorTree &DT;
43 
44   /// LoopInfo for information about loops.
45   LoopInfo &LI;
46 
47   /// Valid Regions for Scop
48   ScopDetection &SD;
49 
50   /// The ScalarEvolution to help building Scop.
51   ScalarEvolution &SE;
52 
53   /// An optimization diagnostic interface to add optimization remarks.
54   OptimizationRemarkEmitter &ORE;
55 
56   /// Set of instructions that might read any memory location.
57   SmallVector<std::pair<ScopStmt *, Instruction *>, 16> GlobalReads;
58 
59   /// Set of all accessed array base pointers.
60   SmallSetVector<Value *, 16> ArrayBasePointers;
61 
62   // The Scop
63   std::unique_ptr<Scop> scop;
64 
65   /// Collection to hold taken assumptions.
66   ///
67   /// There are two reasons why we want to record assumptions first before we
68   /// add them to the assumed/invalid context:
69   ///   1) If the SCoP is not profitable or otherwise invalid without the
70   ///      assumed/invalid context we do not have to compute it.
71   ///   2) Information about the context are gathered rather late in the SCoP
72   ///      construction (basically after we know all parameters), thus the user
73   ///      might see overly complicated assumptions to be taken while they will
74   ///      only be simplified later on.
75   RecordedAssumptionsTy RecordedAssumptions;
76 
77   // Methods for pattern matching against Fortran code generated by dragonegg.
78   // @{
79 
80   /// Try to match for the descriptor of a Fortran array whose allocation
81   /// is not visible. That is, we can see the load/store into the memory, but
82   /// we don't actually know where the memory is allocated. If ALLOCATE had been
83   /// called on the Fortran array, then we will see the lowered malloc() call.
84   /// If not, this is dubbed as an "invisible allocation".
85   ///
86   /// "<descriptor>" is the descriptor of the Fortran array.
87   ///
88   /// Pattern match for "@descriptor":
89   ///  1. %mem = load double*, double** bitcast (%"struct.array1_real(kind=8)"*
90   ///    <descriptor> to double**), align 32
91   ///
92   ///  2. [%slot = getelementptr inbounds i8, i8* %mem, i64 <index>]
93   ///  2 is optional because if you are writing to the 0th index, you don't
94   ///     need a GEP.
95   ///
96   ///  3.1 store/load <memtype> <val>, <memtype>* %slot
97   ///  3.2 store/load <memtype> <val>, <memtype>* %mem
98   ///
99   /// @see polly::MemoryAccess, polly::ScopArrayInfo
100   ///
101   /// @note assumes -polly-canonicalize has been run.
102   ///
103   /// @param Inst The LoadInst/StoreInst that accesses the memory.
104   ///
105   /// @returns Reference to <descriptor> on success, nullptr on failure.
106   Value *findFADAllocationInvisible(MemAccInst Inst);
107 
108   /// Try to match for the descriptor of a Fortran array whose allocation
109   /// call is visible. When we have a Fortran array, we try to look for a
110   /// Fortran array where we can see the lowered ALLOCATE call. ALLOCATE
111   /// is materialized as a malloc(...) which we pattern match for.
112   ///
113   /// Pattern match for "%untypedmem":
114   ///  1. %untypedmem = i8* @malloc(...)
115   ///
116   ///  2. %typedmem = bitcast i8* %untypedmem to <memtype>
117   ///
118   ///  3. [%slot = getelementptr inbounds i8, i8* %typedmem, i64 <index>]
119   ///  3 is optional because if you are writing to the 0th index, you don't
120   ///     need a GEP.
121   ///
122   ///  4.1 store/load <memtype> <val>, <memtype>* %slot, align 8
123   ///  4.2 store/load <memtype> <val>, <memtype>* %mem, align 8
124   ///
125   /// @see polly::MemoryAccess, polly::ScopArrayInfo
126   ///
127   /// @note assumes -polly-canonicalize has been run.
128   ///
129   /// @param Inst The LoadInst/StoreInst that accesses the memory.
130   ///
131   /// @returns Reference to %untypedmem on success, nullptr on failure.
132   Value *findFADAllocationVisible(MemAccInst Inst);
133 
134   // @}
135 
136   // Build the SCoP for Region @p R.
137   void buildScop(Region &R, AssumptionCache &AC);
138 
139   /// Adjust the dimensions of @p Dom that was constructed for @p OldL
140   ///        to be compatible to domains constructed for loop @p NewL.
141   ///
142   /// This function assumes @p NewL and @p OldL are equal or there is a CFG
143   /// edge from @p OldL to @p NewL.
144   isl::set adjustDomainDimensions(isl::set Dom, Loop *OldL, Loop *NewL);
145 
146   /// Compute the domain for each basic block in @p R.
147   ///
148   /// @param R                The region we currently traverse.
149   /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
150   ///                         region.
151   ///
152   /// @returns True if there was no problem and false otherwise.
153   bool buildDomains(Region *R,
154                     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
155 
156   /// Compute the branching constraints for each basic block in @p R.
157   ///
158   /// @param R                The region we currently build branching conditions
159   ///                         for.
160   /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
161   ///                         region.
162   ///
163   /// @returns True if there was no problem and false otherwise.
164   bool buildDomainsWithBranchConstraints(
165       Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
166 
167   /// Build the conditions sets for the terminator @p TI in the @p Domain.
168   ///
169   /// This will fill @p ConditionSets with the conditions under which control
170   /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
171   /// have as many elements as @p TI has successors.
172   bool buildConditionSets(BasicBlock *BB, Instruction *TI, Loop *L,
173                           __isl_keep isl_set *Domain,
174                           DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
175                           SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
176 
177   /// Build the conditions sets for the branch condition @p Condition in
178   /// the @p Domain.
179   ///
180   /// This will fill @p ConditionSets with the conditions under which control
181   /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
182   /// have as many elements as @p TI has successors. If @p TI is nullptr the
183   /// context under which @p Condition is true/false will be returned as the
184   /// new elements of @p ConditionSets.
185   bool buildConditionSets(BasicBlock *BB, Value *Condition, Instruction *TI,
186                           Loop *L, __isl_keep isl_set *Domain,
187                           DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
188                           SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
189 
190   /// Build the conditions sets for the switch @p SI in the @p Domain.
191   ///
192   /// This will fill @p ConditionSets with the conditions under which control
193   /// will be moved from @p SI to its successors. Hence, @p ConditionSets will
194   /// have as many elements as @p SI has successors.
195   bool buildConditionSets(BasicBlock *BB, SwitchInst *SI, Loop *L,
196                           __isl_keep isl_set *Domain,
197                           DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
198                           SmallVectorImpl<__isl_give isl_set *> &ConditionSets);
199 
200   /// Build condition sets for unsigned ICmpInst(s).
201   /// Special handling is required for unsigned operands to ensure that if
202   /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
203   /// it should wrap around.
204   ///
205   /// @param IsStrictUpperBound holds information on the predicate relation
206   /// between TestVal and UpperBound, i.e,
207   /// TestVal < UpperBound  OR  TestVal <= UpperBound
208   __isl_give isl_set *buildUnsignedConditionSets(
209       BasicBlock *BB, Value *Condition, __isl_keep isl_set *Domain,
210       const SCEV *SCEV_TestVal, const SCEV *SCEV_UpperBound,
211       DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
212       bool IsStrictUpperBound);
213 
214   /// Propagate the domain constraints through the region @p R.
215   ///
216   /// @param R                The region we currently build branching
217   /// conditions for.
218   /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
219   ///                         region.
220   ///
221   /// @returns True if there was no problem and false otherwise.
222   bool propagateDomainConstraints(
223       Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
224 
225   /// Propagate domains that are known due to graph properties.
226   ///
227   /// As a CFG is mostly structured we use the graph properties to propagate
228   /// domains without the need to compute all path conditions. In particular,
229   /// if a block A dominates a block B and B post-dominates A we know that the
230   /// domain of B is a superset of the domain of A. As we do not have
231   /// post-dominator information available here we use the less precise region
232   /// information. Given a region R, we know that the exit is always executed
233   /// if the entry was executed, thus the domain of the exit is a superset of
234   /// the domain of the entry. In case the exit can only be reached from
235   /// within the region the domains are in fact equal. This function will use
236   /// this property to avoid the generation of condition constraints that
237   /// determine when a branch is taken. If @p BB is a region entry block we
238   /// will propagate its domain to the region exit block. Additionally, we put
239   /// the region exit block in the @p FinishedExitBlocks set so we can later
240   /// skip edges from within the region to that block.
241   ///
242   /// @param BB                 The block for which the domain is currently
243   ///                           propagated.
244   /// @param BBLoop             The innermost affine loop surrounding @p BB.
245   /// @param FinishedExitBlocks Set of region exits the domain was set for.
246   /// @param InvalidDomainMap   BB to InvalidDomain map for the BB of current
247   ///                           region.
248   void propagateDomainConstraintsToRegionExit(
249       BasicBlock *BB, Loop *BBLoop,
250       SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks,
251       DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
252 
253   /// Propagate invalid domains of statements through @p R.
254   ///
255   /// This method will propagate invalid statement domains through @p R and at
256   /// the same time add error block domains to them. Additionally, the domains
257   /// of error statements and those only reachable via error statements will
258   /// be replaced by an empty set. Later those will be removed completely.
259   ///
260   /// @param R                The currently traversed region.
261   /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
262   ///                         region.
263   //
264   /// @returns True if there was no problem and false otherwise.
265   bool propagateInvalidStmtDomains(
266       Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
267 
268   /// Compute the union of predecessor domains for @p BB.
269   ///
270   /// To compute the union of all domains of predecessors of @p BB this
271   /// function applies similar reasoning on the CFG structure as described for
272   ///   @see propagateDomainConstraintsToRegionExit
273   ///
274   /// @param BB     The block for which the predecessor domains are collected.
275   /// @param Domain The domain under which BB is executed.
276   ///
277   /// @returns The domain under which @p BB is executed.
278   isl::set getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain);
279 
280   /// Add loop carried constraints to the header block of the loop @p L.
281   ///
282   /// @param L                The loop to process.
283   /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
284   ///                         region.
285   ///
286   /// @returns True if there was no problem and false otherwise.
287   bool addLoopBoundsToHeaderDomain(
288       Loop *L, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
289 
290   /// Compute the isl representation for the SCEV @p E in this BB.
291   ///
292   /// @param BB               The BB for which isl representation is to be
293   /// computed.
294   /// @param InvalidDomainMap A map of BB to their invalid domains.
295   /// @param E                The SCEV that should be translated.
296   /// @param NonNegative      Flag to indicate the @p E has to be
297   /// non-negative.
298   ///
299   /// Note that this function will also adjust the invalid context
300   /// accordingly.
301   __isl_give isl_pw_aff *
302   getPwAff(BasicBlock *BB, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
303            const SCEV *E, bool NonNegative = false);
304 
305   /// Create equivalence classes for required invariant accesses.
306   ///
307   /// These classes will consolidate multiple required invariant loads from the
308   /// same address in order to keep the number of dimensions in the SCoP
309   /// description small. For each such class equivalence class only one
310   /// representing element, hence one required invariant load, will be chosen
311   /// and modeled as parameter. The method
312   /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
313   /// equivalence class with the representing element that is modeled. As a
314   /// consequence Scop::getIdForParam() will only return an id for the
315   /// representing element of each equivalence class, thus for each required
316   /// invariant location.
317   void buildInvariantEquivalenceClasses();
318 
319   /// Try to build a multi-dimensional fixed sized MemoryAccess from the
320   /// Load/Store instruction.
321   ///
322   /// @param Inst       The Load/Store instruction that access the memory
323   /// @param Stmt       The parent statement of the instruction
324   ///
325   /// @returns True if the access could be built, False otherwise.
326   bool buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt);
327 
328   /// Try to build a multi-dimensional parametric sized MemoryAccess.
329   ///        from the Load/Store instruction.
330   ///
331   /// @param Inst       The Load/Store instruction that access the memory
332   /// @param Stmt       The parent statement of the instruction
333   ///
334   /// @returns True if the access could be built, False otherwise.
335   bool buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt);
336 
337   /// Try to build a MemoryAccess for a memory intrinsic.
338   ///
339   /// @param Inst       The instruction that access the memory
340   /// @param Stmt       The parent statement of the instruction
341   ///
342   /// @returns True if the access could be built, False otherwise.
343   bool buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt);
344 
345   /// Try to build a MemoryAccess for a call instruction.
346   ///
347   /// @param Inst       The call instruction that access the memory
348   /// @param Stmt       The parent statement of the instruction
349   ///
350   /// @returns True if the access could be built, False otherwise.
351   bool buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt);
352 
353   /// Build a single-dimensional parametric sized MemoryAccess
354   ///        from the Load/Store instruction.
355   ///
356   /// @param Inst       The Load/Store instruction that access the memory
357   /// @param Stmt       The parent statement of the instruction
358   void buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt);
359 
360   /// Finalize all access relations.
361   ///
362   /// When building up access relations, temporary access relations that
363   /// correctly represent each individual access are constructed. However, these
364   /// access relations can be inconsistent or non-optimal when looking at the
365   /// set of accesses as a whole. This function finalizes the memory accesses
366   /// and constructs a globally consistent state.
367   void finalizeAccesses();
368 
369   /// Update access dimensionalities.
370   ///
371   /// When detecting memory accesses different accesses to the same array may
372   /// have built with different dimensionality, as outer zero-values dimensions
373   /// may not have been recognized as separate dimensions. This function goes
374   /// again over all memory accesses and updates their dimensionality to match
375   /// the dimensionality of the underlying ScopArrayInfo object.
376   void updateAccessDimensionality();
377 
378   /// Fold size constants to the right.
379   ///
380   /// In case all memory accesses in a given dimension are multiplied with a
381   /// common constant, we can remove this constant from the individual access
382   /// functions and move it to the size of the memory access. We do this as this
383   /// increases the size of the innermost dimension, consequently widens the
384   /// valid range the array subscript in this dimension can evaluate to, and
385   /// as a result increases the likelihood that our delinearization is
386   /// correct.
387   ///
388   /// Example:
389   ///
390   ///    A[][n]
391   ///    S[i,j] -> A[2i][2j+1]
392   ///    S[i,j] -> A[2i][2j]
393   ///
394   ///    =>
395   ///
396   ///    A[][2n]
397   ///    S[i,j] -> A[i][2j+1]
398   ///    S[i,j] -> A[i][2j]
399   ///
400   /// Constants in outer dimensions can arise when the elements of a parametric
401   /// multi-dimensional array are not elementary data types, but e.g.,
402   /// structures.
403   void foldSizeConstantsToRight();
404 
405   /// Fold memory accesses to handle parametric offset.
406   ///
407   /// As a post-processing step, we 'fold' memory accesses to parametric
408   /// offsets in the access functions. @see MemoryAccess::foldAccess for
409   /// details.
410   void foldAccessRelations();
411 
412   /// Assume that all memory accesses are within bounds.
413   ///
414   /// After we have built a model of all memory accesses, we need to assume
415   /// that the model we built matches reality -- aka. all modeled memory
416   /// accesses always remain within bounds. We do this as last step, after
417   /// all memory accesses have been modeled and canonicalized.
418   void assumeNoOutOfBounds();
419 
420   /// Mark arrays that have memory accesses with FortranArrayDescriptor.
421   void markFortranArrays();
422 
423   /// Build the alias checks for this SCoP.
424   bool buildAliasChecks();
425 
426   /// A vector of memory accesses that belong to an alias group.
427   using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
428 
429   /// A vector of alias groups.
430   using AliasGroupVectorTy = SmallVector<AliasGroupTy, 4>;
431 
432   /// Build a given alias group and its access data.
433   ///
434   /// @param AliasGroup     The alias group to build.
435   /// @param HasWriteAccess A set of arrays through which memory is not only
436   ///                       read, but also written.
437   //
438   /// @returns True if __no__ error occurred, false otherwise.
439   bool buildAliasGroup(AliasGroupTy &AliasGroup,
440                        DenseSet<const ScopArrayInfo *> HasWriteAccess);
441 
442   /// Build all alias groups for this SCoP.
443   ///
444   /// @returns True if __no__ error occurred, false otherwise.
445   bool buildAliasGroups();
446 
447   /// Build alias groups for all memory accesses in the Scop.
448   ///
449   /// Using the alias analysis and an alias set tracker we build alias sets
450   /// for all memory accesses inside the Scop. For each alias set we then map
451   /// the aliasing pointers back to the memory accesses we know, thus obtain
452   /// groups of memory accesses which might alias. We also collect the set of
453   /// arrays through which memory is written.
454   ///
455   /// @returns A pair consistent of a vector of alias groups and a set of arrays
456   ///          through which memory is written.
457   std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
458   buildAliasGroupsForAccesses();
459 
460   ///  Split alias groups by iteration domains.
461   ///
462   ///  We split each group based on the domains of the minimal/maximal accesses.
463   ///  That means two minimal/maximal accesses are only in a group if their
464   ///  access domains intersect. Otherwise, they are in different groups.
465   ///
466   ///  @param AliasGroups The alias groups to split
467   void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
468 
469   /// Build an instance of MemoryAccess from the Load/Store instruction.
470   ///
471   /// @param Inst       The Load/Store instruction that access the memory
472   /// @param Stmt       The parent statement of the instruction
473   void buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt);
474 
475   /// Analyze and extract the cross-BB scalar dependences (or, dataflow
476   /// dependencies) of an instruction.
477   ///
478   /// @param UserStmt The statement @p Inst resides in.
479   /// @param Inst     The instruction to be analyzed.
480   void buildScalarDependences(ScopStmt *UserStmt, Instruction *Inst);
481 
482   /// Build the escaping dependences for @p Inst.
483   ///
484   /// Search for uses of the llvm::Value defined by @p Inst that are not
485   /// within the SCoP. If there is such use, add a SCALAR WRITE such that
486   /// it is available after the SCoP as escaping value.
487   ///
488   /// @param Inst The instruction to be analyzed.
489   void buildEscapingDependences(Instruction *Inst);
490 
491   /// Create MemoryAccesses for the given PHI node in the given region.
492   ///
493   /// @param PHIStmt            The statement @p PHI resides in.
494   /// @param PHI                The PHI node to be handled
495   /// @param NonAffineSubRegion The non affine sub-region @p PHI is in.
496   /// @param IsExitBlock        Flag to indicate that @p PHI is in the exit BB.
497   void buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI,
498                         Region *NonAffineSubRegion, bool IsExitBlock = false);
499 
500   /// Build the access functions for the subregion @p SR.
501   void buildAccessFunctions();
502 
503   /// Should an instruction be modeled in a ScopStmt.
504   ///
505   /// @param Inst The instruction to check.
506   /// @param L    The loop in which context the instruction is looked at.
507   ///
508   /// @returns True if the instruction should be modeled.
509   bool shouldModelInst(Instruction *Inst, Loop *L);
510 
511   /// Create one or more ScopStmts for @p BB.
512   ///
513   /// Consecutive instructions are associated to the same statement until a
514   /// separator is found.
515   void buildSequentialBlockStmts(BasicBlock *BB, bool SplitOnStore = false);
516 
517   /// Create one or more ScopStmts for @p BB using equivalence classes.
518   ///
519   /// Instructions of a basic block that belong to the same equivalence class
520   /// are added to the same statement.
521   void buildEqivClassBlockStmts(BasicBlock *BB);
522 
523   /// Create ScopStmt for all BBs and non-affine subregions of @p SR.
524   ///
525   /// @param SR A subregion of @p R.
526   ///
527   /// Some of the statements might be optimized away later when they do not
528   /// access any memory and thus have no effect.
529   void buildStmts(Region &SR);
530 
531   /// Build the access functions for the statement @p Stmt in or represented by
532   /// @p BB.
533   ///
534   /// @param Stmt               Statement to add MemoryAccesses to.
535   /// @param BB                 A basic block in @p R.
536   /// @param NonAffineSubRegion The non affine sub-region @p BB is in.
537   void buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB,
538                             Region *NonAffineSubRegion = nullptr);
539 
540   /// Create a new MemoryAccess object and add it to #AccFuncMap.
541   ///
542   /// @param Stmt        The statement where the access takes place.
543   /// @param Inst        The instruction doing the access. It is not necessarily
544   ///                    inside @p BB.
545   /// @param AccType     The kind of access.
546   /// @param BaseAddress The accessed array's base address.
547   /// @param ElemType    The type of the accessed array elements.
548   /// @param Affine      Whether all subscripts are affine expressions.
549   /// @param AccessValue Value read or written.
550   /// @param Subscripts  Access subscripts per dimension.
551   /// @param Sizes       The array dimension's sizes.
552   /// @param Kind        The kind of memory accessed.
553   ///
554   /// @return The created MemoryAccess, or nullptr if the access is not within
555   ///         the SCoP.
556   MemoryAccess *addMemoryAccess(ScopStmt *Stmt, Instruction *Inst,
557                                 MemoryAccess::AccessType AccType,
558                                 Value *BaseAddress, Type *ElemType, bool Affine,
559                                 Value *AccessValue,
560                                 ArrayRef<const SCEV *> Subscripts,
561                                 ArrayRef<const SCEV *> Sizes, MemoryKind Kind);
562 
563   /// Create a MemoryAccess that represents either a LoadInst or
564   /// StoreInst.
565   ///
566   /// @param Stmt        The statement to add the MemoryAccess to.
567   /// @param MemAccInst  The LoadInst or StoreInst.
568   /// @param AccType     The kind of access.
569   /// @param BaseAddress The accessed array's base address.
570   /// @param ElemType    The type of the accessed array elements.
571   /// @param IsAffine    Whether all subscripts are affine expressions.
572   /// @param Subscripts  Access subscripts per dimension.
573   /// @param Sizes       The array dimension's sizes.
574   /// @param AccessValue Value read or written.
575   ///
576   /// @see MemoryKind
577   void addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst,
578                       MemoryAccess::AccessType AccType, Value *BaseAddress,
579                       Type *ElemType, bool IsAffine,
580                       ArrayRef<const SCEV *> Subscripts,
581                       ArrayRef<const SCEV *> Sizes, Value *AccessValue);
582 
583   /// Create a MemoryAccess for writing an llvm::Instruction.
584   ///
585   /// The access will be created at the position of @p Inst.
586   ///
587   /// @param Inst The instruction to be written.
588   ///
589   /// @see ensureValueRead()
590   /// @see MemoryKind
591   void ensureValueWrite(Instruction *Inst);
592 
593   /// Ensure an llvm::Value is available in the BB's statement, creating a
594   /// MemoryAccess for reloading it if necessary.
595   ///
596   /// @param V        The value expected to be loaded.
597   /// @param UserStmt Where to reload the value.
598   ///
599   /// @see ensureValueStore()
600   /// @see MemoryKind
601   void ensureValueRead(Value *V, ScopStmt *UserStmt);
602 
603   /// Create a write MemoryAccess for the incoming block of a phi node.
604   ///
605   /// Each of the incoming blocks write their incoming value to be picked in the
606   /// phi's block.
607   ///
608   /// @param PHI           PHINode under consideration.
609   /// @param IncomingStmt  The statement to add the MemoryAccess to.
610   /// @param IncomingBlock Some predecessor block.
611   /// @param IncomingValue @p PHI's value when coming from @p IncomingBlock.
612   /// @param IsExitBlock   When true, uses the .s2a alloca instead of the
613   ///                      .phiops one. Required for values escaping through a
614   ///                      PHINode in the SCoP region's exit block.
615   /// @see addPHIReadAccess()
616   /// @see MemoryKind
617   void ensurePHIWrite(PHINode *PHI, ScopStmt *IncomintStmt,
618                       BasicBlock *IncomingBlock, Value *IncomingValue,
619                       bool IsExitBlock);
620 
621   /// Add user provided parameter constraints to context (command line).
622   void addUserContext();
623 
624   /// Add user provided parameter constraints to context (source code).
625   void addUserAssumptions(AssumptionCache &AC,
626                           DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
627 
628   /// Add all recorded assumptions to the assumed context.
629   void addRecordedAssumptions();
630 
631   /// Create a MemoryAccess for reading the value of a phi.
632   ///
633   /// The modeling assumes that all incoming blocks write their incoming value
634   /// to the same location. Thus, this access will read the incoming block's
635   /// value as instructed by this @p PHI.
636   ///
637   /// @param PHIStmt Statement @p PHI resides in.
638   /// @param PHI     PHINode under consideration; the READ access will be added
639   ///                here.
640   ///
641   /// @see ensurePHIWrite()
642   /// @see MemoryKind
643   void addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI);
644 
645   /// Wrapper function to calculate minimal/maximal accesses to each array.
646   bool calculateMinMaxAccess(AliasGroupTy AliasGroup,
647                              Scop::MinMaxVectorTy &MinMaxAccesses);
648   /// Build the domain of @p Stmt.
649   void buildDomain(ScopStmt &Stmt);
650 
651   /// Fill NestLoops with loops surrounding @p Stmt.
652   void collectSurroundingLoops(ScopStmt &Stmt);
653 
654   /// Check for reductions in @p Stmt.
655   ///
656   /// Iterate over all store memory accesses and check for valid binary
657   /// reduction like chains. For all candidates we check if they have the same
658   /// base address and there are no other accesses which overlap with them. The
659   /// base address check rules out impossible reductions candidates early. The
660   /// overlap check, together with the "only one user" check in
661   /// collectCandidateReductionLoads, guarantees that none of the intermediate
662   /// results will escape during execution of the loop nest. We basically check
663   /// here that no other memory access can access the same memory as the
664   /// potential reduction.
665   void checkForReductions(ScopStmt &Stmt);
666 
667   /// Verify that all required invariant loads have been hoisted.
668   ///
669   /// Invariant load hoisting is not guaranteed to hoist all loads that were
670   /// assumed to be scop invariant during scop detection. This function checks
671   /// for cases where the hoisting failed, but where it would have been
672   /// necessary for our scop modeling to be correct. In case of insufficient
673   /// hoisting the scop is marked as invalid.
674   ///
675   /// In the example below Bound[1] is required to be invariant:
676   ///
677   /// for (int i = 1; i < Bound[0]; i++)
678   ///   for (int j = 1; j < Bound[1]; j++)
679   ///     ...
680   void verifyInvariantLoads();
681 
682   /// Hoist invariant memory loads and check for required ones.
683   ///
684   /// We first identify "common" invariant loads, thus loads that are invariant
685   /// and can be hoisted. Then we check if all required invariant loads have
686   /// been identified as (common) invariant. A load is a required invariant load
687   /// if it was assumed to be invariant during SCoP detection, e.g., to assume
688   /// loop bounds to be affine or runtime alias checks to be placeable. In case
689   /// a required invariant load was not identified as (common) invariant we will
690   /// drop this SCoP. An example for both "common" as well as required invariant
691   /// loads is given below:
692   ///
693   /// for (int i = 1; i < *LB[0]; i++)
694   ///   for (int j = 1; j < *LB[1]; j++)
695   ///     A[i][j] += A[0][0] + (*V);
696   ///
697   /// Common inv. loads: V, A[0][0], LB[0], LB[1]
698   /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
699   void hoistInvariantLoads();
700 
701   /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
702   void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
703 
704   /// Check if @p MA can always be hoisted without execution context.
705   bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
706                           bool MAInvalidCtxIsEmpty,
707                           bool NonHoistableCtxIsEmpty);
708 
709   /// Return true if and only if @p LI is a required invariant load.
isRequiredInvariantLoad(LoadInst * LI)710   bool isRequiredInvariantLoad(LoadInst *LI) const {
711     return scop->getRequiredInvariantLoads().count(LI);
712   }
713 
714   /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
715   bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
716 
717   /// Return the context under which the access cannot be hoisted.
718   ///
719   /// @param Access The access to check.
720   /// @param Writes The set of all memory writes in the scop.
721   ///
722   /// @return Return the context under which the access cannot be hoisted or a
723   ///         nullptr if it cannot be hoisted at all.
724   isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
725 
726   /// Collect loads which might form a reduction chain with @p StoreMA.
727   ///
728   /// Check if the stored value for @p StoreMA is a binary operator with one or
729   /// two loads as operands. If the binary operand is commutative & associative,
730   /// used only once (by @p StoreMA) and its load operands are also used only
731   /// once, we have found a possible reduction chain. It starts at an operand
732   /// load and includes the binary operator and @p StoreMA.
733   ///
734   /// Note: We allow only one use to ensure the load and binary operator cannot
735   ///       escape this block or into any other store except @p StoreMA.
736   void collectCandidateReductionLoads(MemoryAccess *StoreMA,
737                                       SmallVectorImpl<MemoryAccess *> &Loads);
738 
739   /// Build the access relation of all memory accesses of @p Stmt.
740   void buildAccessRelations(ScopStmt &Stmt);
741 
742   /// Canonicalize arrays with base pointers from the same equivalence class.
743   ///
744   /// Some context: in our normal model we assume that each base pointer is
745   /// related to a single specific memory region, where memory regions
746   /// associated with different base pointers are disjoint. Consequently we do
747   /// not need to compute additional data dependences that model possible
748   /// overlaps of these memory regions. To verify our assumption we compute
749   /// alias checks that verify that modeled arrays indeed do not overlap. In
750   /// case an overlap is detected the runtime check fails and we fall back to
751   /// the original code.
752   ///
753   /// In case of arrays where the base pointers are know to be identical,
754   /// because they are dynamically loaded by accesses that are in the same
755   /// invariant load equivalence class, such run-time alias check would always
756   /// be false.
757   ///
758   /// This function makes sure that we do not generate consistently failing
759   /// run-time checks for code that contains distinct arrays with known
760   /// equivalent base pointers. It identifies for each invariant load
761   /// equivalence class a single canonical array and canonicalizes all memory
762   /// accesses that reference arrays that have base pointers that are known to
763   /// be equal to the base pointer of such a canonical array to this canonical
764   /// array.
765   ///
766   /// We currently do not canonicalize arrays for which certain memory accesses
767   /// have been hoisted as loop invariant.
768   void canonicalizeDynamicBasePtrs();
769 
770   /// Construct the schedule of this SCoP.
771   void buildSchedule();
772 
773   /// A loop stack element to keep track of per-loop information during
774   ///        schedule construction.
775   using LoopStackElementTy = struct LoopStackElement {
776     // The loop for which we keep information.
777     Loop *L;
778 
779     // The (possibly incomplete) schedule for this loop.
780     isl::schedule Schedule;
781 
782     // The number of basic blocks in the current loop, for which a schedule has
783     // already been constructed.
784     unsigned NumBlocksProcessed;
785 
LoopStackElementLoopStackElement786     LoopStackElement(Loop *L, isl::schedule S, unsigned NumBlocksProcessed)
787         : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
788   };
789 
790   /// The loop stack used for schedule construction.
791   ///
792   /// The loop stack keeps track of schedule information for a set of nested
793   /// loops as well as an (optional) 'nullptr' loop that models the outermost
794   /// schedule dimension. The loops in a loop stack always have a parent-child
795   /// relation where the loop at position n is the parent of the loop at
796   /// position n + 1.
797   using LoopStackTy = SmallVector<LoopStackElementTy, 4>;
798 
799   /// Construct schedule information for a given Region and add the
800   ///        derived information to @p LoopStack.
801   ///
802   /// Given a Region we derive schedule information for all RegionNodes
803   /// contained in this region ensuring that the assigned execution times
804   /// correctly model the existing control flow relations.
805   ///
806   /// @param R              The region which to process.
807   /// @param LoopStack      A stack of loops that are currently under
808   ///                       construction.
809   void buildSchedule(Region *R, LoopStackTy &LoopStack);
810 
811   /// Build Schedule for the region node @p RN and add the derived
812   ///        information to @p LoopStack.
813   ///
814   /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
815   /// schedule for this @p RN and also finalize loop schedules in case the
816   /// current @p RN completes the loop.
817   ///
818   /// In case @p RN is a not-non-affine Region, we delegate the construction to
819   /// buildSchedule(Region *R, ...).
820   ///
821   /// @param RN             The RegionNode region traversed.
822   /// @param LoopStack      A stack of loops that are currently under
823   ///                       construction.
824   void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack);
825 
826 public:
827   explicit ScopBuilder(Region *R, AssumptionCache &AC, AAResults &AA,
828                        const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
829                        ScopDetection &SD, ScalarEvolution &SE,
830                        OptimizationRemarkEmitter &ORE);
831   ScopBuilder(const ScopBuilder &) = delete;
832   ScopBuilder &operator=(const ScopBuilder &) = delete;
833   ~ScopBuilder() = default;
834 
835   /// Try to build the Polly IR of static control part on the current
836   /// SESE-Region.
837   ///
838   /// @return Give up the ownership of the scop object or static control part
839   ///         for the region
getScop()840   std::unique_ptr<Scop> getScop() { return std::move(scop); }
841 };
842 } // end namespace polly
843 
844 #endif // POLLY_SCOPBUILDER_H
845