blob: a4fe301156c762ac16d3e62f3344a7f7cbfa2000 [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 Grosser21a059a2017-01-16 14:08:10 +0000177static cl::list<int>
178 FirstLevelTileSizes("polly-tile-sizes",
179 cl::desc("A tile size for each loop dimension, filled "
Tobias Grosser04832712015-08-20 13:45:02 +0000180 "with --polly-default-tile-size"),
Tobias Grosser21a059a2017-01-16 14:08:10 +0000181 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
182 cl::cat(PollyCategory));
Tobias Grosser04832712015-08-20 13:45:02 +0000183
184static cl::opt<bool>
185 SecondLevelTiling("polly-2nd-level-tiling",
186 cl::desc("Enable a 2nd level loop of loop tiling"),
187 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
188
189static cl::opt<int> SecondLevelDefaultTileSize(
190 "polly-2nd-level-default-tile-size",
191 cl::desc("The default 2nd-level tile size (if not enough were provided by"
192 " --polly-2nd-level-tile-sizes)"),
193 cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
194
195static cl::list<int>
196 SecondLevelTileSizes("polly-2nd-level-tile-sizes",
197 cl::desc("A tile size for each loop dimension, filled "
198 "with --polly-default-tile-size"),
199 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
200 cl::cat(PollyCategory));
201
Tobias Grosser42e24892015-08-20 13:45:05 +0000202static cl::opt<bool> RegisterTiling("polly-register-tiling",
203 cl::desc("Enable register tiling"),
204 cl::init(false), cl::ZeroOrMore,
205 cl::cat(PollyCategory));
206
207static cl::opt<int> RegisterDefaultTileSize(
208 "polly-register-tiling-default-tile-size",
209 cl::desc("The default register tile size (if not enough were provided by"
210 " --polly-register-tile-sizes)"),
211 cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
212
Roman Gareevbe5299a2016-12-21 12:51:12 +0000213static cl::opt<int> PollyPatternMatchingNcQuotient(
214 "polly-pattern-matching-nc-quotient",
215 cl::desc("Quotient that is obtained by dividing Nc, the parameter of the"
216 "macro-kernel, by Nr, the parameter of the micro-kernel"),
217 cl::Hidden, cl::init(256), cl::ZeroOrMore, cl::cat(PollyCategory));
218
Tobias Grosser42e24892015-08-20 13:45:05 +0000219static cl::list<int>
220 RegisterTileSizes("polly-register-tile-sizes",
221 cl::desc("A tile size for each loop dimension, filled "
222 "with --polly-register-tile-size"),
223 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
224 cl::cat(PollyCategory));
225
Roman Gareev9c3eb592016-05-28 16:17:58 +0000226static cl::opt<bool>
227 PMBasedOpts("polly-pattern-matching-based-opts",
228 cl::desc("Perform optimizations based on pattern matching"),
229 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
230
Roman Gareev5f99f862016-08-21 11:20:39 +0000231static cl::opt<bool> OptimizedScops(
232 "polly-optimized-scops",
233 cl::desc("Polly - Dump polyhedral description of Scops optimized with "
234 "the isl scheduling optimizer and the set of post-scheduling "
235 "transformations is applied on the schedule tree"),
236 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
237
Tobias Grosserc80d6972016-09-02 06:33:33 +0000238/// Create an isl_union_set, which describes the isolate option based on
239/// IsoalteDomain.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000240///
241/// @param IsolateDomain An isl_set whose last dimension is the only one that
242/// should belong to the current band node.
243static __isl_give isl_union_set *
244getIsolateOptions(__isl_take isl_set *IsolateDomain) {
245 auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
246 auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
247 IsolateRelation = isl_map_move_dims(IsolateRelation, isl_dim_out, 0,
248 isl_dim_in, Dims - 1, 1);
249 auto *IsolateOption = isl_map_wrap(IsolateRelation);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000250 auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000251 return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
252}
253
Tobias Grosserc80d6972016-09-02 06:33:33 +0000254/// Create an isl_union_set, which describes the atomic option for the dimension
255/// of the current node.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000256///
257/// It may help to reduce the size of generated code.
258///
259/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
260static __isl_give isl_union_set *getAtomicOptions(__isl_take isl_ctx *Ctx) {
261 auto *Space = isl_space_set_alloc(Ctx, 0, 1);
262 auto *AtomicOption = isl_set_universe(Space);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000263 auto *Id = isl_id_alloc(Ctx, "atomic", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000264 return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
265}
266
Tobias Grosserc80d6972016-09-02 06:33:33 +0000267/// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000268///
269/// @param Set A set, which should be modified.
270/// @param VectorWidth A parameter, which determines the constraint.
271static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
272 int VectorWidth) {
273 auto Dims = isl_set_dim(Set, isl_dim_set);
274 auto Space = isl_set_get_space(Set);
275 auto *LocalSpace = isl_local_space_from_space(Space);
276 auto *ExtConstr =
277 isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
278 ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
279 ExtConstr =
280 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
281 Set = isl_set_add_constraint(Set, ExtConstr);
282 ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
283 ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
284 ExtConstr =
285 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
286 return isl_set_add_constraint(Set, ExtConstr);
287}
288
Tobias Grosserc80d6972016-09-02 06:33:33 +0000289/// Build the desired set of partial tile prefixes.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000290///
291/// We build a set of partial tile prefixes, which are prefixes of the vector
292/// loop that have exactly VectorWidth iterations.
293///
294/// 1. Get all prefixes of the vector loop.
295/// 2. Extend it to a set, which has exactly VectorWidth iterations for
296/// any prefix from the set that was built on the previous step.
297/// 3. Subtract loop domain from it, project out the vector loop dimension and
Roman Gareev76614d32016-05-31 11:22:21 +0000298/// get a set of prefixes, which don't have exactly VectorWidth iterations.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000299/// 4. Subtract it from all prefixes of the vector loop and get the desired
300/// set.
301///
302/// @param ScheduleRange A range of a map, which describes a prefix schedule
303/// relation.
304static __isl_give isl_set *
305getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
306 auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
307 auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
308 isl_dim_set, Dims - 1, 1);
309 auto *ExtentPrefixes =
310 isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
311 ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
312 auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
313 BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
314 return isl_set_subtract(LoopPrefixes, BadPrefixes);
315}
316
317__isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
318 __isl_take isl_schedule_node *Node, int VectorWidth) {
319 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
320 Node = isl_schedule_node_child(Node, 0);
321 Node = isl_schedule_node_child(Node, 0);
322 auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
323 auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
324 auto *ScheduleRange = isl_map_range(ScheduleRelation);
325 auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
326 auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
327 auto *IsolateOption = getIsolateOptions(IsolateDomain);
328 Node = isl_schedule_node_parent(Node);
329 Node = isl_schedule_node_parent(Node);
330 auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
331 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
332 return Node;
333}
334
Tobias Grosserb241d922015-07-28 18:03:36 +0000335__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000336ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
337 unsigned DimToVectorize,
338 int VectorWidth) {
Tobias Grosserb241d922015-07-28 18:03:36 +0000339 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
Tobias Grosserc6699b72011-06-30 20:29:13 +0000340
Tobias Grosserb241d922015-07-28 18:03:36 +0000341 auto Space = isl_schedule_node_band_get_space(Node);
342 auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
343 isl_space_free(Space);
344 assert(DimToVectorize < ScheduleDimensions);
Tobias Grosserf5338802011-10-06 00:03:35 +0000345
Tobias Grosserb241d922015-07-28 18:03:36 +0000346 if (DimToVectorize > 0) {
347 Node = isl_schedule_node_band_split(Node, DimToVectorize);
348 Node = isl_schedule_node_child(Node, 0);
349 }
350 if (DimToVectorize < ScheduleDimensions - 1)
351 Node = isl_schedule_node_band_split(Node, 1);
352 Space = isl_schedule_node_band_get_space(Node);
353 auto Sizes = isl_multi_val_zero(Space);
354 auto Ctx = isl_schedule_node_get_ctx(Node);
355 Sizes =
356 isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
357 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000358 Node = isolateFullPartialTiles(Node, VectorWidth);
Tobias Grosserb241d922015-07-28 18:03:36 +0000359 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser42e24892015-08-20 13:45:05 +0000360 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
361 // we will have troubles to match it in the backend.
362 Node = isl_schedule_node_band_set_ast_build_options(
Tobias Grosserfc490a92015-08-20 19:08:16 +0000363 Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
364 Node = isl_schedule_node_band_sink(Node);
Tobias Grosserb241d922015-07-28 18:03:36 +0000365 Node = isl_schedule_node_child(Node, 0);
Roman Gareev11001e12016-02-23 09:00:13 +0000366 if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
367 Node = isl_schedule_node_parent(Node);
368 isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
369 Node = isl_schedule_node_insert_mark(Node, LoopMarker);
Tobias Grosserb241d922015-07-28 18:03:36 +0000370 return Node;
Tobias Grosserc6699b72011-06-30 20:29:13 +0000371}
372
Tobias Grosserd891b542015-08-20 12:16:23 +0000373__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000374ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
375 const char *Identifier, ArrayRef<int> TileSizes,
376 int DefaultTileSize) {
Tobias Grosser9bdea572015-08-20 12:22:37 +0000377 auto Ctx = isl_schedule_node_get_ctx(Node);
378 auto Space = isl_schedule_node_band_get_space(Node);
379 auto Dims = isl_space_dim(Space, isl_dim_set);
380 auto Sizes = isl_multi_val_zero(Space);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000381 std::string IdentifierString(Identifier);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000382 for (unsigned i = 0; i < Dims; i++) {
383 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
384 Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
385 }
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000386 auto TileLoopMarkerStr = IdentifierString + " - Tiles";
387 isl_id *TileLoopMarker =
388 isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
389 Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
390 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000391 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000392 Node = isl_schedule_node_child(Node, 0);
393 auto PointLoopMarkerStr = IdentifierString + " - Points";
394 isl_id *PointLoopMarker =
395 isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
396 Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
397 Node = isl_schedule_node_child(Node, 0);
398 return Node;
Tobias Grosser9bdea572015-08-20 12:22:37 +0000399}
400
Roman Gareevb17b9a82016-06-12 17:20:05 +0000401__isl_give isl_schedule_node *
402ScheduleTreeOptimizer::applyRegisterTiling(__isl_take isl_schedule_node *Node,
403 llvm::ArrayRef<int> TileSizes,
404 int DefaultTileSize) {
405 auto *Ctx = isl_schedule_node_get_ctx(Node);
406 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
407 Node = isl_schedule_node_band_set_ast_build_options(
408 Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
409 return Node;
410}
411
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000412bool ScheduleTreeOptimizer::isTileableBandNode(
Tobias Grosser862b9b52015-08-20 12:32:45 +0000413 __isl_keep isl_schedule_node *Node) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000414 if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000415 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000416
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000417 if (isl_schedule_node_n_children(Node) != 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000418 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000419
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000420 if (!isl_schedule_node_band_get_permutable(Node))
Tobias Grosser862b9b52015-08-20 12:32:45 +0000421 return false;
Tobias Grosser44f19ac2011-07-05 22:15:53 +0000422
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000423 auto Space = isl_schedule_node_band_get_space(Node);
424 auto Dims = isl_space_dim(Space, isl_dim_set);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000425 isl_space_free(Space);
Tobias Grosserde68cc92011-06-30 20:01:02 +0000426
Tobias Grosser9bdea572015-08-20 12:22:37 +0000427 if (Dims <= 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000428 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000429
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000430 auto Child = isl_schedule_node_get_child(Node, 0);
431 auto Type = isl_schedule_node_get_type(Child);
432 isl_schedule_node_free(Child);
433
Tobias Grosser9bdea572015-08-20 12:22:37 +0000434 if (Type != isl_schedule_node_leaf)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000435 return false;
436
437 return true;
438}
439
440__isl_give isl_schedule_node *
Roman Gareev9c3eb592016-05-28 16:17:58 +0000441ScheduleTreeOptimizer::standardBandOpts(__isl_take isl_schedule_node *Node,
442 void *User) {
Tobias Grosser04832712015-08-20 13:45:02 +0000443 if (FirstLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000444 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
445 FirstLevelDefaultTileSize);
Tobias Grosser04832712015-08-20 13:45:02 +0000446
447 if (SecondLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000448 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
449 SecondLevelDefaultTileSize);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000450
Roman Gareevb17b9a82016-06-12 17:20:05 +0000451 if (RegisterTiling)
452 Node =
453 applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
Tobias Grosser42e24892015-08-20 13:45:05 +0000454
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000455 if (PollyVectorizerChoice == VECTORIZER_NONE)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000456 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000457
Tobias Grosser862b9b52015-08-20 12:32:45 +0000458 auto Space = isl_schedule_node_band_get_space(Node);
459 auto Dims = isl_space_dim(Space, isl_dim_set);
460 isl_space_free(Space);
461
Tobias Grosserb241d922015-07-28 18:03:36 +0000462 for (int i = Dims - 1; i >= 0; i--)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000463 if (isl_schedule_node_band_member_get_coincident(Node, i)) {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000464 Node = prevectSchedBand(Node, i, PrevectorWidth);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000465 break;
466 }
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000467
Tobias Grosserf10f4632015-08-19 08:03:37 +0000468 return Node;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000469}
470
Tobias Grosserc80d6972016-09-02 06:33:33 +0000471/// Check whether output dimensions of the map rely on the specified input
472/// dimension.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000473///
474/// @param IslMap The isl map to be considered.
475/// @param DimNum The number of an input dimension to be checked.
476static bool isInputDimUsed(__isl_take isl_map *IslMap, unsigned DimNum) {
477 auto *CheckedAccessRelation =
478 isl_map_project_out(isl_map_copy(IslMap), isl_dim_in, DimNum, 1);
479 CheckedAccessRelation =
480 isl_map_insert_dims(CheckedAccessRelation, isl_dim_in, DimNum, 1);
481 auto *InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
482 CheckedAccessRelation =
483 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_in, InputDimsId);
484 InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_out);
485 CheckedAccessRelation =
486 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_out, InputDimsId);
487 auto res = !isl_map_is_equal(CheckedAccessRelation, IslMap);
488 isl_map_free(CheckedAccessRelation);
489 isl_map_free(IslMap);
490 return res;
491}
492
Tobias Grosserc80d6972016-09-02 06:33:33 +0000493/// Check if the SCoP statement could probably be optimized with analytical
494/// modeling.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000495///
496/// containsMatrMult tries to determine whether the following conditions
497/// are true:
498/// 1. all memory accesses of the statement will have stride 0 or 1,
499/// if we interchange loops (switch the variable used in the inner
500/// loop to the outer loop).
501/// 2. all memory accesses of the statement except from the last one, are
502/// read memory access and the last one is write memory access.
Roman Gareev76614d32016-05-31 11:22:21 +0000503/// 3. all subscripts of the last memory access of the statement don't contain
Roman Gareev9c3eb592016-05-28 16:17:58 +0000504/// the variable used in the inner loop.
505///
506/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
507/// to check.
508static bool containsMatrMult(__isl_keep isl_map *PartialSchedule) {
509 auto InputDimsId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
510 auto *ScpStmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
511 isl_id_free(InputDimsId);
512 if (ScpStmt->size() <= 1)
513 return false;
514 auto MemA = ScpStmt->begin();
515 for (unsigned i = 0; i < ScpStmt->size() - 2 && MemA != ScpStmt->end();
516 i++, MemA++)
Roman Gareev76614d32016-05-31 11:22:21 +0000517 if (!(*MemA)->isRead() ||
518 ((*MemA)->isArrayKind() &&
519 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000520 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule)))))
521 return false;
522 MemA++;
Roman Gareev76614d32016-05-31 11:22:21 +0000523 if (!(*MemA)->isWrite() || !(*MemA)->isArrayKind() ||
524 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000525 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule))))
526 return false;
527 auto DimNum = isl_map_dim(PartialSchedule, isl_dim_in);
528 return !isInputDimUsed((*MemA)->getAccessRelation(), DimNum - 1);
529}
530
Tobias Grosserc80d6972016-09-02 06:33:33 +0000531/// Circular shift of output dimensions of the integer map.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000532///
533/// @param IslMap The isl map to be modified.
534static __isl_give isl_map *circularShiftOutputDims(__isl_take isl_map *IslMap) {
Roman Gareev9c3eb592016-05-28 16:17:58 +0000535 auto DimNum = isl_map_dim(IslMap, isl_dim_out);
Roman Gareev4b8c7ae2016-06-03 18:46:29 +0000536 if (DimNum == 0)
537 return IslMap;
538 auto InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
Roman Gareev9c3eb592016-05-28 16:17:58 +0000539 IslMap = isl_map_move_dims(IslMap, isl_dim_in, 0, isl_dim_out, DimNum - 1, 1);
540 IslMap = isl_map_move_dims(IslMap, isl_dim_out, 0, isl_dim_in, 0, 1);
541 return isl_map_set_tuple_id(IslMap, isl_dim_in, InputDimsId);
542}
543
Tobias Grosserc80d6972016-09-02 06:33:33 +0000544/// Permute two dimensions of the band node.
Roman Gareev3a18a932016-07-25 09:42:53 +0000545///
546/// Permute FirstDim and SecondDim dimensions of the Node.
547///
548/// @param Node The band node to be modified.
549/// @param FirstDim The first dimension to be permuted.
550/// @param SecondDim The second dimension to be permuted.
551static __isl_give isl_schedule_node *
552permuteBandNodeDimensions(__isl_take isl_schedule_node *Node, unsigned FirstDim,
553 unsigned SecondDim) {
554 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band &&
555 isl_schedule_node_band_n_member(Node) > std::max(FirstDim, SecondDim));
556 auto PartialSchedule = isl_schedule_node_band_get_partial_schedule(Node);
557 auto PartialScheduleFirstDim =
558 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, FirstDim);
559 auto PartialScheduleSecondDim =
560 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, SecondDim);
561 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
562 PartialSchedule, SecondDim, PartialScheduleFirstDim);
563 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
564 PartialSchedule, FirstDim, PartialScheduleSecondDim);
565 Node = isl_schedule_node_delete(Node);
566 Node = isl_schedule_node_insert_partial_schedule(Node, PartialSchedule);
567 return Node;
568}
569
Roman Gareev2cb4d132016-07-25 07:27:59 +0000570__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMicroKernel(
571 __isl_take isl_schedule_node *Node, MicroKernelParamsTy MicroKernelParams) {
Roman Gareev8babe1a2016-12-15 11:47:38 +0000572 applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr}, 1);
573 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
574 Node = permuteBandNodeDimensions(Node, 0, 1);
575 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000576}
577
Roman Gareev3a18a932016-07-25 09:42:53 +0000578__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMacroKernel(
579 __isl_take isl_schedule_node *Node, MacroKernelParamsTy MacroKernelParams) {
580 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
581 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
582 MacroKernelParams.Kc == 1)
583 return Node;
584 Node = tileNode(
585 Node, "1st level tiling",
586 {MacroKernelParams.Mc, MacroKernelParams.Nc, MacroKernelParams.Kc}, 1);
587 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
588 Node = permuteBandNodeDimensions(Node, 1, 2);
Roman Gareev8babe1a2016-12-15 11:47:38 +0000589 Node = permuteBandNodeDimensions(Node, 0, 2);
Roman Gareev3a18a932016-07-25 09:42:53 +0000590 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
591}
592
Roman Gareev2cb4d132016-07-25 07:27:59 +0000593/// Get parameters of the BLIS micro kernel.
594///
595/// We choose the Mr and Nr parameters of the micro kernel to be large enough
596/// such that no stalls caused by the combination of latencies and dependencies
597/// are introduced during the updates of the resulting matrix of the matrix
598/// multiplication. However, they should also be as small as possible to
599/// release more registers for entries of multiplied matrices.
600///
601/// @param TTI Target Transform Info.
602/// @return The structure of type MicroKernelParamsTy.
603/// @see MicroKernelParamsTy
604static struct MicroKernelParamsTy
605getMicroKernelParams(const llvm::TargetTransformInfo *TTI) {
Roman Gareev42402c92016-06-22 09:52:37 +0000606 assert(TTI && "The target transform info should be provided.");
Roman Gareev2cb4d132016-07-25 07:27:59 +0000607
Roman Gareev42402c92016-06-22 09:52:37 +0000608 // Nvec - Number of double-precision floating-point numbers that can be hold
609 // by a vector register. Use 2 by default.
Tobias Grosser67e94fb2017-01-14 07:14:54 +0000610 long RegisterBitwidth = VectorRegisterBitwidth;
611
612 if (RegisterBitwidth == -1)
613 RegisterBitwidth = TTI->getRegisterBitWidth(true);
614 auto Nvec = RegisterBitwidth / 64;
Roman Gareev42402c92016-06-22 09:52:37 +0000615 if (Nvec == 0)
616 Nvec = 2;
617 int Nr =
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000618 ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec;
619 int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000620 return {Mr, Nr};
621}
622
Roman Gareev3a18a932016-07-25 09:42:53 +0000623/// Get parameters of the BLIS macro kernel.
624///
625/// During the computation of matrix multiplication, blocks of partitioned
626/// matrices are mapped to different layers of the memory hierarchy.
627/// To optimize data reuse, blocks should be ideally kept in cache between
628/// iterations. Since parameters of the macro kernel determine sizes of these
629/// blocks, there are upper and lower bounds on these parameters.
630///
631/// @param MicroKernelParams Parameters of the micro-kernel
632/// to be taken into account.
633/// @return The structure of type MacroKernelParamsTy.
634/// @see MacroKernelParamsTy
635/// @see MicroKernelParamsTy
636static struct MacroKernelParamsTy
637getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams) {
638 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
639 // it requires information about the first two levels of a cache to determine
640 // all the parameters of a macro-kernel. It also checks that an associativity
641 // degree of a cache level is greater than two. Otherwise, another algorithm
642 // for determination of the parameters should be used.
643 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
Roman Gareev1c2927b2016-12-25 16:32:28 +0000644 FirstCacheLevelSize > 0 && SecondCacheLevelSize > 0 &&
645 FirstCacheLevelAssociativity > 2 && SecondCacheLevelAssociativity > 2))
Roman Gareev3a18a932016-07-25 09:42:53 +0000646 return {1, 1, 1};
Roman Gareevbe5299a2016-12-21 12:51:12 +0000647 // The quotient should be greater than zero.
648 if (PollyPatternMatchingNcQuotient <= 0)
649 return {1, 1, 1};
Roman Gareev15db81e2016-12-15 12:00:57 +0000650 int Car = floor(
Roman Gareev1c2927b2016-12-25 16:32:28 +0000651 (FirstCacheLevelAssociativity - 1) /
Roman Gareev8babe1a2016-12-15 11:47:38 +0000652 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
Roman Gareev1c2927b2016-12-25 16:32:28 +0000653 int Kc = (Car * FirstCacheLevelSize) /
654 (MicroKernelParams.Mr * FirstCacheLevelAssociativity * 8);
655 double Cac = static_cast<double>(Kc * 8 * SecondCacheLevelAssociativity) /
656 SecondCacheLevelSize;
657 int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac);
Roman Gareevbe5299a2016-12-21 12:51:12 +0000658 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
Roman Gareev3a18a932016-07-25 09:42:53 +0000659 return {Mc, Nc, Kc};
660}
661
Tobias Grosserc80d6972016-09-02 06:33:33 +0000662/// Identify a memory access through the shape of its memory access relation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000663///
664/// Identify the unique memory access in @p Stmt, that has an access relation
665/// equal to @p ExpectedAccessRelation.
666///
667/// @param Stmt The SCoP statement that contains the memory accesses under
668/// consideration.
669/// @param ExpectedAccessRelation The access relation that identifies
670/// the memory access.
671/// @return The memory access of @p Stmt whose memory access relation is equal
672/// to @p ExpectedAccessRelation. nullptr in case there is no or more
673/// than one such access.
674MemoryAccess *
675identifyAccessByAccessRelation(ScopStmt *Stmt,
676 __isl_take isl_map *ExpectedAccessRelation) {
677 if (isl_map_has_tuple_id(ExpectedAccessRelation, isl_dim_out))
678 ExpectedAccessRelation =
679 isl_map_reset_tuple_id(ExpectedAccessRelation, isl_dim_out);
680 MemoryAccess *IdentifiedAccess = nullptr;
681 for (auto *Access : *Stmt) {
682 auto *AccessRelation = Access->getAccessRelation();
683 AccessRelation = isl_map_reset_tuple_id(AccessRelation, isl_dim_out);
684 if (isl_map_is_equal(ExpectedAccessRelation, AccessRelation)) {
685 if (IdentifiedAccess) {
686 isl_map_free(AccessRelation);
687 isl_map_free(ExpectedAccessRelation);
688 return nullptr;
689 }
690 IdentifiedAccess = Access;
691 }
692 isl_map_free(AccessRelation);
693 }
694 isl_map_free(ExpectedAccessRelation);
695 return IdentifiedAccess;
696}
697
Roman Gareevb3224ad2016-09-14 06:26:09 +0000698/// Add constrains to @Dim dimension of @p ExtMap.
699///
700/// If @ExtMap has the following form [O0, O1, O2]->[I1, I2, I3],
701/// the following constraint will be added
702/// Bound * OM <= IM <= Bound * (OM + 1) - 1,
703/// where M is @p Dim and Bound is @p Bound.
704///
705/// @param ExtMap The isl map to be modified.
706/// @param Dim The output dimension to be modfied.
707/// @param Bound The value that is used to specify the constraint.
708/// @return The modified isl map
709__isl_give isl_map *
710addExtensionMapMatMulDimConstraint(__isl_take isl_map *ExtMap, unsigned Dim,
711 unsigned Bound) {
712 assert(Bound != 0);
713 auto *ExtMapSpace = isl_map_get_space(ExtMap);
714 auto *ConstrSpace = isl_local_space_from_space(ExtMapSpace);
715 auto *Constr =
716 isl_constraint_alloc_inequality(isl_local_space_copy(ConstrSpace));
717 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, 1);
718 Constr =
719 isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound * (-1));
720 ExtMap = isl_map_add_constraint(ExtMap, Constr);
721 Constr = isl_constraint_alloc_inequality(ConstrSpace);
722 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, -1);
723 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound);
724 Constr = isl_constraint_set_constant_si(Constr, Bound - 1);
725 return isl_map_add_constraint(ExtMap, Constr);
726}
727
728/// Create an access relation that is specific for matrix multiplication
729/// pattern.
730///
731/// Create an access relation of the following form:
732/// { [O0, O1, O2]->[I1, I2, I3] :
733/// FirstOutputDimBound * O0 <= I1 <= FirstOutputDimBound * (O0 + 1) - 1
734/// and SecondOutputDimBound * O1 <= I2 <= SecondOutputDimBound * (O1 + 1) - 1
735/// and ThirdOutputDimBound * O2 <= I3 <= ThirdOutputDimBound * (O2 + 1) - 1}
736/// where FirstOutputDimBound is @p FirstOutputDimBound,
737/// SecondOutputDimBound is @p SecondOutputDimBound,
738/// ThirdOutputDimBound is @p ThirdOutputDimBound
739///
740/// @param Ctx The isl context.
741/// @param FirstOutputDimBound,
742/// SecondOutputDimBound,
743/// ThirdOutputDimBound The parameters of the access relation.
744/// @return The specified access relation.
745__isl_give isl_map *getMatMulExt(isl_ctx *Ctx, unsigned FirstOutputDimBound,
746 unsigned SecondOutputDimBound,
747 unsigned ThirdOutputDimBound) {
748 auto *NewRelSpace = isl_space_alloc(Ctx, 0, 3, 3);
749 auto *extensionMap = isl_map_universe(NewRelSpace);
750 if (!FirstOutputDimBound)
751 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 0, 0);
752 else
753 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 0,
754 FirstOutputDimBound);
755 if (!SecondOutputDimBound)
756 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 1, 0);
757 else
758 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 1,
759 SecondOutputDimBound);
760 if (!ThirdOutputDimBound)
761 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 2, 0);
762 else
763 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 2,
764 ThirdOutputDimBound);
765 return extensionMap;
766}
767
Tobias Grosserc80d6972016-09-02 06:33:33 +0000768/// Create an access relation that is specific to the matrix
Roman Gareev1c892e92016-08-15 12:22:54 +0000769/// multiplication pattern.
770///
771/// Create an access relation of the following form:
772/// Stmt[O0, O1, O2]->[OI, OJ],
773/// where I is @p I, J is @J
774///
775/// @param Stmt The SCoP statement for which to generate the access relation.
776/// @param I The index of the input dimension that is mapped to the first output
777/// dimension.
778/// @param J The index of the input dimension that is mapped to the second
779/// output dimension.
780/// @return The specified access relation.
781__isl_give isl_map *
782getMatMulPatternOriginalAccessRelation(ScopStmt *Stmt, unsigned I, unsigned J) {
783 auto *AccessRelSpace = isl_space_alloc(Stmt->getIslCtx(), 0, 3, 2);
784 auto *AccessRel = isl_map_universe(AccessRelSpace);
785 AccessRel = isl_map_equate(AccessRel, isl_dim_in, I, isl_dim_out, 0);
786 AccessRel = isl_map_equate(AccessRel, isl_dim_in, J, isl_dim_out, 1);
787 AccessRel = isl_map_set_tuple_id(AccessRel, isl_dim_in, Stmt->getDomainId());
788 return AccessRel;
789}
790
Tobias Grosserc80d6972016-09-02 06:33:33 +0000791/// Identify the memory access that corresponds to the access to the second
792/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000793///
794/// Identify the memory access that corresponds to the access
795/// to the matrix B of the matrix multiplication C = A x B.
796///
797/// @param Stmt The SCoP statement that contains the memory accesses
798/// under consideration.
799/// @return The memory access of @p Stmt that corresponds to the access
800/// to the second operand of the matrix multiplication.
801MemoryAccess *identifyAccessA(ScopStmt *Stmt) {
802 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 0, 2);
803 return identifyAccessByAccessRelation(Stmt, OriginalRel);
804}
805
Tobias Grosserc80d6972016-09-02 06:33:33 +0000806/// Identify the memory access that corresponds to the access to the first
807/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000808///
809/// Identify the memory access that corresponds to the access
810/// to the matrix A of the matrix multiplication C = A x B.
811///
812/// @param Stmt The SCoP statement that contains the memory accesses
813/// under consideration.
814/// @return The memory access of @p Stmt that corresponds to the access
815/// to the first operand of the matrix multiplication.
816MemoryAccess *identifyAccessB(ScopStmt *Stmt) {
817 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 2, 1);
818 return identifyAccessByAccessRelation(Stmt, OriginalRel);
819}
820
Tobias Grosserc80d6972016-09-02 06:33:33 +0000821/// Create an access relation that is specific to
Roman Gareev1c892e92016-08-15 12:22:54 +0000822/// the matrix multiplication pattern.
823///
824/// Create an access relation of the following form:
Roman Gareev92c44602016-12-21 11:18:42 +0000825/// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
826/// where I is @p FirstDim, J is @p SecondDim.
Roman Gareev1c892e92016-08-15 12:22:54 +0000827///
828/// It can be used, for example, to create relations that helps to consequently
829/// access elements of operands of a matrix multiplication after creation of
830/// the BLIS micro and macro kernels.
831///
832/// @see ScheduleTreeOptimizer::createMicroKernel
833/// @see ScheduleTreeOptimizer::createMacroKernel
834///
835/// Subsequently, the described access relation is applied to the range of
836/// @p MapOldIndVar, that is used to map original induction variables to
837/// the ones, which are produced by schedule transformations. It helps to
838/// define relations using a new space and, at the same time, keep them
839/// in the original one.
840///
841/// @param MapOldIndVar The relation, which maps original induction variables
842/// to the ones, which are produced by schedule
843/// transformations.
Roman Gareev1c892e92016-08-15 12:22:54 +0000844/// @param FirstDim, SecondDim The input dimensions that are used to define
845/// the specified access relation.
846/// @return The specified access relation.
847__isl_give isl_map *getMatMulAccRel(__isl_take isl_map *MapOldIndVar,
Roman Gareev92c44602016-12-21 11:18:42 +0000848 unsigned FirstDim, unsigned SecondDim) {
Roman Gareev1c892e92016-08-15 12:22:54 +0000849 auto *Ctx = isl_map_get_ctx(MapOldIndVar);
Roman Gareev92c44602016-12-21 11:18:42 +0000850 auto *AccessRelSpace = isl_space_alloc(Ctx, 0, 9, 3);
851 auto *AccessRel = isl_map_universe(AccessRelSpace);
852 AccessRel = isl_map_equate(AccessRel, isl_dim_in, FirstDim, isl_dim_out, 0);
853 AccessRel = isl_map_equate(AccessRel, isl_dim_in, 5, isl_dim_out, 1);
854 AccessRel = isl_map_equate(AccessRel, isl_dim_in, SecondDim, isl_dim_out, 2);
Roman Gareev1c892e92016-08-15 12:22:54 +0000855 return isl_map_apply_range(MapOldIndVar, AccessRel);
856}
857
Roman Gareevb3224ad2016-09-14 06:26:09 +0000858__isl_give isl_schedule_node *
859createExtensionNode(__isl_take isl_schedule_node *Node,
860 __isl_take isl_map *ExtensionMap) {
861 auto *Extension = isl_union_map_from_map(ExtensionMap);
862 auto *NewNode = isl_schedule_node_from_extension(Extension);
863 return isl_schedule_node_graft_before(Node, NewNode);
864}
865
Tobias Grosserc80d6972016-09-02 06:33:33 +0000866/// Apply the packing transformation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000867///
868/// The packing transformation can be described as a data-layout
869/// transformation that requires to introduce a new array, copy data
Roman Gareev7758a2a2017-01-29 10:37:50 +0000870/// to the array, and change memory access locations to reference the array.
871/// It can be used to ensure that elements of the new array are read in-stride
872/// access, aligned to cache lines boundaries, and preloaded into certain cache
873/// levels.
874///
875/// As an example let us consider the packing of the array A that would help
876/// to read its elements with in-stride access. An access to the array A
877/// is represented by an access relation that has the form
878/// S[i, j, k] -> A[i, k]. The scheduling function of the SCoP statement S has
879/// the form S[i,j, k] -> [floor((j mod Nc) / Nr), floor((i mod Mc) / Mr),
880/// k mod Kc, j mod Nr, i mod Mr].
881///
882/// To ensure that elements of the array A are read in-stride access, we add
883/// a new array Packed_A[Mc/Mr][Kc][Mr] to the SCoP, using
884/// Scop::createScopArrayInfo, change the access relation
885/// S[i, j, k] -> A[i, k] to
886/// S[i, j, k] -> Packed_A[floor((i mod Mc) / Mr), k mod Kc, i mod Mr], using
887/// MemoryAccess::setNewAccessRelation, and copy the data to the array, using
888/// the copy statement created by Scop::addScopStmt.
Roman Gareev1c892e92016-08-15 12:22:54 +0000889///
890/// @param Node The schedule node to be optimized.
891/// @param MapOldIndVar The relation, which maps original induction variables
892/// to the ones, which are produced by schedule
893/// transformations.
894/// @param MicroParams, MacroParams Parameters of the BLIS kernel
895/// to be taken into account.
896/// @return The optimized schedule node.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000897static __isl_give isl_schedule_node *optimizeDataLayoutMatrMulPattern(
898 __isl_take isl_schedule_node *Node, __isl_take isl_map *MapOldIndVar,
899 MicroKernelParamsTy MicroParams, MacroKernelParamsTy MacroParams) {
Roman Gareev2606c482016-12-15 12:35:59 +0000900 // Check whether memory accesses of the SCoP statement correspond to
901 // the matrix multiplication pattern and if this is true, obtain them.
Roman Gareev1c892e92016-08-15 12:22:54 +0000902 auto InputDimsId = isl_map_get_tuple_id(MapOldIndVar, isl_dim_in);
903 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
904 isl_id_free(InputDimsId);
905 MemoryAccess *MemAccessA = identifyAccessA(Stmt);
906 MemoryAccess *MemAccessB = identifyAccessB(Stmt);
907 if (!MemAccessA || !MemAccessB) {
908 isl_map_free(MapOldIndVar);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000909 return Node;
Roman Gareev1c892e92016-08-15 12:22:54 +0000910 }
Roman Gareev2606c482016-12-15 12:35:59 +0000911
912 // Create a copy statement that corresponds to the memory access to the
913 // matrix B, the second operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000914 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
915 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
916 Node = isl_schedule_node_parent(Node);
917 Node = isl_schedule_node_child(isl_schedule_node_band_split(Node, 2), 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000918 auto *AccRel = getMatMulAccRel(isl_map_copy(MapOldIndVar), 3, 7);
919 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
920 unsigned SecondDimSize = MacroParams.Kc;
921 unsigned ThirdDimSize = MicroParams.Nr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000922 auto *SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000923 MemAccessB->getElementType(), "Packed_B",
924 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000925 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000926 auto *OldAcc = MemAccessB->getAccessRelation();
927 MemAccessB->setNewAccessRelation(AccRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000928 auto *ExtMap =
Roman Gareev8babe1a2016-12-15 11:47:38 +0000929 getMatMulExt(Stmt->getIslCtx(), 0, MacroParams.Nc, MacroParams.Kc);
930 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
931 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
932 ExtMap = isl_map_project_out(ExtMap, isl_dim_in, 2, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000933 auto *Domain = Stmt->getDomain();
Roman Gareev2606c482016-12-15 12:35:59 +0000934
935 // Restrict the domains of the copy statements to only execute when also its
936 // originating statement is executed.
937 auto *DomainId = isl_set_get_tuple_id(Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000938 auto *NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev8babe1a2016-12-15 11:47:38 +0000939 OldAcc, MemAccessB->getAccessRelation(), isl_set_copy(Domain));
Roman Gareev2606c482016-12-15 12:35:59 +0000940 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, isl_id_copy(DomainId));
941 ExtMap = isl_map_intersect_range(ExtMap, isl_set_copy(Domain));
Roman Gareevb3224ad2016-09-14 06:26:09 +0000942 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
943 Node = createExtensionNode(Node, ExtMap);
Roman Gareev2606c482016-12-15 12:35:59 +0000944
945 // Create a copy statement that corresponds to the memory access
946 // to the matrix A, the first operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000947 Node = isl_schedule_node_child(Node, 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000948 AccRel = getMatMulAccRel(MapOldIndVar, 4, 6);
949 FirstDimSize = MacroParams.Mc / MicroParams.Mr;
950 ThirdDimSize = MicroParams.Mr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000951 SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000952 MemAccessA->getElementType(), "Packed_A",
953 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000954 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000955 OldAcc = MemAccessA->getAccessRelation();
956 MemAccessA->setNewAccessRelation(AccRel);
957 ExtMap = getMatMulExt(Stmt->getIslCtx(), MacroParams.Mc, 0, MacroParams.Kc);
958 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000959 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
960 NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev2606c482016-12-15 12:35:59 +0000961 OldAcc, MemAccessA->getAccessRelation(), isl_set_copy(Domain));
962
963 // Restrict the domains of the copy statements to only execute when also its
964 // originating statement is executed.
965 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, DomainId);
966 ExtMap = isl_map_intersect_range(ExtMap, Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000967 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
968 Node = createExtensionNode(Node, ExtMap);
969 Node = isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
970 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev1c892e92016-08-15 12:22:54 +0000971}
972
Tobias Grosserc80d6972016-09-02 06:33:33 +0000973/// Get a relation mapping induction variables produced by schedule
974/// transformations to the original ones.
Roman Gareev1c892e92016-08-15 12:22:54 +0000975///
976/// @param Node The schedule node produced as the result of creation
977/// of the BLIS kernels.
978/// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
979/// to be taken into account.
980/// @return The relation mapping original induction variables to the ones
981/// produced by schedule transformation.
982/// @see ScheduleTreeOptimizer::createMicroKernel
983/// @see ScheduleTreeOptimizer::createMacroKernel
984/// @see getMacroKernelParams
985__isl_give isl_map *
986getInductionVariablesSubstitution(__isl_take isl_schedule_node *Node,
987 MicroKernelParamsTy MicroKernelParams,
988 MacroKernelParamsTy MacroKernelParams) {
989 auto *Child = isl_schedule_node_get_child(Node, 0);
990 auto *UnMapOldIndVar = isl_schedule_node_get_prefix_schedule_union_map(Child);
991 isl_schedule_node_free(Child);
992 auto *MapOldIndVar = isl_map_from_union_map(UnMapOldIndVar);
993 if (isl_map_dim(MapOldIndVar, isl_dim_out) > 9)
994 MapOldIndVar =
995 isl_map_project_out(MapOldIndVar, isl_dim_out, 0,
996 isl_map_dim(MapOldIndVar, isl_dim_out) - 9);
997 return MapOldIndVar;
998}
999
Roman Gareev2cb4d132016-07-25 07:27:59 +00001000__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeMatMulPattern(
1001 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
1002 assert(TTI && "The target transform info should be provided.");
1003 auto MicroKernelParams = getMicroKernelParams(TTI);
Roman Gareev3a18a932016-07-25 09:42:53 +00001004 auto MacroKernelParams = getMacroKernelParams(MicroKernelParams);
1005 Node = createMacroKernel(Node, MacroKernelParams);
Roman Gareev2cb4d132016-07-25 07:27:59 +00001006 Node = createMicroKernel(Node, MicroKernelParams);
Roman Gareev1c892e92016-08-15 12:22:54 +00001007 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
1008 MacroKernelParams.Kc == 1)
1009 return Node;
1010 auto *MapOldIndVar = getInductionVariablesSubstitution(
1011 Node, MicroKernelParams, MacroKernelParams);
1012 if (!MapOldIndVar)
1013 return Node;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001014 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
1015 MacroKernelParams);
Roman Gareev42402c92016-06-22 09:52:37 +00001016}
1017
Roman Gareev9c3eb592016-05-28 16:17:58 +00001018bool ScheduleTreeOptimizer::isMatrMultPattern(
1019 __isl_keep isl_schedule_node *Node) {
1020 auto *PartialSchedule =
1021 isl_schedule_node_band_get_partial_schedule_union_map(Node);
Roman Gareev397a34a2016-06-22 12:11:30 +00001022 if (isl_schedule_node_band_n_member(Node) != 3 ||
1023 isl_union_map_n_map(PartialSchedule) != 1) {
1024 isl_union_map_free(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +00001025 return false;
1026 }
Roman Gareev397a34a2016-06-22 12:11:30 +00001027 auto *NewPartialSchedule = isl_map_from_union_map(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +00001028 NewPartialSchedule = circularShiftOutputDims(NewPartialSchedule);
1029 if (containsMatrMult(NewPartialSchedule)) {
1030 isl_map_free(NewPartialSchedule);
1031 return true;
1032 }
1033 isl_map_free(NewPartialSchedule);
1034 return false;
1035}
1036
1037__isl_give isl_schedule_node *
1038ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
1039 void *User) {
1040 if (!isTileableBandNode(Node))
1041 return Node;
1042
Roman Gareev42402c92016-06-22 09:52:37 +00001043 if (PMBasedOpts && User && isMatrMultPattern(Node)) {
Roman Gareev9c3eb592016-05-28 16:17:58 +00001044 DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
Roman Gareev42402c92016-06-22 09:52:37 +00001045 const llvm::TargetTransformInfo *TTI;
1046 TTI = static_cast<const llvm::TargetTransformInfo *>(User);
1047 Node = optimizeMatMulPattern(Node, TTI);
1048 }
Roman Gareev9c3eb592016-05-28 16:17:58 +00001049
1050 return standardBandOpts(Node, User);
1051}
1052
Tobias Grosser808cd692015-07-14 09:33:13 +00001053__isl_give isl_schedule *
Roman Gareev42402c92016-06-22 09:52:37 +00001054ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule,
1055 const llvm::TargetTransformInfo *TTI) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001056 isl_schedule_node *Root = isl_schedule_get_root(Schedule);
Roman Gareev42402c92016-06-22 09:52:37 +00001057 Root = optimizeScheduleNode(Root, TTI);
Tobias Grosser808cd692015-07-14 09:33:13 +00001058 isl_schedule_free(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001059 auto S = isl_schedule_node_get_schedule(Root);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001060 isl_schedule_node_free(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +00001061 return S;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001062}
1063
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001064__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
Roman Gareev42402c92016-06-22 09:52:37 +00001065 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
1066 Node = isl_schedule_node_map_descendant_bottom_up(
1067 Node, optimizeBand, const_cast<void *>(static_cast<const void *>(TTI)));
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001068 return Node;
1069}
1070
1071bool ScheduleTreeOptimizer::isProfitableSchedule(
Roman Gareevb3224ad2016-09-14 06:26:09 +00001072 Scop &S, __isl_keep isl_schedule *NewSchedule) {
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001073 // To understand if the schedule has been optimized we check if the schedule
1074 // has changed at all.
1075 // TODO: We can improve this by tracking if any necessarily beneficial
1076 // transformations have been performed. This can e.g. be tiling, loop
1077 // interchange, or ...) We can track this either at the place where the
1078 // transformation has been performed or, in case of automatic ILP based
1079 // optimizations, by comparing (yet to be defined) performance metrics
1080 // before/after the scheduling optimizer
1081 // (e.g., #stride-one accesses)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001082 if (S.containsExtensionNode(NewSchedule))
1083 return true;
1084 auto *NewScheduleMap = isl_schedule_get_map(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001085 isl_union_map *OldSchedule = S.getSchedule();
Tobias Grosser21a059a2017-01-16 14:08:10 +00001086 assert(OldSchedule &&
1087 "Only IslScheduleOptimizer can insert extension nodes "
1088 "that make Scop::getSchedule() return nullptr.");
Roman Gareevb3224ad2016-09-14 06:26:09 +00001089 bool changed = !isl_union_map_is_equal(OldSchedule, NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001090 isl_union_map_free(OldSchedule);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001091 isl_union_map_free(NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001092 return changed;
1093}
1094
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001095namespace {
1096class IslScheduleOptimizer : public ScopPass {
1097public:
1098 static char ID;
1099 explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
1100
1101 ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
1102
Tobias Grosserc80d6972016-09-02 06:33:33 +00001103 /// Optimize the schedule of the SCoP @p S.
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001104 bool runOnScop(Scop &S) override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001105
Tobias Grosserc80d6972016-09-02 06:33:33 +00001106 /// Print the new schedule for the SCoP @p S.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001107 void printScop(raw_ostream &OS, Scop &S) const override;
1108
Tobias Grosserc80d6972016-09-02 06:33:33 +00001109 /// Register all analyses and transformation required.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001110 void getAnalysisUsage(AnalysisUsage &AU) const override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001111
Tobias Grosserc80d6972016-09-02 06:33:33 +00001112 /// Release the internal memory.
Johannes Doerfert0f376302015-09-27 15:42:28 +00001113 void releaseMemory() override {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001114 isl_schedule_free(LastSchedule);
1115 LastSchedule = nullptr;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001116 }
Johannes Doerfert45be6442015-09-27 15:43:29 +00001117
1118private:
1119 isl_schedule *LastSchedule;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001120};
Tobias Grosser522478d2016-06-23 22:17:27 +00001121} // namespace
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001122
1123char IslScheduleOptimizer::ID = 0;
1124
Tobias Grosser73600b82011-10-08 00:30:40 +00001125bool IslScheduleOptimizer::runOnScop(Scop &S) {
Johannes Doerfert6f7921f2015-02-14 12:02:24 +00001126
1127 // Skip empty SCoPs but still allow code generation as it will delete the
1128 // loops present but not needed.
1129 if (S.getSize() == 0) {
1130 S.markAsOptimized();
1131 return false;
1132 }
1133
Hongbin Zheng2a798852016-03-03 08:15:33 +00001134 const Dependences &D =
1135 getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001136
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001137 if (!D.hasValidDependences())
Tobias Grosser38c36ea2014-02-23 15:15:44 +00001138 return false;
1139
Tobias Grosser28781422012-10-16 07:29:19 +00001140 isl_schedule_free(LastSchedule);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001141 LastSchedule = nullptr;
Tobias Grosser28781422012-10-16 07:29:19 +00001142
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001143 // Build input data.
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001144 int ValidityKinds =
1145 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001146 int ProximityKinds;
1147
1148 if (OptimizeDeps == "all")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001149 ProximityKinds =
1150 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001151 else if (OptimizeDeps == "raw")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001152 ProximityKinds = Dependences::TYPE_RAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001153 else {
1154 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001155 << " Falling back to optimizing all dependences.\n";
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001156 ProximityKinds =
1157 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001158 }
1159
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001160 isl_union_set *Domain = S.getDomains();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001161
Tobias Grosser98610ee2012-02-13 23:31:39 +00001162 if (!Domain)
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001163 return false;
1164
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001165 isl_union_map *Validity = D.getDependences(ValidityKinds);
1166 isl_union_map *Proximity = D.getDependences(ProximityKinds);
Tobias Grosser8a507022012-03-16 11:51:41 +00001167
Tobias Grossera26db472012-01-30 19:38:43 +00001168 // Simplify the dependences by removing the constraints introduced by the
1169 // domains. This can speed up the scheduling time significantly, as large
1170 // constant coefficients will be removed from the dependences. The
1171 // introduction of some additional dependences reduces the possible
1172 // transformations, but in most cases, such transformation do not seem to be
1173 // interesting anyway. In some cases this option may stop the scheduler to
1174 // find any schedule.
1175 if (SimplifyDeps == "yes") {
Tobias Grosser00383a72012-02-14 14:02:44 +00001176 Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
1177 Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001178 Proximity =
1179 isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
Tobias Grosser00383a72012-02-14 14:02:44 +00001180 Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
Tobias Grossera26db472012-01-30 19:38:43 +00001181 } else if (SimplifyDeps != "no") {
1182 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
1183 "or 'no'. Falling back to default: 'yes'\n";
1184 }
1185
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001186 DEBUG(dbgs() << "\n\nCompute schedule from: ");
Tobias Grosser01aea582014-10-22 23:16:28 +00001187 DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
1188 DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
1189 DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001190
Michael Krusec59f22c2015-06-18 16:45:40 +00001191 unsigned IslSerializeSCCs;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001192
1193 if (FusionStrategy == "max") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001194 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001195 } else if (FusionStrategy == "min") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001196 IslSerializeSCCs = 1;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001197 } else {
1198 errs() << "warning: Unknown fusion strategy. Falling back to maximal "
1199 "fusion.\n";
Michael Krusec59f22c2015-06-18 16:45:40 +00001200 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001201 }
1202
Tobias Grosser95e860c2012-01-30 19:38:54 +00001203 int IslMaximizeBands;
1204
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001205 if (MaximizeBandDepth == "yes") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001206 IslMaximizeBands = 1;
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001207 } else if (MaximizeBandDepth == "no") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001208 IslMaximizeBands = 0;
1209 } else {
1210 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
1211 " or 'no'. Falling back to default: 'yes'\n";
1212 IslMaximizeBands = 1;
1213 }
1214
Michael Kruse315aa322016-05-02 11:35:27 +00001215 int IslOuterCoincidence;
1216
1217 if (OuterCoincidence == "yes") {
1218 IslOuterCoincidence = 1;
1219 } else if (OuterCoincidence == "no") {
1220 IslOuterCoincidence = 0;
1221 } else {
1222 errs() << "warning: Option -polly-opt-outer-coincidence should either be "
1223 "'yes' or 'no'. Falling back to default: 'no'\n";
1224 IslOuterCoincidence = 0;
1225 }
1226
Tobias Grosseraf149932016-06-30 20:42:56 +00001227 isl_ctx *Ctx = S.getIslCtx();
Tobias Grosser42152ff2012-01-30 19:38:47 +00001228
Tobias Grosseraf149932016-06-30 20:42:56 +00001229 isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
1230 isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs);
1231 isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
1232 isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
1233 isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
1234 isl_options_set_tile_scale_tile_loops(Ctx, 0);
1235
Tobias Grosser3898a042016-06-30 20:42:58 +00001236 auto OnErrorStatus = isl_options_get_on_error(Ctx);
Tobias Grosseraf149932016-06-30 20:42:56 +00001237 isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
Tobias Grossera38c9242014-01-26 19:36:28 +00001238
1239 isl_schedule_constraints *ScheduleConstraints;
1240 ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
1241 ScheduleConstraints =
1242 isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
1243 ScheduleConstraints = isl_schedule_constraints_set_validity(
1244 ScheduleConstraints, isl_union_map_copy(Validity));
1245 ScheduleConstraints =
1246 isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
Tobias Grosser00383a72012-02-14 14:02:44 +00001247 isl_schedule *Schedule;
Tobias Grossera38c9242014-01-26 19:36:28 +00001248 Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
Tobias Grosser3898a042016-06-30 20:42:58 +00001249 isl_options_set_on_error(Ctx, OnErrorStatus);
Tobias Grosser42152ff2012-01-30 19:38:47 +00001250
1251 // In cases the scheduler is not able to optimize the code, we just do not
1252 // touch the schedule.
Tobias Grosser98610ee2012-02-13 23:31:39 +00001253 if (!Schedule)
Tobias Grosser42152ff2012-01-30 19:38:47 +00001254 return false;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001255
Tobias Grosser97d87452015-05-30 06:46:59 +00001256 DEBUG({
Tobias Grosseraf149932016-06-30 20:42:56 +00001257 auto *P = isl_printer_to_str(Ctx);
Tobias Grosser97d87452015-05-30 06:46:59 +00001258 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1259 P = isl_printer_print_schedule(P, Schedule);
Michael Kruse79c01732016-12-12 14:51:06 +00001260 auto *str = isl_printer_get_str(P);
1261 dbgs() << "NewScheduleTree: \n" << str << "\n";
1262 free(str);
Tobias Grosser97d87452015-05-30 06:46:59 +00001263 isl_printer_free(P);
1264 });
Tobias Grosser4d63b9d2012-02-20 08:41:21 +00001265
Roman Gareev42402c92016-06-22 09:52:37 +00001266 Function &F = S.getFunction();
1267 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1268 isl_schedule *NewSchedule =
1269 ScheduleTreeOptimizer::optimizeSchedule(Schedule, TTI);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001270
Roman Gareevb3224ad2016-09-14 06:26:09 +00001271 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule)) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001272 isl_schedule_free(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001273 return false;
1274 }
1275
Tobias Grosser808cd692015-07-14 09:33:13 +00001276 S.setScheduleTree(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001277 S.markAsOptimized();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001278
Roman Gareev5f99f862016-08-21 11:20:39 +00001279 if (OptimizedScops)
1280 S.dump();
1281
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001282 return false;
1283}
1284
Johannes Doerfert3fe584d2015-03-01 18:40:25 +00001285void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
Tobias Grosser28781422012-10-16 07:29:19 +00001286 isl_printer *p;
1287 char *ScheduleStr;
1288
1289 OS << "Calculated schedule:\n";
1290
1291 if (!LastSchedule) {
1292 OS << "n/a\n";
1293 return;
1294 }
1295
1296 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
1297 p = isl_printer_print_schedule(p, LastSchedule);
1298 ScheduleStr = isl_printer_get_str(p);
1299 isl_printer_free(p);
1300
1301 OS << ScheduleStr << "\n";
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001302}
1303
Tobias Grosser73600b82011-10-08 00:30:40 +00001304void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001305 ScopPass::getAnalysisUsage(AU);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001306 AU.addRequired<DependenceInfo>();
Roman Gareev42402c92016-06-22 09:52:37 +00001307 AU.addRequired<TargetTransformInfoWrapperPass>();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001308}
1309
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001310Pass *polly::createIslScheduleOptimizerPass() {
Tobias Grosser73600b82011-10-08 00:30:40 +00001311 return new IslScheduleOptimizer();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001312}
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001313
1314INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
1315 "Polly - Optimize schedule of SCoP", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001316INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Johannes Doerfert99191c72016-05-31 09:41:04 +00001317INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
Roman Gareev42402c92016-06-22 09:52:37 +00001318INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001319INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
1320 "Polly - Optimize schedule of SCoP", false, false)