1 //===- 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 // 10 // This pass generates an entirely new schedule tree from the data dependences 11 // and iteration domains. The new schedule tree is computed in two steps: 12 // 13 // 1) The isl scheduling optimizer is run 14 // 15 // The isl scheduling optimizer creates a new schedule tree that maximizes 16 // parallelism and tileability and minimizes data-dependence distances. The 17 // algorithm used is a modified version of the ``Pluto'' algorithm: 18 // 19 // U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan. 20 // A Practical Automatic Polyhedral Parallelizer and Locality Optimizer. 21 // In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language 22 // Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008. 23 // 24 // 2) A set of post-scheduling transformations is applied on the schedule tree. 25 // 26 // These optimizations include: 27 // 28 // - Tiling of the innermost tilable bands 29 // - Prevectorization - The choice of a possible outer loop that is strip-mined 30 // to the innermost level to enable inner-loop 31 // vectorization. 32 // - Some optimizations for spatial locality are also planned. 33 // 34 // For a detailed description of the schedule tree itself please see section 6 35 // of: 36 // 37 // Polyhedral AST generation is more than scanning polyhedra 38 // Tobias Grosser, Sven Verdoolaege, Albert Cohen 39 // ACM Transactions on Programming Languages and Systems (TOPLAS), 40 // 37(4), July 2015 41 // http://www.grosser.es/#pub-polyhedral-AST-generation 42 // 43 // This publication also contains a detailed discussion of the different options 44 // for polyhedral loop unrolling, full/partial tile separation and other uses 45 // of the schedule tree. 46 // 47 //===----------------------------------------------------------------------===// 48 49 #include "polly/ScheduleOptimizer.h" 50 #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/ScopPass.h" 56 #include "polly/Simplify.h" 57 #include "polly/Support/GICHelper.h" 58 #include "polly/Support/ISLOStream.h" 59 #include "llvm/ADT/Statistic.h" 60 #include "llvm/Analysis/TargetTransformInfo.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/Pass.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/raw_ostream.h" 66 #include "isl/constraint.h" 67 #include "isl/ctx.h" 68 #include "isl/map.h" 69 #include "isl/options.h" 70 #include "isl/printer.h" 71 #include "isl/schedule.h" 72 #include "isl/schedule_node.h" 73 #include "isl/space.h" 74 #include "isl/union_map.h" 75 #include "isl/union_set.h" 76 #include <algorithm> 77 #include <cassert> 78 #include <cmath> 79 #include <cstdint> 80 #include <cstdlib> 81 #include <string> 82 #include <vector> 83 84 using namespace llvm; 85 using namespace polly; 86 87 #define DEBUG_TYPE "polly-opt-isl" 88 89 static cl::opt<std::string> 90 OptimizeDeps("polly-opt-optimize-only", 91 cl::desc("Only a certain kind of dependences (all/raw)"), 92 cl::Hidden, cl::init("all"), cl::ZeroOrMore, 93 cl::cat(PollyCategory)); 94 95 static cl::opt<std::string> 96 SimplifyDeps("polly-opt-simplify-deps", 97 cl::desc("Dependences should be simplified (yes/no)"), 98 cl::Hidden, cl::init("yes"), cl::ZeroOrMore, 99 cl::cat(PollyCategory)); 100 101 static cl::opt<int> MaxConstantTerm( 102 "polly-opt-max-constant-term", 103 cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden, 104 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory)); 105 106 static cl::opt<int> MaxCoefficient( 107 "polly-opt-max-coefficient", 108 cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden, 109 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory)); 110 111 static cl::opt<std::string> FusionStrategy( 112 "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"), 113 cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory)); 114 115 static cl::opt<std::string> 116 MaximizeBandDepth("polly-opt-maximize-bands", 117 cl::desc("Maximize the band depth (yes/no)"), cl::Hidden, 118 cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory)); 119 120 static cl::opt<std::string> OuterCoincidence( 121 "polly-opt-outer-coincidence", 122 cl::desc("Try to construct schedules where the outer member of each band " 123 "satisfies the coincidence constraints (yes/no)"), 124 cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory)); 125 126 static cl::opt<int> PrevectorWidth( 127 "polly-prevect-width", 128 cl::desc( 129 "The number of loop iterations to strip-mine for pre-vectorization"), 130 cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory)); 131 132 static cl::opt<bool> FirstLevelTiling("polly-tiling", 133 cl::desc("Enable loop tiling"), 134 cl::init(true), cl::ZeroOrMore, 135 cl::cat(PollyCategory)); 136 137 static cl::opt<int> LatencyVectorFma( 138 "polly-target-latency-vector-fma", 139 cl::desc("The minimal number of cycles between issuing two " 140 "dependent consecutive vector fused multiply-add " 141 "instructions."), 142 cl::Hidden, cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory)); 143 144 static cl::opt<int> ThroughputVectorFma( 145 "polly-target-throughput-vector-fma", 146 cl::desc("A throughput of the processor floating-point arithmetic units " 147 "expressed in the number of vector fused multiply-add " 148 "instructions per clock cycle."), 149 cl::Hidden, cl::init(1), cl::ZeroOrMore, cl::cat(PollyCategory)); 150 151 // This option, along with --polly-target-2nd-cache-level-associativity, 152 // --polly-target-1st-cache-level-size, and --polly-target-2st-cache-level-size 153 // represent the parameters of the target cache, which do not have typical 154 // values that can be used by default. However, to apply the pattern matching 155 // optimizations, we use the values of the parameters of Intel Core i7-3820 156 // SandyBridge in case the parameters are not specified. Such an approach helps 157 // also to attain the high-performance on IBM POWER System S822 and IBM Power 158 // 730 Express server. 159 static cl::opt<int> FirstCacheLevelAssociativity( 160 "polly-target-1st-cache-level-associativity", 161 cl::desc("The associativity of the first cache level."), cl::Hidden, 162 cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory)); 163 164 static cl::opt<int> SecondCacheLevelAssociativity( 165 "polly-target-2nd-cache-level-associativity", 166 cl::desc("The associativity of the second cache level."), cl::Hidden, 167 cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory)); 168 169 static cl::opt<int> FirstCacheLevelSize( 170 "polly-target-1st-cache-level-size", 171 cl::desc("The size of the first cache level specified in bytes."), 172 cl::Hidden, cl::init(32768), cl::ZeroOrMore, cl::cat(PollyCategory)); 173 174 static cl::opt<int> SecondCacheLevelSize( 175 "polly-target-2nd-cache-level-size", 176 cl::desc("The size of the second level specified in bytes."), cl::Hidden, 177 cl::init(262144), cl::ZeroOrMore, cl::cat(PollyCategory)); 178 179 static cl::opt<int> VectorRegisterBitwidth( 180 "polly-target-vector-register-bitwidth", 181 cl::desc("The size in bits of a vector register (if not set, this " 182 "information is taken from LLVM's target information."), 183 cl::Hidden, cl::init(-1), cl::ZeroOrMore, cl::cat(PollyCategory)); 184 185 static cl::opt<int> FirstLevelDefaultTileSize( 186 "polly-default-tile-size", 187 cl::desc("The default tile size (if not enough were provided by" 188 " --polly-tile-sizes)"), 189 cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory)); 190 191 static cl::list<int> 192 FirstLevelTileSizes("polly-tile-sizes", 193 cl::desc("A tile size for each loop dimension, filled " 194 "with --polly-default-tile-size"), 195 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, 196 cl::cat(PollyCategory)); 197 198 static cl::opt<bool> 199 SecondLevelTiling("polly-2nd-level-tiling", 200 cl::desc("Enable a 2nd level loop of loop tiling"), 201 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 202 203 static cl::opt<int> SecondLevelDefaultTileSize( 204 "polly-2nd-level-default-tile-size", 205 cl::desc("The default 2nd-level tile size (if not enough were provided by" 206 " --polly-2nd-level-tile-sizes)"), 207 cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory)); 208 209 static cl::list<int> 210 SecondLevelTileSizes("polly-2nd-level-tile-sizes", 211 cl::desc("A tile size for each loop dimension, filled " 212 "with --polly-default-tile-size"), 213 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, 214 cl::cat(PollyCategory)); 215 216 static cl::opt<bool> RegisterTiling("polly-register-tiling", 217 cl::desc("Enable register tiling"), 218 cl::init(false), cl::ZeroOrMore, 219 cl::cat(PollyCategory)); 220 221 static cl::opt<int> RegisterDefaultTileSize( 222 "polly-register-tiling-default-tile-size", 223 cl::desc("The default register tile size (if not enough were provided by" 224 " --polly-register-tile-sizes)"), 225 cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory)); 226 227 static cl::opt<int> PollyPatternMatchingNcQuotient( 228 "polly-pattern-matching-nc-quotient", 229 cl::desc("Quotient that is obtained by dividing Nc, the parameter of the" 230 "macro-kernel, by Nr, the parameter of the micro-kernel"), 231 cl::Hidden, cl::init(256), cl::ZeroOrMore, cl::cat(PollyCategory)); 232 233 static cl::list<int> 234 RegisterTileSizes("polly-register-tile-sizes", 235 cl::desc("A tile size for each loop dimension, filled " 236 "with --polly-register-tile-size"), 237 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, 238 cl::cat(PollyCategory)); 239 240 static cl::opt<bool> 241 PMBasedOpts("polly-pattern-matching-based-opts", 242 cl::desc("Perform optimizations based on pattern matching"), 243 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory)); 244 245 static cl::opt<bool> OptimizedScops( 246 "polly-optimized-scops", 247 cl::desc("Polly - Dump polyhedral description of Scops optimized with " 248 "the isl scheduling optimizer and the set of post-scheduling " 249 "transformations is applied on the schedule tree"), 250 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 251 252 STATISTIC(ScopsProcessed, "Number of scops processed"); 253 STATISTIC(ScopsRescheduled, "Number of scops rescheduled"); 254 STATISTIC(ScopsOptimized, "Number of scops optimized"); 255 256 STATISTIC(NumAffineLoopsOptimized, "Number of affine loops optimized"); 257 STATISTIC(NumBoxedLoopsOptimized, "Number of boxed loops optimized"); 258 259 #define THREE_STATISTICS(VARNAME, DESC) \ 260 static Statistic VARNAME[3] = { \ 261 {DEBUG_TYPE, #VARNAME "0", DESC " (original)", {0}, false}, \ 262 {DEBUG_TYPE, #VARNAME "1", DESC " (after scheduler)", {0}, false}, \ 263 {DEBUG_TYPE, #VARNAME "2", DESC " (after optimizer)", {0}, false}} 264 265 THREE_STATISTICS(NumBands, "Number of bands"); 266 THREE_STATISTICS(NumBandMembers, "Number of band members"); 267 THREE_STATISTICS(NumCoincident, "Number of coincident band members"); 268 THREE_STATISTICS(NumPermutable, "Number of permutable bands"); 269 THREE_STATISTICS(NumFilters, "Number of filter nodes"); 270 THREE_STATISTICS(NumExtension, "Number of extension nodes"); 271 272 STATISTIC(FirstLevelTileOpts, "Number of first level tiling applied"); 273 STATISTIC(SecondLevelTileOpts, "Number of second level tiling applied"); 274 STATISTIC(RegisterTileOpts, "Number of register tiling applied"); 275 STATISTIC(PrevectOpts, "Number of strip-mining for prevectorization applied"); 276 STATISTIC(MatMulOpts, 277 "Number of matrix multiplication patterns detected and optimized"); 278 279 /// Create an isl::union_set, which describes the isolate option based on 280 /// IsolateDomain. 281 /// 282 /// @param IsolateDomain An isl::set whose @p OutDimsNum last dimensions should 283 /// belong to the current band node. 284 /// @param OutDimsNum A number of dimensions that should belong to 285 /// the current band node. 286 static isl::union_set getIsolateOptions(isl::set IsolateDomain, 287 unsigned OutDimsNum) { 288 unsigned Dims = IsolateDomain.dim(isl::dim::set); 289 assert(OutDimsNum <= Dims && 290 "The isl::set IsolateDomain is used to describe the range of schedule " 291 "dimensions values, which should be isolated. Consequently, the " 292 "number of its dimensions should be greater than or equal to the " 293 "number of the schedule dimensions."); 294 isl::map IsolateRelation = isl::map::from_domain(IsolateDomain); 295 IsolateRelation = IsolateRelation.move_dims(isl::dim::out, 0, isl::dim::in, 296 Dims - OutDimsNum, OutDimsNum); 297 isl::set IsolateOption = IsolateRelation.wrap(); 298 isl::id Id = isl::id::alloc(IsolateOption.get_ctx(), "isolate", nullptr); 299 IsolateOption = IsolateOption.set_tuple_id(Id); 300 return isl::union_set(IsolateOption); 301 } 302 303 /// Create an isl::union_set, which describes the atomic option for the 304 /// dimension of the current node. 305 /// 306 /// It may help to reduce the size of generated code. 307 /// 308 /// @param Ctx An isl::ctx, which is used to create the isl::union_set. 309 static isl::union_set getAtomicOptions(isl::ctx Ctx) { 310 isl::space Space(Ctx, 0, 1); 311 isl::set AtomicOption = isl::set::universe(Space); 312 isl::id Id = isl::id::alloc(Ctx, "atomic", nullptr); 313 AtomicOption = AtomicOption.set_tuple_id(Id); 314 return isl::union_set(AtomicOption); 315 } 316 317 /// Create an isl::union_set, which describes the option of the form 318 /// [isolate[] -> unroll[x]]. 319 /// 320 /// @param Ctx An isl::ctx, which is used to create the isl::union_set. 321 static isl::union_set getUnrollIsolatedSetOptions(isl::ctx Ctx) { 322 isl::space Space = isl::space(Ctx, 0, 0, 1); 323 isl::map UnrollIsolatedSetOption = isl::map::universe(Space); 324 isl::id DimInId = isl::id::alloc(Ctx, "isolate", nullptr); 325 isl::id DimOutId = isl::id::alloc(Ctx, "unroll", nullptr); 326 UnrollIsolatedSetOption = 327 UnrollIsolatedSetOption.set_tuple_id(isl::dim::in, DimInId); 328 UnrollIsolatedSetOption = 329 UnrollIsolatedSetOption.set_tuple_id(isl::dim::out, DimOutId); 330 return UnrollIsolatedSetOption.wrap(); 331 } 332 333 /// Make the last dimension of Set to take values from 0 to VectorWidth - 1. 334 /// 335 /// @param Set A set, which should be modified. 336 /// @param VectorWidth A parameter, which determines the constraint. 337 static isl::set addExtentConstraints(isl::set Set, int VectorWidth) { 338 unsigned Dims = Set.dim(isl::dim::set); 339 isl::space Space = Set.get_space(); 340 isl::local_space LocalSpace = isl::local_space(Space); 341 isl::constraint ExtConstr = isl::constraint::alloc_inequality(LocalSpace); 342 ExtConstr = ExtConstr.set_constant_si(0); 343 ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, 1); 344 Set = Set.add_constraint(ExtConstr); 345 ExtConstr = isl::constraint::alloc_inequality(LocalSpace); 346 ExtConstr = ExtConstr.set_constant_si(VectorWidth - 1); 347 ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, -1); 348 return Set.add_constraint(ExtConstr); 349 } 350 351 isl::set getPartialTilePrefixes(isl::set ScheduleRange, int VectorWidth) { 352 unsigned Dims = ScheduleRange.dim(isl::dim::set); 353 isl::set LoopPrefixes = 354 ScheduleRange.drop_constraints_involving_dims(isl::dim::set, Dims - 1, 1); 355 auto ExtentPrefixes = addExtentConstraints(LoopPrefixes, VectorWidth); 356 isl::set BadPrefixes = ExtentPrefixes.subtract(ScheduleRange); 357 BadPrefixes = BadPrefixes.project_out(isl::dim::set, Dims - 1, 1); 358 LoopPrefixes = LoopPrefixes.project_out(isl::dim::set, Dims - 1, 1); 359 return LoopPrefixes.subtract(BadPrefixes); 360 } 361 362 isl::schedule_node 363 ScheduleTreeOptimizer::isolateFullPartialTiles(isl::schedule_node Node, 364 int VectorWidth) { 365 assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band); 366 Node = Node.child(0).child(0); 367 isl::union_map SchedRelUMap = Node.get_prefix_schedule_relation(); 368 isl::map ScheduleRelation = isl::map::from_union_map(SchedRelUMap); 369 isl::set ScheduleRange = ScheduleRelation.range(); 370 isl::set IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth); 371 isl::union_set AtomicOption = getAtomicOptions(IsolateDomain.get_ctx()); 372 isl::union_set IsolateOption = getIsolateOptions(IsolateDomain, 1); 373 Node = Node.parent().parent(); 374 isl::union_set Options = IsolateOption.unite(AtomicOption); 375 Node = Node.band_set_ast_build_options(Options); 376 return Node; 377 } 378 379 isl::schedule_node ScheduleTreeOptimizer::prevectSchedBand( 380 isl::schedule_node Node, unsigned DimToVectorize, int VectorWidth) { 381 assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band); 382 383 auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 384 auto ScheduleDimensions = Space.dim(isl::dim::set); 385 assert(DimToVectorize < ScheduleDimensions); 386 387 if (DimToVectorize > 0) { 388 Node = isl::manage( 389 isl_schedule_node_band_split(Node.release(), DimToVectorize)); 390 Node = Node.child(0); 391 } 392 if (DimToVectorize < ScheduleDimensions - 1) 393 Node = isl::manage(isl_schedule_node_band_split(Node.release(), 1)); 394 Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 395 auto Sizes = isl::multi_val::zero(Space); 396 Sizes = Sizes.set_val(0, isl::val(Node.get_ctx(), VectorWidth)); 397 Node = 398 isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release())); 399 Node = isolateFullPartialTiles(Node, VectorWidth); 400 Node = Node.child(0); 401 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise, 402 // we will have troubles to match it in the backend. 403 Node = Node.band_set_ast_build_options( 404 isl::union_set(Node.get_ctx(), "{ unroll[x]: 1 = 0 }")); 405 Node = isl::manage(isl_schedule_node_band_sink(Node.release())); 406 Node = Node.child(0); 407 if (isl_schedule_node_get_type(Node.get()) == isl_schedule_node_leaf) 408 Node = Node.parent(); 409 auto LoopMarker = isl::id::alloc(Node.get_ctx(), "SIMD", nullptr); 410 PrevectOpts++; 411 return Node.insert_mark(LoopMarker); 412 } 413 414 isl::schedule_node ScheduleTreeOptimizer::tileNode(isl::schedule_node Node, 415 const char *Identifier, 416 ArrayRef<int> TileSizes, 417 int DefaultTileSize) { 418 auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 419 auto Dims = Space.dim(isl::dim::set); 420 auto Sizes = isl::multi_val::zero(Space); 421 std::string IdentifierString(Identifier); 422 for (unsigned i = 0; i < Dims; i++) { 423 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize; 424 Sizes = Sizes.set_val(i, isl::val(Node.get_ctx(), tileSize)); 425 } 426 auto TileLoopMarkerStr = IdentifierString + " - Tiles"; 427 auto TileLoopMarker = 428 isl::id::alloc(Node.get_ctx(), TileLoopMarkerStr, nullptr); 429 Node = Node.insert_mark(TileLoopMarker); 430 Node = Node.child(0); 431 Node = 432 isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release())); 433 Node = Node.child(0); 434 auto PointLoopMarkerStr = IdentifierString + " - Points"; 435 auto PointLoopMarker = 436 isl::id::alloc(Node.get_ctx(), PointLoopMarkerStr, nullptr); 437 Node = Node.insert_mark(PointLoopMarker); 438 return Node.child(0); 439 } 440 441 isl::schedule_node ScheduleTreeOptimizer::applyRegisterTiling( 442 isl::schedule_node Node, ArrayRef<int> TileSizes, int DefaultTileSize) { 443 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize); 444 auto Ctx = Node.get_ctx(); 445 return Node.band_set_ast_build_options(isl::union_set(Ctx, "{unroll[x]}")); 446 } 447 448 static bool isSimpleInnermostBand(const isl::schedule_node &Node) { 449 assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band); 450 assert(isl_schedule_node_n_children(Node.keep()) == 1); 451 452 auto ChildType = isl_schedule_node_get_type(Node.child(0).keep()); 453 454 if (ChildType == isl_schedule_node_leaf) 455 return true; 456 457 if (ChildType != isl_schedule_node_sequence) 458 return false; 459 460 auto Sequence = Node.child(0); 461 462 for (int c = 0, nc = isl_schedule_node_n_children(Sequence.keep()); c < nc; 463 ++c) { 464 auto Child = Sequence.child(c); 465 if (isl_schedule_node_get_type(Child.keep()) != isl_schedule_node_filter) 466 return false; 467 if (isl_schedule_node_get_type(Child.child(0).keep()) != 468 isl_schedule_node_leaf) 469 return false; 470 } 471 return true; 472 } 473 474 bool ScheduleTreeOptimizer::isTileableBandNode(isl::schedule_node Node) { 475 if (isl_schedule_node_get_type(Node.get()) != isl_schedule_node_band) 476 return false; 477 478 if (isl_schedule_node_n_children(Node.get()) != 1) 479 return false; 480 481 if (!isl_schedule_node_band_get_permutable(Node.get())) 482 return false; 483 484 auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 485 auto Dims = Space.dim(isl::dim::set); 486 487 if (Dims <= 1) 488 return false; 489 490 return isSimpleInnermostBand(Node); 491 } 492 493 __isl_give isl::schedule_node 494 ScheduleTreeOptimizer::standardBandOpts(isl::schedule_node Node, void *User) { 495 if (FirstLevelTiling) { 496 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes, 497 FirstLevelDefaultTileSize); 498 FirstLevelTileOpts++; 499 } 500 501 if (SecondLevelTiling) { 502 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes, 503 SecondLevelDefaultTileSize); 504 SecondLevelTileOpts++; 505 } 506 507 if (RegisterTiling) { 508 Node = 509 applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize); 510 RegisterTileOpts++; 511 } 512 513 if (PollyVectorizerChoice == VECTORIZER_NONE) 514 return Node; 515 516 auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 517 auto Dims = Space.dim(isl::dim::set); 518 519 for (int i = Dims - 1; i >= 0; i--) 520 if (Node.band_member_get_coincident(i)) { 521 Node = prevectSchedBand(Node, i, PrevectorWidth); 522 break; 523 } 524 525 return Node; 526 } 527 528 /// Permute the two dimensions of the isl map. 529 /// 530 /// Permute @p DstPos and @p SrcPos dimensions of the isl map @p Map that 531 /// have type @p DimType. 532 /// 533 /// @param Map The isl map to be modified. 534 /// @param DimType The type of the dimensions. 535 /// @param DstPos The first dimension. 536 /// @param SrcPos The second dimension. 537 /// @return The modified map. 538 isl::map permuteDimensions(isl::map Map, isl::dim DimType, unsigned DstPos, 539 unsigned SrcPos) { 540 assert(DstPos < Map.dim(DimType) && SrcPos < Map.dim(DimType)); 541 if (DstPos == SrcPos) 542 return Map; 543 isl::id DimId; 544 if (Map.has_tuple_id(DimType)) 545 DimId = Map.get_tuple_id(DimType); 546 auto FreeDim = DimType == isl::dim::in ? isl::dim::out : isl::dim::in; 547 isl::id FreeDimId; 548 if (Map.has_tuple_id(FreeDim)) 549 FreeDimId = Map.get_tuple_id(FreeDim); 550 auto MaxDim = std::max(DstPos, SrcPos); 551 auto MinDim = std::min(DstPos, SrcPos); 552 Map = Map.move_dims(FreeDim, 0, DimType, MaxDim, 1); 553 Map = Map.move_dims(FreeDim, 0, DimType, MinDim, 1); 554 Map = Map.move_dims(DimType, MinDim, FreeDim, 1, 1); 555 Map = Map.move_dims(DimType, MaxDim, FreeDim, 0, 1); 556 if (DimId) 557 Map = Map.set_tuple_id(DimType, DimId); 558 if (FreeDimId) 559 Map = Map.set_tuple_id(FreeDim, FreeDimId); 560 return Map; 561 } 562 563 /// Check the form of the access relation. 564 /// 565 /// Check that the access relation @p AccMap has the form M[i][j], where i 566 /// is a @p FirstPos and j is a @p SecondPos. 567 /// 568 /// @param AccMap The access relation to be checked. 569 /// @param FirstPos The index of the input dimension that is mapped to 570 /// the first output dimension. 571 /// @param SecondPos The index of the input dimension that is mapped to the 572 /// second output dimension. 573 /// @return True in case @p AccMap has the expected form and false, 574 /// otherwise. 575 static bool isMatMulOperandAcc(isl::set Domain, isl::map AccMap, int &FirstPos, 576 int &SecondPos) { 577 isl::space Space = AccMap.get_space(); 578 isl::map Universe = isl::map::universe(Space); 579 580 if (Space.dim(isl::dim::out) != 2) 581 return false; 582 583 // MatMul has the form: 584 // for (i = 0; i < N; i++) 585 // for (j = 0; j < M; j++) 586 // for (k = 0; k < P; k++) 587 // C[i, j] += A[i, k] * B[k, j] 588 // 589 // Permutation of three outer loops: 3! = 6 possibilities. 590 int FirstDims[] = {0, 0, 1, 1, 2, 2}; 591 int SecondDims[] = {1, 2, 2, 0, 0, 1}; 592 for (int i = 0; i < 6; i += 1) { 593 auto PossibleMatMul = 594 Universe.equate(isl::dim::in, FirstDims[i], isl::dim::out, 0) 595 .equate(isl::dim::in, SecondDims[i], isl::dim::out, 1); 596 597 AccMap = AccMap.intersect_domain(Domain); 598 PossibleMatMul = PossibleMatMul.intersect_domain(Domain); 599 600 // If AccMap spans entire domain (Non-partial write), 601 // compute FirstPos and SecondPos. 602 // If AccMap != PossibleMatMul here (the two maps have been gisted at 603 // this point), it means that the writes are not complete, or in other 604 // words, it is a Partial write and Partial writes must be rejected. 605 if (AccMap.is_equal(PossibleMatMul)) { 606 if (FirstPos != -1 && FirstPos != FirstDims[i]) 607 continue; 608 FirstPos = FirstDims[i]; 609 if (SecondPos != -1 && SecondPos != SecondDims[i]) 610 continue; 611 SecondPos = SecondDims[i]; 612 return true; 613 } 614 } 615 616 return false; 617 } 618 619 /// Does the memory access represent a non-scalar operand of the matrix 620 /// multiplication. 621 /// 622 /// Check that the memory access @p MemAccess is the read access to a non-scalar 623 /// operand of the matrix multiplication or its result. 624 /// 625 /// @param MemAccess The memory access to be checked. 626 /// @param MMI Parameters of the matrix multiplication operands. 627 /// @return True in case the memory access represents the read access 628 /// to a non-scalar operand of the matrix multiplication and 629 /// false, otherwise. 630 static bool isMatMulNonScalarReadAccess(MemoryAccess *MemAccess, 631 MatMulInfoTy &MMI) { 632 if (!MemAccess->isLatestArrayKind() || !MemAccess->isRead()) 633 return false; 634 auto AccMap = MemAccess->getLatestAccessRelation(); 635 isl::set StmtDomain = MemAccess->getStatement()->getDomain(); 636 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.i, MMI.j) && !MMI.ReadFromC) { 637 MMI.ReadFromC = MemAccess; 638 return true; 639 } 640 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.i, MMI.k) && !MMI.A) { 641 MMI.A = MemAccess; 642 return true; 643 } 644 if (isMatMulOperandAcc(StmtDomain, AccMap, MMI.k, MMI.j) && !MMI.B) { 645 MMI.B = MemAccess; 646 return true; 647 } 648 return false; 649 } 650 651 /// Check accesses to operands of the matrix multiplication. 652 /// 653 /// Check that accesses of the SCoP statement, which corresponds to 654 /// the partial schedule @p PartialSchedule, are scalar in terms of loops 655 /// containing the matrix multiplication, in case they do not represent 656 /// accesses to the non-scalar operands of the matrix multiplication or 657 /// its result. 658 /// 659 /// @param PartialSchedule The partial schedule of the SCoP statement. 660 /// @param MMI Parameters of the matrix multiplication operands. 661 /// @return True in case the corresponding SCoP statement 662 /// represents matrix multiplication and false, 663 /// otherwise. 664 static bool containsOnlyMatrMultAcc(isl::map PartialSchedule, 665 MatMulInfoTy &MMI) { 666 auto InputDimId = PartialSchedule.get_tuple_id(isl::dim::in); 667 auto *Stmt = static_cast<ScopStmt *>(InputDimId.get_user()); 668 unsigned OutDimNum = PartialSchedule.dim(isl::dim::out); 669 assert(OutDimNum > 2 && "In case of the matrix multiplication the loop nest " 670 "and, consequently, the corresponding scheduling " 671 "functions have at least three dimensions."); 672 auto MapI = 673 permuteDimensions(PartialSchedule, isl::dim::out, MMI.i, OutDimNum - 1); 674 auto MapJ = 675 permuteDimensions(PartialSchedule, isl::dim::out, MMI.j, OutDimNum - 1); 676 auto MapK = 677 permuteDimensions(PartialSchedule, isl::dim::out, MMI.k, OutDimNum - 1); 678 679 auto Accesses = getAccessesInOrder(*Stmt); 680 for (auto *MemA = Accesses.begin(); MemA != Accesses.end() - 1; MemA++) { 681 auto *MemAccessPtr = *MemA; 682 if (MemAccessPtr->isLatestArrayKind() && MemAccessPtr != MMI.WriteToC && 683 !isMatMulNonScalarReadAccess(MemAccessPtr, MMI) && 684 !(MemAccessPtr->isStrideZero(MapI)) && 685 MemAccessPtr->isStrideZero(MapJ) && MemAccessPtr->isStrideZero(MapK)) 686 return false; 687 } 688 return true; 689 } 690 691 /// Check for dependencies corresponding to the matrix multiplication. 692 /// 693 /// Check that there is only true dependence of the form 694 /// S(..., k, ...) -> S(..., k + 1, …), where S is the SCoP statement 695 /// represented by @p Schedule and k is @p Pos. Such a dependence corresponds 696 /// to the dependency produced by the matrix multiplication. 697 /// 698 /// @param Schedule The schedule of the SCoP statement. 699 /// @param D The SCoP dependencies. 700 /// @param Pos The parameter to describe an acceptable true dependence. 701 /// In case it has a negative value, try to determine its 702 /// acceptable value. 703 /// @return True in case dependencies correspond to the matrix multiplication 704 /// and false, otherwise. 705 static bool containsOnlyMatMulDep(isl::map Schedule, const Dependences *D, 706 int &Pos) { 707 auto Dep = isl::manage(D->getDependences(Dependences::TYPE_RAW)); 708 auto Red = isl::manage(D->getDependences(Dependences::TYPE_RED)); 709 if (Red) 710 Dep = Dep.unite(Red); 711 auto DomainSpace = Schedule.get_space().domain(); 712 auto Space = DomainSpace.map_from_domain_and_range(DomainSpace); 713 auto Deltas = Dep.extract_map(Space).deltas(); 714 int DeltasDimNum = Deltas.dim(isl::dim::set); 715 for (int i = 0; i < DeltasDimNum; i++) { 716 auto Val = Deltas.plain_get_val_if_fixed(isl::dim::set, i); 717 Pos = Pos < 0 && Val.is_one() ? i : Pos; 718 if (Val.is_nan() || !(Val.is_zero() || (i == Pos && Val.is_one()))) 719 return false; 720 } 721 if (DeltasDimNum == 0 || Pos < 0) 722 return false; 723 return true; 724 } 725 726 /// Check if the SCoP statement could probably be optimized with analytical 727 /// modeling. 728 /// 729 /// containsMatrMult tries to determine whether the following conditions 730 /// are true: 731 /// 1. The last memory access modeling an array, MA1, represents writing to 732 /// memory and has the form S(..., i1, ..., i2, ...) -> M(i1, i2) or 733 /// S(..., i2, ..., i1, ...) -> M(i1, i2), where S is the SCoP statement 734 /// under consideration. 735 /// 2. There is only one loop-carried true dependency, and it has the 736 /// form S(..., i3, ...) -> S(..., i3 + 1, ...), and there are no 737 /// loop-carried or anti dependencies. 738 /// 3. SCoP contains three access relations, MA2, MA3, and MA4 that represent 739 /// reading from memory and have the form S(..., i3, ...) -> M(i1, i3), 740 /// S(..., i3, ...) -> M(i3, i2), S(...) -> M(i1, i2), respectively, 741 /// and all memory accesses of the SCoP that are different from MA1, MA2, 742 /// MA3, and MA4 have stride 0, if the innermost loop is exchanged with any 743 /// of loops i1, i2 and i3. 744 /// 745 /// @param PartialSchedule The PartialSchedule that contains a SCoP statement 746 /// to check. 747 /// @D The SCoP dependencies. 748 /// @MMI Parameters of the matrix multiplication operands. 749 static bool containsMatrMult(isl::map PartialSchedule, const Dependences *D, 750 MatMulInfoTy &MMI) { 751 auto InputDimsId = PartialSchedule.get_tuple_id(isl::dim::in); 752 auto *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user()); 753 if (Stmt->size() <= 1) 754 return false; 755 756 auto Accesses = getAccessesInOrder(*Stmt); 757 for (auto *MemA = Accesses.end() - 1; MemA != Accesses.begin(); MemA--) { 758 auto *MemAccessPtr = *MemA; 759 if (!MemAccessPtr->isLatestArrayKind()) 760 continue; 761 if (!MemAccessPtr->isWrite()) 762 return false; 763 auto AccMap = MemAccessPtr->getLatestAccessRelation(); 764 if (!isMatMulOperandAcc(Stmt->getDomain(), AccMap, MMI.i, MMI.j)) 765 return false; 766 MMI.WriteToC = MemAccessPtr; 767 break; 768 } 769 770 if (!containsOnlyMatMulDep(PartialSchedule, D, MMI.k)) 771 return false; 772 773 if (!MMI.WriteToC || !containsOnlyMatrMultAcc(PartialSchedule, MMI)) 774 return false; 775 776 if (!MMI.A || !MMI.B || !MMI.ReadFromC) 777 return false; 778 return true; 779 } 780 781 /// Permute two dimensions of the band node. 782 /// 783 /// Permute FirstDim and SecondDim dimensions of the Node. 784 /// 785 /// @param Node The band node to be modified. 786 /// @param FirstDim The first dimension to be permuted. 787 /// @param SecondDim The second dimension to be permuted. 788 static isl::schedule_node permuteBandNodeDimensions(isl::schedule_node Node, 789 unsigned FirstDim, 790 unsigned SecondDim) { 791 assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band && 792 isl_schedule_node_band_n_member(Node.get()) > 793 std::max(FirstDim, SecondDim)); 794 auto PartialSchedule = 795 isl::manage(isl_schedule_node_band_get_partial_schedule(Node.get())); 796 auto PartialScheduleFirstDim = PartialSchedule.get_union_pw_aff(FirstDim); 797 auto PartialScheduleSecondDim = PartialSchedule.get_union_pw_aff(SecondDim); 798 PartialSchedule = 799 PartialSchedule.set_union_pw_aff(SecondDim, PartialScheduleFirstDim); 800 PartialSchedule = 801 PartialSchedule.set_union_pw_aff(FirstDim, PartialScheduleSecondDim); 802 Node = isl::manage(isl_schedule_node_delete(Node.release())); 803 return Node.insert_partial_schedule(PartialSchedule); 804 } 805 806 isl::schedule_node ScheduleTreeOptimizer::createMicroKernel( 807 isl::schedule_node Node, MicroKernelParamsTy MicroKernelParams) { 808 Node = applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr}, 809 1); 810 Node = Node.parent().parent(); 811 return permuteBandNodeDimensions(Node, 0, 1).child(0).child(0); 812 } 813 814 isl::schedule_node ScheduleTreeOptimizer::createMacroKernel( 815 isl::schedule_node Node, MacroKernelParamsTy MacroKernelParams) { 816 assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band); 817 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 && 818 MacroKernelParams.Kc == 1) 819 return Node; 820 int DimOutNum = isl_schedule_node_band_n_member(Node.get()); 821 std::vector<int> TileSizes(DimOutNum, 1); 822 TileSizes[DimOutNum - 3] = MacroKernelParams.Mc; 823 TileSizes[DimOutNum - 2] = MacroKernelParams.Nc; 824 TileSizes[DimOutNum - 1] = MacroKernelParams.Kc; 825 Node = tileNode(Node, "1st level tiling", TileSizes, 1); 826 Node = Node.parent().parent(); 827 Node = permuteBandNodeDimensions(Node, DimOutNum - 2, DimOutNum - 1); 828 Node = permuteBandNodeDimensions(Node, DimOutNum - 3, DimOutNum - 1); 829 return Node.child(0).child(0); 830 } 831 832 /// Get the size of the widest type of the matrix multiplication operands 833 /// in bytes, including alignment padding. 834 /// 835 /// @param MMI Parameters of the matrix multiplication operands. 836 /// @return The size of the widest type of the matrix multiplication operands 837 /// in bytes, including alignment padding. 838 static uint64_t getMatMulAlignTypeSize(MatMulInfoTy MMI) { 839 auto *S = MMI.A->getStatement()->getParent(); 840 auto &DL = S->getFunction().getParent()->getDataLayout(); 841 auto ElementSizeA = DL.getTypeAllocSize(MMI.A->getElementType()); 842 auto ElementSizeB = DL.getTypeAllocSize(MMI.B->getElementType()); 843 auto ElementSizeC = DL.getTypeAllocSize(MMI.WriteToC->getElementType()); 844 return std::max({ElementSizeA, ElementSizeB, ElementSizeC}); 845 } 846 847 /// Get the size of the widest type of the matrix multiplication operands 848 /// in bits. 849 /// 850 /// @param MMI Parameters of the matrix multiplication operands. 851 /// @return The size of the widest type of the matrix multiplication operands 852 /// in bits. 853 static uint64_t getMatMulTypeSize(MatMulInfoTy MMI) { 854 auto *S = MMI.A->getStatement()->getParent(); 855 auto &DL = S->getFunction().getParent()->getDataLayout(); 856 auto ElementSizeA = DL.getTypeSizeInBits(MMI.A->getElementType()); 857 auto ElementSizeB = DL.getTypeSizeInBits(MMI.B->getElementType()); 858 auto ElementSizeC = DL.getTypeSizeInBits(MMI.WriteToC->getElementType()); 859 return std::max({ElementSizeA, ElementSizeB, ElementSizeC}); 860 } 861 862 /// Get parameters of the BLIS micro kernel. 863 /// 864 /// We choose the Mr and Nr parameters of the micro kernel to be large enough 865 /// such that no stalls caused by the combination of latencies and dependencies 866 /// are introduced during the updates of the resulting matrix of the matrix 867 /// multiplication. However, they should also be as small as possible to 868 /// release more registers for entries of multiplied matrices. 869 /// 870 /// @param TTI Target Transform Info. 871 /// @param MMI Parameters of the matrix multiplication operands. 872 /// @return The structure of type MicroKernelParamsTy. 873 /// @see MicroKernelParamsTy 874 static struct MicroKernelParamsTy 875 getMicroKernelParams(const TargetTransformInfo *TTI, MatMulInfoTy MMI) { 876 assert(TTI && "The target transform info should be provided."); 877 878 // Nvec - Number of double-precision floating-point numbers that can be hold 879 // by a vector register. Use 2 by default. 880 long RegisterBitwidth = VectorRegisterBitwidth; 881 882 if (RegisterBitwidth == -1) 883 RegisterBitwidth = TTI->getRegisterBitWidth(true); 884 auto ElementSize = getMatMulTypeSize(MMI); 885 assert(ElementSize > 0 && "The element size of the matrix multiplication " 886 "operands should be greater than zero."); 887 auto Nvec = RegisterBitwidth / ElementSize; 888 if (Nvec == 0) 889 Nvec = 2; 890 int Nr = 891 ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec; 892 int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr); 893 return {Mr, Nr}; 894 } 895 896 /// Get parameters of the BLIS macro kernel. 897 /// 898 /// During the computation of matrix multiplication, blocks of partitioned 899 /// matrices are mapped to different layers of the memory hierarchy. 900 /// To optimize data reuse, blocks should be ideally kept in cache between 901 /// iterations. Since parameters of the macro kernel determine sizes of these 902 /// blocks, there are upper and lower bounds on these parameters. 903 /// 904 /// @param MicroKernelParams Parameters of the micro-kernel 905 /// to be taken into account. 906 /// @param MMI Parameters of the matrix multiplication operands. 907 /// @return The structure of type MacroKernelParamsTy. 908 /// @see MacroKernelParamsTy 909 /// @see MicroKernelParamsTy 910 static struct MacroKernelParamsTy 911 getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams, 912 MatMulInfoTy MMI) { 913 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf, 914 // it requires information about the first two levels of a cache to determine 915 // all the parameters of a macro-kernel. It also checks that an associativity 916 // degree of a cache level is greater than two. Otherwise, another algorithm 917 // for determination of the parameters should be used. 918 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 && 919 FirstCacheLevelSize > 0 && SecondCacheLevelSize > 0 && 920 FirstCacheLevelAssociativity > 2 && SecondCacheLevelAssociativity > 2)) 921 return {1, 1, 1}; 922 // The quotient should be greater than zero. 923 if (PollyPatternMatchingNcQuotient <= 0) 924 return {1, 1, 1}; 925 int Car = floor( 926 (FirstCacheLevelAssociativity - 1) / 927 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr)); 928 929 // Car can be computed to be zero since it is floor to int. 930 // On Mac OS, division by 0 does not raise a signal. This causes negative 931 // tile sizes to be computed. Prevent division by Cac==0 by early returning 932 // if this happens. 933 if (Car == 0) 934 return {1, 1, 1}; 935 936 auto ElementSize = getMatMulAlignTypeSize(MMI); 937 assert(ElementSize > 0 && "The element size of the matrix multiplication " 938 "operands should be greater than zero."); 939 int Kc = (Car * FirstCacheLevelSize) / 940 (MicroKernelParams.Mr * FirstCacheLevelAssociativity * ElementSize); 941 double Cac = 942 static_cast<double>(Kc * ElementSize * SecondCacheLevelAssociativity) / 943 SecondCacheLevelSize; 944 int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac); 945 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr; 946 947 assert(Mc > 0 && Nc > 0 && Kc > 0 && 948 "Matrix block sizes should be greater than zero"); 949 return {Mc, Nc, Kc}; 950 } 951 952 /// Create an access relation that is specific to 953 /// the matrix multiplication pattern. 954 /// 955 /// Create an access relation of the following form: 956 /// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ] 957 /// where I is @p FirstDim, J is @p SecondDim. 958 /// 959 /// It can be used, for example, to create relations that helps to consequently 960 /// access elements of operands of a matrix multiplication after creation of 961 /// the BLIS micro and macro kernels. 962 /// 963 /// @see ScheduleTreeOptimizer::createMicroKernel 964 /// @see ScheduleTreeOptimizer::createMacroKernel 965 /// 966 /// Subsequently, the described access relation is applied to the range of 967 /// @p MapOldIndVar, that is used to map original induction variables to 968 /// the ones, which are produced by schedule transformations. It helps to 969 /// define relations using a new space and, at the same time, keep them 970 /// in the original one. 971 /// 972 /// @param MapOldIndVar The relation, which maps original induction variables 973 /// to the ones, which are produced by schedule 974 /// transformations. 975 /// @param FirstDim, SecondDim The input dimensions that are used to define 976 /// the specified access relation. 977 /// @return The specified access relation. 978 isl::map getMatMulAccRel(isl::map MapOldIndVar, unsigned FirstDim, 979 unsigned SecondDim) { 980 auto AccessRelSpace = isl::space(MapOldIndVar.get_ctx(), 0, 9, 3); 981 auto AccessRel = isl::map::universe(AccessRelSpace); 982 AccessRel = AccessRel.equate(isl::dim::in, FirstDim, isl::dim::out, 0); 983 AccessRel = AccessRel.equate(isl::dim::in, 5, isl::dim::out, 1); 984 AccessRel = AccessRel.equate(isl::dim::in, SecondDim, isl::dim::out, 2); 985 return MapOldIndVar.apply_range(AccessRel); 986 } 987 988 isl::schedule_node createExtensionNode(isl::schedule_node Node, 989 isl::map ExtensionMap) { 990 auto Extension = isl::union_map(ExtensionMap); 991 auto NewNode = isl::schedule_node::from_extension(Extension); 992 return Node.graft_before(NewNode); 993 } 994 995 /// Apply the packing transformation. 996 /// 997 /// The packing transformation can be described as a data-layout 998 /// transformation that requires to introduce a new array, copy data 999 /// to the array, and change memory access locations to reference the array. 1000 /// It can be used to ensure that elements of the new array are read in-stride 1001 /// access, aligned to cache lines boundaries, and preloaded into certain cache 1002 /// levels. 1003 /// 1004 /// As an example let us consider the packing of the array A that would help 1005 /// to read its elements with in-stride access. An access to the array A 1006 /// is represented by an access relation that has the form 1007 /// S[i, j, k] -> A[i, k]. The scheduling function of the SCoP statement S has 1008 /// the form S[i,j, k] -> [floor((j mod Nc) / Nr), floor((i mod Mc) / Mr), 1009 /// k mod Kc, j mod Nr, i mod Mr]. 1010 /// 1011 /// To ensure that elements of the array A are read in-stride access, we add 1012 /// a new array Packed_A[Mc/Mr][Kc][Mr] to the SCoP, using 1013 /// Scop::createScopArrayInfo, change the access relation 1014 /// S[i, j, k] -> A[i, k] to 1015 /// S[i, j, k] -> Packed_A[floor((i mod Mc) / Mr), k mod Kc, i mod Mr], using 1016 /// MemoryAccess::setNewAccessRelation, and copy the data to the array, using 1017 /// the copy statement created by Scop::addScopStmt. 1018 /// 1019 /// @param Node The schedule node to be optimized. 1020 /// @param MapOldIndVar The relation, which maps original induction variables 1021 /// to the ones, which are produced by schedule 1022 /// transformations. 1023 /// @param MicroParams, MacroParams Parameters of the BLIS kernel 1024 /// to be taken into account. 1025 /// @param MMI Parameters of the matrix multiplication operands. 1026 /// @return The optimized schedule node. 1027 static isl::schedule_node 1028 optimizeDataLayoutMatrMulPattern(isl::schedule_node Node, isl::map MapOldIndVar, 1029 MicroKernelParamsTy MicroParams, 1030 MacroKernelParamsTy MacroParams, 1031 MatMulInfoTy &MMI) { 1032 auto InputDimsId = MapOldIndVar.get_tuple_id(isl::dim::in); 1033 auto *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user()); 1034 1035 // Create a copy statement that corresponds to the memory access to the 1036 // matrix B, the second operand of the matrix multiplication. 1037 Node = Node.parent().parent().parent().parent().parent().parent(); 1038 Node = isl::manage(isl_schedule_node_band_split(Node.release(), 2)).child(0); 1039 auto AccRel = getMatMulAccRel(isl::manage(MapOldIndVar.copy()), 3, 7); 1040 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr; 1041 unsigned SecondDimSize = MacroParams.Kc; 1042 unsigned ThirdDimSize = MicroParams.Nr; 1043 auto *SAI = Stmt->getParent()->createScopArrayInfo( 1044 MMI.B->getElementType(), "Packed_B", 1045 {FirstDimSize, SecondDimSize, ThirdDimSize}); 1046 AccRel = AccRel.set_tuple_id(isl::dim::out, SAI->getBasePtrId()); 1047 auto OldAcc = MMI.B->getLatestAccessRelation(); 1048 MMI.B->setNewAccessRelation(AccRel); 1049 auto ExtMap = MapOldIndVar.project_out(isl::dim::out, 2, 1050 MapOldIndVar.dim(isl::dim::out) - 2); 1051 ExtMap = ExtMap.reverse(); 1052 ExtMap = ExtMap.fix_si(isl::dim::out, MMI.i, 0); 1053 auto Domain = Stmt->getDomain(); 1054 1055 // Restrict the domains of the copy statements to only execute when also its 1056 // originating statement is executed. 1057 auto DomainId = Domain.get_tuple_id(); 1058 auto *NewStmt = Stmt->getParent()->addScopStmt( 1059 OldAcc, MMI.B->getLatestAccessRelation(), Domain); 1060 ExtMap = ExtMap.set_tuple_id(isl::dim::out, isl::manage(DomainId.copy())); 1061 ExtMap = ExtMap.intersect_range(isl::manage(Domain.copy())); 1062 ExtMap = ExtMap.set_tuple_id(isl::dim::out, NewStmt->getDomainId()); 1063 Node = createExtensionNode(Node, ExtMap); 1064 1065 // Create a copy statement that corresponds to the memory access 1066 // to the matrix A, the first operand of the matrix multiplication. 1067 Node = Node.child(0); 1068 AccRel = getMatMulAccRel(isl::manage(MapOldIndVar.copy()), 4, 6); 1069 FirstDimSize = MacroParams.Mc / MicroParams.Mr; 1070 ThirdDimSize = MicroParams.Mr; 1071 SAI = Stmt->getParent()->createScopArrayInfo( 1072 MMI.A->getElementType(), "Packed_A", 1073 {FirstDimSize, SecondDimSize, ThirdDimSize}); 1074 AccRel = AccRel.set_tuple_id(isl::dim::out, SAI->getBasePtrId()); 1075 OldAcc = MMI.A->getLatestAccessRelation(); 1076 MMI.A->setNewAccessRelation(AccRel); 1077 ExtMap = MapOldIndVar.project_out(isl::dim::out, 3, 1078 MapOldIndVar.dim(isl::dim::out) - 3); 1079 ExtMap = ExtMap.reverse(); 1080 ExtMap = ExtMap.fix_si(isl::dim::out, MMI.j, 0); 1081 NewStmt = Stmt->getParent()->addScopStmt( 1082 OldAcc, MMI.A->getLatestAccessRelation(), Domain); 1083 1084 // Restrict the domains of the copy statements to only execute when also its 1085 // originating statement is executed. 1086 ExtMap = ExtMap.set_tuple_id(isl::dim::out, DomainId); 1087 ExtMap = ExtMap.intersect_range(Domain); 1088 ExtMap = ExtMap.set_tuple_id(isl::dim::out, NewStmt->getDomainId()); 1089 Node = createExtensionNode(Node, ExtMap); 1090 return Node.child(0).child(0).child(0).child(0).child(0); 1091 } 1092 1093 /// Get a relation mapping induction variables produced by schedule 1094 /// transformations to the original ones. 1095 /// 1096 /// @param Node The schedule node produced as the result of creation 1097 /// of the BLIS kernels. 1098 /// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel 1099 /// to be taken into account. 1100 /// @return The relation mapping original induction variables to the ones 1101 /// produced by schedule transformation. 1102 /// @see ScheduleTreeOptimizer::createMicroKernel 1103 /// @see ScheduleTreeOptimizer::createMacroKernel 1104 /// @see getMacroKernelParams 1105 isl::map 1106 getInductionVariablesSubstitution(isl::schedule_node Node, 1107 MicroKernelParamsTy MicroKernelParams, 1108 MacroKernelParamsTy MacroKernelParams) { 1109 auto Child = Node.child(0); 1110 auto UnMapOldIndVar = Child.get_prefix_schedule_union_map(); 1111 auto MapOldIndVar = isl::map::from_union_map(UnMapOldIndVar); 1112 if (MapOldIndVar.dim(isl::dim::out) > 9) 1113 return MapOldIndVar.project_out(isl::dim::out, 0, 1114 MapOldIndVar.dim(isl::dim::out) - 9); 1115 return MapOldIndVar; 1116 } 1117 1118 /// Isolate a set of partial tile prefixes and unroll the isolated part. 1119 /// 1120 /// The set should ensure that it contains only partial tile prefixes that have 1121 /// exactly Mr x Nr iterations of the two innermost loops produced by 1122 /// the optimization of the matrix multiplication. Mr and Nr are parameters of 1123 /// the micro-kernel. 1124 /// 1125 /// In case of parametric bounds, this helps to auto-vectorize the unrolled 1126 /// innermost loops, using the SLP vectorizer. 1127 /// 1128 /// @param Node The schedule node to be modified. 1129 /// @param MicroKernelParams Parameters of the micro-kernel 1130 /// to be taken into account. 1131 /// @return The modified isl_schedule_node. 1132 static isl::schedule_node 1133 isolateAndUnrollMatMulInnerLoops(isl::schedule_node Node, 1134 struct MicroKernelParamsTy MicroKernelParams) { 1135 isl::schedule_node Child = Node.get_child(0); 1136 isl::union_map UnMapOldIndVar = Child.get_prefix_schedule_relation(); 1137 isl::set Prefix = isl::map::from_union_map(UnMapOldIndVar).range(); 1138 unsigned Dims = Prefix.dim(isl::dim::set); 1139 Prefix = Prefix.project_out(isl::dim::set, Dims - 1, 1); 1140 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Nr); 1141 Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Mr); 1142 1143 isl::union_set IsolateOption = 1144 getIsolateOptions(Prefix.add_dims(isl::dim::set, 3), 3); 1145 isl::ctx Ctx = Node.get_ctx(); 1146 isl::union_set AtomicOption = getAtomicOptions(Ctx); 1147 isl::union_set Options = IsolateOption.unite(AtomicOption); 1148 Options = Options.unite(getUnrollIsolatedSetOptions(Ctx)); 1149 Node = Node.band_set_ast_build_options(Options); 1150 Node = Node.parent().parent().parent(); 1151 IsolateOption = getIsolateOptions(Prefix, 3); 1152 Options = IsolateOption.unite(AtomicOption); 1153 Node = Node.band_set_ast_build_options(Options); 1154 Node = Node.child(0).child(0).child(0); 1155 return Node; 1156 } 1157 1158 /// Mark @p BasePtr with "Inter iteration alias-free" mark node. 1159 /// 1160 /// @param Node The child of the mark node to be inserted. 1161 /// @param BasePtr The pointer to be marked. 1162 /// @return The modified isl_schedule_node. 1163 static isl::schedule_node markInterIterationAliasFree(isl::schedule_node Node, 1164 Value *BasePtr) { 1165 if (!BasePtr) 1166 return Node; 1167 1168 auto Id = 1169 isl::id::alloc(Node.get_ctx(), "Inter iteration alias-free", BasePtr); 1170 return Node.insert_mark(Id).child(0); 1171 } 1172 1173 /// Insert "Loop Vectorizer Disabled" mark node. 1174 /// 1175 /// @param Node The child of the mark node to be inserted. 1176 /// @return The modified isl_schedule_node. 1177 static isl::schedule_node markLoopVectorizerDisabled(isl::schedule_node Node) { 1178 auto Id = isl::id::alloc(Node.get_ctx(), "Loop Vectorizer Disabled", nullptr); 1179 return Node.insert_mark(Id).child(0); 1180 } 1181 1182 /// Restore the initial ordering of dimensions of the band node 1183 /// 1184 /// In case the band node represents all the dimensions of the iteration 1185 /// domain, recreate the band node to restore the initial ordering of the 1186 /// dimensions. 1187 /// 1188 /// @param Node The band node to be modified. 1189 /// @return The modified schedule node. 1190 static isl::schedule_node 1191 getBandNodeWithOriginDimOrder(isl::schedule_node Node) { 1192 assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band); 1193 if (isl_schedule_node_get_type(Node.child(0).keep()) != 1194 isl_schedule_node_leaf) 1195 return Node; 1196 auto Domain = Node.get_universe_domain(); 1197 assert(isl_union_set_n_set(Domain.keep()) == 1); 1198 if (Node.get_schedule_depth() != 0 || 1199 (isl::set(isl::manage(Domain.copy())).dim(isl::dim::set) != 1200 isl_schedule_node_band_n_member(Node.keep()))) 1201 return Node; 1202 Node = isl::manage(isl_schedule_node_delete(Node.take())); 1203 auto PartialSchedulePwAff = Domain.identity_union_pw_multi_aff(); 1204 auto PartialScheduleMultiPwAff = 1205 isl::multi_union_pw_aff(PartialSchedulePwAff); 1206 PartialScheduleMultiPwAff = 1207 PartialScheduleMultiPwAff.reset_tuple_id(isl::dim::set); 1208 return Node.insert_partial_schedule(PartialScheduleMultiPwAff); 1209 } 1210 1211 isl::schedule_node 1212 ScheduleTreeOptimizer::optimizeMatMulPattern(isl::schedule_node Node, 1213 const TargetTransformInfo *TTI, 1214 MatMulInfoTy &MMI) { 1215 assert(TTI && "The target transform info should be provided."); 1216 Node = markInterIterationAliasFree( 1217 Node, MMI.WriteToC->getLatestScopArrayInfo()->getBasePtr()); 1218 int DimOutNum = isl_schedule_node_band_n_member(Node.get()); 1219 assert(DimOutNum > 2 && "In case of the matrix multiplication the loop nest " 1220 "and, consequently, the corresponding scheduling " 1221 "functions have at least three dimensions."); 1222 Node = getBandNodeWithOriginDimOrder(Node); 1223 Node = permuteBandNodeDimensions(Node, MMI.i, DimOutNum - 3); 1224 int NewJ = MMI.j == DimOutNum - 3 ? MMI.i : MMI.j; 1225 int NewK = MMI.k == DimOutNum - 3 ? MMI.i : MMI.k; 1226 Node = permuteBandNodeDimensions(Node, NewJ, DimOutNum - 2); 1227 NewK = NewK == DimOutNum - 2 ? NewJ : NewK; 1228 Node = permuteBandNodeDimensions(Node, NewK, DimOutNum - 1); 1229 auto MicroKernelParams = getMicroKernelParams(TTI, MMI); 1230 auto MacroKernelParams = getMacroKernelParams(MicroKernelParams, MMI); 1231 Node = createMacroKernel(Node, MacroKernelParams); 1232 Node = createMicroKernel(Node, MicroKernelParams); 1233 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 || 1234 MacroKernelParams.Kc == 1) 1235 return Node; 1236 auto MapOldIndVar = getInductionVariablesSubstitution(Node, MicroKernelParams, 1237 MacroKernelParams); 1238 if (!MapOldIndVar) 1239 return Node; 1240 Node = markLoopVectorizerDisabled(Node.parent()).child(0); 1241 Node = isolateAndUnrollMatMulInnerLoops(Node, MicroKernelParams); 1242 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams, 1243 MacroKernelParams, MMI); 1244 } 1245 1246 bool ScheduleTreeOptimizer::isMatrMultPattern(isl::schedule_node Node, 1247 const Dependences *D, 1248 MatMulInfoTy &MMI) { 1249 auto PartialSchedule = isl::manage( 1250 isl_schedule_node_band_get_partial_schedule_union_map(Node.get())); 1251 Node = Node.child(0); 1252 auto LeafType = isl_schedule_node_get_type(Node.get()); 1253 Node = Node.parent(); 1254 if (LeafType != isl_schedule_node_leaf || 1255 isl_schedule_node_band_n_member(Node.get()) < 3 || 1256 Node.get_schedule_depth() != 0 || 1257 isl_union_map_n_map(PartialSchedule.get()) != 1) 1258 return false; 1259 auto NewPartialSchedule = isl::map::from_union_map(PartialSchedule); 1260 if (containsMatrMult(NewPartialSchedule, D, MMI)) 1261 return true; 1262 return false; 1263 } 1264 1265 __isl_give isl_schedule_node * 1266 ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node, 1267 void *User) { 1268 if (!isTileableBandNode(isl::manage(isl_schedule_node_copy(Node)))) 1269 return Node; 1270 1271 const OptimizerAdditionalInfoTy *OAI = 1272 static_cast<const OptimizerAdditionalInfoTy *>(User); 1273 1274 MatMulInfoTy MMI; 1275 if (PMBasedOpts && User && 1276 isMatrMultPattern(isl::manage(isl_schedule_node_copy(Node)), OAI->D, 1277 MMI)) { 1278 DEBUG(dbgs() << "The matrix multiplication pattern was detected\n"); 1279 MatMulOpts++; 1280 return optimizeMatMulPattern(isl::manage(Node), OAI->TTI, MMI).release(); 1281 } 1282 1283 return standardBandOpts(isl::manage(Node), User).release(); 1284 } 1285 1286 isl::schedule 1287 ScheduleTreeOptimizer::optimizeSchedule(isl::schedule Schedule, 1288 const OptimizerAdditionalInfoTy *OAI) { 1289 auto Root = Schedule.get_root(); 1290 Root = optimizeScheduleNode(Root, OAI); 1291 return Root.get_schedule(); 1292 } 1293 1294 isl::schedule_node ScheduleTreeOptimizer::optimizeScheduleNode( 1295 isl::schedule_node Node, const OptimizerAdditionalInfoTy *OAI) { 1296 Node = isl::manage(isl_schedule_node_map_descendant_bottom_up( 1297 Node.release(), optimizeBand, 1298 const_cast<void *>(static_cast<const void *>(OAI)))); 1299 return Node; 1300 } 1301 1302 bool ScheduleTreeOptimizer::isProfitableSchedule(Scop &S, 1303 isl::schedule NewSchedule) { 1304 // To understand if the schedule has been optimized we check if the schedule 1305 // has changed at all. 1306 // TODO: We can improve this by tracking if any necessarily beneficial 1307 // transformations have been performed. This can e.g. be tiling, loop 1308 // interchange, or ...) We can track this either at the place where the 1309 // transformation has been performed or, in case of automatic ILP based 1310 // optimizations, by comparing (yet to be defined) performance metrics 1311 // before/after the scheduling optimizer 1312 // (e.g., #stride-one accesses) 1313 if (S.containsExtensionNode(NewSchedule.get())) 1314 return true; 1315 auto NewScheduleMap = NewSchedule.get_map(); 1316 auto OldSchedule = S.getSchedule(); 1317 assert(OldSchedule && "Only IslScheduleOptimizer can insert extension nodes " 1318 "that make Scop::getSchedule() return nullptr."); 1319 bool changed = !OldSchedule.is_equal(NewScheduleMap); 1320 return changed; 1321 } 1322 1323 namespace { 1324 1325 class IslScheduleOptimizer : public ScopPass { 1326 public: 1327 static char ID; 1328 1329 explicit IslScheduleOptimizer() : ScopPass(ID) {} 1330 1331 ~IslScheduleOptimizer() override { isl_schedule_free(LastSchedule); } 1332 1333 /// Optimize the schedule of the SCoP @p S. 1334 bool runOnScop(Scop &S) override; 1335 1336 /// Print the new schedule for the SCoP @p S. 1337 void printScop(raw_ostream &OS, Scop &S) const override; 1338 1339 /// Register all analyses and transformation required. 1340 void getAnalysisUsage(AnalysisUsage &AU) const override; 1341 1342 /// Release the internal memory. 1343 void releaseMemory() override { 1344 isl_schedule_free(LastSchedule); 1345 LastSchedule = nullptr; 1346 } 1347 1348 private: 1349 isl_schedule *LastSchedule = nullptr; 1350 }; 1351 1352 } // namespace 1353 1354 char IslScheduleOptimizer::ID = 0; 1355 1356 /// Collect statistics for the schedule tree. 1357 /// 1358 /// @param Schedule The schedule tree to analyze. If not a schedule tree it is 1359 /// ignored. 1360 /// @param Version The version of the schedule tree that is analyzed. 1361 /// 0 for the original schedule tree before any transformation. 1362 /// 1 for the schedule tree after isl's rescheduling. 1363 /// 2 for the schedule tree after optimizations are applied 1364 /// (tiling, pattern matching) 1365 static void walkScheduleTreeForStatistics(isl::schedule Schedule, int Version) { 1366 auto Root = Schedule.get_root(); 1367 if (!Root) 1368 return; 1369 1370 Root.foreach_ancestor_top_down([Version]( 1371 isl::schedule_node Node) -> isl::stat { 1372 switch (isl_schedule_node_get_type(Node.get())) { 1373 case isl_schedule_node_band: { 1374 NumBands[Version]++; 1375 if (isl_schedule_node_band_get_permutable(Node.get()) == isl_bool_true) 1376 NumPermutable[Version]++; 1377 1378 int CountMembers = isl_schedule_node_band_n_member(Node.get()); 1379 NumBandMembers[Version] += CountMembers; 1380 for (int i = 0; i < CountMembers; i += 1) { 1381 if (Node.band_member_get_coincident(i)) 1382 NumCoincident[Version]++; 1383 } 1384 break; 1385 } 1386 1387 case isl_schedule_node_filter: 1388 NumFilters[Version]++; 1389 break; 1390 1391 case isl_schedule_node_extension: 1392 NumExtension[Version]++; 1393 break; 1394 1395 default: 1396 break; 1397 } 1398 1399 return isl::stat::ok; 1400 }); 1401 } 1402 1403 bool IslScheduleOptimizer::runOnScop(Scop &S) { 1404 // Skip SCoPs in case they're already optimised by PPCGCodeGeneration 1405 if (S.isToBeSkipped()) 1406 return false; 1407 1408 // Skip empty SCoPs but still allow code generation as it will delete the 1409 // loops present but not needed. 1410 if (S.getSize() == 0) { 1411 S.markAsOptimized(); 1412 return false; 1413 } 1414 1415 const Dependences &D = 1416 getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement); 1417 1418 if (!D.hasValidDependences()) 1419 return false; 1420 1421 isl_schedule_free(LastSchedule); 1422 LastSchedule = nullptr; 1423 1424 // Build input data. 1425 int ValidityKinds = 1426 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW; 1427 int ProximityKinds; 1428 1429 if (OptimizeDeps == "all") 1430 ProximityKinds = 1431 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW; 1432 else if (OptimizeDeps == "raw") 1433 ProximityKinds = Dependences::TYPE_RAW; 1434 else { 1435 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'" 1436 << " Falling back to optimizing all dependences.\n"; 1437 ProximityKinds = 1438 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW; 1439 } 1440 1441 isl::union_set Domain = S.getDomains(); 1442 1443 if (!Domain) 1444 return false; 1445 1446 ScopsProcessed++; 1447 walkScheduleTreeForStatistics(S.getScheduleTree(), 0); 1448 1449 isl::union_map Validity = give(D.getDependences(ValidityKinds)); 1450 isl::union_map Proximity = give(D.getDependences(ProximityKinds)); 1451 1452 // Simplify the dependences by removing the constraints introduced by the 1453 // domains. This can speed up the scheduling time significantly, as large 1454 // constant coefficients will be removed from the dependences. The 1455 // introduction of some additional dependences reduces the possible 1456 // transformations, but in most cases, such transformation do not seem to be 1457 // interesting anyway. In some cases this option may stop the scheduler to 1458 // find any schedule. 1459 if (SimplifyDeps == "yes") { 1460 Validity = Validity.gist_domain(Domain); 1461 Validity = Validity.gist_range(Domain); 1462 Proximity = Proximity.gist_domain(Domain); 1463 Proximity = Proximity.gist_range(Domain); 1464 } else if (SimplifyDeps != "no") { 1465 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' " 1466 "or 'no'. Falling back to default: 'yes'\n"; 1467 } 1468 1469 DEBUG(dbgs() << "\n\nCompute schedule from: "); 1470 DEBUG(dbgs() << "Domain := " << Domain << ";\n"); 1471 DEBUG(dbgs() << "Proximity := " << Proximity << ";\n"); 1472 DEBUG(dbgs() << "Validity := " << Validity << ";\n"); 1473 1474 unsigned IslSerializeSCCs; 1475 1476 if (FusionStrategy == "max") { 1477 IslSerializeSCCs = 0; 1478 } else if (FusionStrategy == "min") { 1479 IslSerializeSCCs = 1; 1480 } else { 1481 errs() << "warning: Unknown fusion strategy. Falling back to maximal " 1482 "fusion.\n"; 1483 IslSerializeSCCs = 0; 1484 } 1485 1486 int IslMaximizeBands; 1487 1488 if (MaximizeBandDepth == "yes") { 1489 IslMaximizeBands = 1; 1490 } else if (MaximizeBandDepth == "no") { 1491 IslMaximizeBands = 0; 1492 } else { 1493 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'" 1494 " or 'no'. Falling back to default: 'yes'\n"; 1495 IslMaximizeBands = 1; 1496 } 1497 1498 int IslOuterCoincidence; 1499 1500 if (OuterCoincidence == "yes") { 1501 IslOuterCoincidence = 1; 1502 } else if (OuterCoincidence == "no") { 1503 IslOuterCoincidence = 0; 1504 } else { 1505 errs() << "warning: Option -polly-opt-outer-coincidence should either be " 1506 "'yes' or 'no'. Falling back to default: 'no'\n"; 1507 IslOuterCoincidence = 0; 1508 } 1509 1510 isl_ctx *Ctx = S.getIslCtx(); 1511 1512 isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence); 1513 isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs); 1514 isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands); 1515 isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm); 1516 isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient); 1517 isl_options_set_tile_scale_tile_loops(Ctx, 0); 1518 1519 auto OnErrorStatus = isl_options_get_on_error(Ctx); 1520 isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE); 1521 1522 auto SC = isl::schedule_constraints::on_domain(Domain); 1523 SC = SC.set_proximity(Proximity); 1524 SC = SC.set_validity(Validity); 1525 SC = SC.set_coincidence(Validity); 1526 auto Schedule = SC.compute_schedule(); 1527 isl_options_set_on_error(Ctx, OnErrorStatus); 1528 1529 walkScheduleTreeForStatistics(Schedule, 1); 1530 1531 // In cases the scheduler is not able to optimize the code, we just do not 1532 // touch the schedule. 1533 if (!Schedule) 1534 return false; 1535 1536 ScopsRescheduled++; 1537 1538 DEBUG({ 1539 auto *P = isl_printer_to_str(Ctx); 1540 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 1541 P = isl_printer_print_schedule(P, Schedule.get()); 1542 auto *str = isl_printer_get_str(P); 1543 dbgs() << "NewScheduleTree: \n" << str << "\n"; 1544 free(str); 1545 isl_printer_free(P); 1546 }); 1547 1548 Function &F = S.getFunction(); 1549 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1550 const OptimizerAdditionalInfoTy OAI = {TTI, const_cast<Dependences *>(&D)}; 1551 auto NewSchedule = ScheduleTreeOptimizer::optimizeSchedule(Schedule, &OAI); 1552 walkScheduleTreeForStatistics(NewSchedule, 1); 1553 1554 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule)) 1555 return false; 1556 1557 auto ScopStats = S.getStatistics(); 1558 ScopsOptimized++; 1559 NumAffineLoopsOptimized += ScopStats.NumAffineLoops; 1560 NumBoxedLoopsOptimized += ScopStats.NumBoxedLoops; 1561 1562 S.setScheduleTree(NewSchedule.release()); 1563 S.markAsOptimized(); 1564 1565 if (OptimizedScops) 1566 errs() << S; 1567 1568 return false; 1569 } 1570 1571 void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const { 1572 isl_printer *p; 1573 char *ScheduleStr; 1574 1575 OS << "Calculated schedule:\n"; 1576 1577 if (!LastSchedule) { 1578 OS << "n/a\n"; 1579 return; 1580 } 1581 1582 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule)); 1583 p = isl_printer_print_schedule(p, LastSchedule); 1584 ScheduleStr = isl_printer_get_str(p); 1585 isl_printer_free(p); 1586 1587 OS << ScheduleStr << "\n"; 1588 } 1589 1590 void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const { 1591 ScopPass::getAnalysisUsage(AU); 1592 AU.addRequired<DependenceInfo>(); 1593 AU.addRequired<TargetTransformInfoWrapperPass>(); 1594 1595 AU.addPreserved<DependenceInfo>(); 1596 } 1597 1598 Pass *polly::createIslScheduleOptimizerPass() { 1599 return new IslScheduleOptimizer(); 1600 } 1601 1602 INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl", 1603 "Polly - Optimize schedule of SCoP", false, false); 1604 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 1605 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass); 1606 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass); 1607 INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl", 1608 "Polly - Optimize schedule of SCoP", false, false) 1609