1 //===------ FlattenAlgo.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 // Main algorithm of the FlattenSchedulePass. This is a separate file to avoid
11 // the unittest for this requiring linking against LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/FlattenAlgo.h"
16 #include "polly/Support/ISLOStream.h"
17 #include "llvm/Support/Debug.h"
18 #define DEBUG_TYPE "polly-flatten-algo"
19 
20 using namespace polly;
21 using namespace llvm;
22 
23 namespace {
24 
25 /// Whether a dimension of a set is bounded (lower and upper) by a constant,
26 /// i.e. there are two constants Min and Max, such that every value x of the
27 /// chosen dimensions is Min <= x <= Max.
28 bool isDimBoundedByConstant(isl::set Set, unsigned dim) {
29   auto ParamDims = Set.dim(isl::dim::param);
30   Set = Set.project_out(isl::dim::param, 0, ParamDims);
31   Set = Set.project_out(isl::dim::set, 0, dim);
32   auto SetDims = Set.dim(isl::dim::set);
33   Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
34   return bool(Set.is_bounded());
35 }
36 
37 /// Whether a dimension of a set is (lower and upper) bounded by a constant or
38 /// parameters, i.e. there are two expressions Min_p and Max_p of the parameters
39 /// p, such that every value x of the chosen dimensions is
40 /// Min_p <= x <= Max_p.
41 bool isDimBoundedByParameter(isl::set Set, unsigned dim) {
42   Set = Set.project_out(isl::dim::set, 0, dim);
43   auto SetDims = Set.dim(isl::dim::set);
44   Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
45   return bool(Set.is_bounded());
46 }
47 
48 /// Whether BMap's first out-dimension is not a constant.
49 bool isVariableDim(const isl::basic_map &BMap) {
50   auto FixedVal = BMap.plain_get_val_if_fixed(isl::dim::out, 0);
51   return !FixedVal || FixedVal.is_nan();
52 }
53 
54 /// Whether Map's first out dimension is no constant nor piecewise constant.
55 bool isVariableDim(const isl::map &Map) {
56   return Map.foreach_basic_map([](isl::basic_map BMap) -> isl::stat {
57     if (isVariableDim(BMap))
58       return isl::stat::error;
59     return isl::stat::ok;
60   }) == isl::stat::ok;
61 }
62 
63 /// Whether UMap's first out dimension is no (piecewise) constant.
64 bool isVariableDim(const isl::union_map &UMap) {
65   return UMap.foreach_map([](isl::map Map) -> isl::stat {
66     if (isVariableDim(Map))
67       return isl::stat::error;
68     return isl::stat::ok;
69   }) == isl::stat::ok;
70 }
71 
72 /// If @p PwAff maps to a constant, return said constant. If @p Max/@p Min, it
73 /// can also be a piecewise constant and it would return the minimum/maximum
74 /// value. Otherwise, return NaN.
75 isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
76   assert(!Max || !Min);
77   isl::val Result;
78   PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
79     if (Result && Result.is_nan())
80       return isl::stat::ok;
81 
82     // TODO: If Min/Max, we can also determine a minimum/maximum value if
83     // Set is constant-bounded.
84     if (!Aff.is_cst()) {
85       Result = isl::val::nan(Aff.get_ctx());
86       return isl::stat::error;
87     }
88 
89     auto ThisVal = Aff.get_constant_val();
90     if (!Result) {
91       Result = ThisVal;
92       return isl::stat::ok;
93     }
94 
95     if (Result.eq(ThisVal))
96       return isl::stat::ok;
97 
98     if (Max && ThisVal.gt(Result)) {
99       Result = ThisVal;
100       return isl::stat::ok;
101     }
102 
103     if (Min && ThisVal.lt(Result)) {
104       Result = ThisVal;
105       return isl::stat::ok;
106     }
107 
108     // Not compatible
109     Result = isl::val::nan(Aff.get_ctx());
110     return isl::stat::error;
111   });
112   return Result;
113 }
114 
115 /// Compute @p UPwAff - @p Val.
116 isl::union_pw_aff subtract(isl::union_pw_aff UPwAff, isl::val Val) {
117   if (Val.is_zero())
118     return UPwAff;
119 
120   auto Result = isl::union_pw_aff::empty(UPwAff.get_space());
121   UPwAff.foreach_pw_aff([=, &Result](isl::pw_aff PwAff) -> isl::stat {
122     auto ValAff =
123         isl::pw_aff(isl::set::universe(PwAff.get_space().domain()), Val);
124     auto Subtracted = PwAff.sub(ValAff);
125     Result = Result.union_add(isl::union_pw_aff(Subtracted));
126     return isl::stat::ok;
127   });
128   return Result;
129 }
130 
131 /// Compute @UPwAff * @p Val.
132 isl::union_pw_aff multiply(isl::union_pw_aff UPwAff, isl::val Val) {
133   if (Val.is_one())
134     return UPwAff;
135 
136   auto Result = isl::union_pw_aff::empty(UPwAff.get_space());
137   UPwAff.foreach_pw_aff([=, &Result](isl::pw_aff PwAff) -> isl::stat {
138     auto ValAff =
139         isl::pw_aff(isl::set::universe(PwAff.get_space().domain()), Val);
140     auto Multiplied = PwAff.mul(ValAff);
141     Result = Result.union_add(Multiplied);
142     return isl::stat::ok;
143   });
144   return Result;
145 }
146 
147 /// Remove @p n dimensions from @p UMap's range, starting at @p first.
148 ///
149 /// It is assumed that all maps in the maps have at least the necessary number
150 /// of out dimensions.
151 isl::union_map scheduleProjectOut(const isl::union_map &UMap, unsigned first,
152                                   unsigned n) {
153   if (n == 0)
154     return UMap; /* isl_map_project_out would also reset the tuple, which should
155                     have no effect on schedule ranges */
156 
157   auto Result = isl::union_map::empty(UMap.get_space());
158   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
159     auto Outprojected = Map.project_out(isl::dim::out, first, n);
160     Result = Result.add_map(Outprojected);
161     return isl::stat::ok;
162   });
163   return Result;
164 }
165 
166 /// Return the number of dimensions in the input map's range.
167 ///
168 /// Because this function takes an isl_union_map, the out dimensions could be
169 /// different. We return the maximum number in this case. However, a different
170 /// number of dimensions is not supported by the other code in this file.
171 size_t scheduleScatterDims(const isl::union_map &Schedule) {
172   unsigned Dims = 0;
173   Schedule.foreach_map([&Dims](isl::map Map) -> isl::stat {
174     Dims = std::max(Dims, Map.dim(isl::dim::out));
175     return isl::stat::ok;
176   });
177   return Dims;
178 }
179 
180 /// Return the @p pos' range dimension, converted to an isl_union_pw_aff.
181 isl::union_pw_aff scheduleExtractDimAff(isl::union_map UMap, unsigned pos) {
182   auto SingleUMap = isl::union_map::empty(UMap.get_space());
183   UMap.foreach_map([=, &SingleUMap](isl::map Map) -> isl::stat {
184     auto MapDims = Map.dim(isl::dim::out);
185     auto SingleMap = Map.project_out(isl::dim::out, 0, pos);
186     SingleMap = SingleMap.project_out(isl::dim::out, 1, MapDims - pos - 1);
187     SingleUMap = SingleUMap.add_map(SingleMap);
188     return isl::stat::ok;
189   });
190 
191   auto UAff = isl::union_pw_multi_aff(SingleUMap);
192   auto FirstMAff = isl::multi_union_pw_aff(UAff);
193   return FirstMAff.get_union_pw_aff(0);
194 }
195 
196 /// Flatten a sequence-like first dimension.
197 ///
198 /// A sequence-like scatter dimension is constant, or at least only small
199 /// variation, typically the result of ordering a sequence of different
200 /// statements. An example would be:
201 ///   { Stmt_A[] -> [0, X, ...]; Stmt_B[] -> [1, Y, ...] }
202 /// to schedule all instances of Stmt_A before any instance of Stmt_B.
203 ///
204 /// To flatten, first begin with an offset of zero. Then determine the lowest
205 /// possible value of the dimension, call it "i" [In the example we start at 0].
206 /// Considering only schedules with that value, consider only instances with
207 /// that value and determine the extent of the next dimension. Let l_X(i) and
208 /// u_X(i) its minimum (lower bound) and maximum (upper bound) value. Add them
209 /// as "Offset + X - l_X(i)" to the new schedule, then add "u_X(i) - l_X(i) + 1"
210 /// to Offset and remove all i-instances from the old schedule. Repeat with the
211 /// remaining lowest value i' until there are no instances in the old schedule
212 /// left.
213 /// The example schedule would be transformed to:
214 ///   { Stmt_X[] -> [X - l_X, ...]; Stmt_B -> [l_X - u_X + 1 + Y - l_Y, ...] }
215 isl::union_map tryFlattenSequence(isl::union_map Schedule) {
216   auto IslCtx = Schedule.get_ctx();
217   auto ScatterSet = isl::set(Schedule.range());
218 
219   auto ParamSpace = Schedule.get_space().params();
220   auto Dims = ScatterSet.dim(isl::dim::set);
221   assert(Dims >= 2);
222 
223   // Would cause an infinite loop.
224   if (!isDimBoundedByConstant(ScatterSet, 0)) {
225     DEBUG(dbgs() << "Abort; dimension is not of fixed size\n");
226     return nullptr;
227   }
228 
229   auto AllDomains = Schedule.domain();
230   auto AllDomainsToNull = isl::union_pw_multi_aff(AllDomains);
231 
232   auto NewSchedule = isl::union_map::empty(ParamSpace);
233   auto Counter = isl::pw_aff(isl::local_space(ParamSpace.set_from_params()));
234 
235   while (!ScatterSet.is_empty()) {
236     DEBUG(dbgs() << "Next counter:\n  " << Counter << "\n");
237     DEBUG(dbgs() << "Remaining scatter set:\n  " << ScatterSet << "\n");
238     auto ThisSet = ScatterSet.project_out(isl::dim::set, 1, Dims - 1);
239     auto ThisFirst = ThisSet.lexmin();
240     auto ScatterFirst = ThisFirst.add_dims(isl::dim::set, Dims - 1);
241 
242     auto SubSchedule = Schedule.intersect_range(ScatterFirst);
243     SubSchedule = scheduleProjectOut(SubSchedule, 0, 1);
244     SubSchedule = flattenSchedule(SubSchedule);
245 
246     auto SubDims = scheduleScatterDims(SubSchedule);
247     auto FirstSubSchedule = scheduleProjectOut(SubSchedule, 1, SubDims - 1);
248     auto FirstScheduleAff = scheduleExtractDimAff(FirstSubSchedule, 0);
249     auto RemainingSubSchedule = scheduleProjectOut(SubSchedule, 0, 1);
250 
251     auto FirstSubScatter = isl::set(FirstSubSchedule.range());
252     DEBUG(dbgs() << "Next step in sequence is:\n  " << FirstSubScatter << "\n");
253 
254     if (!isDimBoundedByParameter(FirstSubScatter, 0)) {
255       DEBUG(dbgs() << "Abort; sequence step is not bounded\n");
256       return nullptr;
257     }
258 
259     auto FirstSubScatterMap = isl::map::from_range(FirstSubScatter);
260 
261     // isl_set_dim_max returns a strange isl_pw_aff with domain tuple_id of
262     // 'none'. It doesn't match with any space including a 0-dimensional
263     // anonymous tuple.
264     // Interesting, one can create such a set using
265     // isl_set_universe(ParamSpace). Bug?
266     auto PartMin = FirstSubScatterMap.dim_min(0);
267     auto PartMax = FirstSubScatterMap.dim_max(0);
268     auto One = isl::pw_aff(isl::set::universe(ParamSpace.set_from_params()),
269                            isl::val::one(IslCtx));
270     auto PartLen = PartMax.add(PartMin.neg()).add(One);
271 
272     auto AllPartMin = isl::union_pw_aff(PartMin).pullback(AllDomainsToNull);
273     auto FirstScheduleAffNormalized = FirstScheduleAff.sub(AllPartMin);
274     auto AllCounter = isl::union_pw_aff(Counter).pullback(AllDomainsToNull);
275     auto FirstScheduleAffWithOffset =
276         FirstScheduleAffNormalized.add(AllCounter);
277 
278     auto ScheduleWithOffset = isl::union_map(FirstScheduleAffWithOffset)
279                                   .flat_range_product(RemainingSubSchedule);
280     NewSchedule = NewSchedule.unite(ScheduleWithOffset);
281 
282     ScatterSet = ScatterSet.subtract(ScatterFirst);
283     Counter = Counter.add(PartLen);
284   }
285 
286   DEBUG(dbgs() << "Sequence-flatten result is:\n  " << NewSchedule << "\n");
287   return NewSchedule;
288 }
289 
290 /// Flatten a loop-like first dimension.
291 ///
292 /// A loop-like dimension is one that depends on a variable (usually a loop's
293 /// induction variable). Let the input schedule look like this:
294 ///   { Stmt[i] -> [i, X, ...] }
295 ///
296 /// To flatten, we determine the largest extent of X which may not depend on the
297 /// actual value of i. Let l_X() the smallest possible value of X and u_X() its
298 /// largest value. Then, construct a new schedule
299 ///   { Stmt[i] -> [i * (u_X() - l_X() + 1), ...] }
300 isl::union_map tryFlattenLoop(isl::union_map Schedule) {
301   assert(scheduleScatterDims(Schedule) >= 2);
302 
303   auto Remaining = scheduleProjectOut(Schedule, 0, 1);
304   auto SubSchedule = flattenSchedule(Remaining);
305   auto SubDims = scheduleScatterDims(SubSchedule);
306 
307   auto SubExtent = isl::set(SubSchedule.range());
308   auto SubExtentDims = SubExtent.dim(isl::dim::param);
309   SubExtent = SubExtent.project_out(isl::dim::param, 0, SubExtentDims);
310   SubExtent = SubExtent.project_out(isl::dim::set, 1, SubDims - 1);
311 
312   if (!isDimBoundedByConstant(SubExtent, 0)) {
313     DEBUG(dbgs() << "Abort; dimension not bounded by constant\n");
314     return nullptr;
315   }
316 
317   auto Min = SubExtent.dim_min(0);
318   DEBUG(dbgs() << "Min bound:\n  " << Min << "\n");
319   auto MinVal = getConstant(Min, false, true);
320   auto Max = SubExtent.dim_max(0);
321   DEBUG(dbgs() << "Max bound:\n  " << Max << "\n");
322   auto MaxVal = getConstant(Max, true, false);
323 
324   if (!MinVal || !MaxVal || MinVal.is_nan() || MaxVal.is_nan()) {
325     DEBUG(dbgs() << "Abort; dimension bounds could not be determined\n");
326     return nullptr;
327   }
328 
329   auto FirstSubScheduleAff = scheduleExtractDimAff(SubSchedule, 0);
330   auto RemainingSubSchedule = scheduleProjectOut(std::move(SubSchedule), 0, 1);
331 
332   auto LenVal = MaxVal.sub(MinVal).add_ui(1);
333   auto FirstSubScheduleNormalized = subtract(FirstSubScheduleAff, MinVal);
334 
335   // TODO: Normalize FirstAff to zero (convert to isl_map, determine minimum,
336   // subtract it)
337   auto FirstAff = scheduleExtractDimAff(Schedule, 0);
338   auto Offset = multiply(FirstAff, LenVal);
339   auto Index = FirstSubScheduleNormalized.add(Offset);
340   auto IndexMap = isl::union_map(Index);
341 
342   auto Result = IndexMap.flat_range_product(RemainingSubSchedule);
343   DEBUG(dbgs() << "Loop-flatten result is:\n  " << Result << "\n");
344   return Result;
345 }
346 } // anonymous namespace
347 
348 isl::union_map polly::flattenSchedule(isl::union_map Schedule) {
349   auto Dims = scheduleScatterDims(Schedule);
350   DEBUG(dbgs() << "Recursive schedule to process:\n  " << Schedule << "\n");
351 
352   // Base case; no dimensions left
353   if (Dims == 0) {
354     // TODO: Add one dimension?
355     return Schedule;
356   }
357 
358   // Base case; already one-dimensional
359   if (Dims == 1)
360     return Schedule;
361 
362   // Fixed dimension; no need to preserve variabledness.
363   if (!isVariableDim(Schedule)) {
364     DEBUG(dbgs() << "Fixed dimension; try sequence flattening\n");
365     auto NewScheduleSequence = tryFlattenSequence(Schedule);
366     if (NewScheduleSequence)
367       return NewScheduleSequence;
368   }
369 
370   // Constant stride
371   DEBUG(dbgs() << "Try loop flattening\n");
372   auto NewScheduleLoop = tryFlattenLoop(Schedule);
373   if (NewScheduleLoop)
374     return NewScheduleLoop;
375 
376   // Try again without loop condition (may blow up the number of pieces!!)
377   DEBUG(dbgs() << "Try sequence flattening again\n");
378   auto NewScheduleSequence = tryFlattenSequence(Schedule);
379   if (NewScheduleSequence)
380     return NewScheduleSequence;
381 
382   // Cannot flatten
383   return Schedule;
384 }
385