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