1 //===- Schedule.cpp - Calculate an optimized schedule ---------------------===//
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 // This pass the isl to calculate a schedule that is optimized for parallelism
11 // and tileablility. The algorithm used in isl is an optimized version of the
12 // algorithm described in following paper:
13 //
14 // U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
15 // A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
16 // In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
17 // Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
18 //===----------------------------------------------------------------------===//
19 
20 #include "polly/ScheduleOptimizer.h"
21 #include "polly/CodeGen/CodeGeneration.h"
22 #include "polly/DependenceInfo.h"
23 #include "polly/LinkAllPasses.h"
24 #include "polly/Options.h"
25 #include "polly/ScopInfo.h"
26 #include "polly/Support/GICHelper.h"
27 #include "llvm/Support/Debug.h"
28 #include "isl/aff.h"
29 #include "isl/band.h"
30 #include "isl/constraint.h"
31 #include "isl/map.h"
32 #include "isl/options.h"
33 #include "isl/schedule.h"
34 #include "isl/schedule_node.h"
35 #include "isl/space.h"
36 #include "isl/union_map.h"
37 #include "isl/union_set.h"
38 
39 using namespace llvm;
40 using namespace polly;
41 
42 #define DEBUG_TYPE "polly-opt-isl"
43 
44 namespace polly {
45 bool DisablePollyTiling;
46 }
47 static cl::opt<bool, true>
48     DisableTiling("polly-no-tiling",
49                   cl::desc("Disable tiling in the scheduler"),
50                   cl::location(polly::DisablePollyTiling), cl::init(false),
51                   cl::ZeroOrMore, cl::cat(PollyCategory));
52 
53 static cl::opt<std::string>
54     OptimizeDeps("polly-opt-optimize-only",
55                  cl::desc("Only a certain kind of dependences (all/raw)"),
56                  cl::Hidden, cl::init("all"), cl::ZeroOrMore,
57                  cl::cat(PollyCategory));
58 
59 static cl::opt<std::string>
60     SimplifyDeps("polly-opt-simplify-deps",
61                  cl::desc("Dependences should be simplified (yes/no)"),
62                  cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
63                  cl::cat(PollyCategory));
64 
65 static cl::opt<int> MaxConstantTerm(
66     "polly-opt-max-constant-term",
67     cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
68     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
69 
70 static cl::opt<int> MaxCoefficient(
71     "polly-opt-max-coefficient",
72     cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
73     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
74 
75 static cl::opt<std::string> FusionStrategy(
76     "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
77     cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
78 
79 static cl::opt<std::string>
80     MaximizeBandDepth("polly-opt-maximize-bands",
81                       cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
82                       cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
83 
84 static cl::opt<int> DefaultTileSize(
85     "polly-default-tile-size",
86     cl::desc("The default tile size (if not enough were provided by"
87              " --polly-tile-sizes)"),
88     cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
89 
90 static cl::list<int> TileSizes("polly-tile-sizes",
91                                cl::desc("A tile size"
92                                         " for each loop dimension, filled with"
93                                         " --polly-default-tile-size"),
94                                cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
95                                cl::cat(PollyCategory));
96 namespace {
97 
98 class IslScheduleOptimizer : public ScopPass {
99 public:
100   static char ID;
101   explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
102 
103   ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
104 
105   bool runOnScop(Scop &S) override;
106   void printScop(raw_ostream &OS, Scop &S) const override;
107   void getAnalysisUsage(AnalysisUsage &AU) const override;
108 
109 private:
110   isl_schedule *LastSchedule;
111 
112   /// @brief Decide if the @p NewSchedule is profitable for @p S.
113   ///
114   /// @param S           The SCoP we optimize.
115   /// @param NewSchedule The new schedule we computed.
116   ///
117   /// @return True, if we believe @p NewSchedule is an improvement for @p S.
118   bool isProfitableSchedule(Scop &S, __isl_keep isl_union_map *NewSchedule);
119 
120   /// @brief Create a map that pre-vectorizes one scheduling dimension.
121   ///
122   /// getPrevectorMap creates a map that maps each input dimension to the same
123   /// output dimension, except for the dimension DimToVectorize.
124   /// DimToVectorize is strip mined by 'VectorWidth' and the newly created
125   /// point loop of DimToVectorize is moved to the innermost level.
126   ///
127   /// Example (DimToVectorize=0, ScheduleDimensions=2, VectorWidth=4):
128   ///
129   /// | Before transformation
130   /// |
131   /// | A[i,j] -> [i,j]
132   /// |
133   /// | for (i = 0; i < 128; i++)
134   /// |    for (j = 0; j < 128; j++)
135   /// |      A(i,j);
136   ///
137   ///   Prevector map:
138   ///   [i,j] -> [it,j,ip] : it % 4 = 0 and it <= ip <= it + 3 and i = ip
139   ///
140   /// | After transformation:
141   /// |
142   /// | A[i,j] -> [it,j,ip] : it % 4 = 0 and it <= ip <= it + 3 and i = ip
143   /// |
144   /// | for (it = 0; it < 128; it+=4)
145   /// |    for (j = 0; j < 128; j++)
146   /// |      for (ip = max(0,it); ip < min(128, it + 3); ip++)
147   /// |        A(ip,j);
148   ///
149   /// The goal of this transformation is to create a trivially vectorizable
150   /// loop.  This means a parallel loop at the innermost level that has a
151   /// constant number of iterations corresponding to the target vector width.
152   ///
153   /// This transformation creates a loop at the innermost level. The loop has
154   /// a constant number of iterations, if the number of loop iterations at
155   /// DimToVectorize can be divided by VectorWidth. The default VectorWidth is
156   /// currently constant and not yet target specific. This function does not
157   /// reason about parallelism.
158   static __isl_give isl_map *getPrevectorMap(isl_ctx *ctx, int DimToVectorize,
159                                              int ScheduleDimensions,
160                                              int VectorWidth = 4);
161 
162   /// @brief Apply additional optimizations on the bands in the schedule tree.
163   ///
164   /// We are looking for an innermost band node and apply the following
165   /// transformations:
166   ///
167   ///  - Tile the band
168   ///      - if the band is tileable
169   ///      - if the band has more than one loop dimension
170   ///
171   ///  - Prevectorize the point loop of the tile
172   ///      - if vectorization is enabled
173   ///
174   /// @param Node The schedule node to (possibly) optimize.
175   /// @param User A pointer to forward some use information (currently unused).
176   static isl_schedule_node *optimizeBand(isl_schedule_node *Node, void *User);
177 
178   static __isl_give isl_union_map *
179   getScheduleMap(__isl_keep isl_schedule *Schedule);
180 
181   using llvm::Pass::doFinalization;
182 
183   virtual bool doFinalization() override {
184     isl_schedule_free(LastSchedule);
185     LastSchedule = nullptr;
186     return true;
187   }
188 };
189 }
190 
191 char IslScheduleOptimizer::ID = 0;
192 
193 __isl_give isl_map *
194 IslScheduleOptimizer::getPrevectorMap(isl_ctx *ctx, int DimToVectorize,
195                                       int ScheduleDimensions, int VectorWidth) {
196   isl_space *Space;
197   isl_local_space *LocalSpace, *LocalSpaceRange;
198   isl_set *Modulo;
199   isl_map *TilingMap;
200   isl_constraint *c;
201   isl_aff *Aff;
202   int PointDimension; /* ip */
203   int TileDimension;  /* it */
204   isl_val *VectorWidthMP;
205 
206   assert(0 <= DimToVectorize && DimToVectorize < ScheduleDimensions);
207 
208   Space = isl_space_alloc(ctx, 0, ScheduleDimensions, ScheduleDimensions + 1);
209   TilingMap = isl_map_universe(isl_space_copy(Space));
210   LocalSpace = isl_local_space_from_space(Space);
211   PointDimension = ScheduleDimensions;
212   TileDimension = DimToVectorize;
213 
214   // Create an identity map for everything except DimToVectorize and map
215   // DimToVectorize to the point loop at the innermost dimension.
216   for (int i = 0; i < ScheduleDimensions; i++) {
217     c = isl_equality_alloc(isl_local_space_copy(LocalSpace));
218     c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
219 
220     if (i == DimToVectorize)
221       c = isl_constraint_set_coefficient_si(c, isl_dim_out, PointDimension, 1);
222     else
223       c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, 1);
224 
225     TilingMap = isl_map_add_constraint(TilingMap, c);
226   }
227 
228   // it % 'VectorWidth' = 0
229   LocalSpaceRange = isl_local_space_range(isl_local_space_copy(LocalSpace));
230   Aff = isl_aff_zero_on_domain(LocalSpaceRange);
231   Aff = isl_aff_set_constant_si(Aff, VectorWidth);
232   Aff = isl_aff_set_coefficient_si(Aff, isl_dim_in, TileDimension, 1);
233   VectorWidthMP = isl_val_int_from_si(ctx, VectorWidth);
234   Aff = isl_aff_mod_val(Aff, VectorWidthMP);
235   Modulo = isl_pw_aff_zero_set(isl_pw_aff_from_aff(Aff));
236   TilingMap = isl_map_intersect_range(TilingMap, Modulo);
237 
238   // it <= ip
239   c = isl_inequality_alloc(isl_local_space_copy(LocalSpace));
240   isl_constraint_set_coefficient_si(c, isl_dim_out, TileDimension, -1);
241   isl_constraint_set_coefficient_si(c, isl_dim_out, PointDimension, 1);
242   TilingMap = isl_map_add_constraint(TilingMap, c);
243 
244   // ip <= it + ('VectorWidth' - 1)
245   c = isl_inequality_alloc(LocalSpace);
246   isl_constraint_set_coefficient_si(c, isl_dim_out, TileDimension, 1);
247   isl_constraint_set_coefficient_si(c, isl_dim_out, PointDimension, -1);
248   isl_constraint_set_constant_si(c, VectorWidth - 1);
249   TilingMap = isl_map_add_constraint(TilingMap, c);
250 
251   return TilingMap;
252 }
253 
254 isl_schedule_node *IslScheduleOptimizer::optimizeBand(isl_schedule_node *Node,
255                                                       void *User) {
256   if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
257     return Node;
258 
259   if (isl_schedule_node_n_children(Node) != 1)
260     return Node;
261 
262   if (!isl_schedule_node_band_get_permutable(Node))
263     return Node;
264 
265   auto Space = isl_schedule_node_band_get_space(Node);
266   auto Dims = isl_space_dim(Space, isl_dim_set);
267 
268   if (Dims <= 1) {
269     isl_space_free(Space);
270     return Node;
271   }
272 
273   auto Child = isl_schedule_node_get_child(Node, 0);
274   auto Type = isl_schedule_node_get_type(Child);
275   isl_schedule_node_free(Child);
276 
277   if (Type != isl_schedule_node_leaf) {
278     isl_space_free(Space);
279     return Node;
280   }
281 
282   auto Sizes = isl_multi_val_zero(Space);
283   auto Ctx = isl_schedule_node_get_ctx(Node);
284 
285   for (unsigned i = 0; i < Dims; i++) {
286     auto tileSize = TileSizes.size() > i ? TileSizes[i] : DefaultTileSize;
287     Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
288   }
289 
290   isl_schedule_node *Res;
291 
292   if (DisableTiling) {
293     isl_multi_val_free(Sizes);
294     Res = Node;
295   } else {
296     Res = isl_schedule_node_band_tile(Node, Sizes);
297   }
298 
299   if (PollyVectorizerChoice == VECTORIZER_NONE)
300     return Res;
301 
302   Child = isl_schedule_node_get_child(Res, 0);
303   auto ChildSchedule = isl_schedule_node_band_get_partial_schedule(Child);
304 
305   for (int i = Dims - 1; i >= 0; i--) {
306     if (isl_schedule_node_band_member_get_coincident(Child, i)) {
307       auto TileMap = IslScheduleOptimizer::getPrevectorMap(Ctx, i, Dims);
308       auto TileUMap = isl_union_map_from_map(TileMap);
309       auto ChildSchedule2 = isl_union_map_apply_range(
310           isl_union_map_from_multi_union_pw_aff(ChildSchedule), TileUMap);
311       ChildSchedule = isl_multi_union_pw_aff_from_union_map(ChildSchedule2);
312       break;
313     }
314   }
315 
316   isl_schedule_node_free(Res);
317   Res = isl_schedule_node_delete(Child);
318   Res = isl_schedule_node_insert_partial_schedule(Res, ChildSchedule);
319   return Res;
320 }
321 
322 __isl_give isl_union_map *
323 IslScheduleOptimizer::getScheduleMap(__isl_keep isl_schedule *Schedule) {
324   isl_schedule_node *Root = isl_schedule_get_root(Schedule);
325   Root = isl_schedule_node_map_descendant(
326       Root, IslScheduleOptimizer::optimizeBand, NULL);
327   auto ScheduleMap = isl_schedule_node_get_subtree_schedule_union_map(Root);
328   ScheduleMap = isl_union_map_detect_equalities(ScheduleMap);
329   isl_schedule_node_free(Root);
330   return ScheduleMap;
331 }
332 
333 bool IslScheduleOptimizer::isProfitableSchedule(
334     Scop &S, __isl_keep isl_union_map *NewSchedule) {
335   // To understand if the schedule has been optimized we check if the schedule
336   // has changed at all.
337   // TODO: We can improve this by tracking if any necessarily beneficial
338   // transformations have been performed. This can e.g. be tiling, loop
339   // interchange, or ...) We can track this either at the place where the
340   // transformation has been performed or, in case of automatic ILP based
341   // optimizations, by comparing (yet to be defined) performance metrics
342   // before/after the scheduling optimizer
343   // (e.g., #stride-one accesses)
344   isl_union_map *OldSchedule = S.getSchedule();
345   bool changed = !isl_union_map_is_equal(OldSchedule, NewSchedule);
346   isl_union_map_free(OldSchedule);
347   return changed;
348 }
349 
350 bool IslScheduleOptimizer::runOnScop(Scop &S) {
351 
352   // Skip empty SCoPs but still allow code generation as it will delete the
353   // loops present but not needed.
354   if (S.getSize() == 0) {
355     S.markAsOptimized();
356     return false;
357   }
358 
359   const Dependences &D = getAnalysis<DependenceInfo>().getDependences();
360 
361   if (!D.hasValidDependences())
362     return false;
363 
364   isl_schedule_free(LastSchedule);
365   LastSchedule = nullptr;
366 
367   // Build input data.
368   int ValidityKinds =
369       Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
370   int ProximityKinds;
371 
372   if (OptimizeDeps == "all")
373     ProximityKinds =
374         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
375   else if (OptimizeDeps == "raw")
376     ProximityKinds = Dependences::TYPE_RAW;
377   else {
378     errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
379            << " Falling back to optimizing all dependences.\n";
380     ProximityKinds =
381         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
382   }
383 
384   isl_union_set *Domain = S.getDomains();
385 
386   if (!Domain)
387     return false;
388 
389   isl_union_map *Validity = D.getDependences(ValidityKinds);
390   isl_union_map *Proximity = D.getDependences(ProximityKinds);
391 
392   // Simplify the dependences by removing the constraints introduced by the
393   // domains. This can speed up the scheduling time significantly, as large
394   // constant coefficients will be removed from the dependences. The
395   // introduction of some additional dependences reduces the possible
396   // transformations, but in most cases, such transformation do not seem to be
397   // interesting anyway. In some cases this option may stop the scheduler to
398   // find any schedule.
399   if (SimplifyDeps == "yes") {
400     Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
401     Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
402     Proximity =
403         isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
404     Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
405   } else if (SimplifyDeps != "no") {
406     errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
407               "or 'no'. Falling back to default: 'yes'\n";
408   }
409 
410   DEBUG(dbgs() << "\n\nCompute schedule from: ");
411   DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
412   DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
413   DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
414 
415   int IslFusionStrategy;
416 
417   if (FusionStrategy == "max") {
418     IslFusionStrategy = ISL_SCHEDULE_FUSE_MAX;
419   } else if (FusionStrategy == "min") {
420     IslFusionStrategy = ISL_SCHEDULE_FUSE_MIN;
421   } else {
422     errs() << "warning: Unknown fusion strategy. Falling back to maximal "
423               "fusion.\n";
424     IslFusionStrategy = ISL_SCHEDULE_FUSE_MAX;
425   }
426 
427   int IslMaximizeBands;
428 
429   if (MaximizeBandDepth == "yes") {
430     IslMaximizeBands = 1;
431   } else if (MaximizeBandDepth == "no") {
432     IslMaximizeBands = 0;
433   } else {
434     errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
435               " or 'no'. Falling back to default: 'yes'\n";
436     IslMaximizeBands = 1;
437   }
438 
439   isl_options_set_schedule_fuse(S.getIslCtx(), IslFusionStrategy);
440   isl_options_set_schedule_maximize_band_depth(S.getIslCtx(), IslMaximizeBands);
441   isl_options_set_schedule_max_constant_term(S.getIslCtx(), MaxConstantTerm);
442   isl_options_set_schedule_max_coefficient(S.getIslCtx(), MaxCoefficient);
443   isl_options_set_tile_scale_tile_loops(S.getIslCtx(), 0);
444 
445   isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_CONTINUE);
446 
447   isl_schedule_constraints *ScheduleConstraints;
448   ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
449   ScheduleConstraints =
450       isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
451   ScheduleConstraints = isl_schedule_constraints_set_validity(
452       ScheduleConstraints, isl_union_map_copy(Validity));
453   ScheduleConstraints =
454       isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
455   isl_schedule *Schedule;
456   Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
457   isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_ABORT);
458 
459   // In cases the scheduler is not able to optimize the code, we just do not
460   // touch the schedule.
461   if (!Schedule)
462     return false;
463 
464   DEBUG(dbgs() << "Schedule := " << stringFromIslObj(Schedule) << ";\n");
465 
466   isl_union_map *NewSchedule = getScheduleMap(Schedule);
467 
468   // Check if the optimizations performed were profitable, otherwise exit early.
469   if (!isProfitableSchedule(S, NewSchedule)) {
470     isl_schedule_free(Schedule);
471     isl_union_map_free(NewSchedule);
472     return false;
473   }
474 
475   S.markAsOptimized();
476 
477   for (ScopStmt *Stmt : S) {
478     isl_map *StmtSchedule;
479     isl_set *Domain = Stmt->getDomain();
480     isl_union_map *StmtBand;
481     StmtBand = isl_union_map_intersect_domain(isl_union_map_copy(NewSchedule),
482                                               isl_union_set_from_set(Domain));
483     if (isl_union_map_is_empty(StmtBand)) {
484       StmtSchedule = isl_map_from_domain(isl_set_empty(Stmt->getDomainSpace()));
485       isl_union_map_free(StmtBand);
486     } else {
487       assert(isl_union_map_n_map(StmtBand) == 1);
488       StmtSchedule = isl_map_from_union_map(StmtBand);
489     }
490 
491     Stmt->setSchedule(StmtSchedule);
492   }
493 
494   isl_schedule_free(Schedule);
495   isl_union_map_free(NewSchedule);
496   return false;
497 }
498 
499 void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
500   isl_printer *p;
501   char *ScheduleStr;
502 
503   OS << "Calculated schedule:\n";
504 
505   if (!LastSchedule) {
506     OS << "n/a\n";
507     return;
508   }
509 
510   p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
511   p = isl_printer_print_schedule(p, LastSchedule);
512   ScheduleStr = isl_printer_get_str(p);
513   isl_printer_free(p);
514 
515   OS << ScheduleStr << "\n";
516 }
517 
518 void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
519   ScopPass::getAnalysisUsage(AU);
520   AU.addRequired<DependenceInfo>();
521 }
522 
523 Pass *polly::createIslScheduleOptimizerPass() {
524   return new IslScheduleOptimizer();
525 }
526 
527 INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
528                       "Polly - Optimize schedule of SCoP", false, false);
529 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
530 INITIALIZE_PASS_DEPENDENCY(ScopInfo);
531 INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
532                     "Polly - Optimize schedule of SCoP", false, false)
533