1 //===------ ZoneAlgo.cpp ----------------------------------------*- 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 // Derive information about array elements between statements ("Zones").
11 //
12 // The algorithms here work on the scatter space - the image space of the
13 // schedule returned by Scop::getSchedule(). We call an element in that space a
14 // "timepoint". Timepoints are lexicographically ordered such that we can
15 // defined ranges in the scatter space. We use two flavors of such ranges:
16 // Timepoint sets and zones. A timepoint set is simply a subset of the scatter
17 // space and is directly stored as isl_set.
18 //
19 // Zones are used to describe the space between timepoints as open sets, i.e.
20 // they do not contain the extrema. Using isl rational sets to express these
21 // would be overkill. We also cannot store them as the integer timepoints they
22 // contain; the (nonempty) zone between 1 and 2 would be empty and
23 // indistinguishable from e.g. the zone between 3 and 4. Also, we cannot store
24 // the integer set including the extrema; the set ]1,2[ + ]3,4[ could be
25 // coalesced to ]1,3[, although we defined the range [2,3] to be not in the set.
26 // Instead, we store the "half-open" integer extrema, including the lower bound,
27 // but excluding the upper bound. Examples:
28 //
29 // * The set { [i] : 1 <= i <= 3 } represents the zone ]0,3[ (which contains the
30 //   integer points 1 and 2, but not 0 or 3)
31 //
32 // * { [1] } represents the zone ]0,1[
33 //
34 // * { [i] : i = 1 or i = 3 } represents the zone ]0,1[ + ]2,3[
35 //
36 // Therefore, an integer i in the set represents the zone ]i-1,i[, i.e. strictly
37 // speaking the integer points never belong to the zone. However, depending an
38 // the interpretation, one might want to include them. Part of the
39 // interpretation may not be known when the zone is constructed.
40 //
41 // Reads are assumed to always take place before writes, hence we can think of
42 // reads taking place at the beginning of a timepoint and writes at the end.
43 //
44 // Let's assume that the zone represents the lifetime of a variable. That is,
45 // the zone begins with a write that defines the value during its lifetime and
46 // ends with the last read of that value. In the following we consider whether a
47 // read/write at the beginning/ending of the lifetime zone should be within the
48 // zone or outside of it.
49 //
50 // * A read at the timepoint that starts the live-range loads the previous
51 //   value. Hence, exclude the timepoint starting the zone.
52 //
53 // * A write at the timepoint that starts the live-range is not defined whether
54 //   it occurs before or after the write that starts the lifetime. We do not
55 //   allow this situation to occur. Hence, we include the timepoint starting the
56 //   zone to determine whether they are conflicting.
57 //
58 // * A read at the timepoint that ends the live-range reads the same variable.
59 //   We include the timepoint at the end of the zone to include that read into
60 //   the live-range. Doing otherwise would mean that the two reads access
61 //   different values, which would mean that the value they read are both alive
62 //   at the same time but occupy the same variable.
63 //
64 // * A write at the timepoint that ends the live-range starts a new live-range.
65 //   It must not be included in the live-range of the previous definition.
66 //
67 // All combinations of reads and writes at the endpoints are possible, but most
68 // of the time only the write->read (for instance, a live-range from definition
69 // to last use) and read->write (for instance, an unused range from last use to
70 // overwrite) and combinations are interesting (half-open ranges). write->write
71 // zones might be useful as well in some context to represent
72 // output-dependencies.
73 //
74 // @see convertZoneToTimepoints
75 //
76 //
77 // The code makes use of maps and sets in many different spaces. To not loose
78 // track in which space a set or map is expected to be in, variables holding an
79 // isl reference are usually annotated in the comments. They roughly follow isl
80 // syntax for spaces, but only the tuples, not the dimensions. The tuples have a
81 // meaning as follows:
82 //
83 // * Space[] - An unspecified tuple. Used for function parameters such that the
84 //             function caller can use it for anything they like.
85 //
86 // * Domain[] - A statement instance as returned by ScopStmt::getDomain()
87 //     isl_id_get_name: Stmt_<NameOfBasicBlock>
88 //     isl_id_get_user: Pointer to ScopStmt
89 //
90 // * Element[] - An array element as in the range part of
91 //               MemoryAccess::getAccessRelation()
92 //     isl_id_get_name: MemRef_<NameOfArrayVariable>
93 //     isl_id_get_user: Pointer to ScopArrayInfo
94 //
95 // * Scatter[] - Scatter space or space of timepoints
96 //     Has no tuple id
97 //
98 // * Zone[] - Range between timepoints as described above
99 //     Has no tuple id
100 //
101 // * ValInst[] - An llvm::Value as defined at a specific timepoint.
102 //
103 //     A ValInst[] itself can be structured as one of:
104 //
105 //     * [] - An unknown value.
106 //         Always zero dimensions
107 //         Has no tuple id
108 //
109 //     * Value[] - An llvm::Value that is read-only in the SCoP, i.e. its
110 //                 runtime content does not depend on the timepoint.
111 //         Always zero dimensions
112 //         isl_id_get_name: Val_<NameOfValue>
113 //         isl_id_get_user: A pointer to an llvm::Value
114 //
115 //     * SCEV[...] - A synthesizable llvm::SCEV Expression.
116 //         In contrast to a Value[] is has at least one dimension per
117 //         SCEVAddRecExpr in the SCEV.
118 //
119 //     * [Domain[] -> Value[]] - An llvm::Value that may change during the
120 //                               Scop's execution.
121 //         The tuple itself has no id, but it wraps a map space holding a
122 //         statement instance which defines the llvm::Value as the map's domain
123 //         and llvm::Value itself as range.
124 //
125 // @see makeValInst()
126 //
127 // An annotation "{ Domain[] -> Scatter[] }" therefore means: A map from a
128 // statement instance to a timepoint, aka a schedule. There is only one scatter
129 // space, but most of the time multiple statements are processed in one set.
130 // This is why most of the time isl_union_map has to be used.
131 //
132 // The basic algorithm works as follows:
133 // At first we verify that the SCoP is compatible with this technique. For
134 // instance, two writes cannot write to the same location at the same statement
135 // instance because we cannot determine within the polyhedral model which one
136 // comes first. Once this was verified, we compute zones at which an array
137 // element is unused. This computation can fail if it takes too long. Then the
138 // main algorithm is executed. Because every store potentially trails an unused
139 // zone, we start at stores. We search for a scalar (MemoryKind::Value or
140 // MemoryKind::PHI) that we can map to the array element overwritten by the
141 // store, preferably one that is used by the store or at least the ScopStmt.
142 // When it does not conflict with the lifetime of the values in the array
143 // element, the map is applied and the unused zone updated as it is now used. We
144 // continue to try to map scalars to the array element until there are no more
145 // candidates to map. The algorithm is greedy in the sense that the first scalar
146 // not conflicting will be mapped. Other scalars processed later that could have
147 // fit the same unused zone will be rejected. As such the result depends on the
148 // processing order.
149 //
150 //===----------------------------------------------------------------------===//
151 
152 #include "polly/ZoneAlgo.h"
153 #include "polly/ScopInfo.h"
154 #include "polly/Support/GICHelper.h"
155 #include "polly/Support/ISLTools.h"
156 #include "polly/Support/VirtualInstruction.h"
157 #include "llvm/ADT/Statistic.h"
158 
159 #define DEBUG_TYPE "polly-zone"
160 
161 STATISTIC(NumIncompatibleArrays, "Number of not zone-analyzable arrays");
162 STATISTIC(NumCompatibleArrays, "Number of zone-analyzable arrays");
163 STATISTIC(NumRecursivePHIs, "Number of recursive PHIs");
164 STATISTIC(NumNormalizablePHIs, "Number of normalizable PHIs");
165 STATISTIC(NumPHINormialization, "Number of PHI executed normalizations");
166 
167 using namespace polly;
168 using namespace llvm;
169 
170 static isl::union_map computeReachingDefinition(isl::union_map Schedule,
171                                                 isl::union_map Writes,
172                                                 bool InclDef, bool InclRedef) {
173   return computeReachingWrite(Schedule, Writes, false, InclDef, InclRedef);
174 }
175 
176 /// Compute the reaching definition of a scalar.
177 ///
178 /// Compared to computeReachingDefinition, there is just one element which is
179 /// accessed and therefore only a set if instances that accesses that element is
180 /// required.
181 ///
182 /// @param Schedule  { DomainWrite[] -> Scatter[] }
183 /// @param Writes    { DomainWrite[] }
184 /// @param InclDef   Include the timepoint of the definition to the result.
185 /// @param InclRedef Include the timepoint of the overwrite into the result.
186 ///
187 /// @return { Scatter[] -> DomainWrite[] }
188 static isl::union_map computeScalarReachingDefinition(isl::union_map Schedule,
189                                                       isl::union_set Writes,
190                                                       bool InclDef,
191                                                       bool InclRedef) {
192   // { DomainWrite[] -> Element[] }
193   isl::union_map Defs = isl::union_map::from_domain(Writes);
194 
195   // { [Element[] -> Scatter[]] -> DomainWrite[] }
196   auto ReachDefs =
197       computeReachingDefinition(Schedule, Defs, InclDef, InclRedef);
198 
199   // { Scatter[] -> DomainWrite[] }
200   return ReachDefs.curry().range().unwrap();
201 }
202 
203 /// Compute the reaching definition of a scalar.
204 ///
205 /// This overload accepts only a single writing statement as an isl_map,
206 /// consequently the result also is only a single isl_map.
207 ///
208 /// @param Schedule  { DomainWrite[] -> Scatter[] }
209 /// @param Writes    { DomainWrite[] }
210 /// @param InclDef   Include the timepoint of the definition to the result.
211 /// @param InclRedef Include the timepoint of the overwrite into the result.
212 ///
213 /// @return { Scatter[] -> DomainWrite[] }
214 static isl::map computeScalarReachingDefinition(isl::union_map Schedule,
215                                                 isl::set Writes, bool InclDef,
216                                                 bool InclRedef) {
217   isl::space DomainSpace = Writes.get_space();
218   isl::space ScatterSpace = getScatterSpace(Schedule);
219 
220   //  { Scatter[] -> DomainWrite[] }
221   isl::union_map UMap = computeScalarReachingDefinition(
222       Schedule, isl::union_set(Writes), InclDef, InclRedef);
223 
224   isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomainSpace);
225   return singleton(UMap, ResultSpace);
226 }
227 
228 isl::union_map polly::makeUnknownForDomain(isl::union_set Domain) {
229   return give(isl_union_map_from_domain(Domain.take()));
230 }
231 
232 /// Create a domain-to-unknown value mapping.
233 ///
234 /// @see makeUnknownForDomain(isl::union_set)
235 ///
236 /// @param Domain { Domain[] }
237 ///
238 /// @return { Domain[] -> ValInst[] }
239 static isl::map makeUnknownForDomain(isl::set Domain) {
240   return give(isl_map_from_domain(Domain.take()));
241 }
242 
243 /// Return whether @p Map maps to an unknown value.
244 ///
245 /// @param { [] -> ValInst[] }
246 static bool isMapToUnknown(const isl::map &Map) {
247   isl::space Space = Map.get_space().range();
248   return Space.has_tuple_id(isl::dim::set).is_false() &&
249          Space.is_wrapping().is_false() && Space.dim(isl::dim::set) == 0;
250 }
251 
252 isl::union_map polly::filterKnownValInst(const isl::union_map &UMap) {
253   isl::union_map Result = isl::union_map::empty(UMap.get_space());
254   isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
255     if (!isMapToUnknown(Map))
256       Result = Result.add_map(Map);
257     return isl::stat::ok;
258   });
259   if (Success != isl::stat::ok)
260     return {};
261   return Result;
262 }
263 
264 ZoneAlgorithm::ZoneAlgorithm(const char *PassName, Scop *S, LoopInfo *LI)
265     : PassName(PassName), IslCtx(S->getSharedIslCtx()), S(S), LI(LI),
266       Schedule(S->getSchedule()) {
267   auto Domains = S->getDomains();
268 
269   Schedule =
270       give(isl_union_map_intersect_domain(Schedule.take(), Domains.take()));
271   ParamSpace = give(isl_union_map_get_space(Schedule.keep()));
272   ScatterSpace = getScatterSpace(Schedule);
273 }
274 
275 /// Check if all stores in @p Stmt store the very same value.
276 ///
277 /// This covers a special situation occurring in Polybench's
278 /// covariance/correlation (which is typical for algorithms that cover symmetric
279 /// matrices):
280 ///
281 /// for (int i = 0; i < n; i += 1)
282 /// 	for (int j = 0; j <= i; j += 1) {
283 /// 		double x = ...;
284 /// 		C[i][j] = x;
285 /// 		C[j][i] = x;
286 /// 	}
287 ///
288 /// For i == j, the same value is written twice to the same element.Double
289 /// writes to the same element are not allowed in DeLICM because its algorithm
290 /// does not see which of the writes is effective.But if its the same value
291 /// anyway, it doesn't matter.
292 ///
293 /// LLVM passes, however, cannot simplify this because the write is necessary
294 /// for i != j (unless it would add a condition for one of the writes to occur
295 /// only if i != j).
296 ///
297 /// TODO: In the future we may want to extent this to make the checks
298 ///       specific to different memory locations.
299 static bool onlySameValueWrites(ScopStmt *Stmt) {
300   Value *V = nullptr;
301 
302   for (auto *MA : *Stmt) {
303     if (!MA->isLatestArrayKind() || !MA->isMustWrite() ||
304         !MA->isOriginalArrayKind())
305       continue;
306 
307     if (!V) {
308       V = MA->getAccessValue();
309       continue;
310     }
311 
312     if (V != MA->getAccessValue())
313       return false;
314   }
315   return true;
316 }
317 
318 void ZoneAlgorithm::collectIncompatibleElts(ScopStmt *Stmt,
319                                             isl::union_set &IncompatibleElts,
320                                             isl::union_set &AllElts) {
321   auto Stores = makeEmptyUnionMap();
322   auto Loads = makeEmptyUnionMap();
323 
324   // This assumes that the MemoryKind::Array MemoryAccesses are iterated in
325   // order.
326   for (auto *MA : *Stmt) {
327     if (!MA->isOriginalArrayKind())
328       continue;
329 
330     isl::map AccRelMap = getAccessRelationFor(MA);
331     isl::union_map AccRel = AccRelMap;
332 
333     // To avoid solving any ILP problems, always add entire arrays instead of
334     // just the elements that are accessed.
335     auto ArrayElts = isl::set::universe(AccRelMap.get_space().range());
336     AllElts = AllElts.add_set(ArrayElts);
337 
338     if (MA->isRead()) {
339       // Reject load after store to same location.
340       if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep())) {
341         DEBUG(dbgs() << "Load after store of same element in same statement\n");
342         OptimizationRemarkMissed R(PassName, "LoadAfterStore",
343                                    MA->getAccessInstruction());
344         R << "load after store of same element in same statement";
345         R << " (previous stores: " << Stores;
346         R << ", loading: " << AccRel << ")";
347         S->getFunction().getContext().diagnose(R);
348 
349         IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
350       }
351 
352       Loads = give(isl_union_map_union(Loads.take(), AccRel.take()));
353 
354       continue;
355     }
356 
357     // In region statements the order is less clear, eg. the load and store
358     // might be in a boxed loop.
359     if (Stmt->isRegionStmt() &&
360         !isl_union_map_is_disjoint(Loads.keep(), AccRel.keep())) {
361       DEBUG(dbgs() << "WRITE in non-affine subregion not supported\n");
362       OptimizationRemarkMissed R(PassName, "StoreInSubregion",
363                                  MA->getAccessInstruction());
364       R << "store is in a non-affine subregion";
365       S->getFunction().getContext().diagnose(R);
366 
367       IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
368     }
369 
370     // Do not allow more than one store to the same location.
371     if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep()) &&
372         !onlySameValueWrites(Stmt)) {
373       DEBUG(dbgs() << "WRITE after WRITE to same element\n");
374       OptimizationRemarkMissed R(PassName, "StoreAfterStore",
375                                  MA->getAccessInstruction());
376       R << "store after store of same element in same statement";
377       R << " (previous stores: " << Stores;
378       R << ", storing: " << AccRel << ")";
379       S->getFunction().getContext().diagnose(R);
380 
381       IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
382     }
383 
384     Stores = give(isl_union_map_union(Stores.take(), AccRel.take()));
385   }
386 }
387 
388 void ZoneAlgorithm::addArrayReadAccess(MemoryAccess *MA) {
389   assert(MA->isLatestArrayKind());
390   assert(MA->isRead());
391   ScopStmt *Stmt = MA->getStatement();
392 
393   // { DomainRead[] -> Element[] }
394   auto AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
395   AllReads = give(isl_union_map_add_map(AllReads.take(), AccRel.copy()));
396 
397   if (LoadInst *Load = dyn_cast_or_null<LoadInst>(MA->getAccessInstruction())) {
398     // { DomainRead[] -> ValInst[] }
399     isl::map LoadValInst = makeValInst(
400         Load, Stmt, LI->getLoopFor(Load->getParent()), Stmt->isBlockStmt());
401 
402     // { DomainRead[] -> [Element[] -> DomainRead[]] }
403     isl::map IncludeElement =
404         give(isl_map_curry(isl_map_domain_map(AccRel.take())));
405 
406     // { [Element[] -> DomainRead[]] -> ValInst[] }
407     isl::map EltLoadValInst =
408         give(isl_map_apply_domain(LoadValInst.take(), IncludeElement.take()));
409 
410     AllReadValInst = give(
411         isl_union_map_add_map(AllReadValInst.take(), EltLoadValInst.take()));
412   }
413 }
414 
415 isl::union_map ZoneAlgorithm::getWrittenValue(MemoryAccess *MA,
416                                               isl::map AccRel) {
417   if (!MA->isMustWrite())
418     return {};
419 
420   Value *AccVal = MA->getAccessValue();
421   ScopStmt *Stmt = MA->getStatement();
422   Instruction *AccInst = MA->getAccessInstruction();
423 
424   // Write a value to a single element.
425   auto L = MA->isOriginalArrayKind() ? LI->getLoopFor(AccInst->getParent())
426                                      : Stmt->getSurroundingLoop();
427   if (AccVal &&
428       AccVal->getType() == MA->getLatestScopArrayInfo()->getElementType() &&
429       AccRel.is_single_valued().is_true())
430     return makeNormalizedValInst(AccVal, Stmt, L);
431 
432   // memset(_, '0', ) is equivalent to writing the null value to all touched
433   // elements. isMustWrite() ensures that all of an element's bytes are
434   // overwritten.
435   if (auto *Memset = dyn_cast<MemSetInst>(AccInst)) {
436     auto *WrittenConstant = dyn_cast<Constant>(Memset->getValue());
437     Type *Ty = MA->getLatestScopArrayInfo()->getElementType();
438     if (WrittenConstant && WrittenConstant->isZeroValue()) {
439       Constant *Zero = Constant::getNullValue(Ty);
440       return makeNormalizedValInst(Zero, Stmt, L);
441     }
442   }
443 
444   return {};
445 }
446 
447 void ZoneAlgorithm::addArrayWriteAccess(MemoryAccess *MA) {
448   assert(MA->isLatestArrayKind());
449   assert(MA->isWrite());
450   auto *Stmt = MA->getStatement();
451 
452   // { Domain[] -> Element[] }
453   isl::map AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
454 
455   if (MA->isMustWrite())
456     AllMustWrites = AllMustWrites.add_map(AccRel);
457 
458   if (MA->isMayWrite())
459     AllMayWrites = AllMayWrites.add_map(AccRel);
460 
461   // { Domain[] -> ValInst[] }
462   isl::union_map WriteValInstance = getWrittenValue(MA, AccRel);
463   if (!WriteValInstance)
464     WriteValInstance = makeUnknownForDomain(Stmt);
465 
466   // { Domain[] -> [Element[] -> Domain[]] }
467   isl::map IncludeElement = AccRel.domain_map().curry();
468 
469   // { [Element[] -> DomainWrite[]] -> ValInst[] }
470   isl::union_map EltWriteValInst =
471       WriteValInstance.apply_domain(IncludeElement);
472 
473   AllWriteValInst = AllWriteValInst.unite(EltWriteValInst);
474 }
475 
476 /// Return whether @p PHI refers (also transitively through other PHIs) to
477 /// itself.
478 ///
479 /// loop:
480 ///   %phi1 = phi [0, %preheader], [%phi1, %loop]
481 ///   br i1 %c, label %loop, label %exit
482 ///
483 /// exit:
484 ///   %phi2 = phi [%phi1, %bb]
485 ///
486 /// In this example, %phi1 is recursive, but %phi2 is not.
487 static bool isRecursivePHI(const PHINode *PHI) {
488   SmallVector<const PHINode *, 8> Worklist;
489   SmallPtrSet<const PHINode *, 8> Visited;
490   Worklist.push_back(PHI);
491 
492   while (!Worklist.empty()) {
493     const PHINode *Cur = Worklist.pop_back_val();
494 
495     if (Visited.count(Cur))
496       continue;
497     Visited.insert(Cur);
498 
499     for (const Use &Incoming : Cur->incoming_values()) {
500       Value *IncomingVal = Incoming.get();
501       auto *IncomingPHI = dyn_cast<PHINode>(IncomingVal);
502       if (!IncomingPHI)
503         continue;
504 
505       if (IncomingPHI == PHI)
506         return true;
507       Worklist.push_back(IncomingPHI);
508     }
509   }
510   return false;
511 }
512 
513 isl::union_map ZoneAlgorithm::computePerPHI(const ScopArrayInfo *SAI) {
514   // TODO: If the PHI has an incoming block from before the SCoP, it is not
515   // represented in any ScopStmt.
516 
517   auto *PHI = cast<PHINode>(SAI->getBasePtr());
518   auto It = PerPHIMaps.find(PHI);
519   if (It != PerPHIMaps.end())
520     return It->second;
521 
522   assert(SAI->isPHIKind());
523 
524   // { DomainPHIWrite[] -> Scatter[] }
525   isl::union_map PHIWriteScatter = makeEmptyUnionMap();
526 
527   // Collect all incoming block timepoints.
528   for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
529     isl::map Scatter = getScatterFor(MA);
530     PHIWriteScatter = PHIWriteScatter.add_map(Scatter);
531   }
532 
533   // { DomainPHIRead[] -> Scatter[] }
534   isl::map PHIReadScatter = getScatterFor(S->getPHIRead(SAI));
535 
536   // { DomainPHIRead[] -> Scatter[] }
537   isl::map BeforeRead = beforeScatter(PHIReadScatter, true);
538 
539   // { Scatter[] }
540   isl::set WriteTimes = singleton(PHIWriteScatter.range(), ScatterSpace);
541 
542   // { DomainPHIRead[] -> Scatter[] }
543   isl::map PHIWriteTimes = BeforeRead.intersect_range(WriteTimes);
544   isl::map LastPerPHIWrites = PHIWriteTimes.lexmax();
545 
546   // { DomainPHIRead[] -> DomainPHIWrite[] }
547   isl::union_map Result =
548       isl::union_map(LastPerPHIWrites).apply_range(PHIWriteScatter.reverse());
549   assert(!Result.is_single_valued().is_false());
550   assert(!Result.is_injective().is_false());
551 
552   PerPHIMaps.insert({PHI, Result});
553   return Result;
554 }
555 
556 isl::union_set ZoneAlgorithm::makeEmptyUnionSet() const {
557   return give(isl_union_set_empty(ParamSpace.copy()));
558 }
559 
560 isl::union_map ZoneAlgorithm::makeEmptyUnionMap() const {
561   return give(isl_union_map_empty(ParamSpace.copy()));
562 }
563 
564 void ZoneAlgorithm::collectCompatibleElts() {
565   // First find all the incompatible elements, then take the complement.
566   // We compile the list of compatible (rather than incompatible) elements so
567   // users can intersect with the list, not requiring a subtract operation. It
568   // also allows us to define a 'universe' of all elements and makes it more
569   // explicit in which array elements can be used.
570   isl::union_set AllElts = makeEmptyUnionSet();
571   isl::union_set IncompatibleElts = makeEmptyUnionSet();
572 
573   for (auto &Stmt : *S)
574     collectIncompatibleElts(&Stmt, IncompatibleElts, AllElts);
575 
576   NumIncompatibleArrays += isl_union_set_n_set(IncompatibleElts.keep());
577   CompatibleElts = AllElts.subtract(IncompatibleElts);
578   NumCompatibleArrays += isl_union_set_n_set(CompatibleElts.keep());
579 }
580 
581 isl::map ZoneAlgorithm::getScatterFor(ScopStmt *Stmt) const {
582   isl::space ResultSpace = give(isl_space_map_from_domain_and_range(
583       Stmt->getDomainSpace().release(), ScatterSpace.copy()));
584   return give(isl_union_map_extract_map(Schedule.keep(), ResultSpace.take()));
585 }
586 
587 isl::map ZoneAlgorithm::getScatterFor(MemoryAccess *MA) const {
588   return getScatterFor(MA->getStatement());
589 }
590 
591 isl::union_map ZoneAlgorithm::getScatterFor(isl::union_set Domain) const {
592   return give(isl_union_map_intersect_domain(Schedule.copy(), Domain.take()));
593 }
594 
595 isl::map ZoneAlgorithm::getScatterFor(isl::set Domain) const {
596   auto ResultSpace = give(isl_space_map_from_domain_and_range(
597       isl_set_get_space(Domain.keep()), ScatterSpace.copy()));
598   auto UDomain = give(isl_union_set_from_set(Domain.copy()));
599   auto UResult = getScatterFor(std::move(UDomain));
600   auto Result = singleton(std::move(UResult), std::move(ResultSpace));
601   assert(!Result || isl_set_is_equal(give(isl_map_domain(Result.copy())).keep(),
602                                      Domain.keep()) == isl_bool_true);
603   return Result;
604 }
605 
606 isl::set ZoneAlgorithm::getDomainFor(ScopStmt *Stmt) const {
607   return Stmt->getDomain().remove_redundancies();
608 }
609 
610 isl::set ZoneAlgorithm::getDomainFor(MemoryAccess *MA) const {
611   return getDomainFor(MA->getStatement());
612 }
613 
614 isl::map ZoneAlgorithm::getAccessRelationFor(MemoryAccess *MA) const {
615   auto Domain = getDomainFor(MA);
616   auto AccRel = MA->getLatestAccessRelation();
617   return give(isl_map_intersect_domain(AccRel.take(), Domain.take()));
618 }
619 
620 isl::map ZoneAlgorithm::getScalarReachingDefinition(ScopStmt *Stmt) {
621   auto &Result = ScalarReachDefZone[Stmt];
622   if (Result)
623     return Result;
624 
625   auto Domain = getDomainFor(Stmt);
626   Result = computeScalarReachingDefinition(Schedule, Domain, false, true);
627   simplify(Result);
628 
629   return Result;
630 }
631 
632 isl::map ZoneAlgorithm::getScalarReachingDefinition(isl::set DomainDef) {
633   auto DomId = give(isl_set_get_tuple_id(DomainDef.keep()));
634   auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(DomId.keep()));
635 
636   auto StmtResult = getScalarReachingDefinition(Stmt);
637 
638   return give(isl_map_intersect_range(StmtResult.take(), DomainDef.take()));
639 }
640 
641 isl::map ZoneAlgorithm::makeUnknownForDomain(ScopStmt *Stmt) const {
642   return ::makeUnknownForDomain(getDomainFor(Stmt));
643 }
644 
645 isl::id ZoneAlgorithm::makeValueId(Value *V) {
646   if (!V)
647     return nullptr;
648 
649   auto &Id = ValueIds[V];
650   if (Id.is_null()) {
651     auto Name = getIslCompatibleName("Val_", V, ValueIds.size() - 1,
652                                      std::string(), UseInstructionNames);
653     Id = give(isl_id_alloc(IslCtx.get(), Name.c_str(), V));
654   }
655   return Id;
656 }
657 
658 isl::space ZoneAlgorithm::makeValueSpace(Value *V) {
659   auto Result = give(isl_space_set_from_params(ParamSpace.copy()));
660   return give(isl_space_set_tuple_id(Result.take(), isl_dim_set,
661                                      makeValueId(V).take()));
662 }
663 
664 isl::set ZoneAlgorithm::makeValueSet(Value *V) {
665   auto Space = makeValueSpace(V);
666   return give(isl_set_universe(Space.take()));
667 }
668 
669 isl::map ZoneAlgorithm::makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
670                                     bool IsCertain) {
671   // If the definition/write is conditional, the value at the location could
672   // be either the written value or the old value. Since we cannot know which
673   // one, consider the value to be unknown.
674   if (!IsCertain)
675     return makeUnknownForDomain(UserStmt);
676 
677   auto DomainUse = getDomainFor(UserStmt);
678   auto VUse = VirtualUse::create(S, UserStmt, Scope, Val, true);
679   switch (VUse.getKind()) {
680   case VirtualUse::Constant:
681   case VirtualUse::Block:
682   case VirtualUse::Hoisted:
683   case VirtualUse::ReadOnly: {
684     // The definition does not depend on the statement which uses it.
685     auto ValSet = makeValueSet(Val);
686     return give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
687   }
688 
689   case VirtualUse::Synthesizable: {
690     auto *ScevExpr = VUse.getScevExpr();
691     auto UseDomainSpace = give(isl_set_get_space(DomainUse.keep()));
692 
693     // Construct the SCEV space.
694     // TODO: Add only the induction variables referenced in SCEVAddRecExpr
695     // expressions, not just all of them.
696     auto ScevId = give(isl_id_alloc(UseDomainSpace.get_ctx().get(), nullptr,
697                                     const_cast<SCEV *>(ScevExpr)));
698     auto ScevSpace =
699         give(isl_space_drop_dims(UseDomainSpace.copy(), isl_dim_set, 0, 0));
700     ScevSpace = give(
701         isl_space_set_tuple_id(ScevSpace.take(), isl_dim_set, ScevId.copy()));
702 
703     // { DomainUse[] -> ScevExpr[] }
704     auto ValInst = give(isl_map_identity(isl_space_map_from_domain_and_range(
705         UseDomainSpace.copy(), ScevSpace.copy())));
706     return ValInst;
707   }
708 
709   case VirtualUse::Intra: {
710     // Definition and use is in the same statement. We do not need to compute
711     // a reaching definition.
712 
713     // { llvm::Value }
714     auto ValSet = makeValueSet(Val);
715 
716     // {  UserDomain[] -> llvm::Value }
717     auto ValInstSet =
718         give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
719 
720     // { UserDomain[] -> [UserDomain[] - >llvm::Value] }
721     auto Result = give(isl_map_reverse(isl_map_domain_map(ValInstSet.take())));
722     simplify(Result);
723     return Result;
724   }
725 
726   case VirtualUse::Inter: {
727     // The value is defined in a different statement.
728 
729     auto *Inst = cast<Instruction>(Val);
730     auto *ValStmt = S->getStmtFor(Inst);
731 
732     // If the llvm::Value is defined in a removed Stmt, we cannot derive its
733     // domain. We could use an arbitrary statement, but this could result in
734     // different ValInst[] for the same llvm::Value.
735     if (!ValStmt)
736       return ::makeUnknownForDomain(DomainUse);
737 
738     // { DomainDef[] }
739     auto DomainDef = getDomainFor(ValStmt);
740 
741     // { Scatter[] -> DomainDef[] }
742     auto ReachDef = getScalarReachingDefinition(DomainDef);
743 
744     // { DomainUse[] -> Scatter[] }
745     auto UserSched = getScatterFor(DomainUse);
746 
747     // { DomainUse[] -> DomainDef[] }
748     auto UsedInstance =
749         give(isl_map_apply_range(UserSched.take(), ReachDef.take()));
750 
751     // { llvm::Value }
752     auto ValSet = makeValueSet(Val);
753 
754     // { DomainUse[] -> llvm::Value[] }
755     auto ValInstSet =
756         give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
757 
758     // { DomainUse[] -> [DomainDef[] -> llvm::Value]  }
759     auto Result =
760         give(isl_map_range_product(UsedInstance.take(), ValInstSet.take()));
761 
762     simplify(Result);
763     return Result;
764   }
765   }
766   llvm_unreachable("Unhandled use type");
767 }
768 
769 /// Remove all computed PHIs out of @p Input and replace by their incoming
770 /// value.
771 ///
772 /// @param Input        { [] -> ValInst[] }
773 /// @param ComputedPHIs Set of PHIs that are replaced. Its ValInst must appear
774 ///                     on the LHS of @p NormalizeMap.
775 /// @param NormalizeMap { ValInst[] -> ValInst[] }
776 static isl::union_map normalizeValInst(isl::union_map Input,
777                                        const DenseSet<PHINode *> &ComputedPHIs,
778                                        isl::union_map NormalizeMap) {
779   isl::union_map Result = isl::union_map::empty(Input.get_space());
780   Input.foreach_map(
781       [&Result, &ComputedPHIs, &NormalizeMap](isl::map Map) -> isl::stat {
782         isl::space Space = Map.get_space();
783         isl::space RangeSpace = Space.range();
784 
785         // Instructions within the SCoP are always wrapped. Non-wrapped tuples
786         // are therefore invariant in the SCoP and don't need normalization.
787         if (!RangeSpace.is_wrapping()) {
788           Result = Result.add_map(Map);
789           return isl::stat::ok;
790         }
791 
792         auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
793             RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
794 
795         // If no normalization is necessary, then the ValInst stands for itself.
796         if (!ComputedPHIs.count(PHI)) {
797           Result = Result.add_map(Map);
798           return isl::stat::ok;
799         }
800 
801         // Otherwise, apply the normalization.
802         isl::union_map Mapped = isl::union_map(Map).apply_range(NormalizeMap);
803         Result = Result.unite(Mapped);
804         NumPHINormialization++;
805         return isl::stat::ok;
806       });
807   return Result;
808 }
809 
810 isl::union_map ZoneAlgorithm::makeNormalizedValInst(llvm::Value *Val,
811                                                     ScopStmt *UserStmt,
812                                                     llvm::Loop *Scope,
813                                                     bool IsCertain) {
814   isl::map ValInst = makeValInst(Val, UserStmt, Scope, IsCertain);
815   isl::union_map Normalized =
816       normalizeValInst(ValInst, ComputedPHIs, NormalizeMap);
817   return Normalized;
818 }
819 
820 bool ZoneAlgorithm::isCompatibleAccess(MemoryAccess *MA) {
821   if (!MA)
822     return false;
823   if (!MA->isLatestArrayKind())
824     return false;
825   Instruction *AccInst = MA->getAccessInstruction();
826   return isa<StoreInst>(AccInst) || isa<LoadInst>(AccInst);
827 }
828 
829 bool ZoneAlgorithm::isNormalizable(MemoryAccess *MA) {
830   assert(MA->isRead());
831 
832   // Exclude ExitPHIs, we are assuming that a normalizable PHI has a READ
833   // MemoryAccess.
834   if (!MA->isOriginalPHIKind())
835     return false;
836 
837   // Exclude recursive PHIs, normalizing them would require a transitive
838   // closure.
839   auto *PHI = cast<PHINode>(MA->getAccessInstruction());
840   if (RecursivePHIs.count(PHI))
841     return false;
842 
843   // Ensure that each incoming value can be represented by a ValInst[].
844   // We do represent values from statements associated to multiple incoming
845   // value by the PHI itself, but we do not handle this case yet (especially
846   // isNormalized()) when normalizing.
847   const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
848   auto Incomings = S->getPHIIncomings(SAI);
849   for (MemoryAccess *Incoming : Incomings) {
850     if (Incoming->getIncoming().size() != 1)
851       return false;
852   }
853 
854   return true;
855 }
856 
857 bool ZoneAlgorithm::isNormalized(isl::map Map) {
858   isl::space Space = Map.get_space();
859   isl::space RangeSpace = Space.range();
860 
861   if (!RangeSpace.is_wrapping())
862     return true;
863 
864   auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
865       RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
866   if (!PHI)
867     return true;
868 
869   auto *IncomingStmt = static_cast<ScopStmt *>(
870       RangeSpace.unwrap().get_tuple_id(isl::dim::in).get_user());
871   MemoryAccess *PHIRead = IncomingStmt->lookupPHIReadOf(PHI);
872   if (!isNormalizable(PHIRead))
873     return true;
874 
875   return false;
876 }
877 
878 bool ZoneAlgorithm::isNormalized(isl::union_map UMap) {
879   auto Result = UMap.foreach_map([this](isl::map Map) -> isl::stat {
880     if (isNormalized(Map))
881       return isl::stat::ok;
882     return isl::stat::error;
883   });
884   return Result == isl::stat::ok;
885 }
886 
887 void ZoneAlgorithm::computeCommon() {
888   AllReads = makeEmptyUnionMap();
889   AllMayWrites = makeEmptyUnionMap();
890   AllMustWrites = makeEmptyUnionMap();
891   AllWriteValInst = makeEmptyUnionMap();
892   AllReadValInst = makeEmptyUnionMap();
893 
894   // Default to empty, i.e. no normalization/replacement is taking place. Call
895   // computeNormalizedPHIs() to initialize.
896   NormalizeMap = makeEmptyUnionMap();
897   ComputedPHIs.clear();
898 
899   for (auto &Stmt : *S) {
900     for (auto *MA : Stmt) {
901       if (!MA->isLatestArrayKind())
902         continue;
903 
904       if (MA->isRead())
905         addArrayReadAccess(MA);
906 
907       if (MA->isWrite())
908         addArrayWriteAccess(MA);
909     }
910   }
911 
912   // { DomainWrite[] -> Element[] }
913   AllWrites =
914       give(isl_union_map_union(AllMustWrites.copy(), AllMayWrites.copy()));
915 
916   // { [Element[] -> Zone[]] -> DomainWrite[] }
917   WriteReachDefZone =
918       computeReachingDefinition(Schedule, AllWrites, false, true);
919   simplify(WriteReachDefZone);
920 }
921 
922 void ZoneAlgorithm::computeNormalizedPHIs() {
923   // Determine which PHIs can reference themselves. They are excluded from
924   // normalization to avoid problems with transitive closures.
925   for (ScopStmt &Stmt : *S) {
926     for (MemoryAccess *MA : Stmt) {
927       if (!MA->isPHIKind())
928         continue;
929       if (!MA->isRead())
930         continue;
931 
932       // TODO: Can be more efficient since isRecursivePHI can theoretically
933       // determine recursiveness for multiple values and/or cache results.
934       auto *PHI = cast<PHINode>(MA->getAccessInstruction());
935       if (isRecursivePHI(PHI)) {
936         NumRecursivePHIs++;
937         RecursivePHIs.insert(PHI);
938       }
939     }
940   }
941 
942   // { PHIValInst[] -> IncomingValInst[] }
943   isl::union_map AllPHIMaps = makeEmptyUnionMap();
944 
945   // Discover new PHIs and try to normalize them.
946   DenseSet<PHINode *> AllPHIs;
947   for (ScopStmt &Stmt : *S) {
948     for (MemoryAccess *MA : Stmt) {
949       if (!MA->isOriginalPHIKind())
950         continue;
951       if (!MA->isRead())
952         continue;
953       if (!isNormalizable(MA))
954         continue;
955 
956       auto *PHI = cast<PHINode>(MA->getAccessInstruction());
957       const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
958 
959       // { PHIDomain[] -> PHIValInst[] }
960       isl::map PHIValInst = makeValInst(PHI, &Stmt, Stmt.getSurroundingLoop());
961 
962       // { IncomingDomain[] -> IncomingValInst[] }
963       isl::union_map IncomingValInsts = makeEmptyUnionMap();
964 
965       // Get all incoming values.
966       for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
967         ScopStmt *IncomingStmt = MA->getStatement();
968 
969         auto Incoming = MA->getIncoming();
970         assert(Incoming.size() == 1 && "The incoming value must be "
971                                        "representable by something else than "
972                                        "the PHI itself");
973         Value *IncomingVal = Incoming[0].second;
974 
975         // { IncomingDomain[] -> IncomingValInst[] }
976         isl::map IncomingValInst = makeValInst(
977             IncomingVal, IncomingStmt, IncomingStmt->getSurroundingLoop());
978 
979         IncomingValInsts = IncomingValInsts.add_map(IncomingValInst);
980       }
981 
982       // Determine which instance of the PHI statement corresponds to which
983       // incoming value.
984       // { PHIDomain[] -> IncomingDomain[] }
985       isl::union_map PerPHI = computePerPHI(SAI);
986 
987       // { PHIValInst[] -> IncomingValInst[] }
988       isl::union_map PHIMap =
989           PerPHI.apply_domain(PHIValInst).apply_range(IncomingValInsts);
990       assert(!PHIMap.is_single_valued().is_false());
991 
992       // Resolve transitiveness: The incoming value of the newly discovered PHI
993       // may reference a previously normalized PHI. At the same time, already
994       // normalized PHIs might be normalized to the new PHI. At the end, none of
995       // the PHIs may appear on the right-hand-side of the normalization map.
996       PHIMap = normalizeValInst(PHIMap, AllPHIs, AllPHIMaps);
997       AllPHIs.insert(PHI);
998       AllPHIMaps = normalizeValInst(AllPHIMaps, AllPHIs, PHIMap);
999 
1000       AllPHIMaps = AllPHIMaps.unite(PHIMap);
1001       NumNormalizablePHIs++;
1002     }
1003   }
1004   simplify(AllPHIMaps);
1005 
1006   // Apply the normalization.
1007   ComputedPHIs = AllPHIs;
1008   NormalizeMap = AllPHIMaps;
1009 
1010   assert(!NormalizeMap || isNormalized(NormalizeMap));
1011 }
1012 
1013 void ZoneAlgorithm::printAccesses(llvm::raw_ostream &OS, int Indent) const {
1014   OS.indent(Indent) << "After accesses {\n";
1015   for (auto &Stmt : *S) {
1016     OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
1017     for (auto *MA : Stmt)
1018       MA->print(OS);
1019   }
1020   OS.indent(Indent) << "}\n";
1021 }
1022 
1023 isl::union_map ZoneAlgorithm::computeKnownFromMustWrites() const {
1024   // { [Element[] -> Zone[]] -> [Element[] -> DomainWrite[]] }
1025   isl::union_map EltReachdDef = distributeDomain(WriteReachDefZone.curry());
1026 
1027   // { [Element[] -> DomainWrite[]] -> ValInst[] }
1028   isl::union_map AllKnownWriteValInst = filterKnownValInst(AllWriteValInst);
1029 
1030   // { [Element[] -> Zone[]] -> ValInst[] }
1031   return EltReachdDef.apply_range(AllKnownWriteValInst);
1032 }
1033 
1034 isl::union_map ZoneAlgorithm::computeKnownFromLoad() const {
1035   // { Element[] }
1036   isl::union_set AllAccessedElts = AllReads.range().unite(AllWrites.range());
1037 
1038   // { Element[] -> Scatter[] }
1039   isl::union_map EltZoneUniverse = isl::union_map::from_domain_and_range(
1040       AllAccessedElts, isl::set::universe(ScatterSpace));
1041 
1042   // This assumes there are no "holes" in
1043   // isl_union_map_domain(WriteReachDefZone); alternatively, compute the zone
1044   // before the first write or that are not written at all.
1045   // { Element[] -> Scatter[] }
1046   isl::union_set NonReachDef =
1047       EltZoneUniverse.wrap().subtract(WriteReachDefZone.domain());
1048 
1049   // { [Element[] -> Zone[]] -> ReachDefId[] }
1050   isl::union_map DefZone =
1051       WriteReachDefZone.unite(isl::union_map::from_domain(NonReachDef));
1052 
1053   // { [Element[] -> Scatter[]] -> Element[] }
1054   isl::union_map EltZoneElt = EltZoneUniverse.domain_map();
1055 
1056   // { [Element[] -> Zone[]] -> [Element[] -> ReachDefId[]] }
1057   isl::union_map DefZoneEltDefId = EltZoneElt.range_product(DefZone);
1058 
1059   // { Element[] -> [Zone[] -> ReachDefId[]] }
1060   isl::union_map EltDefZone = DefZone.curry();
1061 
1062   // { [Element[] -> Zone[] -> [Element[] -> ReachDefId[]] }
1063   isl::union_map EltZoneEltDefid = distributeDomain(EltDefZone);
1064 
1065   // { [Element[] -> Scatter[]] -> DomainRead[] }
1066   isl::union_map Reads = AllReads.range_product(Schedule).reverse();
1067 
1068   // { [Element[] -> Scatter[]] -> [Element[] -> DomainRead[]] }
1069   isl::union_map ReadsElt = EltZoneElt.range_product(Reads);
1070 
1071   // { [Element[] -> Scatter[]] -> ValInst[] }
1072   isl::union_map ScatterKnown = ReadsElt.apply_range(AllReadValInst);
1073 
1074   // { [Element[] -> ReachDefId[]] -> ValInst[] }
1075   isl::union_map DefidKnown =
1076       DefZoneEltDefId.apply_domain(ScatterKnown).reverse();
1077 
1078   // { [Element[] -> Zone[]] -> ValInst[] }
1079   return DefZoneEltDefId.apply_range(DefidKnown);
1080 }
1081 
1082 isl::union_map ZoneAlgorithm::computeKnown(bool FromWrite,
1083                                            bool FromRead) const {
1084   isl::union_map Result = makeEmptyUnionMap();
1085 
1086   if (FromWrite)
1087     Result = Result.unite(computeKnownFromMustWrites());
1088 
1089   if (FromRead)
1090     Result = Result.unite(computeKnownFromLoad());
1091 
1092   simplify(Result);
1093   return Result;
1094 }
1095