1 //===------ ISLTools.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 // Tools, utilities, helpers and extensions useful in conjunction with the
11 // Integer Set Library (isl).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/Support/ISLTools.h"
16 #include "llvm/ADT/StringRef.h"
17 
18 using namespace polly;
19 
20 namespace {
21 /// Create a map that shifts one dimension by an offset.
22 ///
23 /// Example:
24 /// makeShiftDimAff({ [i0, i1] -> [o0, o1] }, 1, -2)
25 ///   = { [i0, i1] -> [i0, i1 - 1] }
26 ///
27 /// @param Space  The map space of the result. Must have equal number of in- and
28 ///               out-dimensions.
29 /// @param Pos    Position to shift.
30 /// @param Amount Value added to the shifted dimension.
31 ///
32 /// @return An isl_multi_aff for the map with this shifted dimension.
33 isl::multi_aff makeShiftDimAff(isl::space Space, int Pos, int Amount) {
34   auto Identity = isl::multi_aff::identity(Space);
35   if (Amount == 0)
36     return Identity;
37   auto ShiftAff = Identity.get_aff(Pos);
38   ShiftAff = ShiftAff.set_constant_si(Amount);
39   return Identity.set_aff(Pos, ShiftAff);
40 }
41 
42 /// Construct a map that swaps two nested tuples.
43 ///
44 /// @param FromSpace1 { Space1[] }
45 /// @param FromSpace2 { Space2[] }
46 ///
47 /// @return { [Space1[] -> Space2[]] -> [Space2[] -> Space1[]] }
48 isl::basic_map makeTupleSwapBasicMap(isl::space FromSpace1,
49                                      isl::space FromSpace2) {
50   assert(FromSpace1.is_set());
51   assert(FromSpace2.is_set());
52 
53   unsigned Dims1 = FromSpace1.dim(isl::dim::set);
54   unsigned Dims2 = FromSpace2.dim(isl::dim::set);
55 
56   isl::space FromSpace =
57       FromSpace1.map_from_domain_and_range(FromSpace2).wrap();
58   isl::space ToSpace = FromSpace2.map_from_domain_and_range(FromSpace1).wrap();
59   isl::space MapSpace = FromSpace.map_from_domain_and_range(ToSpace);
60 
61   isl::basic_map Result = isl::basic_map::universe(MapSpace);
62   for (auto i = Dims1 - Dims1; i < Dims1; i += 1)
63     Result = Result.equate(isl::dim::in, i, isl::dim::out, Dims2 + i);
64   for (auto i = Dims2 - Dims2; i < Dims2; i += 1) {
65     Result = Result.equate(isl::dim::in, Dims1 + i, isl::dim::out, i);
66   }
67 
68   return Result;
69 }
70 
71 /// Like makeTupleSwapBasicMap(isl::space,isl::space), but returns
72 /// an isl_map.
73 isl::map makeTupleSwapMap(isl::space FromSpace1, isl::space FromSpace2) {
74   isl::basic_map BMapResult = makeTupleSwapBasicMap(FromSpace1, FromSpace2);
75   return isl::map(BMapResult);
76 }
77 } // anonymous namespace
78 
79 isl::map polly::beforeScatter(isl::map Map, bool Strict) {
80   isl::space RangeSpace = Map.get_space().range();
81   isl::map ScatterRel =
82       Strict ? isl::map::lex_gt(RangeSpace) : isl::map::lex_ge(RangeSpace);
83   return Map.apply_range(ScatterRel);
84 }
85 
86 isl::union_map polly::beforeScatter(isl::union_map UMap, bool Strict) {
87   isl::union_map Result = isl::union_map::empty(UMap.get_space());
88   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
89     isl::map After = beforeScatter(Map, Strict);
90     Result = Result.add_map(After);
91     return isl::stat::ok;
92   });
93   return Result;
94 }
95 
96 isl::map polly::afterScatter(isl::map Map, bool Strict) {
97   isl::space RangeSpace = Map.get_space().range();
98   isl::map ScatterRel =
99       Strict ? isl::map::lex_lt(RangeSpace) : isl::map::lex_le(RangeSpace);
100   return Map.apply_range(ScatterRel);
101 }
102 
103 isl::union_map polly::afterScatter(const isl::union_map &UMap, bool Strict) {
104   isl::union_map Result = isl::union_map::empty(UMap.get_space());
105   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
106     isl::map After = afterScatter(Map, Strict);
107     Result = Result.add_map(After);
108     return isl::stat::ok;
109   });
110   return Result;
111 }
112 
113 isl::map polly::betweenScatter(isl::map From, isl::map To, bool InclFrom,
114                                bool InclTo) {
115   isl::map AfterFrom = afterScatter(From, !InclFrom);
116   isl::map BeforeTo = beforeScatter(To, !InclTo);
117 
118   return AfterFrom.intersect(BeforeTo);
119 }
120 
121 isl::union_map polly::betweenScatter(isl::union_map From, isl::union_map To,
122                                      bool InclFrom, bool InclTo) {
123   isl::union_map AfterFrom = afterScatter(From, !InclFrom);
124   isl::union_map BeforeTo = beforeScatter(To, !InclTo);
125 
126   return AfterFrom.intersect(BeforeTo);
127 }
128 
129 isl::map polly::singleton(isl::union_map UMap, isl::space ExpectedSpace) {
130   if (!UMap)
131     return nullptr;
132 
133   if (isl_union_map_n_map(UMap.get()) == 0)
134     return isl::map::empty(ExpectedSpace);
135 
136   isl::map Result = isl::map::from_union_map(UMap);
137   assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
138 
139   return Result;
140 }
141 
142 isl::set polly::singleton(isl::union_set USet, isl::space ExpectedSpace) {
143   if (!USet)
144     return nullptr;
145 
146   if (isl_union_set_n_set(USet.get()) == 0)
147     return isl::set::empty(ExpectedSpace);
148 
149   isl::set Result(USet);
150   assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
151 
152   return Result;
153 }
154 
155 unsigned polly::getNumScatterDims(const isl::union_map &Schedule) {
156   unsigned Dims = 0;
157   Schedule.foreach_map([&Dims](isl::map Map) -> isl::stat {
158     Dims = std::max(Dims, Map.dim(isl::dim::out));
159     return isl::stat::ok;
160   });
161   return Dims;
162 }
163 
164 isl::space polly::getScatterSpace(const isl::union_map &Schedule) {
165   if (!Schedule)
166     return nullptr;
167   unsigned Dims = getNumScatterDims(Schedule);
168   isl::space ScatterSpace = Schedule.get_space().set_from_params();
169   return ScatterSpace.add_dims(isl::dim::set, Dims);
170 }
171 
172 isl::union_map polly::makeIdentityMap(const isl::union_set &USet,
173                                       bool RestrictDomain) {
174   isl::union_map Result = isl::union_map::empty(USet.get_space());
175   USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
176     isl::map IdentityMap = isl::map::identity(Set.get_space().map_from_set());
177     if (RestrictDomain)
178       IdentityMap = IdentityMap.intersect_domain(Set);
179     Result = Result.add_map(IdentityMap);
180     return isl::stat::ok;
181   });
182   return Result;
183 }
184 
185 isl::map polly::reverseDomain(isl::map Map) {
186   isl::space DomSpace = Map.get_space().domain().unwrap();
187   isl::space Space1 = DomSpace.domain();
188   isl::space Space2 = DomSpace.range();
189   isl::map Swap = makeTupleSwapMap(Space1, Space2);
190   return Map.apply_domain(Swap);
191 }
192 
193 isl::union_map polly::reverseDomain(const isl::union_map &UMap) {
194   isl::union_map Result = isl::union_map::empty(UMap.get_space());
195   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
196     auto Reversed = reverseDomain(std::move(Map));
197     Result = Result.add_map(Reversed);
198     return isl::stat::ok;
199   });
200   return Result;
201 }
202 
203 isl::set polly::shiftDim(isl::set Set, int Pos, int Amount) {
204   int NumDims = Set.dim(isl::dim::set);
205   if (Pos < 0)
206     Pos = NumDims + Pos;
207   assert(Pos < NumDims && "Dimension index must be in range");
208   isl::space Space = Set.get_space();
209   Space = Space.map_from_domain_and_range(Space);
210   isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
211   isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
212   return Set.apply(TranslatorMap);
213 }
214 
215 isl::union_set polly::shiftDim(isl::union_set USet, int Pos, int Amount) {
216   isl::union_set Result = isl::union_set::empty(USet.get_space());
217   USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
218     isl::set Shifted = shiftDim(Set, Pos, Amount);
219     Result = Result.add_set(Shifted);
220     return isl::stat::ok;
221   });
222   return Result;
223 }
224 
225 isl::map polly::shiftDim(isl::map Map, isl::dim Dim, int Pos, int Amount) {
226   int NumDims = Map.dim(Dim);
227   if (Pos < 0)
228     Pos = NumDims + Pos;
229   assert(Pos < NumDims && "Dimension index must be in range");
230   isl::space Space = Map.get_space();
231   switch (Dim) {
232   case isl::dim::in:
233     Space = Space.domain();
234     break;
235   case isl::dim::out:
236     Space = Space.range();
237     break;
238   default:
239     llvm_unreachable("Unsupported value for 'dim'");
240   }
241   Space = Space.map_from_domain_and_range(Space);
242   isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
243   isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
244   switch (Dim) {
245   case isl::dim::in:
246     return Map.apply_domain(TranslatorMap);
247   case isl::dim::out:
248     return Map.apply_range(TranslatorMap);
249   default:
250     llvm_unreachable("Unsupported value for 'dim'");
251   }
252 }
253 
254 isl::union_map polly::shiftDim(isl::union_map UMap, isl::dim Dim, int Pos,
255                                int Amount) {
256   isl::union_map Result = isl::union_map::empty(UMap.get_space());
257 
258   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
259     isl::map Shifted = shiftDim(Map, Dim, Pos, Amount);
260     Result = Result.add_map(Shifted);
261     return isl::stat::ok;
262   });
263   return Result;
264 }
265 
266 void polly::simplify(isl::set &Set) {
267   Set = isl::manage(isl_set_compute_divs(Set.copy()));
268   Set = Set.detect_equalities();
269   Set = Set.coalesce();
270 }
271 
272 void polly::simplify(isl::union_set &USet) {
273   USet = isl::manage(isl_union_set_compute_divs(USet.copy()));
274   USet = USet.detect_equalities();
275   USet = USet.coalesce();
276 }
277 
278 void polly::simplify(isl::map &Map) {
279   Map = isl::manage(isl_map_compute_divs(Map.copy()));
280   Map = Map.detect_equalities();
281   Map = Map.coalesce();
282 }
283 
284 void polly::simplify(isl::union_map &UMap) {
285   UMap = isl::manage(isl_union_map_compute_divs(UMap.copy()));
286   UMap = UMap.detect_equalities();
287   UMap = UMap.coalesce();
288 }
289 
290 isl::union_map polly::computeReachingWrite(isl::union_map Schedule,
291                                            isl::union_map Writes, bool Reverse,
292                                            bool InclPrevDef, bool InclNextDef) {
293 
294   // { Scatter[] }
295   isl::space ScatterSpace = getScatterSpace(Schedule);
296 
297   // { ScatterRead[] -> ScatterWrite[] }
298   isl::map Relation;
299   if (Reverse)
300     Relation = InclPrevDef ? isl::map::lex_lt(ScatterSpace)
301                            : isl::map::lex_le(ScatterSpace);
302   else
303     Relation = InclNextDef ? isl::map::lex_gt(ScatterSpace)
304                            : isl::map::lex_ge(ScatterSpace);
305 
306   // { ScatterWrite[] -> [ScatterRead[] -> ScatterWrite[]] }
307   isl::map RelationMap = Relation.range_map().reverse();
308 
309   // { Element[] -> ScatterWrite[] }
310   isl::union_map WriteAction = Schedule.apply_domain(Writes);
311 
312   // { ScatterWrite[] -> Element[] }
313   isl::union_map WriteActionRev = WriteAction.reverse();
314 
315   // { Element[] -> [ScatterUse[] -> ScatterWrite[]] }
316   isl::union_map DefSchedRelation =
317       isl::union_map(RelationMap).apply_domain(WriteActionRev);
318 
319   // For each element, at every point in time, map to the times of previous
320   // definitions. { [Element[] -> ScatterRead[]] -> ScatterWrite[] }
321   isl::union_map ReachableWrites = DefSchedRelation.uncurry();
322   if (Reverse)
323     ReachableWrites = ReachableWrites.lexmin();
324   else
325     ReachableWrites = ReachableWrites.lexmax();
326 
327   // { [Element[] -> ScatterWrite[]] -> ScatterWrite[] }
328   isl::union_map SelfUse = WriteAction.range_map();
329 
330   if (InclPrevDef && InclNextDef) {
331     // Add the Def itself to the solution.
332     ReachableWrites = ReachableWrites.unite(SelfUse).coalesce();
333   } else if (!InclPrevDef && !InclNextDef) {
334     // Remove Def itself from the solution.
335     ReachableWrites = ReachableWrites.subtract(SelfUse);
336   }
337 
338   // { [Element[] -> ScatterRead[]] -> Domain[] }
339   return ReachableWrites.apply_range(Schedule.reverse());
340 }
341 
342 isl::union_map
343 polly::computeArrayUnused(isl::union_map Schedule, isl::union_map Writes,
344                           isl::union_map Reads, bool ReadEltInSameInst,
345                           bool IncludeLastRead, bool IncludeWrite) {
346   // { Element[] -> Scatter[] }
347   isl::union_map ReadActions = Schedule.apply_domain(Reads);
348   isl::union_map WriteActions = Schedule.apply_domain(Writes);
349 
350   // { [Element[] -> DomainWrite[]] -> Scatter[] }
351   isl::union_map EltDomWrites =
352       Writes.reverse().range_map().apply_range(Schedule);
353 
354   // { [Element[] -> Scatter[]] -> DomainWrite[] }
355   isl::union_map ReachingOverwrite = computeReachingWrite(
356       Schedule, Writes, true, ReadEltInSameInst, !ReadEltInSameInst);
357 
358   // { [Element[] -> Scatter[]] -> DomainWrite[] }
359   isl::union_map ReadsOverwritten =
360       ReachingOverwrite.intersect_domain(ReadActions.wrap());
361 
362   // { [Element[] -> DomainWrite[]] -> Scatter[] }
363   isl::union_map ReadsOverwrittenRotated =
364       reverseDomain(ReadsOverwritten).curry().reverse();
365   isl::union_map LastOverwrittenRead = ReadsOverwrittenRotated.lexmax();
366 
367   // { [Element[] -> DomainWrite[]] -> Scatter[] }
368   isl::union_map BetweenLastReadOverwrite = betweenScatter(
369       LastOverwrittenRead, EltDomWrites, IncludeLastRead, IncludeWrite);
370 
371   // { [Element[] -> Scatter[]] -> DomainWrite[] }
372   isl::union_map ReachingOverwriteZone = computeReachingWrite(
373       Schedule, Writes, true, IncludeLastRead, IncludeWrite);
374 
375   // { [Element[] -> DomainWrite[]] -> Scatter[] }
376   isl::union_map ReachingOverwriteRotated =
377       reverseDomain(ReachingOverwriteZone).curry().reverse();
378 
379   // { [Element[] -> DomainWrite[]] -> Scatter[] }
380   isl::union_map WritesWithoutReads = ReachingOverwriteRotated.subtract_domain(
381       ReadsOverwrittenRotated.domain());
382 
383   return BetweenLastReadOverwrite.unite(WritesWithoutReads)
384       .domain_factor_domain();
385 }
386 
387 isl::union_set polly::convertZoneToTimepoints(isl::union_set Zone,
388                                               bool InclStart, bool InclEnd) {
389   if (!InclStart && InclEnd)
390     return Zone;
391 
392   auto ShiftedZone = shiftDim(Zone, -1, -1);
393   if (InclStart && !InclEnd)
394     return ShiftedZone;
395   else if (!InclStart && !InclEnd)
396     return Zone.intersect(ShiftedZone);
397 
398   assert(InclStart && InclEnd);
399   return Zone.unite(ShiftedZone);
400 }
401 
402 isl::union_map polly::convertZoneToTimepoints(isl::union_map Zone, isl::dim Dim,
403                                               bool InclStart, bool InclEnd) {
404   if (!InclStart && InclEnd)
405     return Zone;
406 
407   auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
408   if (InclStart && !InclEnd)
409     return ShiftedZone;
410   else if (!InclStart && !InclEnd)
411     return Zone.intersect(ShiftedZone);
412 
413   assert(InclStart && InclEnd);
414   return Zone.unite(ShiftedZone);
415 }
416 
417 isl::map polly::convertZoneToTimepoints(isl::map Zone, isl::dim Dim,
418                                         bool InclStart, bool InclEnd) {
419   if (!InclStart && InclEnd)
420     return Zone;
421 
422   auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
423   if (InclStart && !InclEnd)
424     return ShiftedZone;
425   else if (!InclStart && !InclEnd)
426     return Zone.intersect(ShiftedZone);
427 
428   assert(InclStart && InclEnd);
429   return Zone.unite(ShiftedZone);
430 }
431 
432 isl::map polly::distributeDomain(isl::map Map) {
433   // Note that we cannot take Map apart into { Domain[] -> Range1[] } and {
434   // Domain[] -> Range2[] } and combine again. We would loose any relation
435   // between Range1[] and Range2[] that is not also a constraint to Domain[].
436 
437   isl::space Space = Map.get_space();
438   isl::space DomainSpace = Space.domain();
439   unsigned DomainDims = DomainSpace.dim(isl::dim::set);
440   isl::space RangeSpace = Space.range().unwrap();
441   isl::space Range1Space = RangeSpace.domain();
442   unsigned Range1Dims = Range1Space.dim(isl::dim::set);
443   isl::space Range2Space = RangeSpace.range();
444   unsigned Range2Dims = Range2Space.dim(isl::dim::set);
445 
446   isl::space OutputSpace =
447       DomainSpace.map_from_domain_and_range(Range1Space)
448           .wrap()
449           .map_from_domain_and_range(
450               DomainSpace.map_from_domain_and_range(Range2Space).wrap());
451 
452   isl::basic_map Translator = isl::basic_map::universe(
453       Space.wrap().map_from_domain_and_range(OutputSpace.wrap()));
454 
455   for (unsigned i = 0; i < DomainDims; i += 1) {
456     Translator = Translator.equate(isl::dim::in, i, isl::dim::out, i);
457     Translator = Translator.equate(isl::dim::in, i, isl::dim::out,
458                                    DomainDims + Range1Dims + i);
459   }
460   for (unsigned i = 0; i < Range1Dims; i += 1)
461     Translator = Translator.equate(isl::dim::in, DomainDims + i, isl::dim::out,
462                                    DomainDims + i);
463   for (unsigned i = 0; i < Range2Dims; i += 1)
464     Translator = Translator.equate(isl::dim::in, DomainDims + Range1Dims + i,
465                                    isl::dim::out,
466                                    DomainDims + Range1Dims + DomainDims + i);
467 
468   return Map.wrap().apply(Translator).unwrap();
469 }
470 
471 isl::union_map polly::distributeDomain(isl::union_map UMap) {
472   isl::union_map Result = isl::union_map::empty(UMap.get_space());
473   isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) {
474     auto Distributed = distributeDomain(Map);
475     Result = Result.add_map(Distributed);
476     return isl::stat::ok;
477   });
478   if (Success != isl::stat::ok)
479     return {};
480   return Result;
481 }
482 
483 isl::union_map polly::liftDomains(isl::union_map UMap, isl::union_set Factor) {
484 
485   // { Factor[] -> Factor[] }
486   isl::union_map Factors = makeIdentityMap(Factor, true);
487 
488   return Factors.product(UMap);
489 }
490 
491 isl::union_map polly::applyDomainRange(isl::union_map UMap,
492                                        isl::union_map Func) {
493   // This implementation creates unnecessary cross products of the
494   // DomainDomain[] and Func. An alternative implementation could reverse
495   // domain+uncurry,apply Func to what now is the domain, then undo the
496   // preparing transformation. Another alternative implementation could create a
497   // translator map for each piece.
498 
499   // { DomainDomain[] }
500   isl::union_set DomainDomain = UMap.domain().unwrap().domain();
501 
502   // { [DomainDomain[] -> DomainRange[]] -> [DomainDomain[] -> NewDomainRange[]]
503   // }
504   isl::union_map LifetedFunc = liftDomains(std::move(Func), DomainDomain);
505 
506   return UMap.apply_domain(LifetedFunc);
507 }
508 
509 isl::map polly::intersectRange(isl::map Map, isl::union_set Range) {
510   isl::set RangeSet = Range.extract_set(Map.get_space().range());
511   return Map.intersect_range(RangeSet);
512 }
513 
514 isl::val polly::getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
515   assert(!Max || !Min); // Cannot return min and max at the same time.
516   isl::val Result;
517   PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
518     if (Result && Result.is_nan())
519       return isl::stat::ok;
520 
521     // TODO: If Min/Max, we can also determine a minimum/maximum value if
522     // Set is constant-bounded.
523     if (!Aff.is_cst()) {
524       Result = isl::val::nan(Aff.get_ctx());
525       return isl::stat::error;
526     }
527 
528     isl::val ThisVal = Aff.get_constant_val();
529     if (!Result) {
530       Result = ThisVal;
531       return isl::stat::ok;
532     }
533 
534     if (Result.eq(ThisVal))
535       return isl::stat::ok;
536 
537     if (Max && ThisVal.gt(Result)) {
538       Result = ThisVal;
539       return isl::stat::ok;
540     }
541 
542     if (Min && ThisVal.lt(Result)) {
543       Result = ThisVal;
544       return isl::stat::ok;
545     }
546 
547     // Not compatible
548     Result = isl::val::nan(Aff.get_ctx());
549     return isl::stat::error;
550   });
551   return Result;
552 }
553 
554 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
555 static void foreachPoint(const isl::set &Set,
556                          const std::function<void(isl::point P)> &F) {
557   Set.foreach_point([&](isl::point P) -> isl::stat {
558     F(P);
559     return isl::stat::ok;
560   });
561 }
562 
563 static void foreachPoint(isl::basic_set BSet,
564                          const std::function<void(isl::point P)> &F) {
565   foreachPoint(isl::set(BSet), F);
566 }
567 
568 /// Determine the sorting order of the sets @p A and @p B without considering
569 /// the space structure.
570 ///
571 /// Ordering is based on the lower bounds of the set's dimensions. First
572 /// dimensions are considered first.
573 static int flatCompare(const isl::basic_set &A, const isl::basic_set &B) {
574   unsigned ALen = A.dim(isl::dim::set);
575   unsigned BLen = B.dim(isl::dim::set);
576   unsigned Len = std::min(ALen, BLen);
577 
578   for (unsigned i = 0; i < Len; i += 1) {
579     isl::basic_set ADim =
580         A.project_out(isl::dim::param, 0, A.dim(isl::dim::param))
581             .project_out(isl::dim::set, i + 1, ALen - i - 1)
582             .project_out(isl::dim::set, 0, i);
583     isl::basic_set BDim =
584         B.project_out(isl::dim::param, 0, B.dim(isl::dim::param))
585             .project_out(isl::dim::set, i + 1, BLen - i - 1)
586             .project_out(isl::dim::set, 0, i);
587 
588     isl::basic_set AHull = isl::set(ADim).convex_hull();
589     isl::basic_set BHull = isl::set(BDim).convex_hull();
590 
591     bool ALowerBounded =
592         bool(isl::set(AHull).dim_has_any_lower_bound(isl::dim::set, 0));
593     bool BLowerBounded =
594         bool(isl::set(BHull).dim_has_any_lower_bound(isl::dim::set, 0));
595 
596     int BoundedCompare = BLowerBounded - ALowerBounded;
597     if (BoundedCompare != 0)
598       return BoundedCompare;
599 
600     if (!ALowerBounded || !BLowerBounded)
601       continue;
602 
603     isl::pw_aff AMin = isl::set(ADim).dim_min(0);
604     isl::pw_aff BMin = isl::set(BDim).dim_min(0);
605 
606     isl::val AMinVal = polly::getConstant(AMin, false, true);
607     isl::val BMinVal = polly::getConstant(BMin, false, true);
608 
609     int MinCompare = AMinVal.sub(BMinVal).sgn();
610     if (MinCompare != 0)
611       return MinCompare;
612   }
613 
614   // If all the dimensions' lower bounds are equal or incomparable, sort based
615   // on the number of dimensions.
616   return ALen - BLen;
617 }
618 
619 /// Compare the sets @p A and @p B according to their nested space structure.
620 /// Returns 0 if the structure is considered equal.
621 /// If @p ConsiderTupleLen is false, the number of dimensions in a tuple are
622 /// ignored, i.e. a tuple with the same name but different number of dimensions
623 /// are considered equal.
624 static int structureCompare(const isl::space &ASpace, const isl::space &BSpace,
625                             bool ConsiderTupleLen) {
626   int WrappingCompare = bool(ASpace.is_wrapping()) - bool(BSpace.is_wrapping());
627   if (WrappingCompare != 0)
628     return WrappingCompare;
629 
630   if (ASpace.is_wrapping() && BSpace.is_wrapping()) {
631     isl::space AMap = ASpace.unwrap();
632     isl::space BMap = BSpace.unwrap();
633 
634     int FirstResult =
635         structureCompare(AMap.domain(), BMap.domain(), ConsiderTupleLen);
636     if (FirstResult != 0)
637       return FirstResult;
638 
639     return structureCompare(AMap.range(), BMap.range(), ConsiderTupleLen);
640   }
641 
642   std::string AName;
643   if (ASpace.has_tuple_name(isl::dim::set))
644     AName = ASpace.get_tuple_name(isl::dim::set);
645 
646   std::string BName;
647   if (BSpace.has_tuple_name(isl::dim::set))
648     BName = BSpace.get_tuple_name(isl::dim::set);
649 
650   int NameCompare = AName.compare(BName);
651   if (NameCompare != 0)
652     return NameCompare;
653 
654   if (ConsiderTupleLen) {
655     int LenCompare = BSpace.dim(isl::dim::set) - ASpace.dim(isl::dim::set);
656     if (LenCompare != 0)
657       return LenCompare;
658   }
659 
660   return 0;
661 }
662 
663 /// Compare the sets @p A and @p B according to their nested space structure. If
664 /// the structure is the same, sort using the dimension lower bounds.
665 /// Returns an std::sort compatible bool.
666 static bool orderComparer(const isl::basic_set &A, const isl::basic_set &B) {
667   isl::space ASpace = A.get_space();
668   isl::space BSpace = B.get_space();
669 
670   // Ignoring number of dimensions first ensures that structures with same tuple
671   // names, but different number of dimensions are still sorted close together.
672   int TupleNestingCompare = structureCompare(ASpace, BSpace, false);
673   if (TupleNestingCompare != 0)
674     return TupleNestingCompare < 0;
675 
676   int TupleCompare = structureCompare(ASpace, BSpace, true);
677   if (TupleCompare != 0)
678     return TupleCompare < 0;
679 
680   return flatCompare(A, B) < 0;
681 }
682 
683 /// Print a string representation of @p USet to @p OS.
684 ///
685 /// The pieces of @p USet are printed in a sorted order. Spaces with equal or
686 /// similar nesting structure are printed together. Compared to isl's own
687 /// printing function the uses the structure itself as base of the sorting, not
688 /// a hash of it. It ensures that e.g. maps spaces with same domain structure
689 /// are printed together. Set pieces with same structure are printed in order of
690 /// their lower bounds.
691 ///
692 /// @param USet     Polyhedra to print.
693 /// @param OS       Target stream.
694 /// @param Simplify Whether to simplify the polyhedron before printing.
695 /// @param IsMap    Whether @p USet is a wrapped map. If true, sets are
696 ///                 unwrapped before printing to again appear as a map.
697 static void printSortedPolyhedra(isl::union_set USet, llvm::raw_ostream &OS,
698                                  bool Simplify, bool IsMap) {
699   if (!USet) {
700     OS << "<null>\n";
701     return;
702   }
703 
704   if (Simplify)
705     simplify(USet);
706 
707   // Get all the polyhedra.
708   std::vector<isl::basic_set> BSets;
709   USet.foreach_set([&BSets](isl::set Set) -> isl::stat {
710     Set.foreach_basic_set([&BSets](isl::basic_set BSet) -> isl::stat {
711       BSets.push_back(BSet);
712       return isl::stat::ok;
713     });
714     return isl::stat::ok;
715   });
716 
717   if (BSets.empty()) {
718     OS << "{\n}\n";
719     return;
720   }
721 
722   // Sort the polyhedra.
723   llvm::sort(BSets.begin(), BSets.end(), orderComparer);
724 
725   // Print the polyhedra.
726   bool First = true;
727   for (const isl::basic_set &BSet : BSets) {
728     std::string Str;
729     if (IsMap)
730       Str = isl::map(BSet.unwrap()).to_str();
731     else
732       Str = isl::set(BSet).to_str();
733     size_t OpenPos = Str.find_first_of('{');
734     assert(OpenPos != std::string::npos);
735     size_t ClosePos = Str.find_last_of('}');
736     assert(ClosePos != std::string::npos);
737 
738     if (First)
739       OS << llvm::StringRef(Str).substr(0, OpenPos + 1) << "\n ";
740     else
741       OS << ";\n ";
742 
743     OS << llvm::StringRef(Str).substr(OpenPos + 1, ClosePos - OpenPos - 2);
744     First = false;
745   }
746   assert(!First);
747   OS << "\n}\n";
748 }
749 
750 static void recursiveExpand(isl::basic_set BSet, int Dim, isl::set &Expanded) {
751   int Dims = BSet.dim(isl::dim::set);
752   if (Dim >= Dims) {
753     Expanded = Expanded.unite(BSet);
754     return;
755   }
756 
757   isl::basic_set DimOnly =
758       BSet.project_out(isl::dim::param, 0, BSet.dim(isl::dim::param))
759           .project_out(isl::dim::set, Dim + 1, Dims - Dim - 1)
760           .project_out(isl::dim::set, 0, Dim);
761   if (!DimOnly.is_bounded()) {
762     recursiveExpand(BSet, Dim + 1, Expanded);
763     return;
764   }
765 
766   foreachPoint(DimOnly, [&, Dim](isl::point P) {
767     isl::val Val = P.get_coordinate_val(isl::dim::set, 0);
768     isl::basic_set FixBSet = BSet.fix_val(isl::dim::set, Dim, Val);
769     recursiveExpand(FixBSet, Dim + 1, Expanded);
770   });
771 }
772 
773 /// Make each point of a set explicit.
774 ///
775 /// "Expanding" makes each point a set contains explicit. That is, the result is
776 /// a set of singleton polyhedra. Unbounded dimensions are not expanded.
777 ///
778 /// Example:
779 ///   { [i] : 0 <= i < 2 }
780 /// is expanded to:
781 ///   { [0]; [1] }
782 static isl::set expand(const isl::set &Set) {
783   isl::set Expanded = isl::set::empty(Set.get_space());
784   Set.foreach_basic_set([&](isl::basic_set BSet) -> isl::stat {
785     recursiveExpand(BSet, 0, Expanded);
786     return isl::stat::ok;
787   });
788   return Expanded;
789 }
790 
791 /// Expand all points of a union set explicit.
792 ///
793 /// @see expand(const isl::set)
794 static isl::union_set expand(const isl::union_set &USet) {
795   isl::union_set Expanded = isl::union_set::empty(USet.get_space());
796   USet.foreach_set([&](isl::set Set) -> isl::stat {
797     isl::set SetExpanded = expand(Set);
798     Expanded = Expanded.add_set(SetExpanded);
799     return isl::stat::ok;
800   });
801   return Expanded;
802 }
803 
804 LLVM_DUMP_METHOD void polly::dumpPw(const isl::set &Set) {
805   printSortedPolyhedra(Set, llvm::errs(), true, false);
806 }
807 
808 LLVM_DUMP_METHOD void polly::dumpPw(const isl::map &Map) {
809   printSortedPolyhedra(Map.wrap(), llvm::errs(), true, true);
810 }
811 
812 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_set &USet) {
813   printSortedPolyhedra(USet, llvm::errs(), true, false);
814 }
815 
816 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_map &UMap) {
817   printSortedPolyhedra(UMap.wrap(), llvm::errs(), true, true);
818 }
819 
820 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_set *Set) {
821   dumpPw(isl::manage_copy(Set));
822 }
823 
824 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_map *Map) {
825   dumpPw(isl::manage_copy(Map));
826 }
827 
828 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_set *USet) {
829   dumpPw(isl::manage_copy(USet));
830 }
831 
832 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_map *UMap) {
833   dumpPw(isl::manage_copy(UMap));
834 }
835 
836 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::set &Set) {
837   printSortedPolyhedra(expand(Set), llvm::errs(), false, false);
838 }
839 
840 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::map &Map) {
841   printSortedPolyhedra(expand(Map.wrap()), llvm::errs(), false, true);
842 }
843 
844 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_set &USet) {
845   printSortedPolyhedra(expand(USet), llvm::errs(), false, false);
846 }
847 
848 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_map &UMap) {
849   printSortedPolyhedra(expand(UMap.wrap()), llvm::errs(), false, true);
850 }
851 
852 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_set *Set) {
853   dumpExpanded(isl::manage_copy(Set));
854 }
855 
856 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_map *Map) {
857   dumpExpanded(isl::manage_copy(Map));
858 }
859 
860 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_set *USet) {
861   dumpExpanded(isl::manage_copy(USet));
862 }
863 
864 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_map *UMap) {
865   dumpExpanded(isl::manage_copy(UMap));
866 }
867 #endif
868