1 //===- ScopBuilder.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 // 9 // Create a polyhedral description for a static control flow region. 10 // 11 // The pass creates a polyhedral description of the Scops detected by the SCoP 12 // detection derived from their LLVM-IR code. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "polly/ScopBuilder.h" 17 #include "polly/Options.h" 18 #include "polly/ScopDetection.h" 19 #include "polly/ScopInfo.h" 20 #include "polly/Support/GICHelper.h" 21 #include "polly/Support/ISLTools.h" 22 #include "polly/Support/SCEVValidator.h" 23 #include "polly/Support/ScopHelper.h" 24 #include "polly/Support/VirtualInstruction.h" 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/EquivalenceClasses.h" 27 #include "llvm/ADT/PostOrderIterator.h" 28 #include "llvm/ADT/Sequence.h" 29 #include "llvm/ADT/SmallSet.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/AliasAnalysis.h" 32 #include "llvm/Analysis/AssumptionCache.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/LoopInfo.h" 35 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 36 #include "llvm/Analysis/RegionInfo.h" 37 #include "llvm/Analysis/RegionIterator.h" 38 #include "llvm/Analysis/ScalarEvolution.h" 39 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 40 #include "llvm/IR/BasicBlock.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/Type.h" 50 #include "llvm/IR/Use.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <cassert> 58 59 using namespace llvm; 60 using namespace polly; 61 62 #define DEBUG_TYPE "polly-scops" 63 64 STATISTIC(ScopFound, "Number of valid Scops"); 65 STATISTIC(RichScopFound, "Number of Scops containing a loop"); 66 STATISTIC(InfeasibleScops, 67 "Number of SCoPs with statically infeasible context."); 68 69 bool polly::ModelReadOnlyScalars; 70 71 // The maximal number of dimensions we allow during invariant load construction. 72 // More complex access ranges will result in very high compile time and are also 73 // unlikely to result in good code. This value is very high and should only 74 // trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006). 75 static int const MaxDimensionsInAccessRange = 9; 76 77 static cl::opt<bool, true> XModelReadOnlyScalars( 78 "polly-analyze-read-only-scalars", 79 cl::desc("Model read-only scalar values in the scop description"), 80 cl::location(ModelReadOnlyScalars), cl::Hidden, cl::ZeroOrMore, 81 cl::init(true), cl::cat(PollyCategory)); 82 83 static cl::opt<int> 84 OptComputeOut("polly-analysis-computeout", 85 cl::desc("Bound the scop analysis by a maximal amount of " 86 "computational steps (0 means no bound)"), 87 cl::Hidden, cl::init(800000), cl::ZeroOrMore, 88 cl::cat(PollyCategory)); 89 90 static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams( 91 "polly-allow-dereference-of-all-function-parameters", 92 cl::desc( 93 "Treat all parameters to functions that are pointers as dereferencible." 94 " This is useful for invariant load hoisting, since we can generate" 95 " less runtime checks. This is only valid if all pointers to functions" 96 " are always initialized, so that Polly can choose to hoist" 97 " their loads. "), 98 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 99 100 static cl::opt<bool> 101 PollyIgnoreInbounds("polly-ignore-inbounds", 102 cl::desc("Do not take inbounds assumptions at all"), 103 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 104 105 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup( 106 "polly-rtc-max-arrays-per-group", 107 cl::desc("The maximal number of arrays to compare in each alias group."), 108 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory)); 109 110 static cl::opt<int> RunTimeChecksMaxAccessDisjuncts( 111 "polly-rtc-max-array-disjuncts", 112 cl::desc("The maximal number of disjunts allowed in memory accesses to " 113 "to build RTCs."), 114 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 115 116 static cl::opt<unsigned> RunTimeChecksMaxParameters( 117 "polly-rtc-max-parameters", 118 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden, 119 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 120 121 static cl::opt<bool> UnprofitableScalarAccs( 122 "polly-unprofitable-scalar-accs", 123 cl::desc("Count statements with scalar accesses as not optimizable"), 124 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 125 126 static cl::opt<std::string> UserContextStr( 127 "polly-context", cl::value_desc("isl parameter set"), 128 cl::desc("Provide additional constraints on the context parameters"), 129 cl::init(""), cl::cat(PollyCategory)); 130 131 static cl::opt<bool> DetectFortranArrays( 132 "polly-detect-fortran-arrays", 133 cl::desc("Detect Fortran arrays and use this for code generation"), 134 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 135 136 static cl::opt<bool> DetectReductions("polly-detect-reductions", 137 cl::desc("Detect and exploit reductions"), 138 cl::Hidden, cl::ZeroOrMore, 139 cl::init(true), cl::cat(PollyCategory)); 140 141 // Multiplicative reductions can be disabled separately as these kind of 142 // operations can overflow easily. Additive reductions and bit operations 143 // are in contrast pretty stable. 144 static cl::opt<bool> DisableMultiplicativeReductions( 145 "polly-disable-multiplicative-reductions", 146 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore, 147 cl::init(false), cl::cat(PollyCategory)); 148 149 enum class GranularityChoice { BasicBlocks, ScalarIndependence, Stores }; 150 151 static cl::opt<GranularityChoice> StmtGranularity( 152 "polly-stmt-granularity", 153 cl::desc( 154 "Algorithm to use for splitting basic blocks into multiple statements"), 155 cl::values(clEnumValN(GranularityChoice::BasicBlocks, "bb", 156 "One statement per basic block"), 157 clEnumValN(GranularityChoice::ScalarIndependence, "scalar-indep", 158 "Scalar independence heuristic"), 159 clEnumValN(GranularityChoice::Stores, "store", 160 "Store-level granularity")), 161 cl::init(GranularityChoice::ScalarIndependence), cl::cat(PollyCategory)); 162 163 /// Helper to treat non-affine regions and basic blocks the same. 164 /// 165 ///{ 166 167 /// Return the block that is the representing block for @p RN. 168 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) { 169 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry() 170 : RN->getNodeAs<BasicBlock>(); 171 } 172 173 /// Return the @p idx'th block that is executed after @p RN. 174 static inline BasicBlock * 175 getRegionNodeSuccessor(RegionNode *RN, Instruction *TI, unsigned idx) { 176 if (RN->isSubRegion()) { 177 assert(idx == 0); 178 return RN->getNodeAs<Region>()->getExit(); 179 } 180 return TI->getSuccessor(idx); 181 } 182 183 static bool containsErrorBlock(RegionNode *RN, const Region &R, 184 ScopDetection *SD) { 185 if (!RN->isSubRegion()) 186 return SD->isErrorBlock(*RN->getNodeAs<BasicBlock>(), R); 187 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks()) 188 if (SD->isErrorBlock(*BB, R)) 189 return true; 190 return false; 191 } 192 193 ///} 194 195 /// Create a map to map from a given iteration to a subsequent iteration. 196 /// 197 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim 198 /// is incremented by one and all other dimensions are equal, e.g., 199 /// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3] 200 /// 201 /// if @p Dim is 2 and @p SetSpace has 4 dimensions. 202 static isl::map createNextIterationMap(isl::space SetSpace, unsigned Dim) { 203 isl::space MapSpace = SetSpace.map_from_set(); 204 isl::map NextIterationMap = isl::map::universe(MapSpace); 205 for (auto u : seq<isl_size>(0, NextIterationMap.domain_tuple_dim().release())) 206 if (u != (isl_size)Dim) 207 NextIterationMap = 208 NextIterationMap.equate(isl::dim::in, u, isl::dim::out, u); 209 isl::constraint C = 210 isl::constraint::alloc_equality(isl::local_space(MapSpace)); 211 C = C.set_constant_si(1); 212 C = C.set_coefficient_si(isl::dim::in, Dim, 1); 213 C = C.set_coefficient_si(isl::dim::out, Dim, -1); 214 NextIterationMap = NextIterationMap.add_constraint(C); 215 return NextIterationMap; 216 } 217 218 /// Add @p BSet to set @p BoundedParts if @p BSet is bounded. 219 static isl::set collectBoundedParts(isl::set S) { 220 isl::set BoundedParts = isl::set::empty(S.get_space()); 221 for (isl::basic_set BSet : S.get_basic_set_list()) 222 if (BSet.is_bounded()) 223 BoundedParts = BoundedParts.unite(isl::set(BSet)); 224 return BoundedParts; 225 } 226 227 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim. 228 /// 229 /// @returns A separation of @p S into first an unbounded then a bounded subset, 230 /// both with regards to the dimension @p Dim. 231 static std::pair<isl::set, isl::set> partitionSetParts(isl::set S, 232 unsigned Dim) { 233 for (unsigned u = 0, e = S.tuple_dim().release(); u < e; u++) 234 S = S.lower_bound_si(isl::dim::set, u, 0); 235 236 unsigned NumDimsS = S.tuple_dim().release(); 237 isl::set OnlyDimS = S; 238 239 // Remove dimensions that are greater than Dim as they are not interesting. 240 assert(NumDimsS >= Dim + 1); 241 OnlyDimS = OnlyDimS.project_out(isl::dim::set, Dim + 1, NumDimsS - Dim - 1); 242 243 // Create artificial parametric upper bounds for dimensions smaller than Dim 244 // as we are not interested in them. 245 OnlyDimS = OnlyDimS.insert_dims(isl::dim::param, 0, Dim); 246 247 for (unsigned u = 0; u < Dim; u++) { 248 isl::constraint C = isl::constraint::alloc_inequality( 249 isl::local_space(OnlyDimS.get_space())); 250 C = C.set_coefficient_si(isl::dim::param, u, 1); 251 C = C.set_coefficient_si(isl::dim::set, u, -1); 252 OnlyDimS = OnlyDimS.add_constraint(C); 253 } 254 255 // Collect all bounded parts of OnlyDimS. 256 isl::set BoundedParts = collectBoundedParts(OnlyDimS); 257 258 // Create the dimensions greater than Dim again. 259 BoundedParts = 260 BoundedParts.insert_dims(isl::dim::set, Dim + 1, NumDimsS - Dim - 1); 261 262 // Remove the artificial upper bound parameters again. 263 BoundedParts = BoundedParts.remove_dims(isl::dim::param, 0, Dim); 264 265 isl::set UnboundedParts = S.subtract(BoundedParts); 266 return std::make_pair(UnboundedParts, BoundedParts); 267 } 268 269 /// Create the conditions under which @p L @p Pred @p R is true. 270 static isl::set buildConditionSet(ICmpInst::Predicate Pred, isl::pw_aff L, 271 isl::pw_aff R) { 272 switch (Pred) { 273 case ICmpInst::ICMP_EQ: 274 return L.eq_set(R); 275 case ICmpInst::ICMP_NE: 276 return L.ne_set(R); 277 case ICmpInst::ICMP_SLT: 278 return L.lt_set(R); 279 case ICmpInst::ICMP_SLE: 280 return L.le_set(R); 281 case ICmpInst::ICMP_SGT: 282 return L.gt_set(R); 283 case ICmpInst::ICMP_SGE: 284 return L.ge_set(R); 285 case ICmpInst::ICMP_ULT: 286 return L.lt_set(R); 287 case ICmpInst::ICMP_UGT: 288 return L.gt_set(R); 289 case ICmpInst::ICMP_ULE: 290 return L.le_set(R); 291 case ICmpInst::ICMP_UGE: 292 return L.ge_set(R); 293 default: 294 llvm_unreachable("Non integer predicate not supported"); 295 } 296 } 297 298 isl::set ScopBuilder::adjustDomainDimensions(isl::set Dom, Loop *OldL, 299 Loop *NewL) { 300 // If the loops are the same there is nothing to do. 301 if (NewL == OldL) 302 return Dom; 303 304 int OldDepth = scop->getRelativeLoopDepth(OldL); 305 int NewDepth = scop->getRelativeLoopDepth(NewL); 306 // If both loops are non-affine loops there is nothing to do. 307 if (OldDepth == -1 && NewDepth == -1) 308 return Dom; 309 310 // Distinguish three cases: 311 // 1) The depth is the same but the loops are not. 312 // => One loop was left one was entered. 313 // 2) The depth increased from OldL to NewL. 314 // => One loop was entered, none was left. 315 // 3) The depth decreased from OldL to NewL. 316 // => Loops were left were difference of the depths defines how many. 317 if (OldDepth == NewDepth) { 318 assert(OldL->getParentLoop() == NewL->getParentLoop()); 319 Dom = Dom.project_out(isl::dim::set, NewDepth, 1); 320 Dom = Dom.add_dims(isl::dim::set, 1); 321 } else if (OldDepth < NewDepth) { 322 assert(OldDepth + 1 == NewDepth); 323 auto &R = scop->getRegion(); 324 (void)R; 325 assert(NewL->getParentLoop() == OldL || 326 ((!OldL || !R.contains(OldL)) && R.contains(NewL))); 327 Dom = Dom.add_dims(isl::dim::set, 1); 328 } else { 329 assert(OldDepth > NewDepth); 330 int Diff = OldDepth - NewDepth; 331 int NumDim = Dom.tuple_dim().release(); 332 assert(NumDim >= Diff); 333 Dom = Dom.project_out(isl::dim::set, NumDim - Diff, Diff); 334 } 335 336 return Dom; 337 } 338 339 /// Compute the isl representation for the SCEV @p E in this BB. 340 /// 341 /// @param BB The BB for which isl representation is to be 342 /// computed. 343 /// @param InvalidDomainMap A map of BB to their invalid domains. 344 /// @param E The SCEV that should be translated. 345 /// @param NonNegative Flag to indicate the @p E has to be non-negative. 346 /// 347 /// Note that this function will also adjust the invalid context accordingly. 348 349 __isl_give isl_pw_aff * 350 ScopBuilder::getPwAff(BasicBlock *BB, 351 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 352 const SCEV *E, bool NonNegative) { 353 PWACtx PWAC = scop->getPwAff(E, BB, NonNegative, &RecordedAssumptions); 354 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second); 355 return PWAC.first.release(); 356 } 357 358 /// Build condition sets for unsigned ICmpInst(s). 359 /// Special handling is required for unsigned operands to ensure that if 360 /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst 361 /// it should wrap around. 362 /// 363 /// @param IsStrictUpperBound holds information on the predicate relation 364 /// between TestVal and UpperBound, i.e, 365 /// TestVal < UpperBound OR TestVal <= UpperBound 366 __isl_give isl_set *ScopBuilder::buildUnsignedConditionSets( 367 BasicBlock *BB, Value *Condition, __isl_keep isl_set *Domain, 368 const SCEV *SCEV_TestVal, const SCEV *SCEV_UpperBound, 369 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 370 bool IsStrictUpperBound) { 371 // Do not take NonNeg assumption on TestVal 372 // as it might have MSB (Sign bit) set. 373 isl_pw_aff *TestVal = getPwAff(BB, InvalidDomainMap, SCEV_TestVal, false); 374 // Take NonNeg assumption on UpperBound. 375 isl_pw_aff *UpperBound = 376 getPwAff(BB, InvalidDomainMap, SCEV_UpperBound, true); 377 378 // 0 <= TestVal 379 isl_set *First = 380 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space( 381 isl_pw_aff_get_domain_space(TestVal))), 382 isl_pw_aff_copy(TestVal)); 383 384 isl_set *Second; 385 if (IsStrictUpperBound) 386 // TestVal < UpperBound 387 Second = isl_pw_aff_lt_set(TestVal, UpperBound); 388 else 389 // TestVal <= UpperBound 390 Second = isl_pw_aff_le_set(TestVal, UpperBound); 391 392 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second); 393 return ConsequenceCondSet; 394 } 395 396 bool ScopBuilder::buildConditionSets( 397 BasicBlock *BB, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain, 398 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 399 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 400 Value *Condition = getConditionFromTerminator(SI); 401 assert(Condition && "No condition for switch"); 402 403 isl_pw_aff *LHS, *RHS; 404 LHS = getPwAff(BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L)); 405 406 unsigned NumSuccessors = SI->getNumSuccessors(); 407 ConditionSets.resize(NumSuccessors); 408 for (auto &Case : SI->cases()) { 409 unsigned Idx = Case.getSuccessorIndex(); 410 ConstantInt *CaseValue = Case.getCaseValue(); 411 412 RHS = getPwAff(BB, InvalidDomainMap, SE.getSCEV(CaseValue)); 413 isl_set *CaseConditionSet = 414 buildConditionSet(ICmpInst::ICMP_EQ, isl::manage_copy(LHS), 415 isl::manage(RHS)) 416 .release(); 417 ConditionSets[Idx] = isl_set_coalesce( 418 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain))); 419 } 420 421 assert(ConditionSets[0] == nullptr && "Default condition set was set"); 422 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]); 423 for (unsigned u = 2; u < NumSuccessors; u++) 424 ConditionSetUnion = 425 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u])); 426 ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion); 427 428 isl_pw_aff_free(LHS); 429 430 return true; 431 } 432 433 bool ScopBuilder::buildConditionSets( 434 BasicBlock *BB, Value *Condition, Instruction *TI, Loop *L, 435 __isl_keep isl_set *Domain, 436 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 437 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 438 isl_set *ConsequenceCondSet = nullptr; 439 440 if (auto Load = dyn_cast<LoadInst>(Condition)) { 441 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L); 442 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType()); 443 bool NonNeg = false; 444 isl_pw_aff *LHS = getPwAff(BB, InvalidDomainMap, LHSSCEV, NonNeg); 445 isl_pw_aff *RHS = getPwAff(BB, InvalidDomainMap, RHSSCEV, NonNeg); 446 ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, isl::manage(LHS), 447 isl::manage(RHS)) 448 .release(); 449 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) { 450 auto *Unique = dyn_cast<ConstantInt>( 451 getUniqueNonErrorValue(PHI, &scop->getRegion(), &SD)); 452 assert(Unique && 453 "A PHINode condition should only be accepted by ScopDetection if " 454 "getUniqueNonErrorValue returns non-NULL"); 455 456 if (Unique->isZero()) 457 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 458 else 459 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 460 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) { 461 if (CCond->isZero()) 462 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 463 else 464 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 465 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 466 auto Opcode = BinOp->getOpcode(); 467 assert(Opcode == Instruction::And || Opcode == Instruction::Or); 468 469 bool Valid = buildConditionSets(BB, BinOp->getOperand(0), TI, L, Domain, 470 InvalidDomainMap, ConditionSets) && 471 buildConditionSets(BB, BinOp->getOperand(1), TI, L, Domain, 472 InvalidDomainMap, ConditionSets); 473 if (!Valid) { 474 while (!ConditionSets.empty()) 475 isl_set_free(ConditionSets.pop_back_val()); 476 return false; 477 } 478 479 isl_set_free(ConditionSets.pop_back_val()); 480 isl_set *ConsCondPart0 = ConditionSets.pop_back_val(); 481 isl_set_free(ConditionSets.pop_back_val()); 482 isl_set *ConsCondPart1 = ConditionSets.pop_back_val(); 483 484 if (Opcode == Instruction::And) 485 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1); 486 else 487 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1); 488 } else { 489 auto *ICond = dyn_cast<ICmpInst>(Condition); 490 assert(ICond && 491 "Condition of exiting branch was neither constant nor ICmp!"); 492 493 Region &R = scop->getRegion(); 494 495 isl_pw_aff *LHS, *RHS; 496 // For unsigned comparisons we assumed the signed bit of neither operand 497 // to be set. The comparison is equal to a signed comparison under this 498 // assumption. 499 bool NonNeg = ICond->isUnsigned(); 500 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L), 501 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L); 502 503 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, &SD); 504 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, &SD); 505 506 switch (ICond->getPredicate()) { 507 case ICmpInst::ICMP_ULT: 508 ConsequenceCondSet = 509 buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand, 510 RightOperand, InvalidDomainMap, true); 511 break; 512 case ICmpInst::ICMP_ULE: 513 ConsequenceCondSet = 514 buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand, 515 RightOperand, InvalidDomainMap, false); 516 break; 517 case ICmpInst::ICMP_UGT: 518 ConsequenceCondSet = 519 buildUnsignedConditionSets(BB, Condition, Domain, RightOperand, 520 LeftOperand, InvalidDomainMap, true); 521 break; 522 case ICmpInst::ICMP_UGE: 523 ConsequenceCondSet = 524 buildUnsignedConditionSets(BB, Condition, Domain, RightOperand, 525 LeftOperand, InvalidDomainMap, false); 526 break; 527 default: 528 LHS = getPwAff(BB, InvalidDomainMap, LeftOperand, NonNeg); 529 RHS = getPwAff(BB, InvalidDomainMap, RightOperand, NonNeg); 530 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), 531 isl::manage(LHS), isl::manage(RHS)) 532 .release(); 533 break; 534 } 535 } 536 537 // If no terminator was given we are only looking for parameter constraints 538 // under which @p Condition is true/false. 539 if (!TI) 540 ConsequenceCondSet = isl_set_params(ConsequenceCondSet); 541 assert(ConsequenceCondSet); 542 ConsequenceCondSet = isl_set_coalesce( 543 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))); 544 545 isl_set *AlternativeCondSet = nullptr; 546 bool TooComplex = 547 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain; 548 549 if (!TooComplex) { 550 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain), 551 isl_set_copy(ConsequenceCondSet)); 552 TooComplex = 553 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain; 554 } 555 556 if (TooComplex) { 557 scop->invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(), 558 TI ? TI->getParent() : nullptr /* BasicBlock */); 559 isl_set_free(AlternativeCondSet); 560 isl_set_free(ConsequenceCondSet); 561 return false; 562 } 563 564 ConditionSets.push_back(ConsequenceCondSet); 565 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet)); 566 567 return true; 568 } 569 570 bool ScopBuilder::buildConditionSets( 571 BasicBlock *BB, Instruction *TI, Loop *L, __isl_keep isl_set *Domain, 572 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 573 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 574 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) 575 return buildConditionSets(BB, SI, L, Domain, InvalidDomainMap, 576 ConditionSets); 577 578 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch."); 579 580 if (TI->getNumSuccessors() == 1) { 581 ConditionSets.push_back(isl_set_copy(Domain)); 582 return true; 583 } 584 585 Value *Condition = getConditionFromTerminator(TI); 586 assert(Condition && "No condition for Terminator"); 587 588 return buildConditionSets(BB, Condition, TI, L, Domain, InvalidDomainMap, 589 ConditionSets); 590 } 591 592 bool ScopBuilder::propagateDomainConstraints( 593 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 594 // Iterate over the region R and propagate the domain constrains from the 595 // predecessors to the current node. In contrast to the 596 // buildDomainsWithBranchConstraints function, this one will pull the domain 597 // information from the predecessors instead of pushing it to the successors. 598 // Additionally, we assume the domains to be already present in the domain 599 // map here. However, we iterate again in reverse post order so we know all 600 // predecessors have been visited before a block or non-affine subregion is 601 // visited. 602 603 ReversePostOrderTraversal<Region *> RTraversal(R); 604 for (auto *RN : RTraversal) { 605 // Recurse for affine subregions but go on for basic blocks and non-affine 606 // subregions. 607 if (RN->isSubRegion()) { 608 Region *SubRegion = RN->getNodeAs<Region>(); 609 if (!scop->isNonAffineSubRegion(SubRegion)) { 610 if (!propagateDomainConstraints(SubRegion, InvalidDomainMap)) 611 return false; 612 continue; 613 } 614 } 615 616 BasicBlock *BB = getRegionNodeBasicBlock(RN); 617 isl::set &Domain = scop->getOrInitEmptyDomain(BB); 618 assert(!Domain.is_null()); 619 620 // Under the union of all predecessor conditions we can reach this block. 621 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain); 622 Domain = Domain.intersect(PredDom).coalesce(); 623 Domain = Domain.align_params(scop->getParamSpace()); 624 625 Loop *BBLoop = getRegionNodeLoop(RN, LI); 626 if (BBLoop && BBLoop->getHeader() == BB && scop->contains(BBLoop)) 627 if (!addLoopBoundsToHeaderDomain(BBLoop, InvalidDomainMap)) 628 return false; 629 } 630 631 return true; 632 } 633 634 void ScopBuilder::propagateDomainConstraintsToRegionExit( 635 BasicBlock *BB, Loop *BBLoop, 636 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, 637 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 638 // Check if the block @p BB is the entry of a region. If so we propagate it's 639 // domain to the exit block of the region. Otherwise we are done. 640 auto *RI = scop->getRegion().getRegionInfo(); 641 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr; 642 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr; 643 if (!BBReg || BBReg->getEntry() != BB || !scop->contains(ExitBB)) 644 return; 645 646 // Do not propagate the domain if there is a loop backedge inside the region 647 // that would prevent the exit block from being executed. 648 auto *L = BBLoop; 649 while (L && scop->contains(L)) { 650 SmallVector<BasicBlock *, 4> LatchBBs; 651 BBLoop->getLoopLatches(LatchBBs); 652 for (auto *LatchBB : LatchBBs) 653 if (BB != LatchBB && BBReg->contains(LatchBB)) 654 return; 655 L = L->getParentLoop(); 656 } 657 658 isl::set Domain = scop->getOrInitEmptyDomain(BB); 659 assert(!Domain.is_null() && "Cannot propagate a nullptr"); 660 661 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, scop->getBoxedLoops()); 662 663 // Since the dimensions of @p BB and @p ExitBB might be different we have to 664 // adjust the domain before we can propagate it. 665 isl::set AdjustedDomain = adjustDomainDimensions(Domain, BBLoop, ExitBBLoop); 666 isl::set &ExitDomain = scop->getOrInitEmptyDomain(ExitBB); 667 668 // If the exit domain is not yet created we set it otherwise we "add" the 669 // current domain. 670 ExitDomain = 671 !ExitDomain.is_null() ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain; 672 673 // Initialize the invalid domain. 674 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space()); 675 676 FinishedExitBlocks.insert(ExitBB); 677 } 678 679 isl::set ScopBuilder::getPredecessorDomainConstraints(BasicBlock *BB, 680 isl::set Domain) { 681 // If @p BB is the ScopEntry we are done 682 if (scop->getRegion().getEntry() == BB) 683 return isl::set::universe(Domain.get_space()); 684 685 // The region info of this function. 686 auto &RI = *scop->getRegion().getRegionInfo(); 687 688 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, scop->getBoxedLoops()); 689 690 // A domain to collect all predecessor domains, thus all conditions under 691 // which the block is executed. To this end we start with the empty domain. 692 isl::set PredDom = isl::set::empty(Domain.get_space()); 693 694 // Set of regions of which the entry block domain has been propagated to BB. 695 // all predecessors inside any of the regions can be skipped. 696 SmallSet<Region *, 8> PropagatedRegions; 697 698 for (auto *PredBB : predecessors(BB)) { 699 // Skip backedges. 700 if (DT.dominates(BB, PredBB)) 701 continue; 702 703 // If the predecessor is in a region we used for propagation we can skip it. 704 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); }; 705 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(), 706 PredBBInRegion)) { 707 continue; 708 } 709 710 // Check if there is a valid region we can use for propagation, thus look 711 // for a region that contains the predecessor and has @p BB as exit block. 712 // FIXME: This was an side-effect-free (and possibly infinite) loop when 713 // committed and seems not to be needed. 714 auto *PredR = RI.getRegionFor(PredBB); 715 while (PredR->getExit() != BB && !PredR->contains(BB)) 716 PredR = PredR->getParent(); 717 718 // If a valid region for propagation was found use the entry of that region 719 // for propagation, otherwise the PredBB directly. 720 if (PredR->getExit() == BB) { 721 PredBB = PredR->getEntry(); 722 PropagatedRegions.insert(PredR); 723 } 724 725 isl::set PredBBDom = scop->getDomainConditions(PredBB); 726 Loop *PredBBLoop = 727 getFirstNonBoxedLoopFor(PredBB, LI, scop->getBoxedLoops()); 728 PredBBDom = adjustDomainDimensions(PredBBDom, PredBBLoop, BBLoop); 729 PredDom = PredDom.unite(PredBBDom); 730 } 731 732 return PredDom; 733 } 734 735 bool ScopBuilder::addLoopBoundsToHeaderDomain( 736 Loop *L, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 737 int LoopDepth = scop->getRelativeLoopDepth(L); 738 assert(LoopDepth >= 0 && "Loop in region should have at least depth one"); 739 740 BasicBlock *HeaderBB = L->getHeader(); 741 assert(scop->isDomainDefined(HeaderBB)); 742 isl::set &HeaderBBDom = scop->getOrInitEmptyDomain(HeaderBB); 743 744 isl::map NextIterationMap = 745 createNextIterationMap(HeaderBBDom.get_space(), LoopDepth); 746 747 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space()); 748 749 SmallVector<BasicBlock *, 4> LatchBlocks; 750 L->getLoopLatches(LatchBlocks); 751 752 for (BasicBlock *LatchBB : LatchBlocks) { 753 // If the latch is only reachable via error statements we skip it. 754 if (!scop->isDomainDefined(LatchBB)) 755 continue; 756 757 isl::set LatchBBDom = scop->getDomainConditions(LatchBB); 758 759 isl::set BackedgeCondition; 760 761 Instruction *TI = LatchBB->getTerminator(); 762 BranchInst *BI = dyn_cast<BranchInst>(TI); 763 assert(BI && "Only branch instructions allowed in loop latches"); 764 765 if (BI->isUnconditional()) 766 BackedgeCondition = LatchBBDom; 767 else { 768 SmallVector<isl_set *, 8> ConditionSets; 769 int idx = BI->getSuccessor(0) != HeaderBB; 770 if (!buildConditionSets(LatchBB, TI, L, LatchBBDom.get(), 771 InvalidDomainMap, ConditionSets)) 772 return false; 773 774 // Free the non back edge condition set as we do not need it. 775 isl_set_free(ConditionSets[1 - idx]); 776 777 BackedgeCondition = isl::manage(ConditionSets[idx]); 778 } 779 780 int LatchLoopDepth = scop->getRelativeLoopDepth(LI.getLoopFor(LatchBB)); 781 assert(LatchLoopDepth >= LoopDepth); 782 BackedgeCondition = BackedgeCondition.project_out( 783 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth); 784 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition); 785 } 786 787 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space()); 788 for (int i = 0; i < LoopDepth; i++) 789 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i); 790 791 isl::set UnionBackedgeConditionComplement = 792 UnionBackedgeCondition.complement(); 793 UnionBackedgeConditionComplement = 794 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth, 795 0); 796 UnionBackedgeConditionComplement = 797 UnionBackedgeConditionComplement.apply(ForwardMap); 798 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement); 799 HeaderBBDom = HeaderBBDom.apply(NextIterationMap); 800 801 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth); 802 HeaderBBDom = Parts.second; 803 804 // Check if there is a <nsw> tagged AddRec for this loop and if so do not 805 // require a runtime check. The assumption is already implied by the <nsw> 806 // tag. 807 bool RequiresRTC = !scop->hasNSWAddRecForLoop(L); 808 809 isl::set UnboundedCtx = Parts.first.params(); 810 recordAssumption(&RecordedAssumptions, INFINITELOOP, UnboundedCtx, 811 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION, 812 nullptr, RequiresRTC); 813 return true; 814 } 815 816 void ScopBuilder::buildInvariantEquivalenceClasses() { 817 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses; 818 819 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 820 for (LoadInst *LInst : RIL) { 821 const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand()); 822 823 Type *Ty = LInst->getType(); 824 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)]; 825 if (ClassRep) { 826 scop->addInvariantLoadMapping(LInst, ClassRep); 827 continue; 828 } 829 830 ClassRep = LInst; 831 scop->addInvariantEquivClass( 832 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), {}, Ty}); 833 } 834 } 835 836 bool ScopBuilder::buildDomains( 837 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 838 bool IsOnlyNonAffineRegion = scop->isNonAffineSubRegion(R); 839 auto *EntryBB = R->getEntry(); 840 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB); 841 int LD = scop->getRelativeLoopDepth(L); 842 auto *S = 843 isl_set_universe(isl_space_set_alloc(scop->getIslCtx().get(), 0, LD + 1)); 844 845 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S))); 846 isl::set Domain = isl::manage(S); 847 scop->setDomain(EntryBB, Domain); 848 849 if (IsOnlyNonAffineRegion) 850 return !containsErrorBlock(R->getNode(), *R, &SD); 851 852 if (!buildDomainsWithBranchConstraints(R, InvalidDomainMap)) 853 return false; 854 855 if (!propagateDomainConstraints(R, InvalidDomainMap)) 856 return false; 857 858 // Error blocks and blocks dominated by them have been assumed to never be 859 // executed. Representing them in the Scop does not add any value. In fact, 860 // it is likely to cause issues during construction of the ScopStmts. The 861 // contents of error blocks have not been verified to be expressible and 862 // will cause problems when building up a ScopStmt for them. 863 // Furthermore, basic blocks dominated by error blocks may reference 864 // instructions in the error block which, if the error block is not modeled, 865 // can themselves not be constructed properly. To this end we will replace 866 // the domains of error blocks and those only reachable via error blocks 867 // with an empty set. Additionally, we will record for each block under which 868 // parameter combination it would be reached via an error block in its 869 // InvalidDomain. This information is needed during load hoisting. 870 if (!propagateInvalidStmtDomains(R, InvalidDomainMap)) 871 return false; 872 873 return true; 874 } 875 876 bool ScopBuilder::buildDomainsWithBranchConstraints( 877 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 878 // To create the domain for each block in R we iterate over all blocks and 879 // subregions in R and propagate the conditions under which the current region 880 // element is executed. To this end we iterate in reverse post order over R as 881 // it ensures that we first visit all predecessors of a region node (either a 882 // basic block or a subregion) before we visit the region node itself. 883 // Initially, only the domain for the SCoP region entry block is set and from 884 // there we propagate the current domain to all successors, however we add the 885 // condition that the successor is actually executed next. 886 // As we are only interested in non-loop carried constraints here we can 887 // simply skip loop back edges. 888 889 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks; 890 ReversePostOrderTraversal<Region *> RTraversal(R); 891 for (auto *RN : RTraversal) { 892 // Recurse for affine subregions but go on for basic blocks and non-affine 893 // subregions. 894 if (RN->isSubRegion()) { 895 Region *SubRegion = RN->getNodeAs<Region>(); 896 if (!scop->isNonAffineSubRegion(SubRegion)) { 897 if (!buildDomainsWithBranchConstraints(SubRegion, InvalidDomainMap)) 898 return false; 899 continue; 900 } 901 } 902 903 if (containsErrorBlock(RN, scop->getRegion(), &SD)) 904 scop->notifyErrorBlock(); 905 ; 906 907 BasicBlock *BB = getRegionNodeBasicBlock(RN); 908 Instruction *TI = BB->getTerminator(); 909 910 if (isa<UnreachableInst>(TI)) 911 continue; 912 913 if (!scop->isDomainDefined(BB)) 914 continue; 915 isl::set Domain = scop->getDomainConditions(BB); 916 917 scop->updateMaxLoopDepth(Domain.tuple_dim().release()); 918 919 auto *BBLoop = getRegionNodeLoop(RN, LI); 920 // Propagate the domain from BB directly to blocks that have a superset 921 // domain, at the moment only region exit nodes of regions that start in BB. 922 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, 923 InvalidDomainMap); 924 925 // If all successors of BB have been set a domain through the propagation 926 // above we do not need to build condition sets but can just skip this 927 // block. However, it is important to note that this is a local property 928 // with regards to the region @p R. To this end FinishedExitBlocks is a 929 // local variable. 930 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) { 931 return FinishedExitBlocks.count(SuccBB); 932 }; 933 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit)) 934 continue; 935 936 // Build the condition sets for the successor nodes of the current region 937 // node. If it is a non-affine subregion we will always execute the single 938 // exit node, hence the single entry node domain is the condition set. For 939 // basic blocks we use the helper function buildConditionSets. 940 SmallVector<isl_set *, 8> ConditionSets; 941 if (RN->isSubRegion()) 942 ConditionSets.push_back(Domain.copy()); 943 else if (!buildConditionSets(BB, TI, BBLoop, Domain.get(), InvalidDomainMap, 944 ConditionSets)) 945 return false; 946 947 // Now iterate over the successors and set their initial domain based on 948 // their condition set. We skip back edges here and have to be careful when 949 // we leave a loop not to keep constraints over a dimension that doesn't 950 // exist anymore. 951 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size()); 952 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) { 953 isl::set CondSet = isl::manage(ConditionSets[u]); 954 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u); 955 956 // Skip blocks outside the region. 957 if (!scop->contains(SuccBB)) 958 continue; 959 960 // If we propagate the domain of some block to "SuccBB" we do not have to 961 // adjust the domain. 962 if (FinishedExitBlocks.count(SuccBB)) 963 continue; 964 965 // Skip back edges. 966 if (DT.dominates(SuccBB, BB)) 967 continue; 968 969 Loop *SuccBBLoop = 970 getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops()); 971 972 CondSet = adjustDomainDimensions(CondSet, BBLoop, SuccBBLoop); 973 974 // Set the domain for the successor or merge it with an existing domain in 975 // case there are multiple paths (without loop back edges) to the 976 // successor block. 977 isl::set &SuccDomain = scop->getOrInitEmptyDomain(SuccBB); 978 979 if (!SuccDomain.is_null()) { 980 SuccDomain = SuccDomain.unite(CondSet).coalesce(); 981 } else { 982 // Initialize the invalid domain. 983 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space()); 984 SuccDomain = CondSet; 985 } 986 987 SuccDomain = SuccDomain.detect_equalities(); 988 989 // Check if the maximal number of domain disjunctions was reached. 990 // In case this happens we will clean up and bail. 991 if (SuccDomain.n_basic_set().release() < MaxDisjunctsInDomain) 992 continue; 993 994 scop->invalidate(COMPLEXITY, DebugLoc()); 995 while (++u < ConditionSets.size()) 996 isl_set_free(ConditionSets[u]); 997 return false; 998 } 999 } 1000 1001 return true; 1002 } 1003 1004 bool ScopBuilder::propagateInvalidStmtDomains( 1005 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 1006 ReversePostOrderTraversal<Region *> RTraversal(R); 1007 for (auto *RN : RTraversal) { 1008 1009 // Recurse for affine subregions but go on for basic blocks and non-affine 1010 // subregions. 1011 if (RN->isSubRegion()) { 1012 Region *SubRegion = RN->getNodeAs<Region>(); 1013 if (!scop->isNonAffineSubRegion(SubRegion)) { 1014 propagateInvalidStmtDomains(SubRegion, InvalidDomainMap); 1015 continue; 1016 } 1017 } 1018 1019 bool ContainsErrorBlock = containsErrorBlock(RN, scop->getRegion(), &SD); 1020 BasicBlock *BB = getRegionNodeBasicBlock(RN); 1021 isl::set &Domain = scop->getOrInitEmptyDomain(BB); 1022 assert(!Domain.is_null() && "Cannot propagate a nullptr"); 1023 1024 isl::set InvalidDomain = InvalidDomainMap[BB]; 1025 1026 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain); 1027 1028 if (!IsInvalidBlock) { 1029 InvalidDomain = InvalidDomain.intersect(Domain); 1030 } else { 1031 InvalidDomain = Domain; 1032 isl::set DomPar = Domain.params(); 1033 recordAssumption(&RecordedAssumptions, ERRORBLOCK, DomPar, 1034 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION); 1035 Domain = isl::set::empty(Domain.get_space()); 1036 } 1037 1038 if (InvalidDomain.is_empty()) { 1039 InvalidDomainMap[BB] = InvalidDomain; 1040 continue; 1041 } 1042 1043 auto *BBLoop = getRegionNodeLoop(RN, LI); 1044 auto *TI = BB->getTerminator(); 1045 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors(); 1046 for (unsigned u = 0; u < NumSuccs; u++) { 1047 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u); 1048 1049 // Skip successors outside the SCoP. 1050 if (!scop->contains(SuccBB)) 1051 continue; 1052 1053 // Skip backedges. 1054 if (DT.dominates(SuccBB, BB)) 1055 continue; 1056 1057 Loop *SuccBBLoop = 1058 getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops()); 1059 1060 auto AdjustedInvalidDomain = 1061 adjustDomainDimensions(InvalidDomain, BBLoop, SuccBBLoop); 1062 1063 isl::set SuccInvalidDomain = InvalidDomainMap[SuccBB]; 1064 SuccInvalidDomain = SuccInvalidDomain.unite(AdjustedInvalidDomain); 1065 SuccInvalidDomain = SuccInvalidDomain.coalesce(); 1066 1067 InvalidDomainMap[SuccBB] = SuccInvalidDomain; 1068 1069 // Check if the maximal number of domain disjunctions was reached. 1070 // In case this happens we will bail. 1071 if (SuccInvalidDomain.n_basic_set().release() < MaxDisjunctsInDomain) 1072 continue; 1073 1074 InvalidDomainMap.erase(BB); 1075 scop->invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent()); 1076 return false; 1077 } 1078 1079 InvalidDomainMap[BB] = InvalidDomain; 1080 } 1081 1082 return true; 1083 } 1084 1085 void ScopBuilder::buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI, 1086 Region *NonAffineSubRegion, 1087 bool IsExitBlock) { 1088 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is 1089 // true, are not modeled as ordinary PHI nodes as they are not part of the 1090 // region. However, we model the operands in the predecessor blocks that are 1091 // part of the region as regular scalar accesses. 1092 1093 // If we can synthesize a PHI we can skip it, however only if it is in 1094 // the region. If it is not it can only be in the exit block of the region. 1095 // In this case we model the operands but not the PHI itself. 1096 auto *Scope = LI.getLoopFor(PHI->getParent()); 1097 if (!IsExitBlock && canSynthesize(PHI, *scop, &SE, Scope)) 1098 return; 1099 1100 // PHI nodes are modeled as if they had been demoted prior to the SCoP 1101 // detection. Hence, the PHI is a load of a new memory location in which the 1102 // incoming value was written at the end of the incoming basic block. 1103 bool OnlyNonAffineSubRegionOperands = true; 1104 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) { 1105 Value *Op = PHI->getIncomingValue(u); 1106 BasicBlock *OpBB = PHI->getIncomingBlock(u); 1107 ScopStmt *OpStmt = scop->getIncomingStmtFor(PHI->getOperandUse(u)); 1108 1109 // Do not build PHI dependences inside a non-affine subregion, but make 1110 // sure that the necessary scalar values are still made available. 1111 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) { 1112 auto *OpInst = dyn_cast<Instruction>(Op); 1113 if (!OpInst || !NonAffineSubRegion->contains(OpInst)) 1114 ensureValueRead(Op, OpStmt); 1115 continue; 1116 } 1117 1118 OnlyNonAffineSubRegionOperands = false; 1119 ensurePHIWrite(PHI, OpStmt, OpBB, Op, IsExitBlock); 1120 } 1121 1122 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) { 1123 addPHIReadAccess(PHIStmt, PHI); 1124 } 1125 } 1126 1127 void ScopBuilder::buildScalarDependences(ScopStmt *UserStmt, 1128 Instruction *Inst) { 1129 assert(!isa<PHINode>(Inst)); 1130 1131 // Pull-in required operands. 1132 for (Use &Op : Inst->operands()) 1133 ensureValueRead(Op.get(), UserStmt); 1134 } 1135 1136 // Create a sequence of two schedules. Either argument may be null and is 1137 // interpreted as the empty schedule. Can also return null if both schedules are 1138 // empty. 1139 static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) { 1140 if (Prev.is_null()) 1141 return Succ; 1142 if (Succ.is_null()) 1143 return Prev; 1144 1145 return Prev.sequence(Succ); 1146 } 1147 1148 // Create an isl_multi_union_aff that defines an identity mapping from the 1149 // elements of USet to their N-th dimension. 1150 // 1151 // # Example: 1152 // 1153 // Domain: { A[i,j]; B[i,j,k] } 1154 // N: 1 1155 // 1156 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] } 1157 // 1158 // @param USet A union set describing the elements for which to generate a 1159 // mapping. 1160 // @param N The dimension to map to. 1161 // @returns A mapping from USet to its N-th dimension. 1162 static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) { 1163 assert(N >= 0); 1164 assert(!USet.is_null()); 1165 assert(!USet.is_empty()); 1166 1167 auto Result = isl::union_pw_multi_aff::empty(USet.get_space()); 1168 1169 for (isl::set S : USet.get_set_list()) { 1170 int Dim = S.tuple_dim().release(); 1171 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set, 1172 N, Dim - N); 1173 if (N > 1) 1174 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1); 1175 1176 Result = Result.add_pw_multi_aff(PMA); 1177 } 1178 1179 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result)); 1180 } 1181 1182 void ScopBuilder::buildSchedule() { 1183 Loop *L = getLoopSurroundingScop(*scop, LI); 1184 LoopStackTy LoopStack({LoopStackElementTy(L, {}, 0)}); 1185 buildSchedule(scop->getRegion().getNode(), LoopStack); 1186 assert(LoopStack.size() == 1 && LoopStack.back().L == L); 1187 scop->setScheduleTree(LoopStack[0].Schedule); 1188 } 1189 1190 /// To generate a schedule for the elements in a Region we traverse the Region 1191 /// in reverse-post-order and add the contained RegionNodes in traversal order 1192 /// to the schedule of the loop that is currently at the top of the LoopStack. 1193 /// For loop-free codes, this results in a correct sequential ordering. 1194 /// 1195 /// Example: 1196 /// bb1(0) 1197 /// / \. 1198 /// bb2(1) bb3(2) 1199 /// \ / \. 1200 /// bb4(3) bb5(4) 1201 /// \ / 1202 /// bb6(5) 1203 /// 1204 /// Including loops requires additional processing. Whenever a loop header is 1205 /// encountered, the corresponding loop is added to the @p LoopStack. Starting 1206 /// from an empty schedule, we first process all RegionNodes that are within 1207 /// this loop and complete the sequential schedule at this loop-level before 1208 /// processing about any other nodes. To implement this 1209 /// loop-nodes-first-processing, the reverse post-order traversal is 1210 /// insufficient. Hence, we additionally check if the traversal yields 1211 /// sub-regions or blocks that are outside the last loop on the @p LoopStack. 1212 /// These region-nodes are then queue and only traverse after the all nodes 1213 /// within the current loop have been processed. 1214 void ScopBuilder::buildSchedule(Region *R, LoopStackTy &LoopStack) { 1215 Loop *OuterScopLoop = getLoopSurroundingScop(*scop, LI); 1216 1217 ReversePostOrderTraversal<Region *> RTraversal(R); 1218 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end()); 1219 std::deque<RegionNode *> DelayList; 1220 bool LastRNWaiting = false; 1221 1222 // Iterate over the region @p R in reverse post-order but queue 1223 // sub-regions/blocks iff they are not part of the last encountered but not 1224 // completely traversed loop. The variable LastRNWaiting is a flag to indicate 1225 // that we queued the last sub-region/block from the reverse post-order 1226 // iterator. If it is set we have to explore the next sub-region/block from 1227 // the iterator (if any) to guarantee progress. If it is not set we first try 1228 // the next queued sub-region/blocks. 1229 while (!WorkList.empty() || !DelayList.empty()) { 1230 RegionNode *RN; 1231 1232 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) { 1233 RN = WorkList.front(); 1234 WorkList.pop_front(); 1235 LastRNWaiting = false; 1236 } else { 1237 RN = DelayList.front(); 1238 DelayList.pop_front(); 1239 } 1240 1241 Loop *L = getRegionNodeLoop(RN, LI); 1242 if (!scop->contains(L)) 1243 L = OuterScopLoop; 1244 1245 Loop *LastLoop = LoopStack.back().L; 1246 if (LastLoop != L) { 1247 if (LastLoop && !LastLoop->contains(L)) { 1248 LastRNWaiting = true; 1249 DelayList.push_back(RN); 1250 continue; 1251 } 1252 LoopStack.push_back({L, {}, 0}); 1253 } 1254 buildSchedule(RN, LoopStack); 1255 } 1256 } 1257 1258 void ScopBuilder::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack) { 1259 if (RN->isSubRegion()) { 1260 auto *LocalRegion = RN->getNodeAs<Region>(); 1261 if (!scop->isNonAffineSubRegion(LocalRegion)) { 1262 buildSchedule(LocalRegion, LoopStack); 1263 return; 1264 } 1265 } 1266 1267 assert(LoopStack.rbegin() != LoopStack.rend()); 1268 auto LoopData = LoopStack.rbegin(); 1269 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN); 1270 1271 for (auto *Stmt : scop->getStmtListFor(RN)) { 1272 isl::union_set UDomain{Stmt->getDomain()}; 1273 auto StmtSchedule = isl::schedule::from_domain(UDomain); 1274 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule); 1275 } 1276 1277 // Check if we just processed the last node in this loop. If we did, finalize 1278 // the loop by: 1279 // 1280 // - adding new schedule dimensions 1281 // - folding the resulting schedule into the parent loop schedule 1282 // - dropping the loop schedule from the LoopStack. 1283 // 1284 // Then continue to check surrounding loops, which might also have been 1285 // completed by this node. 1286 size_t Dimension = LoopStack.size(); 1287 while (LoopData->L && 1288 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) { 1289 isl::schedule Schedule = LoopData->Schedule; 1290 auto NumBlocksProcessed = LoopData->NumBlocksProcessed; 1291 1292 assert(std::next(LoopData) != LoopStack.rend()); 1293 Loop *L = LoopData->L; 1294 ++LoopData; 1295 --Dimension; 1296 1297 if (!Schedule.is_null()) { 1298 isl::union_set Domain = Schedule.get_domain(); 1299 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension); 1300 Schedule = Schedule.insert_partial_schedule(MUPA); 1301 1302 if (hasDisableAllTransformsHint(L)) { 1303 /// If any of the loops has a disable_nonforced heuristic, mark the 1304 /// entire SCoP as such. The ISL rescheduler can only reschedule the 1305 /// SCoP in its entirety. 1306 /// TODO: ScopDetection could avoid including such loops or warp them as 1307 /// boxed loop. It still needs to pass-through loop with user-defined 1308 /// metadata. 1309 scop->markDisableHeuristics(); 1310 } 1311 1312 // It is easier to insert the marks here that do it retroactively. 1313 isl::id IslLoopId = createIslLoopAttr(scop->getIslCtx(), L); 1314 if (!IslLoopId.is_null()) 1315 Schedule = 1316 Schedule.get_root().child(0).insert_mark(IslLoopId).get_schedule(); 1317 1318 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule); 1319 } 1320 1321 LoopData->NumBlocksProcessed += NumBlocksProcessed; 1322 } 1323 // Now pop all loops processed up there from the LoopStack 1324 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end()); 1325 } 1326 1327 void ScopBuilder::buildEscapingDependences(Instruction *Inst) { 1328 // Check for uses of this instruction outside the scop. Because we do not 1329 // iterate over such instructions and therefore did not "ensure" the existence 1330 // of a write, we must determine such use here. 1331 if (scop->isEscaping(Inst)) 1332 ensureValueWrite(Inst); 1333 } 1334 1335 /// Check that a value is a Fortran Array descriptor. 1336 /// 1337 /// We check if V has the following structure: 1338 /// %"struct.array1_real(kind=8)" = type { i8*, i<zz>, i<zz>, 1339 /// [<num> x %struct.descriptor_dimension] } 1340 /// 1341 /// 1342 /// %struct.descriptor_dimension = type { i<zz>, i<zz>, i<zz> } 1343 /// 1344 /// 1. V's type name starts with "struct.array" 1345 /// 2. V's type has layout as shown. 1346 /// 3. Final member of V's type has name "struct.descriptor_dimension", 1347 /// 4. "struct.descriptor_dimension" has layout as shown. 1348 /// 5. Consistent use of i<zz> where <zz> is some fixed integer number. 1349 /// 1350 /// We are interested in such types since this is the code that dragonegg 1351 /// generates for Fortran array descriptors. 1352 /// 1353 /// @param V the Value to be checked. 1354 /// 1355 /// @returns True if V is a Fortran array descriptor, False otherwise. 1356 bool isFortranArrayDescriptor(Value *V) { 1357 PointerType *PTy = dyn_cast<PointerType>(V->getType()); 1358 1359 if (!PTy) 1360 return false; 1361 1362 Type *Ty = PTy->getElementType(); 1363 assert(Ty && "Ty expected to be initialized"); 1364 auto *StructArrTy = dyn_cast<StructType>(Ty); 1365 1366 if (!(StructArrTy && StructArrTy->hasName())) 1367 return false; 1368 1369 if (!StructArrTy->getName().startswith("struct.array")) 1370 return false; 1371 1372 if (StructArrTy->getNumElements() != 4) 1373 return false; 1374 1375 const ArrayRef<Type *> ArrMemberTys = StructArrTy->elements(); 1376 1377 // i8* match 1378 if (ArrMemberTys[0] != Type::getInt8PtrTy(V->getContext())) 1379 return false; 1380 1381 // Get a reference to the int type and check that all the members 1382 // share the same int type 1383 Type *IntTy = ArrMemberTys[1]; 1384 if (ArrMemberTys[2] != IntTy) 1385 return false; 1386 1387 // type: [<num> x %struct.descriptor_dimension] 1388 ArrayType *DescriptorDimArrayTy = dyn_cast<ArrayType>(ArrMemberTys[3]); 1389 if (!DescriptorDimArrayTy) 1390 return false; 1391 1392 // type: %struct.descriptor_dimension := type { ixx, ixx, ixx } 1393 StructType *DescriptorDimTy = 1394 dyn_cast<StructType>(DescriptorDimArrayTy->getElementType()); 1395 1396 if (!(DescriptorDimTy && DescriptorDimTy->hasName())) 1397 return false; 1398 1399 if (DescriptorDimTy->getName() != "struct.descriptor_dimension") 1400 return false; 1401 1402 if (DescriptorDimTy->getNumElements() != 3) 1403 return false; 1404 1405 for (auto MemberTy : DescriptorDimTy->elements()) { 1406 if (MemberTy != IntTy) 1407 return false; 1408 } 1409 1410 return true; 1411 } 1412 1413 Value *ScopBuilder::findFADAllocationVisible(MemAccInst Inst) { 1414 // match: 4.1 & 4.2 store/load 1415 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst)) 1416 return nullptr; 1417 1418 // match: 4 1419 if (Inst.getAlignment() != 8) 1420 return nullptr; 1421 1422 Value *Address = Inst.getPointerOperand(); 1423 1424 const BitCastInst *Bitcast = nullptr; 1425 // [match: 3] 1426 if (auto *Slot = dyn_cast<GetElementPtrInst>(Address)) { 1427 Value *TypedMem = Slot->getPointerOperand(); 1428 // match: 2 1429 Bitcast = dyn_cast<BitCastInst>(TypedMem); 1430 } else { 1431 // match: 2 1432 Bitcast = dyn_cast<BitCastInst>(Address); 1433 } 1434 1435 if (!Bitcast) 1436 return nullptr; 1437 1438 auto *MallocMem = Bitcast->getOperand(0); 1439 1440 // match: 1 1441 auto *MallocCall = dyn_cast<CallInst>(MallocMem); 1442 if (!MallocCall) 1443 return nullptr; 1444 1445 Function *MallocFn = MallocCall->getCalledFunction(); 1446 if (!(MallocFn && MallocFn->hasName() && MallocFn->getName() == "malloc")) 1447 return nullptr; 1448 1449 // Find all uses the malloc'd memory. 1450 // We are looking for a "store" into a struct with the type being the Fortran 1451 // descriptor type 1452 for (auto user : MallocMem->users()) { 1453 /// match: 5 1454 auto *MallocStore = dyn_cast<StoreInst>(user); 1455 if (!MallocStore) 1456 continue; 1457 1458 auto *DescriptorGEP = 1459 dyn_cast<GEPOperator>(MallocStore->getPointerOperand()); 1460 if (!DescriptorGEP) 1461 continue; 1462 1463 // match: 5 1464 auto DescriptorType = 1465 dyn_cast<StructType>(DescriptorGEP->getSourceElementType()); 1466 if (!(DescriptorType && DescriptorType->hasName())) 1467 continue; 1468 1469 Value *Descriptor = dyn_cast<Value>(DescriptorGEP->getPointerOperand()); 1470 1471 if (!Descriptor) 1472 continue; 1473 1474 if (!isFortranArrayDescriptor(Descriptor)) 1475 continue; 1476 1477 return Descriptor; 1478 } 1479 1480 return nullptr; 1481 } 1482 1483 Value *ScopBuilder::findFADAllocationInvisible(MemAccInst Inst) { 1484 // match: 3 1485 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst)) 1486 return nullptr; 1487 1488 Value *Slot = Inst.getPointerOperand(); 1489 1490 LoadInst *MemLoad = nullptr; 1491 // [match: 2] 1492 if (auto *SlotGEP = dyn_cast<GetElementPtrInst>(Slot)) { 1493 // match: 1 1494 MemLoad = dyn_cast<LoadInst>(SlotGEP->getPointerOperand()); 1495 } else { 1496 // match: 1 1497 MemLoad = dyn_cast<LoadInst>(Slot); 1498 } 1499 1500 if (!MemLoad) 1501 return nullptr; 1502 1503 auto *BitcastOperator = 1504 dyn_cast<BitCastOperator>(MemLoad->getPointerOperand()); 1505 if (!BitcastOperator) 1506 return nullptr; 1507 1508 Value *Descriptor = dyn_cast<Value>(BitcastOperator->getOperand(0)); 1509 if (!Descriptor) 1510 return nullptr; 1511 1512 if (!isFortranArrayDescriptor(Descriptor)) 1513 return nullptr; 1514 1515 return Descriptor; 1516 } 1517 1518 void ScopBuilder::addRecordedAssumptions() { 1519 for (auto &AS : llvm::reverse(RecordedAssumptions)) { 1520 1521 if (!AS.BB) { 1522 scop->addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, 1523 nullptr /* BasicBlock */, AS.RequiresRTC); 1524 continue; 1525 } 1526 1527 // If the domain was deleted the assumptions are void. 1528 isl_set *Dom = scop->getDomainConditions(AS.BB).release(); 1529 if (!Dom) 1530 continue; 1531 1532 // If a basic block was given use its domain to simplify the assumption. 1533 // In case of restrictions we know they only have to hold on the domain, 1534 // thus we can intersect them with the domain of the block. However, for 1535 // assumptions the domain has to imply them, thus: 1536 // _ _____ 1537 // Dom => S <==> A v B <==> A - B 1538 // 1539 // To avoid the complement we will register A - B as a restriction not an 1540 // assumption. 1541 isl_set *S = AS.Set.copy(); 1542 if (AS.Sign == AS_RESTRICTION) 1543 S = isl_set_params(isl_set_intersect(S, Dom)); 1544 else /* (AS.Sign == AS_ASSUMPTION) */ 1545 S = isl_set_params(isl_set_subtract(Dom, S)); 1546 1547 scop->addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB, 1548 AS.RequiresRTC); 1549 } 1550 } 1551 1552 void ScopBuilder::addUserAssumptions( 1553 AssumptionCache &AC, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 1554 for (auto &Assumption : AC.assumptions()) { 1555 auto *CI = dyn_cast_or_null<CallInst>(Assumption); 1556 if (!CI || CI->getNumArgOperands() != 1) 1557 continue; 1558 1559 bool InScop = scop->contains(CI); 1560 if (!InScop && !scop->isDominatedBy(DT, CI->getParent())) 1561 continue; 1562 1563 auto *L = LI.getLoopFor(CI->getParent()); 1564 auto *Val = CI->getArgOperand(0); 1565 ParameterSetTy DetectedParams; 1566 auto &R = scop->getRegion(); 1567 if (!isAffineConstraint(Val, &R, L, SE, DetectedParams)) { 1568 ORE.emit( 1569 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI) 1570 << "Non-affine user assumption ignored."); 1571 continue; 1572 } 1573 1574 // Collect all newly introduced parameters. 1575 ParameterSetTy NewParams; 1576 for (auto *Param : DetectedParams) { 1577 Param = extractConstantFactor(Param, SE).second; 1578 Param = scop->getRepresentingInvariantLoadSCEV(Param); 1579 if (scop->isParam(Param)) 1580 continue; 1581 NewParams.insert(Param); 1582 } 1583 1584 SmallVector<isl_set *, 2> ConditionSets; 1585 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr; 1586 BasicBlock *BB = InScop ? CI->getParent() : R.getEntry(); 1587 auto *Dom = InScop ? isl_set_copy(scop->getDomainConditions(BB).get()) 1588 : isl_set_copy(scop->getContext().get()); 1589 assert(Dom && "Cannot propagate a nullptr."); 1590 bool Valid = buildConditionSets(BB, Val, TI, L, Dom, InvalidDomainMap, 1591 ConditionSets); 1592 isl_set_free(Dom); 1593 1594 if (!Valid) 1595 continue; 1596 1597 isl_set *AssumptionCtx = nullptr; 1598 if (InScop) { 1599 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1])); 1600 isl_set_free(ConditionSets[0]); 1601 } else { 1602 AssumptionCtx = isl_set_complement(ConditionSets[1]); 1603 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]); 1604 } 1605 1606 // Project out newly introduced parameters as they are not otherwise useful. 1607 if (!NewParams.empty()) { 1608 for (isl_size u = 0; u < isl_set_n_param(AssumptionCtx); u++) { 1609 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u); 1610 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id)); 1611 isl_id_free(Id); 1612 1613 if (!NewParams.count(Param)) 1614 continue; 1615 1616 AssumptionCtx = 1617 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1); 1618 } 1619 } 1620 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI) 1621 << "Use user assumption: " 1622 << stringFromIslObj(AssumptionCtx, "null")); 1623 isl::set newContext = 1624 scop->getContext().intersect(isl::manage(AssumptionCtx)); 1625 scop->setContext(newContext); 1626 } 1627 } 1628 1629 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt) { 1630 Value *Val = Inst.getValueOperand(); 1631 Type *ElementType = Val->getType(); 1632 Value *Address = Inst.getPointerOperand(); 1633 const SCEV *AccessFunction = 1634 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1635 const SCEVUnknown *BasePointer = 1636 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1637 enum MemoryAccess::AccessType AccType = 1638 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1639 1640 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) { 1641 auto *Src = BitCast->getOperand(0); 1642 auto *SrcTy = Src->getType(); 1643 auto *DstTy = BitCast->getType(); 1644 // Do not try to delinearize non-sized (opaque) pointers. 1645 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) || 1646 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) { 1647 return false; 1648 } 1649 if (SrcTy->isPointerTy() && DstTy->isPointerTy() && 1650 DL.getTypeAllocSize(SrcTy->getPointerElementType()) == 1651 DL.getTypeAllocSize(DstTy->getPointerElementType())) 1652 Address = Src; 1653 } 1654 1655 auto *GEP = dyn_cast<GetElementPtrInst>(Address); 1656 if (!GEP) 1657 return false; 1658 1659 SmallVector<const SCEV *, 4> Subscripts; 1660 SmallVector<int, 4> Sizes; 1661 SE.getIndexExpressionsFromGEP(GEP, Subscripts, Sizes); 1662 auto *BasePtr = GEP->getOperand(0); 1663 1664 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr)) 1665 BasePtr = BasePtrCast->getOperand(0); 1666 1667 // Check for identical base pointers to ensure that we do not miss index 1668 // offsets that have been added before this GEP is applied. 1669 if (BasePtr != BasePointer->getValue()) 1670 return false; 1671 1672 std::vector<const SCEV *> SizesSCEV; 1673 1674 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1675 1676 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1677 for (auto *Subscript : Subscripts) { 1678 InvariantLoadsSetTy AccessILS; 1679 if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE, 1680 &AccessILS)) 1681 return false; 1682 1683 for (LoadInst *LInst : AccessILS) 1684 if (!ScopRIL.count(LInst)) 1685 return false; 1686 } 1687 1688 if (Sizes.empty()) 1689 return false; 1690 1691 SizesSCEV.push_back(nullptr); 1692 1693 for (auto V : Sizes) 1694 SizesSCEV.push_back(SE.getSCEV( 1695 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V))); 1696 1697 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1698 true, Subscripts, SizesSCEV, Val); 1699 return true; 1700 } 1701 1702 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt) { 1703 if (!PollyDelinearize) 1704 return false; 1705 1706 Value *Address = Inst.getPointerOperand(); 1707 Value *Val = Inst.getValueOperand(); 1708 Type *ElementType = Val->getType(); 1709 unsigned ElementSize = DL.getTypeAllocSize(ElementType); 1710 enum MemoryAccess::AccessType AccType = 1711 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1712 1713 const SCEV *AccessFunction = 1714 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1715 const SCEVUnknown *BasePointer = 1716 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1717 1718 assert(BasePointer && "Could not find base pointer"); 1719 1720 auto &InsnToMemAcc = scop->getInsnToMemAccMap(); 1721 auto AccItr = InsnToMemAcc.find(Inst); 1722 if (AccItr == InsnToMemAcc.end()) 1723 return false; 1724 1725 std::vector<const SCEV *> Sizes = {nullptr}; 1726 1727 Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(), 1728 AccItr->second.Shape->DelinearizedSizes.end()); 1729 1730 // In case only the element size is contained in the 'Sizes' array, the 1731 // access does not access a real multi-dimensional array. Hence, we allow 1732 // the normal single-dimensional access construction to handle this. 1733 if (Sizes.size() == 1) 1734 return false; 1735 1736 // Remove the element size. This information is already provided by the 1737 // ElementSize parameter. In case the element size of this access and the 1738 // element size used for delinearization differs the delinearization is 1739 // incorrect. Hence, we invalidate the scop. 1740 // 1741 // TODO: Handle delinearization with differing element sizes. 1742 auto DelinearizedSize = 1743 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue(); 1744 Sizes.pop_back(); 1745 if (ElementSize != DelinearizedSize) 1746 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc(), Inst->getParent()); 1747 1748 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1749 true, AccItr->second.DelinearizedSubscripts, Sizes, Val); 1750 return true; 1751 } 1752 1753 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt) { 1754 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst); 1755 1756 if (MemIntr == nullptr) 1757 return false; 1758 1759 auto *L = LI.getLoopFor(Inst->getParent()); 1760 auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L); 1761 assert(LengthVal); 1762 1763 // Check if the length val is actually affine or if we overapproximate it 1764 InvariantLoadsSetTy AccessILS; 1765 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1766 1767 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1768 bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop, 1769 LengthVal, SE, &AccessILS); 1770 for (LoadInst *LInst : AccessILS) 1771 if (!ScopRIL.count(LInst)) 1772 LengthIsAffine = false; 1773 if (!LengthIsAffine) 1774 LengthVal = nullptr; 1775 1776 auto *DestPtrVal = MemIntr->getDest(); 1777 assert(DestPtrVal); 1778 1779 auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L); 1780 assert(DestAccFunc); 1781 // Ignore accesses to "NULL". 1782 // TODO: We could use this to optimize the region further, e.g., intersect 1783 // the context with 1784 // isl_set_complement(isl_set_params(getDomain())) 1785 // as we know it would be undefined to execute this instruction anyway. 1786 if (DestAccFunc->isZero()) 1787 return true; 1788 1789 if (auto *U = dyn_cast<SCEVUnknown>(DestAccFunc)) { 1790 if (isa<ConstantPointerNull>(U->getValue())) 1791 return true; 1792 } 1793 1794 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc)); 1795 assert(DestPtrSCEV); 1796 DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV); 1797 addArrayAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(), 1798 IntegerType::getInt8Ty(DestPtrVal->getContext()), 1799 LengthIsAffine, {DestAccFunc, LengthVal}, {nullptr}, 1800 Inst.getValueOperand()); 1801 1802 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr); 1803 if (!MemTrans) 1804 return true; 1805 1806 auto *SrcPtrVal = MemTrans->getSource(); 1807 assert(SrcPtrVal); 1808 1809 auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L); 1810 assert(SrcAccFunc); 1811 // Ignore accesses to "NULL". 1812 // TODO: See above TODO 1813 if (SrcAccFunc->isZero()) 1814 return true; 1815 1816 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc)); 1817 assert(SrcPtrSCEV); 1818 SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV); 1819 addArrayAccess(Stmt, Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(), 1820 IntegerType::getInt8Ty(SrcPtrVal->getContext()), 1821 LengthIsAffine, {SrcAccFunc, LengthVal}, {nullptr}, 1822 Inst.getValueOperand()); 1823 1824 return true; 1825 } 1826 1827 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt) { 1828 auto *CI = dyn_cast_or_null<CallInst>(Inst); 1829 1830 if (CI == nullptr) 1831 return false; 1832 1833 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI) || isDebugCall(CI)) 1834 return true; 1835 1836 bool ReadOnly = false; 1837 auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0); 1838 auto *CalledFunction = CI->getCalledFunction(); 1839 switch (AA.getModRefBehavior(CalledFunction)) { 1840 case FMRB_UnknownModRefBehavior: 1841 llvm_unreachable("Unknown mod ref behaviour cannot be represented."); 1842 case FMRB_DoesNotAccessMemory: 1843 return true; 1844 case FMRB_OnlyWritesMemory: 1845 case FMRB_OnlyWritesInaccessibleMem: 1846 case FMRB_OnlyWritesInaccessibleOrArgMem: 1847 case FMRB_OnlyAccessesInaccessibleMem: 1848 case FMRB_OnlyAccessesInaccessibleOrArgMem: 1849 return false; 1850 case FMRB_OnlyReadsMemory: 1851 case FMRB_OnlyReadsInaccessibleMem: 1852 case FMRB_OnlyReadsInaccessibleOrArgMem: 1853 GlobalReads.emplace_back(Stmt, CI); 1854 return true; 1855 case FMRB_OnlyReadsArgumentPointees: 1856 ReadOnly = true; 1857 LLVM_FALLTHROUGH; 1858 case FMRB_OnlyWritesArgumentPointees: 1859 case FMRB_OnlyAccessesArgumentPointees: { 1860 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE; 1861 Loop *L = LI.getLoopFor(Inst->getParent()); 1862 for (const auto &Arg : CI->arg_operands()) { 1863 if (!Arg->getType()->isPointerTy()) 1864 continue; 1865 1866 auto *ArgSCEV = SE.getSCEVAtScope(Arg, L); 1867 if (ArgSCEV->isZero()) 1868 continue; 1869 1870 if (auto *U = dyn_cast<SCEVUnknown>(ArgSCEV)) { 1871 if (isa<ConstantPointerNull>(U->getValue())) 1872 return true; 1873 } 1874 1875 auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV)); 1876 addArrayAccess(Stmt, Inst, AccType, ArgBasePtr->getValue(), 1877 ArgBasePtr->getType(), false, {AF}, {nullptr}, CI); 1878 } 1879 return true; 1880 } 1881 } 1882 1883 return true; 1884 } 1885 1886 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt) { 1887 Value *Address = Inst.getPointerOperand(); 1888 Value *Val = Inst.getValueOperand(); 1889 Type *ElementType = Val->getType(); 1890 enum MemoryAccess::AccessType AccType = 1891 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1892 1893 const SCEV *AccessFunction = 1894 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1895 const SCEVUnknown *BasePointer = 1896 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1897 1898 assert(BasePointer && "Could not find base pointer"); 1899 AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer); 1900 1901 // Check if the access depends on a loop contained in a non-affine subregion. 1902 bool isVariantInNonAffineLoop = false; 1903 SetVector<const Loop *> Loops; 1904 findLoops(AccessFunction, Loops); 1905 for (const Loop *L : Loops) 1906 if (Stmt->contains(L)) { 1907 isVariantInNonAffineLoop = true; 1908 break; 1909 } 1910 1911 InvariantLoadsSetTy AccessILS; 1912 1913 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1914 bool IsAffine = !isVariantInNonAffineLoop && 1915 isAffineExpr(&scop->getRegion(), SurroundingLoop, 1916 AccessFunction, SE, &AccessILS); 1917 1918 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1919 for (LoadInst *LInst : AccessILS) 1920 if (!ScopRIL.count(LInst)) 1921 IsAffine = false; 1922 1923 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE) 1924 AccType = MemoryAccess::MAY_WRITE; 1925 1926 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1927 IsAffine, {AccessFunction}, {nullptr}, Val); 1928 } 1929 1930 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt) { 1931 if (buildAccessMemIntrinsic(Inst, Stmt)) 1932 return; 1933 1934 if (buildAccessCallInst(Inst, Stmt)) 1935 return; 1936 1937 if (buildAccessMultiDimFixed(Inst, Stmt)) 1938 return; 1939 1940 if (buildAccessMultiDimParam(Inst, Stmt)) 1941 return; 1942 1943 buildAccessSingleDim(Inst, Stmt); 1944 } 1945 1946 void ScopBuilder::buildAccessFunctions() { 1947 for (auto &Stmt : *scop) { 1948 if (Stmt.isBlockStmt()) { 1949 buildAccessFunctions(&Stmt, *Stmt.getBasicBlock()); 1950 continue; 1951 } 1952 1953 Region *R = Stmt.getRegion(); 1954 for (BasicBlock *BB : R->blocks()) 1955 buildAccessFunctions(&Stmt, *BB, R); 1956 } 1957 1958 // Build write accesses for values that are used after the SCoP. 1959 // The instructions defining them might be synthesizable and therefore not 1960 // contained in any statement, hence we iterate over the original instructions 1961 // to identify all escaping values. 1962 for (BasicBlock *BB : scop->getRegion().blocks()) { 1963 for (Instruction &Inst : *BB) 1964 buildEscapingDependences(&Inst); 1965 } 1966 } 1967 1968 bool ScopBuilder::shouldModelInst(Instruction *Inst, Loop *L) { 1969 return !Inst->isTerminator() && !isIgnoredIntrinsic(Inst) && 1970 !canSynthesize(Inst, *scop, &SE, L); 1971 } 1972 1973 /// Generate a name for a statement. 1974 /// 1975 /// @param BB The basic block the statement will represent. 1976 /// @param BBIdx The index of the @p BB relative to other BBs/regions. 1977 /// @param Count The index of the created statement in @p BB. 1978 /// @param IsMain Whether this is the main of all statement for @p BB. If true, 1979 /// no suffix will be added. 1980 /// @param IsLast Uses a special indicator for the last statement of a BB. 1981 static std::string makeStmtName(BasicBlock *BB, long BBIdx, int Count, 1982 bool IsMain, bool IsLast = false) { 1983 std::string Suffix; 1984 if (!IsMain) { 1985 if (UseInstructionNames) 1986 Suffix = '_'; 1987 if (IsLast) 1988 Suffix += "last"; 1989 else if (Count < 26) 1990 Suffix += 'a' + Count; 1991 else 1992 Suffix += std::to_string(Count); 1993 } 1994 return getIslCompatibleName("Stmt", BB, BBIdx, Suffix, UseInstructionNames); 1995 } 1996 1997 /// Generate a name for a statement that represents a non-affine subregion. 1998 /// 1999 /// @param R The region the statement will represent. 2000 /// @param RIdx The index of the @p R relative to other BBs/regions. 2001 static std::string makeStmtName(Region *R, long RIdx) { 2002 return getIslCompatibleName("Stmt", R->getNameStr(), RIdx, "", 2003 UseInstructionNames); 2004 } 2005 2006 void ScopBuilder::buildSequentialBlockStmts(BasicBlock *BB, bool SplitOnStore) { 2007 Loop *SurroundingLoop = LI.getLoopFor(BB); 2008 2009 int Count = 0; 2010 long BBIdx = scop->getNextStmtIdx(); 2011 std::vector<Instruction *> Instructions; 2012 for (Instruction &Inst : *BB) { 2013 if (shouldModelInst(&Inst, SurroundingLoop)) 2014 Instructions.push_back(&Inst); 2015 if (Inst.getMetadata("polly_split_after") || 2016 (SplitOnStore && isa<StoreInst>(Inst))) { 2017 std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0); 2018 scop->addScopStmt(BB, Name, SurroundingLoop, Instructions); 2019 Count++; 2020 Instructions.clear(); 2021 } 2022 } 2023 2024 std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0); 2025 scop->addScopStmt(BB, Name, SurroundingLoop, Instructions); 2026 } 2027 2028 /// Is @p Inst an ordered instruction? 2029 /// 2030 /// An unordered instruction is an instruction, such that a sequence of 2031 /// unordered instructions can be permuted without changing semantics. Any 2032 /// instruction for which this is not always the case is ordered. 2033 static bool isOrderedInstruction(Instruction *Inst) { 2034 return Inst->mayHaveSideEffects() || Inst->mayReadOrWriteMemory(); 2035 } 2036 2037 /// Join instructions to the same statement if one uses the scalar result of the 2038 /// other. 2039 static void joinOperandTree(EquivalenceClasses<Instruction *> &UnionFind, 2040 ArrayRef<Instruction *> ModeledInsts) { 2041 for (Instruction *Inst : ModeledInsts) { 2042 if (isa<PHINode>(Inst)) 2043 continue; 2044 2045 for (Use &Op : Inst->operands()) { 2046 Instruction *OpInst = dyn_cast<Instruction>(Op.get()); 2047 if (!OpInst) 2048 continue; 2049 2050 // Check if OpInst is in the BB and is a modeled instruction. 2051 auto OpVal = UnionFind.findValue(OpInst); 2052 if (OpVal == UnionFind.end()) 2053 continue; 2054 2055 UnionFind.unionSets(Inst, OpInst); 2056 } 2057 } 2058 } 2059 2060 /// Ensure that the order of ordered instructions does not change. 2061 /// 2062 /// If we encounter an ordered instruction enclosed in instructions belonging to 2063 /// a different statement (which might as well contain ordered instructions, but 2064 /// this is not tested here), join them. 2065 static void 2066 joinOrderedInstructions(EquivalenceClasses<Instruction *> &UnionFind, 2067 ArrayRef<Instruction *> ModeledInsts) { 2068 SetVector<Instruction *> SeenLeaders; 2069 for (Instruction *Inst : ModeledInsts) { 2070 if (!isOrderedInstruction(Inst)) 2071 continue; 2072 2073 Instruction *Leader = UnionFind.getLeaderValue(Inst); 2074 // Since previous iterations might have merged sets, some items in 2075 // SeenLeaders are not leaders anymore. However, The new leader of 2076 // previously merged instructions must be one of the former leaders of 2077 // these merged instructions. 2078 bool Inserted = SeenLeaders.insert(Leader); 2079 if (Inserted) 2080 continue; 2081 2082 // Merge statements to close holes. Say, we have already seen statements A 2083 // and B, in this order. Then we see an instruction of A again and we would 2084 // see the pattern "A B A". This function joins all statements until the 2085 // only seen occurrence of A. 2086 for (Instruction *Prev : reverse(SeenLeaders)) { 2087 // We are backtracking from the last element until we see Inst's leader 2088 // in SeenLeaders and merge all into one set. Although leaders of 2089 // instructions change during the execution of this loop, it's irrelevant 2090 // as we are just searching for the element that we already confirmed is 2091 // in the list. 2092 if (Prev == Leader) 2093 break; 2094 UnionFind.unionSets(Prev, Leader); 2095 } 2096 } 2097 } 2098 2099 /// If the BasicBlock has an edge from itself, ensure that the PHI WRITEs for 2100 /// the incoming values from this block are executed after the PHI READ. 2101 /// 2102 /// Otherwise it could overwrite the incoming value from before the BB with the 2103 /// value for the next execution. This can happen if the PHI WRITE is added to 2104 /// the statement with the instruction that defines the incoming value (instead 2105 /// of the last statement of the same BB). To ensure that the PHI READ and WRITE 2106 /// are in order, we put both into the statement. PHI WRITEs are always executed 2107 /// after PHI READs when they are in the same statement. 2108 /// 2109 /// TODO: This is an overpessimization. We only have to ensure that the PHI 2110 /// WRITE is not put into a statement containing the PHI itself. That could also 2111 /// be done by 2112 /// - having all (strongly connected) PHIs in a single statement, 2113 /// - unite only the PHIs in the operand tree of the PHI WRITE (because it only 2114 /// has a chance of being lifted before a PHI by being in a statement with a 2115 /// PHI that comes before in the basic block), or 2116 /// - when uniting statements, ensure that no (relevant) PHIs are overtaken. 2117 static void joinOrderedPHIs(EquivalenceClasses<Instruction *> &UnionFind, 2118 ArrayRef<Instruction *> ModeledInsts) { 2119 for (Instruction *Inst : ModeledInsts) { 2120 PHINode *PHI = dyn_cast<PHINode>(Inst); 2121 if (!PHI) 2122 continue; 2123 2124 int Idx = PHI->getBasicBlockIndex(PHI->getParent()); 2125 if (Idx < 0) 2126 continue; 2127 2128 Instruction *IncomingVal = 2129 dyn_cast<Instruction>(PHI->getIncomingValue(Idx)); 2130 if (!IncomingVal) 2131 continue; 2132 2133 UnionFind.unionSets(PHI, IncomingVal); 2134 } 2135 } 2136 2137 void ScopBuilder::buildEqivClassBlockStmts(BasicBlock *BB) { 2138 Loop *L = LI.getLoopFor(BB); 2139 2140 // Extracting out modeled instructions saves us from checking 2141 // shouldModelInst() repeatedly. 2142 SmallVector<Instruction *, 32> ModeledInsts; 2143 EquivalenceClasses<Instruction *> UnionFind; 2144 Instruction *MainInst = nullptr, *MainLeader = nullptr; 2145 for (Instruction &Inst : *BB) { 2146 if (!shouldModelInst(&Inst, L)) 2147 continue; 2148 ModeledInsts.push_back(&Inst); 2149 UnionFind.insert(&Inst); 2150 2151 // When a BB is split into multiple statements, the main statement is the 2152 // one containing the 'main' instruction. We select the first instruction 2153 // that is unlikely to be removed (because it has side-effects) as the main 2154 // one. It is used to ensure that at least one statement from the bb has the 2155 // same name as with -polly-stmt-granularity=bb. 2156 if (!MainInst && (isa<StoreInst>(Inst) || 2157 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))) 2158 MainInst = &Inst; 2159 } 2160 2161 joinOperandTree(UnionFind, ModeledInsts); 2162 joinOrderedInstructions(UnionFind, ModeledInsts); 2163 joinOrderedPHIs(UnionFind, ModeledInsts); 2164 2165 // The list of instructions for statement (statement represented by the leader 2166 // instruction). 2167 MapVector<Instruction *, std::vector<Instruction *>> LeaderToInstList; 2168 2169 // The order of statements must be preserved w.r.t. their ordered 2170 // instructions. Without this explicit scan, we would also use non-ordered 2171 // instructions (whose order is arbitrary) to determine statement order. 2172 for (Instruction *Inst : ModeledInsts) { 2173 if (!isOrderedInstruction(Inst)) 2174 continue; 2175 2176 auto LeaderIt = UnionFind.findLeader(Inst); 2177 if (LeaderIt == UnionFind.member_end()) 2178 continue; 2179 2180 // Insert element for the leader instruction. 2181 (void)LeaderToInstList[*LeaderIt]; 2182 } 2183 2184 // Collect the instructions of all leaders. UnionFind's member iterator 2185 // unfortunately are not in any specific order. 2186 for (Instruction *Inst : ModeledInsts) { 2187 auto LeaderIt = UnionFind.findLeader(Inst); 2188 if (LeaderIt == UnionFind.member_end()) 2189 continue; 2190 2191 if (Inst == MainInst) 2192 MainLeader = *LeaderIt; 2193 std::vector<Instruction *> &InstList = LeaderToInstList[*LeaderIt]; 2194 InstList.push_back(Inst); 2195 } 2196 2197 // Finally build the statements. 2198 int Count = 0; 2199 long BBIdx = scop->getNextStmtIdx(); 2200 for (auto &Instructions : LeaderToInstList) { 2201 std::vector<Instruction *> &InstList = Instructions.second; 2202 2203 // If there is no main instruction, make the first statement the main. 2204 bool IsMain = (MainInst ? MainLeader == Instructions.first : Count == 0); 2205 2206 std::string Name = makeStmtName(BB, BBIdx, Count, IsMain); 2207 scop->addScopStmt(BB, Name, L, std::move(InstList)); 2208 Count += 1; 2209 } 2210 2211 // Unconditionally add an epilogue (last statement). It contains no 2212 // instructions, but holds the PHI write accesses for successor basic blocks, 2213 // if the incoming value is not defined in another statement if the same BB. 2214 // The epilogue becomes the main statement only if there is no other 2215 // statement that could become main. 2216 // The epilogue will be removed if no PHIWrite is added to it. 2217 std::string EpilogueName = makeStmtName(BB, BBIdx, Count, Count == 0, true); 2218 scop->addScopStmt(BB, EpilogueName, L, {}); 2219 } 2220 2221 void ScopBuilder::buildStmts(Region &SR) { 2222 if (scop->isNonAffineSubRegion(&SR)) { 2223 std::vector<Instruction *> Instructions; 2224 Loop *SurroundingLoop = 2225 getFirstNonBoxedLoopFor(SR.getEntry(), LI, scop->getBoxedLoops()); 2226 for (Instruction &Inst : *SR.getEntry()) 2227 if (shouldModelInst(&Inst, SurroundingLoop)) 2228 Instructions.push_back(&Inst); 2229 long RIdx = scop->getNextStmtIdx(); 2230 std::string Name = makeStmtName(&SR, RIdx); 2231 scop->addScopStmt(&SR, Name, SurroundingLoop, Instructions); 2232 return; 2233 } 2234 2235 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I) 2236 if (I->isSubRegion()) 2237 buildStmts(*I->getNodeAs<Region>()); 2238 else { 2239 BasicBlock *BB = I->getNodeAs<BasicBlock>(); 2240 switch (StmtGranularity) { 2241 case GranularityChoice::BasicBlocks: 2242 buildSequentialBlockStmts(BB); 2243 break; 2244 case GranularityChoice::ScalarIndependence: 2245 buildEqivClassBlockStmts(BB); 2246 break; 2247 case GranularityChoice::Stores: 2248 buildSequentialBlockStmts(BB, true); 2249 break; 2250 } 2251 } 2252 } 2253 2254 void ScopBuilder::buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB, 2255 Region *NonAffineSubRegion) { 2256 assert( 2257 Stmt && 2258 "The exit BB is the only one that cannot be represented by a statement"); 2259 assert(Stmt->represents(&BB)); 2260 2261 // We do not build access functions for error blocks, as they may contain 2262 // instructions we can not model. 2263 if (SD.isErrorBlock(BB, scop->getRegion())) 2264 return; 2265 2266 auto BuildAccessesForInst = [this, Stmt, 2267 NonAffineSubRegion](Instruction *Inst) { 2268 PHINode *PHI = dyn_cast<PHINode>(Inst); 2269 if (PHI) 2270 buildPHIAccesses(Stmt, PHI, NonAffineSubRegion, false); 2271 2272 if (auto MemInst = MemAccInst::dyn_cast(*Inst)) { 2273 assert(Stmt && "Cannot build access function in non-existing statement"); 2274 buildMemoryAccess(MemInst, Stmt); 2275 } 2276 2277 // PHI nodes have already been modeled above and terminators that are 2278 // not part of a non-affine subregion are fully modeled and regenerated 2279 // from the polyhedral domains. Hence, they do not need to be modeled as 2280 // explicit data dependences. 2281 if (!PHI) 2282 buildScalarDependences(Stmt, Inst); 2283 }; 2284 2285 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 2286 bool IsEntryBlock = (Stmt->getEntryBlock() == &BB); 2287 if (IsEntryBlock) { 2288 for (Instruction *Inst : Stmt->getInstructions()) 2289 BuildAccessesForInst(Inst); 2290 if (Stmt->isRegionStmt()) 2291 BuildAccessesForInst(BB.getTerminator()); 2292 } else { 2293 for (Instruction &Inst : BB) { 2294 if (isIgnoredIntrinsic(&Inst)) 2295 continue; 2296 2297 // Invariant loads already have been processed. 2298 if (isa<LoadInst>(Inst) && RIL.count(cast<LoadInst>(&Inst))) 2299 continue; 2300 2301 BuildAccessesForInst(&Inst); 2302 } 2303 } 2304 } 2305 2306 MemoryAccess *ScopBuilder::addMemoryAccess( 2307 ScopStmt *Stmt, Instruction *Inst, MemoryAccess::AccessType AccType, 2308 Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue, 2309 ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes, 2310 MemoryKind Kind) { 2311 bool isKnownMustAccess = false; 2312 2313 // Accesses in single-basic block statements are always executed. 2314 if (Stmt->isBlockStmt()) 2315 isKnownMustAccess = true; 2316 2317 if (Stmt->isRegionStmt()) { 2318 // Accesses that dominate the exit block of a non-affine region are always 2319 // executed. In non-affine regions there may exist MemoryKind::Values that 2320 // do not dominate the exit. MemoryKind::Values will always dominate the 2321 // exit and MemoryKind::PHIs only if there is at most one PHI_WRITE in the 2322 // non-affine region. 2323 if (Inst && DT.dominates(Inst->getParent(), Stmt->getRegion()->getExit())) 2324 isKnownMustAccess = true; 2325 } 2326 2327 // Non-affine PHI writes do not "happen" at a particular instruction, but 2328 // after exiting the statement. Therefore they are guaranteed to execute and 2329 // overwrite the old value. 2330 if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI) 2331 isKnownMustAccess = true; 2332 2333 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE) 2334 AccType = MemoryAccess::MAY_WRITE; 2335 2336 auto *Access = new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType, 2337 Affine, Subscripts, Sizes, AccessValue, Kind); 2338 2339 scop->addAccessFunction(Access); 2340 Stmt->addAccess(Access); 2341 return Access; 2342 } 2343 2344 void ScopBuilder::addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst, 2345 MemoryAccess::AccessType AccType, 2346 Value *BaseAddress, Type *ElementType, 2347 bool IsAffine, 2348 ArrayRef<const SCEV *> Subscripts, 2349 ArrayRef<const SCEV *> Sizes, 2350 Value *AccessValue) { 2351 ArrayBasePointers.insert(BaseAddress); 2352 auto *MemAccess = addMemoryAccess(Stmt, MemAccInst, AccType, BaseAddress, 2353 ElementType, IsAffine, AccessValue, 2354 Subscripts, Sizes, MemoryKind::Array); 2355 2356 if (!DetectFortranArrays) 2357 return; 2358 2359 if (Value *FAD = findFADAllocationInvisible(MemAccInst)) 2360 MemAccess->setFortranArrayDescriptor(FAD); 2361 else if (Value *FAD = findFADAllocationVisible(MemAccInst)) 2362 MemAccess->setFortranArrayDescriptor(FAD); 2363 } 2364 2365 /// Check if @p Expr is divisible by @p Size. 2366 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) { 2367 assert(Size != 0); 2368 if (Size == 1) 2369 return true; 2370 2371 // Only one factor needs to be divisible. 2372 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) { 2373 for (auto *FactorExpr : MulExpr->operands()) 2374 if (isDivisible(FactorExpr, Size, SE)) 2375 return true; 2376 return false; 2377 } 2378 2379 // For other n-ary expressions (Add, AddRec, Max,...) all operands need 2380 // to be divisible. 2381 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) { 2382 for (auto *OpExpr : NAryExpr->operands()) 2383 if (!isDivisible(OpExpr, Size, SE)) 2384 return false; 2385 return true; 2386 } 2387 2388 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size); 2389 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV); 2390 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV); 2391 return MulSCEV == Expr; 2392 } 2393 2394 void ScopBuilder::foldSizeConstantsToRight() { 2395 isl::union_set Accessed = scop->getAccesses().range(); 2396 2397 for (auto Array : scop->arrays()) { 2398 if (Array->getNumberOfDimensions() <= 1) 2399 continue; 2400 2401 isl::space Space = Array->getSpace(); 2402 Space = Space.align_params(Accessed.get_space()); 2403 2404 if (!Accessed.contains(Space)) 2405 continue; 2406 2407 isl::set Elements = Accessed.extract_set(Space); 2408 isl::map Transform = isl::map::universe(Array->getSpace().map_from_set()); 2409 2410 std::vector<int> Int; 2411 int Dims = Elements.tuple_dim().release(); 2412 for (int i = 0; i < Dims; i++) { 2413 isl::set DimOnly = isl::set(Elements).project_out(isl::dim::set, 0, i); 2414 DimOnly = DimOnly.project_out(isl::dim::set, 1, Dims - i - 1); 2415 DimOnly = DimOnly.lower_bound_si(isl::dim::set, 0, 0); 2416 2417 isl::basic_set DimHull = DimOnly.affine_hull(); 2418 2419 if (i == Dims - 1) { 2420 Int.push_back(1); 2421 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i); 2422 continue; 2423 } 2424 2425 if (DimHull.dim(isl::dim::div).release() == 1) { 2426 isl::aff Diff = DimHull.get_div(0); 2427 isl::val Val = Diff.get_denominator_val(); 2428 2429 int ValInt = 1; 2430 if (Val.is_int()) { 2431 auto ValAPInt = APIntFromVal(Val); 2432 if (ValAPInt.isSignedIntN(32)) 2433 ValInt = ValAPInt.getSExtValue(); 2434 } else { 2435 } 2436 2437 Int.push_back(ValInt); 2438 isl::constraint C = isl::constraint::alloc_equality( 2439 isl::local_space(Transform.get_space())); 2440 C = C.set_coefficient_si(isl::dim::out, i, ValInt); 2441 C = C.set_coefficient_si(isl::dim::in, i, -1); 2442 Transform = Transform.add_constraint(C); 2443 continue; 2444 } 2445 2446 isl::basic_set ZeroSet = isl::basic_set(DimHull); 2447 ZeroSet = ZeroSet.fix_si(isl::dim::set, 0, 0); 2448 2449 int ValInt = 1; 2450 if (ZeroSet.is_equal(DimHull)) { 2451 ValInt = 0; 2452 } 2453 2454 Int.push_back(ValInt); 2455 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i); 2456 } 2457 2458 isl::set MappedElements = isl::map(Transform).domain(); 2459 if (!Elements.is_subset(MappedElements)) 2460 continue; 2461 2462 bool CanFold = true; 2463 if (Int[0] <= 1) 2464 CanFold = false; 2465 2466 unsigned NumDims = Array->getNumberOfDimensions(); 2467 for (unsigned i = 1; i < NumDims - 1; i++) 2468 if (Int[0] != Int[i] && Int[i]) 2469 CanFold = false; 2470 2471 if (!CanFold) 2472 continue; 2473 2474 for (auto &Access : scop->access_functions()) 2475 if (Access->getScopArrayInfo() == Array) 2476 Access->setAccessRelation( 2477 Access->getAccessRelation().apply_range(Transform)); 2478 2479 std::vector<const SCEV *> Sizes; 2480 for (unsigned i = 0; i < NumDims; i++) { 2481 auto Size = Array->getDimensionSize(i); 2482 2483 if (i == NumDims - 1) 2484 Size = SE.getMulExpr(Size, SE.getConstant(Size->getType(), Int[0])); 2485 Sizes.push_back(Size); 2486 } 2487 2488 Array->updateSizes(Sizes, false /* CheckConsistency */); 2489 } 2490 } 2491 2492 void ScopBuilder::markFortranArrays() { 2493 for (ScopStmt &Stmt : *scop) { 2494 for (MemoryAccess *MemAcc : Stmt) { 2495 Value *FAD = MemAcc->getFortranArrayDescriptor(); 2496 if (!FAD) 2497 continue; 2498 2499 // TODO: const_cast-ing to edit 2500 ScopArrayInfo *SAI = 2501 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo()); 2502 assert(SAI && "memory access into a Fortran array does not " 2503 "have an associated ScopArrayInfo"); 2504 SAI->applyAndSetFAD(FAD); 2505 } 2506 } 2507 } 2508 2509 void ScopBuilder::finalizeAccesses() { 2510 updateAccessDimensionality(); 2511 foldSizeConstantsToRight(); 2512 foldAccessRelations(); 2513 assumeNoOutOfBounds(); 2514 markFortranArrays(); 2515 } 2516 2517 void ScopBuilder::updateAccessDimensionality() { 2518 // Check all array accesses for each base pointer and find a (virtual) element 2519 // size for the base pointer that divides all access functions. 2520 for (ScopStmt &Stmt : *scop) 2521 for (MemoryAccess *Access : Stmt) { 2522 if (!Access->isArrayKind()) 2523 continue; 2524 ScopArrayInfo *Array = 2525 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo()); 2526 2527 if (Array->getNumberOfDimensions() != 1) 2528 continue; 2529 unsigned DivisibleSize = Array->getElemSizeInBytes(); 2530 const SCEV *Subscript = Access->getSubscript(0); 2531 while (!isDivisible(Subscript, DivisibleSize, SE)) 2532 DivisibleSize /= 2; 2533 auto *Ty = IntegerType::get(SE.getContext(), DivisibleSize * 8); 2534 Array->updateElementType(Ty); 2535 } 2536 2537 for (auto &Stmt : *scop) 2538 for (auto &Access : Stmt) 2539 Access->updateDimensionality(); 2540 } 2541 2542 void ScopBuilder::foldAccessRelations() { 2543 for (auto &Stmt : *scop) 2544 for (auto &Access : Stmt) 2545 Access->foldAccessRelation(); 2546 } 2547 2548 void ScopBuilder::assumeNoOutOfBounds() { 2549 if (PollyIgnoreInbounds) 2550 return; 2551 for (auto &Stmt : *scop) 2552 for (auto &Access : Stmt) { 2553 isl::set Outside = Access->assumeNoOutOfBound(); 2554 const auto &Loc = Access->getAccessInstruction() 2555 ? Access->getAccessInstruction()->getDebugLoc() 2556 : DebugLoc(); 2557 recordAssumption(&RecordedAssumptions, INBOUNDS, Outside, Loc, 2558 AS_ASSUMPTION); 2559 } 2560 } 2561 2562 void ScopBuilder::ensureValueWrite(Instruction *Inst) { 2563 // Find the statement that defines the value of Inst. That statement has to 2564 // write the value to make it available to those statements that read it. 2565 ScopStmt *Stmt = scop->getStmtFor(Inst); 2566 2567 // It is possible that the value is synthesizable within a loop (such that it 2568 // is not part of any statement), but not after the loop (where you need the 2569 // number of loop round-trips to synthesize it). In LCSSA-form a PHI node will 2570 // avoid this. In case the IR has no such PHI, use the last statement (where 2571 // the value is synthesizable) to write the value. 2572 if (!Stmt) 2573 Stmt = scop->getLastStmtFor(Inst->getParent()); 2574 2575 // Inst not defined within this SCoP. 2576 if (!Stmt) 2577 return; 2578 2579 // Do not process further if the instruction is already written. 2580 if (Stmt->lookupValueWriteOf(Inst)) 2581 return; 2582 2583 addMemoryAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, Inst, Inst->getType(), 2584 true, Inst, ArrayRef<const SCEV *>(), 2585 ArrayRef<const SCEV *>(), MemoryKind::Value); 2586 } 2587 2588 void ScopBuilder::ensureValueRead(Value *V, ScopStmt *UserStmt) { 2589 // TODO: Make ScopStmt::ensureValueRead(Value*) offer the same functionality 2590 // to be able to replace this one. Currently, there is a split responsibility. 2591 // In a first step, the MemoryAccess is created, but without the 2592 // AccessRelation. In the second step by ScopStmt::buildAccessRelations(), the 2593 // AccessRelation is created. At least for scalar accesses, there is no new 2594 // information available at ScopStmt::buildAccessRelations(), so we could 2595 // create the AccessRelation right away. This is what 2596 // ScopStmt::ensureValueRead(Value*) does. 2597 2598 auto *Scope = UserStmt->getSurroundingLoop(); 2599 auto VUse = VirtualUse::create(scop.get(), UserStmt, Scope, V, false); 2600 switch (VUse.getKind()) { 2601 case VirtualUse::Constant: 2602 case VirtualUse::Block: 2603 case VirtualUse::Synthesizable: 2604 case VirtualUse::Hoisted: 2605 case VirtualUse::Intra: 2606 // Uses of these kinds do not need a MemoryAccess. 2607 break; 2608 2609 case VirtualUse::ReadOnly: 2610 // Add MemoryAccess for invariant values only if requested. 2611 if (!ModelReadOnlyScalars) 2612 break; 2613 2614 LLVM_FALLTHROUGH; 2615 case VirtualUse::Inter: 2616 2617 // Do not create another MemoryAccess for reloading the value if one already 2618 // exists. 2619 if (UserStmt->lookupValueReadOf(V)) 2620 break; 2621 2622 addMemoryAccess(UserStmt, nullptr, MemoryAccess::READ, V, V->getType(), 2623 true, V, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2624 MemoryKind::Value); 2625 2626 // Inter-statement uses need to write the value in their defining statement. 2627 if (VUse.isInter()) 2628 ensureValueWrite(cast<Instruction>(V)); 2629 break; 2630 } 2631 } 2632 2633 void ScopBuilder::ensurePHIWrite(PHINode *PHI, ScopStmt *IncomingStmt, 2634 BasicBlock *IncomingBlock, 2635 Value *IncomingValue, bool IsExitBlock) { 2636 // As the incoming block might turn out to be an error statement ensure we 2637 // will create an exit PHI SAI object. It is needed during code generation 2638 // and would be created later anyway. 2639 if (IsExitBlock) 2640 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {}, 2641 MemoryKind::ExitPHI); 2642 2643 // This is possible if PHI is in the SCoP's entry block. The incoming blocks 2644 // from outside the SCoP's region have no statement representation. 2645 if (!IncomingStmt) 2646 return; 2647 2648 // Take care for the incoming value being available in the incoming block. 2649 // This must be done before the check for multiple PHI writes because multiple 2650 // exiting edges from subregion each can be the effective written value of the 2651 // subregion. As such, all of them must be made available in the subregion 2652 // statement. 2653 ensureValueRead(IncomingValue, IncomingStmt); 2654 2655 // Do not add more than one MemoryAccess per PHINode and ScopStmt. 2656 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) { 2657 assert(Acc->getAccessInstruction() == PHI); 2658 Acc->addIncoming(IncomingBlock, IncomingValue); 2659 return; 2660 } 2661 2662 MemoryAccess *Acc = addMemoryAccess( 2663 IncomingStmt, PHI, MemoryAccess::MUST_WRITE, PHI, PHI->getType(), true, 2664 PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2665 IsExitBlock ? MemoryKind::ExitPHI : MemoryKind::PHI); 2666 assert(Acc); 2667 Acc->addIncoming(IncomingBlock, IncomingValue); 2668 } 2669 2670 void ScopBuilder::addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI) { 2671 addMemoryAccess(PHIStmt, PHI, MemoryAccess::READ, PHI, PHI->getType(), true, 2672 PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2673 MemoryKind::PHI); 2674 } 2675 2676 void ScopBuilder::buildDomain(ScopStmt &Stmt) { 2677 isl::id Id = isl::id::alloc(scop->getIslCtx(), Stmt.getBaseName(), &Stmt); 2678 2679 Stmt.Domain = scop->getDomainConditions(&Stmt); 2680 Stmt.Domain = Stmt.Domain.set_tuple_id(Id); 2681 } 2682 2683 void ScopBuilder::collectSurroundingLoops(ScopStmt &Stmt) { 2684 isl::set Domain = Stmt.getDomain(); 2685 BasicBlock *BB = Stmt.getEntryBlock(); 2686 2687 Loop *L = LI.getLoopFor(BB); 2688 2689 while (L && Stmt.isRegionStmt() && Stmt.getRegion()->contains(L)) 2690 L = L->getParentLoop(); 2691 2692 SmallVector<llvm::Loop *, 8> Loops; 2693 2694 while (L && Stmt.getParent()->getRegion().contains(L)) { 2695 Loops.push_back(L); 2696 L = L->getParentLoop(); 2697 } 2698 2699 Stmt.NestLoops.insert(Stmt.NestLoops.begin(), Loops.rbegin(), Loops.rend()); 2700 } 2701 2702 /// Return the reduction type for a given binary operator. 2703 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp, 2704 const Instruction *Load) { 2705 if (!BinOp) 2706 return MemoryAccess::RT_NONE; 2707 switch (BinOp->getOpcode()) { 2708 case Instruction::FAdd: 2709 if (!BinOp->isFast()) 2710 return MemoryAccess::RT_NONE; 2711 LLVM_FALLTHROUGH; 2712 case Instruction::Add: 2713 return MemoryAccess::RT_ADD; 2714 case Instruction::Or: 2715 return MemoryAccess::RT_BOR; 2716 case Instruction::Xor: 2717 return MemoryAccess::RT_BXOR; 2718 case Instruction::And: 2719 return MemoryAccess::RT_BAND; 2720 case Instruction::FMul: 2721 if (!BinOp->isFast()) 2722 return MemoryAccess::RT_NONE; 2723 LLVM_FALLTHROUGH; 2724 case Instruction::Mul: 2725 if (DisableMultiplicativeReductions) 2726 return MemoryAccess::RT_NONE; 2727 return MemoryAccess::RT_MUL; 2728 default: 2729 return MemoryAccess::RT_NONE; 2730 } 2731 } 2732 2733 void ScopBuilder::checkForReductions(ScopStmt &Stmt) { 2734 SmallVector<MemoryAccess *, 2> Loads; 2735 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates; 2736 2737 // First collect candidate load-store reduction chains by iterating over all 2738 // stores and collecting possible reduction loads. 2739 for (MemoryAccess *StoreMA : Stmt) { 2740 if (StoreMA->isRead()) 2741 continue; 2742 2743 Loads.clear(); 2744 collectCandidateReductionLoads(StoreMA, Loads); 2745 for (MemoryAccess *LoadMA : Loads) 2746 Candidates.push_back(std::make_pair(LoadMA, StoreMA)); 2747 } 2748 2749 // Then check each possible candidate pair. 2750 for (const auto &CandidatePair : Candidates) { 2751 bool Valid = true; 2752 isl::map LoadAccs = CandidatePair.first->getAccessRelation(); 2753 isl::map StoreAccs = CandidatePair.second->getAccessRelation(); 2754 2755 // Skip those with obviously unequal base addresses. 2756 if (!LoadAccs.has_equal_space(StoreAccs)) { 2757 continue; 2758 } 2759 2760 // And check if the remaining for overlap with other memory accesses. 2761 isl::map AllAccsRel = LoadAccs.unite(StoreAccs); 2762 AllAccsRel = AllAccsRel.intersect_domain(Stmt.getDomain()); 2763 isl::set AllAccs = AllAccsRel.range(); 2764 2765 for (MemoryAccess *MA : Stmt) { 2766 if (MA == CandidatePair.first || MA == CandidatePair.second) 2767 continue; 2768 2769 isl::map AccRel = 2770 MA->getAccessRelation().intersect_domain(Stmt.getDomain()); 2771 isl::set Accs = AccRel.range(); 2772 2773 if (AllAccs.has_equal_space(Accs)) { 2774 isl::set OverlapAccs = Accs.intersect(AllAccs); 2775 Valid = Valid && OverlapAccs.is_empty(); 2776 } 2777 } 2778 2779 if (!Valid) 2780 continue; 2781 2782 const LoadInst *Load = 2783 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction()); 2784 MemoryAccess::ReductionType RT = 2785 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load); 2786 2787 // If no overlapping access was found we mark the load and store as 2788 // reduction like. 2789 CandidatePair.first->markAsReductionLike(RT); 2790 CandidatePair.second->markAsReductionLike(RT); 2791 } 2792 } 2793 2794 void ScopBuilder::verifyInvariantLoads() { 2795 auto &RIL = scop->getRequiredInvariantLoads(); 2796 for (LoadInst *LI : RIL) { 2797 assert(LI && scop->contains(LI)); 2798 // If there exists a statement in the scop which has a memory access for 2799 // @p LI, then mark this scop as infeasible for optimization. 2800 for (ScopStmt &Stmt : *scop) 2801 if (Stmt.getArrayAccessOrNULLFor(LI)) { 2802 scop->invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent()); 2803 return; 2804 } 2805 } 2806 } 2807 2808 void ScopBuilder::hoistInvariantLoads() { 2809 if (!PollyInvariantLoadHoisting) 2810 return; 2811 2812 isl::union_map Writes = scop->getWrites(); 2813 for (ScopStmt &Stmt : *scop) { 2814 InvariantAccessesTy InvariantAccesses; 2815 2816 for (MemoryAccess *Access : Stmt) { 2817 isl::set NHCtx = getNonHoistableCtx(Access, Writes); 2818 if (!NHCtx.is_null()) 2819 InvariantAccesses.push_back({Access, NHCtx}); 2820 } 2821 2822 // Transfer the memory access from the statement to the SCoP. 2823 for (auto InvMA : InvariantAccesses) 2824 Stmt.removeMemoryAccess(InvMA.MA); 2825 addInvariantLoads(Stmt, InvariantAccesses); 2826 } 2827 } 2828 2829 /// Check if an access range is too complex. 2830 /// 2831 /// An access range is too complex, if it contains either many disjuncts or 2832 /// very complex expressions. As a simple heuristic, we assume if a set to 2833 /// be too complex if the sum of existentially quantified dimensions and 2834 /// set dimensions is larger than a threshold. This reliably detects both 2835 /// sets with many disjuncts as well as sets with many divisions as they 2836 /// arise in h264. 2837 /// 2838 /// @param AccessRange The range to check for complexity. 2839 /// 2840 /// @returns True if the access range is too complex. 2841 static bool isAccessRangeTooComplex(isl::set AccessRange) { 2842 int NumTotalDims = 0; 2843 2844 for (isl::basic_set BSet : AccessRange.get_basic_set_list()) { 2845 NumTotalDims += BSet.dim(isl::dim::div).release(); 2846 NumTotalDims += BSet.dim(isl::dim::set).release(); 2847 } 2848 2849 if (NumTotalDims > MaxDimensionsInAccessRange) 2850 return true; 2851 2852 return false; 2853 } 2854 2855 bool ScopBuilder::hasNonHoistableBasePtrInScop(MemoryAccess *MA, 2856 isl::union_map Writes) { 2857 if (auto *BasePtrMA = scop->lookupBasePtrAccess(MA)) { 2858 return getNonHoistableCtx(BasePtrMA, Writes).is_null(); 2859 } 2860 2861 Value *BaseAddr = MA->getOriginalBaseAddr(); 2862 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr)) 2863 if (!isa<LoadInst>(BasePtrInst)) 2864 return scop->contains(BasePtrInst); 2865 2866 return false; 2867 } 2868 2869 void ScopBuilder::addUserContext() { 2870 if (UserContextStr.empty()) 2871 return; 2872 2873 isl::set UserContext = isl::set(scop->getIslCtx(), UserContextStr.c_str()); 2874 isl::space Space = scop->getParamSpace(); 2875 if (Space.dim(isl::dim::param).release() != 2876 UserContext.dim(isl::dim::param).release()) { 2877 std::string SpaceStr = stringFromIslObj(Space, "null"); 2878 errs() << "Error: the context provided in -polly-context has not the same " 2879 << "number of dimensions than the computed context. Due to this " 2880 << "mismatch, the -polly-context option is ignored. Please provide " 2881 << "the context in the parameter space: " << SpaceStr << ".\n"; 2882 return; 2883 } 2884 2885 for (auto i : seq<isl_size>(0, Space.dim(isl::dim::param).release())) { 2886 std::string NameContext = 2887 scop->getContext().get_dim_name(isl::dim::param, i); 2888 std::string NameUserContext = UserContext.get_dim_name(isl::dim::param, i); 2889 2890 if (NameContext != NameUserContext) { 2891 std::string SpaceStr = stringFromIslObj(Space, "null"); 2892 errs() << "Error: the name of dimension " << i 2893 << " provided in -polly-context " 2894 << "is '" << NameUserContext << "', but the name in the computed " 2895 << "context is '" << NameContext 2896 << "'. Due to this name mismatch, " 2897 << "the -polly-context option is ignored. Please provide " 2898 << "the context in the parameter space: " << SpaceStr << ".\n"; 2899 return; 2900 } 2901 2902 UserContext = UserContext.set_dim_id(isl::dim::param, i, 2903 Space.get_dim_id(isl::dim::param, i)); 2904 } 2905 isl::set newContext = scop->getContext().intersect(UserContext); 2906 scop->setContext(newContext); 2907 } 2908 2909 isl::set ScopBuilder::getNonHoistableCtx(MemoryAccess *Access, 2910 isl::union_map Writes) { 2911 // TODO: Loads that are not loop carried, hence are in a statement with 2912 // zero iterators, are by construction invariant, though we 2913 // currently "hoist" them anyway. This is necessary because we allow 2914 // them to be treated as parameters (e.g., in conditions) and our code 2915 // generation would otherwise use the old value. 2916 2917 auto &Stmt = *Access->getStatement(); 2918 BasicBlock *BB = Stmt.getEntryBlock(); 2919 2920 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() || 2921 Access->isMemoryIntrinsic()) 2922 return {}; 2923 2924 // Skip accesses that have an invariant base pointer which is defined but 2925 // not loaded inside the SCoP. This can happened e.g., if a readnone call 2926 // returns a pointer that is used as a base address. However, as we want 2927 // to hoist indirect pointers, we allow the base pointer to be defined in 2928 // the region if it is also a memory access. Each ScopArrayInfo object 2929 // that has a base pointer origin has a base pointer that is loaded and 2930 // that it is invariant, thus it will be hoisted too. However, if there is 2931 // no base pointer origin we check that the base pointer is defined 2932 // outside the region. 2933 auto *LI = cast<LoadInst>(Access->getAccessInstruction()); 2934 if (hasNonHoistableBasePtrInScop(Access, Writes)) 2935 return {}; 2936 2937 isl::map AccessRelation = Access->getAccessRelation(); 2938 assert(!AccessRelation.is_empty()); 2939 2940 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators())) 2941 return {}; 2942 2943 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain()); 2944 isl::set SafeToLoad; 2945 2946 auto &DL = scop->getFunction().getParent()->getDataLayout(); 2947 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getType(), 2948 LI->getAlign(), DL)) { 2949 SafeToLoad = isl::set::universe(AccessRelation.get_space().range()); 2950 } else if (BB != LI->getParent()) { 2951 // Skip accesses in non-affine subregions as they might not be executed 2952 // under the same condition as the entry of the non-affine subregion. 2953 return {}; 2954 } else { 2955 SafeToLoad = AccessRelation.range(); 2956 } 2957 2958 if (isAccessRangeTooComplex(AccessRelation.range())) 2959 return {}; 2960 2961 isl::union_map Written = Writes.intersect_range(SafeToLoad); 2962 isl::set WrittenCtx = Written.params(); 2963 bool IsWritten = !WrittenCtx.is_empty(); 2964 2965 if (!IsWritten) 2966 return WrittenCtx; 2967 2968 WrittenCtx = WrittenCtx.remove_divs(); 2969 bool TooComplex = WrittenCtx.n_basic_set().release() >= MaxDisjunctsInDomain; 2970 if (TooComplex || !isRequiredInvariantLoad(LI)) 2971 return {}; 2972 2973 scop->addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), 2974 AS_RESTRICTION, LI->getParent()); 2975 return WrittenCtx; 2976 } 2977 2978 static bool isAParameter(llvm::Value *maybeParam, const Function &F) { 2979 for (const llvm::Argument &Arg : F.args()) 2980 if (&Arg == maybeParam) 2981 return true; 2982 2983 return false; 2984 } 2985 2986 bool ScopBuilder::canAlwaysBeHoisted(MemoryAccess *MA, 2987 bool StmtInvalidCtxIsEmpty, 2988 bool MAInvalidCtxIsEmpty, 2989 bool NonHoistableCtxIsEmpty) { 2990 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 2991 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout(); 2992 if (PollyAllowDereferenceOfAllFunctionParams && 2993 isAParameter(LInst->getPointerOperand(), scop->getFunction())) 2994 return true; 2995 2996 // TODO: We can provide more information for better but more expensive 2997 // results. 2998 if (!isDereferenceableAndAlignedPointer( 2999 LInst->getPointerOperand(), LInst->getType(), LInst->getAlign(), DL)) 3000 return false; 3001 3002 // If the location might be overwritten we do not hoist it unconditionally. 3003 // 3004 // TODO: This is probably too conservative. 3005 if (!NonHoistableCtxIsEmpty) 3006 return false; 3007 3008 // If a dereferenceable load is in a statement that is modeled precisely we 3009 // can hoist it. 3010 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty) 3011 return true; 3012 3013 // Even if the statement is not modeled precisely we can hoist the load if it 3014 // does not involve any parameters that might have been specialized by the 3015 // statement domain. 3016 for (const SCEV *Subscript : MA->subscripts()) 3017 if (!isa<SCEVConstant>(Subscript)) 3018 return false; 3019 return true; 3020 } 3021 3022 void ScopBuilder::addInvariantLoads(ScopStmt &Stmt, 3023 InvariantAccessesTy &InvMAs) { 3024 if (InvMAs.empty()) 3025 return; 3026 3027 isl::set StmtInvalidCtx = Stmt.getInvalidContext(); 3028 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty(); 3029 3030 // Get the context under which the statement is executed but remove the error 3031 // context under which this statement is reached. 3032 isl::set DomainCtx = Stmt.getDomain().params(); 3033 DomainCtx = DomainCtx.subtract(StmtInvalidCtx); 3034 3035 if (DomainCtx.n_basic_set().release() >= MaxDisjunctsInDomain) { 3036 auto *AccInst = InvMAs.front().MA->getAccessInstruction(); 3037 scop->invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent()); 3038 return; 3039 } 3040 3041 // Project out all parameters that relate to loads in the statement. Otherwise 3042 // we could have cyclic dependences on the constraints under which the 3043 // hoisted loads are executed and we could not determine an order in which to 3044 // pre-load them. This happens because not only lower bounds are part of the 3045 // domain but also upper bounds. 3046 for (auto &InvMA : InvMAs) { 3047 auto *MA = InvMA.MA; 3048 Instruction *AccInst = MA->getAccessInstruction(); 3049 if (SE.isSCEVable(AccInst->getType())) { 3050 SetVector<Value *> Values; 3051 for (const SCEV *Parameter : scop->parameters()) { 3052 Values.clear(); 3053 findValues(Parameter, SE, Values); 3054 if (!Values.count(AccInst)) 3055 continue; 3056 3057 isl::id ParamId = scop->getIdForParam(Parameter); 3058 if (!ParamId.is_null()) { 3059 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId); 3060 if (Dim >= 0) 3061 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1); 3062 } 3063 } 3064 } 3065 } 3066 3067 for (auto &InvMA : InvMAs) { 3068 auto *MA = InvMA.MA; 3069 isl::set NHCtx = InvMA.NonHoistableCtx; 3070 3071 // Check for another invariant access that accesses the same location as 3072 // MA and if found consolidate them. Otherwise create a new equivalence 3073 // class at the end of InvariantEquivClasses. 3074 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3075 Type *Ty = LInst->getType(); 3076 const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand()); 3077 3078 isl::set MAInvalidCtx = MA->getInvalidContext(); 3079 bool NonHoistableCtxIsEmpty = NHCtx.is_empty(); 3080 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty(); 3081 3082 isl::set MACtx; 3083 // Check if we know that this pointer can be speculatively accessed. 3084 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty, 3085 NonHoistableCtxIsEmpty)) { 3086 MACtx = isl::set::universe(DomainCtx.get_space()); 3087 } else { 3088 MACtx = DomainCtx; 3089 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx)); 3090 MACtx = MACtx.gist_params(scop->getContext()); 3091 } 3092 3093 bool Consolidated = false; 3094 for (auto &IAClass : scop->invariantEquivClasses()) { 3095 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3096 continue; 3097 3098 // If the pointer and the type is equal check if the access function wrt. 3099 // to the domain is equal too. It can happen that the domain fixes 3100 // parameter values and these can be different for distinct part of the 3101 // SCoP. If this happens we cannot consolidate the loads but need to 3102 // create a new invariant load equivalence class. 3103 auto &MAs = IAClass.InvariantAccesses; 3104 if (!MAs.empty()) { 3105 auto *LastMA = MAs.front(); 3106 3107 isl::set AR = MA->getAccessRelation().range(); 3108 isl::set LastAR = LastMA->getAccessRelation().range(); 3109 bool SameAR = AR.is_equal(LastAR); 3110 3111 if (!SameAR) 3112 continue; 3113 } 3114 3115 // Add MA to the list of accesses that are in this class. 3116 MAs.push_front(MA); 3117 3118 Consolidated = true; 3119 3120 // Unify the execution context of the class and this statement. 3121 isl::set IAClassDomainCtx = IAClass.ExecutionContext; 3122 if (!IAClassDomainCtx.is_null()) 3123 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce(); 3124 else 3125 IAClassDomainCtx = MACtx; 3126 IAClass.ExecutionContext = IAClassDomainCtx; 3127 break; 3128 } 3129 3130 if (Consolidated) 3131 continue; 3132 3133 MACtx = MACtx.coalesce(); 3134 3135 // If we did not consolidate MA, thus did not find an equivalence class 3136 // for it, we create a new one. 3137 scop->addInvariantEquivClass( 3138 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty}); 3139 } 3140 } 3141 3142 void ScopBuilder::collectCandidateReductionLoads( 3143 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) { 3144 ScopStmt *Stmt = StoreMA->getStatement(); 3145 3146 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction()); 3147 if (!Store) 3148 return; 3149 3150 // Skip if there is not one binary operator between the load and the store 3151 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand()); 3152 if (!BinOp) 3153 return; 3154 3155 // Skip if the binary operators has multiple uses 3156 if (BinOp->getNumUses() != 1) 3157 return; 3158 3159 // Skip if the opcode of the binary operator is not commutative/associative 3160 if (!BinOp->isCommutative() || !BinOp->isAssociative()) 3161 return; 3162 3163 // Skip if the binary operator is outside the current SCoP 3164 if (BinOp->getParent() != Store->getParent()) 3165 return; 3166 3167 // Skip if it is a multiplicative reduction and we disabled them 3168 if (DisableMultiplicativeReductions && 3169 (BinOp->getOpcode() == Instruction::Mul || 3170 BinOp->getOpcode() == Instruction::FMul)) 3171 return; 3172 3173 // Check the binary operator operands for a candidate load 3174 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0)); 3175 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1)); 3176 if (!PossibleLoad0 && !PossibleLoad1) 3177 return; 3178 3179 // A load is only a candidate if it cannot escape (thus has only this use) 3180 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1) 3181 if (PossibleLoad0->getParent() == Store->getParent()) 3182 Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad0)); 3183 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1) 3184 if (PossibleLoad1->getParent() == Store->getParent()) 3185 Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad1)); 3186 } 3187 3188 /// Find the canonical scop array info object for a set of invariant load 3189 /// hoisted loads. The canonical array is the one that corresponds to the 3190 /// first load in the list of accesses which is used as base pointer of a 3191 /// scop array. 3192 static const ScopArrayInfo *findCanonicalArray(Scop &S, 3193 MemoryAccessList &Accesses) { 3194 for (MemoryAccess *Access : Accesses) { 3195 const ScopArrayInfo *CanonicalArray = S.getScopArrayInfoOrNull( 3196 Access->getAccessInstruction(), MemoryKind::Array); 3197 if (CanonicalArray) 3198 return CanonicalArray; 3199 } 3200 return nullptr; 3201 } 3202 3203 /// Check if @p Array severs as base array in an invariant load. 3204 static bool isUsedForIndirectHoistedLoad(Scop &S, const ScopArrayInfo *Array) { 3205 for (InvariantEquivClassTy &EqClass2 : S.getInvariantAccesses()) 3206 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses) 3207 if (Access2->getScopArrayInfo() == Array) 3208 return true; 3209 return false; 3210 } 3211 3212 /// Replace the base pointer arrays in all memory accesses referencing @p Old, 3213 /// with a reference to @p New. 3214 static void replaceBasePtrArrays(Scop &S, const ScopArrayInfo *Old, 3215 const ScopArrayInfo *New) { 3216 for (ScopStmt &Stmt : S) 3217 for (MemoryAccess *Access : Stmt) { 3218 if (Access->getLatestScopArrayInfo() != Old) 3219 continue; 3220 3221 isl::id Id = New->getBasePtrId(); 3222 isl::map Map = Access->getAccessRelation(); 3223 Map = Map.set_tuple_id(isl::dim::out, Id); 3224 Access->setAccessRelation(Map); 3225 } 3226 } 3227 3228 void ScopBuilder::canonicalizeDynamicBasePtrs() { 3229 for (InvariantEquivClassTy &EqClass : scop->InvariantEquivClasses) { 3230 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses; 3231 3232 const ScopArrayInfo *CanonicalBasePtrSAI = 3233 findCanonicalArray(*scop, BasePtrAccesses); 3234 3235 if (!CanonicalBasePtrSAI) 3236 continue; 3237 3238 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) { 3239 const ScopArrayInfo *BasePtrSAI = scop->getScopArrayInfoOrNull( 3240 BasePtrAccess->getAccessInstruction(), MemoryKind::Array); 3241 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI || 3242 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI)) 3243 continue; 3244 3245 // we currently do not canonicalize arrays where some accesses are 3246 // hoisted as invariant loads. If we would, we need to update the access 3247 // function of the invariant loads as well. However, as this is not a 3248 // very common situation, we leave this for now to avoid further 3249 // complexity increases. 3250 if (isUsedForIndirectHoistedLoad(*scop, BasePtrSAI)) 3251 continue; 3252 3253 replaceBasePtrArrays(*scop, BasePtrSAI, CanonicalBasePtrSAI); 3254 } 3255 } 3256 } 3257 3258 void ScopBuilder::buildAccessRelations(ScopStmt &Stmt) { 3259 for (MemoryAccess *Access : Stmt.MemAccs) { 3260 Type *ElementType = Access->getElementType(); 3261 3262 MemoryKind Ty; 3263 if (Access->isPHIKind()) 3264 Ty = MemoryKind::PHI; 3265 else if (Access->isExitPHIKind()) 3266 Ty = MemoryKind::ExitPHI; 3267 else if (Access->isValueKind()) 3268 Ty = MemoryKind::Value; 3269 else 3270 Ty = MemoryKind::Array; 3271 3272 // Create isl::pw_aff for SCEVs which describe sizes. Collect all 3273 // assumptions which are taken. isl::pw_aff objects are cached internally 3274 // and they are used later by scop. 3275 for (const SCEV *Size : Access->Sizes) { 3276 if (!Size) 3277 continue; 3278 scop->getPwAff(Size, nullptr, false, &RecordedAssumptions); 3279 } 3280 auto *SAI = scop->getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(), 3281 ElementType, Access->Sizes, Ty); 3282 3283 // Create isl::pw_aff for SCEVs which describe subscripts. Collect all 3284 // assumptions which are taken. isl::pw_aff objects are cached internally 3285 // and they are used later by scop. 3286 for (const SCEV *Subscript : Access->subscripts()) { 3287 if (!Access->isAffine() || !Subscript) 3288 continue; 3289 scop->getPwAff(Subscript, Stmt.getEntryBlock(), false, 3290 &RecordedAssumptions); 3291 } 3292 Access->buildAccessRelation(SAI); 3293 scop->addAccessData(Access); 3294 } 3295 } 3296 3297 /// Add the minimal/maximal access in @p Set to @p User. 3298 /// 3299 /// @return True if more accesses should be added, false if we reached the 3300 /// maximal number of run-time checks to be generated. 3301 static bool buildMinMaxAccess(isl::set Set, 3302 Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) { 3303 isl::pw_multi_aff MinPMA, MaxPMA; 3304 isl::pw_aff LastDimAff; 3305 isl::aff OneAff; 3306 unsigned Pos; 3307 3308 Set = Set.remove_divs(); 3309 polly::simplify(Set); 3310 3311 if (Set.n_basic_set().release() > RunTimeChecksMaxAccessDisjuncts) 3312 Set = Set.simple_hull(); 3313 3314 // Restrict the number of parameters involved in the access as the lexmin/ 3315 // lexmax computation will take too long if this number is high. 3316 // 3317 // Experiments with a simple test case using an i7 4800MQ: 3318 // 3319 // #Parameters involved | Time (in sec) 3320 // 6 | 0.01 3321 // 7 | 0.04 3322 // 8 | 0.12 3323 // 9 | 0.40 3324 // 10 | 1.54 3325 // 11 | 6.78 3326 // 12 | 30.38 3327 // 3328 if (isl_set_n_param(Set.get()) > 3329 static_cast<isl_size>(RunTimeChecksMaxParameters)) { 3330 unsigned InvolvedParams = 0; 3331 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++) 3332 if (Set.involves_dims(isl::dim::param, u, 1)) 3333 InvolvedParams++; 3334 3335 if (InvolvedParams > RunTimeChecksMaxParameters) 3336 return false; 3337 } 3338 3339 MinPMA = Set.lexmin_pw_multi_aff(); 3340 MaxPMA = Set.lexmax_pw_multi_aff(); 3341 3342 MinPMA = MinPMA.coalesce(); 3343 MaxPMA = MaxPMA.coalesce(); 3344 3345 // Adjust the last dimension of the maximal access by one as we want to 3346 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer 3347 // we test during code generation might now point after the end of the 3348 // allocated array but we will never dereference it anyway. 3349 assert((MaxPMA.is_null() || MaxPMA.dim(isl::dim::out).release()) && 3350 "Assumed at least one output dimension"); 3351 3352 Pos = MaxPMA.dim(isl::dim::out).release() - 1; 3353 LastDimAff = MaxPMA.at(Pos); 3354 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space())); 3355 OneAff = OneAff.add_constant_si(1); 3356 LastDimAff = LastDimAff.add(OneAff); 3357 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff); 3358 3359 if (MinPMA.is_null() || MaxPMA.is_null()) 3360 return false; 3361 3362 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA)); 3363 3364 return true; 3365 } 3366 3367 /// Wrapper function to calculate minimal/maximal accesses to each array. 3368 bool ScopBuilder::calculateMinMaxAccess(AliasGroupTy AliasGroup, 3369 Scop::MinMaxVectorTy &MinMaxAccesses) { 3370 MinMaxAccesses.reserve(AliasGroup.size()); 3371 3372 isl::union_set Domains = scop->getDomains(); 3373 isl::union_map Accesses = isl::union_map::empty(scop->getIslCtx()); 3374 3375 for (MemoryAccess *MA : AliasGroup) 3376 Accesses = Accesses.unite(MA->getAccessRelation()); 3377 3378 Accesses = Accesses.intersect_domain(Domains); 3379 isl::union_set Locations = Accesses.range(); 3380 3381 bool LimitReached = false; 3382 for (isl::set Set : Locations.get_set_list()) { 3383 LimitReached |= !buildMinMaxAccess(Set, MinMaxAccesses, *scop); 3384 if (LimitReached) 3385 break; 3386 } 3387 3388 return !LimitReached; 3389 } 3390 3391 static isl::set getAccessDomain(MemoryAccess *MA) { 3392 isl::set Domain = MA->getStatement()->getDomain(); 3393 Domain = Domain.project_out(isl::dim::set, 0, Domain.tuple_dim().release()); 3394 return Domain.reset_tuple_id(); 3395 } 3396 3397 bool ScopBuilder::buildAliasChecks() { 3398 if (!PollyUseRuntimeAliasChecks) 3399 return true; 3400 3401 if (buildAliasGroups()) { 3402 // Aliasing assumptions do not go through addAssumption but we still want to 3403 // collect statistics so we do it here explicitly. 3404 if (scop->getAliasGroups().size()) 3405 Scop::incrementNumberOfAliasingAssumptions(1); 3406 return true; 3407 } 3408 3409 // If a problem occurs while building the alias groups we need to delete 3410 // this SCoP and pretend it wasn't valid in the first place. To this end 3411 // we make the assumed context infeasible. 3412 scop->invalidate(ALIASING, DebugLoc()); 3413 3414 LLVM_DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << scop->getNameStr() 3415 << " could not be created. This SCoP has been dismissed."); 3416 return false; 3417 } 3418 3419 std::tuple<ScopBuilder::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>> 3420 ScopBuilder::buildAliasGroupsForAccesses() { 3421 AliasSetTracker AST(AA); 3422 3423 DenseMap<Value *, MemoryAccess *> PtrToAcc; 3424 DenseSet<const ScopArrayInfo *> HasWriteAccess; 3425 for (ScopStmt &Stmt : *scop) { 3426 3427 isl::set StmtDomain = Stmt.getDomain(); 3428 bool StmtDomainEmpty = StmtDomain.is_empty(); 3429 3430 // Statements with an empty domain will never be executed. 3431 if (StmtDomainEmpty) 3432 continue; 3433 3434 for (MemoryAccess *MA : Stmt) { 3435 if (MA->isScalarKind()) 3436 continue; 3437 if (!MA->isRead()) 3438 HasWriteAccess.insert(MA->getScopArrayInfo()); 3439 MemAccInst Acc(MA->getAccessInstruction()); 3440 if (MA->isRead() && isa<MemTransferInst>(Acc)) 3441 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA; 3442 else 3443 PtrToAcc[Acc.getPointerOperand()] = MA; 3444 AST.add(Acc); 3445 } 3446 } 3447 3448 AliasGroupVectorTy AliasGroups; 3449 for (AliasSet &AS : AST) { 3450 if (AS.isMustAlias() || AS.isForwardingAliasSet()) 3451 continue; 3452 AliasGroupTy AG; 3453 for (auto &PR : AS) 3454 AG.push_back(PtrToAcc[PR.getValue()]); 3455 if (AG.size() < 2) 3456 continue; 3457 AliasGroups.push_back(std::move(AG)); 3458 } 3459 3460 return std::make_tuple(AliasGroups, HasWriteAccess); 3461 } 3462 3463 bool ScopBuilder::buildAliasGroups() { 3464 // To create sound alias checks we perform the following steps: 3465 // o) We partition each group into read only and non read only accesses. 3466 // o) For each group with more than one base pointer we then compute minimal 3467 // and maximal accesses to each array of a group in read only and non 3468 // read only partitions separately. 3469 AliasGroupVectorTy AliasGroups; 3470 DenseSet<const ScopArrayInfo *> HasWriteAccess; 3471 3472 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(); 3473 3474 splitAliasGroupsByDomain(AliasGroups); 3475 3476 for (AliasGroupTy &AG : AliasGroups) { 3477 if (!scop->hasFeasibleRuntimeContext()) 3478 return false; 3479 3480 { 3481 IslMaxOperationsGuard MaxOpGuard(scop->getIslCtx().get(), OptComputeOut); 3482 bool Valid = buildAliasGroup(AG, HasWriteAccess); 3483 if (!Valid) 3484 return false; 3485 } 3486 if (isl_ctx_last_error(scop->getIslCtx().get()) == isl_error_quota) { 3487 scop->invalidate(COMPLEXITY, DebugLoc()); 3488 return false; 3489 } 3490 } 3491 3492 return true; 3493 } 3494 3495 bool ScopBuilder::buildAliasGroup( 3496 AliasGroupTy &AliasGroup, DenseSet<const ScopArrayInfo *> HasWriteAccess) { 3497 AliasGroupTy ReadOnlyAccesses; 3498 AliasGroupTy ReadWriteAccesses; 3499 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays; 3500 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays; 3501 3502 if (AliasGroup.size() < 2) 3503 return true; 3504 3505 for (MemoryAccess *Access : AliasGroup) { 3506 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias", 3507 Access->getAccessInstruction()) 3508 << "Possibly aliasing pointer, use restrict keyword."); 3509 const ScopArrayInfo *Array = Access->getScopArrayInfo(); 3510 if (HasWriteAccess.count(Array)) { 3511 ReadWriteArrays.insert(Array); 3512 ReadWriteAccesses.push_back(Access); 3513 } else { 3514 ReadOnlyArrays.insert(Array); 3515 ReadOnlyAccesses.push_back(Access); 3516 } 3517 } 3518 3519 // If there are no read-only pointers, and less than two read-write pointers, 3520 // no alias check is needed. 3521 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1) 3522 return true; 3523 3524 // If there is no read-write pointer, no alias check is needed. 3525 if (ReadWriteArrays.empty()) 3526 return true; 3527 3528 // For non-affine accesses, no alias check can be generated as we cannot 3529 // compute a sufficiently tight lower and upper bound: bail out. 3530 for (MemoryAccess *MA : AliasGroup) { 3531 if (!MA->isAffine()) { 3532 scop->invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(), 3533 MA->getAccessInstruction()->getParent()); 3534 return false; 3535 } 3536 } 3537 3538 // Ensure that for all memory accesses for which we generate alias checks, 3539 // their base pointers are available. 3540 for (MemoryAccess *MA : AliasGroup) { 3541 if (MemoryAccess *BasePtrMA = scop->lookupBasePtrAccess(MA)) 3542 scop->addRequiredInvariantLoad( 3543 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3544 } 3545 3546 // scop->getAliasGroups().emplace_back(); 3547 // Scop::MinMaxVectorPairTy &pair = scop->getAliasGroups().back(); 3548 Scop::MinMaxVectorTy MinMaxAccessesReadWrite; 3549 Scop::MinMaxVectorTy MinMaxAccessesReadOnly; 3550 3551 bool Valid; 3552 3553 Valid = calculateMinMaxAccess(ReadWriteAccesses, MinMaxAccessesReadWrite); 3554 3555 if (!Valid) 3556 return false; 3557 3558 // Bail out if the number of values we need to compare is too large. 3559 // This is important as the number of comparisons grows quadratically with 3560 // the number of values we need to compare. 3561 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() > 3562 RunTimeChecksMaxArraysPerGroup) 3563 return false; 3564 3565 Valid = calculateMinMaxAccess(ReadOnlyAccesses, MinMaxAccessesReadOnly); 3566 3567 scop->addAliasGroup(MinMaxAccessesReadWrite, MinMaxAccessesReadOnly); 3568 if (!Valid) 3569 return false; 3570 3571 return true; 3572 } 3573 3574 void ScopBuilder::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) { 3575 for (unsigned u = 0; u < AliasGroups.size(); u++) { 3576 AliasGroupTy NewAG; 3577 AliasGroupTy &AG = AliasGroups[u]; 3578 AliasGroupTy::iterator AGI = AG.begin(); 3579 isl::set AGDomain = getAccessDomain(*AGI); 3580 while (AGI != AG.end()) { 3581 MemoryAccess *MA = *AGI; 3582 isl::set MADomain = getAccessDomain(MA); 3583 if (AGDomain.is_disjoint(MADomain)) { 3584 NewAG.push_back(MA); 3585 AGI = AG.erase(AGI); 3586 } else { 3587 AGDomain = AGDomain.unite(MADomain); 3588 AGI++; 3589 } 3590 } 3591 if (NewAG.size() > 1) 3592 AliasGroups.push_back(std::move(NewAG)); 3593 } 3594 } 3595 3596 #ifndef NDEBUG 3597 static void verifyUse(Scop *S, Use &Op, LoopInfo &LI) { 3598 auto PhysUse = VirtualUse::create(S, Op, &LI, false); 3599 auto VirtUse = VirtualUse::create(S, Op, &LI, true); 3600 assert(PhysUse.getKind() == VirtUse.getKind()); 3601 } 3602 3603 /// Check the consistency of every statement's MemoryAccesses. 3604 /// 3605 /// The check is carried out by expecting the "physical" kind of use (derived 3606 /// from the BasicBlocks instructions resides in) to be same as the "virtual" 3607 /// kind of use (derived from a statement's MemoryAccess). 3608 /// 3609 /// The "physical" uses are taken by ensureValueRead to determine whether to 3610 /// create MemoryAccesses. When done, the kind of scalar access should be the 3611 /// same no matter which way it was derived. 3612 /// 3613 /// The MemoryAccesses might be changed by later SCoP-modifying passes and hence 3614 /// can intentionally influence on the kind of uses (not corresponding to the 3615 /// "physical" anymore, hence called "virtual"). The CodeGenerator therefore has 3616 /// to pick up the virtual uses. But here in the code generator, this has not 3617 /// happened yet, such that virtual and physical uses are equivalent. 3618 static void verifyUses(Scop *S, LoopInfo &LI, DominatorTree &DT) { 3619 for (auto *BB : S->getRegion().blocks()) { 3620 for (auto &Inst : *BB) { 3621 auto *Stmt = S->getStmtFor(&Inst); 3622 if (!Stmt) 3623 continue; 3624 3625 if (isIgnoredIntrinsic(&Inst)) 3626 continue; 3627 3628 // Branch conditions are encoded in the statement domains. 3629 if (Inst.isTerminator() && Stmt->isBlockStmt()) 3630 continue; 3631 3632 // Verify all uses. 3633 for (auto &Op : Inst.operands()) 3634 verifyUse(S, Op, LI); 3635 3636 // Stores do not produce values used by other statements. 3637 if (isa<StoreInst>(Inst)) 3638 continue; 3639 3640 // For every value defined in the block, also check that a use of that 3641 // value in the same statement would not be an inter-statement use. It can 3642 // still be synthesizable or load-hoisted, but these kind of instructions 3643 // are not directly copied in code-generation. 3644 auto VirtDef = 3645 VirtualUse::create(S, Stmt, Stmt->getSurroundingLoop(), &Inst, true); 3646 assert(VirtDef.getKind() == VirtualUse::Synthesizable || 3647 VirtDef.getKind() == VirtualUse::Intra || 3648 VirtDef.getKind() == VirtualUse::Hoisted); 3649 } 3650 } 3651 3652 if (S->hasSingleExitEdge()) 3653 return; 3654 3655 // PHINodes in the SCoP region's exit block are also uses to be checked. 3656 if (!S->getRegion().isTopLevelRegion()) { 3657 for (auto &Inst : *S->getRegion().getExit()) { 3658 if (!isa<PHINode>(Inst)) 3659 break; 3660 3661 for (auto &Op : Inst.operands()) 3662 verifyUse(S, Op, LI); 3663 } 3664 } 3665 } 3666 #endif 3667 3668 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC) { 3669 scop.reset(new Scop(R, SE, LI, DT, *SD.getDetectionContext(&R), ORE, 3670 SD.getNextID())); 3671 3672 buildStmts(R); 3673 3674 // Create all invariant load instructions first. These are categorized as 3675 // 'synthesizable', therefore are not part of any ScopStmt but need to be 3676 // created somewhere. 3677 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 3678 for (BasicBlock *BB : scop->getRegion().blocks()) { 3679 if (SD.isErrorBlock(*BB, scop->getRegion())) 3680 continue; 3681 3682 for (Instruction &Inst : *BB) { 3683 LoadInst *Load = dyn_cast<LoadInst>(&Inst); 3684 if (!Load) 3685 continue; 3686 3687 if (!RIL.count(Load)) 3688 continue; 3689 3690 // Invariant loads require a MemoryAccess to be created in some statement. 3691 // It is not important to which statement the MemoryAccess is added 3692 // because it will later be removed from the ScopStmt again. We chose the 3693 // first statement of the basic block the LoadInst is in. 3694 ArrayRef<ScopStmt *> List = scop->getStmtListFor(BB); 3695 assert(!List.empty()); 3696 ScopStmt *RILStmt = List.front(); 3697 buildMemoryAccess(Load, RILStmt); 3698 } 3699 } 3700 buildAccessFunctions(); 3701 3702 // In case the region does not have an exiting block we will later (during 3703 // code generation) split the exit block. This will move potential PHI nodes 3704 // from the current exit block into the new region exiting block. Hence, PHI 3705 // nodes that are at this point not part of the region will be. 3706 // To handle these PHI nodes later we will now model their operands as scalar 3707 // accesses. Note that we do not model anything in the exit block if we have 3708 // an exiting block in the region, as there will not be any splitting later. 3709 if (!R.isTopLevelRegion() && !scop->hasSingleExitEdge()) { 3710 for (Instruction &Inst : *R.getExit()) { 3711 PHINode *PHI = dyn_cast<PHINode>(&Inst); 3712 if (!PHI) 3713 break; 3714 3715 buildPHIAccesses(nullptr, PHI, nullptr, true); 3716 } 3717 } 3718 3719 // Create memory accesses for global reads since all arrays are now known. 3720 auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0); 3721 for (auto GlobalReadPair : GlobalReads) { 3722 ScopStmt *GlobalReadStmt = GlobalReadPair.first; 3723 Instruction *GlobalRead = GlobalReadPair.second; 3724 for (auto *BP : ArrayBasePointers) 3725 addArrayAccess(GlobalReadStmt, MemAccInst(GlobalRead), MemoryAccess::READ, 3726 BP, BP->getType(), false, {AF}, {nullptr}, GlobalRead); 3727 } 3728 3729 buildInvariantEquivalenceClasses(); 3730 3731 /// A map from basic blocks to their invalid domains. 3732 DenseMap<BasicBlock *, isl::set> InvalidDomainMap; 3733 3734 if (!buildDomains(&R, InvalidDomainMap)) { 3735 LLVM_DEBUG( 3736 dbgs() << "Bailing-out because buildDomains encountered problems\n"); 3737 return; 3738 } 3739 3740 addUserAssumptions(AC, InvalidDomainMap); 3741 3742 // Initialize the invalid domain. 3743 for (ScopStmt &Stmt : scop->Stmts) 3744 if (Stmt.isBlockStmt()) 3745 Stmt.setInvalidDomain(InvalidDomainMap[Stmt.getEntryBlock()]); 3746 else 3747 Stmt.setInvalidDomain(InvalidDomainMap[getRegionNodeBasicBlock( 3748 Stmt.getRegion()->getNode())]); 3749 3750 // Remove empty statements. 3751 // Exit early in case there are no executable statements left in this scop. 3752 scop->removeStmtNotInDomainMap(); 3753 scop->simplifySCoP(false); 3754 if (scop->isEmpty()) { 3755 LLVM_DEBUG(dbgs() << "Bailing-out because SCoP is empty\n"); 3756 return; 3757 } 3758 3759 // The ScopStmts now have enough information to initialize themselves. 3760 for (ScopStmt &Stmt : *scop) { 3761 collectSurroundingLoops(Stmt); 3762 3763 buildDomain(Stmt); 3764 buildAccessRelations(Stmt); 3765 3766 if (DetectReductions) 3767 checkForReductions(Stmt); 3768 } 3769 3770 // Check early for a feasible runtime context. 3771 if (!scop->hasFeasibleRuntimeContext()) { 3772 LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (early)\n"); 3773 return; 3774 } 3775 3776 // Check early for profitability. Afterwards it cannot change anymore, 3777 // only the runtime context could become infeasible. 3778 if (!scop->isProfitable(UnprofitableScalarAccs)) { 3779 scop->invalidate(PROFITABLE, DebugLoc()); 3780 LLVM_DEBUG( 3781 dbgs() << "Bailing-out because SCoP is not considered profitable\n"); 3782 return; 3783 } 3784 3785 buildSchedule(); 3786 3787 finalizeAccesses(); 3788 3789 scop->realignParams(); 3790 addUserContext(); 3791 3792 // After the context was fully constructed, thus all our knowledge about 3793 // the parameters is in there, we add all recorded assumptions to the 3794 // assumed/invalid context. 3795 addRecordedAssumptions(); 3796 3797 scop->simplifyContexts(); 3798 if (!buildAliasChecks()) { 3799 LLVM_DEBUG(dbgs() << "Bailing-out because could not build alias checks\n"); 3800 return; 3801 } 3802 3803 hoistInvariantLoads(); 3804 canonicalizeDynamicBasePtrs(); 3805 verifyInvariantLoads(); 3806 scop->simplifySCoP(true); 3807 3808 // Check late for a feasible runtime context because profitability did not 3809 // change. 3810 if (!scop->hasFeasibleRuntimeContext()) { 3811 LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (late)\n"); 3812 return; 3813 } 3814 3815 #ifndef NDEBUG 3816 verifyUses(scop.get(), LI, DT); 3817 #endif 3818 } 3819 3820 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA, 3821 const DataLayout &DL, DominatorTree &DT, LoopInfo &LI, 3822 ScopDetection &SD, ScalarEvolution &SE, 3823 OptimizationRemarkEmitter &ORE) 3824 : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE), ORE(ORE) { 3825 DebugLoc Beg, End; 3826 auto P = getBBPairForRegion(R); 3827 getDebugLocations(P, Beg, End); 3828 3829 std::string Msg = "SCoP begins here."; 3830 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEntry", Beg, P.first) 3831 << Msg); 3832 3833 buildScop(*R, AC); 3834 3835 LLVM_DEBUG(dbgs() << *scop); 3836 3837 if (!scop->hasFeasibleRuntimeContext()) { 3838 InfeasibleScops++; 3839 Msg = "SCoP ends here but was dismissed."; 3840 LLVM_DEBUG(dbgs() << "SCoP detected but dismissed\n"); 3841 RecordedAssumptions.clear(); 3842 scop.reset(); 3843 } else { 3844 Msg = "SCoP ends here."; 3845 ++ScopFound; 3846 if (scop->getMaxLoopDepth() > 0) 3847 ++RichScopFound; 3848 } 3849 3850 if (R->isTopLevelRegion()) 3851 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.first) 3852 << Msg); 3853 else 3854 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.second) 3855 << Msg); 3856 } 3857