blob: fc549e0d274eb395744bb49dafea70dd0b4e9e46 [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 Grosser2219d152016-08-03 05:28:09 +000010// This pass generates an entirely new schedule tree from the data dependences
Tobias Grosser234a4822015-08-15 09:34:33 +000011// 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"
Roman Gareev42402c92016-06-22 09:52:37 +000056#include "llvm/Analysis/TargetTransformInfo.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000057#include "llvm/Support/Debug.h"
Tobias Grosser2493e922011-12-07 07:42:57 +000058#include "isl/aff.h"
Tobias Grosserde68cc92011-06-30 20:01:02 +000059#include "isl/band.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000060#include "isl/constraint.h"
61#include "isl/map.h"
Tobias Grosser42152ff2012-01-30 19:38:47 +000062#include "isl/options.h"
Tobias Grosser97d87452015-05-30 06:46:59 +000063#include "isl/printer.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000064#include "isl/schedule.h"
Tobias Grosserbbb4cec2015-03-22 12:06:39 +000065#include "isl/schedule_node.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000066#include "isl/space.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000067#include "isl/union_map.h"
68#include "isl/union_set.h"
Tobias Grosser30aa24c2011-05-14 19:02:06 +000069
70using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-opt-isl"
74
Tobias Grossera26db472012-01-30 19:38:43 +000075static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000076 OptimizeDeps("polly-opt-optimize-only",
77 cl::desc("Only a certain kind of dependences (all/raw)"),
78 cl::Hidden, cl::init("all"), cl::ZeroOrMore,
79 cl::cat(PollyCategory));
Tobias Grosser1deda292012-02-14 14:02:48 +000080
81static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000082 SimplifyDeps("polly-opt-simplify-deps",
83 cl::desc("Dependences should be simplified (yes/no)"),
84 cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
85 cl::cat(PollyCategory));
Tobias Grossera26db472012-01-30 19:38:43 +000086
Tobias Grosser483a90d2014-07-09 10:50:10 +000087static cl::opt<int> MaxConstantTerm(
88 "polly-opt-max-constant-term",
89 cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
90 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser992e60c2012-02-20 08:41:15 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<int> MaxCoefficient(
93 "polly-opt-max-coefficient",
94 cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
95 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
96
97static cl::opt<std::string> FusionStrategy(
98 "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
99 cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser92f54802012-02-20 08:41:47 +0000100
Tobias Grossere602a072013-05-07 07:30:56 +0000101static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000102 MaximizeBandDepth("polly-opt-maximize-bands",
103 cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
104 cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000105
Michael Kruse315aa322016-05-02 11:35:27 +0000106static cl::opt<std::string> OuterCoincidence(
107 "polly-opt-outer-coincidence",
108 cl::desc("Try to construct schedules where the outer member of each band "
109 "satisfies the coincidence constraints (yes/no)"),
110 cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory));
111
Tobias Grosser07c1c2f2015-08-19 08:46:11 +0000112static cl::opt<int> PrevectorWidth(
113 "polly-prevect-width",
114 cl::desc(
115 "The number of loop iterations to strip-mine for pre-vectorization"),
116 cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
117
Tobias Grosser04832712015-08-20 13:45:02 +0000118static cl::opt<bool> FirstLevelTiling("polly-tiling",
119 cl::desc("Enable loop tiling"),
120 cl::init(true), cl::ZeroOrMore,
121 cl::cat(PollyCategory));
122
Roman Gareev42402c92016-06-22 09:52:37 +0000123static cl::opt<int> LatencyVectorFma(
124 "polly-target-latency-vector-fma",
125 cl::desc("The minimal number of cycles between issuing two "
126 "dependent consecutive vector fused multiply-add "
127 "instructions."),
128 cl::Hidden, cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
129
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000130static cl::opt<int> ThroughputVectorFma(
131 "polly-target-throughput-vector-fma",
Roman Gareev42402c92016-06-22 09:52:37 +0000132 cl::desc("A throughput of the processor floating-point arithmetic units "
133 "expressed in the number of vector fused multiply-add "
134 "instructions per clock cycle."),
135 cl::Hidden, cl::init(1), cl::ZeroOrMore, cl::cat(PollyCategory));
136
Roman Gareev1c2927b2016-12-25 16:32:28 +0000137// This option, along with --polly-target-2nd-cache-level-associativity,
138// --polly-target-1st-cache-level-size, and --polly-target-2st-cache-level-size
139// represent the parameters of the target cache, which do not have typical
140// values that can be used by default. However, to apply the pattern matching
141// optimizations, we use the values of the parameters of Intel Core i7-3820
142// SandyBridge in case the parameters are not specified. Such an approach helps
143// also to attain the high-performance on IBM POWER System S822 and IBM Power
144// 730 Express server.
145static cl::opt<int> FirstCacheLevelAssociativity(
146 "polly-target-1st-cache-level-associativity",
147 cl::desc("The associativity of the first cache level."), cl::Hidden,
148 cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
Roman Gareev3a18a932016-07-25 09:42:53 +0000149
Roman Gareev1c2927b2016-12-25 16:32:28 +0000150static cl::opt<int> SecondCacheLevelAssociativity(
151 "polly-target-2nd-cache-level-associativity",
152 cl::desc("The associativity of the second cache level."), cl::Hidden,
153 cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
154
155static cl::opt<int> FirstCacheLevelSize(
156 "polly-target-1st-cache-level-size",
157 cl::desc("The size of the first cache level specified in bytes."),
158 cl::Hidden, cl::init(32768), cl::ZeroOrMore, cl::cat(PollyCategory));
159
160static cl::opt<int> SecondCacheLevelSize(
161 "polly-target-2nd-cache-level-size",
162 cl::desc("The size of the second level specified in bytes."), cl::Hidden,
163 cl::init(262144), cl::ZeroOrMore, cl::cat(PollyCategory));
Roman Gareev3a18a932016-07-25 09:42:53 +0000164
Tobias Grosser67e94fb2017-01-14 07:14:54 +0000165static cl::opt<int> VectorRegisterBitwidth(
166 "polly-target-vector-register-bitwidth",
167 cl::desc("The size in bits of a vector register (if not set, this "
168 "information is taken from LLVM's target information."),
169 cl::Hidden, cl::init(-1), cl::ZeroOrMore, cl::cat(PollyCategory));
170
Tobias Grosser04832712015-08-20 13:45:02 +0000171static cl::opt<int> FirstLevelDefaultTileSize(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000172 "polly-default-tile-size",
173 cl::desc("The default tile size (if not enough were provided by"
174 " --polly-tile-sizes)"),
175 cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertc3958b22014-05-28 17:21:02 +0000176
Tobias Grosser04832712015-08-20 13:45:02 +0000177static cl::list<int> FirstLevelTileSizes(
178 "polly-tile-sizes", cl::desc("A tile size for each loop dimension, filled "
179 "with --polly-default-tile-size"),
180 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
181
182static cl::opt<bool>
183 SecondLevelTiling("polly-2nd-level-tiling",
184 cl::desc("Enable a 2nd level loop of loop tiling"),
185 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
186
187static cl::opt<int> SecondLevelDefaultTileSize(
188 "polly-2nd-level-default-tile-size",
189 cl::desc("The default 2nd-level tile size (if not enough were provided by"
190 " --polly-2nd-level-tile-sizes)"),
191 cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
192
193static cl::list<int>
194 SecondLevelTileSizes("polly-2nd-level-tile-sizes",
195 cl::desc("A tile size for each loop dimension, filled "
196 "with --polly-default-tile-size"),
197 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
198 cl::cat(PollyCategory));
199
Tobias Grosser42e24892015-08-20 13:45:05 +0000200static cl::opt<bool> RegisterTiling("polly-register-tiling",
201 cl::desc("Enable register tiling"),
202 cl::init(false), cl::ZeroOrMore,
203 cl::cat(PollyCategory));
204
205static cl::opt<int> RegisterDefaultTileSize(
206 "polly-register-tiling-default-tile-size",
207 cl::desc("The default register tile size (if not enough were provided by"
208 " --polly-register-tile-sizes)"),
209 cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
210
Roman Gareevbe5299a2016-12-21 12:51:12 +0000211static cl::opt<int> PollyPatternMatchingNcQuotient(
212 "polly-pattern-matching-nc-quotient",
213 cl::desc("Quotient that is obtained by dividing Nc, the parameter of the"
214 "macro-kernel, by Nr, the parameter of the micro-kernel"),
215 cl::Hidden, cl::init(256), cl::ZeroOrMore, cl::cat(PollyCategory));
216
Tobias Grosser42e24892015-08-20 13:45:05 +0000217static cl::list<int>
218 RegisterTileSizes("polly-register-tile-sizes",
219 cl::desc("A tile size for each loop dimension, filled "
220 "with --polly-register-tile-size"),
221 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
222 cl::cat(PollyCategory));
223
Roman Gareev9c3eb592016-05-28 16:17:58 +0000224static cl::opt<bool>
225 PMBasedOpts("polly-pattern-matching-based-opts",
226 cl::desc("Perform optimizations based on pattern matching"),
227 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
228
Roman Gareev5f99f862016-08-21 11:20:39 +0000229static cl::opt<bool> OptimizedScops(
230 "polly-optimized-scops",
231 cl::desc("Polly - Dump polyhedral description of Scops optimized with "
232 "the isl scheduling optimizer and the set of post-scheduling "
233 "transformations is applied on the schedule tree"),
234 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
235
Tobias Grosserc80d6972016-09-02 06:33:33 +0000236/// Create an isl_union_set, which describes the isolate option based on
237/// IsoalteDomain.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000238///
239/// @param IsolateDomain An isl_set whose last dimension is the only one that
240/// should belong to the current band node.
241static __isl_give isl_union_set *
242getIsolateOptions(__isl_take isl_set *IsolateDomain) {
243 auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
244 auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
245 IsolateRelation = isl_map_move_dims(IsolateRelation, isl_dim_out, 0,
246 isl_dim_in, Dims - 1, 1);
247 auto *IsolateOption = isl_map_wrap(IsolateRelation);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000248 auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000249 return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
250}
251
Tobias Grosserc80d6972016-09-02 06:33:33 +0000252/// Create an isl_union_set, which describes the atomic option for the dimension
253/// of the current node.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000254///
255/// It may help to reduce the size of generated code.
256///
257/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
258static __isl_give isl_union_set *getAtomicOptions(__isl_take isl_ctx *Ctx) {
259 auto *Space = isl_space_set_alloc(Ctx, 0, 1);
260 auto *AtomicOption = isl_set_universe(Space);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000261 auto *Id = isl_id_alloc(Ctx, "atomic", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000262 return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
263}
264
Tobias Grosserc80d6972016-09-02 06:33:33 +0000265/// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000266///
267/// @param Set A set, which should be modified.
268/// @param VectorWidth A parameter, which determines the constraint.
269static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
270 int VectorWidth) {
271 auto Dims = isl_set_dim(Set, isl_dim_set);
272 auto Space = isl_set_get_space(Set);
273 auto *LocalSpace = isl_local_space_from_space(Space);
274 auto *ExtConstr =
275 isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
276 ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
277 ExtConstr =
278 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
279 Set = isl_set_add_constraint(Set, ExtConstr);
280 ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
281 ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
282 ExtConstr =
283 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
284 return isl_set_add_constraint(Set, ExtConstr);
285}
286
Tobias Grosserc80d6972016-09-02 06:33:33 +0000287/// Build the desired set of partial tile prefixes.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000288///
289/// We build a set of partial tile prefixes, which are prefixes of the vector
290/// loop that have exactly VectorWidth iterations.
291///
292/// 1. Get all prefixes of the vector loop.
293/// 2. Extend it to a set, which has exactly VectorWidth iterations for
294/// any prefix from the set that was built on the previous step.
295/// 3. Subtract loop domain from it, project out the vector loop dimension and
Roman Gareev76614d32016-05-31 11:22:21 +0000296/// get a set of prefixes, which don't have exactly VectorWidth iterations.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000297/// 4. Subtract it from all prefixes of the vector loop and get the desired
298/// set.
299///
300/// @param ScheduleRange A range of a map, which describes a prefix schedule
301/// relation.
302static __isl_give isl_set *
303getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
304 auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
305 auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
306 isl_dim_set, Dims - 1, 1);
307 auto *ExtentPrefixes =
308 isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
309 ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
310 auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
311 BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
312 return isl_set_subtract(LoopPrefixes, BadPrefixes);
313}
314
315__isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
316 __isl_take isl_schedule_node *Node, int VectorWidth) {
317 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
318 Node = isl_schedule_node_child(Node, 0);
319 Node = isl_schedule_node_child(Node, 0);
320 auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
321 auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
322 auto *ScheduleRange = isl_map_range(ScheduleRelation);
323 auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
324 auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
325 auto *IsolateOption = getIsolateOptions(IsolateDomain);
326 Node = isl_schedule_node_parent(Node);
327 Node = isl_schedule_node_parent(Node);
328 auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
329 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
330 return Node;
331}
332
Tobias Grosserb241d922015-07-28 18:03:36 +0000333__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000334ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
335 unsigned DimToVectorize,
336 int VectorWidth) {
Tobias Grosserb241d922015-07-28 18:03:36 +0000337 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
Tobias Grosserc6699b72011-06-30 20:29:13 +0000338
Tobias Grosserb241d922015-07-28 18:03:36 +0000339 auto Space = isl_schedule_node_band_get_space(Node);
340 auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
341 isl_space_free(Space);
342 assert(DimToVectorize < ScheduleDimensions);
Tobias Grosserf5338802011-10-06 00:03:35 +0000343
Tobias Grosserb241d922015-07-28 18:03:36 +0000344 if (DimToVectorize > 0) {
345 Node = isl_schedule_node_band_split(Node, DimToVectorize);
346 Node = isl_schedule_node_child(Node, 0);
347 }
348 if (DimToVectorize < ScheduleDimensions - 1)
349 Node = isl_schedule_node_band_split(Node, 1);
350 Space = isl_schedule_node_band_get_space(Node);
351 auto Sizes = isl_multi_val_zero(Space);
352 auto Ctx = isl_schedule_node_get_ctx(Node);
353 Sizes =
354 isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
355 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000356 Node = isolateFullPartialTiles(Node, VectorWidth);
Tobias Grosserb241d922015-07-28 18:03:36 +0000357 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser42e24892015-08-20 13:45:05 +0000358 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
359 // we will have troubles to match it in the backend.
360 Node = isl_schedule_node_band_set_ast_build_options(
Tobias Grosserfc490a92015-08-20 19:08:16 +0000361 Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
362 Node = isl_schedule_node_band_sink(Node);
Tobias Grosserb241d922015-07-28 18:03:36 +0000363 Node = isl_schedule_node_child(Node, 0);
Roman Gareev11001e12016-02-23 09:00:13 +0000364 if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
365 Node = isl_schedule_node_parent(Node);
366 isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
367 Node = isl_schedule_node_insert_mark(Node, LoopMarker);
Tobias Grosserb241d922015-07-28 18:03:36 +0000368 return Node;
Tobias Grosserc6699b72011-06-30 20:29:13 +0000369}
370
Tobias Grosserd891b542015-08-20 12:16:23 +0000371__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000372ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
373 const char *Identifier, ArrayRef<int> TileSizes,
374 int DefaultTileSize) {
Tobias Grosser9bdea572015-08-20 12:22:37 +0000375 auto Ctx = isl_schedule_node_get_ctx(Node);
376 auto Space = isl_schedule_node_band_get_space(Node);
377 auto Dims = isl_space_dim(Space, isl_dim_set);
378 auto Sizes = isl_multi_val_zero(Space);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000379 std::string IdentifierString(Identifier);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000380 for (unsigned i = 0; i < Dims; i++) {
381 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
382 Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
383 }
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000384 auto TileLoopMarkerStr = IdentifierString + " - Tiles";
385 isl_id *TileLoopMarker =
386 isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
387 Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
388 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000389 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000390 Node = isl_schedule_node_child(Node, 0);
391 auto PointLoopMarkerStr = IdentifierString + " - Points";
392 isl_id *PointLoopMarker =
393 isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
394 Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
395 Node = isl_schedule_node_child(Node, 0);
396 return Node;
Tobias Grosser9bdea572015-08-20 12:22:37 +0000397}
398
Roman Gareevb17b9a82016-06-12 17:20:05 +0000399__isl_give isl_schedule_node *
400ScheduleTreeOptimizer::applyRegisterTiling(__isl_take isl_schedule_node *Node,
401 llvm::ArrayRef<int> TileSizes,
402 int DefaultTileSize) {
403 auto *Ctx = isl_schedule_node_get_ctx(Node);
404 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
405 Node = isl_schedule_node_band_set_ast_build_options(
406 Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
407 return Node;
408}
409
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000410bool ScheduleTreeOptimizer::isTileableBandNode(
Tobias Grosser862b9b52015-08-20 12:32:45 +0000411 __isl_keep isl_schedule_node *Node) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000412 if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000413 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000414
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000415 if (isl_schedule_node_n_children(Node) != 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000416 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000417
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000418 if (!isl_schedule_node_band_get_permutable(Node))
Tobias Grosser862b9b52015-08-20 12:32:45 +0000419 return false;
Tobias Grosser44f19ac2011-07-05 22:15:53 +0000420
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000421 auto Space = isl_schedule_node_band_get_space(Node);
422 auto Dims = isl_space_dim(Space, isl_dim_set);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000423 isl_space_free(Space);
Tobias Grosserde68cc92011-06-30 20:01:02 +0000424
Tobias Grosser9bdea572015-08-20 12:22:37 +0000425 if (Dims <= 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000426 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000427
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000428 auto Child = isl_schedule_node_get_child(Node, 0);
429 auto Type = isl_schedule_node_get_type(Child);
430 isl_schedule_node_free(Child);
431
Tobias Grosser9bdea572015-08-20 12:22:37 +0000432 if (Type != isl_schedule_node_leaf)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000433 return false;
434
435 return true;
436}
437
438__isl_give isl_schedule_node *
Roman Gareev9c3eb592016-05-28 16:17:58 +0000439ScheduleTreeOptimizer::standardBandOpts(__isl_take isl_schedule_node *Node,
440 void *User) {
Tobias Grosser04832712015-08-20 13:45:02 +0000441 if (FirstLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000442 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
443 FirstLevelDefaultTileSize);
Tobias Grosser04832712015-08-20 13:45:02 +0000444
445 if (SecondLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000446 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
447 SecondLevelDefaultTileSize);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000448
Roman Gareevb17b9a82016-06-12 17:20:05 +0000449 if (RegisterTiling)
450 Node =
451 applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
Tobias Grosser42e24892015-08-20 13:45:05 +0000452
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000453 if (PollyVectorizerChoice == VECTORIZER_NONE)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000454 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000455
Tobias Grosser862b9b52015-08-20 12:32:45 +0000456 auto Space = isl_schedule_node_band_get_space(Node);
457 auto Dims = isl_space_dim(Space, isl_dim_set);
458 isl_space_free(Space);
459
Tobias Grosserb241d922015-07-28 18:03:36 +0000460 for (int i = Dims - 1; i >= 0; i--)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000461 if (isl_schedule_node_band_member_get_coincident(Node, i)) {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000462 Node = prevectSchedBand(Node, i, PrevectorWidth);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000463 break;
464 }
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000465
Tobias Grosserf10f4632015-08-19 08:03:37 +0000466 return Node;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000467}
468
Tobias Grosserc80d6972016-09-02 06:33:33 +0000469/// Check whether output dimensions of the map rely on the specified input
470/// dimension.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000471///
472/// @param IslMap The isl map to be considered.
473/// @param DimNum The number of an input dimension to be checked.
474static bool isInputDimUsed(__isl_take isl_map *IslMap, unsigned DimNum) {
475 auto *CheckedAccessRelation =
476 isl_map_project_out(isl_map_copy(IslMap), isl_dim_in, DimNum, 1);
477 CheckedAccessRelation =
478 isl_map_insert_dims(CheckedAccessRelation, isl_dim_in, DimNum, 1);
479 auto *InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
480 CheckedAccessRelation =
481 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_in, InputDimsId);
482 InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_out);
483 CheckedAccessRelation =
484 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_out, InputDimsId);
485 auto res = !isl_map_is_equal(CheckedAccessRelation, IslMap);
486 isl_map_free(CheckedAccessRelation);
487 isl_map_free(IslMap);
488 return res;
489}
490
Tobias Grosserc80d6972016-09-02 06:33:33 +0000491/// Check if the SCoP statement could probably be optimized with analytical
492/// modeling.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000493///
494/// containsMatrMult tries to determine whether the following conditions
495/// are true:
496/// 1. all memory accesses of the statement will have stride 0 or 1,
497/// if we interchange loops (switch the variable used in the inner
498/// loop to the outer loop).
499/// 2. all memory accesses of the statement except from the last one, are
500/// read memory access and the last one is write memory access.
Roman Gareev76614d32016-05-31 11:22:21 +0000501/// 3. all subscripts of the last memory access of the statement don't contain
Roman Gareev9c3eb592016-05-28 16:17:58 +0000502/// the variable used in the inner loop.
503///
504/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
505/// to check.
506static bool containsMatrMult(__isl_keep isl_map *PartialSchedule) {
507 auto InputDimsId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
508 auto *ScpStmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
509 isl_id_free(InputDimsId);
510 if (ScpStmt->size() <= 1)
511 return false;
512 auto MemA = ScpStmt->begin();
513 for (unsigned i = 0; i < ScpStmt->size() - 2 && MemA != ScpStmt->end();
514 i++, MemA++)
Roman Gareev76614d32016-05-31 11:22:21 +0000515 if (!(*MemA)->isRead() ||
516 ((*MemA)->isArrayKind() &&
517 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000518 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule)))))
519 return false;
520 MemA++;
Roman Gareev76614d32016-05-31 11:22:21 +0000521 if (!(*MemA)->isWrite() || !(*MemA)->isArrayKind() ||
522 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000523 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule))))
524 return false;
525 auto DimNum = isl_map_dim(PartialSchedule, isl_dim_in);
526 return !isInputDimUsed((*MemA)->getAccessRelation(), DimNum - 1);
527}
528
Tobias Grosserc80d6972016-09-02 06:33:33 +0000529/// Circular shift of output dimensions of the integer map.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000530///
531/// @param IslMap The isl map to be modified.
532static __isl_give isl_map *circularShiftOutputDims(__isl_take isl_map *IslMap) {
Roman Gareev9c3eb592016-05-28 16:17:58 +0000533 auto DimNum = isl_map_dim(IslMap, isl_dim_out);
Roman Gareev4b8c7ae2016-06-03 18:46:29 +0000534 if (DimNum == 0)
535 return IslMap;
536 auto InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
Roman Gareev9c3eb592016-05-28 16:17:58 +0000537 IslMap = isl_map_move_dims(IslMap, isl_dim_in, 0, isl_dim_out, DimNum - 1, 1);
538 IslMap = isl_map_move_dims(IslMap, isl_dim_out, 0, isl_dim_in, 0, 1);
539 return isl_map_set_tuple_id(IslMap, isl_dim_in, InputDimsId);
540}
541
Tobias Grosserc80d6972016-09-02 06:33:33 +0000542/// Permute two dimensions of the band node.
Roman Gareev3a18a932016-07-25 09:42:53 +0000543///
544/// Permute FirstDim and SecondDim dimensions of the Node.
545///
546/// @param Node The band node to be modified.
547/// @param FirstDim The first dimension to be permuted.
548/// @param SecondDim The second dimension to be permuted.
549static __isl_give isl_schedule_node *
550permuteBandNodeDimensions(__isl_take isl_schedule_node *Node, unsigned FirstDim,
551 unsigned SecondDim) {
552 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band &&
553 isl_schedule_node_band_n_member(Node) > std::max(FirstDim, SecondDim));
554 auto PartialSchedule = isl_schedule_node_band_get_partial_schedule(Node);
555 auto PartialScheduleFirstDim =
556 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, FirstDim);
557 auto PartialScheduleSecondDim =
558 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, SecondDim);
559 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
560 PartialSchedule, SecondDim, PartialScheduleFirstDim);
561 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
562 PartialSchedule, FirstDim, PartialScheduleSecondDim);
563 Node = isl_schedule_node_delete(Node);
564 Node = isl_schedule_node_insert_partial_schedule(Node, PartialSchedule);
565 return Node;
566}
567
Roman Gareev2cb4d132016-07-25 07:27:59 +0000568__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMicroKernel(
569 __isl_take isl_schedule_node *Node, MicroKernelParamsTy MicroKernelParams) {
Roman Gareev8babe1a2016-12-15 11:47:38 +0000570 applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr}, 1);
571 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
572 Node = permuteBandNodeDimensions(Node, 0, 1);
573 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000574}
575
Roman Gareev3a18a932016-07-25 09:42:53 +0000576__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMacroKernel(
577 __isl_take isl_schedule_node *Node, MacroKernelParamsTy MacroKernelParams) {
578 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
579 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
580 MacroKernelParams.Kc == 1)
581 return Node;
582 Node = tileNode(
583 Node, "1st level tiling",
584 {MacroKernelParams.Mc, MacroKernelParams.Nc, MacroKernelParams.Kc}, 1);
585 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
586 Node = permuteBandNodeDimensions(Node, 1, 2);
Roman Gareev8babe1a2016-12-15 11:47:38 +0000587 Node = permuteBandNodeDimensions(Node, 0, 2);
Roman Gareev3a18a932016-07-25 09:42:53 +0000588 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
589}
590
Roman Gareev2cb4d132016-07-25 07:27:59 +0000591/// Get parameters of the BLIS micro kernel.
592///
593/// We choose the Mr and Nr parameters of the micro kernel to be large enough
594/// such that no stalls caused by the combination of latencies and dependencies
595/// are introduced during the updates of the resulting matrix of the matrix
596/// multiplication. However, they should also be as small as possible to
597/// release more registers for entries of multiplied matrices.
598///
599/// @param TTI Target Transform Info.
600/// @return The structure of type MicroKernelParamsTy.
601/// @see MicroKernelParamsTy
602static struct MicroKernelParamsTy
603getMicroKernelParams(const llvm::TargetTransformInfo *TTI) {
Roman Gareev42402c92016-06-22 09:52:37 +0000604 assert(TTI && "The target transform info should be provided.");
Roman Gareev2cb4d132016-07-25 07:27:59 +0000605
Roman Gareev42402c92016-06-22 09:52:37 +0000606 // Nvec - Number of double-precision floating-point numbers that can be hold
607 // by a vector register. Use 2 by default.
Tobias Grosser67e94fb2017-01-14 07:14:54 +0000608 long RegisterBitwidth = VectorRegisterBitwidth;
609
610 if (RegisterBitwidth == -1)
611 RegisterBitwidth = TTI->getRegisterBitWidth(true);
612 auto Nvec = RegisterBitwidth / 64;
Roman Gareev42402c92016-06-22 09:52:37 +0000613 if (Nvec == 0)
614 Nvec = 2;
615 int Nr =
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000616 ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec;
617 int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000618 return {Mr, Nr};
619}
620
Roman Gareev3a18a932016-07-25 09:42:53 +0000621/// Get parameters of the BLIS macro kernel.
622///
623/// During the computation of matrix multiplication, blocks of partitioned
624/// matrices are mapped to different layers of the memory hierarchy.
625/// To optimize data reuse, blocks should be ideally kept in cache between
626/// iterations. Since parameters of the macro kernel determine sizes of these
627/// blocks, there are upper and lower bounds on these parameters.
628///
629/// @param MicroKernelParams Parameters of the micro-kernel
630/// to be taken into account.
631/// @return The structure of type MacroKernelParamsTy.
632/// @see MacroKernelParamsTy
633/// @see MicroKernelParamsTy
634static struct MacroKernelParamsTy
635getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams) {
636 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
637 // it requires information about the first two levels of a cache to determine
638 // all the parameters of a macro-kernel. It also checks that an associativity
639 // degree of a cache level is greater than two. Otherwise, another algorithm
640 // for determination of the parameters should be used.
641 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
Roman Gareev1c2927b2016-12-25 16:32:28 +0000642 FirstCacheLevelSize > 0 && SecondCacheLevelSize > 0 &&
643 FirstCacheLevelAssociativity > 2 && SecondCacheLevelAssociativity > 2))
Roman Gareev3a18a932016-07-25 09:42:53 +0000644 return {1, 1, 1};
Roman Gareevbe5299a2016-12-21 12:51:12 +0000645 // The quotient should be greater than zero.
646 if (PollyPatternMatchingNcQuotient <= 0)
647 return {1, 1, 1};
Roman Gareev15db81e2016-12-15 12:00:57 +0000648 int Car = floor(
Roman Gareev1c2927b2016-12-25 16:32:28 +0000649 (FirstCacheLevelAssociativity - 1) /
Roman Gareev8babe1a2016-12-15 11:47:38 +0000650 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
Roman Gareev1c2927b2016-12-25 16:32:28 +0000651 int Kc = (Car * FirstCacheLevelSize) /
652 (MicroKernelParams.Mr * FirstCacheLevelAssociativity * 8);
653 double Cac = static_cast<double>(Kc * 8 * SecondCacheLevelAssociativity) /
654 SecondCacheLevelSize;
655 int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac);
Roman Gareevbe5299a2016-12-21 12:51:12 +0000656 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
Roman Gareev3a18a932016-07-25 09:42:53 +0000657 return {Mc, Nc, Kc};
658}
659
Tobias Grosserc80d6972016-09-02 06:33:33 +0000660/// Identify a memory access through the shape of its memory access relation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000661///
662/// Identify the unique memory access in @p Stmt, that has an access relation
663/// equal to @p ExpectedAccessRelation.
664///
665/// @param Stmt The SCoP statement that contains the memory accesses under
666/// consideration.
667/// @param ExpectedAccessRelation The access relation that identifies
668/// the memory access.
669/// @return The memory access of @p Stmt whose memory access relation is equal
670/// to @p ExpectedAccessRelation. nullptr in case there is no or more
671/// than one such access.
672MemoryAccess *
673identifyAccessByAccessRelation(ScopStmt *Stmt,
674 __isl_take isl_map *ExpectedAccessRelation) {
675 if (isl_map_has_tuple_id(ExpectedAccessRelation, isl_dim_out))
676 ExpectedAccessRelation =
677 isl_map_reset_tuple_id(ExpectedAccessRelation, isl_dim_out);
678 MemoryAccess *IdentifiedAccess = nullptr;
679 for (auto *Access : *Stmt) {
680 auto *AccessRelation = Access->getAccessRelation();
681 AccessRelation = isl_map_reset_tuple_id(AccessRelation, isl_dim_out);
682 if (isl_map_is_equal(ExpectedAccessRelation, AccessRelation)) {
683 if (IdentifiedAccess) {
684 isl_map_free(AccessRelation);
685 isl_map_free(ExpectedAccessRelation);
686 return nullptr;
687 }
688 IdentifiedAccess = Access;
689 }
690 isl_map_free(AccessRelation);
691 }
692 isl_map_free(ExpectedAccessRelation);
693 return IdentifiedAccess;
694}
695
Roman Gareevb3224ad2016-09-14 06:26:09 +0000696/// Add constrains to @Dim dimension of @p ExtMap.
697///
698/// If @ExtMap has the following form [O0, O1, O2]->[I1, I2, I3],
699/// the following constraint will be added
700/// Bound * OM <= IM <= Bound * (OM + 1) - 1,
701/// where M is @p Dim and Bound is @p Bound.
702///
703/// @param ExtMap The isl map to be modified.
704/// @param Dim The output dimension to be modfied.
705/// @param Bound The value that is used to specify the constraint.
706/// @return The modified isl map
707__isl_give isl_map *
708addExtensionMapMatMulDimConstraint(__isl_take isl_map *ExtMap, unsigned Dim,
709 unsigned Bound) {
710 assert(Bound != 0);
711 auto *ExtMapSpace = isl_map_get_space(ExtMap);
712 auto *ConstrSpace = isl_local_space_from_space(ExtMapSpace);
713 auto *Constr =
714 isl_constraint_alloc_inequality(isl_local_space_copy(ConstrSpace));
715 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, 1);
716 Constr =
717 isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound * (-1));
718 ExtMap = isl_map_add_constraint(ExtMap, Constr);
719 Constr = isl_constraint_alloc_inequality(ConstrSpace);
720 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, -1);
721 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound);
722 Constr = isl_constraint_set_constant_si(Constr, Bound - 1);
723 return isl_map_add_constraint(ExtMap, Constr);
724}
725
726/// Create an access relation that is specific for matrix multiplication
727/// pattern.
728///
729/// Create an access relation of the following form:
730/// { [O0, O1, O2]->[I1, I2, I3] :
731/// FirstOutputDimBound * O0 <= I1 <= FirstOutputDimBound * (O0 + 1) - 1
732/// and SecondOutputDimBound * O1 <= I2 <= SecondOutputDimBound * (O1 + 1) - 1
733/// and ThirdOutputDimBound * O2 <= I3 <= ThirdOutputDimBound * (O2 + 1) - 1}
734/// where FirstOutputDimBound is @p FirstOutputDimBound,
735/// SecondOutputDimBound is @p SecondOutputDimBound,
736/// ThirdOutputDimBound is @p ThirdOutputDimBound
737///
738/// @param Ctx The isl context.
739/// @param FirstOutputDimBound,
740/// SecondOutputDimBound,
741/// ThirdOutputDimBound The parameters of the access relation.
742/// @return The specified access relation.
743__isl_give isl_map *getMatMulExt(isl_ctx *Ctx, unsigned FirstOutputDimBound,
744 unsigned SecondOutputDimBound,
745 unsigned ThirdOutputDimBound) {
746 auto *NewRelSpace = isl_space_alloc(Ctx, 0, 3, 3);
747 auto *extensionMap = isl_map_universe(NewRelSpace);
748 if (!FirstOutputDimBound)
749 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 0, 0);
750 else
751 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 0,
752 FirstOutputDimBound);
753 if (!SecondOutputDimBound)
754 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 1, 0);
755 else
756 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 1,
757 SecondOutputDimBound);
758 if (!ThirdOutputDimBound)
759 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 2, 0);
760 else
761 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 2,
762 ThirdOutputDimBound);
763 return extensionMap;
764}
765
Tobias Grosserc80d6972016-09-02 06:33:33 +0000766/// Create an access relation that is specific to the matrix
Roman Gareev1c892e92016-08-15 12:22:54 +0000767/// multiplication pattern.
768///
769/// Create an access relation of the following form:
770/// Stmt[O0, O1, O2]->[OI, OJ],
771/// where I is @p I, J is @J
772///
773/// @param Stmt The SCoP statement for which to generate the access relation.
774/// @param I The index of the input dimension that is mapped to the first output
775/// dimension.
776/// @param J The index of the input dimension that is mapped to the second
777/// output dimension.
778/// @return The specified access relation.
779__isl_give isl_map *
780getMatMulPatternOriginalAccessRelation(ScopStmt *Stmt, unsigned I, unsigned J) {
781 auto *AccessRelSpace = isl_space_alloc(Stmt->getIslCtx(), 0, 3, 2);
782 auto *AccessRel = isl_map_universe(AccessRelSpace);
783 AccessRel = isl_map_equate(AccessRel, isl_dim_in, I, isl_dim_out, 0);
784 AccessRel = isl_map_equate(AccessRel, isl_dim_in, J, isl_dim_out, 1);
785 AccessRel = isl_map_set_tuple_id(AccessRel, isl_dim_in, Stmt->getDomainId());
786 return AccessRel;
787}
788
Tobias Grosserc80d6972016-09-02 06:33:33 +0000789/// Identify the memory access that corresponds to the access to the second
790/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000791///
792/// Identify the memory access that corresponds to the access
793/// to the matrix B of the matrix multiplication C = A x B.
794///
795/// @param Stmt The SCoP statement that contains the memory accesses
796/// under consideration.
797/// @return The memory access of @p Stmt that corresponds to the access
798/// to the second operand of the matrix multiplication.
799MemoryAccess *identifyAccessA(ScopStmt *Stmt) {
800 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 0, 2);
801 return identifyAccessByAccessRelation(Stmt, OriginalRel);
802}
803
Tobias Grosserc80d6972016-09-02 06:33:33 +0000804/// Identify the memory access that corresponds to the access to the first
805/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000806///
807/// Identify the memory access that corresponds to the access
808/// to the matrix A of the matrix multiplication C = A x B.
809///
810/// @param Stmt The SCoP statement that contains the memory accesses
811/// under consideration.
812/// @return The memory access of @p Stmt that corresponds to the access
813/// to the first operand of the matrix multiplication.
814MemoryAccess *identifyAccessB(ScopStmt *Stmt) {
815 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 2, 1);
816 return identifyAccessByAccessRelation(Stmt, OriginalRel);
817}
818
Tobias Grosserc80d6972016-09-02 06:33:33 +0000819/// Create an access relation that is specific to
Roman Gareev1c892e92016-08-15 12:22:54 +0000820/// the matrix multiplication pattern.
821///
822/// Create an access relation of the following form:
Roman Gareev92c44602016-12-21 11:18:42 +0000823/// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
824/// where I is @p FirstDim, J is @p SecondDim.
Roman Gareev1c892e92016-08-15 12:22:54 +0000825///
826/// It can be used, for example, to create relations that helps to consequently
827/// access elements of operands of a matrix multiplication after creation of
828/// the BLIS micro and macro kernels.
829///
830/// @see ScheduleTreeOptimizer::createMicroKernel
831/// @see ScheduleTreeOptimizer::createMacroKernel
832///
833/// Subsequently, the described access relation is applied to the range of
834/// @p MapOldIndVar, that is used to map original induction variables to
835/// the ones, which are produced by schedule transformations. It helps to
836/// define relations using a new space and, at the same time, keep them
837/// in the original one.
838///
839/// @param MapOldIndVar The relation, which maps original induction variables
840/// to the ones, which are produced by schedule
841/// transformations.
Roman Gareev1c892e92016-08-15 12:22:54 +0000842/// @param FirstDim, SecondDim The input dimensions that are used to define
843/// the specified access relation.
844/// @return The specified access relation.
845__isl_give isl_map *getMatMulAccRel(__isl_take isl_map *MapOldIndVar,
Roman Gareev92c44602016-12-21 11:18:42 +0000846 unsigned FirstDim, unsigned SecondDim) {
Roman Gareev1c892e92016-08-15 12:22:54 +0000847 auto *Ctx = isl_map_get_ctx(MapOldIndVar);
Roman Gareev92c44602016-12-21 11:18:42 +0000848 auto *AccessRelSpace = isl_space_alloc(Ctx, 0, 9, 3);
849 auto *AccessRel = isl_map_universe(AccessRelSpace);
850 AccessRel = isl_map_equate(AccessRel, isl_dim_in, FirstDim, isl_dim_out, 0);
851 AccessRel = isl_map_equate(AccessRel, isl_dim_in, 5, isl_dim_out, 1);
852 AccessRel = isl_map_equate(AccessRel, isl_dim_in, SecondDim, isl_dim_out, 2);
Roman Gareev1c892e92016-08-15 12:22:54 +0000853 return isl_map_apply_range(MapOldIndVar, AccessRel);
854}
855
Roman Gareevb3224ad2016-09-14 06:26:09 +0000856__isl_give isl_schedule_node *
857createExtensionNode(__isl_take isl_schedule_node *Node,
858 __isl_take isl_map *ExtensionMap) {
859 auto *Extension = isl_union_map_from_map(ExtensionMap);
860 auto *NewNode = isl_schedule_node_from_extension(Extension);
861 return isl_schedule_node_graft_before(Node, NewNode);
862}
863
Tobias Grosserc80d6972016-09-02 06:33:33 +0000864/// Apply the packing transformation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000865///
866/// The packing transformation can be described as a data-layout
867/// transformation that requires to introduce a new array, copy data
868/// to the array, and change memory access locations of the compute kernel
869/// to reference the array.
870///
871/// @param Node The schedule node to be optimized.
872/// @param MapOldIndVar The relation, which maps original induction variables
873/// to the ones, which are produced by schedule
874/// transformations.
875/// @param MicroParams, MacroParams Parameters of the BLIS kernel
876/// to be taken into account.
877/// @return The optimized schedule node.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000878static __isl_give isl_schedule_node *optimizeDataLayoutMatrMulPattern(
879 __isl_take isl_schedule_node *Node, __isl_take isl_map *MapOldIndVar,
880 MicroKernelParamsTy MicroParams, MacroKernelParamsTy MacroParams) {
Roman Gareev2606c482016-12-15 12:35:59 +0000881 // Check whether memory accesses of the SCoP statement correspond to
882 // the matrix multiplication pattern and if this is true, obtain them.
Roman Gareev1c892e92016-08-15 12:22:54 +0000883 auto InputDimsId = isl_map_get_tuple_id(MapOldIndVar, isl_dim_in);
884 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
885 isl_id_free(InputDimsId);
886 MemoryAccess *MemAccessA = identifyAccessA(Stmt);
887 MemoryAccess *MemAccessB = identifyAccessB(Stmt);
888 if (!MemAccessA || !MemAccessB) {
889 isl_map_free(MapOldIndVar);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000890 return Node;
Roman Gareev1c892e92016-08-15 12:22:54 +0000891 }
Roman Gareev2606c482016-12-15 12:35:59 +0000892
893 // Create a copy statement that corresponds to the memory access to the
894 // matrix B, the second operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000895 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
896 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
897 Node = isl_schedule_node_parent(Node);
898 Node = isl_schedule_node_child(isl_schedule_node_band_split(Node, 2), 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000899 auto *AccRel = getMatMulAccRel(isl_map_copy(MapOldIndVar), 3, 7);
900 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
901 unsigned SecondDimSize = MacroParams.Kc;
902 unsigned ThirdDimSize = MicroParams.Nr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000903 auto *SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000904 MemAccessB->getElementType(), "Packed_B",
905 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000906 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000907 auto *OldAcc = MemAccessB->getAccessRelation();
908 MemAccessB->setNewAccessRelation(AccRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000909 auto *ExtMap =
Roman Gareev8babe1a2016-12-15 11:47:38 +0000910 getMatMulExt(Stmt->getIslCtx(), 0, MacroParams.Nc, MacroParams.Kc);
911 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
912 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
913 ExtMap = isl_map_project_out(ExtMap, isl_dim_in, 2, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000914 auto *Domain = Stmt->getDomain();
Roman Gareev2606c482016-12-15 12:35:59 +0000915
916 // Restrict the domains of the copy statements to only execute when also its
917 // originating statement is executed.
918 auto *DomainId = isl_set_get_tuple_id(Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000919 auto *NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev8babe1a2016-12-15 11:47:38 +0000920 OldAcc, MemAccessB->getAccessRelation(), isl_set_copy(Domain));
Roman Gareev2606c482016-12-15 12:35:59 +0000921 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, isl_id_copy(DomainId));
922 ExtMap = isl_map_intersect_range(ExtMap, isl_set_copy(Domain));
Roman Gareevb3224ad2016-09-14 06:26:09 +0000923 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
924 Node = createExtensionNode(Node, ExtMap);
Roman Gareev2606c482016-12-15 12:35:59 +0000925
926 // Create a copy statement that corresponds to the memory access
927 // to the matrix A, the first operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000928 Node = isl_schedule_node_child(Node, 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000929 AccRel = getMatMulAccRel(MapOldIndVar, 4, 6);
930 FirstDimSize = MacroParams.Mc / MicroParams.Mr;
931 ThirdDimSize = MicroParams.Mr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000932 SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000933 MemAccessA->getElementType(), "Packed_A",
934 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000935 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000936 OldAcc = MemAccessA->getAccessRelation();
937 MemAccessA->setNewAccessRelation(AccRel);
938 ExtMap = getMatMulExt(Stmt->getIslCtx(), MacroParams.Mc, 0, MacroParams.Kc);
939 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000940 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
941 NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev2606c482016-12-15 12:35:59 +0000942 OldAcc, MemAccessA->getAccessRelation(), isl_set_copy(Domain));
943
944 // Restrict the domains of the copy statements to only execute when also its
945 // originating statement is executed.
946 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, DomainId);
947 ExtMap = isl_map_intersect_range(ExtMap, Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000948 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
949 Node = createExtensionNode(Node, ExtMap);
950 Node = isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
951 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev1c892e92016-08-15 12:22:54 +0000952}
953
Tobias Grosserc80d6972016-09-02 06:33:33 +0000954/// Get a relation mapping induction variables produced by schedule
955/// transformations to the original ones.
Roman Gareev1c892e92016-08-15 12:22:54 +0000956///
957/// @param Node The schedule node produced as the result of creation
958/// of the BLIS kernels.
959/// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
960/// to be taken into account.
961/// @return The relation mapping original induction variables to the ones
962/// produced by schedule transformation.
963/// @see ScheduleTreeOptimizer::createMicroKernel
964/// @see ScheduleTreeOptimizer::createMacroKernel
965/// @see getMacroKernelParams
966__isl_give isl_map *
967getInductionVariablesSubstitution(__isl_take isl_schedule_node *Node,
968 MicroKernelParamsTy MicroKernelParams,
969 MacroKernelParamsTy MacroKernelParams) {
970 auto *Child = isl_schedule_node_get_child(Node, 0);
971 auto *UnMapOldIndVar = isl_schedule_node_get_prefix_schedule_union_map(Child);
972 isl_schedule_node_free(Child);
973 auto *MapOldIndVar = isl_map_from_union_map(UnMapOldIndVar);
974 if (isl_map_dim(MapOldIndVar, isl_dim_out) > 9)
975 MapOldIndVar =
976 isl_map_project_out(MapOldIndVar, isl_dim_out, 0,
977 isl_map_dim(MapOldIndVar, isl_dim_out) - 9);
978 return MapOldIndVar;
979}
980
Roman Gareev2cb4d132016-07-25 07:27:59 +0000981__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeMatMulPattern(
982 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
983 assert(TTI && "The target transform info should be provided.");
984 auto MicroKernelParams = getMicroKernelParams(TTI);
Roman Gareev3a18a932016-07-25 09:42:53 +0000985 auto MacroKernelParams = getMacroKernelParams(MicroKernelParams);
986 Node = createMacroKernel(Node, MacroKernelParams);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000987 Node = createMicroKernel(Node, MicroKernelParams);
Roman Gareev1c892e92016-08-15 12:22:54 +0000988 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
989 MacroKernelParams.Kc == 1)
990 return Node;
991 auto *MapOldIndVar = getInductionVariablesSubstitution(
992 Node, MicroKernelParams, MacroKernelParams);
993 if (!MapOldIndVar)
994 return Node;
Roman Gareevb3224ad2016-09-14 06:26:09 +0000995 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
996 MacroKernelParams);
Roman Gareev42402c92016-06-22 09:52:37 +0000997}
998
Roman Gareev9c3eb592016-05-28 16:17:58 +0000999bool ScheduleTreeOptimizer::isMatrMultPattern(
1000 __isl_keep isl_schedule_node *Node) {
1001 auto *PartialSchedule =
1002 isl_schedule_node_band_get_partial_schedule_union_map(Node);
Roman Gareev397a34a2016-06-22 12:11:30 +00001003 if (isl_schedule_node_band_n_member(Node) != 3 ||
1004 isl_union_map_n_map(PartialSchedule) != 1) {
1005 isl_union_map_free(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +00001006 return false;
1007 }
Roman Gareev397a34a2016-06-22 12:11:30 +00001008 auto *NewPartialSchedule = isl_map_from_union_map(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +00001009 NewPartialSchedule = circularShiftOutputDims(NewPartialSchedule);
1010 if (containsMatrMult(NewPartialSchedule)) {
1011 isl_map_free(NewPartialSchedule);
1012 return true;
1013 }
1014 isl_map_free(NewPartialSchedule);
1015 return false;
1016}
1017
1018__isl_give isl_schedule_node *
1019ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
1020 void *User) {
1021 if (!isTileableBandNode(Node))
1022 return Node;
1023
Roman Gareev42402c92016-06-22 09:52:37 +00001024 if (PMBasedOpts && User && isMatrMultPattern(Node)) {
Roman Gareev9c3eb592016-05-28 16:17:58 +00001025 DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
Roman Gareev42402c92016-06-22 09:52:37 +00001026 const llvm::TargetTransformInfo *TTI;
1027 TTI = static_cast<const llvm::TargetTransformInfo *>(User);
1028 Node = optimizeMatMulPattern(Node, TTI);
1029 }
Roman Gareev9c3eb592016-05-28 16:17:58 +00001030
1031 return standardBandOpts(Node, User);
1032}
1033
Tobias Grosser808cd692015-07-14 09:33:13 +00001034__isl_give isl_schedule *
Roman Gareev42402c92016-06-22 09:52:37 +00001035ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule,
1036 const llvm::TargetTransformInfo *TTI) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001037 isl_schedule_node *Root = isl_schedule_get_root(Schedule);
Roman Gareev42402c92016-06-22 09:52:37 +00001038 Root = optimizeScheduleNode(Root, TTI);
Tobias Grosser808cd692015-07-14 09:33:13 +00001039 isl_schedule_free(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001040 auto S = isl_schedule_node_get_schedule(Root);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001041 isl_schedule_node_free(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +00001042 return S;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001043}
1044
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001045__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
Roman Gareev42402c92016-06-22 09:52:37 +00001046 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
1047 Node = isl_schedule_node_map_descendant_bottom_up(
1048 Node, optimizeBand, const_cast<void *>(static_cast<const void *>(TTI)));
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001049 return Node;
1050}
1051
1052bool ScheduleTreeOptimizer::isProfitableSchedule(
Roman Gareevb3224ad2016-09-14 06:26:09 +00001053 Scop &S, __isl_keep isl_schedule *NewSchedule) {
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001054 // To understand if the schedule has been optimized we check if the schedule
1055 // has changed at all.
1056 // TODO: We can improve this by tracking if any necessarily beneficial
1057 // transformations have been performed. This can e.g. be tiling, loop
1058 // interchange, or ...) We can track this either at the place where the
1059 // transformation has been performed or, in case of automatic ILP based
1060 // optimizations, by comparing (yet to be defined) performance metrics
1061 // before/after the scheduling optimizer
1062 // (e.g., #stride-one accesses)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001063 if (S.containsExtensionNode(NewSchedule))
1064 return true;
1065 auto *NewScheduleMap = isl_schedule_get_map(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001066 isl_union_map *OldSchedule = S.getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001067 assert(OldSchedule && "Only IslScheduleOptimizer can insert extension nodes "
1068 "that make Scop::getSchedule() return nullptr.");
1069 bool changed = !isl_union_map_is_equal(OldSchedule, NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001070 isl_union_map_free(OldSchedule);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001071 isl_union_map_free(NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001072 return changed;
1073}
1074
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001075namespace {
1076class IslScheduleOptimizer : public ScopPass {
1077public:
1078 static char ID;
1079 explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
1080
1081 ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
1082
Tobias Grosserc80d6972016-09-02 06:33:33 +00001083 /// Optimize the schedule of the SCoP @p S.
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001084 bool runOnScop(Scop &S) override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001085
Tobias Grosserc80d6972016-09-02 06:33:33 +00001086 /// Print the new schedule for the SCoP @p S.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001087 void printScop(raw_ostream &OS, Scop &S) const override;
1088
Tobias Grosserc80d6972016-09-02 06:33:33 +00001089 /// Register all analyses and transformation required.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001090 void getAnalysisUsage(AnalysisUsage &AU) const override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001091
Tobias Grosserc80d6972016-09-02 06:33:33 +00001092 /// Release the internal memory.
Johannes Doerfert0f376302015-09-27 15:42:28 +00001093 void releaseMemory() override {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001094 isl_schedule_free(LastSchedule);
1095 LastSchedule = nullptr;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001096 }
Johannes Doerfert45be6442015-09-27 15:43:29 +00001097
1098private:
1099 isl_schedule *LastSchedule;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001100};
Tobias Grosser522478d2016-06-23 22:17:27 +00001101} // namespace
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001102
1103char IslScheduleOptimizer::ID = 0;
1104
Tobias Grosser73600b82011-10-08 00:30:40 +00001105bool IslScheduleOptimizer::runOnScop(Scop &S) {
Johannes Doerfert6f7921f2015-02-14 12:02:24 +00001106
1107 // Skip empty SCoPs but still allow code generation as it will delete the
1108 // loops present but not needed.
1109 if (S.getSize() == 0) {
1110 S.markAsOptimized();
1111 return false;
1112 }
1113
Hongbin Zheng2a798852016-03-03 08:15:33 +00001114 const Dependences &D =
1115 getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001116
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001117 if (!D.hasValidDependences())
Tobias Grosser38c36ea2014-02-23 15:15:44 +00001118 return false;
1119
Tobias Grosser28781422012-10-16 07:29:19 +00001120 isl_schedule_free(LastSchedule);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001121 LastSchedule = nullptr;
Tobias Grosser28781422012-10-16 07:29:19 +00001122
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001123 // Build input data.
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001124 int ValidityKinds =
1125 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001126 int ProximityKinds;
1127
1128 if (OptimizeDeps == "all")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001129 ProximityKinds =
1130 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001131 else if (OptimizeDeps == "raw")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001132 ProximityKinds = Dependences::TYPE_RAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001133 else {
1134 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001135 << " Falling back to optimizing all dependences.\n";
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001136 ProximityKinds =
1137 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001138 }
1139
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001140 isl_union_set *Domain = S.getDomains();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001141
Tobias Grosser98610ee2012-02-13 23:31:39 +00001142 if (!Domain)
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001143 return false;
1144
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001145 isl_union_map *Validity = D.getDependences(ValidityKinds);
1146 isl_union_map *Proximity = D.getDependences(ProximityKinds);
Tobias Grosser8a507022012-03-16 11:51:41 +00001147
Tobias Grossera26db472012-01-30 19:38:43 +00001148 // Simplify the dependences by removing the constraints introduced by the
1149 // domains. This can speed up the scheduling time significantly, as large
1150 // constant coefficients will be removed from the dependences. The
1151 // introduction of some additional dependences reduces the possible
1152 // transformations, but in most cases, such transformation do not seem to be
1153 // interesting anyway. In some cases this option may stop the scheduler to
1154 // find any schedule.
1155 if (SimplifyDeps == "yes") {
Tobias Grosser00383a72012-02-14 14:02:44 +00001156 Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
1157 Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001158 Proximity =
1159 isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
Tobias Grosser00383a72012-02-14 14:02:44 +00001160 Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
Tobias Grossera26db472012-01-30 19:38:43 +00001161 } else if (SimplifyDeps != "no") {
1162 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
1163 "or 'no'. Falling back to default: 'yes'\n";
1164 }
1165
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001166 DEBUG(dbgs() << "\n\nCompute schedule from: ");
Tobias Grosser01aea582014-10-22 23:16:28 +00001167 DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
1168 DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
1169 DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001170
Michael Krusec59f22c2015-06-18 16:45:40 +00001171 unsigned IslSerializeSCCs;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001172
1173 if (FusionStrategy == "max") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001174 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001175 } else if (FusionStrategy == "min") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001176 IslSerializeSCCs = 1;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001177 } else {
1178 errs() << "warning: Unknown fusion strategy. Falling back to maximal "
1179 "fusion.\n";
Michael Krusec59f22c2015-06-18 16:45:40 +00001180 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001181 }
1182
Tobias Grosser95e860c2012-01-30 19:38:54 +00001183 int IslMaximizeBands;
1184
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001185 if (MaximizeBandDepth == "yes") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001186 IslMaximizeBands = 1;
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001187 } else if (MaximizeBandDepth == "no") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001188 IslMaximizeBands = 0;
1189 } else {
1190 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
1191 " or 'no'. Falling back to default: 'yes'\n";
1192 IslMaximizeBands = 1;
1193 }
1194
Michael Kruse315aa322016-05-02 11:35:27 +00001195 int IslOuterCoincidence;
1196
1197 if (OuterCoincidence == "yes") {
1198 IslOuterCoincidence = 1;
1199 } else if (OuterCoincidence == "no") {
1200 IslOuterCoincidence = 0;
1201 } else {
1202 errs() << "warning: Option -polly-opt-outer-coincidence should either be "
1203 "'yes' or 'no'. Falling back to default: 'no'\n";
1204 IslOuterCoincidence = 0;
1205 }
1206
Tobias Grosseraf149932016-06-30 20:42:56 +00001207 isl_ctx *Ctx = S.getIslCtx();
Tobias Grosser42152ff2012-01-30 19:38:47 +00001208
Tobias Grosseraf149932016-06-30 20:42:56 +00001209 isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
1210 isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs);
1211 isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
1212 isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
1213 isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
1214 isl_options_set_tile_scale_tile_loops(Ctx, 0);
1215
Tobias Grosser3898a042016-06-30 20:42:58 +00001216 auto OnErrorStatus = isl_options_get_on_error(Ctx);
Tobias Grosseraf149932016-06-30 20:42:56 +00001217 isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
Tobias Grossera38c9242014-01-26 19:36:28 +00001218
1219 isl_schedule_constraints *ScheduleConstraints;
1220 ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
1221 ScheduleConstraints =
1222 isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
1223 ScheduleConstraints = isl_schedule_constraints_set_validity(
1224 ScheduleConstraints, isl_union_map_copy(Validity));
1225 ScheduleConstraints =
1226 isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
Tobias Grosser00383a72012-02-14 14:02:44 +00001227 isl_schedule *Schedule;
Tobias Grossera38c9242014-01-26 19:36:28 +00001228 Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
Tobias Grosser3898a042016-06-30 20:42:58 +00001229 isl_options_set_on_error(Ctx, OnErrorStatus);
Tobias Grosser42152ff2012-01-30 19:38:47 +00001230
1231 // In cases the scheduler is not able to optimize the code, we just do not
1232 // touch the schedule.
Tobias Grosser98610ee2012-02-13 23:31:39 +00001233 if (!Schedule)
Tobias Grosser42152ff2012-01-30 19:38:47 +00001234 return false;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001235
Tobias Grosser97d87452015-05-30 06:46:59 +00001236 DEBUG({
Tobias Grosseraf149932016-06-30 20:42:56 +00001237 auto *P = isl_printer_to_str(Ctx);
Tobias Grosser97d87452015-05-30 06:46:59 +00001238 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1239 P = isl_printer_print_schedule(P, Schedule);
Michael Kruse79c01732016-12-12 14:51:06 +00001240 auto *str = isl_printer_get_str(P);
1241 dbgs() << "NewScheduleTree: \n" << str << "\n";
1242 free(str);
Tobias Grosser97d87452015-05-30 06:46:59 +00001243 isl_printer_free(P);
1244 });
Tobias Grosser4d63b9d2012-02-20 08:41:21 +00001245
Roman Gareev42402c92016-06-22 09:52:37 +00001246 Function &F = S.getFunction();
1247 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1248 isl_schedule *NewSchedule =
1249 ScheduleTreeOptimizer::optimizeSchedule(Schedule, TTI);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001250
Roman Gareevb3224ad2016-09-14 06:26:09 +00001251 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule)) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001252 isl_schedule_free(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001253 return false;
1254 }
1255
Tobias Grosser808cd692015-07-14 09:33:13 +00001256 S.setScheduleTree(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001257 S.markAsOptimized();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001258
Roman Gareev5f99f862016-08-21 11:20:39 +00001259 if (OptimizedScops)
1260 S.dump();
1261
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001262 return false;
1263}
1264
Johannes Doerfert3fe584d2015-03-01 18:40:25 +00001265void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
Tobias Grosser28781422012-10-16 07:29:19 +00001266 isl_printer *p;
1267 char *ScheduleStr;
1268
1269 OS << "Calculated schedule:\n";
1270
1271 if (!LastSchedule) {
1272 OS << "n/a\n";
1273 return;
1274 }
1275
1276 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
1277 p = isl_printer_print_schedule(p, LastSchedule);
1278 ScheduleStr = isl_printer_get_str(p);
1279 isl_printer_free(p);
1280
1281 OS << ScheduleStr << "\n";
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001282}
1283
Tobias Grosser73600b82011-10-08 00:30:40 +00001284void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001285 ScopPass::getAnalysisUsage(AU);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001286 AU.addRequired<DependenceInfo>();
Roman Gareev42402c92016-06-22 09:52:37 +00001287 AU.addRequired<TargetTransformInfoWrapperPass>();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001288}
1289
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001290Pass *polly::createIslScheduleOptimizerPass() {
Tobias Grosser73600b82011-10-08 00:30:40 +00001291 return new IslScheduleOptimizer();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001292}
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001293
1294INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
1295 "Polly - Optimize schedule of SCoP", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001296INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Johannes Doerfert99191c72016-05-31 09:41:04 +00001297INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
Roman Gareev42402c92016-06-22 09:52:37 +00001298INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001299INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
1300 "Polly - Optimize schedule of SCoP", false, false)