blob: 77c339f8d728c493972be07b51ad52794511d038 [file] [log] [blame]
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001//===- 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//
Tobias Grosser234a4822015-08-15 09:34:33 +000010// This pass generates an entirey new schedule tree from the data dependences
11// and iteration domains. The new schedule tree is computed in two steps:
Tobias Grosser30aa24c2011-05-14 19:02:06 +000012//
Tobias Grosser234a4822015-08-15 09:34:33 +000013// 1) The isl scheduling optimizer is run
14//
15// The isl scheduling optimizer creates a new schedule tree that maximizes
16// parallelism and tileability and minimizes data-dependence distances. The
17// algorithm used is a modified version of the ``Pluto'' algorithm:
18//
19// U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
20// A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
21// In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
22// Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
23//
24// 2) A set of post-scheduling transformations is applied on the schedule tree.
25//
26// These optimizations include:
27//
28// - Tiling of the innermost tilable bands
29// - Prevectorization - The coice of a possible outer loop that is strip-mined
30// to the innermost level to enable inner-loop
31// vectorization.
32// - Some optimizations for spatial locality are also planned.
33//
34// For a detailed description of the schedule tree itself please see section 6
35// of:
36//
37// Polyhedral AST generation is more than scanning polyhedra
38// Tobias Grosser, Sven Verdoolaege, Albert Cohen
39// ACM Transations on Programming Languages and Systems (TOPLAS),
40// 37(4), July 2015
41// http://www.grosser.es/#pub-polyhedral-AST-generation
42//
43// This publication also contains a detailed discussion of the different options
44// for polyhedral loop unrolling, full/partial tile separation and other uses
45// of the schedule tree.
46//
Tobias Grosser30aa24c2011-05-14 19:02:06 +000047//===----------------------------------------------------------------------===//
48
Tobias Grosser967239c2011-10-23 20:59:44 +000049#include "polly/ScheduleOptimizer.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "polly/CodeGen/CodeGeneration.h"
51#include "polly/DependenceInfo.h"
52#include "polly/LinkAllPasses.h"
53#include "polly/Options.h"
54#include "polly/ScopInfo.h"
55#include "polly/Support/GICHelper.h"
56#include "llvm/Support/Debug.h"
Tobias Grosser2493e922011-12-07 07:42:57 +000057#include "isl/aff.h"
Tobias Grosserde68cc92011-06-30 20:01:02 +000058#include "isl/band.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000059#include "isl/constraint.h"
60#include "isl/map.h"
Tobias Grosser42152ff2012-01-30 19:38:47 +000061#include "isl/options.h"
Tobias Grosser97d87452015-05-30 06:46:59 +000062#include "isl/printer.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000063#include "isl/schedule.h"
Tobias Grosserbbb4cec2015-03-22 12:06:39 +000064#include "isl/schedule_node.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000065#include "isl/space.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000066#include "isl/union_map.h"
67#include "isl/union_set.h"
Tobias Grosser30aa24c2011-05-14 19:02:06 +000068
69using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-opt-isl"
73
Tobias Grossera26db472012-01-30 19:38:43 +000074static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000075 OptimizeDeps("polly-opt-optimize-only",
76 cl::desc("Only a certain kind of dependences (all/raw)"),
77 cl::Hidden, cl::init("all"), cl::ZeroOrMore,
78 cl::cat(PollyCategory));
Tobias Grosser1deda292012-02-14 14:02:48 +000079
80static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000081 SimplifyDeps("polly-opt-simplify-deps",
82 cl::desc("Dependences should be simplified (yes/no)"),
83 cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
84 cl::cat(PollyCategory));
Tobias Grossera26db472012-01-30 19:38:43 +000085
Tobias Grosser483a90d2014-07-09 10:50:10 +000086static cl::opt<int> MaxConstantTerm(
87 "polly-opt-max-constant-term",
88 cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
89 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser992e60c2012-02-20 08:41:15 +000090
Tobias Grosser483a90d2014-07-09 10:50:10 +000091static cl::opt<int> MaxCoefficient(
92 "polly-opt-max-coefficient",
93 cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
94 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
95
96static cl::opt<std::string> FusionStrategy(
97 "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
98 cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser92f54802012-02-20 08:41:47 +000099
Tobias Grossere602a072013-05-07 07:30:56 +0000100static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000101 MaximizeBandDepth("polly-opt-maximize-bands",
102 cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
103 cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000104
Tobias Grosser07c1c2f2015-08-19 08:46:11 +0000105static cl::opt<int> PrevectorWidth(
106 "polly-prevect-width",
107 cl::desc(
108 "The number of loop iterations to strip-mine for pre-vectorization"),
109 cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
110
Tobias Grosser04832712015-08-20 13:45:02 +0000111static cl::opt<bool> FirstLevelTiling("polly-tiling",
112 cl::desc("Enable loop tiling"),
113 cl::init(true), cl::ZeroOrMore,
114 cl::cat(PollyCategory));
115
116static cl::opt<int> FirstLevelDefaultTileSize(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000117 "polly-default-tile-size",
118 cl::desc("The default tile size (if not enough were provided by"
119 " --polly-tile-sizes)"),
120 cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertc3958b22014-05-28 17:21:02 +0000121
Tobias Grosser04832712015-08-20 13:45:02 +0000122static cl::list<int> FirstLevelTileSizes(
123 "polly-tile-sizes", cl::desc("A tile size for each loop dimension, filled "
124 "with --polly-default-tile-size"),
125 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
126
127static cl::opt<bool>
128 SecondLevelTiling("polly-2nd-level-tiling",
129 cl::desc("Enable a 2nd level loop of loop tiling"),
130 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
131
132static cl::opt<int> SecondLevelDefaultTileSize(
133 "polly-2nd-level-default-tile-size",
134 cl::desc("The default 2nd-level tile size (if not enough were provided by"
135 " --polly-2nd-level-tile-sizes)"),
136 cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
137
138static cl::list<int>
139 SecondLevelTileSizes("polly-2nd-level-tile-sizes",
140 cl::desc("A tile size for each loop dimension, filled "
141 "with --polly-default-tile-size"),
142 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
143 cl::cat(PollyCategory));
144
Tobias Grosser42e24892015-08-20 13:45:05 +0000145static cl::opt<bool> RegisterTiling("polly-register-tiling",
146 cl::desc("Enable register tiling"),
147 cl::init(false), cl::ZeroOrMore,
148 cl::cat(PollyCategory));
149
150static cl::opt<int> RegisterDefaultTileSize(
151 "polly-register-tiling-default-tile-size",
152 cl::desc("The default register tile size (if not enough were provided by"
153 " --polly-register-tile-sizes)"),
154 cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
155
156static cl::list<int>
157 RegisterTileSizes("polly-register-tile-sizes",
158 cl::desc("A tile size for each loop dimension, filled "
159 "with --polly-register-tile-size"),
160 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
161 cl::cat(PollyCategory));
162
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000163/// @brief Create an isl_union_set, which describes the isolate option based
164/// on IsoalteDomain.
165///
166/// @param IsolateDomain An isl_set whose last dimension is the only one that
167/// should belong to the current band node.
168static __isl_give isl_union_set *
169getIsolateOptions(__isl_take isl_set *IsolateDomain) {
170 auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
171 auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
172 IsolateRelation = isl_map_move_dims(IsolateRelation, isl_dim_out, 0,
173 isl_dim_in, Dims - 1, 1);
174 auto *IsolateOption = isl_map_wrap(IsolateRelation);
175 auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", NULL);
176 return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
177}
178
179/// @brief Create an isl_union_set, which describes the atomic option for the
180/// dimension of the current node.
181///
182/// It may help to reduce the size of generated code.
183///
184/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
185static __isl_give isl_union_set *getAtomicOptions(__isl_take isl_ctx *Ctx) {
186 auto *Space = isl_space_set_alloc(Ctx, 0, 1);
187 auto *AtomicOption = isl_set_universe(Space);
188 auto *Id = isl_id_alloc(Ctx, "atomic", NULL);
189 return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
190}
191
192/// @brief Make the last dimension of Set to take values
193/// from 0 to VectorWidth - 1.
194///
195/// @param Set A set, which should be modified.
196/// @param VectorWidth A parameter, which determines the constraint.
197static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
198 int VectorWidth) {
199 auto Dims = isl_set_dim(Set, isl_dim_set);
200 auto Space = isl_set_get_space(Set);
201 auto *LocalSpace = isl_local_space_from_space(Space);
202 auto *ExtConstr =
203 isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
204 ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
205 ExtConstr =
206 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
207 Set = isl_set_add_constraint(Set, ExtConstr);
208 ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
209 ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
210 ExtConstr =
211 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
212 return isl_set_add_constraint(Set, ExtConstr);
213}
214
215/// @brief Build the desired set of partial tile prefixes.
216///
217/// We build a set of partial tile prefixes, which are prefixes of the vector
218/// loop that have exactly VectorWidth iterations.
219///
220/// 1. Get all prefixes of the vector loop.
221/// 2. Extend it to a set, which has exactly VectorWidth iterations for
222/// any prefix from the set that was built on the previous step.
223/// 3. Subtract loop domain from it, project out the vector loop dimension and
224/// get a set of prefixes, which don’t have exactly VectorWidth iterations.
225/// 4. Subtract it from all prefixes of the vector loop and get the desired
226/// set.
227///
228/// @param ScheduleRange A range of a map, which describes a prefix schedule
229/// relation.
230static __isl_give isl_set *
231getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
232 auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
233 auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
234 isl_dim_set, Dims - 1, 1);
235 auto *ExtentPrefixes =
236 isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
237 ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
238 auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
239 BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
240 return isl_set_subtract(LoopPrefixes, BadPrefixes);
241}
242
243__isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
244 __isl_take isl_schedule_node *Node, int VectorWidth) {
245 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
246 Node = isl_schedule_node_child(Node, 0);
247 Node = isl_schedule_node_child(Node, 0);
248 auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
249 auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
250 auto *ScheduleRange = isl_map_range(ScheduleRelation);
251 auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
252 auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
253 auto *IsolateOption = getIsolateOptions(IsolateDomain);
254 Node = isl_schedule_node_parent(Node);
255 Node = isl_schedule_node_parent(Node);
256 auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
257 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
258 return Node;
259}
260
Tobias Grosserb241d922015-07-28 18:03:36 +0000261__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000262ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
263 unsigned DimToVectorize,
264 int VectorWidth) {
Tobias Grosserb241d922015-07-28 18:03:36 +0000265 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
Tobias Grosserc6699b72011-06-30 20:29:13 +0000266
Tobias Grosserb241d922015-07-28 18:03:36 +0000267 auto Space = isl_schedule_node_band_get_space(Node);
268 auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
269 isl_space_free(Space);
270 assert(DimToVectorize < ScheduleDimensions);
Tobias Grosserf5338802011-10-06 00:03:35 +0000271
Tobias Grosserb241d922015-07-28 18:03:36 +0000272 if (DimToVectorize > 0) {
273 Node = isl_schedule_node_band_split(Node, DimToVectorize);
274 Node = isl_schedule_node_child(Node, 0);
275 }
276 if (DimToVectorize < ScheduleDimensions - 1)
277 Node = isl_schedule_node_band_split(Node, 1);
278 Space = isl_schedule_node_band_get_space(Node);
279 auto Sizes = isl_multi_val_zero(Space);
280 auto Ctx = isl_schedule_node_get_ctx(Node);
281 Sizes =
282 isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
283 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000284 Node = isolateFullPartialTiles(Node, VectorWidth);
Tobias Grosserb241d922015-07-28 18:03:36 +0000285 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser42e24892015-08-20 13:45:05 +0000286 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
287 // we will have troubles to match it in the backend.
288 Node = isl_schedule_node_band_set_ast_build_options(
Tobias Grosserfc490a92015-08-20 19:08:16 +0000289 Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
290 Node = isl_schedule_node_band_sink(Node);
Tobias Grosserb241d922015-07-28 18:03:36 +0000291 Node = isl_schedule_node_child(Node, 0);
Roman Gareev11001e12016-02-23 09:00:13 +0000292 if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
293 Node = isl_schedule_node_parent(Node);
294 isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
295 Node = isl_schedule_node_insert_mark(Node, LoopMarker);
Tobias Grosserb241d922015-07-28 18:03:36 +0000296 return Node;
Tobias Grosserc6699b72011-06-30 20:29:13 +0000297}
298
Tobias Grosserd891b542015-08-20 12:16:23 +0000299__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000300ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
301 const char *Identifier, ArrayRef<int> TileSizes,
302 int DefaultTileSize) {
Tobias Grosser9bdea572015-08-20 12:22:37 +0000303 auto Ctx = isl_schedule_node_get_ctx(Node);
304 auto Space = isl_schedule_node_band_get_space(Node);
305 auto Dims = isl_space_dim(Space, isl_dim_set);
306 auto Sizes = isl_multi_val_zero(Space);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000307 std::string IdentifierString(Identifier);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000308 for (unsigned i = 0; i < Dims; i++) {
309 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
310 Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
311 }
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000312 auto TileLoopMarkerStr = IdentifierString + " - Tiles";
313 isl_id *TileLoopMarker =
314 isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
315 Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
316 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000317 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000318 Node = isl_schedule_node_child(Node, 0);
319 auto PointLoopMarkerStr = IdentifierString + " - Points";
320 isl_id *PointLoopMarker =
321 isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
322 Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
323 Node = isl_schedule_node_child(Node, 0);
324 return Node;
Tobias Grosser9bdea572015-08-20 12:22:37 +0000325}
326
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000327bool ScheduleTreeOptimizer::isTileableBandNode(
Tobias Grosser862b9b52015-08-20 12:32:45 +0000328 __isl_keep isl_schedule_node *Node) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000329 if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000330 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000331
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000332 if (isl_schedule_node_n_children(Node) != 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000333 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000334
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000335 if (!isl_schedule_node_band_get_permutable(Node))
Tobias Grosser862b9b52015-08-20 12:32:45 +0000336 return false;
Tobias Grosser44f19ac2011-07-05 22:15:53 +0000337
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000338 auto Space = isl_schedule_node_band_get_space(Node);
339 auto Dims = isl_space_dim(Space, isl_dim_set);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000340 isl_space_free(Space);
Tobias Grosserde68cc92011-06-30 20:01:02 +0000341
Tobias Grosser9bdea572015-08-20 12:22:37 +0000342 if (Dims <= 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000343 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000344
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000345 auto Child = isl_schedule_node_get_child(Node, 0);
346 auto Type = isl_schedule_node_get_type(Child);
347 isl_schedule_node_free(Child);
348
Tobias Grosser9bdea572015-08-20 12:22:37 +0000349 if (Type != isl_schedule_node_leaf)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000350 return false;
351
352 return true;
353}
354
355__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000356ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
357 void *User) {
Tobias Grosser862b9b52015-08-20 12:32:45 +0000358 if (!isTileableBandNode(Node))
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000359 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000360
Tobias Grosser04832712015-08-20 13:45:02 +0000361 if (FirstLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000362 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
363 FirstLevelDefaultTileSize);
Tobias Grosser04832712015-08-20 13:45:02 +0000364
365 if (SecondLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000366 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
367 SecondLevelDefaultTileSize);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000368
Tobias Grosser42e24892015-08-20 13:45:05 +0000369 if (RegisterTiling) {
370 auto *Ctx = isl_schedule_node_get_ctx(Node);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000371 Node = tileNode(Node, "Register tiling", RegisterTileSizes,
372 RegisterDefaultTileSize);
Tobias Grosser42e24892015-08-20 13:45:05 +0000373 Node = isl_schedule_node_band_set_ast_build_options(
374 Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
375 }
376
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000377 if (PollyVectorizerChoice == VECTORIZER_NONE)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000378 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000379
Tobias Grosser862b9b52015-08-20 12:32:45 +0000380 auto Space = isl_schedule_node_band_get_space(Node);
381 auto Dims = isl_space_dim(Space, isl_dim_set);
382 isl_space_free(Space);
383
Tobias Grosserb241d922015-07-28 18:03:36 +0000384 for (int i = Dims - 1; i >= 0; i--)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000385 if (isl_schedule_node_band_member_get_coincident(Node, i)) {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000386 Node = prevectSchedBand(Node, i, PrevectorWidth);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000387 break;
388 }
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000389
Tobias Grosserf10f4632015-08-19 08:03:37 +0000390 return Node;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000391}
392
Tobias Grosser808cd692015-07-14 09:33:13 +0000393__isl_give isl_schedule *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000394ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000395 isl_schedule_node *Root = isl_schedule_get_root(Schedule);
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000396 Root = optimizeScheduleNode(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +0000397 isl_schedule_free(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +0000398 auto S = isl_schedule_node_get_schedule(Root);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000399 isl_schedule_node_free(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +0000400 return S;
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000401}
402
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000403__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
404 __isl_take isl_schedule_node *Node) {
405 Node = isl_schedule_node_map_descendant_bottom_up(Node, optimizeBand, NULL);
406 return Node;
407}
408
409bool ScheduleTreeOptimizer::isProfitableSchedule(
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000410 Scop &S, __isl_keep isl_union_map *NewSchedule) {
411 // To understand if the schedule has been optimized we check if the schedule
412 // has changed at all.
413 // TODO: We can improve this by tracking if any necessarily beneficial
414 // transformations have been performed. This can e.g. be tiling, loop
415 // interchange, or ...) We can track this either at the place where the
416 // transformation has been performed or, in case of automatic ILP based
417 // optimizations, by comparing (yet to be defined) performance metrics
418 // before/after the scheduling optimizer
419 // (e.g., #stride-one accesses)
420 isl_union_map *OldSchedule = S.getSchedule();
421 bool changed = !isl_union_map_is_equal(OldSchedule, NewSchedule);
422 isl_union_map_free(OldSchedule);
423 return changed;
424}
425
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000426namespace {
427class IslScheduleOptimizer : public ScopPass {
428public:
429 static char ID;
430 explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
431
432 ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
433
Johannes Doerfert45be6442015-09-27 15:43:29 +0000434 /// @brief Optimize the schedule of the SCoP @p S.
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000435 bool runOnScop(Scop &S) override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000436
Johannes Doerfert45be6442015-09-27 15:43:29 +0000437 /// @brief Print the new schedule for the SCoP @p S.
438 void printScop(raw_ostream &OS, Scop &S) const override;
439
440 /// @brief Register all analyses and transformation required.
441 void getAnalysisUsage(AnalysisUsage &AU) const override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000442
Johannes Doerfert0f376302015-09-27 15:42:28 +0000443 /// @brief Release the internal memory.
444 void releaseMemory() override {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000445 isl_schedule_free(LastSchedule);
446 LastSchedule = nullptr;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000447 }
Johannes Doerfert45be6442015-09-27 15:43:29 +0000448
449private:
450 isl_schedule *LastSchedule;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000451};
452}
453
454char IslScheduleOptimizer::ID = 0;
455
Tobias Grosser73600b82011-10-08 00:30:40 +0000456bool IslScheduleOptimizer::runOnScop(Scop &S) {
Johannes Doerfert6f7921f2015-02-14 12:02:24 +0000457
458 // Skip empty SCoPs but still allow code generation as it will delete the
459 // loops present but not needed.
460 if (S.getSize() == 0) {
461 S.markAsOptimized();
462 return false;
463 }
464
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000465 const Dependences &D = getAnalysis<DependenceInfo>().getDependences();
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000466
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000467 if (!D.hasValidDependences())
Tobias Grosser38c36ea2014-02-23 15:15:44 +0000468 return false;
469
Tobias Grosser28781422012-10-16 07:29:19 +0000470 isl_schedule_free(LastSchedule);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000471 LastSchedule = nullptr;
Tobias Grosser28781422012-10-16 07:29:19 +0000472
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000473 // Build input data.
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000474 int ValidityKinds =
475 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +0000476 int ProximityKinds;
477
478 if (OptimizeDeps == "all")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000479 ProximityKinds =
480 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +0000481 else if (OptimizeDeps == "raw")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000482 ProximityKinds = Dependences::TYPE_RAW;
Tobias Grosser1deda292012-02-14 14:02:48 +0000483 else {
484 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000485 << " Falling back to optimizing all dependences.\n";
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000486 ProximityKinds =
487 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +0000488 }
489
Tobias Grosser5f9a7622012-02-14 14:02:40 +0000490 isl_union_set *Domain = S.getDomains();
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000491
Tobias Grosser98610ee2012-02-13 23:31:39 +0000492 if (!Domain)
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000493 return false;
494
Johannes Doerfert7e6424b2015-03-05 00:43:48 +0000495 isl_union_map *Validity = D.getDependences(ValidityKinds);
496 isl_union_map *Proximity = D.getDependences(ProximityKinds);
Tobias Grosser8a507022012-03-16 11:51:41 +0000497
Tobias Grossera26db472012-01-30 19:38:43 +0000498 // Simplify the dependences by removing the constraints introduced by the
499 // domains. This can speed up the scheduling time significantly, as large
500 // constant coefficients will be removed from the dependences. The
501 // introduction of some additional dependences reduces the possible
502 // transformations, but in most cases, such transformation do not seem to be
503 // interesting anyway. In some cases this option may stop the scheduler to
504 // find any schedule.
505 if (SimplifyDeps == "yes") {
Tobias Grosser00383a72012-02-14 14:02:44 +0000506 Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
507 Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000508 Proximity =
509 isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
Tobias Grosser00383a72012-02-14 14:02:44 +0000510 Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
Tobias Grossera26db472012-01-30 19:38:43 +0000511 } else if (SimplifyDeps != "no") {
512 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
513 "or 'no'. Falling back to default: 'yes'\n";
514 }
515
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000516 DEBUG(dbgs() << "\n\nCompute schedule from: ");
Tobias Grosser01aea582014-10-22 23:16:28 +0000517 DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
518 DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
519 DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000520
Michael Krusec59f22c2015-06-18 16:45:40 +0000521 unsigned IslSerializeSCCs;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000522
523 if (FusionStrategy == "max") {
Michael Krusec59f22c2015-06-18 16:45:40 +0000524 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000525 } else if (FusionStrategy == "min") {
Michael Krusec59f22c2015-06-18 16:45:40 +0000526 IslSerializeSCCs = 1;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000527 } else {
528 errs() << "warning: Unknown fusion strategy. Falling back to maximal "
529 "fusion.\n";
Michael Krusec59f22c2015-06-18 16:45:40 +0000530 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000531 }
532
Tobias Grosser95e860c2012-01-30 19:38:54 +0000533 int IslMaximizeBands;
534
Tobias Grossera4ea90b2012-01-30 22:43:56 +0000535 if (MaximizeBandDepth == "yes") {
Tobias Grosser95e860c2012-01-30 19:38:54 +0000536 IslMaximizeBands = 1;
Tobias Grossera4ea90b2012-01-30 22:43:56 +0000537 } else if (MaximizeBandDepth == "no") {
Tobias Grosser95e860c2012-01-30 19:38:54 +0000538 IslMaximizeBands = 0;
539 } else {
540 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
541 " or 'no'. Falling back to default: 'yes'\n";
542 IslMaximizeBands = 1;
543 }
544
Michael Krusec59f22c2015-06-18 16:45:40 +0000545 isl_options_set_schedule_serialize_sccs(S.getIslCtx(), IslSerializeSCCs);
Tobias Grosser95e860c2012-01-30 19:38:54 +0000546 isl_options_set_schedule_maximize_band_depth(S.getIslCtx(), IslMaximizeBands);
Tobias Grosser992e60c2012-02-20 08:41:15 +0000547 isl_options_set_schedule_max_constant_term(S.getIslCtx(), MaxConstantTerm);
Tobias Grosser92f54802012-02-20 08:41:47 +0000548 isl_options_set_schedule_max_coefficient(S.getIslCtx(), MaxCoefficient);
Tobias Grosser4f6bcef2015-03-31 07:52:36 +0000549 isl_options_set_tile_scale_tile_loops(S.getIslCtx(), 0);
Tobias Grosser42152ff2012-01-30 19:38:47 +0000550
551 isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_CONTINUE);
Tobias Grossera38c9242014-01-26 19:36:28 +0000552
553 isl_schedule_constraints *ScheduleConstraints;
554 ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
555 ScheduleConstraints =
556 isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
557 ScheduleConstraints = isl_schedule_constraints_set_validity(
558 ScheduleConstraints, isl_union_map_copy(Validity));
559 ScheduleConstraints =
560 isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
Tobias Grosser00383a72012-02-14 14:02:44 +0000561 isl_schedule *Schedule;
Tobias Grossera38c9242014-01-26 19:36:28 +0000562 Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
Tobias Grosser42152ff2012-01-30 19:38:47 +0000563 isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_ABORT);
564
565 // In cases the scheduler is not able to optimize the code, we just do not
566 // touch the schedule.
Tobias Grosser98610ee2012-02-13 23:31:39 +0000567 if (!Schedule)
Tobias Grosser42152ff2012-01-30 19:38:47 +0000568 return false;
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000569
Tobias Grosser97d87452015-05-30 06:46:59 +0000570 DEBUG({
571 auto *P = isl_printer_to_str(S.getIslCtx());
572 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
573 P = isl_printer_print_schedule(P, Schedule);
574 dbgs() << "NewScheduleTree: \n" << isl_printer_get_str(P) << "\n";
575 isl_printer_free(P);
576 });
Tobias Grosser4d63b9d2012-02-20 08:41:21 +0000577
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000578 isl_schedule *NewSchedule = ScheduleTreeOptimizer::optimizeSchedule(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +0000579 isl_union_map *NewScheduleMap = isl_schedule_get_map(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000580
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000581 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewScheduleMap)) {
Tobias Grosser808cd692015-07-14 09:33:13 +0000582 isl_union_map_free(NewScheduleMap);
583 isl_schedule_free(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000584 return false;
585 }
586
Tobias Grosser808cd692015-07-14 09:33:13 +0000587 S.setScheduleTree(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000588 S.markAsOptimized();
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000589
Tobias Grosser808cd692015-07-14 09:33:13 +0000590 isl_union_map_free(NewScheduleMap);
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000591 return false;
592}
593
Johannes Doerfert3fe584d2015-03-01 18:40:25 +0000594void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
Tobias Grosser28781422012-10-16 07:29:19 +0000595 isl_printer *p;
596 char *ScheduleStr;
597
598 OS << "Calculated schedule:\n";
599
600 if (!LastSchedule) {
601 OS << "n/a\n";
602 return;
603 }
604
605 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
606 p = isl_printer_print_schedule(p, LastSchedule);
607 ScheduleStr = isl_printer_get_str(p);
608 isl_printer_free(p);
609
610 OS << ScheduleStr << "\n";
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000611}
612
Tobias Grosser73600b82011-10-08 00:30:40 +0000613void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000614 ScopPass::getAnalysisUsage(AU);
Johannes Doerfertf6557f92015-03-04 22:43:40 +0000615 AU.addRequired<DependenceInfo>();
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000616}
617
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000618Pass *polly::createIslScheduleOptimizerPass() {
Tobias Grosser73600b82011-10-08 00:30:40 +0000619 return new IslScheduleOptimizer();
Tobias Grosser30aa24c2011-05-14 19:02:06 +0000620}
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000621
622INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
623 "Polly - Optimize schedule of SCoP", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +0000624INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000625INITIALIZE_PASS_DEPENDENCY(ScopInfo);
626INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
627 "Polly - Optimize schedule of SCoP", false, false)