blob: f4b082ca3c899ec392382ffcfe2529ab3aad4b1e [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
Siddharth Bhat3e4a7d32017-03-17 14:52:19 +000029// - Prevectorization - The choice of a possible outer loop that is strip-mined
Tobias Grosser234a4822015-08-15 09:34:33 +000030// 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
Siddharth Bhat3e4a7d32017-03-17 14:52:19 +000039// ACM Transactions on Programming Languages and Systems (TOPLAS),
Tobias Grosser234a4822015-08-15 09:34:33 +000040// 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"),
Roman Gareev96e11192017-02-23 11:44:12 +0000229 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Roman Gareev9c3eb592016-05-28 16:17:58 +0000230
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///
Roman Gareev99890882017-02-09 07:10:01 +0000241/// @param IsolateDomain An isl_set whose @p OutDimsNum last dimensions should
242/// belong to the current band node.
243/// @param OutDimsNum A number of dimensions that should belong to
244/// the current band node.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000245static __isl_give isl_union_set *
Roman Gareev99890882017-02-09 07:10:01 +0000246getIsolateOptions(__isl_take isl_set *IsolateDomain, unsigned OutDimsNum) {
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000247 auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
Roman Gareev99890882017-02-09 07:10:01 +0000248 assert(OutDimsNum <= Dims &&
249 "The isl_set IsolateDomain is used to describe the range of schedule "
250 "dimensions values, which should be isolated. Consequently, the "
251 "number of its dimensions should be greater than or equal to the "
252 "number of the schedule dimensions.");
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000253 auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
Roman Gareev99890882017-02-09 07:10:01 +0000254 IsolateRelation =
255 isl_map_move_dims(IsolateRelation, isl_dim_out, 0, isl_dim_in,
256 Dims - OutDimsNum, OutDimsNum);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000257 auto *IsolateOption = isl_map_wrap(IsolateRelation);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000258 auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000259 return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
260}
261
Tobias Grosserc80d6972016-09-02 06:33:33 +0000262/// Create an isl_union_set, which describes the atomic option for the dimension
263/// of the current node.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000264///
265/// It may help to reduce the size of generated code.
266///
267/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
Roman Gareevafcf0262017-02-11 07:14:37 +0000268static __isl_give isl_union_set *getAtomicOptions(isl_ctx *Ctx) {
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000269 auto *Space = isl_space_set_alloc(Ctx, 0, 1);
270 auto *AtomicOption = isl_set_universe(Space);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000271 auto *Id = isl_id_alloc(Ctx, "atomic", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000272 return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
273}
274
Roman Gareev99890882017-02-09 07:10:01 +0000275/// Create an isl_union_set, which describes the option of the form
276/// [isolate[] -> unroll[x]].
277///
278/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
279static __isl_give isl_union_set *getUnrollIsolatedSetOptions(isl_ctx *Ctx) {
280 auto *Space = isl_space_alloc(Ctx, 0, 0, 1);
281 auto *UnrollIsolatedSetOption = isl_map_universe(Space);
282 auto *DimInId = isl_id_alloc(Ctx, "isolate", nullptr);
283 auto *DimOutId = isl_id_alloc(Ctx, "unroll", nullptr);
284 UnrollIsolatedSetOption =
285 isl_map_set_tuple_id(UnrollIsolatedSetOption, isl_dim_in, DimInId);
286 UnrollIsolatedSetOption =
287 isl_map_set_tuple_id(UnrollIsolatedSetOption, isl_dim_out, DimOutId);
288 return isl_union_set_from_set(isl_map_wrap(UnrollIsolatedSetOption));
289}
290
Tobias Grosserc80d6972016-09-02 06:33:33 +0000291/// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000292///
293/// @param Set A set, which should be modified.
294/// @param VectorWidth A parameter, which determines the constraint.
295static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
296 int VectorWidth) {
297 auto Dims = isl_set_dim(Set, isl_dim_set);
298 auto Space = isl_set_get_space(Set);
299 auto *LocalSpace = isl_local_space_from_space(Space);
300 auto *ExtConstr =
301 isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
302 ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
303 ExtConstr =
304 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
305 Set = isl_set_add_constraint(Set, ExtConstr);
306 ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
307 ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
308 ExtConstr =
309 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
310 return isl_set_add_constraint(Set, ExtConstr);
311}
312
Tobias Grosserc80d6972016-09-02 06:33:33 +0000313/// Build the desired set of partial tile prefixes.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000314///
315/// We build a set of partial tile prefixes, which are prefixes of the vector
316/// loop that have exactly VectorWidth iterations.
317///
318/// 1. Get all prefixes of the vector loop.
319/// 2. Extend it to a set, which has exactly VectorWidth iterations for
320/// any prefix from the set that was built on the previous step.
321/// 3. Subtract loop domain from it, project out the vector loop dimension and
Roman Gareev76614d32016-05-31 11:22:21 +0000322/// get a set of prefixes, which don't have exactly VectorWidth iterations.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000323/// 4. Subtract it from all prefixes of the vector loop and get the desired
324/// set.
325///
326/// @param ScheduleRange A range of a map, which describes a prefix schedule
327/// relation.
328static __isl_give isl_set *
329getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
330 auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
331 auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
332 isl_dim_set, Dims - 1, 1);
333 auto *ExtentPrefixes =
334 isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
335 ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
336 auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
337 BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
338 return isl_set_subtract(LoopPrefixes, BadPrefixes);
339}
340
341__isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
342 __isl_take isl_schedule_node *Node, int VectorWidth) {
343 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
344 Node = isl_schedule_node_child(Node, 0);
345 Node = isl_schedule_node_child(Node, 0);
346 auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
347 auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
348 auto *ScheduleRange = isl_map_range(ScheduleRelation);
349 auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
350 auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
Roman Gareev99890882017-02-09 07:10:01 +0000351 auto *IsolateOption = getIsolateOptions(IsolateDomain, 1);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000352 Node = isl_schedule_node_parent(Node);
353 Node = isl_schedule_node_parent(Node);
354 auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
355 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
356 return Node;
357}
358
Tobias Grosserb241d922015-07-28 18:03:36 +0000359__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000360ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
361 unsigned DimToVectorize,
362 int VectorWidth) {
Tobias Grosserb241d922015-07-28 18:03:36 +0000363 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
Tobias Grosserc6699b72011-06-30 20:29:13 +0000364
Tobias Grosserb241d922015-07-28 18:03:36 +0000365 auto Space = isl_schedule_node_band_get_space(Node);
366 auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
367 isl_space_free(Space);
368 assert(DimToVectorize < ScheduleDimensions);
Tobias Grosserf5338802011-10-06 00:03:35 +0000369
Tobias Grosserb241d922015-07-28 18:03:36 +0000370 if (DimToVectorize > 0) {
371 Node = isl_schedule_node_band_split(Node, DimToVectorize);
372 Node = isl_schedule_node_child(Node, 0);
373 }
374 if (DimToVectorize < ScheduleDimensions - 1)
375 Node = isl_schedule_node_band_split(Node, 1);
376 Space = isl_schedule_node_band_get_space(Node);
377 auto Sizes = isl_multi_val_zero(Space);
378 auto Ctx = isl_schedule_node_get_ctx(Node);
379 Sizes =
380 isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
381 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000382 Node = isolateFullPartialTiles(Node, VectorWidth);
Tobias Grosserb241d922015-07-28 18:03:36 +0000383 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser42e24892015-08-20 13:45:05 +0000384 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
385 // we will have troubles to match it in the backend.
386 Node = isl_schedule_node_band_set_ast_build_options(
Tobias Grosserfc490a92015-08-20 19:08:16 +0000387 Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
388 Node = isl_schedule_node_band_sink(Node);
Tobias Grosserb241d922015-07-28 18:03:36 +0000389 Node = isl_schedule_node_child(Node, 0);
Roman Gareev11001e12016-02-23 09:00:13 +0000390 if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
391 Node = isl_schedule_node_parent(Node);
392 isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
393 Node = isl_schedule_node_insert_mark(Node, LoopMarker);
Tobias Grosserb241d922015-07-28 18:03:36 +0000394 return Node;
Tobias Grosserc6699b72011-06-30 20:29:13 +0000395}
396
Tobias Grosserd891b542015-08-20 12:16:23 +0000397__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000398ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
399 const char *Identifier, ArrayRef<int> TileSizes,
400 int DefaultTileSize) {
Tobias Grosser9bdea572015-08-20 12:22:37 +0000401 auto Ctx = isl_schedule_node_get_ctx(Node);
402 auto Space = isl_schedule_node_band_get_space(Node);
403 auto Dims = isl_space_dim(Space, isl_dim_set);
404 auto Sizes = isl_multi_val_zero(Space);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000405 std::string IdentifierString(Identifier);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000406 for (unsigned i = 0; i < Dims; i++) {
407 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
408 Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
409 }
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000410 auto TileLoopMarkerStr = IdentifierString + " - Tiles";
411 isl_id *TileLoopMarker =
412 isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
413 Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
414 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000415 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000416 Node = isl_schedule_node_child(Node, 0);
417 auto PointLoopMarkerStr = IdentifierString + " - Points";
418 isl_id *PointLoopMarker =
419 isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
420 Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
421 Node = isl_schedule_node_child(Node, 0);
422 return Node;
Tobias Grosser9bdea572015-08-20 12:22:37 +0000423}
424
Roman Gareevb17b9a82016-06-12 17:20:05 +0000425__isl_give isl_schedule_node *
426ScheduleTreeOptimizer::applyRegisterTiling(__isl_take isl_schedule_node *Node,
427 llvm::ArrayRef<int> TileSizes,
428 int DefaultTileSize) {
429 auto *Ctx = isl_schedule_node_get_ctx(Node);
430 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
431 Node = isl_schedule_node_band_set_ast_build_options(
432 Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
433 return Node;
434}
435
Tobias Grosserc9d4cb22017-03-12 19:02:31 +0000436namespace {
437bool isSimpleInnermostBand(const isl::schedule_node &Node) {
438 assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band);
439 assert(isl_schedule_node_n_children(Node.keep()) == 1);
440
441 auto ChildType = isl_schedule_node_get_type(Node.child(0).keep());
442
443 if (ChildType == isl_schedule_node_leaf)
444 return true;
445
446 if (ChildType != isl_schedule_node_sequence)
447 return false;
448
449 auto Sequence = Node.child(0);
450
451 for (int c = 0, nc = isl_schedule_node_n_children(Sequence.keep()); c < nc;
452 ++c) {
453 auto Child = Sequence.child(c);
454 if (isl_schedule_node_get_type(Child.keep()) != isl_schedule_node_filter)
455 return false;
456 if (isl_schedule_node_get_type(Child.child(0).keep()) !=
457 isl_schedule_node_leaf)
458 return false;
459 }
460 return true;
461}
462} // namespace
463
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000464bool ScheduleTreeOptimizer::isTileableBandNode(
Tobias Grosser862b9b52015-08-20 12:32:45 +0000465 __isl_keep isl_schedule_node *Node) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000466 if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000467 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000468
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000469 if (isl_schedule_node_n_children(Node) != 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000470 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000471
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000472 if (!isl_schedule_node_band_get_permutable(Node))
Tobias Grosser862b9b52015-08-20 12:32:45 +0000473 return false;
Tobias Grosser44f19ac2011-07-05 22:15:53 +0000474
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000475 auto Space = isl_schedule_node_band_get_space(Node);
476 auto Dims = isl_space_dim(Space, isl_dim_set);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000477 isl_space_free(Space);
Tobias Grosserde68cc92011-06-30 20:01:02 +0000478
Tobias Grosser9bdea572015-08-20 12:22:37 +0000479 if (Dims <= 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000480 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000481
Tobias Grosserc9d4cb22017-03-12 19:02:31 +0000482 auto ManagedNode = isl::manage(isl_schedule_node_copy(Node));
483 return isSimpleInnermostBand(ManagedNode);
Tobias Grosser862b9b52015-08-20 12:32:45 +0000484}
485
486__isl_give isl_schedule_node *
Roman Gareev9c3eb592016-05-28 16:17:58 +0000487ScheduleTreeOptimizer::standardBandOpts(__isl_take isl_schedule_node *Node,
488 void *User) {
Tobias Grosser04832712015-08-20 13:45:02 +0000489 if (FirstLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000490 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
491 FirstLevelDefaultTileSize);
Tobias Grosser04832712015-08-20 13:45:02 +0000492
493 if (SecondLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000494 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
495 SecondLevelDefaultTileSize);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000496
Roman Gareevb17b9a82016-06-12 17:20:05 +0000497 if (RegisterTiling)
498 Node =
499 applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
Tobias Grosser42e24892015-08-20 13:45:05 +0000500
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000501 if (PollyVectorizerChoice == VECTORIZER_NONE)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000502 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000503
Tobias Grosser862b9b52015-08-20 12:32:45 +0000504 auto Space = isl_schedule_node_band_get_space(Node);
505 auto Dims = isl_space_dim(Space, isl_dim_set);
506 isl_space_free(Space);
507
Tobias Grosserb241d922015-07-28 18:03:36 +0000508 for (int i = Dims - 1; i >= 0; i--)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000509 if (isl_schedule_node_band_member_get_coincident(Node, i)) {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000510 Node = prevectSchedBand(Node, i, PrevectorWidth);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000511 break;
512 }
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000513
Tobias Grosserf10f4632015-08-19 08:03:37 +0000514 return Node;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000515}
516
Roman Gareev98075fe2017-02-02 14:23:14 +0000517/// Get the position of a dimension with a non-zero coefficient.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000518///
Roman Gareev98075fe2017-02-02 14:23:14 +0000519/// Check that isl constraint @p Constraint has only one non-zero
520/// coefficient for dimensions that have type @p DimType. If this is true,
521/// return the position of the dimension corresponding to the non-zero
522/// coefficient and negative value, otherwise.
523///
524/// @param Constraint The isl constraint to be checked.
525/// @param DimType The type of the dimensions.
526/// @return The position of the dimension in case the isl
527/// constraint satisfies the requirements, a negative
528/// value, otherwise.
529static int getMatMulConstraintDim(__isl_keep isl_constraint *Constraint,
530 enum isl_dim_type DimType) {
531 int DimPos = -1;
532 auto *LocalSpace = isl_constraint_get_local_space(Constraint);
533 int LocalSpaceDimNum = isl_local_space_dim(LocalSpace, DimType);
534 for (int i = 0; i < LocalSpaceDimNum; i++) {
535 auto *Val = isl_constraint_get_coefficient_val(Constraint, DimType, i);
536 if (isl_val_is_zero(Val)) {
537 isl_val_free(Val);
538 continue;
539 }
540 if (DimPos >= 0 || (DimType == isl_dim_out && !isl_val_is_one(Val)) ||
541 (DimType == isl_dim_in && !isl_val_is_negone(Val))) {
542 isl_val_free(Val);
543 isl_local_space_free(LocalSpace);
544 return -1;
545 }
546 DimPos = i;
547 isl_val_free(Val);
548 }
549 isl_local_space_free(LocalSpace);
550 return DimPos;
551}
552
553/// Check the form of the isl constraint.
554///
555/// Check that the @p DimInPos input dimension of the isl constraint
556/// @p Constraint has a coefficient that is equal to negative one, the @p
557/// DimOutPos has a coefficient that is equal to one and others
558/// have coefficients equal to zero.
559///
560/// @param Constraint The isl constraint to be checked.
561/// @param DimInPos The input dimension of the isl constraint.
562/// @param DimOutPos The output dimension of the isl constraint.
563/// @return isl_stat_ok in case the isl constraint satisfies
564/// the requirements, isl_stat_error otherwise.
565static isl_stat isMatMulOperandConstraint(__isl_keep isl_constraint *Constraint,
566 int &DimInPos, int &DimOutPos) {
567 auto *Val = isl_constraint_get_constant_val(Constraint);
568 if (!isl_constraint_is_equality(Constraint) || !isl_val_is_zero(Val)) {
569 isl_val_free(Val);
570 return isl_stat_error;
571 }
572 isl_val_free(Val);
573 DimInPos = getMatMulConstraintDim(Constraint, isl_dim_in);
574 if (DimInPos < 0)
575 return isl_stat_error;
576 DimOutPos = getMatMulConstraintDim(Constraint, isl_dim_out);
577 if (DimOutPos < 0)
578 return isl_stat_error;
579 return isl_stat_ok;
580}
581
582/// Check that the access relation corresponds to a non-constant operand
583/// of the matrix multiplication.
584///
585/// Access relations that correspond to non-constant operands of the matrix
586/// multiplication depend only on two input dimensions and have two output
587/// dimensions. The function checks that the isl basic map @p bmap satisfies
588/// the requirements. The two input dimensions can be specified via @p user
589/// array.
590///
591/// @param bmap The isl basic map to be checked.
592/// @param user The input dimensions of @p bmap.
593/// @return isl_stat_ok in case isl basic map satisfies the requirements,
594/// isl_stat_error otherwise.
595static isl_stat isMatMulOperandBasicMap(__isl_take isl_basic_map *bmap,
596 void *user) {
597 auto *Constraints = isl_basic_map_get_constraint_list(bmap);
598 isl_basic_map_free(bmap);
599 if (isl_constraint_list_n_constraint(Constraints) != 2) {
600 isl_constraint_list_free(Constraints);
601 return isl_stat_error;
602 }
603 int InPosPair[] = {-1, -1};
604 auto DimInPos = user ? static_cast<int *>(user) : InPosPair;
605 for (int i = 0; i < 2; i++) {
606 auto *Constraint = isl_constraint_list_get_constraint(Constraints, i);
607 int InPos, OutPos;
608 if (isMatMulOperandConstraint(Constraint, InPos, OutPos) ==
609 isl_stat_error ||
610 OutPos > 1 || (DimInPos[OutPos] >= 0 && DimInPos[OutPos] != InPos)) {
611 isl_constraint_free(Constraint);
612 isl_constraint_list_free(Constraints);
613 return isl_stat_error;
614 }
615 DimInPos[OutPos] = InPos;
616 isl_constraint_free(Constraint);
617 }
618 isl_constraint_list_free(Constraints);
619 return isl_stat_ok;
620}
621
622/// Permute the two dimensions of the isl map.
623///
624/// Permute @p DstPos and @p SrcPos dimensions of the isl map @p Map that
625/// have type @p DimType.
626///
627/// @param Map The isl map to be modified.
628/// @param DimType The type of the dimensions.
629/// @param DstPos The first dimension.
630/// @param SrcPos The second dimension.
631/// @return The modified map.
632__isl_give isl_map *permuteDimensions(__isl_take isl_map *Map,
633 enum isl_dim_type DimType,
634 unsigned DstPos, unsigned SrcPos) {
635 assert(DstPos < isl_map_dim(Map, DimType) &&
636 SrcPos < isl_map_dim(Map, DimType));
637 if (DstPos == SrcPos)
638 return Map;
639 isl_id *DimId = nullptr;
640 if (isl_map_has_tuple_id(Map, DimType))
641 DimId = isl_map_get_tuple_id(Map, DimType);
642 auto FreeDim = DimType == isl_dim_in ? isl_dim_out : isl_dim_in;
643 isl_id *FreeDimId = nullptr;
644 if (isl_map_has_tuple_id(Map, FreeDim))
645 FreeDimId = isl_map_get_tuple_id(Map, FreeDim);
646 auto MaxDim = std::max(DstPos, SrcPos);
647 auto MinDim = std::min(DstPos, SrcPos);
648 Map = isl_map_move_dims(Map, FreeDim, 0, DimType, MaxDim, 1);
649 Map = isl_map_move_dims(Map, FreeDim, 0, DimType, MinDim, 1);
650 Map = isl_map_move_dims(Map, DimType, MinDim, FreeDim, 1, 1);
651 Map = isl_map_move_dims(Map, DimType, MaxDim, FreeDim, 0, 1);
652 if (DimId)
653 Map = isl_map_set_tuple_id(Map, DimType, DimId);
654 if (FreeDimId)
655 Map = isl_map_set_tuple_id(Map, FreeDim, FreeDimId);
656 return Map;
657}
658
659/// Check the form of the access relation.
660///
661/// Check that the access relation @p AccMap has the form M[i][j], where i
662/// is a @p FirstPos and j is a @p SecondPos.
663///
664/// @param AccMap The access relation to be checked.
665/// @param FirstPos The index of the input dimension that is mapped to
666/// the first output dimension.
667/// @param SecondPos The index of the input dimension that is mapped to the
668/// second output dimension.
669/// @return True in case @p AccMap has the expected form and false,
670/// otherwise.
671static bool isMatMulOperandAcc(__isl_keep isl_map *AccMap, int &FirstPos,
672 int &SecondPos) {
673 int DimInPos[] = {FirstPos, SecondPos};
674 if (isl_map_foreach_basic_map(AccMap, isMatMulOperandBasicMap,
675 static_cast<void *>(DimInPos)) != isl_stat_ok ||
676 DimInPos[0] < 0 || DimInPos[1] < 0)
677 return false;
678 FirstPos = DimInPos[0];
679 SecondPos = DimInPos[1];
680 return true;
681}
682
683/// Does the memory access represent a non-scalar operand of the matrix
684/// multiplication.
685///
686/// Check that the memory access @p MemAccess is the read access to a non-scalar
687/// operand of the matrix multiplication or its result.
688///
689/// @param MemAccess The memory access to be checked.
690/// @param MMI Parameters of the matrix multiplication operands.
691/// @return True in case the memory access represents the read access
692/// to a non-scalar operand of the matrix multiplication and
693/// false, otherwise.
694static bool isMatMulNonScalarReadAccess(MemoryAccess *MemAccess,
695 MatMulInfoTy &MMI) {
696 if (!MemAccess->isArrayKind() || !MemAccess->isRead())
697 return false;
698 isl_map *AccMap = MemAccess->getAccessRelation();
699 if (isMatMulOperandAcc(AccMap, MMI.i, MMI.j) && !MMI.ReadFromC &&
700 isl_map_n_basic_map(AccMap) == 1) {
701 MMI.ReadFromC = MemAccess;
702 isl_map_free(AccMap);
703 return true;
704 }
705 if (isMatMulOperandAcc(AccMap, MMI.i, MMI.k) && !MMI.A &&
706 isl_map_n_basic_map(AccMap) == 1) {
707 MMI.A = MemAccess;
708 isl_map_free(AccMap);
709 return true;
710 }
711 if (isMatMulOperandAcc(AccMap, MMI.k, MMI.j) && !MMI.B &&
712 isl_map_n_basic_map(AccMap) == 1) {
713 MMI.B = MemAccess;
714 isl_map_free(AccMap);
715 return true;
716 }
717 isl_map_free(AccMap);
718 return false;
719}
720
721/// Check accesses to operands of the matrix multiplication.
722///
723/// Check that accesses of the SCoP statement, which corresponds to
724/// the partial schedule @p PartialSchedule, are scalar in terms of loops
725/// containing the matrix multiplication, in case they do not represent
726/// accesses to the non-scalar operands of the matrix multiplication or
727/// its result.
728///
729/// @param PartialSchedule The partial schedule of the SCoP statement.
730/// @param MMI Parameters of the matrix multiplication operands.
731/// @return True in case the corresponding SCoP statement
732/// represents matrix multiplication and false,
733/// otherwise.
734static bool containsOnlyMatrMultAcc(__isl_keep isl_map *PartialSchedule,
735 MatMulInfoTy &MMI) {
736 auto *InputDimId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
737 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimId));
738 isl_id_free(InputDimId);
739 unsigned OutDimNum = isl_map_dim(PartialSchedule, isl_dim_out);
740 assert(OutDimNum > 2 && "In case of the matrix multiplication the loop nest "
741 "and, consequently, the corresponding scheduling "
742 "functions have at least three dimensions.");
743 auto *MapI = permuteDimensions(isl_map_copy(PartialSchedule), isl_dim_out,
744 MMI.i, OutDimNum - 1);
745 auto *MapJ = permuteDimensions(isl_map_copy(PartialSchedule), isl_dim_out,
746 MMI.j, OutDimNum - 1);
747 auto *MapK = permuteDimensions(isl_map_copy(PartialSchedule), isl_dim_out,
748 MMI.k, OutDimNum - 1);
749 for (auto *MemA = Stmt->begin(); MemA != Stmt->end() - 1; MemA++) {
750 auto *MemAccessPtr = *MemA;
751 if (MemAccessPtr->isArrayKind() && MemAccessPtr != MMI.WriteToC &&
752 !isMatMulNonScalarReadAccess(MemAccessPtr, MMI) &&
753 !(MemAccessPtr->isStrideZero(isl_map_copy(MapI)) &&
754 MemAccessPtr->isStrideZero(isl_map_copy(MapJ)) &&
755 MemAccessPtr->isStrideZero(isl_map_copy(MapK)))) {
756 isl_map_free(MapI);
757 isl_map_free(MapJ);
758 isl_map_free(MapK);
759 return false;
760 }
761 }
762 isl_map_free(MapI);
763 isl_map_free(MapJ);
764 isl_map_free(MapK);
765 return true;
766}
767
768/// Check for dependencies corresponding to the matrix multiplication.
769///
770/// Check that there is only true dependence of the form
771/// S(..., k, ...) -> S(..., k + 1, …), where S is the SCoP statement
772/// represented by @p Schedule and k is @p Pos. Such a dependence corresponds
773/// to the dependency produced by the matrix multiplication.
774///
775/// @param Schedule The schedule of the SCoP statement.
776/// @param D The SCoP dependencies.
777/// @param Pos The parameter to desribe an acceptable true dependence.
778/// In case it has a negative value, try to determine its
779/// acceptable value.
780/// @return True in case dependencies correspond to the matrix multiplication
781/// and false, otherwise.
782static bool containsOnlyMatMulDep(__isl_keep isl_map *Schedule,
783 const Dependences *D, int &Pos) {
Roman Gareevb1960552017-02-11 09:59:09 +0000784 auto *Dep = D->getDependences(Dependences::TYPE_RAW);
785 auto *Red = D->getDependences(Dependences::TYPE_RED);
786 if (Red)
787 Dep = isl_union_map_union(Dep, Red);
Roman Gareevafcf0262017-02-11 07:14:37 +0000788 auto *DomainSpace = isl_space_domain(isl_map_get_space(Schedule));
789 auto *Space = isl_space_map_from_domain_and_range(isl_space_copy(DomainSpace),
790 DomainSpace);
Roman Gareevb1960552017-02-11 09:59:09 +0000791 auto *Deltas = isl_map_deltas(isl_union_map_extract_map(Dep, Space));
792 isl_union_map_free(Dep);
Roman Gareev98075fe2017-02-02 14:23:14 +0000793 int DeltasDimNum = isl_set_dim(Deltas, isl_dim_set);
794 for (int i = 0; i < DeltasDimNum; i++) {
795 auto *Val = isl_set_plain_get_val_if_fixed(Deltas, isl_dim_set, i);
Roman Gareevafcf0262017-02-11 07:14:37 +0000796 Pos = Pos < 0 && isl_val_is_one(Val) ? i : Pos;
Roman Gareev98075fe2017-02-02 14:23:14 +0000797 if (isl_val_is_nan(Val) ||
798 !(isl_val_is_zero(Val) || (i == Pos && isl_val_is_one(Val)))) {
799 isl_val_free(Val);
Roman Gareev4eb07e42017-02-16 07:04:41 +0000800 isl_set_free(Deltas);
Roman Gareev98075fe2017-02-02 14:23:14 +0000801 return false;
802 }
803 isl_val_free(Val);
804 }
Roman Gareev4eb07e42017-02-16 07:04:41 +0000805 isl_set_free(Deltas);
Roman Gareevde692932017-02-11 09:48:09 +0000806 if (DeltasDimNum == 0 || Pos < 0)
807 return false;
Roman Gareev98075fe2017-02-02 14:23:14 +0000808 return true;
Roman Gareev9c3eb592016-05-28 16:17:58 +0000809}
810
Tobias Grosserc80d6972016-09-02 06:33:33 +0000811/// Check if the SCoP statement could probably be optimized with analytical
812/// modeling.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000813///
814/// containsMatrMult tries to determine whether the following conditions
815/// are true:
Roman Gareev98075fe2017-02-02 14:23:14 +0000816/// 1. The last memory access modeling an array, MA1, represents writing to
817/// memory and has the form S(..., i1, ..., i2, ...) -> M(i1, i2) or
818/// S(..., i2, ..., i1, ...) -> M(i1, i2), where S is the SCoP statement
819/// under consideration.
820/// 2. There is only one loop-carried true dependency, and it has the
821/// form S(..., i3, ...) -> S(..., i3 + 1, ...), and there are no
822/// loop-carried or anti dependencies.
823/// 3. SCoP contains three access relations, MA2, MA3, and MA4 that represent
824/// reading from memory and have the form S(..., i3, ...) -> M(i1, i3),
825/// S(..., i3, ...) -> M(i3, i2), S(...) -> M(i1, i2), respectively,
826/// and all memory accesses of the SCoP that are different from MA1, MA2,
827/// MA3, and MA4 have stride 0, if the innermost loop is exchanged with any
828/// of loops i1, i2 and i3.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000829///
830/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
831/// to check.
Roman Gareev98075fe2017-02-02 14:23:14 +0000832/// @D The SCoP dependencies.
833/// @MMI Parameters of the matrix multiplication operands.
834static bool containsMatrMult(__isl_keep isl_map *PartialSchedule,
835 const Dependences *D, MatMulInfoTy &MMI) {
836 auto *InputDimsId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
837 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
Roman Gareev9c3eb592016-05-28 16:17:58 +0000838 isl_id_free(InputDimsId);
Roman Gareev98075fe2017-02-02 14:23:14 +0000839 if (Stmt->size() <= 1)
Roman Gareev9c3eb592016-05-28 16:17:58 +0000840 return false;
Roman Gareev98075fe2017-02-02 14:23:14 +0000841 for (auto *MemA = Stmt->end() - 1; MemA != Stmt->begin(); MemA--) {
842 auto *MemAccessPtr = *MemA;
843 if (!MemAccessPtr->isArrayKind())
844 continue;
845 if (!MemAccessPtr->isWrite())
Roman Gareev9c3eb592016-05-28 16:17:58 +0000846 return false;
Roman Gareev98075fe2017-02-02 14:23:14 +0000847 auto *AccMap = MemAccessPtr->getAccessRelation();
848 if (isl_map_n_basic_map(AccMap) != 1 ||
849 !isMatMulOperandAcc(AccMap, MMI.i, MMI.j)) {
850 isl_map_free(AccMap);
851 return false;
852 }
853 isl_map_free(AccMap);
854 MMI.WriteToC = MemAccessPtr;
855 break;
856 }
Roman Gareev9c3eb592016-05-28 16:17:58 +0000857
Roman Gareev98075fe2017-02-02 14:23:14 +0000858 if (!containsOnlyMatMulDep(PartialSchedule, D, MMI.k))
859 return false;
860
861 if (!MMI.WriteToC || !containsOnlyMatrMultAcc(PartialSchedule, MMI))
862 return false;
863
864 if (!MMI.A || !MMI.B || !MMI.ReadFromC)
865 return false;
866 return true;
Roman Gareev9c3eb592016-05-28 16:17:58 +0000867}
868
Tobias Grosserc80d6972016-09-02 06:33:33 +0000869/// Permute two dimensions of the band node.
Roman Gareev3a18a932016-07-25 09:42:53 +0000870///
871/// Permute FirstDim and SecondDim dimensions of the Node.
872///
873/// @param Node The band node to be modified.
874/// @param FirstDim The first dimension to be permuted.
875/// @param SecondDim The second dimension to be permuted.
876static __isl_give isl_schedule_node *
877permuteBandNodeDimensions(__isl_take isl_schedule_node *Node, unsigned FirstDim,
878 unsigned SecondDim) {
879 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band &&
880 isl_schedule_node_band_n_member(Node) > std::max(FirstDim, SecondDim));
881 auto PartialSchedule = isl_schedule_node_band_get_partial_schedule(Node);
882 auto PartialScheduleFirstDim =
883 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, FirstDim);
884 auto PartialScheduleSecondDim =
885 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, SecondDim);
886 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
887 PartialSchedule, SecondDim, PartialScheduleFirstDim);
888 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
889 PartialSchedule, FirstDim, PartialScheduleSecondDim);
890 Node = isl_schedule_node_delete(Node);
891 Node = isl_schedule_node_insert_partial_schedule(Node, PartialSchedule);
892 return Node;
893}
894
Roman Gareev2cb4d132016-07-25 07:27:59 +0000895__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMicroKernel(
896 __isl_take isl_schedule_node *Node, MicroKernelParamsTy MicroKernelParams) {
Roman Gareev8babe1a2016-12-15 11:47:38 +0000897 applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr}, 1);
898 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
899 Node = permuteBandNodeDimensions(Node, 0, 1);
900 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000901}
902
Roman Gareev3a18a932016-07-25 09:42:53 +0000903__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMacroKernel(
904 __isl_take isl_schedule_node *Node, MacroKernelParamsTy MacroKernelParams) {
905 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
906 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
907 MacroKernelParams.Kc == 1)
908 return Node;
Roman Gareev98075fe2017-02-02 14:23:14 +0000909 int DimOutNum = isl_schedule_node_band_n_member(Node);
910 std::vector<int> TileSizes(DimOutNum, 1);
911 TileSizes[DimOutNum - 3] = MacroKernelParams.Mc;
912 TileSizes[DimOutNum - 2] = MacroKernelParams.Nc;
913 TileSizes[DimOutNum - 1] = MacroKernelParams.Kc;
914 Node = tileNode(Node, "1st level tiling", TileSizes, 1);
Roman Gareev3a18a932016-07-25 09:42:53 +0000915 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
Roman Gareev98075fe2017-02-02 14:23:14 +0000916 Node = permuteBandNodeDimensions(Node, DimOutNum - 2, DimOutNum - 1);
917 Node = permuteBandNodeDimensions(Node, DimOutNum - 3, DimOutNum - 1);
Roman Gareev3a18a932016-07-25 09:42:53 +0000918 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
919}
920
Roman Gareev3d4eae32017-02-11 07:00:05 +0000921/// Get the size of the widest type of the matrix multiplication operands
922/// in bytes, including alignment padding.
923///
924/// @param MMI Parameters of the matrix multiplication operands.
925/// @return The size of the widest type of the matrix multiplication operands
926/// in bytes, including alignment padding.
927static uint64_t getMatMulAlignTypeSize(MatMulInfoTy MMI) {
928 auto *S = MMI.A->getStatement()->getParent();
929 auto &DL = S->getFunction().getParent()->getDataLayout();
930 auto ElementSizeA = DL.getTypeAllocSize(MMI.A->getElementType());
931 auto ElementSizeB = DL.getTypeAllocSize(MMI.B->getElementType());
932 auto ElementSizeC = DL.getTypeAllocSize(MMI.WriteToC->getElementType());
933 return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
934}
935
936/// Get the size of the widest type of the matrix multiplication operands
937/// in bits.
938///
939/// @param MMI Parameters of the matrix multiplication operands.
940/// @return The size of the widest type of the matrix multiplication operands
941/// in bits.
942static uint64_t getMatMulTypeSize(MatMulInfoTy MMI) {
943 auto *S = MMI.A->getStatement()->getParent();
944 auto &DL = S->getFunction().getParent()->getDataLayout();
945 auto ElementSizeA = DL.getTypeSizeInBits(MMI.A->getElementType());
946 auto ElementSizeB = DL.getTypeSizeInBits(MMI.B->getElementType());
947 auto ElementSizeC = DL.getTypeSizeInBits(MMI.WriteToC->getElementType());
948 return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
949}
950
Roman Gareev2cb4d132016-07-25 07:27:59 +0000951/// Get parameters of the BLIS micro kernel.
952///
953/// We choose the Mr and Nr parameters of the micro kernel to be large enough
954/// such that no stalls caused by the combination of latencies and dependencies
955/// are introduced during the updates of the resulting matrix of the matrix
956/// multiplication. However, they should also be as small as possible to
957/// release more registers for entries of multiplied matrices.
958///
959/// @param TTI Target Transform Info.
Roman Gareev3d4eae32017-02-11 07:00:05 +0000960/// @param MMI Parameters of the matrix multiplication operands.
Roman Gareev2cb4d132016-07-25 07:27:59 +0000961/// @return The structure of type MicroKernelParamsTy.
962/// @see MicroKernelParamsTy
963static struct MicroKernelParamsTy
Roman Gareev3d4eae32017-02-11 07:00:05 +0000964getMicroKernelParams(const llvm::TargetTransformInfo *TTI, MatMulInfoTy MMI) {
Roman Gareev42402c92016-06-22 09:52:37 +0000965 assert(TTI && "The target transform info should be provided.");
Roman Gareev2cb4d132016-07-25 07:27:59 +0000966
Roman Gareev42402c92016-06-22 09:52:37 +0000967 // Nvec - Number of double-precision floating-point numbers that can be hold
968 // by a vector register. Use 2 by default.
Tobias Grosser67e94fb2017-01-14 07:14:54 +0000969 long RegisterBitwidth = VectorRegisterBitwidth;
970
971 if (RegisterBitwidth == -1)
972 RegisterBitwidth = TTI->getRegisterBitWidth(true);
Roman Gareev3d4eae32017-02-11 07:00:05 +0000973 auto ElementSize = getMatMulTypeSize(MMI);
974 assert(ElementSize > 0 && "The element size of the matrix multiplication "
975 "operands should be greater than zero.");
976 auto Nvec = RegisterBitwidth / ElementSize;
Roman Gareev42402c92016-06-22 09:52:37 +0000977 if (Nvec == 0)
978 Nvec = 2;
979 int Nr =
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000980 ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec;
981 int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000982 return {Mr, Nr};
983}
984
Roman Gareev3a18a932016-07-25 09:42:53 +0000985/// Get parameters of the BLIS macro kernel.
986///
987/// During the computation of matrix multiplication, blocks of partitioned
988/// matrices are mapped to different layers of the memory hierarchy.
989/// To optimize data reuse, blocks should be ideally kept in cache between
990/// iterations. Since parameters of the macro kernel determine sizes of these
991/// blocks, there are upper and lower bounds on these parameters.
992///
993/// @param MicroKernelParams Parameters of the micro-kernel
994/// to be taken into account.
Roman Gareev3d4eae32017-02-11 07:00:05 +0000995/// @param MMI Parameters of the matrix multiplication operands.
Roman Gareev3a18a932016-07-25 09:42:53 +0000996/// @return The structure of type MacroKernelParamsTy.
997/// @see MacroKernelParamsTy
998/// @see MicroKernelParamsTy
999static struct MacroKernelParamsTy
Roman Gareev3d4eae32017-02-11 07:00:05 +00001000getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams,
1001 MatMulInfoTy MMI) {
Roman Gareev3a18a932016-07-25 09:42:53 +00001002 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
1003 // it requires information about the first two levels of a cache to determine
1004 // all the parameters of a macro-kernel. It also checks that an associativity
1005 // degree of a cache level is greater than two. Otherwise, another algorithm
1006 // for determination of the parameters should be used.
1007 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
Roman Gareev1c2927b2016-12-25 16:32:28 +00001008 FirstCacheLevelSize > 0 && SecondCacheLevelSize > 0 &&
1009 FirstCacheLevelAssociativity > 2 && SecondCacheLevelAssociativity > 2))
Roman Gareev3a18a932016-07-25 09:42:53 +00001010 return {1, 1, 1};
Roman Gareevbe5299a2016-12-21 12:51:12 +00001011 // The quotient should be greater than zero.
1012 if (PollyPatternMatchingNcQuotient <= 0)
1013 return {1, 1, 1};
Roman Gareev15db81e2016-12-15 12:00:57 +00001014 int Car = floor(
Roman Gareev1c2927b2016-12-25 16:32:28 +00001015 (FirstCacheLevelAssociativity - 1) /
Roman Gareev8babe1a2016-12-15 11:47:38 +00001016 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
Siddharth Bhat5eeb1dd2017-04-06 08:20:22 +00001017
1018 // Car can be computed to be zero since it is floor to int.
1019 // On Mac OS, division by 0 does not raise a signal. This causes negative
1020 // tile sizes to be computed. Prevent division by 0 Cac by early returning
1021 // if this happens.
1022 if (Car == 0)
1023 return {1, 1, 1};
1024
Roman Gareev3d4eae32017-02-11 07:00:05 +00001025 auto ElementSize = getMatMulAlignTypeSize(MMI);
1026 assert(ElementSize > 0 && "The element size of the matrix multiplication "
1027 "operands should be greater than zero.");
Roman Gareev1c2927b2016-12-25 16:32:28 +00001028 int Kc = (Car * FirstCacheLevelSize) /
Roman Gareev3d4eae32017-02-11 07:00:05 +00001029 (MicroKernelParams.Mr * FirstCacheLevelAssociativity * ElementSize);
1030 double Cac =
1031 static_cast<double>(Kc * ElementSize * SecondCacheLevelAssociativity) /
1032 SecondCacheLevelSize;
Roman Gareev1c2927b2016-12-25 16:32:28 +00001033 int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac);
Roman Gareevbe5299a2016-12-21 12:51:12 +00001034 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
Siddharth Bhat5eeb1dd2017-04-06 08:20:22 +00001035
1036 assert(Mc > 0 && Nc > 0 && Kc > 0 &&
1037 "Matrix block sizes should be greater than zero");
Roman Gareev3a18a932016-07-25 09:42:53 +00001038 return {Mc, Nc, Kc};
1039}
1040
Tobias Grosserc80d6972016-09-02 06:33:33 +00001041/// Create an access relation that is specific to
Roman Gareev1c892e92016-08-15 12:22:54 +00001042/// the matrix multiplication pattern.
1043///
1044/// Create an access relation of the following form:
Roman Gareev92c44602016-12-21 11:18:42 +00001045/// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
1046/// where I is @p FirstDim, J is @p SecondDim.
Roman Gareev1c892e92016-08-15 12:22:54 +00001047///
1048/// It can be used, for example, to create relations that helps to consequently
1049/// access elements of operands of a matrix multiplication after creation of
1050/// the BLIS micro and macro kernels.
1051///
1052/// @see ScheduleTreeOptimizer::createMicroKernel
1053/// @see ScheduleTreeOptimizer::createMacroKernel
1054///
1055/// Subsequently, the described access relation is applied to the range of
1056/// @p MapOldIndVar, that is used to map original induction variables to
1057/// the ones, which are produced by schedule transformations. It helps to
1058/// define relations using a new space and, at the same time, keep them
1059/// in the original one.
1060///
1061/// @param MapOldIndVar The relation, which maps original induction variables
1062/// to the ones, which are produced by schedule
1063/// transformations.
Roman Gareev1c892e92016-08-15 12:22:54 +00001064/// @param FirstDim, SecondDim The input dimensions that are used to define
1065/// the specified access relation.
1066/// @return The specified access relation.
1067__isl_give isl_map *getMatMulAccRel(__isl_take isl_map *MapOldIndVar,
Roman Gareev92c44602016-12-21 11:18:42 +00001068 unsigned FirstDim, unsigned SecondDim) {
Roman Gareev1c892e92016-08-15 12:22:54 +00001069 auto *Ctx = isl_map_get_ctx(MapOldIndVar);
Roman Gareev92c44602016-12-21 11:18:42 +00001070 auto *AccessRelSpace = isl_space_alloc(Ctx, 0, 9, 3);
1071 auto *AccessRel = isl_map_universe(AccessRelSpace);
1072 AccessRel = isl_map_equate(AccessRel, isl_dim_in, FirstDim, isl_dim_out, 0);
1073 AccessRel = isl_map_equate(AccessRel, isl_dim_in, 5, isl_dim_out, 1);
1074 AccessRel = isl_map_equate(AccessRel, isl_dim_in, SecondDim, isl_dim_out, 2);
Roman Gareev1c892e92016-08-15 12:22:54 +00001075 return isl_map_apply_range(MapOldIndVar, AccessRel);
1076}
1077
Roman Gareevb3224ad2016-09-14 06:26:09 +00001078__isl_give isl_schedule_node *
1079createExtensionNode(__isl_take isl_schedule_node *Node,
1080 __isl_take isl_map *ExtensionMap) {
1081 auto *Extension = isl_union_map_from_map(ExtensionMap);
1082 auto *NewNode = isl_schedule_node_from_extension(Extension);
1083 return isl_schedule_node_graft_before(Node, NewNode);
1084}
1085
Tobias Grosserc80d6972016-09-02 06:33:33 +00001086/// Apply the packing transformation.
Roman Gareev1c892e92016-08-15 12:22:54 +00001087///
1088/// The packing transformation can be described as a data-layout
1089/// transformation that requires to introduce a new array, copy data
Roman Gareev7758a2a2017-01-29 10:37:50 +00001090/// to the array, and change memory access locations to reference the array.
1091/// It can be used to ensure that elements of the new array are read in-stride
1092/// access, aligned to cache lines boundaries, and preloaded into certain cache
1093/// levels.
1094///
1095/// As an example let us consider the packing of the array A that would help
1096/// to read its elements with in-stride access. An access to the array A
1097/// is represented by an access relation that has the form
1098/// S[i, j, k] -> A[i, k]. The scheduling function of the SCoP statement S has
1099/// the form S[i,j, k] -> [floor((j mod Nc) / Nr), floor((i mod Mc) / Mr),
1100/// k mod Kc, j mod Nr, i mod Mr].
1101///
1102/// To ensure that elements of the array A are read in-stride access, we add
1103/// a new array Packed_A[Mc/Mr][Kc][Mr] to the SCoP, using
1104/// Scop::createScopArrayInfo, change the access relation
1105/// S[i, j, k] -> A[i, k] to
1106/// S[i, j, k] -> Packed_A[floor((i mod Mc) / Mr), k mod Kc, i mod Mr], using
1107/// MemoryAccess::setNewAccessRelation, and copy the data to the array, using
1108/// the copy statement created by Scop::addScopStmt.
Roman Gareev1c892e92016-08-15 12:22:54 +00001109///
1110/// @param Node The schedule node to be optimized.
1111/// @param MapOldIndVar The relation, which maps original induction variables
1112/// to the ones, which are produced by schedule
1113/// transformations.
1114/// @param MicroParams, MacroParams Parameters of the BLIS kernel
1115/// to be taken into account.
Roman Gareev98075fe2017-02-02 14:23:14 +00001116/// @param MMI Parameters of the matrix multiplication operands.
Roman Gareev1c892e92016-08-15 12:22:54 +00001117/// @return The optimized schedule node.
Roman Gareevb3224ad2016-09-14 06:26:09 +00001118static __isl_give isl_schedule_node *optimizeDataLayoutMatrMulPattern(
1119 __isl_take isl_schedule_node *Node, __isl_take isl_map *MapOldIndVar,
Roman Gareev98075fe2017-02-02 14:23:14 +00001120 MicroKernelParamsTy MicroParams, MacroKernelParamsTy MacroParams,
1121 MatMulInfoTy &MMI) {
Roman Gareev1c892e92016-08-15 12:22:54 +00001122 auto InputDimsId = isl_map_get_tuple_id(MapOldIndVar, isl_dim_in);
1123 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
1124 isl_id_free(InputDimsId);
Roman Gareev2606c482016-12-15 12:35:59 +00001125
1126 // Create a copy statement that corresponds to the memory access to the
1127 // matrix B, the second operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +00001128 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
1129 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
1130 Node = isl_schedule_node_parent(Node);
1131 Node = isl_schedule_node_child(isl_schedule_node_band_split(Node, 2), 0);
Roman Gareev92c44602016-12-21 11:18:42 +00001132 auto *AccRel = getMatMulAccRel(isl_map_copy(MapOldIndVar), 3, 7);
1133 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
1134 unsigned SecondDimSize = MacroParams.Kc;
1135 unsigned ThirdDimSize = MicroParams.Nr;
Roman Gareev1c892e92016-08-15 12:22:54 +00001136 auto *SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev98075fe2017-02-02 14:23:14 +00001137 MMI.B->getElementType(), "Packed_B",
Roman Gareev92c44602016-12-21 11:18:42 +00001138 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +00001139 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev98075fe2017-02-02 14:23:14 +00001140 auto *OldAcc = MMI.B->getAccessRelation();
1141 MMI.B->setNewAccessRelation(AccRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001142 auto *ExtMap =
Roman Gareev98075fe2017-02-02 14:23:14 +00001143 isl_map_project_out(isl_map_copy(MapOldIndVar), isl_dim_out, 2,
1144 isl_map_dim(MapOldIndVar, isl_dim_out) - 2);
1145 ExtMap = isl_map_reverse(ExtMap);
1146 ExtMap = isl_map_fix_si(ExtMap, isl_dim_out, MMI.i, 0);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001147 auto *Domain = Stmt->getDomain();
Roman Gareev2606c482016-12-15 12:35:59 +00001148
1149 // Restrict the domains of the copy statements to only execute when also its
1150 // originating statement is executed.
1151 auto *DomainId = isl_set_get_tuple_id(Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001152 auto *NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev98075fe2017-02-02 14:23:14 +00001153 OldAcc, MMI.B->getAccessRelation(), isl_set_copy(Domain));
Roman Gareev2606c482016-12-15 12:35:59 +00001154 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, isl_id_copy(DomainId));
1155 ExtMap = isl_map_intersect_range(ExtMap, isl_set_copy(Domain));
Roman Gareevb3224ad2016-09-14 06:26:09 +00001156 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
1157 Node = createExtensionNode(Node, ExtMap);
Roman Gareev2606c482016-12-15 12:35:59 +00001158
1159 // Create a copy statement that corresponds to the memory access
1160 // to the matrix A, the first operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +00001161 Node = isl_schedule_node_child(Node, 0);
Roman Gareev98075fe2017-02-02 14:23:14 +00001162 AccRel = getMatMulAccRel(isl_map_copy(MapOldIndVar), 4, 6);
Roman Gareev92c44602016-12-21 11:18:42 +00001163 FirstDimSize = MacroParams.Mc / MicroParams.Mr;
1164 ThirdDimSize = MicroParams.Mr;
Roman Gareev1c892e92016-08-15 12:22:54 +00001165 SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev98075fe2017-02-02 14:23:14 +00001166 MMI.A->getElementType(), "Packed_A",
Roman Gareev92c44602016-12-21 11:18:42 +00001167 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +00001168 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev98075fe2017-02-02 14:23:14 +00001169 OldAcc = MMI.A->getAccessRelation();
1170 MMI.A->setNewAccessRelation(AccRel);
1171 ExtMap = isl_map_project_out(MapOldIndVar, isl_dim_out, 3,
1172 isl_map_dim(MapOldIndVar, isl_dim_out) - 3);
1173 ExtMap = isl_map_reverse(ExtMap);
1174 ExtMap = isl_map_fix_si(ExtMap, isl_dim_out, MMI.j, 0);
1175 NewStmt = Stmt->getParent()->addScopStmt(OldAcc, MMI.A->getAccessRelation(),
1176 isl_set_copy(Domain));
Roman Gareev2606c482016-12-15 12:35:59 +00001177
1178 // Restrict the domains of the copy statements to only execute when also its
1179 // originating statement is executed.
1180 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, DomainId);
1181 ExtMap = isl_map_intersect_range(ExtMap, Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001182 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
1183 Node = createExtensionNode(Node, ExtMap);
1184 Node = isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
1185 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev1c892e92016-08-15 12:22:54 +00001186}
1187
Tobias Grosserc80d6972016-09-02 06:33:33 +00001188/// Get a relation mapping induction variables produced by schedule
1189/// transformations to the original ones.
Roman Gareev1c892e92016-08-15 12:22:54 +00001190///
1191/// @param Node The schedule node produced as the result of creation
1192/// of the BLIS kernels.
1193/// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
1194/// to be taken into account.
1195/// @return The relation mapping original induction variables to the ones
1196/// produced by schedule transformation.
1197/// @see ScheduleTreeOptimizer::createMicroKernel
1198/// @see ScheduleTreeOptimizer::createMacroKernel
1199/// @see getMacroKernelParams
1200__isl_give isl_map *
1201getInductionVariablesSubstitution(__isl_take isl_schedule_node *Node,
1202 MicroKernelParamsTy MicroKernelParams,
1203 MacroKernelParamsTy MacroKernelParams) {
1204 auto *Child = isl_schedule_node_get_child(Node, 0);
1205 auto *UnMapOldIndVar = isl_schedule_node_get_prefix_schedule_union_map(Child);
1206 isl_schedule_node_free(Child);
1207 auto *MapOldIndVar = isl_map_from_union_map(UnMapOldIndVar);
1208 if (isl_map_dim(MapOldIndVar, isl_dim_out) > 9)
1209 MapOldIndVar =
1210 isl_map_project_out(MapOldIndVar, isl_dim_out, 0,
1211 isl_map_dim(MapOldIndVar, isl_dim_out) - 9);
1212 return MapOldIndVar;
1213}
1214
Roman Gareev99890882017-02-09 07:10:01 +00001215/// Isolate a set of partial tile prefixes and unroll the isolated part.
1216///
1217/// The set should ensure that it contains only partial tile prefixes that have
1218/// exactly Mr x Nr iterations of the two innermost loops produced by
1219/// the optimization of the matrix multiplication. Mr and Nr are parameters of
1220/// the micro-kernel.
1221///
1222/// In case of parametric bounds, this helps to auto-vectorize the unrolled
1223/// innermost loops, using the SLP vectorizer.
1224///
1225/// @param Node The schedule node to be modified.
1226/// @param MicroKernelParams Parameters of the micro-kernel
1227/// to be taken into account.
1228/// @return The modified isl_schedule_node.
1229static __isl_give isl_schedule_node *
1230isolateAndUnrollMatMulInnerLoops(__isl_take isl_schedule_node *Node,
1231 struct MicroKernelParamsTy MicroKernelParams) {
1232 auto *Child = isl_schedule_node_get_child(Node, 0);
1233 auto *UnMapOldIndVar = isl_schedule_node_get_prefix_schedule_relation(Child);
1234 isl_schedule_node_free(Child);
1235 auto *Prefix = isl_map_range(isl_map_from_union_map(UnMapOldIndVar));
1236 auto Dims = isl_set_dim(Prefix, isl_dim_set);
1237 Prefix = isl_set_project_out(Prefix, isl_dim_set, Dims - 1, 1);
1238 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Nr);
1239 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Mr);
1240 auto *IsolateOption = getIsolateOptions(
1241 isl_set_add_dims(isl_set_copy(Prefix), isl_dim_set, 3), 3);
1242 auto *Ctx = isl_schedule_node_get_ctx(Node);
1243 auto *AtomicOption = getAtomicOptions(Ctx);
1244 auto *Options =
1245 isl_union_set_union(IsolateOption, isl_union_set_copy(AtomicOption));
1246 Options = isl_union_set_union(Options, getUnrollIsolatedSetOptions(Ctx));
1247 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
1248 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
1249 IsolateOption = getIsolateOptions(Prefix, 3);
1250 Options = isl_union_set_union(IsolateOption, AtomicOption);
1251 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
1252 Node = isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
1253 return Node;
1254}
1255
Roman Gareevcdfb57d2017-03-22 14:25:24 +00001256/// Mark @p BasePtr with "Inter iteration alias-free" mark node.
1257///
1258/// @param Node The child of the mark node to be inserted.
1259/// @param BasePtr The pointer to be marked.
1260/// @return The modified isl_schedule_node.
1261static isl_schedule_node *markInterIterationAliasFree(isl_schedule_node *Node,
1262 llvm::Value *BasePtr) {
1263 if (!BasePtr)
1264 return Node;
1265
1266 auto *Ctx = isl_schedule_node_get_ctx(Node);
1267 auto *Id = isl_id_alloc(Ctx, "Inter iteration alias-free", BasePtr);
1268 return isl_schedule_node_child(isl_schedule_node_insert_mark(Node, Id), 0);
1269}
1270
Roman Gareeve0d46632017-04-06 17:09:54 +00001271/// Restore the initial ordering of dimensions of the band node
1272///
1273/// In case the band node represents all the dimensions of the iteration
1274/// domain, recreate the band node to restore the initial ordering of the
1275/// dimensions.
1276///
1277/// @param Node The band node to be modified.
1278/// @return The modified schedule node.
1279namespace {
1280isl::schedule_node getBandNodeWithOriginDimOrder(isl::schedule_node Node) {
1281 assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band);
1282 if (isl_schedule_node_get_type(Node.child(0).keep()) !=
1283 isl_schedule_node_leaf)
1284 return Node;
1285 auto Domain = isl::manage(isl_schedule_node_get_universe_domain(Node.keep()));
1286 assert(isl_union_set_n_set(Domain.keep()) == 1);
1287 if (isl_schedule_node_get_schedule_depth(Node.keep()) != 0 ||
1288 (isl::set(isl::manage(Domain.copy())).dim(isl::dim::set) !=
1289 isl_schedule_node_band_n_member(Node.keep())))
1290 return Node;
1291 Node = isl::manage(isl_schedule_node_delete(Node.take()));
1292 auto PartialSchedulePwAff =
1293 isl::manage(isl_union_set_identity_union_pw_multi_aff(Domain.take()));
1294 auto PartialScheduleMultiPwAff =
1295 isl::multi_union_pw_aff(PartialSchedulePwAff);
1296 PartialScheduleMultiPwAff = isl::manage(isl_multi_union_pw_aff_reset_tuple_id(
1297 PartialScheduleMultiPwAff.take(), isl_dim_set));
1298 return isl::manage(isl_schedule_node_insert_partial_schedule(
1299 Node.take(), PartialScheduleMultiPwAff.take()));
1300}
1301} // namespace
1302
Roman Gareev2cb4d132016-07-25 07:27:59 +00001303__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeMatMulPattern(
Roman Gareev98075fe2017-02-02 14:23:14 +00001304 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI,
1305 MatMulInfoTy &MMI) {
Roman Gareev2cb4d132016-07-25 07:27:59 +00001306 assert(TTI && "The target transform info should be provided.");
Roman Gareevcdfb57d2017-03-22 14:25:24 +00001307 Node = markInterIterationAliasFree(Node, MMI.WriteToC->getLatestBaseAddr());
Roman Gareev98075fe2017-02-02 14:23:14 +00001308 int DimOutNum = isl_schedule_node_band_n_member(Node);
1309 assert(DimOutNum > 2 && "In case of the matrix multiplication the loop nest "
1310 "and, consequently, the corresponding scheduling "
1311 "functions have at least three dimensions.");
Roman Gareeve0d46632017-04-06 17:09:54 +00001312 Node = getBandNodeWithOriginDimOrder(isl::manage(Node)).take();
Roman Gareev98075fe2017-02-02 14:23:14 +00001313 Node = permuteBandNodeDimensions(Node, MMI.i, DimOutNum - 3);
1314 int NewJ = MMI.j == DimOutNum - 3 ? MMI.i : MMI.j;
1315 int NewK = MMI.k == DimOutNum - 3 ? MMI.i : MMI.k;
1316 Node = permuteBandNodeDimensions(Node, NewJ, DimOutNum - 2);
Roman Gareev9d4d91c2017-04-06 17:25:08 +00001317 NewK = NewK == DimOutNum - 2 ? NewJ : NewK;
Roman Gareev98075fe2017-02-02 14:23:14 +00001318 Node = permuteBandNodeDimensions(Node, NewK, DimOutNum - 1);
Roman Gareev3d4eae32017-02-11 07:00:05 +00001319 auto MicroKernelParams = getMicroKernelParams(TTI, MMI);
1320 auto MacroKernelParams = getMacroKernelParams(MicroKernelParams, MMI);
Roman Gareev3a18a932016-07-25 09:42:53 +00001321 Node = createMacroKernel(Node, MacroKernelParams);
Roman Gareev2cb4d132016-07-25 07:27:59 +00001322 Node = createMicroKernel(Node, MicroKernelParams);
Roman Gareev1c892e92016-08-15 12:22:54 +00001323 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
1324 MacroKernelParams.Kc == 1)
1325 return Node;
1326 auto *MapOldIndVar = getInductionVariablesSubstitution(
1327 Node, MicroKernelParams, MacroKernelParams);
1328 if (!MapOldIndVar)
1329 return Node;
Roman Gareev99890882017-02-09 07:10:01 +00001330 Node = isolateAndUnrollMatMulInnerLoops(Node, MicroKernelParams);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001331 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
Roman Gareev98075fe2017-02-02 14:23:14 +00001332 MacroKernelParams, MMI);
Roman Gareev42402c92016-06-22 09:52:37 +00001333}
1334
Roman Gareev9c3eb592016-05-28 16:17:58 +00001335bool ScheduleTreeOptimizer::isMatrMultPattern(
Roman Gareev98075fe2017-02-02 14:23:14 +00001336 __isl_keep isl_schedule_node *Node, const Dependences *D,
1337 MatMulInfoTy &MMI) {
Roman Gareev9c3eb592016-05-28 16:17:58 +00001338 auto *PartialSchedule =
1339 isl_schedule_node_band_get_partial_schedule_union_map(Node);
Roman Gareeve0d46632017-04-06 17:09:54 +00001340 Node = isl_schedule_node_child(Node, 0);
1341 auto LeafType = isl_schedule_node_get_type(Node);
1342 Node = isl_schedule_node_parent(Node);
1343 if (LeafType != isl_schedule_node_leaf ||
1344 isl_schedule_node_band_n_member(Node) < 3 ||
1345 isl_schedule_node_get_schedule_depth(Node) != 0 ||
Roman Gareev397a34a2016-06-22 12:11:30 +00001346 isl_union_map_n_map(PartialSchedule) != 1) {
1347 isl_union_map_free(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +00001348 return false;
1349 }
Roman Gareev397a34a2016-06-22 12:11:30 +00001350 auto *NewPartialSchedule = isl_map_from_union_map(PartialSchedule);
Roman Gareev98075fe2017-02-02 14:23:14 +00001351 if (containsMatrMult(NewPartialSchedule, D, MMI)) {
Roman Gareev9c3eb592016-05-28 16:17:58 +00001352 isl_map_free(NewPartialSchedule);
1353 return true;
1354 }
1355 isl_map_free(NewPartialSchedule);
1356 return false;
1357}
1358
1359__isl_give isl_schedule_node *
1360ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
1361 void *User) {
1362 if (!isTileableBandNode(Node))
1363 return Node;
1364
Roman Gareev98075fe2017-02-02 14:23:14 +00001365 const OptimizerAdditionalInfoTy *OAI =
1366 static_cast<const OptimizerAdditionalInfoTy *>(User);
1367
1368 MatMulInfoTy MMI;
1369 if (PMBasedOpts && User && isMatrMultPattern(Node, OAI->D, MMI)) {
Roman Gareev9c3eb592016-05-28 16:17:58 +00001370 DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
Roman Gareev772498d2017-02-08 13:29:06 +00001371 return optimizeMatMulPattern(Node, OAI->TTI, MMI);
Roman Gareev42402c92016-06-22 09:52:37 +00001372 }
Roman Gareev9c3eb592016-05-28 16:17:58 +00001373
1374 return standardBandOpts(Node, User);
1375}
1376
Tobias Grosser808cd692015-07-14 09:33:13 +00001377__isl_give isl_schedule *
Roman Gareev42402c92016-06-22 09:52:37 +00001378ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule,
Roman Gareev98075fe2017-02-02 14:23:14 +00001379 const OptimizerAdditionalInfoTy *OAI) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001380 isl_schedule_node *Root = isl_schedule_get_root(Schedule);
Roman Gareev98075fe2017-02-02 14:23:14 +00001381 Root = optimizeScheduleNode(Root, OAI);
Tobias Grosser808cd692015-07-14 09:33:13 +00001382 isl_schedule_free(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001383 auto S = isl_schedule_node_get_schedule(Root);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001384 isl_schedule_node_free(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +00001385 return S;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001386}
1387
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001388__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
Roman Gareev98075fe2017-02-02 14:23:14 +00001389 __isl_take isl_schedule_node *Node, const OptimizerAdditionalInfoTy *OAI) {
Roman Gareev42402c92016-06-22 09:52:37 +00001390 Node = isl_schedule_node_map_descendant_bottom_up(
Roman Gareev98075fe2017-02-02 14:23:14 +00001391 Node, optimizeBand, const_cast<void *>(static_cast<const void *>(OAI)));
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001392 return Node;
1393}
1394
1395bool ScheduleTreeOptimizer::isProfitableSchedule(
Roman Gareevb3224ad2016-09-14 06:26:09 +00001396 Scop &S, __isl_keep isl_schedule *NewSchedule) {
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001397 // To understand if the schedule has been optimized we check if the schedule
1398 // has changed at all.
1399 // TODO: We can improve this by tracking if any necessarily beneficial
1400 // transformations have been performed. This can e.g. be tiling, loop
1401 // interchange, or ...) We can track this either at the place where the
1402 // transformation has been performed or, in case of automatic ILP based
1403 // optimizations, by comparing (yet to be defined) performance metrics
1404 // before/after the scheduling optimizer
1405 // (e.g., #stride-one accesses)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001406 if (S.containsExtensionNode(NewSchedule))
1407 return true;
1408 auto *NewScheduleMap = isl_schedule_get_map(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001409 isl_union_map *OldSchedule = S.getSchedule();
Tobias Grosserff400872017-02-01 10:12:09 +00001410 assert(OldSchedule && "Only IslScheduleOptimizer can insert extension nodes "
1411 "that make Scop::getSchedule() return nullptr.");
Roman Gareevb3224ad2016-09-14 06:26:09 +00001412 bool changed = !isl_union_map_is_equal(OldSchedule, NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001413 isl_union_map_free(OldSchedule);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001414 isl_union_map_free(NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001415 return changed;
1416}
1417
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001418namespace {
1419class IslScheduleOptimizer : public ScopPass {
1420public:
1421 static char ID;
1422 explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
1423
1424 ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
1425
Tobias Grosserc80d6972016-09-02 06:33:33 +00001426 /// Optimize the schedule of the SCoP @p S.
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001427 bool runOnScop(Scop &S) override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001428
Tobias Grosserc80d6972016-09-02 06:33:33 +00001429 /// Print the new schedule for the SCoP @p S.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001430 void printScop(raw_ostream &OS, Scop &S) const override;
1431
Tobias Grosserc80d6972016-09-02 06:33:33 +00001432 /// Register all analyses and transformation required.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001433 void getAnalysisUsage(AnalysisUsage &AU) const override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001434
Tobias Grosserc80d6972016-09-02 06:33:33 +00001435 /// Release the internal memory.
Johannes Doerfert0f376302015-09-27 15:42:28 +00001436 void releaseMemory() override {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001437 isl_schedule_free(LastSchedule);
1438 LastSchedule = nullptr;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001439 }
Johannes Doerfert45be6442015-09-27 15:43:29 +00001440
1441private:
1442 isl_schedule *LastSchedule;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001443};
Tobias Grosser522478d2016-06-23 22:17:27 +00001444} // namespace
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001445
1446char IslScheduleOptimizer::ID = 0;
1447
Tobias Grosser73600b82011-10-08 00:30:40 +00001448bool IslScheduleOptimizer::runOnScop(Scop &S) {
Johannes Doerfert6f7921f2015-02-14 12:02:24 +00001449
1450 // Skip empty SCoPs but still allow code generation as it will delete the
1451 // loops present but not needed.
1452 if (S.getSize() == 0) {
1453 S.markAsOptimized();
1454 return false;
1455 }
1456
Hongbin Zheng2a798852016-03-03 08:15:33 +00001457 const Dependences &D =
1458 getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001459
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001460 if (!D.hasValidDependences())
Tobias Grosser38c36ea2014-02-23 15:15:44 +00001461 return false;
1462
Tobias Grosser28781422012-10-16 07:29:19 +00001463 isl_schedule_free(LastSchedule);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001464 LastSchedule = nullptr;
Tobias Grosser28781422012-10-16 07:29:19 +00001465
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001466 // Build input data.
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001467 int ValidityKinds =
1468 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001469 int ProximityKinds;
1470
1471 if (OptimizeDeps == "all")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001472 ProximityKinds =
1473 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001474 else if (OptimizeDeps == "raw")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001475 ProximityKinds = Dependences::TYPE_RAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001476 else {
1477 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001478 << " Falling back to optimizing all dependences.\n";
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001479 ProximityKinds =
1480 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001481 }
1482
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001483 isl_union_set *Domain = S.getDomains();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001484
Tobias Grosser98610ee2012-02-13 23:31:39 +00001485 if (!Domain)
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001486 return false;
1487
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001488 isl_union_map *Validity = D.getDependences(ValidityKinds);
1489 isl_union_map *Proximity = D.getDependences(ProximityKinds);
Tobias Grosser8a507022012-03-16 11:51:41 +00001490
Tobias Grossera26db472012-01-30 19:38:43 +00001491 // Simplify the dependences by removing the constraints introduced by the
1492 // domains. This can speed up the scheduling time significantly, as large
1493 // constant coefficients will be removed from the dependences. The
1494 // introduction of some additional dependences reduces the possible
1495 // transformations, but in most cases, such transformation do not seem to be
1496 // interesting anyway. In some cases this option may stop the scheduler to
1497 // find any schedule.
1498 if (SimplifyDeps == "yes") {
Tobias Grosser00383a72012-02-14 14:02:44 +00001499 Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
1500 Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001501 Proximity =
1502 isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
Tobias Grosser00383a72012-02-14 14:02:44 +00001503 Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
Tobias Grossera26db472012-01-30 19:38:43 +00001504 } else if (SimplifyDeps != "no") {
1505 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
1506 "or 'no'. Falling back to default: 'yes'\n";
1507 }
1508
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001509 DEBUG(dbgs() << "\n\nCompute schedule from: ");
Tobias Grosser01aea582014-10-22 23:16:28 +00001510 DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
1511 DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
1512 DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001513
Michael Krusec59f22c2015-06-18 16:45:40 +00001514 unsigned IslSerializeSCCs;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001515
1516 if (FusionStrategy == "max") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001517 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001518 } else if (FusionStrategy == "min") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001519 IslSerializeSCCs = 1;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001520 } else {
1521 errs() << "warning: Unknown fusion strategy. Falling back to maximal "
1522 "fusion.\n";
Michael Krusec59f22c2015-06-18 16:45:40 +00001523 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001524 }
1525
Tobias Grosser95e860c2012-01-30 19:38:54 +00001526 int IslMaximizeBands;
1527
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001528 if (MaximizeBandDepth == "yes") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001529 IslMaximizeBands = 1;
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001530 } else if (MaximizeBandDepth == "no") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001531 IslMaximizeBands = 0;
1532 } else {
1533 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
1534 " or 'no'. Falling back to default: 'yes'\n";
1535 IslMaximizeBands = 1;
1536 }
1537
Michael Kruse315aa322016-05-02 11:35:27 +00001538 int IslOuterCoincidence;
1539
1540 if (OuterCoincidence == "yes") {
1541 IslOuterCoincidence = 1;
1542 } else if (OuterCoincidence == "no") {
1543 IslOuterCoincidence = 0;
1544 } else {
1545 errs() << "warning: Option -polly-opt-outer-coincidence should either be "
1546 "'yes' or 'no'. Falling back to default: 'no'\n";
1547 IslOuterCoincidence = 0;
1548 }
1549
Tobias Grosseraf149932016-06-30 20:42:56 +00001550 isl_ctx *Ctx = S.getIslCtx();
Tobias Grosser42152ff2012-01-30 19:38:47 +00001551
Tobias Grosseraf149932016-06-30 20:42:56 +00001552 isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
1553 isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs);
1554 isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
1555 isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
1556 isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
1557 isl_options_set_tile_scale_tile_loops(Ctx, 0);
1558
Tobias Grosser3898a042016-06-30 20:42:58 +00001559 auto OnErrorStatus = isl_options_get_on_error(Ctx);
Tobias Grosseraf149932016-06-30 20:42:56 +00001560 isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
Tobias Grossera38c9242014-01-26 19:36:28 +00001561
1562 isl_schedule_constraints *ScheduleConstraints;
1563 ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
1564 ScheduleConstraints =
1565 isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
1566 ScheduleConstraints = isl_schedule_constraints_set_validity(
1567 ScheduleConstraints, isl_union_map_copy(Validity));
1568 ScheduleConstraints =
1569 isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
Tobias Grosser00383a72012-02-14 14:02:44 +00001570 isl_schedule *Schedule;
Tobias Grossera38c9242014-01-26 19:36:28 +00001571 Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
Tobias Grosser3898a042016-06-30 20:42:58 +00001572 isl_options_set_on_error(Ctx, OnErrorStatus);
Tobias Grosser42152ff2012-01-30 19:38:47 +00001573
1574 // In cases the scheduler is not able to optimize the code, we just do not
1575 // touch the schedule.
Tobias Grosser98610ee2012-02-13 23:31:39 +00001576 if (!Schedule)
Tobias Grosser42152ff2012-01-30 19:38:47 +00001577 return false;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001578
Tobias Grosser97d87452015-05-30 06:46:59 +00001579 DEBUG({
Tobias Grosseraf149932016-06-30 20:42:56 +00001580 auto *P = isl_printer_to_str(Ctx);
Tobias Grosser97d87452015-05-30 06:46:59 +00001581 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1582 P = isl_printer_print_schedule(P, Schedule);
Michael Kruse79c01732016-12-12 14:51:06 +00001583 auto *str = isl_printer_get_str(P);
1584 dbgs() << "NewScheduleTree: \n" << str << "\n";
1585 free(str);
Tobias Grosser97d87452015-05-30 06:46:59 +00001586 isl_printer_free(P);
1587 });
Tobias Grosser4d63b9d2012-02-20 08:41:21 +00001588
Roman Gareev42402c92016-06-22 09:52:37 +00001589 Function &F = S.getFunction();
1590 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Roman Gareev98075fe2017-02-02 14:23:14 +00001591 const OptimizerAdditionalInfoTy OAI = {TTI, const_cast<Dependences *>(&D)};
Roman Gareev42402c92016-06-22 09:52:37 +00001592 isl_schedule *NewSchedule =
Roman Gareev98075fe2017-02-02 14:23:14 +00001593 ScheduleTreeOptimizer::optimizeSchedule(Schedule, &OAI);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001594
Roman Gareevb3224ad2016-09-14 06:26:09 +00001595 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule)) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001596 isl_schedule_free(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001597 return false;
1598 }
1599
Tobias Grosser808cd692015-07-14 09:33:13 +00001600 S.setScheduleTree(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001601 S.markAsOptimized();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001602
Roman Gareev5f99f862016-08-21 11:20:39 +00001603 if (OptimizedScops)
1604 S.dump();
1605
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001606 return false;
1607}
1608
Johannes Doerfert3fe584d2015-03-01 18:40:25 +00001609void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
Tobias Grosser28781422012-10-16 07:29:19 +00001610 isl_printer *p;
1611 char *ScheduleStr;
1612
1613 OS << "Calculated schedule:\n";
1614
1615 if (!LastSchedule) {
1616 OS << "n/a\n";
1617 return;
1618 }
1619
1620 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
1621 p = isl_printer_print_schedule(p, LastSchedule);
1622 ScheduleStr = isl_printer_get_str(p);
1623 isl_printer_free(p);
1624
1625 OS << ScheduleStr << "\n";
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001626}
1627
Tobias Grosser73600b82011-10-08 00:30:40 +00001628void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001629 ScopPass::getAnalysisUsage(AU);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001630 AU.addRequired<DependenceInfo>();
Roman Gareev42402c92016-06-22 09:52:37 +00001631 AU.addRequired<TargetTransformInfoWrapperPass>();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001632}
1633
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001634Pass *polly::createIslScheduleOptimizerPass() {
Tobias Grosser73600b82011-10-08 00:30:40 +00001635 return new IslScheduleOptimizer();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001636}
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001637
1638INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
1639 "Polly - Optimize schedule of SCoP", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001640INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Johannes Doerfert99191c72016-05-31 09:41:04 +00001641INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
Roman Gareev42402c92016-06-22 09:52:37 +00001642INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001643INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
1644 "Polly - Optimize schedule of SCoP", false, false)