1 //===--------- ScopInfo.cpp ----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Create a polyhedral description for a static control flow region. 11 // 12 // The pass creates a polyhedral description of the Scops detected by the Scop 13 // detection derived from their LLVM-IR code. 14 // 15 // This representation is shared among several tools in the polyhedral 16 // community, which are e.g. Cloog, Pluto, Loopo, Graphite. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "polly/ScopInfo.h" 21 #include "polly/LinkAllPasses.h" 22 #include "polly/Options.h" 23 #include "polly/ScopBuilder.h" 24 #include "polly/Support/GICHelper.h" 25 #include "polly/Support/SCEVValidator.h" 26 #include "polly/Support/ScopHelper.h" 27 #include "llvm/ADT/DepthFirstIterator.h" 28 #include "llvm/ADT/MapVector.h" 29 #include "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/StringExtras.h" 34 #include "llvm/Analysis/AliasAnalysis.h" 35 #include "llvm/Analysis/AssumptionCache.h" 36 #include "llvm/Analysis/Loads.h" 37 #include "llvm/Analysis/LoopInfo.h" 38 #include "llvm/Analysis/LoopIterator.h" 39 #include "llvm/Analysis/RegionIterator.h" 40 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 41 #include "llvm/IR/DiagnosticInfo.h" 42 #include "llvm/Support/Debug.h" 43 #include "isl/aff.h" 44 #include "isl/constraint.h" 45 #include "isl/local_space.h" 46 #include "isl/map.h" 47 #include "isl/options.h" 48 #include "isl/printer.h" 49 #include "isl/schedule.h" 50 #include "isl/schedule_node.h" 51 #include "isl/set.h" 52 #include "isl/union_map.h" 53 #include "isl/union_set.h" 54 #include "isl/val.h" 55 #include <sstream> 56 #include <string> 57 #include <vector> 58 59 using namespace llvm; 60 using namespace polly; 61 62 #define DEBUG_TYPE "polly-scops" 63 64 // The maximal number of basic sets we allow during domain construction to 65 // be created. More complex scops will result in very high compile time and 66 // are also unlikely to result in good code 67 static int const MaxDisjunctionsInDomain = 20; 68 69 static cl::opt<bool> PollyRemarksMinimal( 70 "polly-remarks-minimal", 71 cl::desc("Do not emit remarks about assumptions that are known"), 72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory)); 73 74 // Multiplicative reductions can be disabled separately as these kind of 75 // operations can overflow easily. Additive reductions and bit operations 76 // are in contrast pretty stable. 77 static cl::opt<bool> DisableMultiplicativeReductions( 78 "polly-disable-multiplicative-reductions", 79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore, 80 cl::init(false), cl::cat(PollyCategory)); 81 82 static cl::opt<unsigned> RunTimeChecksMaxParameters( 83 "polly-rtc-max-parameters", 84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden, 85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 86 87 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup( 88 "polly-rtc-max-arrays-per-group", 89 cl::desc("The maximal number of arrays to compare in each alias group."), 90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory)); 91 92 static cl::opt<std::string> UserContextStr( 93 "polly-context", cl::value_desc("isl parameter set"), 94 cl::desc("Provide additional constraints on the context parameters"), 95 cl::init(""), cl::cat(PollyCategory)); 96 97 static cl::opt<bool> DetectReductions("polly-detect-reductions", 98 cl::desc("Detect and exploit reductions"), 99 cl::Hidden, cl::ZeroOrMore, 100 cl::init(true), cl::cat(PollyCategory)); 101 102 static cl::opt<bool> 103 IslOnErrorAbort("polly-on-isl-error-abort", 104 cl::desc("Abort if an isl error is encountered"), 105 cl::init(true), cl::cat(PollyCategory)); 106 107 static cl::opt<bool> UnprofitableScalarAccs( 108 "polly-unprofitable-scalar-accs", 109 cl::desc("Count statements with scalar accesses as not optimizable"), 110 cl::Hidden, cl::init(true), cl::cat(PollyCategory)); 111 112 //===----------------------------------------------------------------------===// 113 114 // Create a sequence of two schedules. Either argument may be null and is 115 // interpreted as the empty schedule. Can also return null if both schedules are 116 // empty. 117 static __isl_give isl_schedule * 118 combineInSequence(__isl_take isl_schedule *Prev, 119 __isl_take isl_schedule *Succ) { 120 if (!Prev) 121 return Succ; 122 if (!Succ) 123 return Prev; 124 125 return isl_schedule_sequence(Prev, Succ); 126 } 127 128 static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S, 129 const ConstantRange &Range, 130 int dim, 131 enum isl_dim_type type) { 132 isl_val *V; 133 isl_ctx *ctx = isl_set_get_ctx(S); 134 135 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet(); 136 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin(); 137 V = isl_valFromAPInt(ctx, LB, true); 138 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V); 139 140 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax(); 141 V = isl_valFromAPInt(ctx, UB, true); 142 if (useLowerUpperBound) 143 V = isl_val_sub_ui(V, 1); 144 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V); 145 146 if (useLowerUpperBound) 147 return isl_set_union(SLB, SUB); 148 else 149 return isl_set_intersect(SLB, SUB); 150 } 151 152 static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) { 153 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr); 154 if (!BasePtrLI) 155 return nullptr; 156 157 if (!S->contains(BasePtrLI)) 158 return nullptr; 159 160 ScalarEvolution &SE = *S->getSE(); 161 162 auto *OriginBaseSCEV = 163 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand())); 164 if (!OriginBaseSCEV) 165 return nullptr; 166 167 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV); 168 if (!OriginBaseSCEVUnknown) 169 return nullptr; 170 171 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(), 172 ScopArrayInfo::MK_Array); 173 } 174 175 ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx, 176 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind, 177 const DataLayout &DL, Scop *S, 178 const char *BaseName) 179 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) { 180 std::string BasePtrName = 181 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr, 182 Kind == MK_PHI ? "__phi" : ""); 183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this); 184 185 updateSizes(Sizes); 186 187 if (!BasePtr || Kind != MK_Array) { 188 BasePtrOriginSAI = nullptr; 189 return; 190 } 191 192 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr); 193 if (BasePtrOriginSAI) 194 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this); 195 } 196 197 __isl_give isl_space *ScopArrayInfo::getSpace() const { 198 auto *Space = 199 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions()); 200 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id)); 201 return Space; 202 } 203 204 bool ScopArrayInfo::isReadOnly() { 205 isl_union_set *WriteSet = isl_union_map_range(S.getWrites()); 206 isl_space *Space = getSpace(); 207 WriteSet = isl_union_set_intersect( 208 WriteSet, isl_union_set_from_set(isl_set_universe(Space))); 209 210 bool IsReadOnly = isl_union_set_is_empty(WriteSet); 211 isl_union_set_free(WriteSet); 212 213 return IsReadOnly; 214 } 215 216 void ScopArrayInfo::updateElementType(Type *NewElementType) { 217 if (NewElementType == ElementType) 218 return; 219 220 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType); 221 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType); 222 223 if (NewElementSize == OldElementSize || NewElementSize == 0) 224 return; 225 226 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) { 227 ElementType = NewElementType; 228 } else { 229 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize); 230 ElementType = IntegerType::get(ElementType->getContext(), GCD); 231 } 232 } 233 234 bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) { 235 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size()); 236 int ExtraDimsNew = NewSizes.size() - SharedDims; 237 int ExtraDimsOld = DimensionSizes.size() - SharedDims; 238 239 for (int i = 0; i < SharedDims; i++) { 240 auto *NewSize = NewSizes[i + ExtraDimsNew]; 241 auto *KnownSize = DimensionSizes[i + ExtraDimsOld]; 242 if (NewSize && KnownSize && NewSize != KnownSize) 243 return false; 244 } 245 246 if (DimensionSizes.size() >= NewSizes.size()) 247 return true; 248 249 DimensionSizes.clear(); 250 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(), 251 NewSizes.end()); 252 for (isl_pw_aff *Size : DimensionSizesPw) 253 isl_pw_aff_free(Size); 254 DimensionSizesPw.clear(); 255 for (const SCEV *Expr : DimensionSizes) { 256 if (!Expr) { 257 DimensionSizesPw.push_back(nullptr); 258 continue; 259 } 260 isl_pw_aff *Size = S.getPwAffOnly(Expr); 261 DimensionSizesPw.push_back(Size); 262 } 263 return true; 264 } 265 266 ScopArrayInfo::~ScopArrayInfo() { 267 isl_id_free(Id); 268 for (isl_pw_aff *Size : DimensionSizesPw) 269 isl_pw_aff_free(Size); 270 } 271 272 std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); } 273 274 int ScopArrayInfo::getElemSizeInBytes() const { 275 return DL.getTypeAllocSize(ElementType); 276 } 277 278 __isl_give isl_id *ScopArrayInfo::getBasePtrId() const { 279 return isl_id_copy(Id); 280 } 281 282 void ScopArrayInfo::dump() const { print(errs()); } 283 284 void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const { 285 OS.indent(8) << *getElementType() << " " << getName(); 286 unsigned u = 0; 287 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) { 288 OS << "[*]"; 289 u++; 290 } 291 for (; u < getNumberOfDimensions(); u++) { 292 OS << "["; 293 294 if (SizeAsPwAff) { 295 auto *Size = getDimensionSizePw(u); 296 OS << " " << Size << " "; 297 isl_pw_aff_free(Size); 298 } else { 299 OS << *getDimensionSize(u); 300 } 301 302 OS << "]"; 303 } 304 305 OS << ";"; 306 307 if (BasePtrOriginSAI) 308 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]"; 309 310 OS << " // Element size " << getElemSizeInBytes() << "\n"; 311 } 312 313 const ScopArrayInfo * 314 ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) { 315 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out); 316 assert(Id && "Output dimension didn't have an ID"); 317 return getFromId(Id); 318 } 319 320 const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) { 321 void *User = isl_id_get_user(Id); 322 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 323 isl_id_free(Id); 324 return SAI; 325 } 326 327 void MemoryAccess::wrapConstantDimensions() { 328 auto *SAI = getScopArrayInfo(); 329 auto *ArraySpace = SAI->getSpace(); 330 auto *Ctx = isl_space_get_ctx(ArraySpace); 331 unsigned DimsArray = SAI->getNumberOfDimensions(); 332 333 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range( 334 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace))); 335 auto *LArraySpace = isl_local_space_from_space(ArraySpace); 336 337 // Begin with last dimension, to iteratively carry into higher dimensions. 338 for (int i = DimsArray - 1; i > 0; i--) { 339 auto *DimSize = SAI->getDimensionSize(i); 340 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize); 341 342 // This transformation is not applicable to dimensions with dynamic size. 343 if (!DimSizeCst) 344 continue; 345 346 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false); 347 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace), 348 isl_dim_set, i); 349 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace), 350 isl_dim_set, i - 1); 351 352 // Compute: index % size 353 // Modulo must apply in the divide of the previous iteration, if any. 354 auto *Modulo = isl_aff_copy(Var); 355 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal)); 356 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff)); 357 358 // Compute: floor(index / size) 359 auto *Divide = Var; 360 Divide = isl_aff_div( 361 Divide, 362 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal)); 363 Divide = isl_aff_floor(Divide); 364 Divide = isl_aff_add(Divide, PrevVar); 365 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff)); 366 367 // Apply Modulo and Divide. 368 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo); 369 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide); 370 } 371 372 // Apply all modulo/divides on the accesses. 373 AccessRelation = 374 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff)); 375 AccessRelation = isl_map_detect_equalities(AccessRelation); 376 isl_local_space_free(LArraySpace); 377 } 378 379 void MemoryAccess::updateDimensionality() { 380 auto *SAI = getScopArrayInfo(); 381 auto *ArraySpace = SAI->getSpace(); 382 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation)); 383 auto *Ctx = isl_space_get_ctx(AccessSpace); 384 385 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set); 386 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set); 387 auto DimsMissing = DimsArray - DimsAccess; 388 389 auto *BB = getStatement()->getEntryBlock(); 390 auto &DL = BB->getModule()->getDataLayout(); 391 unsigned ArrayElemSize = SAI->getElemSizeInBytes(); 392 unsigned ElemBytes = DL.getTypeAllocSize(getElementType()); 393 394 auto *Map = isl_map_from_domain_and_range( 395 isl_set_universe(AccessSpace), 396 isl_set_universe(isl_space_copy(ArraySpace))); 397 398 for (unsigned i = 0; i < DimsMissing; i++) 399 Map = isl_map_fix_si(Map, isl_dim_out, i, 0); 400 401 for (unsigned i = DimsMissing; i < DimsArray; i++) 402 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i); 403 404 AccessRelation = isl_map_apply_range(AccessRelation, Map); 405 406 // For the non delinearized arrays, divide the access function of the last 407 // subscript by the size of the elements in the array. 408 // 409 // A stride one array access in C expressed as A[i] is expressed in 410 // LLVM-IR as something like A[i * elementsize]. This hides the fact that 411 // two subsequent values of 'i' index two values that are stored next to 412 // each other in memory. By this division we make this characteristic 413 // obvious again. If the base pointer was accessed with offsets not divisible 414 // by the accesses element size, we will have chosen a smaller ArrayElemSize 415 // that divides the offsets of all accesses to this base pointer. 416 if (DimsAccess == 1) { 417 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize); 418 AccessRelation = isl_map_floordiv_val(AccessRelation, V); 419 } 420 421 // We currently do this only if we added at least one dimension, which means 422 // some dimension's indices have not been specified, an indicator that some 423 // index values have been added together. 424 // TODO: Investigate general usefulness; Effect on unit tests is to make index 425 // expressions more complicated. 426 if (DimsMissing) 427 wrapConstantDimensions(); 428 429 if (!isAffine()) 430 computeBoundsOnAccessRelation(ArrayElemSize); 431 432 // Introduce multi-element accesses in case the type loaded by this memory 433 // access is larger than the canonical element type of the array. 434 // 435 // An access ((float *)A)[i] to an array char *A is modeled as 436 // {[i] -> A[o] : 4 i <= o <= 4 i + 3 437 if (ElemBytes > ArrayElemSize) { 438 assert(ElemBytes % ArrayElemSize == 0 && 439 "Loaded element size should be multiple of canonical element size"); 440 auto *Map = isl_map_from_domain_and_range( 441 isl_set_universe(isl_space_copy(ArraySpace)), 442 isl_set_universe(isl_space_copy(ArraySpace))); 443 for (unsigned i = 0; i < DimsArray - 1; i++) 444 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i); 445 446 isl_constraint *C; 447 isl_local_space *LS; 448 449 LS = isl_local_space_from_space(isl_map_get_space(Map)); 450 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes(); 451 452 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS)); 453 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1)); 454 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1); 455 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1); 456 Map = isl_map_add_constraint(Map, C); 457 458 C = isl_constraint_alloc_inequality(LS); 459 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1); 460 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1); 461 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0)); 462 Map = isl_map_add_constraint(Map, C); 463 AccessRelation = isl_map_apply_range(AccessRelation, Map); 464 } 465 466 isl_space_free(ArraySpace); 467 468 assumeNoOutOfBound(); 469 } 470 471 const std::string 472 MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) { 473 switch (RT) { 474 case MemoryAccess::RT_NONE: 475 llvm_unreachable("Requested a reduction operator string for a memory " 476 "access which isn't a reduction"); 477 case MemoryAccess::RT_ADD: 478 return "+"; 479 case MemoryAccess::RT_MUL: 480 return "*"; 481 case MemoryAccess::RT_BOR: 482 return "|"; 483 case MemoryAccess::RT_BXOR: 484 return "^"; 485 case MemoryAccess::RT_BAND: 486 return "&"; 487 } 488 llvm_unreachable("Unknown reduction type"); 489 return ""; 490 } 491 492 /// Return the reduction type for a given binary operator. 493 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp, 494 const Instruction *Load) { 495 if (!BinOp) 496 return MemoryAccess::RT_NONE; 497 switch (BinOp->getOpcode()) { 498 case Instruction::FAdd: 499 if (!BinOp->hasUnsafeAlgebra()) 500 return MemoryAccess::RT_NONE; 501 // Fall through 502 case Instruction::Add: 503 return MemoryAccess::RT_ADD; 504 case Instruction::Or: 505 return MemoryAccess::RT_BOR; 506 case Instruction::Xor: 507 return MemoryAccess::RT_BXOR; 508 case Instruction::And: 509 return MemoryAccess::RT_BAND; 510 case Instruction::FMul: 511 if (!BinOp->hasUnsafeAlgebra()) 512 return MemoryAccess::RT_NONE; 513 // Fall through 514 case Instruction::Mul: 515 if (DisableMultiplicativeReductions) 516 return MemoryAccess::RT_NONE; 517 return MemoryAccess::RT_MUL; 518 default: 519 return MemoryAccess::RT_NONE; 520 } 521 } 522 523 MemoryAccess::~MemoryAccess() { 524 isl_id_free(Id); 525 isl_set_free(InvalidDomain); 526 isl_map_free(AccessRelation); 527 isl_map_free(NewAccessRelation); 528 } 529 530 const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const { 531 isl_id *ArrayId = getArrayId(); 532 void *User = isl_id_get_user(ArrayId); 533 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 534 isl_id_free(ArrayId); 535 return SAI; 536 } 537 538 const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const { 539 isl_id *ArrayId = getLatestArrayId(); 540 void *User = isl_id_get_user(ArrayId); 541 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 542 isl_id_free(ArrayId); 543 return SAI; 544 } 545 546 __isl_give isl_id *MemoryAccess::getOriginalArrayId() const { 547 return isl_map_get_tuple_id(AccessRelation, isl_dim_out); 548 } 549 550 __isl_give isl_id *MemoryAccess::getLatestArrayId() const { 551 if (!hasNewAccessRelation()) 552 return getOriginalArrayId(); 553 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out); 554 } 555 556 __isl_give isl_map *MemoryAccess::getAddressFunction() const { 557 return isl_map_lexmin(getAccessRelation()); 558 } 559 560 __isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation( 561 __isl_take isl_union_map *USchedule) const { 562 isl_map *Schedule, *ScheduledAccRel; 563 isl_union_set *UDomain; 564 565 UDomain = isl_union_set_from_set(getStatement()->getDomain()); 566 USchedule = isl_union_map_intersect_domain(USchedule, UDomain); 567 Schedule = isl_map_from_union_map(USchedule); 568 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule); 569 return isl_pw_multi_aff_from_map(ScheduledAccRel); 570 } 571 572 __isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const { 573 return isl_map_copy(AccessRelation); 574 } 575 576 std::string MemoryAccess::getOriginalAccessRelationStr() const { 577 return stringFromIslObj(AccessRelation); 578 } 579 580 __isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const { 581 return isl_map_get_space(AccessRelation); 582 } 583 584 __isl_give isl_map *MemoryAccess::getNewAccessRelation() const { 585 return isl_map_copy(NewAccessRelation); 586 } 587 588 std::string MemoryAccess::getNewAccessRelationStr() const { 589 return stringFromIslObj(NewAccessRelation); 590 } 591 592 __isl_give isl_basic_map * 593 MemoryAccess::createBasicAccessMap(ScopStmt *Statement) { 594 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1); 595 Space = isl_space_align_params(Space, Statement->getDomainSpace()); 596 597 return isl_basic_map_from_domain_and_range( 598 isl_basic_set_universe(Statement->getDomainSpace()), 599 isl_basic_set_universe(Space)); 600 } 601 602 // Formalize no out-of-bound access assumption 603 // 604 // When delinearizing array accesses we optimistically assume that the 605 // delinearized accesses do not access out of bound locations (the subscript 606 // expression of each array evaluates for each statement instance that is 607 // executed to a value that is larger than zero and strictly smaller than the 608 // size of the corresponding dimension). The only exception is the outermost 609 // dimension for which we do not need to assume any upper bound. At this point 610 // we formalize this assumption to ensure that at code generation time the 611 // relevant run-time checks can be generated. 612 // 613 // To find the set of constraints necessary to avoid out of bound accesses, we 614 // first build the set of data locations that are not within array bounds. We 615 // then apply the reverse access relation to obtain the set of iterations that 616 // may contain invalid accesses and reduce this set of iterations to the ones 617 // that are actually executed by intersecting them with the domain of the 618 // statement. If we now project out all loop dimensions, we obtain a set of 619 // parameters that may cause statement instances to be executed that may 620 // possibly yield out of bound memory accesses. The complement of these 621 // constraints is the set of constraints that needs to be assumed to ensure such 622 // statement instances are never executed. 623 void MemoryAccess::assumeNoOutOfBound() { 624 auto *SAI = getScopArrayInfo(); 625 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace()); 626 isl_set *Outside = isl_set_empty(isl_space_copy(Space)); 627 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) { 628 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space)); 629 isl_pw_aff *Var = 630 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i); 631 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS); 632 633 isl_set *DimOutside; 634 635 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero); 636 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i); 637 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in, 638 isl_space_dim(Space, isl_dim_set)); 639 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in, 640 isl_space_get_tuple_id(Space, isl_dim_set)); 641 642 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var)); 643 644 Outside = isl_set_union(Outside, DimOutside); 645 } 646 647 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation())); 648 Outside = isl_set_intersect(Outside, Statement->getDomain()); 649 Outside = isl_set_params(Outside); 650 651 // Remove divs to avoid the construction of overly complicated assumptions. 652 // Doing so increases the set of parameter combinations that are assumed to 653 // not appear. This is always save, but may make the resulting run-time check 654 // bail out more often than strictly necessary. 655 Outside = isl_set_remove_divs(Outside); 656 Outside = isl_set_complement(Outside); 657 const auto &Loc = getAccessInstruction() 658 ? getAccessInstruction()->getDebugLoc() 659 : DebugLoc(); 660 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc, 661 AS_ASSUMPTION); 662 isl_space_free(Space); 663 } 664 665 void MemoryAccess::buildMemIntrinsicAccessRelation() { 666 assert(isa<MemIntrinsic>(getAccessInstruction())); 667 assert(Subscripts.size() == 2 && Sizes.size() == 1); 668 669 auto *SubscriptPWA = getPwAff(Subscripts[0]); 670 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA); 671 672 isl_map *LengthMap; 673 if (Subscripts[1] == nullptr) { 674 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap)); 675 } else { 676 auto *LengthPWA = getPwAff(Subscripts[1]); 677 LengthMap = isl_map_from_pw_aff(LengthPWA); 678 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap)); 679 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace)); 680 } 681 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0); 682 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap)); 683 SubscriptMap = 684 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap)); 685 LengthMap = isl_map_sum(LengthMap, SubscriptMap); 686 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in, 687 getStatement()->getDomainId()); 688 } 689 690 void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) { 691 ScalarEvolution *SE = Statement->getParent()->getSE(); 692 693 auto MAI = MemAccInst(getAccessInstruction()); 694 if (isa<MemIntrinsic>(MAI)) 695 return; 696 697 Value *Ptr = MAI.getPointerOperand(); 698 if (!Ptr || !SE->isSCEVable(Ptr->getType())) 699 return; 700 701 auto *PtrSCEV = SE->getSCEV(Ptr); 702 if (isa<SCEVCouldNotCompute>(PtrSCEV)) 703 return; 704 705 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV); 706 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV)) 707 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV); 708 709 const ConstantRange &Range = SE->getSignedRange(PtrSCEV); 710 if (Range.isFullSet()) 711 return; 712 713 bool isWrapping = Range.isSignWrappedSet(); 714 unsigned BW = Range.getBitWidth(); 715 const auto One = APInt(BW, 1); 716 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin(); 717 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax(); 718 719 auto Min = LB.sdiv(APInt(BW, ElementSize)); 720 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One; 721 722 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation)); 723 AccessRange = 724 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set); 725 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange); 726 } 727 728 __isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation, 729 ScopStmt *Statement) { 730 int Size = Subscripts.size(); 731 732 for (int i = Size - 2; i >= 0; --i) { 733 isl_space *Space; 734 isl_map *MapOne, *MapTwo; 735 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]); 736 737 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize); 738 isl_pw_aff_free(DimSize); 739 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0); 740 741 Space = isl_map_get_space(AccessRelation); 742 Space = isl_space_map_from_set(isl_space_range(Space)); 743 Space = isl_space_align_params(Space, SpaceSize); 744 745 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId); 746 isl_id_free(ParamId); 747 748 MapOne = isl_map_universe(isl_space_copy(Space)); 749 for (int j = 0; j < Size; ++j) 750 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j); 751 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0); 752 753 MapTwo = isl_map_universe(isl_space_copy(Space)); 754 for (int j = 0; j < Size; ++j) 755 if (j < i || j > i + 1) 756 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j); 757 758 isl_local_space *LS = isl_local_space_from_space(Space); 759 isl_constraint *C; 760 C = isl_equality_alloc(isl_local_space_copy(LS)); 761 C = isl_constraint_set_constant_si(C, -1); 762 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1); 763 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1); 764 MapTwo = isl_map_add_constraint(MapTwo, C); 765 C = isl_equality_alloc(LS); 766 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1); 767 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1); 768 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1); 769 MapTwo = isl_map_add_constraint(MapTwo, C); 770 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1); 771 772 MapOne = isl_map_union(MapOne, MapTwo); 773 AccessRelation = isl_map_apply_range(AccessRelation, MapOne); 774 } 775 return AccessRelation; 776 } 777 778 /// Check if @p Expr is divisible by @p Size. 779 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) { 780 assert(Size != 0); 781 if (Size == 1) 782 return true; 783 784 // Only one factor needs to be divisible. 785 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) { 786 for (auto *FactorExpr : MulExpr->operands()) 787 if (isDivisible(FactorExpr, Size, SE)) 788 return true; 789 return false; 790 } 791 792 // For other n-ary expressions (Add, AddRec, Max,...) all operands need 793 // to be divisble. 794 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) { 795 for (auto *OpExpr : NAryExpr->operands()) 796 if (!isDivisible(OpExpr, Size, SE)) 797 return false; 798 return true; 799 } 800 801 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size); 802 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV); 803 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV); 804 return MulSCEV == Expr; 805 } 806 807 void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) { 808 assert(!AccessRelation && "AccessReltation already built"); 809 810 // Initialize the invalid domain which describes all iterations for which the 811 // access relation is not modeled correctly. 812 auto *StmtInvalidDomain = getStatement()->getInvalidDomain(); 813 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain)); 814 isl_set_free(StmtInvalidDomain); 815 816 isl_ctx *Ctx = isl_id_get_ctx(Id); 817 isl_id *BaseAddrId = SAI->getBasePtrId(); 818 819 if (!isAffine()) { 820 if (isa<MemIntrinsic>(getAccessInstruction())) 821 buildMemIntrinsicAccessRelation(); 822 823 // We overapproximate non-affine accesses with a possible access to the 824 // whole array. For read accesses it does not make a difference, if an 825 // access must or may happen. However, for write accesses it is important to 826 // differentiate between writes that must happen and writes that may happen. 827 if (!AccessRelation) 828 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement)); 829 830 AccessRelation = 831 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId); 832 return; 833 } 834 835 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0); 836 AccessRelation = isl_map_universe(Space); 837 838 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) { 839 isl_pw_aff *Affine = getPwAff(Subscripts[i]); 840 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine); 841 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap); 842 } 843 844 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1])) 845 AccessRelation = foldAccess(AccessRelation, Statement); 846 847 Space = Statement->getDomainSpace(); 848 AccessRelation = isl_map_set_tuple_id( 849 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set)); 850 AccessRelation = 851 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId); 852 853 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain()); 854 isl_space_free(Space); 855 } 856 857 MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, 858 AccessType AccType, Value *BaseAddress, 859 Type *ElementType, bool Affine, 860 ArrayRef<const SCEV *> Subscripts, 861 ArrayRef<const SCEV *> Sizes, Value *AccessValue, 862 ScopArrayInfo::MemoryKind Kind, StringRef BaseName) 863 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt), 864 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName), 865 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()), 866 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine), 867 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr), 868 NewAccessRelation(nullptr) { 869 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"}; 870 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_"; 871 872 std::string IdName = 873 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName); 874 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this); 875 } 876 877 MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, 878 __isl_take isl_map *AccRel) 879 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType), 880 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr), 881 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr), 882 NewAccessRelation(AccRel) { 883 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out); 884 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId); 885 Sizes.push_back(nullptr); 886 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++) 887 Sizes.push_back(SAI->getDimensionSize(i)); 888 ElementType = SAI->getElementType(); 889 BaseAddr = SAI->getBasePtr(); 890 BaseName = SAI->getName(); 891 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"}; 892 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_"; 893 894 std::string IdName = 895 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName); 896 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this); 897 } 898 899 void MemoryAccess::realignParams() { 900 auto *Ctx = Statement->getParent()->getContext(); 901 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx)); 902 AccessRelation = isl_map_gist_params(AccessRelation, Ctx); 903 } 904 905 const std::string MemoryAccess::getReductionOperatorStr() const { 906 return MemoryAccess::getReductionOperatorStr(getReductionType()); 907 } 908 909 __isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); } 910 911 raw_ostream &polly::operator<<(raw_ostream &OS, 912 MemoryAccess::ReductionType RT) { 913 if (RT == MemoryAccess::RT_NONE) 914 OS << "NONE"; 915 else 916 OS << MemoryAccess::getReductionOperatorStr(RT); 917 return OS; 918 } 919 920 void MemoryAccess::print(raw_ostream &OS) const { 921 switch (AccType) { 922 case READ: 923 OS.indent(12) << "ReadAccess :=\t"; 924 break; 925 case MUST_WRITE: 926 OS.indent(12) << "MustWriteAccess :=\t"; 927 break; 928 case MAY_WRITE: 929 OS.indent(12) << "MayWriteAccess :=\t"; 930 break; 931 } 932 OS << "[Reduction Type: " << getReductionType() << "] "; 933 OS << "[Scalar: " << isScalarKind() << "]\n"; 934 OS.indent(16) << getOriginalAccessRelationStr() << ";\n"; 935 if (hasNewAccessRelation()) 936 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n"; 937 } 938 939 void MemoryAccess::dump() const { print(errs()); } 940 941 __isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) { 942 auto *Stmt = getStatement(); 943 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock()); 944 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain()); 945 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second); 946 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom); 947 return PWAC.first; 948 } 949 950 // Create a map in the size of the provided set domain, that maps from the 951 // one element of the provided set domain to another element of the provided 952 // set domain. 953 // The mapping is limited to all points that are equal in all but the last 954 // dimension and for which the last dimension of the input is strict smaller 955 // than the last dimension of the output. 956 // 957 // getEqualAndLarger(set[i0, i1, ..., iX]): 958 // 959 // set[i0, i1, ..., iX] -> set[o0, o1, ..., oX] 960 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX 961 // 962 static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) { 963 isl_space *Space = isl_space_map_from_set(setDomain); 964 isl_map *Map = isl_map_universe(Space); 965 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1; 966 967 // Set all but the last dimension to be equal for the input and output 968 // 969 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX] 970 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1) 971 for (unsigned i = 0; i < lastDimension; ++i) 972 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i); 973 974 // Set the last dimension of the input to be strict smaller than the 975 // last dimension of the output. 976 // 977 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX 978 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out, 979 lastDimension); 980 return Map; 981 } 982 983 __isl_give isl_set * 984 MemoryAccess::getStride(__isl_take const isl_map *Schedule) const { 985 isl_map *S = const_cast<isl_map *>(Schedule); 986 isl_map *AccessRelation = getAccessRelation(); 987 isl_space *Space = isl_space_range(isl_map_get_space(S)); 988 isl_map *NextScatt = getEqualAndLarger(Space); 989 990 S = isl_map_reverse(S); 991 NextScatt = isl_map_lexmin(NextScatt); 992 993 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S)); 994 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation)); 995 NextScatt = isl_map_apply_domain(NextScatt, S); 996 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation); 997 998 isl_set *Deltas = isl_map_deltas(NextScatt); 999 return Deltas; 1000 } 1001 1002 bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule, 1003 int StrideWidth) const { 1004 isl_set *Stride, *StrideX; 1005 bool IsStrideX; 1006 1007 Stride = getStride(Schedule); 1008 StrideX = isl_set_universe(isl_set_get_space(Stride)); 1009 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++) 1010 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0); 1011 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 1012 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth); 1013 IsStrideX = isl_set_is_subset(Stride, StrideX); 1014 1015 isl_set_free(StrideX); 1016 isl_set_free(Stride); 1017 1018 return IsStrideX; 1019 } 1020 1021 bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const { 1022 return isStrideX(Schedule, 0); 1023 } 1024 1025 bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const { 1026 return isStrideX(Schedule, 1); 1027 } 1028 1029 void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) { 1030 assert(NewAccess); 1031 1032 #ifndef NDEBUG 1033 // Check domain space compatibility. 1034 auto *NewSpace = isl_map_get_space(NewAccess); 1035 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace)); 1036 auto *OriginalDomainSpace = getStatement()->getDomainSpace(); 1037 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace)); 1038 isl_space_free(NewDomainSpace); 1039 isl_space_free(OriginalDomainSpace); 1040 1041 // Check whether there is an access for every statement instance. 1042 auto *StmtDomain = getStatement()->getDomain(); 1043 StmtDomain = isl_set_intersect_params( 1044 StmtDomain, getStatement()->getParent()->getContext()); 1045 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess)); 1046 assert(isl_set_is_subset(StmtDomain, NewDomain) && 1047 "Partial accesses not supported"); 1048 isl_set_free(NewDomain); 1049 isl_set_free(StmtDomain); 1050 1051 // Check whether access dimensions correspond to number of dimensions of the 1052 // accesses array. 1053 auto *NewAccessSpace = isl_space_range(NewSpace); 1054 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) && 1055 "Must specify the array that is accessed"); 1056 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set); 1057 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId)); 1058 assert(SAI && "Must set a ScopArrayInfo"); 1059 assert(!SAI->getBasePtrOriginSAI() && 1060 "Indirect array not supported by codegen"); 1061 auto Dims = SAI->getNumberOfDimensions(); 1062 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims && 1063 "Access dims must match array dims"); 1064 isl_space_free(NewAccessSpace); 1065 isl_id_free(NewArrayId); 1066 #endif 1067 1068 isl_map_free(NewAccessRelation); 1069 NewAccessRelation = NewAccess; 1070 } 1071 1072 //===----------------------------------------------------------------------===// 1073 1074 __isl_give isl_map *ScopStmt::getSchedule() const { 1075 isl_set *Domain = getDomain(); 1076 if (isl_set_is_empty(Domain)) { 1077 isl_set_free(Domain); 1078 return isl_map_from_aff( 1079 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace()))); 1080 } 1081 auto *Schedule = getParent()->getSchedule(); 1082 if (!Schedule) { 1083 isl_set_free(Domain); 1084 return nullptr; 1085 } 1086 Schedule = isl_union_map_intersect_domain( 1087 Schedule, isl_union_set_from_set(isl_set_copy(Domain))); 1088 if (isl_union_map_is_empty(Schedule)) { 1089 isl_set_free(Domain); 1090 isl_union_map_free(Schedule); 1091 return isl_map_from_aff( 1092 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace()))); 1093 } 1094 auto *M = isl_map_from_union_map(Schedule); 1095 M = isl_map_coalesce(M); 1096 M = isl_map_gist_domain(M, Domain); 1097 M = isl_map_coalesce(M); 1098 return M; 1099 } 1100 1101 __isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) { 1102 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative); 1103 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second); 1104 return PWAC.first; 1105 } 1106 1107 void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) { 1108 assert(isl_set_is_subset(NewDomain, Domain) && 1109 "New domain is not a subset of old domain!"); 1110 isl_set_free(Domain); 1111 Domain = NewDomain; 1112 } 1113 1114 void ScopStmt::buildAccessRelations() { 1115 Scop &S = *getParent(); 1116 for (MemoryAccess *Access : MemAccs) { 1117 Type *ElementType = Access->getElementType(); 1118 1119 ScopArrayInfo::MemoryKind Ty; 1120 if (Access->isPHIKind()) 1121 Ty = ScopArrayInfo::MK_PHI; 1122 else if (Access->isExitPHIKind()) 1123 Ty = ScopArrayInfo::MK_ExitPHI; 1124 else if (Access->isValueKind()) 1125 Ty = ScopArrayInfo::MK_Value; 1126 else 1127 Ty = ScopArrayInfo::MK_Array; 1128 1129 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType, 1130 Access->Sizes, Ty); 1131 Access->buildAccessRelation(SAI); 1132 } 1133 } 1134 1135 void ScopStmt::addAccess(MemoryAccess *Access) { 1136 Instruction *AccessInst = Access->getAccessInstruction(); 1137 1138 if (Access->isArrayKind()) { 1139 MemoryAccessList &MAL = InstructionToAccess[AccessInst]; 1140 MAL.emplace_front(Access); 1141 } else if (Access->isValueKind() && Access->isWrite()) { 1142 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue()); 1143 assert(Parent.getStmtFor(AccessVal) == this); 1144 assert(!ValueWrites.lookup(AccessVal)); 1145 1146 ValueWrites[AccessVal] = Access; 1147 } else if (Access->isValueKind() && Access->isRead()) { 1148 Value *AccessVal = Access->getAccessValue(); 1149 assert(!ValueReads.lookup(AccessVal)); 1150 1151 ValueReads[AccessVal] = Access; 1152 } else if (Access->isAnyPHIKind() && Access->isWrite()) { 1153 PHINode *PHI = cast<PHINode>(Access->getBaseAddr()); 1154 assert(!PHIWrites.lookup(PHI)); 1155 1156 PHIWrites[PHI] = Access; 1157 } 1158 1159 MemAccs.push_back(Access); 1160 } 1161 1162 void ScopStmt::realignParams() { 1163 for (MemoryAccess *MA : *this) 1164 MA->realignParams(); 1165 1166 auto *Ctx = Parent.getContext(); 1167 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx)); 1168 Domain = isl_set_gist_params(Domain, Ctx); 1169 } 1170 1171 /// Add @p BSet to the set @p User if @p BSet is bounded. 1172 static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet, 1173 void *User) { 1174 isl_set **BoundedParts = static_cast<isl_set **>(User); 1175 if (isl_basic_set_is_bounded(BSet)) 1176 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet)); 1177 else 1178 isl_basic_set_free(BSet); 1179 return isl_stat_ok; 1180 } 1181 1182 /// Return the bounded parts of @p S. 1183 static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) { 1184 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S)); 1185 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts); 1186 isl_set_free(S); 1187 return BoundedParts; 1188 } 1189 1190 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim. 1191 /// 1192 /// @returns A separation of @p S into first an unbounded then a bounded subset, 1193 /// both with regards to the dimension @p Dim. 1194 static std::pair<__isl_give isl_set *, __isl_give isl_set *> 1195 partitionSetParts(__isl_take isl_set *S, unsigned Dim) { 1196 1197 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++) 1198 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0); 1199 1200 unsigned NumDimsS = isl_set_n_dim(S); 1201 isl_set *OnlyDimS = isl_set_copy(S); 1202 1203 // Remove dimensions that are greater than Dim as they are not interesting. 1204 assert(NumDimsS >= Dim + 1); 1205 OnlyDimS = 1206 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1); 1207 1208 // Create artificial parametric upper bounds for dimensions smaller than Dim 1209 // as we are not interested in them. 1210 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim); 1211 for (unsigned u = 0; u < Dim; u++) { 1212 isl_constraint *C = isl_inequality_alloc( 1213 isl_local_space_from_space(isl_set_get_space(OnlyDimS))); 1214 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1); 1215 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1); 1216 OnlyDimS = isl_set_add_constraint(OnlyDimS, C); 1217 } 1218 1219 // Collect all bounded parts of OnlyDimS. 1220 isl_set *BoundedParts = collectBoundedParts(OnlyDimS); 1221 1222 // Create the dimensions greater than Dim again. 1223 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1, 1224 NumDimsS - Dim - 1); 1225 1226 // Remove the artificial upper bound parameters again. 1227 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim); 1228 1229 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts)); 1230 return std::make_pair(UnboundedParts, BoundedParts); 1231 } 1232 1233 /// Set the dimension Ids from @p From in @p To. 1234 static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From, 1235 __isl_take isl_set *To) { 1236 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) { 1237 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u); 1238 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId); 1239 } 1240 return To; 1241 } 1242 1243 /// Create the conditions under which @p L @p Pred @p R is true. 1244 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred, 1245 __isl_take isl_pw_aff *L, 1246 __isl_take isl_pw_aff *R) { 1247 switch (Pred) { 1248 case ICmpInst::ICMP_EQ: 1249 return isl_pw_aff_eq_set(L, R); 1250 case ICmpInst::ICMP_NE: 1251 return isl_pw_aff_ne_set(L, R); 1252 case ICmpInst::ICMP_SLT: 1253 return isl_pw_aff_lt_set(L, R); 1254 case ICmpInst::ICMP_SLE: 1255 return isl_pw_aff_le_set(L, R); 1256 case ICmpInst::ICMP_SGT: 1257 return isl_pw_aff_gt_set(L, R); 1258 case ICmpInst::ICMP_SGE: 1259 return isl_pw_aff_ge_set(L, R); 1260 case ICmpInst::ICMP_ULT: 1261 return isl_pw_aff_lt_set(L, R); 1262 case ICmpInst::ICMP_UGT: 1263 return isl_pw_aff_gt_set(L, R); 1264 case ICmpInst::ICMP_ULE: 1265 return isl_pw_aff_le_set(L, R); 1266 case ICmpInst::ICMP_UGE: 1267 return isl_pw_aff_ge_set(L, R); 1268 default: 1269 llvm_unreachable("Non integer predicate not supported"); 1270 } 1271 } 1272 1273 /// Create the conditions under which @p L @p Pred @p R is true. 1274 /// 1275 /// Helper function that will make sure the dimensions of the result have the 1276 /// same isl_id's as the @p Domain. 1277 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred, 1278 __isl_take isl_pw_aff *L, 1279 __isl_take isl_pw_aff *R, 1280 __isl_keep isl_set *Domain) { 1281 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R); 1282 return setDimensionIds(Domain, ConsequenceCondSet); 1283 } 1284 1285 /// Build the conditions sets for the switch @p SI in the @p Domain. 1286 /// 1287 /// This will fill @p ConditionSets with the conditions under which control 1288 /// will be moved from @p SI to its successors. Hence, @p ConditionSets will 1289 /// have as many elements as @p SI has successors. 1290 static bool 1291 buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L, 1292 __isl_keep isl_set *Domain, 1293 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1294 1295 Value *Condition = getConditionFromTerminator(SI); 1296 assert(Condition && "No condition for switch"); 1297 1298 Scop &S = *Stmt.getParent(); 1299 ScalarEvolution &SE = *S.getSE(); 1300 isl_pw_aff *LHS, *RHS; 1301 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L)); 1302 1303 unsigned NumSuccessors = SI->getNumSuccessors(); 1304 ConditionSets.resize(NumSuccessors); 1305 for (auto &Case : SI->cases()) { 1306 unsigned Idx = Case.getSuccessorIndex(); 1307 ConstantInt *CaseValue = Case.getCaseValue(); 1308 1309 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue)); 1310 isl_set *CaseConditionSet = 1311 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain); 1312 ConditionSets[Idx] = isl_set_coalesce( 1313 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain))); 1314 } 1315 1316 assert(ConditionSets[0] == nullptr && "Default condition set was set"); 1317 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]); 1318 for (unsigned u = 2; u < NumSuccessors; u++) 1319 ConditionSetUnion = 1320 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u])); 1321 ConditionSets[0] = setDimensionIds( 1322 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion)); 1323 1324 isl_pw_aff_free(LHS); 1325 1326 return true; 1327 } 1328 1329 /// Build the conditions sets for the branch condition @p Condition in 1330 /// the @p Domain. 1331 /// 1332 /// This will fill @p ConditionSets with the conditions under which control 1333 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will 1334 /// have as many elements as @p TI has successors. If @p TI is nullptr the 1335 /// context under which @p Condition is true/false will be returned as the 1336 /// new elements of @p ConditionSets. 1337 static bool 1338 buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI, 1339 Loop *L, __isl_keep isl_set *Domain, 1340 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1341 1342 Scop &S = *Stmt.getParent(); 1343 isl_set *ConsequenceCondSet = nullptr; 1344 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) { 1345 if (CCond->isZero()) 1346 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 1347 else 1348 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 1349 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 1350 auto Opcode = BinOp->getOpcode(); 1351 assert(Opcode == Instruction::And || Opcode == Instruction::Or); 1352 1353 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain, 1354 ConditionSets) && 1355 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain, 1356 ConditionSets); 1357 if (!Valid) { 1358 while (!ConditionSets.empty()) 1359 isl_set_free(ConditionSets.pop_back_val()); 1360 return false; 1361 } 1362 1363 isl_set_free(ConditionSets.pop_back_val()); 1364 isl_set *ConsCondPart0 = ConditionSets.pop_back_val(); 1365 isl_set_free(ConditionSets.pop_back_val()); 1366 isl_set *ConsCondPart1 = ConditionSets.pop_back_val(); 1367 1368 if (Opcode == Instruction::And) 1369 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1); 1370 else 1371 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1); 1372 } else { 1373 auto *ICond = dyn_cast<ICmpInst>(Condition); 1374 assert(ICond && 1375 "Condition of exiting branch was neither constant nor ICmp!"); 1376 1377 ScalarEvolution &SE = *S.getSE(); 1378 isl_pw_aff *LHS, *RHS; 1379 // For unsigned comparisons we assumed the signed bit of neither operand 1380 // to be set. The comparison is equal to a signed comparison under this 1381 // assumption. 1382 bool NonNeg = ICond->isUnsigned(); 1383 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg); 1384 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg); 1385 ConsequenceCondSet = 1386 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain); 1387 } 1388 1389 // If no terminator was given we are only looking for parameter constraints 1390 // under which @p Condition is true/false. 1391 if (!TI) 1392 ConsequenceCondSet = isl_set_params(ConsequenceCondSet); 1393 assert(ConsequenceCondSet); 1394 ConsequenceCondSet = isl_set_coalesce( 1395 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))); 1396 1397 isl_set *AlternativeCondSet = nullptr; 1398 bool TooComplex = 1399 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain; 1400 1401 if (!TooComplex) { 1402 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain), 1403 isl_set_copy(ConsequenceCondSet)); 1404 TooComplex = 1405 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain; 1406 } 1407 1408 if (TooComplex) { 1409 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc()); 1410 isl_set_free(AlternativeCondSet); 1411 isl_set_free(ConsequenceCondSet); 1412 return false; 1413 } 1414 1415 ConditionSets.push_back(ConsequenceCondSet); 1416 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet)); 1417 1418 return true; 1419 } 1420 1421 /// Build the conditions sets for the terminator @p TI in the @p Domain. 1422 /// 1423 /// This will fill @p ConditionSets with the conditions under which control 1424 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will 1425 /// have as many elements as @p TI has successors. 1426 static bool 1427 buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L, 1428 __isl_keep isl_set *Domain, 1429 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1430 1431 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) 1432 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets); 1433 1434 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch."); 1435 1436 if (TI->getNumSuccessors() == 1) { 1437 ConditionSets.push_back(isl_set_copy(Domain)); 1438 return true; 1439 } 1440 1441 Value *Condition = getConditionFromTerminator(TI); 1442 assert(Condition && "No condition for Terminator"); 1443 1444 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets); 1445 } 1446 1447 void ScopStmt::buildDomain() { 1448 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this); 1449 1450 Domain = getParent()->getDomainConditions(this); 1451 Domain = isl_set_set_tuple_id(Domain, Id); 1452 } 1453 1454 void ScopStmt::collectSurroundingLoops() { 1455 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) { 1456 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u); 1457 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId))); 1458 isl_id_free(DimId); 1459 } 1460 } 1461 1462 ScopStmt::ScopStmt(Scop &parent, Region &R) 1463 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr), 1464 R(&R), Build(nullptr) { 1465 1466 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), ""); 1467 } 1468 1469 ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb) 1470 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb), 1471 R(nullptr), Build(nullptr) { 1472 1473 BaseName = getIslCompatibleName("Stmt_", &bb, ""); 1474 } 1475 1476 ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel, 1477 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain) 1478 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr), 1479 R(nullptr), Build(nullptr) { 1480 BaseName = getIslCompatibleName("CopyStmt_", "", 1481 std::to_string(parent.getCopyStmtsNum())); 1482 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this); 1483 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id)); 1484 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id); 1485 auto *Access = 1486 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel); 1487 parent.addAccessFunction(Access); 1488 addAccess(Access); 1489 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id)); 1490 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel); 1491 parent.addAccessFunction(Access); 1492 addAccess(Access); 1493 } 1494 1495 void ScopStmt::init(LoopInfo &LI) { 1496 assert(!Domain && "init must be called only once"); 1497 1498 buildDomain(); 1499 collectSurroundingLoops(); 1500 buildAccessRelations(); 1501 1502 if (DetectReductions) 1503 checkForReductions(); 1504 } 1505 1506 /// Collect loads which might form a reduction chain with @p StoreMA. 1507 /// 1508 /// Check if the stored value for @p StoreMA is a binary operator with one or 1509 /// two loads as operands. If the binary operand is commutative & associative, 1510 /// used only once (by @p StoreMA) and its load operands are also used only 1511 /// once, we have found a possible reduction chain. It starts at an operand 1512 /// load and includes the binary operator and @p StoreMA. 1513 /// 1514 /// Note: We allow only one use to ensure the load and binary operator cannot 1515 /// escape this block or into any other store except @p StoreMA. 1516 void ScopStmt::collectCandiateReductionLoads( 1517 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) { 1518 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction()); 1519 if (!Store) 1520 return; 1521 1522 // Skip if there is not one binary operator between the load and the store 1523 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand()); 1524 if (!BinOp) 1525 return; 1526 1527 // Skip if the binary operators has multiple uses 1528 if (BinOp->getNumUses() != 1) 1529 return; 1530 1531 // Skip if the opcode of the binary operator is not commutative/associative 1532 if (!BinOp->isCommutative() || !BinOp->isAssociative()) 1533 return; 1534 1535 // Skip if the binary operator is outside the current SCoP 1536 if (BinOp->getParent() != Store->getParent()) 1537 return; 1538 1539 // Skip if it is a multiplicative reduction and we disabled them 1540 if (DisableMultiplicativeReductions && 1541 (BinOp->getOpcode() == Instruction::Mul || 1542 BinOp->getOpcode() == Instruction::FMul)) 1543 return; 1544 1545 // Check the binary operator operands for a candidate load 1546 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0)); 1547 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1)); 1548 if (!PossibleLoad0 && !PossibleLoad1) 1549 return; 1550 1551 // A load is only a candidate if it cannot escape (thus has only this use) 1552 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1) 1553 if (PossibleLoad0->getParent() == Store->getParent()) 1554 Loads.push_back(&getArrayAccessFor(PossibleLoad0)); 1555 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1) 1556 if (PossibleLoad1->getParent() == Store->getParent()) 1557 Loads.push_back(&getArrayAccessFor(PossibleLoad1)); 1558 } 1559 1560 /// Check for reductions in this ScopStmt. 1561 /// 1562 /// Iterate over all store memory accesses and check for valid binary reduction 1563 /// like chains. For all candidates we check if they have the same base address 1564 /// and there are no other accesses which overlap with them. The base address 1565 /// check rules out impossible reductions candidates early. The overlap check, 1566 /// together with the "only one user" check in collectCandiateReductionLoads, 1567 /// guarantees that none of the intermediate results will escape during 1568 /// execution of the loop nest. We basically check here that no other memory 1569 /// access can access the same memory as the potential reduction. 1570 void ScopStmt::checkForReductions() { 1571 SmallVector<MemoryAccess *, 2> Loads; 1572 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates; 1573 1574 // First collect candidate load-store reduction chains by iterating over all 1575 // stores and collecting possible reduction loads. 1576 for (MemoryAccess *StoreMA : MemAccs) { 1577 if (StoreMA->isRead()) 1578 continue; 1579 1580 Loads.clear(); 1581 collectCandiateReductionLoads(StoreMA, Loads); 1582 for (MemoryAccess *LoadMA : Loads) 1583 Candidates.push_back(std::make_pair(LoadMA, StoreMA)); 1584 } 1585 1586 // Then check each possible candidate pair. 1587 for (const auto &CandidatePair : Candidates) { 1588 bool Valid = true; 1589 isl_map *LoadAccs = CandidatePair.first->getAccessRelation(); 1590 isl_map *StoreAccs = CandidatePair.second->getAccessRelation(); 1591 1592 // Skip those with obviously unequal base addresses. 1593 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) { 1594 isl_map_free(LoadAccs); 1595 isl_map_free(StoreAccs); 1596 continue; 1597 } 1598 1599 // And check if the remaining for overlap with other memory accesses. 1600 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs); 1601 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain()); 1602 isl_set *AllAccs = isl_map_range(AllAccsRel); 1603 1604 for (MemoryAccess *MA : MemAccs) { 1605 if (MA == CandidatePair.first || MA == CandidatePair.second) 1606 continue; 1607 1608 isl_map *AccRel = 1609 isl_map_intersect_domain(MA->getAccessRelation(), getDomain()); 1610 isl_set *Accs = isl_map_range(AccRel); 1611 1612 if (isl_set_has_equal_space(AllAccs, Accs)) { 1613 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs)); 1614 Valid = Valid && isl_set_is_empty(OverlapAccs); 1615 isl_set_free(OverlapAccs); 1616 } else { 1617 isl_set_free(Accs); 1618 } 1619 } 1620 1621 isl_set_free(AllAccs); 1622 if (!Valid) 1623 continue; 1624 1625 const LoadInst *Load = 1626 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction()); 1627 MemoryAccess::ReductionType RT = 1628 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load); 1629 1630 // If no overlapping access was found we mark the load and store as 1631 // reduction like. 1632 CandidatePair.first->markAsReductionLike(RT); 1633 CandidatePair.second->markAsReductionLike(RT); 1634 } 1635 } 1636 1637 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); } 1638 1639 std::string ScopStmt::getScheduleStr() const { 1640 auto *S = getSchedule(); 1641 if (!S) 1642 return ""; 1643 auto Str = stringFromIslObj(S); 1644 isl_map_free(S); 1645 return Str; 1646 } 1647 1648 void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) { 1649 isl_set_free(InvalidDomain); 1650 InvalidDomain = ID; 1651 } 1652 1653 BasicBlock *ScopStmt::getEntryBlock() const { 1654 if (isBlockStmt()) 1655 return getBasicBlock(); 1656 return getRegion()->getEntry(); 1657 } 1658 1659 unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); } 1660 1661 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); } 1662 1663 Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const { 1664 return NestLoops[Dimension]; 1665 } 1666 1667 isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); } 1668 1669 __isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); } 1670 1671 __isl_give isl_space *ScopStmt::getDomainSpace() const { 1672 return isl_set_get_space(Domain); 1673 } 1674 1675 __isl_give isl_id *ScopStmt::getDomainId() const { 1676 return isl_set_get_tuple_id(Domain); 1677 } 1678 1679 ScopStmt::~ScopStmt() { 1680 isl_set_free(Domain); 1681 isl_set_free(InvalidDomain); 1682 } 1683 1684 void ScopStmt::print(raw_ostream &OS) const { 1685 OS << "\t" << getBaseName() << "\n"; 1686 OS.indent(12) << "Domain :=\n"; 1687 1688 if (Domain) { 1689 OS.indent(16) << getDomainStr() << ";\n"; 1690 } else 1691 OS.indent(16) << "n/a\n"; 1692 1693 OS.indent(12) << "Schedule :=\n"; 1694 1695 if (Domain) { 1696 OS.indent(16) << getScheduleStr() << ";\n"; 1697 } else 1698 OS.indent(16) << "n/a\n"; 1699 1700 for (MemoryAccess *Access : MemAccs) 1701 Access->print(OS); 1702 } 1703 1704 void ScopStmt::dump() const { print(dbgs()); } 1705 1706 void ScopStmt::removeMemoryAccess(MemoryAccess *MA) { 1707 // Remove the memory accesses from this statement 1708 // together with all scalar accesses that were caused by it. 1709 // MK_Value READs have no access instruction, hence would not be removed by 1710 // this function. However, it is only used for invariant LoadInst accesses, 1711 // its arguments are always affine, hence synthesizable, and therefore there 1712 // are no MK_Value READ accesses to be removed. 1713 auto Predicate = [&](MemoryAccess *Acc) { 1714 return Acc->getAccessInstruction() == MA->getAccessInstruction(); 1715 }; 1716 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate), 1717 MemAccs.end()); 1718 InstructionToAccess.erase(MA->getAccessInstruction()); 1719 } 1720 1721 //===----------------------------------------------------------------------===// 1722 /// Scop class implement 1723 1724 void Scop::setContext(__isl_take isl_set *NewContext) { 1725 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context)); 1726 isl_set_free(Context); 1727 Context = NewContext; 1728 } 1729 1730 /// Remap parameter values but keep AddRecs valid wrt. invariant loads. 1731 struct SCEVSensitiveParameterRewriter 1732 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> { 1733 ValueToValueMap &VMap; 1734 ScalarEvolution &SE; 1735 1736 public: 1737 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE) 1738 : VMap(VMap), SE(SE) {} 1739 1740 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE, 1741 ValueToValueMap &VMap) { 1742 SCEVSensitiveParameterRewriter SSPR(VMap, SE); 1743 return SSPR.visit(E); 1744 } 1745 1746 const SCEV *visit(const SCEV *E) { 1747 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E); 1748 } 1749 1750 const SCEV *visitConstant(const SCEVConstant *E) { return E; } 1751 1752 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) { 1753 return SE.getTruncateExpr(visit(E->getOperand()), E->getType()); 1754 } 1755 1756 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) { 1757 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType()); 1758 } 1759 1760 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) { 1761 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType()); 1762 } 1763 1764 const SCEV *visitAddExpr(const SCEVAddExpr *E) { 1765 SmallVector<const SCEV *, 4> Operands; 1766 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1767 Operands.push_back(visit(E->getOperand(i))); 1768 return SE.getAddExpr(Operands); 1769 } 1770 1771 const SCEV *visitMulExpr(const SCEVMulExpr *E) { 1772 SmallVector<const SCEV *, 4> Operands; 1773 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1774 Operands.push_back(visit(E->getOperand(i))); 1775 return SE.getMulExpr(Operands); 1776 } 1777 1778 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) { 1779 SmallVector<const SCEV *, 4> Operands; 1780 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1781 Operands.push_back(visit(E->getOperand(i))); 1782 return SE.getSMaxExpr(Operands); 1783 } 1784 1785 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) { 1786 SmallVector<const SCEV *, 4> Operands; 1787 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1788 Operands.push_back(visit(E->getOperand(i))); 1789 return SE.getUMaxExpr(Operands); 1790 } 1791 1792 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) { 1793 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS())); 1794 } 1795 1796 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) { 1797 auto *Start = visit(E->getStart()); 1798 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0), 1799 visit(E->getStepRecurrence(SE)), 1800 E->getLoop(), SCEV::FlagAnyWrap); 1801 return SE.getAddExpr(Start, AddRec); 1802 } 1803 1804 const SCEV *visitUnknown(const SCEVUnknown *E) { 1805 if (auto *NewValue = VMap.lookup(E->getValue())) 1806 return SE.getUnknown(NewValue); 1807 return E; 1808 } 1809 }; 1810 1811 const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) { 1812 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap); 1813 } 1814 1815 void Scop::createParameterId(const SCEV *Parameter) { 1816 assert(Parameters.count(Parameter)); 1817 assert(!ParameterIds.count(Parameter)); 1818 1819 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1); 1820 1821 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) { 1822 Value *Val = ValueParameter->getValue(); 1823 1824 // If this parameter references a specific Value and this value has a name 1825 // we use this name as it is likely to be unique and more useful than just 1826 // a number. 1827 if (Val->hasName()) 1828 ParameterName = Val->getName(); 1829 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) { 1830 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets(); 1831 if (LoadOrigin->hasName()) { 1832 ParameterName += "_loaded_from_"; 1833 ParameterName += 1834 LI->getPointerOperand()->stripInBoundsOffsets()->getName(); 1835 } 1836 } 1837 } 1838 1839 ParameterName = getIslCompatibleName("", ParameterName, ""); 1840 1841 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(), 1842 const_cast<void *>((const void *)Parameter)); 1843 ParameterIds[Parameter] = Id; 1844 } 1845 1846 void Scop::addParams(const ParameterSetTy &NewParameters) { 1847 for (const SCEV *Parameter : NewParameters) { 1848 // Normalize the SCEV to get the representing element for an invariant load. 1849 Parameter = extractConstantFactor(Parameter, *SE).second; 1850 Parameter = getRepresentingInvariantLoadSCEV(Parameter); 1851 1852 if (Parameters.insert(Parameter)) 1853 createParameterId(Parameter); 1854 } 1855 } 1856 1857 __isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) { 1858 // Normalize the SCEV to get the representing element for an invariant load. 1859 Parameter = getRepresentingInvariantLoadSCEV(Parameter); 1860 return isl_id_copy(ParameterIds.lookup(Parameter)); 1861 } 1862 1863 __isl_give isl_set * 1864 Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const { 1865 isl_set *DomainContext = isl_union_set_params(getDomains()); 1866 return isl_set_intersect_params(C, DomainContext); 1867 } 1868 1869 bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const { 1870 return DT.dominates(BB, getEntry()); 1871 } 1872 1873 void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, 1874 LoopInfo &LI) { 1875 auto &F = getFunction(); 1876 for (auto &Assumption : AC.assumptions()) { 1877 auto *CI = dyn_cast_or_null<CallInst>(Assumption); 1878 if (!CI || CI->getNumArgOperands() != 1) 1879 continue; 1880 1881 bool InScop = contains(CI); 1882 if (!InScop && !isDominatedBy(DT, CI->getParent())) 1883 continue; 1884 1885 auto *L = LI.getLoopFor(CI->getParent()); 1886 auto *Val = CI->getArgOperand(0); 1887 ParameterSetTy DetectedParams; 1888 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) { 1889 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, 1890 CI->getDebugLoc(), 1891 "Non-affine user assumption ignored."); 1892 continue; 1893 } 1894 1895 // Collect all newly introduced parameters. 1896 ParameterSetTy NewParams; 1897 for (auto *Param : DetectedParams) { 1898 Param = extractConstantFactor(Param, *SE).second; 1899 Param = getRepresentingInvariantLoadSCEV(Param); 1900 if (Parameters.count(Param)) 1901 continue; 1902 NewParams.insert(Param); 1903 } 1904 1905 SmallVector<isl_set *, 2> ConditionSets; 1906 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr; 1907 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin(); 1908 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context); 1909 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets); 1910 isl_set_free(Dom); 1911 1912 if (!Valid) 1913 continue; 1914 1915 isl_set *AssumptionCtx = nullptr; 1916 if (InScop) { 1917 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1])); 1918 isl_set_free(ConditionSets[0]); 1919 } else { 1920 AssumptionCtx = isl_set_complement(ConditionSets[1]); 1921 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]); 1922 } 1923 1924 // Project out newly introduced parameters as they are not otherwise useful. 1925 if (!NewParams.empty()) { 1926 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) { 1927 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u); 1928 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id)); 1929 isl_id_free(Id); 1930 1931 if (!NewParams.count(Param)) 1932 continue; 1933 1934 AssumptionCtx = 1935 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1); 1936 } 1937 } 1938 1939 emitOptimizationRemarkAnalysis( 1940 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(), 1941 "Use user assumption: " + stringFromIslObj(AssumptionCtx)); 1942 Context = isl_set_intersect(Context, AssumptionCtx); 1943 } 1944 } 1945 1946 void Scop::addUserContext() { 1947 if (UserContextStr.empty()) 1948 return; 1949 1950 isl_set *UserContext = 1951 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str()); 1952 isl_space *Space = getParamSpace(); 1953 if (isl_space_dim(Space, isl_dim_param) != 1954 isl_set_dim(UserContext, isl_dim_param)) { 1955 auto SpaceStr = isl_space_to_str(Space); 1956 errs() << "Error: the context provided in -polly-context has not the same " 1957 << "number of dimensions than the computed context. Due to this " 1958 << "mismatch, the -polly-context option is ignored. Please provide " 1959 << "the context in the parameter space: " << SpaceStr << ".\n"; 1960 free(SpaceStr); 1961 isl_set_free(UserContext); 1962 isl_space_free(Space); 1963 return; 1964 } 1965 1966 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1967 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i); 1968 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i); 1969 1970 if (strcmp(NameContext, NameUserContext) != 0) { 1971 auto SpaceStr = isl_space_to_str(Space); 1972 errs() << "Error: the name of dimension " << i 1973 << " provided in -polly-context " 1974 << "is '" << NameUserContext << "', but the name in the computed " 1975 << "context is '" << NameContext 1976 << "'. Due to this name mismatch, " 1977 << "the -polly-context option is ignored. Please provide " 1978 << "the context in the parameter space: " << SpaceStr << ".\n"; 1979 free(SpaceStr); 1980 isl_set_free(UserContext); 1981 isl_space_free(Space); 1982 return; 1983 } 1984 1985 UserContext = 1986 isl_set_set_dim_id(UserContext, isl_dim_param, i, 1987 isl_space_get_dim_id(Space, isl_dim_param, i)); 1988 } 1989 1990 Context = isl_set_intersect(Context, UserContext); 1991 isl_space_free(Space); 1992 } 1993 1994 void Scop::buildInvariantEquivalenceClasses() { 1995 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses; 1996 1997 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads(); 1998 for (LoadInst *LInst : RIL) { 1999 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 2000 2001 Type *Ty = LInst->getType(); 2002 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)]; 2003 if (ClassRep) { 2004 InvEquivClassVMap[LInst] = ClassRep; 2005 continue; 2006 } 2007 2008 ClassRep = LInst; 2009 InvariantEquivClasses.emplace_back( 2010 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty}); 2011 } 2012 } 2013 2014 void Scop::buildContext() { 2015 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0); 2016 Context = isl_set_universe(isl_space_copy(Space)); 2017 InvalidContext = isl_set_empty(isl_space_copy(Space)); 2018 AssumedContext = isl_set_universe(Space); 2019 } 2020 2021 void Scop::addParameterBounds() { 2022 unsigned PDim = 0; 2023 for (auto *Parameter : Parameters) { 2024 ConstantRange SRange = SE->getSignedRange(Parameter); 2025 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param); 2026 } 2027 } 2028 2029 void Scop::realignParams() { 2030 // Add all parameters into a common model. 2031 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size()); 2032 2033 unsigned PDim = 0; 2034 for (const auto *Parameter : Parameters) { 2035 isl_id *id = getIdForParam(Parameter); 2036 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id); 2037 } 2038 2039 // Align the parameters of all data structures to the model. 2040 Context = isl_set_align_params(Context, Space); 2041 2042 // As all parameters are known add bounds to them. 2043 addParameterBounds(); 2044 2045 for (ScopStmt &Stmt : *this) 2046 Stmt.realignParams(); 2047 2048 // Simplify the schedule according to the context too. 2049 Schedule = isl_schedule_gist_domain_params(Schedule, getContext()); 2050 } 2051 2052 static __isl_give isl_set * 2053 simplifyAssumptionContext(__isl_take isl_set *AssumptionContext, 2054 const Scop &S) { 2055 // If we modelt all blocks in the SCoP that have side effects we can simplify 2056 // the context with the constraints that are needed for anything to be 2057 // executed at all. However, if we have error blocks in the SCoP we already 2058 // assumed some parameter combinations cannot occure and removed them from the 2059 // domains, thus we cannot use the remaining domain to simplify the 2060 // assumptions. 2061 if (!S.hasErrorBlock()) { 2062 isl_set *DomainParameters = isl_union_set_params(S.getDomains()); 2063 AssumptionContext = 2064 isl_set_gist_params(AssumptionContext, DomainParameters); 2065 } 2066 2067 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext()); 2068 return AssumptionContext; 2069 } 2070 2071 void Scop::simplifyContexts() { 2072 // The parameter constraints of the iteration domains give us a set of 2073 // constraints that need to hold for all cases where at least a single 2074 // statement iteration is executed in the whole scop. We now simplify the 2075 // assumed context under the assumption that such constraints hold and at 2076 // least a single statement iteration is executed. For cases where no 2077 // statement instances are executed, the assumptions we have taken about 2078 // the executed code do not matter and can be changed. 2079 // 2080 // WARNING: This only holds if the assumptions we have taken do not reduce 2081 // the set of statement instances that are executed. Otherwise we 2082 // may run into a case where the iteration domains suggest that 2083 // for a certain set of parameter constraints no code is executed, 2084 // but in the original program some computation would have been 2085 // performed. In such a case, modifying the run-time conditions and 2086 // possibly influencing the run-time check may cause certain scops 2087 // to not be executed. 2088 // 2089 // Example: 2090 // 2091 // When delinearizing the following code: 2092 // 2093 // for (long i = 0; i < 100; i++) 2094 // for (long j = 0; j < m; j++) 2095 // A[i+p][j] = 1.0; 2096 // 2097 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as 2098 // otherwise we would access out of bound data. Now, knowing that code is 2099 // only executed for the case m >= 0, it is sufficient to assume p >= 0. 2100 AssumedContext = simplifyAssumptionContext(AssumedContext, *this); 2101 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace()); 2102 } 2103 2104 /// Add the minimal/maximal access in @p Set to @p User. 2105 static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) { 2106 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User; 2107 isl_pw_multi_aff *MinPMA, *MaxPMA; 2108 isl_pw_aff *LastDimAff; 2109 isl_aff *OneAff; 2110 unsigned Pos; 2111 2112 Set = isl_set_remove_divs(Set); 2113 2114 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) { 2115 isl_set_free(Set); 2116 return isl_stat_error; 2117 } 2118 2119 // Restrict the number of parameters involved in the access as the lexmin/ 2120 // lexmax computation will take too long if this number is high. 2121 // 2122 // Experiments with a simple test case using an i7 4800MQ: 2123 // 2124 // #Parameters involved | Time (in sec) 2125 // 6 | 0.01 2126 // 7 | 0.04 2127 // 8 | 0.12 2128 // 9 | 0.40 2129 // 10 | 1.54 2130 // 11 | 6.78 2131 // 12 | 30.38 2132 // 2133 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) { 2134 unsigned InvolvedParams = 0; 2135 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++) 2136 if (isl_set_involves_dims(Set, isl_dim_param, u, 1)) 2137 InvolvedParams++; 2138 2139 if (InvolvedParams > RunTimeChecksMaxParameters) { 2140 isl_set_free(Set); 2141 return isl_stat_error; 2142 } 2143 } 2144 2145 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set)); 2146 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set)); 2147 2148 MinPMA = isl_pw_multi_aff_coalesce(MinPMA); 2149 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA); 2150 2151 // Adjust the last dimension of the maximal access by one as we want to 2152 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer 2153 // we test during code generation might now point after the end of the 2154 // allocated array but we will never dereference it anyway. 2155 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) && 2156 "Assumed at least one output dimension"); 2157 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1; 2158 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos); 2159 OneAff = isl_aff_zero_on_domain( 2160 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff))); 2161 OneAff = isl_aff_add_constant_si(OneAff, 1); 2162 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff)); 2163 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff); 2164 2165 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA)); 2166 2167 isl_set_free(Set); 2168 return isl_stat_ok; 2169 } 2170 2171 static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) { 2172 isl_set *Domain = MA->getStatement()->getDomain(); 2173 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain)); 2174 return isl_set_reset_tuple_id(Domain); 2175 } 2176 2177 /// Wrapper function to calculate minimal/maximal accesses to each array. 2178 static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses, 2179 __isl_take isl_union_set *Domains, 2180 Scop::MinMaxVectorTy &MinMaxAccesses) { 2181 2182 Accesses = isl_union_map_intersect_domain(Accesses, Domains); 2183 isl_union_set *Locations = isl_union_map_range(Accesses); 2184 Locations = isl_union_set_coalesce(Locations); 2185 Locations = isl_union_set_detect_equalities(Locations); 2186 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, 2187 &MinMaxAccesses)); 2188 isl_union_set_free(Locations); 2189 return Valid; 2190 } 2191 2192 /// Helper to treat non-affine regions and basic blocks the same. 2193 /// 2194 ///{ 2195 2196 /// Return the block that is the representing block for @p RN. 2197 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) { 2198 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry() 2199 : RN->getNodeAs<BasicBlock>(); 2200 } 2201 2202 /// Return the @p idx'th block that is executed after @p RN. 2203 static inline BasicBlock * 2204 getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) { 2205 if (RN->isSubRegion()) { 2206 assert(idx == 0); 2207 return RN->getNodeAs<Region>()->getExit(); 2208 } 2209 return TI->getSuccessor(idx); 2210 } 2211 2212 /// Return the smallest loop surrounding @p RN. 2213 static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) { 2214 if (!RN->isSubRegion()) 2215 return LI.getLoopFor(RN->getNodeAs<BasicBlock>()); 2216 2217 Region *NonAffineSubRegion = RN->getNodeAs<Region>(); 2218 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry()); 2219 while (L && NonAffineSubRegion->contains(L)) 2220 L = L->getParentLoop(); 2221 return L; 2222 } 2223 2224 static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) { 2225 if (!RN->isSubRegion()) 2226 return 1; 2227 2228 Region *R = RN->getNodeAs<Region>(); 2229 return std::distance(R->block_begin(), R->block_end()); 2230 } 2231 2232 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI, 2233 const DominatorTree &DT) { 2234 if (!RN->isSubRegion()) 2235 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT); 2236 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks()) 2237 if (isErrorBlock(*BB, R, LI, DT)) 2238 return true; 2239 return false; 2240 } 2241 2242 ///} 2243 2244 static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain, 2245 unsigned Dim, Loop *L) { 2246 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1); 2247 isl_id *DimId = 2248 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L)); 2249 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId); 2250 } 2251 2252 __isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const { 2253 return getDomainConditions(Stmt->getEntryBlock()); 2254 } 2255 2256 __isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const { 2257 auto DIt = DomainMap.find(BB); 2258 if (DIt != DomainMap.end()) 2259 return isl_set_copy(DIt->getSecond()); 2260 2261 auto &RI = *R.getRegionInfo(); 2262 auto *BBR = RI.getRegionFor(BB); 2263 while (BBR->getEntry() == BB) 2264 BBR = BBR->getParent(); 2265 return getDomainConditions(BBR->getEntry()); 2266 } 2267 2268 bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) { 2269 2270 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R); 2271 auto *EntryBB = R->getEntry(); 2272 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB); 2273 int LD = getRelativeLoopDepth(L); 2274 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1)); 2275 2276 while (LD-- >= 0) { 2277 S = addDomainDimId(S, LD + 1, L); 2278 L = L->getParentLoop(); 2279 } 2280 2281 // Initialize the invalid domain. 2282 auto *EntryStmt = getStmtFor(EntryBB); 2283 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S))); 2284 2285 DomainMap[EntryBB] = S; 2286 2287 if (IsOnlyNonAffineRegion) 2288 return !containsErrorBlock(R->getNode(), *R, LI, DT); 2289 2290 if (!buildDomainsWithBranchConstraints(R, DT, LI)) 2291 return false; 2292 2293 if (!propagateDomainConstraints(R, DT, LI)) 2294 return false; 2295 2296 // Error blocks and blocks dominated by them have been assumed to never be 2297 // executed. Representing them in the Scop does not add any value. In fact, 2298 // it is likely to cause issues during construction of the ScopStmts. The 2299 // contents of error blocks have not been verified to be expressible and 2300 // will cause problems when building up a ScopStmt for them. 2301 // Furthermore, basic blocks dominated by error blocks may reference 2302 // instructions in the error block which, if the error block is not modeled, 2303 // can themselves not be constructed properly. To this end we will replace 2304 // the domains of error blocks and those only reachable via error blocks 2305 // with an empty set. Additionally, we will record for each block under which 2306 // parameter combination it would be reached via an error block in its 2307 // InvalidDomain. This information is needed during load hoisting. 2308 if (!propagateInvalidStmtDomains(R, DT, LI)) 2309 return false; 2310 2311 return true; 2312 } 2313 2314 // If the loop is nonaffine/boxed, return the first non-boxed surrounding loop 2315 // for Polly. If the loop is affine, return the loop itself. Do not call 2316 // `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need 2317 // to analyze the memory accesses of the nonaffine/boxed loops. 2318 static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI, 2319 const BoxedLoopsSetTy &BoxedLoops) { 2320 auto *L = LI.getLoopFor(BB); 2321 while (BoxedLoops.count(L)) 2322 L = L->getParentLoop(); 2323 return L; 2324 } 2325 2326 /// Adjust the dimensions of @p Dom that was constructed for @p OldL 2327 /// to be compatible to domains constructed for loop @p NewL. 2328 /// 2329 /// This function assumes @p NewL and @p OldL are equal or there is a CFG 2330 /// edge from @p OldL to @p NewL. 2331 static __isl_give isl_set *adjustDomainDimensions(Scop &S, 2332 __isl_take isl_set *Dom, 2333 Loop *OldL, Loop *NewL) { 2334 2335 // If the loops are the same there is nothing to do. 2336 if (NewL == OldL) 2337 return Dom; 2338 2339 int OldDepth = S.getRelativeLoopDepth(OldL); 2340 int NewDepth = S.getRelativeLoopDepth(NewL); 2341 // If both loops are non-affine loops there is nothing to do. 2342 if (OldDepth == -1 && NewDepth == -1) 2343 return Dom; 2344 2345 // Distinguish three cases: 2346 // 1) The depth is the same but the loops are not. 2347 // => One loop was left one was entered. 2348 // 2) The depth increased from OldL to NewL. 2349 // => One loop was entered, none was left. 2350 // 3) The depth decreased from OldL to NewL. 2351 // => Loops were left were difference of the depths defines how many. 2352 if (OldDepth == NewDepth) { 2353 assert(OldL->getParentLoop() == NewL->getParentLoop()); 2354 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1); 2355 Dom = isl_set_add_dims(Dom, isl_dim_set, 1); 2356 Dom = addDomainDimId(Dom, NewDepth, NewL); 2357 } else if (OldDepth < NewDepth) { 2358 assert(OldDepth + 1 == NewDepth); 2359 auto &R = S.getRegion(); 2360 (void)R; 2361 assert(NewL->getParentLoop() == OldL || 2362 ((!OldL || !R.contains(OldL)) && R.contains(NewL))); 2363 Dom = isl_set_add_dims(Dom, isl_dim_set, 1); 2364 Dom = addDomainDimId(Dom, NewDepth, NewL); 2365 } else { 2366 assert(OldDepth > NewDepth); 2367 int Diff = OldDepth - NewDepth; 2368 int NumDim = isl_set_n_dim(Dom); 2369 assert(NumDim >= Diff); 2370 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff); 2371 } 2372 2373 return Dom; 2374 } 2375 2376 bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT, 2377 LoopInfo &LI) { 2378 auto &BoxedLoops = getBoxedLoops(); 2379 2380 ReversePostOrderTraversal<Region *> RTraversal(R); 2381 for (auto *RN : RTraversal) { 2382 2383 // Recurse for affine subregions but go on for basic blocks and non-affine 2384 // subregions. 2385 if (RN->isSubRegion()) { 2386 Region *SubRegion = RN->getNodeAs<Region>(); 2387 if (!isNonAffineSubRegion(SubRegion)) { 2388 propagateInvalidStmtDomains(SubRegion, DT, LI); 2389 continue; 2390 } 2391 } 2392 2393 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT); 2394 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2395 ScopStmt *Stmt = getStmtFor(BB); 2396 isl_set *&Domain = DomainMap[BB]; 2397 assert(Domain && "Cannot propagate a nullptr"); 2398 2399 auto *InvalidDomain = Stmt->getInvalidDomain(); 2400 bool IsInvalidBlock = 2401 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain); 2402 2403 if (!IsInvalidBlock) { 2404 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain)); 2405 } else { 2406 isl_set_free(InvalidDomain); 2407 InvalidDomain = Domain; 2408 isl_set *DomPar = isl_set_params(isl_set_copy(Domain)); 2409 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(), 2410 AS_RESTRICTION); 2411 Domain = nullptr; 2412 } 2413 2414 if (isl_set_is_empty(InvalidDomain)) { 2415 Stmt->setInvalidDomain(InvalidDomain); 2416 continue; 2417 } 2418 2419 auto *BBLoop = getRegionNodeLoop(RN, LI); 2420 auto *TI = BB->getTerminator(); 2421 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors(); 2422 for (unsigned u = 0; u < NumSuccs; u++) { 2423 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u); 2424 auto *SuccStmt = getStmtFor(SuccBB); 2425 2426 // Skip successors outside the SCoP. 2427 if (!SuccStmt) 2428 continue; 2429 2430 // Skip backedges. 2431 if (DT.dominates(SuccBB, BB)) 2432 continue; 2433 2434 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops); 2435 auto *AdjustedInvalidDomain = adjustDomainDimensions( 2436 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop); 2437 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain(); 2438 SuccInvalidDomain = 2439 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain); 2440 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain); 2441 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain); 2442 SuccStmt->setInvalidDomain(SuccInvalidDomain); 2443 2444 // Check if the maximal number of domain disjunctions was reached. 2445 // In case this happens we will bail. 2446 if (NumConjucts < MaxDisjunctionsInDomain) 2447 continue; 2448 2449 isl_set_free(InvalidDomain); 2450 invalidate(COMPLEXITY, TI->getDebugLoc()); 2451 return false; 2452 } 2453 2454 Stmt->setInvalidDomain(InvalidDomain); 2455 } 2456 2457 return true; 2458 } 2459 2460 void Scop::propagateDomainConstraintsToRegionExit( 2461 BasicBlock *BB, Loop *BBLoop, 2462 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) { 2463 2464 // Check if the block @p BB is the entry of a region. If so we propagate it's 2465 // domain to the exit block of the region. Otherwise we are done. 2466 auto *RI = R.getRegionInfo(); 2467 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr; 2468 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr; 2469 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB)) 2470 return; 2471 2472 auto &BoxedLoops = getBoxedLoops(); 2473 // Do not propagate the domain if there is a loop backedge inside the region 2474 // that would prevent the exit block from beeing executed. 2475 auto *L = BBLoop; 2476 while (L && contains(L)) { 2477 SmallVector<BasicBlock *, 4> LatchBBs; 2478 BBLoop->getLoopLatches(LatchBBs); 2479 for (auto *LatchBB : LatchBBs) 2480 if (BB != LatchBB && BBReg->contains(LatchBB)) 2481 return; 2482 L = L->getParentLoop(); 2483 } 2484 2485 auto *Domain = DomainMap[BB]; 2486 assert(Domain && "Cannot propagate a nullptr"); 2487 2488 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops); 2489 2490 // Since the dimensions of @p BB and @p ExitBB might be different we have to 2491 // adjust the domain before we can propagate it. 2492 auto *AdjustedDomain = 2493 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop); 2494 auto *&ExitDomain = DomainMap[ExitBB]; 2495 2496 // If the exit domain is not yet created we set it otherwise we "add" the 2497 // current domain. 2498 ExitDomain = 2499 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain; 2500 2501 // Initialize the invalid domain. 2502 auto *ExitStmt = getStmtFor(ExitBB); 2503 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain))); 2504 2505 FinishedExitBlocks.insert(ExitBB); 2506 } 2507 2508 bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT, 2509 LoopInfo &LI) { 2510 // To create the domain for each block in R we iterate over all blocks and 2511 // subregions in R and propagate the conditions under which the current region 2512 // element is executed. To this end we iterate in reverse post order over R as 2513 // it ensures that we first visit all predecessors of a region node (either a 2514 // basic block or a subregion) before we visit the region node itself. 2515 // Initially, only the domain for the SCoP region entry block is set and from 2516 // there we propagate the current domain to all successors, however we add the 2517 // condition that the successor is actually executed next. 2518 // As we are only interested in non-loop carried constraints here we can 2519 // simply skip loop back edges. 2520 2521 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks; 2522 ReversePostOrderTraversal<Region *> RTraversal(R); 2523 for (auto *RN : RTraversal) { 2524 2525 // Recurse for affine subregions but go on for basic blocks and non-affine 2526 // subregions. 2527 if (RN->isSubRegion()) { 2528 Region *SubRegion = RN->getNodeAs<Region>(); 2529 if (!isNonAffineSubRegion(SubRegion)) { 2530 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI)) 2531 return false; 2532 continue; 2533 } 2534 } 2535 2536 if (containsErrorBlock(RN, getRegion(), LI, DT)) 2537 HasErrorBlock = true; 2538 2539 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2540 TerminatorInst *TI = BB->getTerminator(); 2541 2542 if (isa<UnreachableInst>(TI)) 2543 continue; 2544 2545 isl_set *Domain = DomainMap.lookup(BB); 2546 if (!Domain) 2547 continue; 2548 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain)); 2549 2550 auto *BBLoop = getRegionNodeLoop(RN, LI); 2551 // Propagate the domain from BB directly to blocks that have a superset 2552 // domain, at the moment only region exit nodes of regions that start in BB. 2553 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI); 2554 2555 // If all successors of BB have been set a domain through the propagation 2556 // above we do not need to build condition sets but can just skip this 2557 // block. However, it is important to note that this is a local property 2558 // with regards to the region @p R. To this end FinishedExitBlocks is a 2559 // local variable. 2560 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) { 2561 return FinishedExitBlocks.count(SuccBB); 2562 }; 2563 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit)) 2564 continue; 2565 2566 // Build the condition sets for the successor nodes of the current region 2567 // node. If it is a non-affine subregion we will always execute the single 2568 // exit node, hence the single entry node domain is the condition set. For 2569 // basic blocks we use the helper function buildConditionSets. 2570 SmallVector<isl_set *, 8> ConditionSets; 2571 if (RN->isSubRegion()) 2572 ConditionSets.push_back(isl_set_copy(Domain)); 2573 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain, 2574 ConditionSets)) 2575 return false; 2576 2577 // Now iterate over the successors and set their initial domain based on 2578 // their condition set. We skip back edges here and have to be careful when 2579 // we leave a loop not to keep constraints over a dimension that doesn't 2580 // exist anymore. 2581 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size()); 2582 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) { 2583 isl_set *CondSet = ConditionSets[u]; 2584 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u); 2585 2586 auto *SuccStmt = getStmtFor(SuccBB); 2587 // Skip blocks outside the region. 2588 if (!SuccStmt) { 2589 isl_set_free(CondSet); 2590 continue; 2591 } 2592 2593 // If we propagate the domain of some block to "SuccBB" we do not have to 2594 // adjust the domain. 2595 if (FinishedExitBlocks.count(SuccBB)) { 2596 isl_set_free(CondSet); 2597 continue; 2598 } 2599 2600 // Skip back edges. 2601 if (DT.dominates(SuccBB, BB)) { 2602 isl_set_free(CondSet); 2603 continue; 2604 } 2605 2606 auto &BoxedLoops = getBoxedLoops(); 2607 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops); 2608 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop); 2609 2610 // Set the domain for the successor or merge it with an existing domain in 2611 // case there are multiple paths (without loop back edges) to the 2612 // successor block. 2613 isl_set *&SuccDomain = DomainMap[SuccBB]; 2614 2615 if (SuccDomain) { 2616 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet)); 2617 } else { 2618 // Initialize the invalid domain. 2619 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet))); 2620 SuccDomain = CondSet; 2621 } 2622 2623 // Check if the maximal number of domain disjunctions was reached. 2624 // In case this happens we will clean up and bail. 2625 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain) 2626 continue; 2627 2628 invalidate(COMPLEXITY, DebugLoc()); 2629 while (++u < ConditionSets.size()) 2630 isl_set_free(ConditionSets[u]); 2631 return false; 2632 } 2633 } 2634 2635 return true; 2636 } 2637 2638 __isl_give isl_set * 2639 Scop::getPredecessorDomainConstraints(BasicBlock *BB, 2640 __isl_keep isl_set *Domain, 2641 DominatorTree &DT, LoopInfo &LI) { 2642 // If @p BB is the ScopEntry we are done 2643 if (R.getEntry() == BB) 2644 return isl_set_universe(isl_set_get_space(Domain)); 2645 2646 // The set of boxed loops (loops in non-affine subregions) for this SCoP. 2647 auto &BoxedLoops = getBoxedLoops(); 2648 2649 // The region info of this function. 2650 auto &RI = *R.getRegionInfo(); 2651 2652 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops); 2653 2654 // A domain to collect all predecessor domains, thus all conditions under 2655 // which the block is executed. To this end we start with the empty domain. 2656 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain)); 2657 2658 // Set of regions of which the entry block domain has been propagated to BB. 2659 // all predecessors inside any of the regions can be skipped. 2660 SmallSet<Region *, 8> PropagatedRegions; 2661 2662 for (auto *PredBB : predecessors(BB)) { 2663 // Skip backedges. 2664 if (DT.dominates(BB, PredBB)) 2665 continue; 2666 2667 // If the predecessor is in a region we used for propagation we can skip it. 2668 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); }; 2669 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(), 2670 PredBBInRegion)) { 2671 continue; 2672 } 2673 2674 // Check if there is a valid region we can use for propagation, thus look 2675 // for a region that contains the predecessor and has @p BB as exit block. 2676 auto *PredR = RI.getRegionFor(PredBB); 2677 while (PredR->getExit() != BB && !PredR->contains(BB)) 2678 PredR->getParent(); 2679 2680 // If a valid region for propagation was found use the entry of that region 2681 // for propagation, otherwise the PredBB directly. 2682 if (PredR->getExit() == BB) { 2683 PredBB = PredR->getEntry(); 2684 PropagatedRegions.insert(PredR); 2685 } 2686 2687 auto *PredBBDom = getDomainConditions(PredBB); 2688 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops); 2689 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop); 2690 2691 PredDom = isl_set_union(PredDom, PredBBDom); 2692 } 2693 2694 return PredDom; 2695 } 2696 2697 bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT, 2698 LoopInfo &LI) { 2699 // Iterate over the region R and propagate the domain constrains from the 2700 // predecessors to the current node. In contrast to the 2701 // buildDomainsWithBranchConstraints function, this one will pull the domain 2702 // information from the predecessors instead of pushing it to the successors. 2703 // Additionally, we assume the domains to be already present in the domain 2704 // map here. However, we iterate again in reverse post order so we know all 2705 // predecessors have been visited before a block or non-affine subregion is 2706 // visited. 2707 2708 ReversePostOrderTraversal<Region *> RTraversal(R); 2709 for (auto *RN : RTraversal) { 2710 2711 // Recurse for affine subregions but go on for basic blocks and non-affine 2712 // subregions. 2713 if (RN->isSubRegion()) { 2714 Region *SubRegion = RN->getNodeAs<Region>(); 2715 if (!isNonAffineSubRegion(SubRegion)) { 2716 if (!propagateDomainConstraints(SubRegion, DT, LI)) 2717 return false; 2718 continue; 2719 } 2720 } 2721 2722 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2723 isl_set *&Domain = DomainMap[BB]; 2724 assert(Domain); 2725 2726 // Under the union of all predecessor conditions we can reach this block. 2727 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI); 2728 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom)); 2729 Domain = isl_set_align_params(Domain, getParamSpace()); 2730 2731 Loop *BBLoop = getRegionNodeLoop(RN, LI); 2732 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop)) 2733 if (!addLoopBoundsToHeaderDomain(BBLoop, LI)) 2734 return false; 2735 } 2736 2737 return true; 2738 } 2739 2740 /// Create a map to map from a given iteration to a subsequent iteration. 2741 /// 2742 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim 2743 /// is incremented by one and all other dimensions are equal, e.g., 2744 /// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3] 2745 /// 2746 /// if @p Dim is 2 and @p SetSpace has 4 dimensions. 2747 static __isl_give isl_map * 2748 createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) { 2749 auto *MapSpace = isl_space_map_from_set(SetSpace); 2750 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace)); 2751 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++) 2752 if (u != Dim) 2753 NextIterationMap = 2754 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u); 2755 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace)); 2756 C = isl_constraint_set_constant_si(C, 1); 2757 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1); 2758 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1); 2759 NextIterationMap = isl_map_add_constraint(NextIterationMap, C); 2760 return NextIterationMap; 2761 } 2762 2763 bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) { 2764 int LoopDepth = getRelativeLoopDepth(L); 2765 assert(LoopDepth >= 0 && "Loop in region should have at least depth one"); 2766 2767 BasicBlock *HeaderBB = L->getHeader(); 2768 assert(DomainMap.count(HeaderBB)); 2769 isl_set *&HeaderBBDom = DomainMap[HeaderBB]; 2770 2771 isl_map *NextIterationMap = 2772 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth); 2773 2774 isl_set *UnionBackedgeCondition = 2775 isl_set_empty(isl_set_get_space(HeaderBBDom)); 2776 2777 SmallVector<llvm::BasicBlock *, 4> LatchBlocks; 2778 L->getLoopLatches(LatchBlocks); 2779 2780 for (BasicBlock *LatchBB : LatchBlocks) { 2781 2782 // If the latch is only reachable via error statements we skip it. 2783 isl_set *LatchBBDom = DomainMap.lookup(LatchBB); 2784 if (!LatchBBDom) 2785 continue; 2786 2787 isl_set *BackedgeCondition = nullptr; 2788 2789 TerminatorInst *TI = LatchBB->getTerminator(); 2790 BranchInst *BI = dyn_cast<BranchInst>(TI); 2791 if (BI && BI->isUnconditional()) 2792 BackedgeCondition = isl_set_copy(LatchBBDom); 2793 else { 2794 SmallVector<isl_set *, 8> ConditionSets; 2795 int idx = BI->getSuccessor(0) != HeaderBB; 2796 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom, 2797 ConditionSets)) 2798 return false; 2799 2800 // Free the non back edge condition set as we do not need it. 2801 isl_set_free(ConditionSets[1 - idx]); 2802 2803 BackedgeCondition = ConditionSets[idx]; 2804 } 2805 2806 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB)); 2807 assert(LatchLoopDepth >= LoopDepth); 2808 BackedgeCondition = 2809 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1, 2810 LatchLoopDepth - LoopDepth); 2811 UnionBackedgeCondition = 2812 isl_set_union(UnionBackedgeCondition, BackedgeCondition); 2813 } 2814 2815 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom)); 2816 for (int i = 0; i < LoopDepth; i++) 2817 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i); 2818 2819 isl_set *UnionBackedgeConditionComplement = 2820 isl_set_complement(UnionBackedgeCondition); 2821 UnionBackedgeConditionComplement = isl_set_lower_bound_si( 2822 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0); 2823 UnionBackedgeConditionComplement = 2824 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap); 2825 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement); 2826 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap); 2827 2828 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth); 2829 HeaderBBDom = Parts.second; 2830 2831 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add 2832 // the bounded assumptions to the context as they are already implied by the 2833 // <nsw> tag. 2834 if (Affinator.hasNSWAddRecForLoop(L)) { 2835 isl_set_free(Parts.first); 2836 return true; 2837 } 2838 2839 isl_set *UnboundedCtx = isl_set_params(Parts.first); 2840 recordAssumption(INFINITELOOP, UnboundedCtx, 2841 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION); 2842 return true; 2843 } 2844 2845 MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) { 2846 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr()); 2847 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr)); 2848 if (!PointerBase) 2849 return nullptr; 2850 2851 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue()); 2852 if (!PointerBaseInst) 2853 return nullptr; 2854 2855 auto *BasePtrStmt = getStmtFor(PointerBaseInst); 2856 if (!BasePtrStmt) 2857 return nullptr; 2858 2859 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst); 2860 } 2861 2862 bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA, 2863 __isl_keep isl_union_map *Writes) { 2864 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) { 2865 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes); 2866 bool Hoistable = NHCtx != nullptr; 2867 isl_set_free(NHCtx); 2868 return !Hoistable; 2869 } 2870 2871 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr()); 2872 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr)); 2873 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue())) 2874 if (!isa<LoadInst>(BasePtrInst)) 2875 return contains(BasePtrInst); 2876 2877 return false; 2878 } 2879 2880 bool Scop::buildAliasChecks(AliasAnalysis &AA) { 2881 if (!PollyUseRuntimeAliasChecks) 2882 return true; 2883 2884 if (buildAliasGroups(AA)) 2885 return true; 2886 2887 // If a problem occurs while building the alias groups we need to delete 2888 // this SCoP and pretend it wasn't valid in the first place. To this end 2889 // we make the assumed context infeasible. 2890 invalidate(ALIASING, DebugLoc()); 2891 2892 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr() 2893 << " could not be created as the number of parameters involved " 2894 "is too high. The SCoP will be " 2895 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust " 2896 "the maximal number of parameters but be advised that the " 2897 "compile time might increase exponentially.\n\n"); 2898 return false; 2899 } 2900 2901 bool Scop::buildAliasGroups(AliasAnalysis &AA) { 2902 // To create sound alias checks we perform the following steps: 2903 // o) Use the alias analysis and an alias set tracker to build alias sets 2904 // for all memory accesses inside the SCoP. 2905 // o) For each alias set we then map the aliasing pointers back to the 2906 // memory accesses we know, thus obtain groups of memory accesses which 2907 // might alias. 2908 // o) We divide each group based on the domains of the minimal/maximal 2909 // accesses. That means two minimal/maximal accesses are only in a group 2910 // if their access domains intersect, otherwise they are in different 2911 // ones. 2912 // o) We partition each group into read only and non read only accesses. 2913 // o) For each group with more than one base pointer we then compute minimal 2914 // and maximal accesses to each array of a group in read only and non 2915 // read only partitions separately. 2916 using AliasGroupTy = SmallVector<MemoryAccess *, 4>; 2917 2918 AliasSetTracker AST(AA); 2919 2920 DenseMap<Value *, MemoryAccess *> PtrToAcc; 2921 DenseSet<Value *> HasWriteAccess; 2922 for (ScopStmt &Stmt : *this) { 2923 2924 // Skip statements with an empty domain as they will never be executed. 2925 isl_set *StmtDomain = Stmt.getDomain(); 2926 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain); 2927 isl_set_free(StmtDomain); 2928 if (StmtDomainEmpty) 2929 continue; 2930 2931 for (MemoryAccess *MA : Stmt) { 2932 if (MA->isScalarKind()) 2933 continue; 2934 if (!MA->isRead()) 2935 HasWriteAccess.insert(MA->getBaseAddr()); 2936 MemAccInst Acc(MA->getAccessInstruction()); 2937 if (MA->isRead() && isa<MemTransferInst>(Acc)) 2938 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA; 2939 else 2940 PtrToAcc[Acc.getPointerOperand()] = MA; 2941 AST.add(Acc); 2942 } 2943 } 2944 2945 SmallVector<AliasGroupTy, 4> AliasGroups; 2946 for (AliasSet &AS : AST) { 2947 if (AS.isMustAlias() || AS.isForwardingAliasSet()) 2948 continue; 2949 AliasGroupTy AG; 2950 for (auto &PR : AS) 2951 AG.push_back(PtrToAcc[PR.getValue()]); 2952 if (AG.size() < 2) 2953 continue; 2954 AliasGroups.push_back(std::move(AG)); 2955 } 2956 2957 // Split the alias groups based on their domain. 2958 for (unsigned u = 0; u < AliasGroups.size(); u++) { 2959 AliasGroupTy NewAG; 2960 AliasGroupTy &AG = AliasGroups[u]; 2961 AliasGroupTy::iterator AGI = AG.begin(); 2962 isl_set *AGDomain = getAccessDomain(*AGI); 2963 while (AGI != AG.end()) { 2964 MemoryAccess *MA = *AGI; 2965 isl_set *MADomain = getAccessDomain(MA); 2966 if (isl_set_is_disjoint(AGDomain, MADomain)) { 2967 NewAG.push_back(MA); 2968 AGI = AG.erase(AGI); 2969 isl_set_free(MADomain); 2970 } else { 2971 AGDomain = isl_set_union(AGDomain, MADomain); 2972 AGI++; 2973 } 2974 } 2975 if (NewAG.size() > 1) 2976 AliasGroups.push_back(std::move(NewAG)); 2977 isl_set_free(AGDomain); 2978 } 2979 2980 auto &F = getFunction(); 2981 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs; 2982 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues; 2983 for (AliasGroupTy &AG : AliasGroups) { 2984 NonReadOnlyBaseValues.clear(); 2985 ReadOnlyPairs.clear(); 2986 2987 if (AG.size() < 2) { 2988 AG.clear(); 2989 continue; 2990 } 2991 2992 for (auto II = AG.begin(); II != AG.end();) { 2993 emitOptimizationRemarkAnalysis( 2994 F.getContext(), DEBUG_TYPE, F, 2995 (*II)->getAccessInstruction()->getDebugLoc(), 2996 "Possibly aliasing pointer, use restrict keyword."); 2997 2998 Value *BaseAddr = (*II)->getBaseAddr(); 2999 if (HasWriteAccess.count(BaseAddr)) { 3000 NonReadOnlyBaseValues.insert(BaseAddr); 3001 II++; 3002 } else { 3003 ReadOnlyPairs[BaseAddr].insert(*II); 3004 II = AG.erase(II); 3005 } 3006 } 3007 3008 // If we don't have read only pointers check if there are at least two 3009 // non read only pointers, otherwise clear the alias group. 3010 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) { 3011 AG.clear(); 3012 continue; 3013 } 3014 3015 // If we don't have non read only pointers clear the alias group. 3016 if (NonReadOnlyBaseValues.empty()) { 3017 AG.clear(); 3018 continue; 3019 } 3020 3021 // Check if we have non-affine accesses left, if so bail out as we cannot 3022 // generate a good access range yet. 3023 for (auto *MA : AG) { 3024 if (!MA->isAffine()) { 3025 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc()); 3026 return false; 3027 } 3028 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) 3029 addRequiredInvariantLoad( 3030 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3031 } 3032 for (auto &ReadOnlyPair : ReadOnlyPairs) 3033 for (auto *MA : ReadOnlyPair.second) { 3034 if (!MA->isAffine()) { 3035 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc()); 3036 return false; 3037 } 3038 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) 3039 addRequiredInvariantLoad( 3040 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3041 } 3042 3043 // Calculate minimal and maximal accesses for non read only accesses. 3044 MinMaxAliasGroups.emplace_back(); 3045 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back(); 3046 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first; 3047 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second; 3048 MinMaxAccessesNonReadOnly.reserve(AG.size()); 3049 3050 isl_union_map *Accesses = isl_union_map_empty(getParamSpace()); 3051 3052 // AG contains only non read only accesses. 3053 for (MemoryAccess *MA : AG) 3054 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation()); 3055 3056 bool Valid = calculateMinMaxAccess(Accesses, getDomains(), 3057 MinMaxAccessesNonReadOnly); 3058 3059 // Bail out if the number of values we need to compare is too large. 3060 // This is important as the number of comparisions grows quadratically with 3061 // the number of values we need to compare. 3062 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() > 3063 RunTimeChecksMaxArraysPerGroup)) 3064 return false; 3065 3066 // Calculate minimal and maximal accesses for read only accesses. 3067 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size()); 3068 Accesses = isl_union_map_empty(getParamSpace()); 3069 3070 for (const auto &ReadOnlyPair : ReadOnlyPairs) 3071 for (MemoryAccess *MA : ReadOnlyPair.second) 3072 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation()); 3073 3074 Valid = 3075 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly); 3076 3077 if (!Valid) 3078 return false; 3079 } 3080 3081 return true; 3082 } 3083 3084 /// Get the smallest loop that contains @p S but is not in @p S. 3085 static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) { 3086 // Start with the smallest loop containing the entry and expand that 3087 // loop until it contains all blocks in the region. If there is a loop 3088 // containing all blocks in the region check if it is itself contained 3089 // and if so take the parent loop as it will be the smallest containing 3090 // the region but not contained by it. 3091 Loop *L = LI.getLoopFor(S.getEntry()); 3092 while (L) { 3093 bool AllContained = true; 3094 for (auto *BB : S.blocks()) 3095 AllContained &= L->contains(BB); 3096 if (AllContained) 3097 break; 3098 L = L->getParentLoop(); 3099 } 3100 3101 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr; 3102 } 3103 3104 Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI, 3105 ScopDetection::DetectionContext &DC) 3106 : SE(&ScalarEvolution), R(R), IsOptimized(false), 3107 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false), 3108 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC), 3109 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr), 3110 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr), 3111 Schedule(nullptr) { 3112 if (IslOnErrorAbort) 3113 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT); 3114 buildContext(); 3115 } 3116 3117 void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT, 3118 LoopInfo &LI) { 3119 buildInvariantEquivalenceClasses(); 3120 3121 if (!buildDomains(&R, DT, LI)) 3122 return; 3123 3124 addUserAssumptions(AC, DT, LI); 3125 3126 // Remove empty statements. 3127 // Exit early in case there are no executable statements left in this scop. 3128 simplifySCoP(false); 3129 if (Stmts.empty()) 3130 return; 3131 3132 // The ScopStmts now have enough information to initialize themselves. 3133 for (ScopStmt &Stmt : Stmts) 3134 Stmt.init(LI); 3135 3136 // Check early for profitability. Afterwards it cannot change anymore, 3137 // only the runtime context could become infeasible. 3138 if (!isProfitable()) { 3139 invalidate(PROFITABLE, DebugLoc()); 3140 return; 3141 } 3142 3143 buildSchedule(LI); 3144 3145 updateAccessDimensionality(); 3146 realignParams(); 3147 addUserContext(); 3148 3149 // After the context was fully constructed, thus all our knowledge about 3150 // the parameters is in there, we add all recorded assumptions to the 3151 // assumed/invalid context. 3152 addRecordedAssumptions(); 3153 3154 simplifyContexts(); 3155 if (!buildAliasChecks(AA)) 3156 return; 3157 3158 hoistInvariantLoads(); 3159 verifyInvariantLoads(); 3160 simplifySCoP(true); 3161 3162 // Check late for a feasible runtime context because profitability did not 3163 // change. 3164 if (!hasFeasibleRuntimeContext()) { 3165 invalidate(PROFITABLE, DebugLoc()); 3166 return; 3167 } 3168 } 3169 3170 Scop::~Scop() { 3171 isl_set_free(Context); 3172 isl_set_free(AssumedContext); 3173 isl_set_free(InvalidContext); 3174 isl_schedule_free(Schedule); 3175 3176 for (auto &It : ParameterIds) 3177 isl_id_free(It.second); 3178 3179 for (auto It : DomainMap) 3180 isl_set_free(It.second); 3181 3182 for (auto &AS : RecordedAssumptions) 3183 isl_set_free(AS.Set); 3184 3185 // Free the alias groups 3186 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) { 3187 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) { 3188 isl_pw_multi_aff_free(MMA.first); 3189 isl_pw_multi_aff_free(MMA.second); 3190 } 3191 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) { 3192 isl_pw_multi_aff_free(MMA.first); 3193 isl_pw_multi_aff_free(MMA.second); 3194 } 3195 } 3196 3197 for (const auto &IAClass : InvariantEquivClasses) 3198 isl_set_free(IAClass.ExecutionContext); 3199 3200 // Explicitly release all Scop objects and the underlying isl objects before 3201 // we relase the isl context. 3202 Stmts.clear(); 3203 ScopArrayInfoSet.clear(); 3204 ScopArrayInfoMap.clear(); 3205 ScopArrayNameMap.clear(); 3206 AccessFunctions.clear(); 3207 } 3208 3209 void Scop::updateAccessDimensionality() { 3210 // Check all array accesses for each base pointer and find a (virtual) element 3211 // size for the base pointer that divides all access functions. 3212 for (auto &Stmt : *this) 3213 for (auto *Access : Stmt) { 3214 if (!Access->isArrayKind()) 3215 continue; 3216 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(), 3217 ScopArrayInfo::MK_Array)]; 3218 if (SAI->getNumberOfDimensions() != 1) 3219 continue; 3220 unsigned DivisibleSize = SAI->getElemSizeInBytes(); 3221 auto *Subscript = Access->getSubscript(0); 3222 while (!isDivisible(Subscript, DivisibleSize, *SE)) 3223 DivisibleSize /= 2; 3224 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8); 3225 SAI->updateElementType(Ty); 3226 } 3227 3228 for (auto &Stmt : *this) 3229 for (auto &Access : Stmt) 3230 Access->updateDimensionality(); 3231 } 3232 3233 void Scop::simplifySCoP(bool AfterHoisting) { 3234 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) { 3235 ScopStmt &Stmt = *StmtIt; 3236 3237 bool RemoveStmt = Stmt.isEmpty(); 3238 if (!RemoveStmt) 3239 RemoveStmt = !DomainMap[Stmt.getEntryBlock()]; 3240 3241 // Remove read only statements only after invariant loop hoisting. 3242 if (!RemoveStmt && AfterHoisting) { 3243 bool OnlyRead = true; 3244 for (MemoryAccess *MA : Stmt) { 3245 if (MA->isRead()) 3246 continue; 3247 3248 OnlyRead = false; 3249 break; 3250 } 3251 3252 RemoveStmt = OnlyRead; 3253 } 3254 3255 if (!RemoveStmt) { 3256 StmtIt++; 3257 continue; 3258 } 3259 3260 // Remove the statement because it is unnecessary. 3261 if (Stmt.isRegionStmt()) 3262 for (BasicBlock *BB : Stmt.getRegion()->blocks()) 3263 StmtMap.erase(BB); 3264 else 3265 StmtMap.erase(Stmt.getBasicBlock()); 3266 3267 StmtIt = Stmts.erase(StmtIt); 3268 } 3269 } 3270 3271 InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) { 3272 LoadInst *LInst = dyn_cast<LoadInst>(Val); 3273 if (!LInst) 3274 return nullptr; 3275 3276 if (Value *Rep = InvEquivClassVMap.lookup(LInst)) 3277 LInst = cast<LoadInst>(Rep); 3278 3279 Type *Ty = LInst->getType(); 3280 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 3281 for (auto &IAClass : InvariantEquivClasses) { 3282 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3283 continue; 3284 3285 auto &MAs = IAClass.InvariantAccesses; 3286 for (auto *MA : MAs) 3287 if (MA->getAccessInstruction() == Val) 3288 return &IAClass; 3289 } 3290 3291 return nullptr; 3292 } 3293 3294 /// Check if @p MA can always be hoisted without execution context. 3295 static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty, 3296 bool MAInvalidCtxIsEmpty, 3297 bool NonHoistableCtxIsEmpty) { 3298 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3299 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout(); 3300 // TODO: We can provide more information for better but more expensive 3301 // results. 3302 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(), 3303 LInst->getAlignment(), DL)) 3304 return false; 3305 3306 // If the location might be overwritten we do not hoist it unconditionally. 3307 // 3308 // TODO: This is probably to conservative. 3309 if (!NonHoistableCtxIsEmpty) 3310 return false; 3311 3312 // If a dereferencable load is in a statement that is modeled precisely we can 3313 // hoist it. 3314 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty) 3315 return true; 3316 3317 // Even if the statement is not modeled precisely we can hoist the load if it 3318 // does not involve any parameters that might have been specilized by the 3319 // statement domain. 3320 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++) 3321 if (!isa<SCEVConstant>(MA->getSubscript(u))) 3322 return false; 3323 return true; 3324 } 3325 3326 void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) { 3327 3328 if (InvMAs.empty()) 3329 return; 3330 3331 auto *StmtInvalidCtx = Stmt.getInvalidContext(); 3332 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx); 3333 3334 // Get the context under which the statement is executed but remove the error 3335 // context under which this statement is reached. 3336 isl_set *DomainCtx = isl_set_params(Stmt.getDomain()); 3337 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx); 3338 3339 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) { 3340 auto *AccInst = InvMAs.front().MA->getAccessInstruction(); 3341 invalidate(COMPLEXITY, AccInst->getDebugLoc()); 3342 isl_set_free(DomainCtx); 3343 for (auto &InvMA : InvMAs) 3344 isl_set_free(InvMA.NonHoistableCtx); 3345 return; 3346 } 3347 3348 // Project out all parameters that relate to loads in the statement. Otherwise 3349 // we could have cyclic dependences on the constraints under which the 3350 // hoisted loads are executed and we could not determine an order in which to 3351 // pre-load them. This happens because not only lower bounds are part of the 3352 // domain but also upper bounds. 3353 for (auto &InvMA : InvMAs) { 3354 auto *MA = InvMA.MA; 3355 Instruction *AccInst = MA->getAccessInstruction(); 3356 if (SE->isSCEVable(AccInst->getType())) { 3357 SetVector<Value *> Values; 3358 for (const SCEV *Parameter : Parameters) { 3359 Values.clear(); 3360 findValues(Parameter, *SE, Values); 3361 if (!Values.count(AccInst)) 3362 continue; 3363 3364 if (isl_id *ParamId = getIdForParam(Parameter)) { 3365 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId); 3366 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1); 3367 isl_id_free(ParamId); 3368 } 3369 } 3370 } 3371 } 3372 3373 for (auto &InvMA : InvMAs) { 3374 auto *MA = InvMA.MA; 3375 auto *NHCtx = InvMA.NonHoistableCtx; 3376 3377 // Check for another invariant access that accesses the same location as 3378 // MA and if found consolidate them. Otherwise create a new equivalence 3379 // class at the end of InvariantEquivClasses. 3380 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3381 Type *Ty = LInst->getType(); 3382 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 3383 3384 auto *MAInvalidCtx = MA->getInvalidContext(); 3385 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx); 3386 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx); 3387 3388 isl_set *MACtx; 3389 // Check if we know that this pointer can be speculatively accessed. 3390 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty, 3391 NonHoistableCtxIsEmpty)) { 3392 MACtx = isl_set_universe(isl_set_get_space(DomainCtx)); 3393 isl_set_free(MAInvalidCtx); 3394 isl_set_free(NHCtx); 3395 } else { 3396 MACtx = isl_set_copy(DomainCtx); 3397 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx)); 3398 MACtx = isl_set_gist_params(MACtx, getContext()); 3399 } 3400 3401 bool Consolidated = false; 3402 for (auto &IAClass : InvariantEquivClasses) { 3403 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3404 continue; 3405 3406 // If the pointer and the type is equal check if the access function wrt. 3407 // to the domain is equal too. It can happen that the domain fixes 3408 // parameter values and these can be different for distinct part of the 3409 // SCoP. If this happens we cannot consolidate the loads but need to 3410 // create a new invariant load equivalence class. 3411 auto &MAs = IAClass.InvariantAccesses; 3412 if (!MAs.empty()) { 3413 auto *LastMA = MAs.front(); 3414 3415 auto *AR = isl_map_range(MA->getAccessRelation()); 3416 auto *LastAR = isl_map_range(LastMA->getAccessRelation()); 3417 bool SameAR = isl_set_is_equal(AR, LastAR); 3418 isl_set_free(AR); 3419 isl_set_free(LastAR); 3420 3421 if (!SameAR) 3422 continue; 3423 } 3424 3425 // Add MA to the list of accesses that are in this class. 3426 MAs.push_front(MA); 3427 3428 Consolidated = true; 3429 3430 // Unify the execution context of the class and this statement. 3431 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext; 3432 if (IAClassDomainCtx) 3433 IAClassDomainCtx = 3434 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx)); 3435 else 3436 IAClassDomainCtx = MACtx; 3437 break; 3438 } 3439 3440 if (Consolidated) 3441 continue; 3442 3443 // If we did not consolidate MA, thus did not find an equivalence class 3444 // for it, we create a new one. 3445 InvariantEquivClasses.emplace_back( 3446 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty}); 3447 } 3448 3449 isl_set_free(DomainCtx); 3450 } 3451 3452 __isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access, 3453 __isl_keep isl_union_map *Writes) { 3454 // TODO: Loads that are not loop carried, hence are in a statement with 3455 // zero iterators, are by construction invariant, though we 3456 // currently "hoist" them anyway. This is necessary because we allow 3457 // them to be treated as parameters (e.g., in conditions) and our code 3458 // generation would otherwise use the old value. 3459 3460 auto &Stmt = *Access->getStatement(); 3461 BasicBlock *BB = Stmt.getEntryBlock(); 3462 3463 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine()) 3464 return nullptr; 3465 3466 // Skip accesses that have an invariant base pointer which is defined but 3467 // not loaded inside the SCoP. This can happened e.g., if a readnone call 3468 // returns a pointer that is used as a base address. However, as we want 3469 // to hoist indirect pointers, we allow the base pointer to be defined in 3470 // the region if it is also a memory access. Each ScopArrayInfo object 3471 // that has a base pointer origin has a base pointer that is loaded and 3472 // that it is invariant, thus it will be hoisted too. However, if there is 3473 // no base pointer origin we check that the base pointer is defined 3474 // outside the region. 3475 auto *LI = cast<LoadInst>(Access->getAccessInstruction()); 3476 if (hasNonHoistableBasePtrInScop(Access, Writes)) 3477 return nullptr; 3478 3479 // Skip accesses in non-affine subregions as they might not be executed 3480 // under the same condition as the entry of the non-affine subregion. 3481 if (BB != LI->getParent()) 3482 return nullptr; 3483 3484 isl_map *AccessRelation = Access->getAccessRelation(); 3485 assert(!isl_map_is_empty(AccessRelation)); 3486 3487 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0, 3488 Stmt.getNumIterators())) { 3489 isl_map_free(AccessRelation); 3490 return nullptr; 3491 } 3492 3493 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain()); 3494 isl_set *AccessRange = isl_map_range(AccessRelation); 3495 3496 isl_union_map *Written = isl_union_map_intersect_range( 3497 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange)); 3498 auto *WrittenCtx = isl_union_map_params(Written); 3499 bool IsWritten = !isl_set_is_empty(WrittenCtx); 3500 3501 if (!IsWritten) 3502 return WrittenCtx; 3503 3504 WrittenCtx = isl_set_remove_divs(WrittenCtx); 3505 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain; 3506 if (TooComplex || !isRequiredInvariantLoad(LI)) { 3507 isl_set_free(WrittenCtx); 3508 return nullptr; 3509 } 3510 3511 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(), 3512 AS_RESTRICTION); 3513 return WrittenCtx; 3514 } 3515 3516 void Scop::verifyInvariantLoads() { 3517 auto &RIL = getRequiredInvariantLoads(); 3518 for (LoadInst *LI : RIL) { 3519 assert(LI && contains(LI)); 3520 ScopStmt *Stmt = getStmtFor(LI); 3521 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) { 3522 invalidate(INVARIANTLOAD, LI->getDebugLoc()); 3523 return; 3524 } 3525 } 3526 } 3527 3528 void Scop::hoistInvariantLoads() { 3529 if (!PollyInvariantLoadHoisting) 3530 return; 3531 3532 isl_union_map *Writes = getWrites(); 3533 for (ScopStmt &Stmt : *this) { 3534 InvariantAccessesTy InvariantAccesses; 3535 3536 for (MemoryAccess *Access : Stmt) 3537 if (auto *NHCtx = getNonHoistableCtx(Access, Writes)) 3538 InvariantAccesses.push_back({Access, NHCtx}); 3539 3540 // Transfer the memory access from the statement to the SCoP. 3541 for (auto InvMA : InvariantAccesses) 3542 Stmt.removeMemoryAccess(InvMA.MA); 3543 addInvariantLoads(Stmt, InvariantAccesses); 3544 } 3545 isl_union_map_free(Writes); 3546 } 3547 3548 const ScopArrayInfo *Scop::getOrCreateScopArrayInfo( 3549 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes, 3550 ScopArrayInfo::MemoryKind Kind, const char *BaseName) { 3551 assert((BasePtr || BaseName) && 3552 "BasePtr and BaseName can not be nullptr at the same time."); 3553 assert(!(BasePtr && BaseName) && "BaseName is redundant."); 3554 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)] 3555 : ScopArrayNameMap[BaseName]; 3556 if (!SAI) { 3557 auto &DL = getFunction().getParent()->getDataLayout(); 3558 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind, 3559 DL, this, BaseName)); 3560 ScopArrayInfoSet.insert(SAI.get()); 3561 } else { 3562 SAI->updateElementType(ElementType); 3563 // In case of mismatching array sizes, we bail out by setting the run-time 3564 // context to false. 3565 if (!SAI->updateSizes(Sizes)) 3566 invalidate(DELINEARIZATION, DebugLoc()); 3567 } 3568 return SAI.get(); 3569 } 3570 3571 const ScopArrayInfo * 3572 Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName, 3573 const std::vector<unsigned> &Sizes) { 3574 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext()); 3575 std::vector<const SCEV *> SCEVSizes; 3576 3577 for (auto size : Sizes) 3578 if (size) 3579 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false)); 3580 else 3581 SCEVSizes.push_back(nullptr); 3582 3583 auto *SAI = 3584 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes, 3585 ScopArrayInfo::MK_Array, BaseName.c_str()); 3586 return SAI; 3587 } 3588 3589 const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, 3590 ScopArrayInfo::MemoryKind Kind) { 3591 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get(); 3592 assert(SAI && "No ScopArrayInfo available for this base pointer"); 3593 return SAI; 3594 } 3595 3596 std::string Scop::getContextStr() const { return stringFromIslObj(Context); } 3597 3598 std::string Scop::getAssumedContextStr() const { 3599 assert(AssumedContext && "Assumed context not yet built"); 3600 return stringFromIslObj(AssumedContext); 3601 } 3602 3603 std::string Scop::getInvalidContextStr() const { 3604 return stringFromIslObj(InvalidContext); 3605 } 3606 3607 std::string Scop::getNameStr() const { 3608 std::string ExitName, EntryName; 3609 raw_string_ostream ExitStr(ExitName); 3610 raw_string_ostream EntryStr(EntryName); 3611 3612 R.getEntry()->printAsOperand(EntryStr, false); 3613 EntryStr.str(); 3614 3615 if (R.getExit()) { 3616 R.getExit()->printAsOperand(ExitStr, false); 3617 ExitStr.str(); 3618 } else 3619 ExitName = "FunctionExit"; 3620 3621 return EntryName + "---" + ExitName; 3622 } 3623 3624 __isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); } 3625 __isl_give isl_space *Scop::getParamSpace() const { 3626 return isl_set_get_space(Context); 3627 } 3628 3629 __isl_give isl_set *Scop::getAssumedContext() const { 3630 assert(AssumedContext && "Assumed context not yet built"); 3631 return isl_set_copy(AssumedContext); 3632 } 3633 3634 bool Scop::isProfitable() const { 3635 if (PollyProcessUnprofitable) 3636 return true; 3637 3638 if (!hasFeasibleRuntimeContext()) 3639 return false; 3640 3641 if (isEmpty()) 3642 return false; 3643 3644 unsigned OptimizableStmtsOrLoops = 0; 3645 for (auto &Stmt : *this) { 3646 if (Stmt.getNumIterators() == 0) 3647 continue; 3648 3649 bool ContainsArrayAccs = false; 3650 bool ContainsScalarAccs = false; 3651 for (auto *MA : Stmt) { 3652 if (MA->isRead()) 3653 continue; 3654 ContainsArrayAccs |= MA->isArrayKind(); 3655 ContainsScalarAccs |= MA->isScalarKind(); 3656 } 3657 3658 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs)) 3659 OptimizableStmtsOrLoops += Stmt.getNumIterators(); 3660 } 3661 3662 return OptimizableStmtsOrLoops > 1; 3663 } 3664 3665 bool Scop::hasFeasibleRuntimeContext() const { 3666 auto *PositiveContext = getAssumedContext(); 3667 auto *NegativeContext = getInvalidContext(); 3668 PositiveContext = addNonEmptyDomainConstraints(PositiveContext); 3669 bool IsFeasible = !(isl_set_is_empty(PositiveContext) || 3670 isl_set_is_subset(PositiveContext, NegativeContext)); 3671 isl_set_free(PositiveContext); 3672 if (!IsFeasible) { 3673 isl_set_free(NegativeContext); 3674 return false; 3675 } 3676 3677 auto *DomainContext = isl_union_set_params(getDomains()); 3678 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext); 3679 IsFeasible &= !isl_set_is_subset(Context, NegativeContext); 3680 isl_set_free(NegativeContext); 3681 isl_set_free(DomainContext); 3682 3683 return IsFeasible; 3684 } 3685 3686 static std::string toString(AssumptionKind Kind) { 3687 switch (Kind) { 3688 case ALIASING: 3689 return "No-aliasing"; 3690 case INBOUNDS: 3691 return "Inbounds"; 3692 case WRAPPING: 3693 return "No-overflows"; 3694 case UNSIGNED: 3695 return "Signed-unsigned"; 3696 case COMPLEXITY: 3697 return "Low complexity"; 3698 case PROFITABLE: 3699 return "Profitable"; 3700 case ERRORBLOCK: 3701 return "No-error"; 3702 case INFINITELOOP: 3703 return "Finite loop"; 3704 case INVARIANTLOAD: 3705 return "Invariant load"; 3706 case DELINEARIZATION: 3707 return "Delinearization"; 3708 } 3709 llvm_unreachable("Unknown AssumptionKind!"); 3710 } 3711 3712 bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) { 3713 if (Sign == AS_ASSUMPTION) { 3714 if (isl_set_is_subset(Context, Set)) 3715 return false; 3716 3717 if (isl_set_is_subset(AssumedContext, Set)) 3718 return false; 3719 } else { 3720 if (isl_set_is_disjoint(Set, Context)) 3721 return false; 3722 3723 if (isl_set_is_subset(Set, InvalidContext)) 3724 return false; 3725 } 3726 return true; 3727 } 3728 3729 bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set, 3730 DebugLoc Loc, AssumptionSign Sign) { 3731 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign)) 3732 return false; 3733 3734 auto &F = getFunction(); 3735 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t"; 3736 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set); 3737 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg); 3738 return true; 3739 } 3740 3741 void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set, 3742 DebugLoc Loc, AssumptionSign Sign) { 3743 // Simplify the assumptions/restrictions first. 3744 Set = isl_set_gist_params(Set, getContext()); 3745 3746 if (!trackAssumption(Kind, Set, Loc, Sign)) { 3747 isl_set_free(Set); 3748 return; 3749 } 3750 3751 if (Sign == AS_ASSUMPTION) { 3752 AssumedContext = isl_set_intersect(AssumedContext, Set); 3753 AssumedContext = isl_set_coalesce(AssumedContext); 3754 } else { 3755 InvalidContext = isl_set_union(InvalidContext, Set); 3756 InvalidContext = isl_set_coalesce(InvalidContext); 3757 } 3758 } 3759 3760 void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set, 3761 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) { 3762 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB}); 3763 } 3764 3765 void Scop::addRecordedAssumptions() { 3766 while (!RecordedAssumptions.empty()) { 3767 const Assumption &AS = RecordedAssumptions.pop_back_val(); 3768 3769 if (!AS.BB) { 3770 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign); 3771 continue; 3772 } 3773 3774 // If the domain was deleted the assumptions are void. 3775 isl_set *Dom = getDomainConditions(AS.BB); 3776 if (!Dom) { 3777 isl_set_free(AS.Set); 3778 continue; 3779 } 3780 3781 // If a basic block was given use its domain to simplify the assumption. 3782 // In case of restrictions we know they only have to hold on the domain, 3783 // thus we can intersect them with the domain of the block. However, for 3784 // assumptions the domain has to imply them, thus: 3785 // _ _____ 3786 // Dom => S <==> A v B <==> A - B 3787 // 3788 // To avoid the complement we will register A - B as a restricton not an 3789 // assumption. 3790 isl_set *S = AS.Set; 3791 if (AS.Sign == AS_RESTRICTION) 3792 S = isl_set_params(isl_set_intersect(S, Dom)); 3793 else /* (AS.Sign == AS_ASSUMPTION) */ 3794 S = isl_set_params(isl_set_subtract(Dom, S)); 3795 3796 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION); 3797 } 3798 } 3799 3800 void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) { 3801 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION); 3802 } 3803 3804 __isl_give isl_set *Scop::getInvalidContext() const { 3805 return isl_set_copy(InvalidContext); 3806 } 3807 3808 void Scop::printContext(raw_ostream &OS) const { 3809 OS << "Context:\n"; 3810 OS.indent(4) << Context << "\n"; 3811 3812 OS.indent(4) << "Assumed Context:\n"; 3813 OS.indent(4) << AssumedContext << "\n"; 3814 3815 OS.indent(4) << "Invalid Context:\n"; 3816 OS.indent(4) << InvalidContext << "\n"; 3817 3818 unsigned Dim = 0; 3819 for (const SCEV *Parameter : Parameters) 3820 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n"; 3821 } 3822 3823 void Scop::printAliasAssumptions(raw_ostream &OS) const { 3824 int noOfGroups = 0; 3825 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) { 3826 if (Pair.second.size() == 0) 3827 noOfGroups += 1; 3828 else 3829 noOfGroups += Pair.second.size(); 3830 } 3831 3832 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n"; 3833 if (MinMaxAliasGroups.empty()) { 3834 OS.indent(8) << "n/a\n"; 3835 return; 3836 } 3837 3838 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) { 3839 3840 // If the group has no read only accesses print the write accesses. 3841 if (Pair.second.empty()) { 3842 OS.indent(8) << "[["; 3843 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) { 3844 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second 3845 << ">"; 3846 } 3847 OS << " ]]\n"; 3848 } 3849 3850 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) { 3851 OS.indent(8) << "[["; 3852 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">"; 3853 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) { 3854 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second 3855 << ">"; 3856 } 3857 OS << " ]]\n"; 3858 } 3859 } 3860 } 3861 3862 void Scop::printStatements(raw_ostream &OS) const { 3863 OS << "Statements {\n"; 3864 3865 for (const ScopStmt &Stmt : *this) 3866 OS.indent(4) << Stmt; 3867 3868 OS.indent(4) << "}\n"; 3869 } 3870 3871 void Scop::printArrayInfo(raw_ostream &OS) const { 3872 OS << "Arrays {\n"; 3873 3874 for (auto &Array : arrays()) 3875 Array->print(OS); 3876 3877 OS.indent(4) << "}\n"; 3878 3879 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n"; 3880 3881 for (auto &Array : arrays()) 3882 Array->print(OS, /* SizeAsPwAff */ true); 3883 3884 OS.indent(4) << "}\n"; 3885 } 3886 3887 void Scop::print(raw_ostream &OS) const { 3888 OS.indent(4) << "Function: " << getFunction().getName() << "\n"; 3889 OS.indent(4) << "Region: " << getNameStr() << "\n"; 3890 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n"; 3891 OS.indent(4) << "Invariant Accesses: {\n"; 3892 for (const auto &IAClass : InvariantEquivClasses) { 3893 const auto &MAs = IAClass.InvariantAccesses; 3894 if (MAs.empty()) { 3895 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n"; 3896 } else { 3897 MAs.front()->print(OS); 3898 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext 3899 << "\n"; 3900 } 3901 } 3902 OS.indent(4) << "}\n"; 3903 printContext(OS.indent(4)); 3904 printArrayInfo(OS.indent(4)); 3905 printAliasAssumptions(OS); 3906 printStatements(OS.indent(4)); 3907 } 3908 3909 void Scop::dump() const { print(dbgs()); } 3910 3911 isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); } 3912 3913 __isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB, 3914 bool NonNegative) { 3915 // First try to use the SCEVAffinator to generate a piecewise defined 3916 // affine function from @p E in the context of @p BB. If that tasks becomes to 3917 // complex the affinator might return a nullptr. In such a case we invalidate 3918 // the SCoP and return a dummy value. This way we do not need to add error 3919 // handling cdoe to all users of this function. 3920 auto PWAC = Affinator.getPwAff(E, BB); 3921 if (PWAC.first) { 3922 // TODO: We could use a heuristic and either use: 3923 // SCEVAffinator::takeNonNegativeAssumption 3924 // or 3925 // SCEVAffinator::interpretAsUnsigned 3926 // to deal with unsigned or "NonNegative" SCEVs. 3927 if (NonNegative) 3928 Affinator.takeNonNegativeAssumption(PWAC); 3929 return PWAC; 3930 } 3931 3932 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc(); 3933 invalidate(COMPLEXITY, DL); 3934 return Affinator.getPwAff(SE->getZero(E->getType()), BB); 3935 } 3936 3937 __isl_give isl_union_set *Scop::getDomains() const { 3938 isl_union_set *Domain = isl_union_set_empty(getParamSpace()); 3939 3940 for (const ScopStmt &Stmt : *this) 3941 Domain = isl_union_set_add_set(Domain, Stmt.getDomain()); 3942 3943 return Domain; 3944 } 3945 3946 __isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) { 3947 PWACtx PWAC = getPwAff(E, BB); 3948 isl_set_free(PWAC.second); 3949 return PWAC.first; 3950 } 3951 3952 __isl_give isl_union_map * 3953 Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) { 3954 isl_union_map *Accesses = isl_union_map_empty(getParamSpace()); 3955 3956 for (ScopStmt &Stmt : *this) { 3957 for (MemoryAccess *MA : Stmt) { 3958 if (!Predicate(*MA)) 3959 continue; 3960 3961 isl_set *Domain = Stmt.getDomain(); 3962 isl_map *AccessDomain = MA->getAccessRelation(); 3963 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain); 3964 Accesses = isl_union_map_add_map(Accesses, AccessDomain); 3965 } 3966 } 3967 return isl_union_map_coalesce(Accesses); 3968 } 3969 3970 __isl_give isl_union_map *Scop::getMustWrites() { 3971 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); }); 3972 } 3973 3974 __isl_give isl_union_map *Scop::getMayWrites() { 3975 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); }); 3976 } 3977 3978 __isl_give isl_union_map *Scop::getWrites() { 3979 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); }); 3980 } 3981 3982 __isl_give isl_union_map *Scop::getReads() { 3983 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); }); 3984 } 3985 3986 __isl_give isl_union_map *Scop::getAccesses() { 3987 return getAccessesOfType([](MemoryAccess &MA) { return true; }); 3988 } 3989 3990 // Check whether @p Node is an extension node. 3991 // 3992 // @return true if @p Node is an extension node. 3993 isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) { 3994 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension) 3995 return isl_bool_error; 3996 else 3997 return isl_bool_true; 3998 } 3999 4000 bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) { 4001 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode, 4002 nullptr) == isl_stat_error; 4003 } 4004 4005 __isl_give isl_union_map *Scop::getSchedule() const { 4006 auto *Tree = getScheduleTree(); 4007 if (containsExtensionNode(Tree)) { 4008 isl_schedule_free(Tree); 4009 return nullptr; 4010 } 4011 auto *S = isl_schedule_get_map(Tree); 4012 isl_schedule_free(Tree); 4013 return S; 4014 } 4015 4016 __isl_give isl_schedule *Scop::getScheduleTree() const { 4017 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule), 4018 getDomains()); 4019 } 4020 4021 void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) { 4022 auto *S = isl_schedule_from_domain(getDomains()); 4023 S = isl_schedule_insert_partial_schedule( 4024 S, isl_multi_union_pw_aff_from_union_map(NewSchedule)); 4025 isl_schedule_free(Schedule); 4026 Schedule = S; 4027 } 4028 4029 void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) { 4030 isl_schedule_free(Schedule); 4031 Schedule = NewSchedule; 4032 } 4033 4034 bool Scop::restrictDomains(__isl_take isl_union_set *Domain) { 4035 bool Changed = false; 4036 for (ScopStmt &Stmt : *this) { 4037 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain()); 4038 isl_union_set *NewStmtDomain = isl_union_set_intersect( 4039 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain)); 4040 4041 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) { 4042 isl_union_set_free(StmtDomain); 4043 isl_union_set_free(NewStmtDomain); 4044 continue; 4045 } 4046 4047 Changed = true; 4048 4049 isl_union_set_free(StmtDomain); 4050 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain); 4051 4052 if (isl_union_set_is_empty(NewStmtDomain)) { 4053 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace())); 4054 isl_union_set_free(NewStmtDomain); 4055 } else 4056 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain)); 4057 } 4058 isl_union_set_free(Domain); 4059 return Changed; 4060 } 4061 4062 ScalarEvolution *Scop::getSE() const { return SE; } 4063 4064 struct MapToDimensionDataTy { 4065 int N; 4066 isl_union_pw_multi_aff *Res; 4067 }; 4068 4069 // Create a function that maps the elements of 'Set' to its N-th dimension and 4070 // add it to User->Res. 4071 // 4072 // @param Set The input set. 4073 // @param User->N The dimension to map to. 4074 // @param User->Res The isl_union_pw_multi_aff to which to add the result. 4075 // 4076 // @returns isl_stat_ok if no error occured, othewise isl_stat_error. 4077 static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) { 4078 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User; 4079 int Dim; 4080 isl_space *Space; 4081 isl_pw_multi_aff *PMA; 4082 4083 Dim = isl_set_dim(Set, isl_dim_set); 4084 Space = isl_set_get_space(Set); 4085 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N, 4086 Dim - Data->N); 4087 if (Data->N > 1) 4088 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1); 4089 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA); 4090 4091 isl_set_free(Set); 4092 4093 return isl_stat_ok; 4094 } 4095 4096 // Create an isl_multi_union_aff that defines an identity mapping from the 4097 // elements of USet to their N-th dimension. 4098 // 4099 // # Example: 4100 // 4101 // Domain: { A[i,j]; B[i,j,k] } 4102 // N: 1 4103 // 4104 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] } 4105 // 4106 // @param USet A union set describing the elements for which to generate a 4107 // mapping. 4108 // @param N The dimension to map to. 4109 // @returns A mapping from USet to its N-th dimension. 4110 static __isl_give isl_multi_union_pw_aff * 4111 mapToDimension(__isl_take isl_union_set *USet, int N) { 4112 assert(N >= 0); 4113 assert(USet); 4114 assert(!isl_union_set_is_empty(USet)); 4115 4116 struct MapToDimensionDataTy Data; 4117 4118 auto *Space = isl_union_set_get_space(USet); 4119 auto *PwAff = isl_union_pw_multi_aff_empty(Space); 4120 4121 Data = {N, PwAff}; 4122 4123 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data); 4124 (void)Res; 4125 4126 assert(Res == isl_stat_ok); 4127 4128 isl_union_set_free(USet); 4129 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res); 4130 } 4131 4132 void Scop::addScopStmt(BasicBlock *BB, Region *R) { 4133 if (BB) { 4134 Stmts.emplace_back(*this, *BB); 4135 auto *Stmt = &Stmts.back(); 4136 StmtMap[BB] = Stmt; 4137 } else { 4138 assert(R && "Either basic block or a region expected."); 4139 Stmts.emplace_back(*this, *R); 4140 auto *Stmt = &Stmts.back(); 4141 for (BasicBlock *BB : R->blocks()) 4142 StmtMap[BB] = Stmt; 4143 } 4144 } 4145 4146 ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel, 4147 __isl_take isl_map *TargetRel, 4148 __isl_take isl_set *Domain) { 4149 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain); 4150 CopyStmtsNum++; 4151 return &(Stmts.back()); 4152 } 4153 4154 void Scop::buildSchedule(LoopInfo &LI) { 4155 Loop *L = getLoopSurroundingScop(*this, LI); 4156 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)}); 4157 buildSchedule(getRegion().getNode(), LoopStack, LI); 4158 assert(LoopStack.size() == 1 && LoopStack.back().L == L); 4159 Schedule = LoopStack[0].Schedule; 4160 } 4161 4162 /// To generate a schedule for the elements in a Region we traverse the Region 4163 /// in reverse-post-order and add the contained RegionNodes in traversal order 4164 /// to the schedule of the loop that is currently at the top of the LoopStack. 4165 /// For loop-free codes, this results in a correct sequential ordering. 4166 /// 4167 /// Example: 4168 /// bb1(0) 4169 /// / \. 4170 /// bb2(1) bb3(2) 4171 /// \ / \. 4172 /// bb4(3) bb5(4) 4173 /// \ / 4174 /// bb6(5) 4175 /// 4176 /// Including loops requires additional processing. Whenever a loop header is 4177 /// encountered, the corresponding loop is added to the @p LoopStack. Starting 4178 /// from an empty schedule, we first process all RegionNodes that are within 4179 /// this loop and complete the sequential schedule at this loop-level before 4180 /// processing about any other nodes. To implement this 4181 /// loop-nodes-first-processing, the reverse post-order traversal is 4182 /// insufficient. Hence, we additionally check if the traversal yields 4183 /// sub-regions or blocks that are outside the last loop on the @p LoopStack. 4184 /// These region-nodes are then queue and only traverse after the all nodes 4185 /// within the current loop have been processed. 4186 void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) { 4187 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI); 4188 4189 ReversePostOrderTraversal<Region *> RTraversal(R); 4190 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end()); 4191 std::deque<RegionNode *> DelayList; 4192 bool LastRNWaiting = false; 4193 4194 // Iterate over the region @p R in reverse post-order but queue 4195 // sub-regions/blocks iff they are not part of the last encountered but not 4196 // completely traversed loop. The variable LastRNWaiting is a flag to indicate 4197 // that we queued the last sub-region/block from the reverse post-order 4198 // iterator. If it is set we have to explore the next sub-region/block from 4199 // the iterator (if any) to guarantee progress. If it is not set we first try 4200 // the next queued sub-region/blocks. 4201 while (!WorkList.empty() || !DelayList.empty()) { 4202 RegionNode *RN; 4203 4204 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) { 4205 RN = WorkList.front(); 4206 WorkList.pop_front(); 4207 LastRNWaiting = false; 4208 } else { 4209 RN = DelayList.front(); 4210 DelayList.pop_front(); 4211 } 4212 4213 Loop *L = getRegionNodeLoop(RN, LI); 4214 if (!contains(L)) 4215 L = OuterScopLoop; 4216 4217 Loop *LastLoop = LoopStack.back().L; 4218 if (LastLoop != L) { 4219 if (LastLoop && !LastLoop->contains(L)) { 4220 LastRNWaiting = true; 4221 DelayList.push_back(RN); 4222 continue; 4223 } 4224 LoopStack.push_back({L, nullptr, 0}); 4225 } 4226 buildSchedule(RN, LoopStack, LI); 4227 } 4228 4229 return; 4230 } 4231 4232 void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) { 4233 4234 if (RN->isSubRegion()) { 4235 auto *LocalRegion = RN->getNodeAs<Region>(); 4236 if (!isNonAffineSubRegion(LocalRegion)) { 4237 buildSchedule(LocalRegion, LoopStack, LI); 4238 return; 4239 } 4240 } 4241 4242 auto &LoopData = LoopStack.back(); 4243 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN); 4244 4245 if (auto *Stmt = getStmtFor(RN)) { 4246 auto *UDomain = isl_union_set_from_set(Stmt->getDomain()); 4247 auto *StmtSchedule = isl_schedule_from_domain(UDomain); 4248 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule); 4249 } 4250 4251 // Check if we just processed the last node in this loop. If we did, finalize 4252 // the loop by: 4253 // 4254 // - adding new schedule dimensions 4255 // - folding the resulting schedule into the parent loop schedule 4256 // - dropping the loop schedule from the LoopStack. 4257 // 4258 // Then continue to check surrounding loops, which might also have been 4259 // completed by this node. 4260 while (LoopData.L && 4261 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) { 4262 auto *Schedule = LoopData.Schedule; 4263 auto NumBlocksProcessed = LoopData.NumBlocksProcessed; 4264 4265 LoopStack.pop_back(); 4266 auto &NextLoopData = LoopStack.back(); 4267 4268 if (Schedule) { 4269 auto *Domain = isl_schedule_get_domain(Schedule); 4270 auto *MUPA = mapToDimension(Domain, LoopStack.size()); 4271 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA); 4272 NextLoopData.Schedule = 4273 combineInSequence(NextLoopData.Schedule, Schedule); 4274 } 4275 4276 NextLoopData.NumBlocksProcessed += NumBlocksProcessed; 4277 LoopData = NextLoopData; 4278 } 4279 } 4280 4281 ScopStmt *Scop::getStmtFor(BasicBlock *BB) const { 4282 auto StmtMapIt = StmtMap.find(BB); 4283 if (StmtMapIt == StmtMap.end()) 4284 return nullptr; 4285 return StmtMapIt->second; 4286 } 4287 4288 ScopStmt *Scop::getStmtFor(RegionNode *RN) const { 4289 if (RN->isSubRegion()) 4290 return getStmtFor(RN->getNodeAs<Region>()); 4291 return getStmtFor(RN->getNodeAs<BasicBlock>()); 4292 } 4293 4294 ScopStmt *Scop::getStmtFor(Region *R) const { 4295 ScopStmt *Stmt = getStmtFor(R->getEntry()); 4296 assert(!Stmt || Stmt->getRegion() == R); 4297 return Stmt; 4298 } 4299 4300 int Scop::getRelativeLoopDepth(const Loop *L) const { 4301 Loop *OuterLoop = 4302 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr; 4303 if (!OuterLoop) 4304 return -1; 4305 return L->getLoopDepth() - OuterLoop->getLoopDepth(); 4306 } 4307 4308 ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) { 4309 for (auto &SAI : arrays()) { 4310 if (SAI->getName() == BaseName) 4311 return SAI; 4312 } 4313 return nullptr; 4314 } 4315 4316 //===----------------------------------------------------------------------===// 4317 void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const { 4318 AU.addRequired<LoopInfoWrapperPass>(); 4319 AU.addRequired<RegionInfoPass>(); 4320 AU.addRequired<DominatorTreeWrapperPass>(); 4321 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 4322 AU.addRequiredTransitive<ScopDetection>(); 4323 AU.addRequired<AAResultsWrapperPass>(); 4324 AU.addRequired<AssumptionCacheTracker>(); 4325 AU.setPreservesAll(); 4326 } 4327 4328 bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) { 4329 auto &SD = getAnalysis<ScopDetection>(); 4330 4331 if (!SD.isMaxRegionInScop(*R)) 4332 return false; 4333 4334 Function *F = R->getEntry()->getParent(); 4335 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 4336 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 4337 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 4338 auto const &DL = F->getParent()->getDataLayout(); 4339 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 4340 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F); 4341 4342 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE); 4343 S = SB.getScop(); // take ownership of scop object 4344 return false; 4345 } 4346 4347 void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const { 4348 if (S) 4349 S->print(OS); 4350 else 4351 OS << "Invalid Scop!\n"; 4352 } 4353 4354 char ScopInfoRegionPass::ID = 0; 4355 4356 Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); } 4357 4358 INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops", 4359 "Polly - Create polyhedral description of Scops", false, 4360 false); 4361 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 4362 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker); 4363 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 4364 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 4365 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 4366 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 4367 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 4368 INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops", 4369 "Polly - Create polyhedral description of Scops", false, 4370 false) 4371 4372 //===----------------------------------------------------------------------===// 4373 void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 4374 AU.addRequired<LoopInfoWrapperPass>(); 4375 AU.addRequired<RegionInfoPass>(); 4376 AU.addRequired<DominatorTreeWrapperPass>(); 4377 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 4378 AU.addRequiredTransitive<ScopDetection>(); 4379 AU.addRequired<AAResultsWrapperPass>(); 4380 AU.addRequired<AssumptionCacheTracker>(); 4381 AU.setPreservesAll(); 4382 } 4383 4384 bool ScopInfoWrapperPass::runOnFunction(Function &F) { 4385 auto &SD = getAnalysis<ScopDetection>(); 4386 4387 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 4388 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 4389 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 4390 auto const &DL = F.getParent()->getDataLayout(); 4391 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 4392 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 4393 4394 /// Create polyhedral descripton of scops for all the valid regions of a 4395 /// function. 4396 for (auto &It : SD) { 4397 Region *R = const_cast<Region *>(It); 4398 if (!SD.isMaxRegionInScop(*R)) 4399 continue; 4400 4401 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE); 4402 std::unique_ptr<Scop> S = SB.getScop(); 4403 if (!S) 4404 continue; 4405 bool Inserted = 4406 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second; 4407 assert(Inserted && "Building Scop for the same region twice!"); 4408 (void)Inserted; 4409 } 4410 return false; 4411 } 4412 4413 void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 4414 for (auto &It : RegionToScopMap) { 4415 if (It.second) 4416 It.second->print(OS); 4417 else 4418 OS << "Invalid Scop!\n"; 4419 } 4420 } 4421 4422 char ScopInfoWrapperPass::ID = 0; 4423 4424 Pass *polly::createScopInfoWrapperPassPass() { 4425 return new ScopInfoWrapperPass(); 4426 } 4427 4428 INITIALIZE_PASS_BEGIN( 4429 ScopInfoWrapperPass, "polly-function-scops", 4430 "Polly - Create polyhedral description of all Scops of a function", false, 4431 false); 4432 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 4433 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker); 4434 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 4435 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 4436 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 4437 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 4438 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 4439 INITIALIZE_PASS_END( 4440 ScopInfoWrapperPass, "polly-function-scops", 4441 "Polly - Create polyhedral description of all Scops of a function", false, 4442 false) 4443