Polly 24.0.0git
MatmulOptimizer.cpp
Go to the documentation of this file.
1//===- MatmulOptimizer.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "polly/Options.h"
13#include "polly/ScopInfo.h"
14#include "polly/Simplify.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetOperations.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/TypeSize.h"
31#include "llvm/Support/raw_ostream.h"
32#include "isl/ctx.h"
33#include "isl/schedule_node.h"
34#include "isl/schedule_type.h"
35#include "isl/union_map.h"
36#include "isl/union_set.h"
37#include <algorithm>
38#include <cassert>
39#include <cmath>
40#include <cstdint>
41#include <string>
42#include <vector>
43
45#define DEBUG_TYPE "polly-opt-isl"
46
47using namespace llvm;
48using namespace polly;
49
50namespace llvm {
51class Value;
52}
53
54static cl::opt<int> LatencyVectorFma(
55 "polly-target-latency-vector-fma",
56 cl::desc("The minimal number of cycles between issuing two "
57 "dependent consecutive vector fused multiply-add "
58 "instructions."),
59 cl::Hidden, cl::init(8), cl::cat(PollyCategory));
60
61static cl::opt<int> ThroughputVectorFma(
62 "polly-target-throughput-vector-fma",
63 cl::desc("A throughput of the processor floating-point arithmetic units "
64 "expressed in the number of vector fused multiply-add "
65 "instructions per clock cycle."),
66 cl::Hidden, cl::init(1), cl::cat(PollyCategory));
67
68static cl::opt<int> FirstCacheLevelSize(
69 "polly-target-1st-cache-level-size",
70 cl::desc("The size of the first cache level specified in bytes."),
71 cl::Hidden, cl::init(-1), cl::cat(PollyCategory));
72
73static cl::opt<int> FirstCacheLevelDefaultSize(
74 "polly-target-1st-cache-level-default-size",
75 cl::desc("The default size of the first cache level specified in bytes"
76 " (if not enough were provided by the TargetTransformInfo)."),
77 cl::Hidden, cl::init(32768), cl::cat(PollyCategory));
78
79static cl::opt<int> SecondCacheLevelSize(
80 "polly-target-2nd-cache-level-size",
81 cl::desc("The size of the second level specified in bytes."), cl::Hidden,
82 cl::init(-1), cl::cat(PollyCategory));
83
84static cl::opt<int> SecondCacheLevelDefaultSize(
85 "polly-target-2nd-cache-level-default-size",
86 cl::desc("The default size of the second cache level specified in bytes"
87 " (if not enough were provided by the TargetTransformInfo)."),
88 cl::Hidden, cl::init(262144), cl::cat(PollyCategory));
89
90// This option, along with --polly-target-2nd-cache-level-associativity,
91// --polly-target-1st-cache-level-size, and --polly-target-2st-cache-level-size
92// represent the parameters of the target cache, which do not have typical
93// values that can be used by default. However, to apply the pattern matching
94// optimizations, we use the values of the parameters of Intel Core i7-3820
95// SandyBridge in case the parameters are not specified or not provided by the
96// TargetTransformInfo.
97static cl::opt<int> FirstCacheLevelAssociativity(
98 "polly-target-1st-cache-level-associativity",
99 cl::desc("The associativity of the first cache level."), cl::Hidden,
100 cl::init(-1), cl::cat(PollyCategory));
101
103 "polly-target-1st-cache-level-default-associativity",
104 cl::desc("The default associativity of the first cache level"
105 " (if not enough were provided by the TargetTransformInfo)."),
106 cl::Hidden, cl::init(8), cl::cat(PollyCategory));
107
109 "polly-target-2nd-cache-level-associativity",
110 cl::desc("The associativity of the second cache level."), cl::Hidden,
111 cl::init(-1), cl::cat(PollyCategory));
112
114 "polly-target-2nd-cache-level-default-associativity",
115 cl::desc("The default associativity of the second cache level"
116 " (if not enough were provided by the TargetTransformInfo)."),
117 cl::Hidden, cl::init(8), cl::cat(PollyCategory));
118
119static cl::opt<int> VectorRegisterBitwidth(
120 "polly-target-vector-register-bitwidth",
121 cl::desc("The size in bits of a vector register (if not set, this "
122 "information is taken from LLVM's target information."),
123 cl::Hidden, cl::init(-1), cl::cat(PollyCategory));
124
126 "polly-pattern-matching-nc-quotient",
127 cl::desc("Quotient that is obtained by dividing Nc, the parameter of the"
128 "macro-kernel, by Nr, the parameter of the micro-kernel"),
129 cl::Hidden, cl::init(256), cl::cat(PollyCategory));
130
131static cl::opt<int> MaxStackArraySize(
132 "polly-pattern-matching-max-stack-array-size",
133 cl::desc("The maximal size in bytes of a packed array of the matrix "
134 "multiplication optimization that is allocated on the stack; "
135 "larger ones are allocated on the heap (-1: all on the stack, "
136 "0: all on the heap)"),
137 cl::Hidden, cl::init(1024 * 1024), cl::cat(PollyCategory));
138
139static cl::opt<bool>
140 PMBasedTCOpts("polly-tc-opt",
141 cl::desc("Perform optimizations of tensor contractions based "
142 "on pattern matching"),
143 cl::init(false), cl::cat(PollyCategory));
144
145static cl::opt<bool>
146 PMBasedMMMOpts("polly-matmul-opt",
147 cl::desc("Perform optimizations of matrix multiplications "
148 "based on pattern matching"),
149 cl::init(true), cl::cat(PollyCategory));
150
151static cl::opt<int> OptComputeOut(
152 "polly-tc-dependences-computeout",
153 cl::desc("Bound the dependence analysis by a maximal amount of "
154 "computational steps (0 means no bound)"),
155 cl::Hidden, cl::init(500000), cl::cat(PollyCategory));
156
157namespace {
158/// Parameters of the micro kernel.
159///
160/// Parameters, which determine sizes of rank-1 (i.e., outer product) update
161/// used in the optimized matrix multiplication.
162struct MicroKernelParamsTy {
163 int Mr;
164 int Nr;
165};
166
167/// Parameters of the macro kernel.
168///
169/// Parameters, which determine sizes of blocks of partitioned matrices
170/// used in the optimized matrix multiplication.
171struct MacroKernelParamsTy {
172 int Mc;
173 int Nc;
174 int Kc;
175};
176
177/// Parameters of the matrix multiplication operands.
178///
179/// Parameters, which describe access relations that represent operands of the
180/// matrix multiplication.
181struct MatMulInfoTy {
182 MemoryAccess *A = nullptr;
183 MemoryAccess *B = nullptr;
184 MemoryAccess *ReadFromC = nullptr;
185 MemoryAccess *WriteToC = nullptr;
186 int i = -1;
187 int j = -1;
188 int k = -1;
189};
190
191/// Parameters of the tensor contraction operands.
192///
193/// A general d-dimensional tensor T ∈ R ^ Nu0 x ... x Nud−1 can be defined
194/// as the set of scalar elements indexed by the set of indices u0 ... ud,
195///
196/// T ≡ {Anu0...nud−1 ∈ R | (u0,...,ud−1) ∈ Nu0 x ... x Nud−1}.
197///
198/// Let A, B, and C be dA, dB, and dC-dimensional tensors, respectively.
199/// Let the free and the contracted indices of the tensor A be grouped into
200/// two bundles I = i0...ir−1 and P = p0...pt−1, respectively. Similarly,
201/// the free and the contracted indices of B are grouped into bundles
202/// J = j0..js−1 and P and the free indices of C are grouped into
203/// bundles I and J.
204///
205/// Tensor contraction (TC) of tensors A, B into tensor C can be represented as
206/// C(shuffle(I,J))=∑α·A(shuffle(I,P))·B(shuffle(P,J))+β·C(shuffle(I,J)),
207/// where ∑ is a summation over all contracted indices of P,
208/// α, β ∈ R, Npi is the length of the tensor dimension that corresponds
209/// to the index pi, A(shuffle(I, P)), B(shuffle(P, J)), C(shuffle(I, J)) are
210/// accesses to tensors A, B, C, respectively,
211/// shuffle(I, J), shuffle(I, P), and shuffle(P, J) are permutations of
212/// the enclosed indices.
213///
214/// Multiplication of C(shuffle(I,J)) by β can be moved into a different SCoP
215/// statement by loop distribution, which is done by the isl scheduler.
216// If β is not equal to one, the optimization of TC of Polly requires
217/// such a transformation.
218///
219/// TCInfoTy contains parameters, which describe access relations that represent
220/// operands of the tensor contraction.
221struct TCInfoTy {
222 /// @{
223 /// Memory accesses that represent reading from tensors, which are operands of
224 /// the tensor contraction.
225 MemoryAccess *A = nullptr;
226 MemoryAccess *B = nullptr;
227 /// @}
228
229 /// @{
230 /// Memory accesses that represent reading from and writing into the tensor,
231 /// which contains the result of the tensor contraction.
232 MemoryAccess *ReadFromC = nullptr;
233 MemoryAccess *WriteToC = nullptr;
234 /// @}
235
236 /// @{
237 /// Input dimensions of the schedule space, which represent free
238 /// indices of tensors.
239 SmallDenseSet<int> I;
240 SmallDenseSet<int> J;
241 /// @}
242
243 /// Input dimension of the schedule space, which represents contracted
244 /// indices of tensors.
245 SmallDenseSet<int> P;
246
247 /// @{
248 /// Sizes of tensor dimensions for corresponding input dimensions of
249 /// the schedule space. The size of the tensor dimension can be larger than
250 /// the size of the corresponding input dimension of the schedule space.
251 /// This does not correspond to a tensor contraction. However, such a pattern
252 /// will be optimized by the transformation.
253 SmallVector<int> DimensionSizes;
254 SmallVector<int> ADimensions;
255 SmallVector<int> BDimensions;
256 SmallVector<int> CDimensions;
257 /// @}
258
259 /// @{
260 /// Permutations of indices of I, J, and P, which describe operands of
261 /// the tensor contraction and its result.
262 SmallVector<int> OrderedI;
263 SmallVector<int> OrderedJ;
264 SmallVector<int> OrderedP;
265 /// @}
266};
267
268/// Create an isl::union_set, which describes the option of the form
269/// [isolate[] -> unroll[x]].
270///
271/// @param Ctx An isl::ctx, which is used to create the isl::union_set.
272static isl::union_set getUnrollIsolatedSetOptions(isl::ctx Ctx) {
273 isl::space Space = isl::space(Ctx, 0, 0, 1);
274 isl::map UnrollIsolatedSetOption = isl::map::universe(Space);
275 isl::id DimInId = isl::id::alloc(Ctx, "isolate", nullptr);
276 isl::id DimOutId = isl::id::alloc(Ctx, "unroll", nullptr);
277 UnrollIsolatedSetOption =
278 UnrollIsolatedSetOption.set_tuple_id(isl::dim::in, DimInId);
279 UnrollIsolatedSetOption =
280 UnrollIsolatedSetOption.set_tuple_id(isl::dim::out, DimOutId);
281 return UnrollIsolatedSetOption.wrap();
282}
283
284/// Permute the two dimensions of the isl map.
285///
286/// Permute @p DstPos and @p SrcPos dimensions of the isl map @p Map that
287/// have type @p DimType.
288///
289/// @param Map The isl map to be modified.
290/// @param DimType The type of the dimensions.
291/// @param DstPos The first dimension.
292/// @param SrcPos The second dimension.
293/// @return The modified map.
294static isl::map permuteDimensions(isl::map Map, isl::dim DimType,
295 unsigned DstPos, unsigned SrcPos) {
296 assert(DstPos < unsignedFromIslSize(Map.dim(DimType)) &&
297 SrcPos < unsignedFromIslSize(Map.dim(DimType)));
298 if (DstPos == SrcPos)
299 return Map;
300 isl::id DimId;
301 if (Map.has_tuple_id(DimType))
302 DimId = Map.get_tuple_id(DimType);
303 auto FreeDim = DimType == isl::dim::in ? isl::dim::out : isl::dim::in;
304 isl::id FreeDimId;
305 if (Map.has_tuple_id(FreeDim))
306 FreeDimId = Map.get_tuple_id(FreeDim);
307 auto MaxDim = std::max(DstPos, SrcPos);
308 auto MinDim = std::min(DstPos, SrcPos);
309 Map = Map.move_dims(FreeDim, 0, DimType, MaxDim, 1);
310 Map = Map.move_dims(FreeDim, 0, DimType, MinDim, 1);
311 Map = Map.move_dims(DimType, MinDim, FreeDim, 1, 1);
312 Map = Map.move_dims(DimType, MaxDim, FreeDim, 0, 1);
313 if (!DimId.is_null())
314 Map = Map.set_tuple_id(DimType, DimId);
315 if (!FreeDimId.is_null())
316 Map = Map.set_tuple_id(FreeDim, FreeDimId);
317 return Map;
318}
319
320/// Check the form of the access relation.
321///
322/// Check that the access relation @p AccMap has the form M[i][j], where i
323/// is a @p FirstPos and j is a @p SecondPos.
324///
325/// @param AccMap The access relation to be checked.
326/// @param FirstPos The index of the input dimension that is mapped to
327/// the first output dimension.
328/// @param SecondPos The index of the input dimension that is mapped to the
329/// second output dimension.
330/// @return True in case @p AccMap has the expected form and false,
331/// otherwise.
332static bool isMatMulOperandAcc(isl::set Domain, isl::map AccMap, int &FirstPos,
333 int &SecondPos) {
334 isl::space Space = AccMap.get_space();
335 isl::map Universe = isl::map::universe(Space);
336
337 if (unsignedFromIslSize(Space.dim(isl::dim::out)) != 2)
338 return false;
339
340 // MatMul has the form:
341 // for (i = 0; i < N; i++)
342 // for (j = 0; j < M; j++)
343 // for (k = 0; k < P; k++)
344 // C[i, j] += A[i, k] * B[k, j]
345 //
346 // Permutation of three outer loops: 3! = 6 possibilities.
347 int FirstDims[] = {0, 0, 1, 1, 2, 2};
348 int SecondDims[] = {1, 2, 2, 0, 0, 1};
349 for (int i = 0; i < 6; i += 1) {
350 auto PossibleMatMul =
351 Universe.equate(isl::dim::in, FirstDims[i], isl::dim::out, 0)
352 .equate(isl::dim::in, SecondDims[i], isl::dim::out, 1);
353
354 AccMap = AccMap.intersect_domain(Domain);
355 PossibleMatMul = PossibleMatMul.intersect_domain(Domain);
356
357 // If AccMap spans entire domain (Non-partial write),
358 // compute FirstPos and SecondPos.
359 // If AccMap != PossibleMatMul here (the two maps have been gisted at
360 // this point), it means that the writes are not complete, or in other
361 // words, it is a Partial write and Partial writes must be rejected.
362 if (AccMap.is_equal(PossibleMatMul)) {
363 if (FirstPos != -1 && FirstPos != FirstDims[i])
364 continue;
365 FirstPos = FirstDims[i];
366 if (SecondPos != -1 && SecondPos != SecondDims[i])
367 continue;
368 SecondPos = SecondDims[i];
369 return true;
370 }
371 }
372
373 return false;
374}
375
376/// Does the memory access represent a non-scalar operand of the matrix
377/// multiplication.
378///
379/// Check that the memory access @p MemAccess is the read access to a non-scalar
380/// operand of the matrix multiplication or its result.
381///
382/// @param MemAccess The memory access to be checked.
383/// @param MMI Parameters of the matrix multiplication operands.
384/// @return True in case the memory access represents the read access
385/// to a non-scalar operand of the matrix multiplication and
386/// false, otherwise.
387static bool isMatMulNonScalarReadAccess(MemoryAccess *MemAccess,
388 MatMulInfoTy &MMI) {
389 if (!MemAccess->isLatestArrayKind() || !MemAccess->isRead())
390 return false;
391 auto AccMap = MemAccess->getLatestAccessRelation();
392 isl::set StmtDomain = MemAccess->getStatement()->getDomain();
393 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.i, MMI.j) && !MMI.ReadFromC) {
394 MMI.ReadFromC = MemAccess;
395 return true;
396 }
397 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.i, MMI.k) && !MMI.A) {
398 MMI.A = MemAccess;
399 return true;
400 }
401 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.k, MMI.j) && !MMI.B) {
402 MMI.B = MemAccess;
403 return true;
404 }
405 return false;
406}
407
408/// Check accesses to operands of the matrix multiplication.
409///
410/// Check that accesses of the SCoP statement, which corresponds to
411/// the partial schedule @p PartialSchedule, are scalar in terms of loops
412/// containing the matrix multiplication, in case they do not represent
413/// accesses to the non-scalar operands of the matrix multiplication or
414/// its result.
415///
416/// @param PartialSchedule The partial schedule of the SCoP statement.
417/// @param MMI Parameters of the matrix multiplication operands.
418/// @return True in case the corresponding SCoP statement
419/// represents matrix multiplication and false,
420/// otherwise.
421static bool containsOnlyMatrMultAcc(isl::map PartialSchedule,
422 MatMulInfoTy &MMI) {
423 auto InputDimId = PartialSchedule.get_tuple_id(isl::dim::in);
424 auto *Stmt = static_cast<ScopStmt *>(InputDimId.get_user());
425 unsigned OutDimNum = unsignedFromIslSize(PartialSchedule.range_tuple_dim());
426 assert(OutDimNum > 2 && "In case of the matrix multiplication the loop nest "
427 "and, consequently, the corresponding scheduling "
428 "functions have at least three dimensions.");
429 auto MapI =
430 permuteDimensions(PartialSchedule, isl::dim::out, MMI.i, OutDimNum - 1);
431 auto MapJ =
432 permuteDimensions(PartialSchedule, isl::dim::out, MMI.j, OutDimNum - 1);
433 auto MapK =
434 permuteDimensions(PartialSchedule, isl::dim::out, MMI.k, OutDimNum - 1);
435
436 auto Accesses = getAccessesInOrder(*Stmt);
437 for (auto *MemA = Accesses.begin(); MemA != Accesses.end() - 1; MemA++) {
438 auto *MemAccessPtr = *MemA;
439 if (MemAccessPtr->isLatestArrayKind() && MemAccessPtr != MMI.WriteToC &&
440 !isMatMulNonScalarReadAccess(MemAccessPtr, MMI) &&
441 !(MemAccessPtr->isStrideZero(MapI) &&
442 MemAccessPtr->isStrideZero(MapJ) && MemAccessPtr->isStrideZero(MapK)))
443 return false;
444 }
445 return true;
446}
447
448/// Check for dependencies corresponding to the matrix multiplication.
449///
450/// Check that there is only true dependence of the form
451/// S(..., k, ...) -> S(..., k + 1, …), where S is the SCoP statement
452/// represented by @p Schedule and k is @p Pos. Such a dependence corresponds
453/// to the dependency produced by the matrix multiplication.
454///
455/// @param Schedule The schedule of the SCoP statement.
456/// @param D The SCoP dependencies.
457/// @param Pos The parameter to describe an acceptable true dependence.
458/// In case it has a negative value, try to determine its
459/// acceptable value.
460/// @return True in case dependencies correspond to the matrix multiplication
461/// and false, otherwise.
462static bool containsOnlyMatMulDep(isl::map Schedule, const Dependences *D,
463 int &Pos) {
464 isl::union_map Dep = D->getDependences(Dependences::TYPE_RAW);
465 isl::union_map Red = D->getDependences(Dependences::TYPE_RED);
466 if (!Red.is_null())
467 Dep = Dep.unite(Red);
468 auto DomainSpace = Schedule.get_space().domain();
469 auto Space = DomainSpace.map_from_domain_and_range(DomainSpace);
470 auto Deltas = Dep.extract_map(Space).deltas();
471 int DeltasDimNum = unsignedFromIslSize(Deltas.dim(isl::dim::set));
472 for (int i = 0; i < DeltasDimNum; i++) {
473 auto Val = Deltas.plain_get_val_if_fixed(isl::dim::set, i);
474 Pos = Pos < 0 && Val.is_one() ? i : Pos;
475 if (Val.is_nan() || !(Val.is_zero() || (i == Pos && Val.is_one())))
476 return false;
477 }
478 if (DeltasDimNum == 0 || Pos < 0)
479 return false;
480 return true;
481}
482
483/// Check if the SCoP statement could probably be optimized with analytical
484/// modeling.
485///
486/// containsMatrMult tries to determine whether the following conditions
487/// are true:
488/// 1. The last memory access modeling an array, MA1, represents writing to
489/// memory and has the form S(..., i1, ..., i2, ...) -> M(i1, i2) or
490/// S(..., i2, ..., i1, ...) -> M(i1, i2), where S is the SCoP statement
491/// under consideration.
492/// 2. There is only one loop-carried true dependency, and it has the
493/// form S(..., i3, ...) -> S(..., i3 + 1, ...), and there are no
494/// loop-carried or anti dependencies.
495/// 3. SCoP contains three access relations, MA2, MA3, and MA4 that represent
496/// reading from memory and have the form S(..., i3, ...) -> M(i1, i3),
497/// S(..., i3, ...) -> M(i3, i2), S(...) -> M(i1, i2), respectively,
498/// and all memory accesses of the SCoP that are different from MA1, MA2,
499/// MA3, and MA4 have stride 0, if the innermost loop is exchanged with any
500/// of loops i1, i2 and i3.
501///
502/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
503/// to check.
504/// @D The SCoP dependencies.
505/// @MMI Parameters of the matrix multiplication operands.
506static bool containsMatrMult(isl::map PartialSchedule, const Dependences *D,
507 MatMulInfoTy &MMI) {
508 auto InputDimsId = PartialSchedule.get_tuple_id(isl::dim::in);
509 auto *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
510 if (Stmt->size() <= 1)
511 return false;
512
513 auto Accesses = getAccessesInOrder(*Stmt);
514 for (auto *MemA = Accesses.end() - 1; MemA != Accesses.begin(); MemA--) {
515 auto *MemAccessPtr = *MemA;
516 if (!MemAccessPtr->isLatestArrayKind())
517 continue;
518 if (!MemAccessPtr->isWrite())
519 return false;
520 auto AccMap = MemAccessPtr->getLatestAccessRelation();
521 if (!isMatMulOperandAcc(Stmt->getDomain(), AccMap, MMI.i, MMI.j))
522 return false;
523 MMI.WriteToC = MemAccessPtr;
524 break;
525 }
526
527 if (!containsOnlyMatMulDep(PartialSchedule, D, MMI.k))
528 return false;
529
530 if (!MMI.WriteToC || !containsOnlyMatrMultAcc(PartialSchedule, MMI))
531 return false;
532
533 if (!MMI.A || !MMI.B || !MMI.ReadFromC)
534 return false;
535 return true;
536}
537
538/// Permute two dimensions of the band node.
539///
540/// Permute FirstDim and SecondDim dimensions of the Node.
541///
542/// @param Node The band node to be modified.
543/// @param FirstDim The first dimension to be permuted.
544/// @param SecondDim The second dimension to be permuted.
545static isl::schedule_node permuteBandNodeDimensions(isl::schedule_node Node,
546 unsigned FirstDim,
547 unsigned SecondDim) {
549 (unsigned)isl_schedule_node_band_n_member(Node.get()) >
550 std::max(FirstDim, SecondDim));
551 auto PartialSchedule =
553 auto PartialScheduleFirstDim = PartialSchedule.at(FirstDim);
554 auto PartialScheduleSecondDim = PartialSchedule.at(SecondDim);
555 PartialSchedule =
556 PartialSchedule.set_union_pw_aff(SecondDim, PartialScheduleFirstDim);
557 PartialSchedule =
558 PartialSchedule.set_union_pw_aff(FirstDim, PartialScheduleSecondDim);
560 return Node.insert_partial_schedule(PartialSchedule);
561}
562
563static isl::schedule_node
564createMicroKernel(isl::schedule_node Node,
565 MicroKernelParamsTy MicroKernelParams) {
566 Node = applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr},
567 1);
568 Node = Node.parent().parent();
569 return permuteBandNodeDimensions(Node, 0, 1).child(0).child(0);
570}
571
572/// Create the BLIS macro-kernel.
573///
574/// We create the BLIS macro-kernel by applying a combination of tiling
575/// of dimensions of the band node and interchanging of two innermost
576/// modified dimensions. The values of MacroKernelParams's fields are used
577/// as tile sizes.
578///
579/// @param Node The schedule node to be modified.
580/// @param MacroKernelParams Parameters of the macro kernel
581/// to be used as tile sizes.
582static isl::schedule_node
583createMacroKernel(isl::schedule_node Node,
584 MacroKernelParamsTy MacroKernelParams) {
586 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
587 MacroKernelParams.Kc == 1)
588 return Node;
589 int DimOutNum = isl_schedule_node_band_n_member(Node.get());
590 std::vector<int> TileSizes(DimOutNum, 1);
591 TileSizes[DimOutNum - 3] = MacroKernelParams.Mc;
592 TileSizes[DimOutNum - 2] = MacroKernelParams.Nc;
593 TileSizes[DimOutNum - 1] = MacroKernelParams.Kc;
594 Node = tileNode(Node, "1st level tiling", TileSizes, 1);
595 Node = Node.parent().parent();
596 Node = permuteBandNodeDimensions(Node, DimOutNum - 2, DimOutNum - 1);
597 Node = permuteBandNodeDimensions(Node, DimOutNum - 3, DimOutNum - 1);
598
599 return Node.child(0).child(0);
600}
601
602/// Get the size of the widest type of the matrix multiplication operands
603/// in bytes, including alignment padding.
604///
605/// @param MMI Parameters of the matrix multiplication operands.
606/// @return The size of the widest type of the matrix multiplication operands
607/// in bytes, including alignment padding.
608static uint64_t getMatMulAlignTypeSize(const MatMulInfoTy &MMI) {
609 auto *S = MMI.A->getStatement()->getParent();
610 auto &DL = S->getFunction().getParent()->getDataLayout();
611 auto ElementSizeA = DL.getTypeAllocSize(MMI.A->getElementType());
612 auto ElementSizeB = DL.getTypeAllocSize(MMI.B->getElementType());
613 auto ElementSizeC = DL.getTypeAllocSize(MMI.WriteToC->getElementType());
614 return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
615}
616
617/// Get the size of the widest type of the matrix multiplication operands
618/// in bits.
619///
620/// @param MMI Parameters of the matrix multiplication operands.
621/// @return The size of the widest type of the matrix multiplication operands
622/// in bits.
623static uint64_t getMatMulTypeSize(const MatMulInfoTy &MMI) {
624 auto *S = MMI.A->getStatement()->getParent();
625 auto &DL = S->getFunction().getParent()->getDataLayout();
626 auto ElementSizeA = DL.getTypeSizeInBits(MMI.A->getElementType());
627 auto ElementSizeB = DL.getTypeSizeInBits(MMI.B->getElementType());
628 auto ElementSizeC = DL.getTypeSizeInBits(MMI.WriteToC->getElementType());
629 return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
630}
631
632/// Get parameters of the BLIS micro kernel.
633///
634/// We choose the Mr and Nr parameters of the micro kernel to be large enough
635/// such that no stalls caused by the combination of latencies and dependencies
636/// are introduced during the updates of the resulting matrix of the matrix
637/// multiplication. However, they should also be as small as possible to
638/// release more registers for entries of multiplied matrices.
639///
640/// @param TTI Target Transform Info.
641/// @param MMI Parameters of the matrix multiplication operands.
642/// @return The structure of type MicroKernelParamsTy.
643/// @see MicroKernelParamsTy
644static MicroKernelParamsTy getMicroKernelParams(const TargetTransformInfo *TTI,
645 const MatMulInfoTy &MMI) {
646 assert(TTI && "The target transform info should be provided.");
647
648 // Nvec - Number of double-precision floating-point numbers that can be hold
649 // by a vector register. Use 2 by default.
650 long RegisterBitwidth = VectorRegisterBitwidth;
651
652 if (RegisterBitwidth == -1)
653 RegisterBitwidth =
654 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector);
655 auto ElementSize = getMatMulTypeSize(MMI);
656 assert(ElementSize > 0 && "The element size of the matrix multiplication "
657 "operands should be greater than zero.");
658 auto Nvec = RegisterBitwidth / ElementSize;
659 if (Nvec == 0)
660 Nvec = 2;
661 int Nr = ceil(sqrt((double)(Nvec * LatencyVectorFma * ThroughputVectorFma)) /
662 Nvec) *
663 Nvec;
664 int Mr = ceil((double)(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr));
665 return {Mr, Nr};
666}
667
668/// Determine parameters of the target cache.
669///
670/// @param TTI Target Transform Info.
671static void getTargetCacheParameters(const llvm::TargetTransformInfo *TTI) {
672 auto L1DCache = llvm::TargetTransformInfo::CacheLevel::L1D;
673 auto L2DCache = llvm::TargetTransformInfo::CacheLevel::L2D;
674 if (FirstCacheLevelSize == -1) {
675 if (TTI->getCacheSize(L1DCache))
676 FirstCacheLevelSize = TTI->getCacheSize(L1DCache).value();
677 else
679 }
680 if (SecondCacheLevelSize == -1) {
681 if (TTI->getCacheSize(L2DCache))
682 SecondCacheLevelSize = TTI->getCacheSize(L2DCache).value();
683 else
685 }
687 if (TTI->getCacheAssociativity(L1DCache))
689 TTI->getCacheAssociativity(L1DCache).value();
690 else
692 static_cast<int>(FirstCacheLevelDefaultAssociativity);
693 }
695 if (TTI->getCacheAssociativity(L2DCache))
697 TTI->getCacheAssociativity(L2DCache).value();
698 else
700 static_cast<int>(SecondCacheLevelDefaultAssociativity);
701 }
702}
703
704/// Get parameters of the BLIS macro kernel.
705///
706/// During the computation of matrix multiplication, blocks of partitioned
707/// matrices are mapped to different layers of the memory hierarchy.
708/// To optimize data reuse, blocks should be ideally kept in cache between
709/// iterations. Since parameters of the macro kernel determine sizes of these
710/// blocks, there are upper and lower bounds on these parameters.
711///
712/// @param TTI Target Transform Info.
713/// @param MicroKernelParams Parameters of the micro-kernel
714/// to be taken into account.
715/// @param MMI Parameters of the matrix multiplication operands.
716/// @return The structure of type MacroKernelParamsTy.
717/// @see MacroKernelParamsTy
718/// @see MicroKernelParamsTy
719static MacroKernelParamsTy
720getMacroKernelParams(const llvm::TargetTransformInfo *TTI,
721 const MicroKernelParamsTy &MicroKernelParams,
722 const MatMulInfoTy &MMI) {
723 getTargetCacheParameters(TTI);
724 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
725 // it requires information about the first two levels of a cache to determine
726 // all the parameters of a macro-kernel. It also checks that an associativity
727 // degree of a cache level is greater than two. Otherwise, another algorithm
728 // for determination of the parameters should be used.
729 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
732 return {1, 1, 1};
733 // The quotient should be greater than zero.
735 return {1, 1, 1};
736 int Car = floor(
738 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
739
740 // Car can be computed to be zero since it is floor to int.
741 // On Mac OS, division by 0 does not raise a signal. This causes negative
742 // tile sizes to be computed. Prevent division by Cac==0 by early returning
743 // if this happens.
744 if (Car == 0)
745 return {1, 1, 1};
746
747 auto ElementSize = getMatMulAlignTypeSize(MMI);
748 assert(ElementSize > 0 && "The element size of the matrix multiplication "
749 "operands should be greater than zero.");
750 int Kc = (Car * FirstCacheLevelSize) /
751 (MicroKernelParams.Mr * FirstCacheLevelAssociativity * ElementSize);
752 double Cac =
753 static_cast<double>(Kc * ElementSize * SecondCacheLevelAssociativity) /
755 int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac);
756 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
757
758 assert(Mc > 0 && Nc > 0 && Kc > 0 &&
759 "Matrix block sizes should be greater than zero");
760 return {Mc, Nc, Kc};
761}
762
763/// Create an access relation that is specific to
764/// the matrix multiplication pattern.
765///
766/// Create an access relation of the following form:
767/// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
768/// where I is @p FirstDim, J is @p SecondDim.
769///
770/// It can be used, for example, to create relations that helps to consequently
771/// access elements of operands of a matrix multiplication after creation of
772/// the BLIS micro and macro kernels.
773///
774/// @see ScheduleTreeOptimizer::createMicroKernel
775/// @see ScheduleTreeOptimizer::createMacroKernel
776///
777/// Subsequently, the described access relation is applied to the range of
778/// @p MapOldIndVar, that is used to map original induction variables to
779/// the ones, which are produced by schedule transformations. It helps to
780/// define relations using a new space and, at the same time, keep them
781/// in the original one.
782///
783/// @param MapOldIndVar The relation, which maps original induction variables
784/// to the ones, which are produced by schedule
785/// transformations.
786/// @param FirstDim, SecondDim The input dimensions that are used to define
787/// the specified access relation.
788/// @return The specified access relation.
789static isl::map getMatMulAccRel(isl::map MapOldIndVar, unsigned FirstDim,
790 unsigned SecondDim) {
791 auto AccessRelSpace = isl::space(MapOldIndVar.ctx(), 0, 9, 3);
792 auto AccessRel = isl::map::universe(AccessRelSpace);
793 AccessRel = AccessRel.equate(isl::dim::in, FirstDim, isl::dim::out, 0);
794 AccessRel = AccessRel.equate(isl::dim::in, 5, isl::dim::out, 1);
795 AccessRel = AccessRel.equate(isl::dim::in, SecondDim, isl::dim::out, 2);
796 return MapOldIndVar.apply_range(AccessRel);
797}
798
799static isl::schedule_node createExtensionNode(isl::schedule_node Node,
800 isl::map ExtensionMap) {
801 auto Extension = isl::union_map(ExtensionMap);
802 auto NewNode = isl::schedule_node::from_extension(Extension);
803 return Node.graft_before(NewNode);
804}
805
806/// Allocate the packed array @p SAI, whose dimensions have the sizes
807/// @p DimSizes, on the heap if it is larger than
808/// -polly-pattern-matching-max-stack-array-size and that is not negative, and
809/// on the stack otherwise.
810static void setPackedArrayAllocation(ScopArrayInfo *SAI,
811 ArrayRef<unsigned> DimSizes) {
812 uint64_t Size = SAI->getElemSizeInBytes();
813 for (unsigned DimSize : DimSizes)
814 Size *= DimSize;
815 SAI->setIsOnHeap(MaxStackArraySize >= 0 &&
816 Size > uint64_t(MaxStackArraySize));
817}
818
819static isl::schedule_node optimizePackedB(isl::schedule_node Node,
820 ScopStmt *Stmt, isl::map MapOldIndVar,
821 MicroKernelParamsTy MicroParams,
822 MacroKernelParamsTy MacroParams,
823 MatMulInfoTy &MMI) {
824 Scop *S = Stmt->getParent();
825 isl::set Domain = Stmt->getDomain();
826
827 // Create packed array.
828 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
829 unsigned SecondDimSize = MacroParams.Kc;
830 unsigned ThirdDimSize = MicroParams.Nr;
831 ScopArrayInfo *PackedB =
832 S->createScopArrayInfo(MMI.B->getElementType(), "Packed_B",
833 {FirstDimSize, SecondDimSize, ThirdDimSize});
834 setPackedArrayAllocation(PackedB,
835 {FirstDimSize, SecondDimSize, ThirdDimSize});
836
837 // Compute the access relation for copying from B to PackedB.
838 isl::map AccRelB = MMI.B->getLatestAccessRelation();
839 isl::map AccRelPackedB = getMatMulAccRel(MapOldIndVar, 3, 7);
840 AccRelPackedB =
841 AccRelPackedB.set_tuple_id(isl::dim::out, PackedB->getBasePtrId());
842
843 // Create the copy statement and redirect access.
844 ScopStmt *CopyStmt = S->addScopStmt(AccRelB, AccRelPackedB, Domain);
845 MMI.B->setNewAccessRelation(AccRelPackedB);
846
847 unsigned Dim = unsignedFromIslSize(MapOldIndVar.range_tuple_dim());
848 assert(Dim >= 2);
849 // Insert into the schedule tree.
850 isl::map ExtMap = MapOldIndVar.project_out(isl::dim::out, 2, Dim - 2);
851 ExtMap = ExtMap.reverse();
852 ExtMap = ExtMap.fix_si(isl::dim::out, MMI.i, 0);
853 ExtMap = ExtMap.intersect_range(Domain);
854 ExtMap = ExtMap.set_tuple_id(isl::dim::out, CopyStmt->getDomainId());
855 return createExtensionNode(Node, ExtMap);
856}
857
858static isl::schedule_node optimizePackedA(isl::schedule_node Node, ScopStmt *,
859 isl::map MapOldIndVar,
860 MicroKernelParamsTy MicroParams,
861 MacroKernelParamsTy MacroParams,
862 MatMulInfoTy &MMI) {
863 isl::id InputDimsId = MapOldIndVar.get_tuple_id(isl::dim::in);
864 ScopStmt *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
865 isl::set Domain = Stmt->getDomain();
866 isl::id DomainId = Domain.get_tuple_id();
867
868 // Create the packed array.
869 unsigned FirstDimSize = MacroParams.Mc / MicroParams.Mr;
870 unsigned SecondDimSize = MacroParams.Kc;
871 unsigned ThirdDimSize = MicroParams.Mr;
872 ScopArrayInfo *PackedA = Stmt->getParent()->createScopArrayInfo(
873 MMI.A->getElementType(), "Packed_A",
874 {FirstDimSize, SecondDimSize, ThirdDimSize});
875 setPackedArrayAllocation(PackedA,
876 {FirstDimSize, SecondDimSize, ThirdDimSize});
877
878 // Compute the access relation for copying from A to PackedA.
879 isl::map AccRelA = MMI.A->getLatestAccessRelation();
880 isl::map AccRelPackedA = getMatMulAccRel(MapOldIndVar, 4, 6);
881 AccRelPackedA =
882 AccRelPackedA.set_tuple_id(isl::dim::out, PackedA->getBasePtrId());
883 // { MemrefA[] -> PackedA[] }
884 isl::map PackedATranslator = AccRelPackedA.apply_domain(AccRelA);
885
886 // Compute the domain for the copy statement.
887 // Construct the copy statement domain out of the 3 outermost scatter
888 // dimensions (to match the 3 band nodes surrounding the extension node) and
889 // the array elements to copy (one statement instance per array element).
890 // { Scatter[] }
891 isl::set ScatterDomain = MapOldIndVar.intersect_domain(Domain).range();
892 // { Scatter[] -> OutermostScatter[] }
893 isl::map OuterDomainMap =
894 makeIdentityMap(ScatterDomain, true).project_out(isl::dim::out, 3, 6);
895 // { Scatter[] -> MemrefA[] }
896 isl::map CopyFrom = MapOldIndVar.reverse().apply_range(AccRelA);
897 // { Scatter[] -> CopyStmt[] }
898 isl::map DomainTranslator = OuterDomainMap.range_product(CopyFrom);
899 // { CopyStmt[] }
900 isl::set CopyDomain = DomainTranslator.range();
901
902 // Translate the access relations to the new domain.
903 // { CopyStmt[] -> MemrefA[] }
904 CopyFrom = CopyFrom.apply_domain(DomainTranslator);
905 // { CopyStmt[] -> PackedA[] }
906 isl::map CopyTo = CopyFrom.apply_range(PackedATranslator);
907
908 // Create the copy statement and redirect access.
909 ScopStmt *CopyStmt =
910 Stmt->getParent()->addScopStmt(CopyFrom, CopyTo, CopyDomain);
911 MMI.A->setNewAccessRelation(AccRelPackedA);
912
913 // Insert into the schedule tree.
914 // { Scatter[] -> CopyStmt[] }
915 isl::map ExtScatterCopy = makeIdentityMap(CopyStmt->getDomain(), true);
916 ExtScatterCopy = ExtScatterCopy.project_out(isl::dim::in, 3, 2);
917 return createExtensionNode(Node, ExtScatterCopy);
918}
919
920/// Apply the packing transformation.
921///
922/// The packing transformation can be described as a data-layout
923/// transformation that requires to introduce a new array, copy data
924/// to the array, and change memory access locations to reference the array.
925/// It can be used to ensure that elements of the new array are read in-stride
926/// access, aligned to cache lines boundaries, and preloaded into certain cache
927/// levels.
928///
929/// As an example let us consider the packing of the array A that would help
930/// to read its elements with in-stride access. An access to the array A
931/// is represented by an access relation that has the form
932/// S[i, j, k] -> A[i, k]. The scheduling function of the SCoP statement S has
933/// the form S[i,j, k] -> [floor((j mod Nc) / Nr), floor((i mod Mc) / Mr),
934/// k mod Kc, j mod Nr, i mod Mr].
935///
936/// To ensure that elements of the array A are read in-stride access, we add
937/// a new array Packed_A[Mc/Mr][Kc][Mr] to the SCoP, using
938/// Scop::createScopArrayInfo, change the access relation
939/// S[i, j, k] -> A[i, k] to
940/// S[i, j, k] -> Packed_A[floor((i mod Mc) / Mr), k mod Kc, i mod Mr], using
941/// MemoryAccess::setNewAccessRelation, and copy the data to the array, using
942/// the copy statement created by Scop::addScopStmt.
943///
944/// @param Node The schedule node to be optimized.
945/// @param MapOldIndVar The relation, which maps original induction variables
946/// to the ones, which are produced by schedule
947/// transformations.
948/// @param MicroParams, MacroParams Parameters of the BLIS kernel
949/// to be taken into account.
950/// @param MMI Parameters of the matrix multiplication operands.
951/// @return The optimized schedule node.
952static isl::schedule_node
953optimizeDataLayoutMatrMulPattern(isl::schedule_node Node, isl::map MapOldIndVar,
954 MicroKernelParamsTy MicroParams,
955 MacroKernelParamsTy MacroParams,
956 MatMulInfoTy &MMI) {
957 isl::id InputDimsId = MapOldIndVar.get_tuple_id(isl::dim::in);
958 ScopStmt *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
959
960 Node = Node.parent().parent().parent().parent().parent().parent();
962
963 Node = Node.child(0);
964 Node =
965 optimizePackedB(Node, Stmt, MapOldIndVar, MicroParams, MacroParams, MMI);
966
967 Node = Node.child(0);
968 Node =
969 optimizePackedA(Node, Stmt, MapOldIndVar, MicroParams, MacroParams, MMI);
970
971 return Node.child(0).child(0).child(0).child(0).child(0);
972}
973
974/// Get a relation mapping induction variables produced by schedule
975/// transformations to the original ones.
976///
977/// @param Node The schedule node produced as the result of creation
978/// of the BLIS kernels.
979/// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
980/// to be taken into account.
981/// @return The relation mapping original induction variables to the ones
982/// produced by schedule transformation.
983/// @see ScheduleTreeOptimizer::createMicroKernel
984/// @see ScheduleTreeOptimizer::createMacroKernel
985/// @see getMacroKernelParams
986static isl::map
987getInductionVariablesSubstitution(isl::schedule_node Node,
988 MicroKernelParamsTy MicroKernelParams,
989 MacroKernelParamsTy MacroKernelParams) {
990 auto Child = Node.child(0);
991 auto UnMapOldIndVar = Child.get_prefix_schedule_union_map();
992 auto MapOldIndVar = isl::map::from_union_map(UnMapOldIndVar);
993 unsigned Dim = unsignedFromIslSize(MapOldIndVar.range_tuple_dim());
994 if (Dim > 9u)
995 return MapOldIndVar.project_out(isl::dim::out, 0, Dim - 9);
996 return MapOldIndVar;
997}
998
999/// Isolate a set of partial tile prefixes and unroll the isolated part.
1000///
1001/// The set should ensure that it contains only partial tile prefixes that have
1002/// exactly Mr x Nr iterations of the two innermost loops produced by
1003/// the optimization of the matrix multiplication. Mr and Nr are parameters of
1004/// the micro-kernel.
1005///
1006/// In case of parametric bounds, this helps to auto-vectorize the unrolled
1007/// innermost loops, using the SLP vectorizer.
1008///
1009/// @param Node The schedule node to be modified.
1010/// @param MicroKernelParams Parameters of the micro-kernel
1011/// to be taken into account.
1012/// @return The modified isl_schedule_node.
1013static isl::schedule_node
1014isolateAndUnrollMatMulInnerLoops(isl::schedule_node Node,
1015 MicroKernelParamsTy MicroKernelParams) {
1016 isl::schedule_node Child = Node.child(0);
1017 isl::union_map UnMapOldIndVar = Child.get_prefix_schedule_relation();
1018 isl::set Prefix = isl::map::from_union_map(UnMapOldIndVar).range();
1019 unsigned Dims = unsignedFromIslSize(Prefix.tuple_dim());
1020 assert(Dims >= 1);
1021 Prefix = Prefix.project_out(isl::dim::set, Dims - 1, 1);
1022 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Nr);
1023 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Mr);
1024
1025 isl::union_set IsolateOption =
1026 getIsolateOptions(Prefix.add_dims(isl::dim::set, 3), 3);
1027 isl::ctx Ctx = Node.ctx();
1028 auto Options = IsolateOption.unite(getDimOptions(Ctx, "unroll"));
1029 Options = Options.unite(getUnrollIsolatedSetOptions(Ctx));
1030 Node = Node.as<isl::schedule_node_band>().set_ast_build_options(Options);
1031 Node = Node.parent().parent().parent();
1032 IsolateOption = getIsolateOptions(Prefix, 3);
1033 Options = IsolateOption.unite(getDimOptions(Ctx, "separate"));
1034 Node = Node.as<isl::schedule_node_band>().set_ast_build_options(Options);
1035 Node = Node.child(0).child(0).child(0);
1036 return Node;
1037}
1038
1039/// Insert "Loop Vectorizer Disabled" mark node.
1040///
1041/// @param Node The child of the mark node to be inserted.
1042/// @return The modified isl_schedule_node.
1043static isl::schedule_node markLoopVectorizerDisabled(isl::schedule_node Node) {
1044 auto Id = isl::id::alloc(Node.ctx(), "Loop Vectorizer Disabled", nullptr);
1045 return Node.insert_mark(Id).child(0);
1046}
1047
1048/// Restore the initial ordering of dimensions of the band node
1049///
1050/// In case the band node represents all the dimensions of the iteration
1051/// domain, recreate the band node to restore the initial ordering of the
1052/// dimensions.
1053///
1054/// @param Node The band node to be modified.
1055/// @return The modified schedule node.
1056static isl::schedule_node
1057getBandNodeWithOriginDimOrder(isl::schedule_node Node) {
1060 return Node;
1061 auto Domain = Node.get_universe_domain();
1062 assert(isl_union_set_n_set(Domain.get()) == 1);
1063 if (Node.get_schedule_depth().release() != 0 ||
1064 (unsignedFromIslSize(isl::set(Domain).tuple_dim()) !=
1065 unsignedFromIslSize(Node.as<isl::schedule_node_band>().n_member())))
1066 return Node;
1068 auto PartialSchedulePwAff = Domain.identity_union_pw_multi_aff();
1069 auto PartialScheduleMultiPwAff =
1070 isl::multi_union_pw_aff(PartialSchedulePwAff);
1071 PartialScheduleMultiPwAff =
1072 PartialScheduleMultiPwAff.reset_tuple_id(isl::dim::set);
1073 return Node.insert_partial_schedule(PartialScheduleMultiPwAff);
1074}
1075
1076static isl::schedule_node optimizeMatMulPattern(isl::schedule_node Node,
1077 const TargetTransformInfo *TTI,
1078 MatMulInfoTy &MMI) {
1079 assert(TTI && "The target transform info should be provided.");
1080 int DimOutNum = isl_schedule_node_band_n_member(Node.get());
1081 assert(DimOutNum > 2 && "In case of the matrix multiplication the loop nest "
1082 "and, consequently, the corresponding scheduling "
1083 "functions have at least three dimensions.");
1084 Node = getBandNodeWithOriginDimOrder(Node);
1085 Node = permuteBandNodeDimensions(Node, MMI.i, DimOutNum - 3);
1086 int NewJ = MMI.j == DimOutNum - 3 ? MMI.i : MMI.j;
1087 int NewK = MMI.k == DimOutNum - 3 ? MMI.i : MMI.k;
1088 Node = permuteBandNodeDimensions(Node, NewJ, DimOutNum - 2);
1089 NewK = NewK == DimOutNum - 2 ? NewJ : NewK;
1090 Node = permuteBandNodeDimensions(Node, NewK, DimOutNum - 1);
1091 auto MicroKernelParams = getMicroKernelParams(TTI, MMI);
1092 auto MacroKernelParams = getMacroKernelParams(TTI, MicroKernelParams, MMI);
1093 Node = createMacroKernel(Node, MacroKernelParams);
1094 Node = createMicroKernel(Node, MicroKernelParams);
1095 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
1096 MacroKernelParams.Kc == 1)
1097 return Node;
1098 auto MapOldIndVar = getInductionVariablesSubstitution(Node, MicroKernelParams,
1099 MacroKernelParams);
1100 if (MapOldIndVar.is_null())
1101 return Node;
1102 Node = markLoopVectorizerDisabled(Node.parent()).child(0);
1103 Node = isolateAndUnrollMatMulInnerLoops(Node, MicroKernelParams);
1104 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
1105 MacroKernelParams, MMI);
1106}
1107
1108/// Check if this node contains a partial schedule that could
1109/// probably be optimized with analytical modeling.
1110///
1111/// isMatrMultPattern tries to determine whether the following conditions
1112/// are true:
1113/// 1. the partial schedule contains only one statement.
1114/// 2. there are exactly three input dimensions.
1115/// 3. all memory accesses of the statement will have stride 0 or 1, if we
1116/// interchange loops (switch the variable used in the inner loop to
1117/// the outer loop).
1118/// 4. all memory accesses of the statement except from the last one, are
1119/// read memory access and the last one is write memory access.
1120/// 5. all subscripts of the last memory access of the statement don't
1121/// contain the variable used in the inner loop.
1122/// If this is the case, we could try to use an approach that is similar to
1123/// the one used to get close-to-peak performance of matrix multiplications.
1124///
1125/// @param Node The node to check.
1126/// @param D The SCoP dependencies.
1127/// @param MMI Parameters of the matrix multiplication operands.
1128static bool isMatrMultPattern(isl::schedule_node Node, const Dependences *D,
1129 MatMulInfoTy &MMI) {
1130 auto PartialSchedule = isl::manage(
1132 if (isl_schedule_node_band_n_member(Node.get()) < 3 ||
1133 Node.get_schedule_depth().release() != 0 ||
1134 isl_union_map_n_map(PartialSchedule.get()) != 1)
1135 return false;
1136 auto NewPartialSchedule = isl::map::from_union_map(PartialSchedule);
1137 if (containsMatrMult(NewPartialSchedule, D, MMI))
1138 return true;
1139 return false;
1140}
1141
1142/// Get the dimension size.
1143///
1144/// Return the size of the dimension @p Pos, which is obtained from @p SAI.
1145/// Return -1 in the case of the first dimension of a multi-dimensional array,
1146/// since the ScopArrayInfo class does not carry size information.
1147///
1148/// @param SAI The information about the array.
1149/// @param Pos The position of the dimension.
1150/// @return The size of the dimension.
1151static int getDimSize(const ScopArrayInfo *SAI, unsigned Pos) {
1152 if (Pos == 0)
1153 return -1;
1154 const llvm::SCEV *SCEVDimSize = SAI->getDimensionSize(Pos);
1155 assert(SCEVDimSize);
1156 auto *ConstantDimSize = dyn_cast<const SCEVConstant>(SCEVDimSize);
1157 assert(ConstantDimSize);
1158 auto *IntDimSize = dyn_cast<ConstantInt>(ConstantDimSize->getValue());
1159 assert(IntDimSize);
1160 return IntDimSize->getSExtValue();
1161}
1162
1163/// Check whether the access relation has the specified form.
1164///
1165/// Check that the access relation @p AccMap has the form T[I0, …, In], where
1166/// indexes I0, …, In are specified by @p Dimensions.
1167///
1168/// @param Domain The domain of the access relation.
1169/// @param AccMap The access relation to be checked.
1170/// @param Dimensions The permutation of the subset of the input dimensions.
1171/// @return True if @p AccMap has the expected form and false,
1172/// otherwise.
1173static bool isCorrectAccessMap(isl::set Domain, isl::map AccMap,
1174 ArrayRef<int> Dimensions) {
1175 isl::space Space = AccMap.get_space();
1176 if (unsignedFromIslSize(Space.dim(isl::dim::out)) != Dimensions.size())
1177 return false;
1178
1179 // Create an access relation of the following form:
1180 // [I0, …, Im] -> [Il, …, In], where indexes
1181 // Il, …, In are specified by @p Dimensions.
1182 isl::map PossibleTensor = isl::map::universe(Space);
1183 unsigned DimInSize = unsignedFromIslSize(Space.dim(isl::dim::in));
1184 for (unsigned i = 0; i < Dimensions.size(); i++) {
1185 const int InPos = Dimensions[i];
1186 if ((InPos >= static_cast<int>(DimInSize)) || (InPos < 0))
1187 return false;
1188 PossibleTensor =
1189 PossibleTensor.equate(isl::dim::in, InPos, isl::dim::out, i);
1190 }
1191
1192 AccMap = AccMap.intersect_domain(Domain);
1193 PossibleTensor = PossibleTensor.intersect_domain(Domain);
1194
1195 // If AccMap != PossibleTensor here (the two maps have been gisted at
1196 // this point), it means that the writes are not complete, or in other
1197 // words, it is a Partial write and Partial writes must be rejected.
1198 return AccMap.is_equal(PossibleTensor);
1199}
1200
1201/// Check whether the access represents the tensor contraction operand.
1202///
1203/// Check that the access relation @p AccMap has the form T[i1, …, in].
1204/// Obtained indexes i1, …, in, their sizes and their permutation are stored
1205/// into @p IndexSet, @p DimensionSizes, and @p Dimensions, respectively.
1206///
1207/// @param Domain The domain of the access relation.
1208/// @param AccMap The access relation to be checked.
1209/// @param IndexSet The subset of the input dimensions.
1210/// @param DimensionSizes Sizes of the input dimensions of @p Dimensions.
1211/// @param Dimensions The permutation of the subset of the input dimensions.
1212/// @return True if @p AccMap has the expected form and false,
1213/// otherwise.
1214static bool isTCOperandAcc(isl::set Domain, isl::map AccMap,
1215 SmallDenseSet<int> &IndexSet,
1216 SmallVectorImpl<int> &DimensionSizes,
1217 SmallVectorImpl<int> &Dimensions) {
1218 isl::id Id = AccMap.get_tuple_id(isl::dim::out);
1219 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1220 assert(SAI && "AccMap should represent memory access");
1221
1222 // Fix values of output dimensions with respect to their positions.
1223 // In the case of the tensor contraction, values of output dimensions are
1224 // fixed and form a permutation of a subset of values of input dimensions.
1225 //
1226 // For example, in the case of Stmt[i][j][k] -> A[k][i], which represents
1227 // the operand of the tensor contraction, we get the following map by fixing
1228 // the output dimensions Stmt[1][j][0] -> A[0][1].
1229 //
1230 // We store the permutation of the subset of the input dimensions {2, 0} into
1231 // @p Dimensions.
1232 //
1233 // The obtained permutation and the isCorrectAccessMap function are used to
1234 // check whether the access relation @p AccMap represents the tensor
1235 // contraction operand. For example, in the case of
1236 // Stmt[i][j][k] -> A[i-1][j+1], we get Stmt[1][0][k] -> A[0][1] and,
1237 // consequently, {1, 0}, which is rejected by isCorrectAccessMap,
1238 // since it corresponds to Stmt[i][j][k] -> A[j][i].
1239 isl::map CheckMap = isl::manage(AccMap.copy());
1240 unsigned OutDimNum = unsignedFromIslSize(CheckMap.dim(isl::dim::out));
1241 for (unsigned i = 0; i < OutDimNum; i++)
1242 CheckMap = CheckMap.fix_si(isl::dim::out, i, i);
1243
1244 // Try to obtain the permutation and sizes of corresponding input dimensions.
1245 Dimensions.assign(OutDimNum, -1);
1246 for (unsigned i : rangeIslSize(0, CheckMap.dim(isl::dim::in))) {
1247 isl::val Val = getConstant(CheckMap, isl::dim::in, i);
1248 if (!Val.is_int())
1249 continue;
1250 int OutPos = -1;
1251 llvm::APInt ValAPInt = APIntFromVal(Val);
1252 if (ValAPInt.isSignedIntN(32))
1253 OutPos = ValAPInt.getSExtValue();
1254 if ((OutPos < 0) || (OutPos >= static_cast<int>(OutDimNum)) ||
1255 IndexSet.count(i))
1256 return false;
1257 IndexSet.insert(i);
1258 Dimensions[OutPos] = i;
1259 if (DimensionSizes[i] <= 0)
1260 DimensionSizes[i] = getDimSize(SAI, OutPos);
1261 }
1262
1263 return isCorrectAccessMap(Domain, AccMap, Dimensions);
1264}
1265
1266/// Find the intersection of two sets.
1267///
1268/// Find the intersection of the set @p A and the set @p B.
1269///
1270/// @param A, B Sets to intersect.
1271/// @return The set intersection.
1272static SmallDenseSet<int> intersect(const SmallDenseSet<int> &A,
1273 const SmallDenseSet<int> &B) {
1274 SmallDenseSet<int> Intersection = A;
1275 set_intersect(Intersection, B);
1276 return Intersection;
1277}
1278
1279/// Check whether the set is a superset.
1280///
1281/// Check that the set @p A is a superset of @p B.
1282///
1283/// @param A, B Sets to be checked.
1284/// @return True if the set A is a superset of B.
1285static bool isSuperset(const SmallDenseSet<int> &A,
1286 const SmallDenseSet<int> &B) {
1287 return intersect(A, B).size() == B.size();
1288}
1289
1290/// Find the union of two sets.
1291///
1292/// Find the union of the set @p A and the set @p B.
1293///
1294/// @param A, B Sets to unite.
1295/// @return The set union.
1296static SmallDenseSet<int> unite(const SmallDenseSet<int> &A,
1297 const SmallDenseSet<int> &B) {
1298 SmallDenseSet<int> Union = A;
1299 set_union(Union, B);
1300 return Union;
1301}
1302
1303/// Determine the access that writes to the tensor, which contains
1304/// the result of the tensor contraction.
1305///
1306/// @param Domain The domain of the statement.
1307/// @param Stmt The statement, which writes to memory.
1308/// @param TCI The information about the tensor contraction.
1309/// @param IandJIndexSet The set, which contains free indexes of tensors.
1310/// @return The determined MemoryAccess, or nullptr if there is no necessary
1311/// access within the SCoP.
1312static MemoryAccess *getWriteAccess(isl::set Domain, ScopStmt *Stmt,
1313 TCInfoTy &TCI,
1314 SmallDenseSet<int> &IandJIndexSet) {
1315 TCI.WriteToC = nullptr;
1316 SmallVector<MemoryAccess *, 32> Accesses = getAccessesInOrder(*Stmt);
1317 for (MemoryAccess *MemA : reverse(Accesses)) {
1318 // A TC-like does not contain write scalar memory accesses
1319 if (!MemA->isLatestArrayKind())
1320 return nullptr;
1321 // The last memory access should be a write memory access.
1322 if (!MemA->isWrite())
1323 return nullptr;
1324
1325 isl::map AccMap = MemA->getLatestAccessRelation();
1326 if (!isTCOperandAcc(Domain, AccMap, IandJIndexSet, TCI.DimensionSizes,
1327 TCI.CDimensions))
1328 return nullptr;
1329
1330 return MemA;
1331 }
1332 return nullptr;
1333}
1334
1335/// Determine an access, which reads elements of an operand of the tensor
1336/// contraction
1337///
1338/// @param MemAccessPtr The access, which reads elements of the tensor.
1339/// @param IndexSet The set, which contains indexes of the tensors.
1340/// @param IandJIndexSet The set, which contains free indexes of tensors.
1341/// @param Dimensions The permutation of the subset of the input dimensions.
1342/// @param TCI The information about the tensor contraction.
1343/// @return True if the memory access @p MemAccessPtr corresponds
1344/// to the tensor contraction.
1345static bool setReadAccess(MemoryAccess *MemAccessPtr,
1346 const SmallDenseSet<int> &IndexSet,
1347 const SmallDenseSet<int> &IandJIndexSet,
1348 ArrayRef<int> Dimensions, TCInfoTy &TCI) {
1349 if (!TCI.A) {
1350 // Probably IndexSet is a union of I and P sets.
1351 if (!isSuperset(IndexSet, TCI.P))
1352 return false;
1353
1354 // Obtain the set I.
1355 TCI.I = set_difference(IndexSet, TCI.P);
1356 if (!isSuperset(IandJIndexSet, TCI.I))
1357 return false;
1358
1359 // Obtain the set J.
1360 TCI.J = set_difference(IandJIndexSet, TCI.I);
1361
1362 // Set the first operand of the tensor contraction.
1363 TCI.A = MemAccessPtr;
1364 llvm::replace(TCI.ADimensions, TCI.ADimensions.begin(),
1365 TCI.ADimensions.end(), Dimensions.begin(), Dimensions.end());
1366 return true;
1367 }
1368
1369 if (!TCI.B) {
1370 // IndexSet should be a union of J and P sets.
1371 if (unite(TCI.P, TCI.J) != IndexSet)
1372 return false;
1373
1374 // Set the second operand of the tensor contraction.
1375 TCI.B = MemAccessPtr;
1376 llvm::replace(TCI.BDimensions, TCI.BDimensions.begin(),
1377 TCI.BDimensions.end(), Dimensions.begin(), Dimensions.end());
1378 return true;
1379 }
1380
1381 return false;
1382}
1383
1384/// Check that all memory accesses of the statement, except from the last
1385/// one, are read memory accesses, which read elements of operands of the tensor
1386/// contraction and its result.
1387///
1388/// @param Domain The domain of the statement.
1389/// @param Stmt The statement, which writes to memory.
1390/// @param TCI The information about the tensor contraction.
1391/// @param IandJIndexSet The set, which contains free indexes of tensors.
1392/// @return True if all read memory accesses of the statement @p Stmt correspond
1393/// to the tensor contraction.
1394static bool setReadAccesses(isl::set Domain, ScopStmt *Stmt, TCInfoTy &TCI,
1395 SmallDenseSet<int> &IandJIndexSet) {
1396 TCI.A = nullptr;
1397 TCI.B = nullptr;
1398 TCI.ReadFromC = nullptr;
1399 SmallVector<MemoryAccess *, 32> Accesses = getAccessesInOrder(*Stmt);
1400 for (auto *MemA = Accesses.begin(); *MemA != TCI.WriteToC; MemA++) {
1401 MemoryAccess *MemAccessPtr = *MemA;
1402
1403 // All memory accesses, except from the last one, should be read memory
1404 // accesses.
1405 if (MemAccessPtr->isWrite())
1406 return false;
1407
1408 isl::map AccMap = MemAccessPtr->getLatestAccessRelation();
1409
1410 if (!MemAccessPtr->isLatestArrayKind()) {
1411 // Check whether the scalar read memory access is not partial.
1412 if (!Domain.is_subset(AccMap.domain()))
1413 return false;
1414 continue;
1415 return false;
1416 }
1417
1418 // There is only one memory access, which reads elements of the result of
1419 // the tensor contraction.
1420 if (AccMap.is_equal(TCI.WriteToC->getLatestAccessRelation())) {
1421 if (TCI.ReadFromC)
1422 return false;
1423 TCI.ReadFromC = MemAccessPtr;
1424 continue;
1425 }
1426
1427 SmallVector<int> Dimensions;
1428 SmallDenseSet<int> IndexSet;
1429 if (!isTCOperandAcc(Domain, AccMap, IndexSet, TCI.DimensionSizes,
1430 Dimensions))
1431 return false;
1432
1433 if (!setReadAccess(MemAccessPtr, IndexSet, IandJIndexSet, Dimensions, TCI))
1434 return false;
1435 }
1436
1437 // Check that there are read memory accesses, which read elements of operands
1438 // of the tensor contraction and its result.
1439 return TCI.ReadFromC && TCI.A && TCI.B;
1440}
1441
1442/// Check accesses to operands of the tensor contraction.
1443///
1444/// Check that accesses of the SCoP statement, which corresponds to
1445/// the partial schedule @p PartialSchedule, represent accesses
1446/// to the non-scalar operands of the tensor contraction.
1447///
1448/// @param Domain The domain of the SCoP statement.
1449/// @param PartialSchedule The partial schedule of the SCoP statement.
1450/// @param TCI Parameters of the tensor contraction operands.
1451/// @return True if the corresponding SCoP statement
1452/// represents tensor contraction and false,
1453/// otherwise.
1454static bool containsOnlyTCAcc(isl::set Domain, isl::map PartialSchedule,
1455 TCInfoTy &TCI) {
1456 isl::id InputDimsId = PartialSchedule.get_tuple_id(isl::dim::in);
1457 ScopStmt *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
1458
1459 // In region statements, the order of memory accesses execution is not
1460 // predictable at compile-time.
1461 if ((Stmt->size() <= 1) || Stmt->isRegionStmt())
1462 return false;
1463
1464 unsigned DimNum = unsignedFromIslSize(PartialSchedule.dim(isl::dim::in));
1465 TCI.DimensionSizes.resize(DimNum);
1466 SmallDenseSet<int> IandJIndexSet;
1467
1468 TCI.WriteToC = getWriteAccess(Domain, Stmt, TCI, IandJIndexSet);
1469 if (!TCI.WriteToC)
1470 return false;
1471
1472 if (intersect(IandJIndexSet, TCI.P).size() != 0)
1473 return false;
1474
1475 if (!setReadAccesses(Domain, Stmt, TCI, IandJIndexSet))
1476 return false;
1477
1478 return true;
1479}
1480
1481/// Check that dependency corresponds to the tensor contraction carried over
1482/// loop dimension @p Dim.
1483///
1484/// Check that the dependency has the form
1485/// S(..., ki, max(k(i + 1)), ..., max(kn), ...) ->
1486/// S(..., ki + 1, min(k(i + 1)), ..., min(kn), ...), where S is the SCoP
1487/// statement. For this purpose, we analyze the set @p DepDelta, which
1488/// represents the differences between image elements and domain elements of
1489/// the corresponding map.
1490///
1491/// @param DepDelta The set contains the differences between image elements
1492/// and corresponding domain elements of the map, which
1493/// represents the dependency.
1494/// @param Dim The position of the index ki.
1495/// @param BoundDeltas In the case of indexes of ki, the difference between
1496/// image elements and corresponding domain elements
1497/// corresponds to the difference between lexicographic
1498/// minimum and lexicographic maximum of the corresponding
1499/// dimension of the domain of the statement.
1500/// @param IndexSet Obtained indexes ki, which describe the dependency.
1501/// @return True if dependencies correspond to the tensor contraction
1502/// and false, otherwise.
1503static bool isReductionCarriedOverDim(isl::set DepDelta, unsigned Dim,
1504 isl::pw_multi_aff BoundDeltas,
1505 const SmallDenseSet<int> &IndexSet) {
1506 isl::space Space = DepDelta.get_space();
1507 isl::set Superset = isl::set::universe(Space);
1508 for (unsigned i = 0; i < Dim; i += 1)
1509 Superset = Superset.fix_si(isl::dim::set, i, 0);
1510 Superset = Superset.fix_si(isl::dim::set, Dim, 1);
1511
1512 // Check that the difference between the image element and the domain element
1513 // is equal to one in the case of the index ki. Image elements and
1514 // corresponding domain elements should be equal in the case of positions,
1515 // which are lower than the specified position.
1516 if (!DepDelta.is_subset(Superset))
1517 return false;
1518
1519 // Compute a set, which is used to analyze how values of
1520 // the domain are related to the map that describes the dependency.
1521 isl_pw_multi_aff *DepDeltaPW = isl_pw_multi_aff_from_set(DepDelta.copy());
1522 BoundDeltas = BoundDeltas.add(isl::manage(DepDeltaPW));
1523 isl_set *ComplementRawSet = isl_set_from_pw_multi_aff(BoundDeltas.release());
1524 isl::set Complement = isl::manage(ComplementRawSet);
1525
1526 for (unsigned i : rangeIslSize(Dim + 1, DepDelta.dim(isl::dim::set))) {
1527 if (!IndexSet.count(i)) {
1528 // Check the difference between the image element and the domain element
1529 // in the case of indexes, which do not describe the dependency.
1530 if (DepDelta.plain_get_val_if_fixed(isl::dim::set, i).is_zero())
1531 continue;
1532 return false;
1533 }
1534
1535 // In the case of other indexes, which describe the dependency,
1536 // the difference between the image element and the domain element
1537 // should be equal to the difference between lexicographic minimum and
1538 // lexicographic maximum of the domain of the statement.
1539 if (!Complement.plain_get_val_if_fixed(isl::dim::set, i).is_zero())
1540 return false;
1541 }
1542
1543 return true;
1544}
1545
1546/// Check whether dependencies are over the complete domain.
1547///
1548/// In the case of the tensor contraction RAW, WAW, WAR dependencies
1549/// have the form
1550/// S(..., ki, max(k(i + 1)), ..., max(kn), ...) ->
1551/// S(..., ki + 1, min(k(i + 1)), ..., min(kn), ...), where S is the SCoP
1552/// statement. Consequently, the domain of the dependencies
1553/// can be described as
1554/// Domain / Domain ∩ S(…, max(kn),…) ∩ S(…, max(k(i + 1)),…),
1555/// where Domain is the domain of the statement S.
1556///
1557/// For example, in the case of the following tensor contraction,
1558/// corresponding domains will have the following form.
1559///
1560/// An example of the tensor contraction:
1561/// for (i = 0; i < 1024; i++)
1562/// for (j = 0; j < 1024; j++)
1563/// for (l = 0; l < 64; ++l)
1564/// for (w = 0; w < 64; ++w)
1565/// C[i][j] += A[i][l][w] * B[w][j][l];
1566///
1567/// The domain of the statement:
1568/// { S[i0, i1, i2, i3] : i0 >= 0 and i0 <= 1023 and
1569/// i1 >= 0 and i1 <= 1023 and
1570/// i2 >= 0 and i2 <= 63 and
1571/// i3 >= 0 and i3 <= 63 }
1572///
1573/// The domain of the dependencies:
1574/// { S[i0, i1, i2, i3] : (i0 >= 0 and i0 <= 1023 and
1575/// i1 >= 0 and i1 <= 1023 and
1576/// i2 >= 0 and i2 <= 63 and
1577/// i3 >= 0 and i3 <= 62) or
1578/// (i3 = 63 and i0 >= 0 and i0 <= 1023 and
1579/// i1 >= 0 and i1 <= 1023 and
1580/// i2 >= 0 and i2 <= 62) }
1581///
1582/// @param Domain The domain of the statement.
1583/// @param DepsForStmt RAW and RED dependencies for the statement.
1584/// @param UpperBound The lexicographic maximum of the elements in
1585/// the @p Domain.
1586/// @param IndexSet Obtained indexes ki, which describe the dependencies.
1587/// @return True if dependencies are over the complete domain
1588/// and false, otherwise.
1589static bool areDepsOverCompleteDomain(isl::set Domain, isl::map DepsForStmt,
1590 isl::pw_multi_aff UpperBound,
1591 SmallDenseSet<int> &IndexSet) {
1592 isl_set *UpperBoundRawSet = isl_set_from_pw_multi_aff(UpperBound.copy());
1593 isl::set UpperBoundSet = isl::manage(UpperBoundRawSet);
1594
1595 isl::set DomainRed = isl::manage(Domain.copy());
1596 for (const auto It : IndexSet) {
1597 isl::val FixedVal = UpperBoundSet.plain_get_val_if_fixed(isl::dim::set, It);
1598 if (FixedVal.is_nan())
1599 return false;
1600 DomainRed = isl::manage(
1601 isl_set_fix_val(DomainRed.copy(), isl_dim_set, It, FixedVal.release()));
1602 }
1603 return DepsForStmt.domain().intersect(Domain).is_equal(
1604 Domain.subtract(DomainRed));
1605}
1606
1607/// Check that dependencies correspond to the tensor contraction.
1608///
1609/// Check that there are only true dependencies of the form
1610/// S(..., ki, max(k(i + 1)), ..., max(kn), ...) ->
1611/// S(..., ki + 1, min(k(i + 1)), ..., min(kn), ...), where S is the SCoP
1612/// statement represented by @p Schedule. Such dependencies are produced by
1613/// the tensor contraction. Obtained indexes ki are stored into @p IndexSet.
1614///
1615/// The form of anti and output dependencies is specified implicitly by
1616/// the form the SCoP statement, which is checked by subsequent analysis.
1617///
1618/// @param Schedule The schedule of the SCoP statement.
1619/// @param D The SCoP dependencies.
1620/// @param Domain The domain of the statement.
1621/// @param IndexSet Obtained indexes ki, which describe the dependencies.
1622/// @return True if dependencies correspond to the tensor contraction
1623/// and false, otherwise.
1624static bool containsOnlyTcDeps(isl::map Schedule, const Dependences *D,
1625 SmallDenseSet<int> &IndexSet, isl::set Domain) {
1626 IslMaxOperationsGuard MaxOpGuard(Schedule.ctx().get(), OptComputeOut);
1627
1628 isl::union_map Dep =
1630
1631 isl::space DomainSpace = Schedule.get_space().domain();
1632 isl::space Space = DomainSpace.map_from_domain_and_range(DomainSpace);
1633 isl::map DepsForStmt = Dep.extract_map(Space);
1634 isl::set DepDeltas = DepsForStmt.deltas();
1635 isl::size DeltasDimNum = DepDeltas.dim(isl::dim::set);
1636 isl::pw_multi_aff LowerBound = Domain.lexmin_pw_multi_aff();
1637 isl::pw_multi_aff UpperBound = Domain.lexmax_pw_multi_aff();
1638 isl::pw_multi_aff BoundDeltas = UpperBound.sub(LowerBound);
1639
1640 for (int i : reverse(rangeIslSize(0, DeltasDimNum))) {
1641 // In the case of the tensor contraction, the difference between image
1642 // elements and domain elements lies on a hyperplane where a dimension
1643 // has the fixed value one.
1644 isl::set Intersection = DepDeltas.fix_si(isl::dim::set, i, 1);
1645 if (Intersection.is_empty())
1646 continue;
1647
1648 if (!isReductionCarriedOverDim(Intersection, i, BoundDeltas, IndexSet))
1649 return false;
1650
1651 IndexSet.insert(i);
1652 DepDeltas = DepDeltas.subtract(Intersection);
1653 }
1654
1655 // In the case of the tensor contraction, all dependencies should have
1656 // the previously described form.
1657 if ((unsignedFromIslSize(DeltasDimNum) == 0) || !DepDeltas.is_empty())
1658 return false;
1659
1660 return areDepsOverCompleteDomain(Domain, DepsForStmt, UpperBound, IndexSet);
1661}
1662
1663/// Check if the SCoP statement could probably be optimized with analytical
1664/// modeling.
1665///
1666/// containsTCInfoTy tries to determine whether the following conditions
1667/// are true:
1668///
1669/// 1. The last memory access modeling an array, MA1, represents writing to
1670/// memory and has the form S(..., I, ..., J, ...) -> M(shuffle(I, J)),
1671/// where S is the SCoP statement under consideration and shuffle(I, J)
1672/// is a permutation of indexes of sets I and J.
1673/// 2. There are only true dependencies of the form
1674/// S(..., ki, max(k(i + 1)), ..., max(kn), ...) ->
1675/// S(..., ki + 1, min(k(i + 1)), ..., min(kn), ...), where S is the SCoP
1676/// statement represented by @p Schedule and ki are indexes of the set P.
1677/// 3. SCoP contains an arbitrary number of reads from constants and only three
1678/// access relations, MA2, MA3, and MA4 that represent reading from memory
1679/// and have the form
1680/// S(..., I, ..., P, ...) -> M(shuffle(I, P)),
1681/// S(..., P, ..., J, ...) -> M(shuffle(J, P)),
1682/// S(...) -> M(shuffle(I, J)), respectively.
1683///
1684/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
1685/// to check.
1686/// @param D The SCoP dependencies.
1687/// @param TCI Parameters of the tensor contraction operands.
1688/// @param Domain The domain of the statement.
1689/// @return True if dependencies and memory accesses correspond to the tensor
1690/// contraction and false, otherwise.
1691static bool containsTCInfoTy(isl::map PartialSchedule, const Dependences *D,
1692 TCInfoTy &TCI, isl::set Domain) {
1693 if (!containsOnlyTcDeps(PartialSchedule, D, TCI.P, Domain))
1694 return false;
1695
1696 // TODO: handle cases of scalar multiplication if needed.
1697 if (TCI.P.size() == 0)
1698 return false;
1699
1700 if (!containsOnlyTCAcc(Domain, PartialSchedule, TCI))
1701 return false;
1702
1703 // TODO: handle cases of GEMV if needed.
1704 if ((TCI.I.size() == 0) || (TCI.J.size() == 0))
1705 return false;
1706
1707 return true;
1708}
1709
1710/// Check if this node contains a partial schedule that could
1711/// probably be optimized with analytical modeling.
1712///
1713/// isTCPattern is used to determine whether the SCoP represents a TC-like
1714/// kernel [1], which is a perfectly nested set of loops, with a data usage
1715/// pattern that is similar to that produced by the tensor contraction.
1716///
1717/// A TC-like kernel can be defined as follows:
1718///
1719/// 1. It satisfies the requirements of the polyhedral model.
1720/// 2. Without loss of generality, it contains three nonempty bundles of
1721/// one-dimensional for-loops with induction variables that are grouped into
1722/// bundles I = i0...i(r-1), J = j0..j(s-1), and P = p0...p(t-1), and they
1723/// are incremented by one.
1724/// 3. The innermost loop body can be represented as a statement of the form
1725/// C(shuffle(I, J)) = E(A(shuffle(I, P)), B(shuffle(P, J)),
1726/// C(shuffle(I, J))), where A(shuffle(I, P)), B(shuffle(P, J)),
1727/// C(shuffle(I, J)) are accesses to tensors A, B, C, respectively,
1728/// shuffle(I, J), shuffle(I, P), and shuffle(P, J) are permutations of the
1729/// enclosed indices, and E is an expression that contains reads from
1730/// the tensors A, B, C, and an arbitrary number of reads from constants
1731/// with respect to bundles I, J, and P.
1732///
1733/// TC can be considered as a particular case of a TC-like kernel.
1734///
1735/// The order of loops with indexes from P should be preserved. Otherwise,
1736/// isTCPattern should check if a commutative operation is used.
1737///
1738/// isTCPattern performs the following steps to check whether the SCoP
1739/// corresponds to a definition of a TC-like kernel:
1740///
1741/// 1. Checks that the node is the innermost band node.
1742/// 2. Checks that the partial schedule contains only one statement.
1743/// 3. Check that all ancestors of the node contain all band nodes for
1744/// the statement and only mark nodes interleave such band nodes. This
1745/// corresponds to a straightforward implementation of TC.
1746/// 4. Analyses the dependencies to determine contraction dimensions.
1747/// 5. Check that the last memory access modeling an array, represents writing
1748/// to the result of the TC-like kernel.
1749/// 6. Check that SCoP contains only three access relations that represent
1750/// reading of the operands of the TC-like kernel and an arbitrary number of
1751/// reads from constants.
1752///
1753/// [1] - Gareev R., Grosser T., Kruse M. High-Performance Generalized Tensor
1754/// Operations: A Compiler-Oriented Approach // ACM Transactions
1755/// Architecture and Code Optimization (TACO). 2018.
1756/// Vol. 15, no. 3. P. 34:1–34:27. DOI: 10.1145/3235029.
1757///
1758/// If this is the case, we could logically represent tensors as matrices and
1759/// apply algorithms, which are used to get close-to-peak performance of
1760/// matrix multiplications in manually tuned BLAS libraries (e.g., BLIS).
1761///
1762/// @param Node The node to check.
1763/// @param D The SCoP dependencies.
1764/// @param TCI Parameters of the tensor contraction operands.
1765static bool isTCPattern(isl::schedule_node Node, const Dependences *D,
1766 TCInfoTy &TCI) {
1767 Node = Node.child(0);
1768 isl::union_map PartialSchedule = Node.get_prefix_schedule_union_map();
1769 isl::union_set Domain = Node.domain();
1770 Node = Node.parent();
1771
1772 // The partial schedule should contain only one statement.
1773 // TODO: This constraint should not be intrinsic to the algorithm.
1774 if (isl_union_set_n_set(Domain.get()) != 1)
1775 return false;
1776
1778
1779 // Check that all ancestors of the node contain all band nodes for
1780 // the statement, which represents the TC-like kernel, and only mark nodes
1781 // interleave such band nodes. This corresponds to a straightforward
1782 // implementation of TC with/without DeLICM applied.
1783 //
1784 // For example, this covers the matrix multiplication pattern after a full
1785 // run of -polly-optree and -polly-delicm, where the write access is not
1786 // through the original memory access, but through a PHI node that was
1787 // delicmed. Subsequently, such band nodes will be replaced by a single band
1788 // node.
1789 //
1790 // The corresponding schedule can be the following, where Stmt_for_body8
1791 // contains the matrix multiplication:
1792 //
1793 // domain: "{ Stmt_for_body8[i0, i1, i2] : 0 <= i0 <= 1599 and
1794 // 0 <= i1 <= 1799 and
1795 // 0 <= i2 <= 2199;
1796 // Stmt_for_body3[i0, i1] : 0 <= i0 <= 1599 and
1797 // 0 <= i1 <= 1799;
1798 // Stmt_for_body3_last[i0, i1] : 0 <= i0 <= 1599 and
1799 // 0 <= i1 <= 1799 }"
1800 // child:
1801 // sequence:
1802 // - filter: "{ Stmt_for_body3[i0, i1] }"
1803 // child:
1804 // schedule: "[{ Stmt_for_body3[i0, i1] -> [(i0)] },
1805 // { Stmt_for_body3[i0, i1] -> [(i1)] }]"
1806 // permutable: 1
1807 // coincident: [ 1, 1 ]
1808 // - filter: "{ Stmt_for_body3_last[i0, i1] }"
1809 // child:
1810 // schedule: "[{ Stmt_for_body3_last[i0, i1] -> [(i0)] },
1811 // { Stmt_for_body3_last[i0, i1] -> [(i1)] }]"
1812 // permutable: 1
1813 // coincident: [ 1, 1 ]
1814 // - filter: "{ Stmt_for_body8[i0, i1, i2] }"
1815 // child:
1816 // schedule: "[{ Stmt_for_body8[i0, i1, i2] -> [(i0)] },
1817 // { Stmt_for_body8[i0, i1, i2] -> [(i1)] },
1818 // { Stmt_for_body8[i0, i1, i2] -> [(i2)] }]"
1819 // permutable: 1
1820 // coincident: [ 1, 1, 0 ]
1821 //
1822 while (NodeType != isl_schedule_node_domain) {
1823 if (NodeType == isl_schedule_node_filter) {
1824 if (!Node.parent().isa<isl::schedule_node_sequence>() ||
1825 !Node.parent().parent().isa<isl::schedule_node_domain>())
1826 return false;
1827 break;
1828 }
1829
1830 if ((NodeType != isl_schedule_node_band) &&
1831 (NodeType != isl_schedule_node_mark))
1832 return false;
1833
1834 Node = Node.parent();
1835 NodeType = isl_schedule_node_get_type(Node.get());
1836 }
1837
1838 isl::map PartialScheduleMap = isl::map::from_union_map(PartialSchedule);
1839 if (containsTCInfoTy(PartialScheduleMap, D, TCI, isl::set(Domain)))
1840 return true;
1841
1842 return false;
1843}
1844
1845} // namespace
1846
1849 const llvm::TargetTransformInfo *TTI,
1850 const Dependences *D) {
1851 TCInfoTy TCI;
1852 if (PMBasedTCOpts && isTCPattern(Node, D, TCI))
1853 POLLY_DEBUG(dbgs() << "The tensor contraction pattern was detected\n");
1854 MatMulInfoTy MMI;
1855 if (PMBasedMMMOpts && isMatrMultPattern(Node, D, MMI)) {
1856 POLLY_DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
1857 return optimizeMatMulPattern(Node, TTI, MMI);
1858 }
1859 return {};
1860}
static cl::opt< int > OptComputeOut("polly-dependences-computeout", cl::desc("Bound the dependence analysis by a maximal amount of " "computational steps (0 means no bound)"), cl::Hidden, cl::init(500000), cl::cat(PollyCategory))
unsigned unsignedFromIslSize(const isl::size &Size)
Check that Size is valid (only on debug builds) and cast it to unsigned.
Definition ISLTools.h:40
static cl::opt< int > FirstCacheLevelDefaultSize("polly-target-1st-cache-level-default-size", cl::desc("The default size of the first cache level specified in bytes" " (if not enough were provided by the TargetTransformInfo)."), cl::Hidden, cl::init(32768), cl::cat(PollyCategory))
static cl::opt< bool > PMBasedTCOpts("polly-tc-opt", cl::desc("Perform optimizations of tensor contractions based " "on pattern matching"), cl::init(false), cl::cat(PollyCategory))
static cl::opt< int > SecondCacheLevelDefaultAssociativity("polly-target-2nd-cache-level-default-associativity", cl::desc("The default associativity of the second cache level" " (if not enough were provided by the TargetTransformInfo)."), cl::Hidden, cl::init(8), cl::cat(PollyCategory))
static cl::opt< int > FirstCacheLevelAssociativity("polly-target-1st-cache-level-associativity", cl::desc("The associativity of the first cache level."), cl::Hidden, cl::init(-1), cl::cat(PollyCategory))
static cl::opt< int > SecondCacheLevelDefaultSize("polly-target-2nd-cache-level-default-size", cl::desc("The default size of the second cache level specified in bytes" " (if not enough were provided by the TargetTransformInfo)."), cl::Hidden, cl::init(262144), cl::cat(PollyCategory))
static cl::opt< int > PollyPatternMatchingNcQuotient("polly-pattern-matching-nc-quotient", cl::desc("Quotient that is obtained by dividing Nc, the parameter of the" "macro-kernel, by Nr, the parameter of the micro-kernel"), cl::Hidden, cl::init(256), cl::cat(PollyCategory))
static cl::opt< int > FirstCacheLevelSize("polly-target-1st-cache-level-size", cl::desc("The size of the first cache level specified in bytes."), cl::Hidden, cl::init(-1), cl::cat(PollyCategory))
static cl::opt< int > ThroughputVectorFma("polly-target-throughput-vector-fma", cl::desc("A throughput of the processor floating-point arithmetic units " "expressed in the number of vector fused multiply-add " "instructions per clock cycle."), cl::Hidden, cl::init(1), cl::cat(PollyCategory))
static cl::opt< int > SecondCacheLevelSize("polly-target-2nd-cache-level-size", cl::desc("The size of the second level specified in bytes."), cl::Hidden, cl::init(-1), cl::cat(PollyCategory))
static cl::opt< int > OptComputeOut("polly-tc-dependences-computeout", cl::desc("Bound the dependence analysis by a maximal amount of " "computational steps (0 means no bound)"), cl::Hidden, cl::init(500000), cl::cat(PollyCategory))
static cl::opt< int > FirstCacheLevelDefaultAssociativity("polly-target-1st-cache-level-default-associativity", cl::desc("The default associativity of the first cache level" " (if not enough were provided by the TargetTransformInfo)."), cl::Hidden, cl::init(8), cl::cat(PollyCategory))
static cl::opt< int > SecondCacheLevelAssociativity("polly-target-2nd-cache-level-associativity", cl::desc("The associativity of the second cache level."), cl::Hidden, cl::init(-1), cl::cat(PollyCategory))
static cl::opt< int > VectorRegisterBitwidth("polly-target-vector-register-bitwidth", cl::desc("The size in bits of a vector register (if not set, this " "information is taken from LLVM's target information."), cl::Hidden, cl::init(-1), cl::cat(PollyCategory))
static cl::opt< int > LatencyVectorFma("polly-target-latency-vector-fma", cl::desc("The minimal number of cycles between issuing two " "dependent consecutive vector fused multiply-add " "instructions."), cl::Hidden, cl::init(8), cl::cat(PollyCategory))
static cl::opt< bool > PMBasedMMMOpts("polly-matmul-opt", cl::desc("Perform optimizations of matrix multiplications " "based on pattern matching"), cl::init(true), cl::cat(PollyCategory))
static cl::opt< int > MaxStackArraySize("polly-pattern-matching-max-stack-array-size", cl::desc("The maximal size in bytes of a packed array of the matrix " "multiplication optimization that is allocated on the stack; " "larger ones are allocated on the heap (-1: all on the stack, " "0: all on the heap)"), cl::Hidden, cl::init(1024 *1024), cl::cat(PollyCategory))
llvm::cl::OptionCategory PollyCategory
#define POLLY_DEBUG(X)
Definition PollyDebug.h:23
__isl_give isl_set * isl_set_from_pw_multi_aff(__isl_take isl_pw_multi_aff *pma)
__isl_give isl_pw_multi_aff * isl_pw_multi_aff_from_set(__isl_take isl_set *set)
Definition isl_aff.c:5657
struct isl_pw_multi_aff isl_pw_multi_aff
Definition aff_type.h:33
isl_ctx * get()
bool is_null() const
isl::checked::map reverse() const
isl::checked::set deltas() const
class size range_tuple_dim() const
isl::checked::set range() const
isl::checked::set wrap() const
isl::checked::ctx ctx() const
isl::checked::map apply_range(isl::checked::map map2) const
boolean is_equal(const isl::checked::map &map2) const
isl::checked::map range_product(isl::checked::map map2) const
isl::checked::space get_space() const
isl::checked::map apply_domain(isl::checked::map map2) const
isl::checked::map intersect_domain(isl::checked::set set) const
isl::checked::set domain() const
__isl_keep isl_map * get() const
isl::checked::map intersect_range(isl::checked::set set) const
__isl_give isl_map * copy() const &
bool is_null() const
isl::checked::multi_pw_aff add(const isl::checked::multi_pw_aff &multi2) const
__isl_give isl_pw_multi_aff * copy() const &
isl::checked::multi_pw_aff sub(const isl::checked::multi_pw_aff &multi2) const
__isl_give isl_pw_multi_aff * release()
isl::checked::ctx ctx() const
isl::checked::schedule_node child(int pos) const
__isl_give isl_schedule_node * release()
isl::checked::schedule_node graft_before(isl::checked::schedule_node graft) const
isl::checked::schedule_node insert_partial_schedule(isl::checked::multi_union_pw_aff schedule) const
__isl_give isl_schedule_node * copy() const &
isl::checked::union_map get_prefix_schedule_union_map() const
isl::checked::schedule_node parent() const
isl::checked::schedule_node insert_mark(isl::checked::id mark) const
__isl_keep isl_schedule_node * get() const
__isl_give isl_set * copy() const &
isl::checked::set intersect(isl::checked::set set2) const
boolean is_subset(const isl::checked::set &set2) const
class size tuple_dim() const
boolean is_equal(const isl::checked::set &set2) const
isl::checked::space get_space() const
boolean is_empty() const
isl::checked::set subtract(isl::checked::set set2) const
isl::checked::space domain() const
isl::checked::union_map unite(isl::checked::union_map umap2) const
isl::checked::map extract_map(isl::checked::space space) const
isl::checked::union_set unite(isl::checked::union_set uset2) const
__isl_give isl_val * release()
boolean is_int() const
boolean is_nan() const
static isl::id alloc(isl::ctx ctx, const std::string &name, void *user)
static isl::map from_union_map(isl::union_map umap)
static isl::map universe(isl::space space)
static isl::schedule_node from_extension(isl::union_map extension)
static isl::set universe(isl::space space)
The accumulated dependence information for a SCoP.
isl::union_map getDependences(int Kinds) const
Get the dependences of type Kinds.
isl::map getLatestAccessRelation() const
Return the newest access relation of this access.
Definition ScopInfo.h:786
bool isLatestArrayKind() const
Whether storage memory is either an custom .s2a/.phiops alloca (false) or an existing pointer into an...
Definition ScopInfo.h:947
bool isWrite() const
Is this a write memory access?
Definition ScopInfo.h:766
bool isRead() const
Is this a read memory access?
Definition ScopInfo.h:757
Type * getElementType() const
Return the element type of the accessed array wrt. this access.
Definition ScopInfo.h:861
ScopStmt * getStatement() const
Get the statement that contains this memory access.
Definition ScopInfo.h:1028
void setNewAccessRelation(isl::map NewAccessRelation)
Set the updated access relation read from JSCOP file.
const SCEV * getDimensionSize(unsigned Dim) const
Return the size of dimension dim as SCEV*.
Definition ScopInfo.h:289
static const ScopArrayInfo * getFromId(isl::id Id)
Access the ScopArrayInfo associated with an isl Id.
Definition ScopInfo.cpp:424
void setIsOnHeap(bool value)
Definition ScopInfo.h:266
int getElemSizeInBytes() const
Get element size in bytes.
Definition ScopInfo.cpp:378
isl::id getBasePtrId() const
Return the isl id for the base pointer.
Definition ScopInfo.cpp:382
Scop * getParent()
Definition ScopInfo.h:1525
size_t size() const
Definition ScopInfo.h:1521
isl::id getDomainId() const
Get the id of the iteration domain space.
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1330
isl::set getDomain() const
Get the iteration domain of this ScopStmt.
void addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop, std::vector< Instruction * > Instructions)
Create a new SCoP statement for BB.
ScopArrayInfo * createScopArrayInfo(Type *ElementType, const std::string &BaseName, const std::vector< unsigned > &Sizes)
Create an array and return the corresponding ScopArrayInfo object.
Function & getFunction() const
Return the function this SCoP is in.
Definition ScopInfo.h:2092
A()
B()
#define S(TYPE, NAME)
#define isl_set
enum isl_schedule_node_type isl_schedule_node_get_type(__isl_keep isl_schedule_node *node)
#define assert(exp)
boolean manage(isl_bool val)
Definition cpp-checked.h:98
llvm::SmallVector< MemoryAccess *, 32 > getAccessesInOrder(ScopStmt &Stmt)
Return a vector that contains MemoryAccesses in the order in which they are executed.
Definition Simplify.cpp:765
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
isl::schedule_node applyRegisterTiling(isl::schedule_node Node, llvm::ArrayRef< int > TileSizes, int DefaultTileSize)
Tile a schedule node and unroll point loops.
isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min)
If PwAff maps to a constant, return said constant.
Definition ISLTools.cpp:552
isl::map makeIdentityMap(const isl::set &Set, bool RestrictDomain)
Construct an identity map for the given domain values.
Definition ISLTools.cpp:182
llvm::iota_range< unsigned > rangeIslSize(unsigned Begin, isl::size End)
Check that End is valid and return an iterator from Begin to End.
Definition ISLTools.cpp:597
isl::schedule_node tryOptimizeMatMulPattern(isl::schedule_node Node, const llvm::TargetTransformInfo *TTI, const Dependences *D)
Apply the BLIS matmul optimization pattern if possible.
isl::union_set getIsolateOptions(isl::set IsolateDomain, unsigned OutDimsNum)
Create an isl::union_set, which describes the isolate option based on IsolateDomain.
isl::schedule_node tileNode(isl::schedule_node Node, const char *Identifier, llvm::ArrayRef< int > TileSizes, int DefaultTileSize)
Tile a schedule node.
isl::union_set getDimOptions(isl::ctx Ctx, const char *Option)
Create an isl::union_set, which describes the specified option for the dimension of the current node.
llvm::APInt APIntFromVal(__isl_take isl_val *Val)
Translate isl_val to llvm::APInt.
Definition GICHelper.cpp:51
isl::set getPartialTilePrefixes(isl::set ScheduleRange, int VectorWidth)
Build the desired set of partial tile prefixes.
__isl_export isl_size isl_schedule_node_band_n_member(__isl_keep isl_schedule_node *node)
__isl_export __isl_give isl_multi_union_pw_aff * isl_schedule_node_band_get_partial_schedule(__isl_keep isl_schedule_node *node)
__isl_export __isl_give isl_schedule_node * isl_schedule_node_band_split(__isl_take isl_schedule_node *node, int pos)
__isl_give isl_union_map * isl_schedule_node_band_get_partial_schedule_union_map(__isl_keep isl_schedule_node *node)
__isl_give isl_schedule_node * isl_schedule_node_delete(__isl_take isl_schedule_node *node)
isl_schedule_node_type
@ isl_schedule_node_mark
@ isl_schedule_node_filter
@ isl_schedule_node_domain
@ isl_schedule_node_band
@ isl_schedule_node_leaf
__isl_give isl_set * isl_set_fix_val(__isl_take isl_set *set, enum isl_dim_type type, unsigned pos, __isl_take isl_val *v)
Definition isl_map.c:7321
@ isl_dim_set
Definition space_type.h:18
static TupleKindPtr Domain("Domain")
static TupleKindPtr Ctx
static std::vector< std::string > intersect(const std::vector< std::string > &v1, const std::vector< std::string > &v2)
isl_size isl_union_map_n_map(__isl_keep isl_union_map *umap)
isl_size isl_union_set_n_set(__isl_keep isl_union_set *uset)