1 //===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===// 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 // Detect the maximal Scops of a function. 11 // 12 // A static control part (Scop) is a subgraph of the control flow graph (CFG) 13 // that only has statically known control flow and can therefore be described 14 // within the polyhedral model. 15 // 16 // Every Scop fulfills these restrictions: 17 // 18 // * It is a single entry single exit region 19 // 20 // * Only affine linear bounds in the loops 21 // 22 // Every natural loop in a Scop must have a number of loop iterations that can 23 // be described as an affine linear function in surrounding loop iterators or 24 // parameters. (A parameter is a scalar that does not change its value during 25 // execution of the Scop). 26 // 27 // * Only comparisons of affine linear expressions in conditions 28 // 29 // * All loops and conditions perfectly nested 30 // 31 // The control flow needs to be structured such that it could be written using 32 // just 'for' and 'if' statements, without the need for any 'goto', 'break' or 33 // 'continue'. 34 // 35 // * Side effect free functions call 36 // 37 // Function calls and intrinsics that do not have side effects (readnone) 38 // or memory intrinsics (memset, memcpy, memmove) are allowed. 39 // 40 // The Scop detection finds the largest Scops by checking if the largest 41 // region is a Scop. If this is not the case, its canonical subregions are 42 // checked until a region is a Scop. It is now tried to extend this Scop by 43 // creating a larger non canonical region. 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "polly/ScopDetection.h" 48 #include "polly/CodeGen/CodeGeneration.h" 49 #include "polly/LinkAllPasses.h" 50 #include "polly/Options.h" 51 #include "polly/ScopDetectionDiagnostic.h" 52 #include "polly/Support/SCEVValidator.h" 53 #include "polly/Support/ScopLocation.h" 54 #include "llvm/ADT/Statistic.h" 55 #include "llvm/Analysis/AliasAnalysis.h" 56 #include "llvm/Analysis/Loads.h" 57 #include "llvm/Analysis/LoopInfo.h" 58 #include "llvm/Analysis/RegionIterator.h" 59 #include "llvm/Analysis/ScalarEvolution.h" 60 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 61 #include "llvm/IR/DebugInfo.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/DiagnosticPrinter.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/LLVMContext.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/Regex.h" 68 #include <set> 69 #include <stack> 70 71 using namespace llvm; 72 using namespace polly; 73 74 #define DEBUG_TYPE "polly-detect" 75 76 // This option is set to a very high value, as analyzing such loops increases 77 // compile time on several cases. For experiments that enable this option, 78 // a value of around 40 has been working to avoid run-time regressions with 79 // Polly while still exposing interesting optimization opportunities. 80 static cl::opt<int> ProfitabilityMinPerLoopInstructions( 81 "polly-detect-profitability-min-per-loop-insts", 82 cl::desc("The minimal number of per-loop instructions before a single loop " 83 "region is considered profitable"), 84 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory)); 85 86 bool polly::PollyProcessUnprofitable; 87 static cl::opt<bool, true> XPollyProcessUnprofitable( 88 "polly-process-unprofitable", 89 cl::desc( 90 "Process scops that are unlikely to benefit from Polly optimizations."), 91 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore, 92 cl::cat(PollyCategory)); 93 94 static cl::list<std::string> OnlyFunctions( 95 "polly-only-func", 96 cl::desc("Only run on functions that match a regex. " 97 "Multiple regexes can be comma separated. " 98 "Scop detection will run on all functions that match " 99 "ANY of the regexes provided."), 100 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory)); 101 102 static cl::opt<bool> 103 AllowFullFunction("polly-detect-full-functions", 104 cl::desc("Allow the detection of full functions"), 105 cl::init(false), cl::cat(PollyCategory)); 106 107 static cl::opt<std::string> OnlyRegion( 108 "polly-only-region", 109 cl::desc("Only run on certain regions (The provided identifier must " 110 "appear in the name of the region's entry block"), 111 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""), 112 cl::cat(PollyCategory)); 113 114 static cl::opt<bool> 115 IgnoreAliasing("polly-ignore-aliasing", 116 cl::desc("Ignore possible aliasing of the array bases"), 117 cl::Hidden, cl::init(false), cl::ZeroOrMore, 118 cl::cat(PollyCategory)); 119 120 bool polly::PollyAllowUnsignedOperations; 121 static cl::opt<bool, true> XPollyAllowUnsignedOperations( 122 "polly-allow-unsigned-operations", 123 cl::desc("Allow unsigned operations such as comparisons or zero-extends."), 124 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore, 125 cl::init(true), cl::cat(PollyCategory)); 126 127 bool polly::PollyUseRuntimeAliasChecks; 128 static cl::opt<bool, true> XPollyUseRuntimeAliasChecks( 129 "polly-use-runtime-alias-checks", 130 cl::desc("Use runtime alias checks to resolve possible aliasing."), 131 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore, 132 cl::init(true), cl::cat(PollyCategory)); 133 134 static cl::opt<bool> 135 ReportLevel("polly-report", 136 cl::desc("Print information about the activities of Polly"), 137 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 138 139 static cl::opt<bool> AllowDifferentTypes( 140 "polly-allow-differing-element-types", 141 cl::desc("Allow different element types for array accesses"), cl::Hidden, 142 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory)); 143 144 static cl::opt<bool> 145 AllowNonAffine("polly-allow-nonaffine", 146 cl::desc("Allow non affine access functions in arrays"), 147 cl::Hidden, cl::init(false), cl::ZeroOrMore, 148 cl::cat(PollyCategory)); 149 150 static cl::opt<bool> 151 AllowModrefCall("polly-allow-modref-calls", 152 cl::desc("Allow functions with known modref behavior"), 153 cl::Hidden, cl::init(false), cl::ZeroOrMore, 154 cl::cat(PollyCategory)); 155 156 static cl::opt<bool> AllowNonAffineSubRegions( 157 "polly-allow-nonaffine-branches", 158 cl::desc("Allow non affine conditions for branches"), cl::Hidden, 159 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory)); 160 161 static cl::opt<bool> 162 AllowNonAffineSubLoops("polly-allow-nonaffine-loops", 163 cl::desc("Allow non affine conditions for loops"), 164 cl::Hidden, cl::init(false), cl::ZeroOrMore, 165 cl::cat(PollyCategory)); 166 167 static cl::opt<bool, true> 168 TrackFailures("polly-detect-track-failures", 169 cl::desc("Track failure strings in detecting scop regions"), 170 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore, 171 cl::init(true), cl::cat(PollyCategory)); 172 173 static cl::opt<bool> KeepGoing("polly-detect-keep-going", 174 cl::desc("Do not fail on the first error."), 175 cl::Hidden, cl::ZeroOrMore, cl::init(false), 176 cl::cat(PollyCategory)); 177 178 static cl::opt<bool, true> 179 PollyDelinearizeX("polly-delinearize", 180 cl::desc("Delinearize array access functions"), 181 cl::location(PollyDelinearize), cl::Hidden, 182 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory)); 183 184 static cl::opt<bool> 185 VerifyScops("polly-detect-verify", 186 cl::desc("Verify the detected SCoPs after each transformation"), 187 cl::Hidden, cl::init(false), cl::ZeroOrMore, 188 cl::cat(PollyCategory)); 189 190 bool polly::PollyInvariantLoadHoisting; 191 static cl::opt<bool, true> XPollyInvariantLoadHoisting( 192 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."), 193 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore, 194 cl::init(false), cl::cat(PollyCategory)); 195 196 /// The minimal trip count under which loops are considered unprofitable. 197 static const unsigned MIN_LOOP_TRIP_COUNT = 8; 198 199 bool polly::PollyTrackFailures = false; 200 bool polly::PollyDelinearize = false; 201 StringRef polly::PollySkipFnAttr = "polly.skip.fn"; 202 203 //===----------------------------------------------------------------------===// 204 // Statistics. 205 206 STATISTIC(NumScopRegions, "Number of scops"); 207 STATISTIC(NumLoopsInScop, "Number of loops in scops"); 208 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1"); 209 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2"); 210 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3"); 211 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4"); 212 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5"); 213 STATISTIC(NumScopsDepthLarger, 214 "Number of scops with maximal loop depth 6 and larger"); 215 STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)"); 216 STATISTIC(NumLoopsInProfScop, 217 "Number of loops in scops (profitable scops only)"); 218 STATISTIC(NumLoopsOverall, "Number of total loops"); 219 STATISTIC(NumProfScopsDepthOne, 220 "Number of scops with maximal loop depth 1 (profitable scops only)"); 221 STATISTIC(NumProfScopsDepthTwo, 222 "Number of scops with maximal loop depth 2 (profitable scops only)"); 223 STATISTIC(NumProfScopsDepthThree, 224 "Number of scops with maximal loop depth 3 (profitable scops only)"); 225 STATISTIC(NumProfScopsDepthFour, 226 "Number of scops with maximal loop depth 4 (profitable scops only)"); 227 STATISTIC(NumProfScopsDepthFive, 228 "Number of scops with maximal loop depth 5 (profitable scops only)"); 229 STATISTIC(NumProfScopsDepthLarger, 230 "Number of scops with maximal loop depth 6 and larger " 231 "(profitable scops only)"); 232 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops"); 233 STATISTIC(MaxNumLoopsInProfScop, 234 "Maximal number of loops in scops (profitable scops only)"); 235 236 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats, 237 bool OnlyProfitable); 238 239 class DiagnosticScopFound : public DiagnosticInfo { 240 private: 241 static int PluginDiagnosticKind; 242 243 Function &F; 244 std::string FileName; 245 unsigned EntryLine, ExitLine; 246 247 public: 248 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine, 249 unsigned ExitLine) 250 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName), 251 EntryLine(EntryLine), ExitLine(ExitLine) {} 252 253 virtual void print(DiagnosticPrinter &DP) const; 254 255 static bool classof(const DiagnosticInfo *DI) { 256 return DI->getKind() == PluginDiagnosticKind; 257 } 258 }; 259 260 int DiagnosticScopFound::PluginDiagnosticKind = 261 getNextAvailablePluginDiagnosticKind(); 262 263 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const { 264 DP << "Polly detected an optimizable loop region (scop) in function '" << F 265 << "'\n"; 266 267 if (FileName.empty()) { 268 DP << "Scop location is unknown. Compile with debug info " 269 "(-g) to get more precise information. "; 270 return; 271 } 272 273 DP << FileName << ":" << EntryLine << ": Start of scop\n"; 274 DP << FileName << ":" << ExitLine << ": End of scop"; 275 } 276 277 static bool IsFnNameListedInOnlyFunctions(StringRef FnName) { 278 for (auto RegexStr : OnlyFunctions) { 279 Regex R(RegexStr); 280 281 std::string Err; 282 if (!R.isValid(Err)) 283 report_fatal_error( 284 "invalid regex given as input to -polly-only-func. " + Err, true); 285 286 if (R.match(FnName)) 287 return true; 288 } 289 return false; 290 } 291 //===----------------------------------------------------------------------===// 292 // ScopDetection. 293 294 ScopDetection::ScopDetection(Function &F, const DominatorTree &DT, 295 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI, 296 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE) 297 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) { 298 299 if (!PollyProcessUnprofitable && LI.empty()) 300 return; 301 302 Region *TopRegion = RI.getTopLevelRegion(); 303 304 if (OnlyFunctions.size() > 0 && !IsFnNameListedInOnlyFunctions(F.getName())) 305 return; 306 307 if (!isValidFunction(F)) 308 return; 309 310 findScops(*TopRegion); 311 312 NumScopRegions += ValidRegions.size(); 313 314 // Prune non-profitable regions. 315 for (auto &DIt : DetectionContextMap) { 316 auto &DC = DIt.getSecond(); 317 if (DC.Log.hasErrors()) 318 continue; 319 if (!ValidRegions.count(&DC.CurRegion)) 320 continue; 321 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0); 322 updateLoopCountStatistic(Stats, false /* OnlyProfitable */); 323 if (isProfitableRegion(DC)) { 324 updateLoopCountStatistic(Stats, true /* OnlyProfitable */); 325 continue; 326 } 327 328 ValidRegions.remove(&DC.CurRegion); 329 } 330 331 NumProfScopRegions += ValidRegions.size(); 332 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops; 333 334 // Only makes sense when we tracked errors. 335 if (PollyTrackFailures) 336 emitMissedRemarks(F); 337 338 if (ReportLevel) 339 printLocations(F); 340 341 assert(ValidRegions.size() <= DetectionContextMap.size() && 342 "Cached more results than valid regions"); 343 } 344 345 template <class RR, typename... Args> 346 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert, 347 Args &&... Arguments) const { 348 349 if (!Context.Verifying) { 350 RejectLog &Log = Context.Log; 351 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...); 352 353 if (PollyTrackFailures) 354 Log.report(RejectReason); 355 356 DEBUG(dbgs() << RejectReason->getMessage()); 357 DEBUG(dbgs() << "\n"); 358 } else { 359 assert(!Assert && "Verification of detected scop failed"); 360 } 361 362 return false; 363 } 364 365 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const { 366 if (!ValidRegions.count(&R)) 367 return false; 368 369 if (Verify) { 370 DetectionContextMap.erase(getBBPairForRegion(&R)); 371 const auto &It = DetectionContextMap.insert(std::make_pair( 372 getBBPairForRegion(&R), 373 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/))); 374 DetectionContext &Context = It.first->second; 375 return isValidRegion(Context); 376 } 377 378 return true; 379 } 380 381 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const { 382 // Get the first error we found. Even in keep-going mode, this is the first 383 // reason that caused the candidate to be rejected. 384 auto *Log = lookupRejectionLog(R); 385 386 // This can happen when we marked a region invalid, but didn't track 387 // an error for it. 388 if (!Log || !Log->hasErrors()) 389 return ""; 390 391 RejectReasonPtr RR = *Log->begin(); 392 return RR->getMessage(); 393 } 394 395 bool ScopDetection::addOverApproximatedRegion(Region *AR, 396 DetectionContext &Context) const { 397 398 // If we already know about Ar we can exit. 399 if (!Context.NonAffineSubRegionSet.insert(AR)) 400 return true; 401 402 // All loops in the region have to be overapproximated too if there 403 // are accesses that depend on the iteration count. 404 405 for (BasicBlock *BB : AR->blocks()) { 406 Loop *L = LI.getLoopFor(BB); 407 if (AR->contains(L)) 408 Context.BoxedLoopsSet.insert(L); 409 } 410 411 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty()); 412 } 413 414 bool ScopDetection::onlyValidRequiredInvariantLoads( 415 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const { 416 Region &CurRegion = Context.CurRegion; 417 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout(); 418 419 if (!PollyInvariantLoadHoisting && !RequiredILS.empty()) 420 return false; 421 422 for (LoadInst *Load : RequiredILS) { 423 // If we already know a load has been accepted as required invariant, we 424 // already run the validation below once and consequently don't need to 425 // run it again. Hence, we return early. For certain test cases (e.g., 426 // COSMO this avoids us spending 50% of scop-detection time in this 427 // very function (and its children). 428 if (Context.RequiredILS.count(Load)) 429 continue; 430 431 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT)) 432 return false; 433 434 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) { 435 436 if (isSafeToLoadUnconditionally(Load->getPointerOperand(), 437 Load->getAlignment(), DL)) 438 continue; 439 440 if (NonAffineRegion->contains(Load) && 441 Load->getParent() != NonAffineRegion->getEntry()) 442 return false; 443 } 444 } 445 446 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end()); 447 448 return true; 449 } 450 451 bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1, 452 Loop *Scope) const { 453 SetVector<Value *> Values; 454 findValues(S0, SE, Values); 455 if (S1) 456 findValues(S1, SE, Values); 457 458 SmallPtrSet<Value *, 8> PtrVals; 459 for (auto *V : Values) { 460 if (auto *P2I = dyn_cast<PtrToIntInst>(V)) 461 V = P2I->getOperand(0); 462 463 if (!V->getType()->isPointerTy()) 464 continue; 465 466 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope); 467 if (isa<SCEVConstant>(PtrSCEV)) 468 continue; 469 470 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV)); 471 if (!BasePtr) 472 return true; 473 474 auto *BasePtrVal = BasePtr->getValue(); 475 if (PtrVals.insert(BasePtrVal).second) { 476 for (auto *PtrVal : PtrVals) 477 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal)) 478 return true; 479 } 480 } 481 482 return false; 483 } 484 485 bool ScopDetection::isAffine(const SCEV *S, Loop *Scope, 486 DetectionContext &Context) const { 487 488 InvariantLoadsSetTy AccessILS; 489 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS)) 490 return false; 491 492 if (!onlyValidRequiredInvariantLoads(AccessILS, Context)) 493 return false; 494 495 return true; 496 } 497 498 bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI, 499 Value *Condition, bool IsLoopBranch, 500 DetectionContext &Context) const { 501 Loop *L = LI.getLoopFor(&BB); 502 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L); 503 504 if (IsLoopBranch && L->isLoopLatch(&BB)) 505 return false; 506 507 // Check for invalid usage of different pointers in one expression. 508 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L)) 509 return false; 510 511 if (isAffine(ConditionSCEV, L, Context)) 512 return true; 513 514 if (AllowNonAffineSubRegions && 515 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 516 return true; 517 518 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, 519 ConditionSCEV, ConditionSCEV, SI); 520 } 521 522 bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI, 523 Value *Condition, bool IsLoopBranch, 524 DetectionContext &Context) const { 525 526 // Constant integer conditions are always affine. 527 if (isa<ConstantInt>(Condition)) 528 return true; 529 530 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 531 auto Opcode = BinOp->getOpcode(); 532 if (Opcode == Instruction::And || Opcode == Instruction::Or) { 533 Value *Op0 = BinOp->getOperand(0); 534 Value *Op1 = BinOp->getOperand(1); 535 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) && 536 isValidBranch(BB, BI, Op1, IsLoopBranch, Context); 537 } 538 } 539 540 // Non constant conditions of branches need to be ICmpInst. 541 if (!isa<ICmpInst>(Condition)) { 542 if (!IsLoopBranch && AllowNonAffineSubRegions && 543 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 544 return true; 545 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB); 546 } 547 548 ICmpInst *ICmp = cast<ICmpInst>(Condition); 549 550 // Are both operands of the ICmp affine? 551 if (isa<UndefValue>(ICmp->getOperand(0)) || 552 isa<UndefValue>(ICmp->getOperand(1))) 553 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp); 554 555 Loop *L = LI.getLoopFor(&BB); 556 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L); 557 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L); 558 559 // If unsigned operations are not allowed try to approximate the region. 560 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations) 561 return !IsLoopBranch && AllowNonAffineSubRegions && 562 addOverApproximatedRegion(RI.getRegionFor(&BB), Context); 563 564 // Check for invalid usage of different pointers in one expression. 565 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) && 566 involvesMultiplePtrs(RHS, nullptr, L)) 567 return false; 568 569 // Check for invalid usage of different pointers in a relational comparison. 570 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L)) 571 return false; 572 573 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context)) 574 return true; 575 576 if (!IsLoopBranch && AllowNonAffineSubRegions && 577 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 578 return true; 579 580 if (IsLoopBranch) 581 return false; 582 583 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS, 584 ICmp); 585 } 586 587 bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch, 588 bool AllowUnreachable, 589 DetectionContext &Context) const { 590 Region &CurRegion = Context.CurRegion; 591 592 TerminatorInst *TI = BB.getTerminator(); 593 594 if (AllowUnreachable && isa<UnreachableInst>(TI)) 595 return true; 596 597 // Return instructions are only valid if the region is the top level region. 598 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion()) 599 return true; 600 601 Value *Condition = getConditionFromTerminator(TI); 602 603 if (!Condition) 604 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB); 605 606 // UndefValue is not allowed as condition. 607 if (isa<UndefValue>(Condition)) 608 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB); 609 610 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 611 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context); 612 613 SwitchInst *SI = dyn_cast<SwitchInst>(TI); 614 assert(SI && "Terminator was neither branch nor switch"); 615 616 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context); 617 } 618 619 bool ScopDetection::isValidCallInst(CallInst &CI, 620 DetectionContext &Context) const { 621 if (CI.doesNotReturn()) 622 return false; 623 624 if (CI.doesNotAccessMemory()) 625 return true; 626 627 if (auto *II = dyn_cast<IntrinsicInst>(&CI)) 628 if (isValidIntrinsicInst(*II, Context)) 629 return true; 630 631 Function *CalledFunction = CI.getCalledFunction(); 632 633 // Indirect calls are not supported. 634 if (CalledFunction == nullptr) 635 return false; 636 637 if (AllowModrefCall) { 638 switch (AA.getModRefBehavior(CalledFunction)) { 639 case FMRB_UnknownModRefBehavior: 640 return false; 641 case FMRB_DoesNotAccessMemory: 642 case FMRB_OnlyReadsMemory: 643 // Implicitly disable delinearization since we have an unknown 644 // accesses with an unknown access function. 645 Context.HasUnknownAccess = true; 646 Context.AST.add(&CI); 647 return true; 648 case FMRB_OnlyReadsArgumentPointees: 649 case FMRB_OnlyAccessesArgumentPointees: 650 for (const auto &Arg : CI.arg_operands()) { 651 if (!Arg->getType()->isPointerTy()) 652 continue; 653 654 // Bail if a pointer argument has a base address not known to 655 // ScalarEvolution. Note that a zero pointer is acceptable. 656 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent())); 657 if (ArgSCEV->isZero()) 658 continue; 659 660 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV)); 661 if (!BP) 662 return false; 663 664 // Implicitly disable delinearization since we have an unknown 665 // accesses with an unknown access function. 666 Context.HasUnknownAccess = true; 667 } 668 669 Context.AST.add(&CI); 670 return true; 671 case FMRB_DoesNotReadMemory: 672 case FMRB_OnlyAccessesInaccessibleMem: 673 case FMRB_OnlyAccessesInaccessibleOrArgMem: 674 return false; 675 } 676 } 677 678 return false; 679 } 680 681 bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II, 682 DetectionContext &Context) const { 683 if (isIgnoredIntrinsic(&II)) 684 return true; 685 686 // The closest loop surrounding the call instruction. 687 Loop *L = LI.getLoopFor(II.getParent()); 688 689 // The access function and base pointer for memory intrinsics. 690 const SCEV *AF; 691 const SCEVUnknown *BP; 692 693 switch (II.getIntrinsicID()) { 694 // Memory intrinsics that can be represented are supported. 695 case llvm::Intrinsic::memmove: 696 case llvm::Intrinsic::memcpy: 697 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L); 698 if (!AF->isZero()) { 699 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF)); 700 // Bail if the source pointer is not valid. 701 if (!isValidAccess(&II, AF, BP, Context)) 702 return false; 703 } 704 // Fall through 705 case llvm::Intrinsic::memset: 706 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L); 707 if (!AF->isZero()) { 708 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF)); 709 // Bail if the destination pointer is not valid. 710 if (!isValidAccess(&II, AF, BP, Context)) 711 return false; 712 } 713 714 // Bail if the length is not affine. 715 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L, 716 Context)) 717 return false; 718 719 return true; 720 default: 721 break; 722 } 723 724 return false; 725 } 726 727 bool ScopDetection::isInvariant(Value &Val, const Region &Reg, 728 DetectionContext &Ctx) const { 729 // A reference to function argument or constant value is invariant. 730 if (isa<Argument>(Val) || isa<Constant>(Val)) 731 return true; 732 733 Instruction *I = dyn_cast<Instruction>(&Val); 734 if (!I) 735 return false; 736 737 if (!Reg.contains(I)) 738 return true; 739 740 // Loads within the SCoP may read arbitrary values, need to hoist them. If it 741 // is not hoistable, it will be rejected later, but here we assume it is and 742 // that makes the value invariant. 743 if (auto LI = dyn_cast<LoadInst>(I)) { 744 Ctx.RequiredILS.insert(LI); 745 return true; 746 } 747 748 return false; 749 } 750 751 /// Remove smax of smax(0, size) expressions from a SCEV expression and 752 /// register the '...' components. 753 /// 754 /// Array access expressions as they are generated by GFortran contain smax(0, 755 /// size) expressions that confuse the 'normal' delinearization algorithm. 756 /// However, if we extract such expressions before the normal delinearization 757 /// takes place they can actually help to identify array size expressions in 758 /// Fortran accesses. For the subsequently following delinearization the smax(0, 759 /// size) component can be replaced by just 'size'. This is correct as we will 760 /// always add and verify the assumption that for all subscript expressions 761 /// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify 762 /// that 0 <= size, which means smax(0, size) == size. 763 class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> { 764 public: 765 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE, 766 std::vector<const SCEV *> *Terms = nullptr) { 767 SCEVRemoveMax Rewriter(SE, Terms); 768 return Rewriter.visit(Scev); 769 } 770 771 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms) 772 : SCEVRewriteVisitor(SE), Terms(Terms) {} 773 774 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) { 775 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) { 776 auto Res = visit(Expr->getOperand(1)); 777 if (Terms) 778 (*Terms).push_back(Res); 779 return Res; 780 } 781 782 return Expr; 783 } 784 785 private: 786 std::vector<const SCEV *> *Terms; 787 }; 788 789 SmallVector<const SCEV *, 4> 790 ScopDetection::getDelinearizationTerms(DetectionContext &Context, 791 const SCEVUnknown *BasePointer) const { 792 SmallVector<const SCEV *, 4> Terms; 793 for (const auto &Pair : Context.Accesses[BasePointer]) { 794 std::vector<const SCEV *> MaxTerms; 795 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms); 796 if (MaxTerms.size() > 0) { 797 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end()); 798 continue; 799 } 800 // In case the outermost expression is a plain add, we check if any of its 801 // terms has the form 4 * %inst * %param * %param ..., aka a term that 802 // contains a product between a parameter and an instruction that is 803 // inside the scop. Such instructions, if allowed at all, are instructions 804 // SCEV can not represent, but Polly is still looking through. As a 805 // result, these instructions can depend on induction variables and are 806 // most likely no array sizes. However, terms that are multiplied with 807 // them are likely candidates for array sizes. 808 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) { 809 for (auto Op : AF->operands()) { 810 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op)) 811 SE.collectParametricTerms(AF2, Terms); 812 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) { 813 SmallVector<const SCEV *, 0> Operands; 814 815 for (auto *MulOp : AF2->operands()) { 816 if (auto *Const = dyn_cast<SCEVConstant>(MulOp)) 817 Operands.push_back(Const); 818 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) { 819 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) { 820 if (!Context.CurRegion.contains(Inst)) 821 Operands.push_back(MulOp); 822 823 } else { 824 Operands.push_back(MulOp); 825 } 826 } 827 } 828 if (Operands.size()) 829 Terms.push_back(SE.getMulExpr(Operands)); 830 } 831 } 832 } 833 if (Terms.empty()) 834 SE.collectParametricTerms(Pair.second, Terms); 835 } 836 return Terms; 837 } 838 839 bool ScopDetection::hasValidArraySizes(DetectionContext &Context, 840 SmallVectorImpl<const SCEV *> &Sizes, 841 const SCEVUnknown *BasePointer, 842 Loop *Scope) const { 843 // If no sizes were found, all sizes are trivially valid. We allow this case 844 // to make it possible to pass known-affine accesses to the delinearization to 845 // try to recover some interesting multi-dimensional accesses, but to still 846 // allow the already known to be affine access in case the delinearization 847 // fails. In such situations, the delinearization will just return a Sizes 848 // array of size zero. 849 if (Sizes.size() == 0) 850 return true; 851 852 Value *BaseValue = BasePointer->getValue(); 853 Region &CurRegion = Context.CurRegion; 854 for (const SCEV *DelinearizedSize : Sizes) { 855 if (!isAffine(DelinearizedSize, Scope, Context)) { 856 Sizes.clear(); 857 break; 858 } 859 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) { 860 auto *V = dyn_cast<Value>(Unknown->getValue()); 861 if (auto *Load = dyn_cast<LoadInst>(V)) { 862 if (Context.CurRegion.contains(Load) && 863 isHoistableLoad(Load, CurRegion, LI, SE, DT)) 864 Context.RequiredILS.insert(Load); 865 continue; 866 } 867 } 868 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false, 869 Context.RequiredILS)) 870 return invalid<ReportNonAffineAccess>( 871 Context, /*Assert=*/true, DelinearizedSize, 872 Context.Accesses[BasePointer].front().first, BaseValue); 873 } 874 875 // No array shape derived. 876 if (Sizes.empty()) { 877 if (AllowNonAffine) 878 return true; 879 880 for (const auto &Pair : Context.Accesses[BasePointer]) { 881 const Instruction *Insn = Pair.first; 882 const SCEV *AF = Pair.second; 883 884 if (!isAffine(AF, Scope, Context)) { 885 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn, 886 BaseValue); 887 if (!KeepGoing) 888 return false; 889 } 890 } 891 return false; 892 } 893 return true; 894 } 895 896 // We first store the resulting memory accesses in TempMemoryAccesses. Only 897 // if the access functions for all memory accesses have been successfully 898 // delinearized we continue. Otherwise, we either report a failure or, if 899 // non-affine accesses are allowed, we drop the information. In case the 900 // information is dropped the memory accesses need to be overapproximated 901 // when translated to a polyhedral representation. 902 bool ScopDetection::computeAccessFunctions( 903 DetectionContext &Context, const SCEVUnknown *BasePointer, 904 std::shared_ptr<ArrayShape> Shape) const { 905 Value *BaseValue = BasePointer->getValue(); 906 bool BasePtrHasNonAffine = false; 907 MapInsnToMemAcc TempMemoryAccesses; 908 for (const auto &Pair : Context.Accesses[BasePointer]) { 909 const Instruction *Insn = Pair.first; 910 auto *AF = Pair.second; 911 AF = SCEVRemoveMax::rewrite(AF, SE); 912 bool IsNonAffine = false; 913 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape))); 914 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second; 915 auto *Scope = LI.getLoopFor(Insn->getParent()); 916 917 if (!AF) { 918 if (isAffine(Pair.second, Scope, Context)) 919 Acc->DelinearizedSubscripts.push_back(Pair.second); 920 else 921 IsNonAffine = true; 922 } else { 923 if (Shape->DelinearizedSizes.size() == 0) { 924 Acc->DelinearizedSubscripts.push_back(AF); 925 } else { 926 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts, 927 Shape->DelinearizedSizes); 928 if (Acc->DelinearizedSubscripts.size() == 0) 929 IsNonAffine = true; 930 } 931 for (const SCEV *S : Acc->DelinearizedSubscripts) 932 if (!isAffine(S, Scope, Context)) 933 IsNonAffine = true; 934 } 935 936 // (Possibly) report non affine access 937 if (IsNonAffine) { 938 BasePtrHasNonAffine = true; 939 if (!AllowNonAffine) 940 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second, 941 Insn, BaseValue); 942 if (!KeepGoing && !AllowNonAffine) 943 return false; 944 } 945 } 946 947 if (!BasePtrHasNonAffine) 948 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(), 949 TempMemoryAccesses.end()); 950 951 return true; 952 } 953 954 bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context, 955 const SCEVUnknown *BasePointer, 956 Loop *Scope) const { 957 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer)); 958 959 auto Terms = getDelinearizationTerms(Context, BasePointer); 960 961 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes, 962 Context.ElementSize[BasePointer]); 963 964 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer, 965 Scope)) 966 return false; 967 968 return computeAccessFunctions(Context, BasePointer, Shape); 969 } 970 971 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const { 972 // TODO: If we have an unknown access and other non-affine accesses we do 973 // not try to delinearize them for now. 974 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty()) 975 return AllowNonAffine; 976 977 for (auto &Pair : Context.NonAffineAccesses) { 978 auto *BasePointer = Pair.first; 979 auto *Scope = Pair.second; 980 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) { 981 if (KeepGoing) 982 continue; 983 else 984 return false; 985 } 986 } 987 return true; 988 } 989 990 bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF, 991 const SCEVUnknown *BP, 992 DetectionContext &Context) const { 993 994 if (!BP) 995 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst); 996 997 auto *BV = BP->getValue(); 998 if (isa<UndefValue>(BV)) 999 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst); 1000 1001 // FIXME: Think about allowing IntToPtrInst 1002 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV)) 1003 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst); 1004 1005 // Check that the base address of the access is invariant in the current 1006 // region. 1007 if (!isInvariant(*BV, Context.CurRegion, Context)) 1008 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst); 1009 1010 AF = SE.getMinusSCEV(AF, BP); 1011 1012 const SCEV *Size; 1013 if (!isa<MemIntrinsic>(Inst)) { 1014 Size = SE.getElementSize(Inst); 1015 } else { 1016 auto *SizeTy = 1017 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext())); 1018 Size = SE.getConstant(SizeTy, 8); 1019 } 1020 1021 if (Context.ElementSize[BP]) { 1022 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size) 1023 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true, 1024 Inst, BV); 1025 1026 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]); 1027 } else { 1028 Context.ElementSize[BP] = Size; 1029 } 1030 1031 bool IsVariantInNonAffineLoop = false; 1032 SetVector<const Loop *> Loops; 1033 findLoops(AF, Loops); 1034 for (const Loop *L : Loops) 1035 if (Context.BoxedLoopsSet.count(L)) 1036 IsVariantInNonAffineLoop = true; 1037 1038 auto *Scope = LI.getLoopFor(Inst->getParent()); 1039 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context); 1040 // Do not try to delinearize memory intrinsics and force them to be affine. 1041 if (isa<MemIntrinsic>(Inst) && !IsAffine) { 1042 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst, 1043 BV); 1044 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) { 1045 Context.Accesses[BP].push_back({Inst, AF}); 1046 1047 if (!IsAffine || hasIVParams(AF)) 1048 Context.NonAffineAccesses.insert( 1049 std::make_pair(BP, LI.getLoopFor(Inst->getParent()))); 1050 } else if (!AllowNonAffine && !IsAffine) { 1051 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst, 1052 BV); 1053 } 1054 1055 if (IgnoreAliasing) 1056 return true; 1057 1058 // Check if the base pointer of the memory access does alias with 1059 // any other pointer. This cannot be handled at the moment. 1060 AAMDNodes AATags; 1061 Inst->getAAMetadata(AATags); 1062 AliasSet &AS = Context.AST.getAliasSetForPointer( 1063 BP->getValue(), MemoryLocation::UnknownSize, AATags); 1064 1065 if (!AS.isMustAlias()) { 1066 if (PollyUseRuntimeAliasChecks) { 1067 bool CanBuildRunTimeCheck = true; 1068 // The run-time alias check places code that involves the base pointer at 1069 // the beginning of the SCoP. This breaks if the base pointer is defined 1070 // inside the scop. Hence, we can only create a run-time check if we are 1071 // sure the base pointer is not an instruction defined inside the scop. 1072 // However, we can ignore loads that will be hoisted. 1073 for (const auto &Ptr : AS) { 1074 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue()); 1075 if (Inst && Context.CurRegion.contains(Inst)) { 1076 auto *Load = dyn_cast<LoadInst>(Inst); 1077 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) { 1078 Context.RequiredILS.insert(Load); 1079 continue; 1080 } 1081 1082 CanBuildRunTimeCheck = false; 1083 break; 1084 } 1085 } 1086 1087 if (CanBuildRunTimeCheck) 1088 return true; 1089 } 1090 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS); 1091 } 1092 1093 return true; 1094 } 1095 1096 bool ScopDetection::isValidMemoryAccess(MemAccInst Inst, 1097 DetectionContext &Context) const { 1098 Value *Ptr = Inst.getPointerOperand(); 1099 Loop *L = LI.getLoopFor(Inst->getParent()); 1100 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L); 1101 const SCEVUnknown *BasePointer; 1102 1103 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1104 1105 return isValidAccess(Inst, AccessFunction, BasePointer, Context); 1106 } 1107 1108 bool ScopDetection::isValidInstruction(Instruction &Inst, 1109 DetectionContext &Context) const { 1110 for (auto &Op : Inst.operands()) { 1111 auto *OpInst = dyn_cast<Instruction>(&Op); 1112 1113 if (!OpInst) 1114 continue; 1115 1116 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) 1117 return false; 1118 } 1119 1120 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst)) 1121 return false; 1122 1123 // We only check the call instruction but not invoke instruction. 1124 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) { 1125 if (isValidCallInst(*CI, Context)) 1126 return true; 1127 1128 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst); 1129 } 1130 1131 if (!Inst.mayReadOrWriteMemory()) { 1132 if (!isa<AllocaInst>(Inst)) 1133 return true; 1134 1135 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst); 1136 } 1137 1138 // Check the access function. 1139 if (auto MemInst = MemAccInst::dyn_cast(Inst)) { 1140 Context.hasStores |= isa<StoreInst>(MemInst); 1141 Context.hasLoads |= isa<LoadInst>(MemInst); 1142 if (!MemInst.isSimple()) 1143 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true, 1144 &Inst); 1145 1146 return isValidMemoryAccess(MemInst, Context); 1147 } 1148 1149 // We do not know this instruction, therefore we assume it is invalid. 1150 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst); 1151 } 1152 1153 /// Check whether @p L has exiting blocks. 1154 /// 1155 /// @param L The loop of interest 1156 /// 1157 /// @return True if the loop has exiting blocks, false otherwise. 1158 static bool hasExitingBlocks(Loop *L) { 1159 SmallVector<BasicBlock *, 4> ExitingBlocks; 1160 L->getExitingBlocks(ExitingBlocks); 1161 return !ExitingBlocks.empty(); 1162 } 1163 1164 bool ScopDetection::canUseISLTripCount(Loop *L, 1165 DetectionContext &Context) const { 1166 // Ensure the loop has valid exiting blocks as well as latches, otherwise we 1167 // need to overapproximate it as a boxed loop. 1168 SmallVector<BasicBlock *, 4> LoopControlBlocks; 1169 L->getExitingBlocks(LoopControlBlocks); 1170 L->getLoopLatches(LoopControlBlocks); 1171 for (BasicBlock *ControlBB : LoopControlBlocks) { 1172 if (!isValidCFG(*ControlBB, true, false, Context)) 1173 return false; 1174 } 1175 1176 // We can use ISL to compute the trip count of L. 1177 return true; 1178 } 1179 1180 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const { 1181 // Loops that contain part but not all of the blocks of a region cannot be 1182 // handled by the schedule generation. Such loop constructs can happen 1183 // because a region can contain BBs that have no path to the exit block 1184 // (Infinite loops, UnreachableInst), but such blocks are never part of a 1185 // loop. 1186 // 1187 // _______________ 1188 // | Loop Header | <-----------. 1189 // --------------- | 1190 // | | 1191 // _______________ ______________ 1192 // | RegionEntry |-----> | RegionExit |-----> 1193 // --------------- -------------- 1194 // | 1195 // _______________ 1196 // | EndlessLoop | <--. 1197 // --------------- | 1198 // | | 1199 // \------------/ 1200 // 1201 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is 1202 // neither entirely contained in the region RegionEntry->RegionExit 1203 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained 1204 // in the loop. 1205 // The block EndlessLoop is contained in the region because Region::contains 1206 // tests whether it is not dominated by RegionExit. This is probably to not 1207 // having to query the PostdominatorTree. Instead of an endless loop, a dead 1208 // end can also be formed by an UnreachableInst. This case is already caught 1209 // by isErrorBlock(). We hence only have to reject endless loops here. 1210 if (!hasExitingBlocks(L)) 1211 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L); 1212 1213 if (canUseISLTripCount(L, Context)) 1214 return true; 1215 1216 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) { 1217 Region *R = RI.getRegionFor(L->getHeader()); 1218 while (R != &Context.CurRegion && !R->contains(L)) 1219 R = R->getParent(); 1220 1221 if (addOverApproximatedRegion(R, Context)) 1222 return true; 1223 } 1224 1225 const SCEV *LoopCount = SE.getBackedgeTakenCount(L); 1226 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount); 1227 } 1228 1229 /// Return the number of loops in @p L (incl. @p L) that have a trip 1230 /// count that is not known to be less than @MinProfitableTrips. 1231 ScopDetection::LoopStats 1232 ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE, 1233 unsigned MinProfitableTrips) { 1234 auto *TripCount = SE.getBackedgeTakenCount(L); 1235 1236 int NumLoops = 1; 1237 int MaxLoopDepth = 1; 1238 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount)) 1239 if (TripCountC->getType()->getScalarSizeInBits() <= 64) 1240 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips) 1241 NumLoops -= 1; 1242 1243 for (auto &SubLoop : *L) { 1244 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips); 1245 NumLoops += Stats.NumLoops; 1246 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1); 1247 } 1248 1249 return {NumLoops, MaxLoopDepth}; 1250 } 1251 1252 ScopDetection::LoopStats 1253 ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE, 1254 LoopInfo &LI, unsigned MinProfitableTrips) { 1255 int LoopNum = 0; 1256 int MaxLoopDepth = 0; 1257 1258 auto L = LI.getLoopFor(R->getEntry()); 1259 L = L ? R->outermostLoopInRegion(L) : nullptr; 1260 L = L ? L->getParentLoop() : nullptr; 1261 1262 auto SubLoops = 1263 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end()); 1264 1265 for (auto &SubLoop : SubLoops) 1266 if (R->contains(SubLoop)) { 1267 LoopStats Stats = 1268 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips); 1269 LoopNum += Stats.NumLoops; 1270 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth); 1271 } 1272 1273 return {LoopNum, MaxLoopDepth}; 1274 } 1275 1276 Region *ScopDetection::expandRegion(Region &R) { 1277 // Initial no valid region was found (greater than R) 1278 std::unique_ptr<Region> LastValidRegion; 1279 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion()); 1280 1281 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n"); 1282 1283 while (ExpandedRegion) { 1284 const auto &It = DetectionContextMap.insert(std::make_pair( 1285 getBBPairForRegion(ExpandedRegion.get()), 1286 DetectionContext(*ExpandedRegion, AA, false /*verifying*/))); 1287 DetectionContext &Context = It.first->second; 1288 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n"); 1289 // Only expand when we did not collect errors. 1290 1291 if (!Context.Log.hasErrors()) { 1292 // If the exit is valid check all blocks 1293 // - if true, a valid region was found => store it + keep expanding 1294 // - if false, .tbd. => stop (should this really end the loop?) 1295 if (!allBlocksValid(Context) || Context.Log.hasErrors()) { 1296 removeCachedResults(*ExpandedRegion); 1297 DetectionContextMap.erase(It.first); 1298 break; 1299 } 1300 1301 // Store this region, because it is the greatest valid (encountered so 1302 // far). 1303 if (LastValidRegion) { 1304 removeCachedResults(*LastValidRegion); 1305 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get())); 1306 } 1307 LastValidRegion = std::move(ExpandedRegion); 1308 1309 // Create and test the next greater region (if any) 1310 ExpandedRegion = 1311 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion()); 1312 1313 } else { 1314 // Create and test the next greater region (if any) 1315 removeCachedResults(*ExpandedRegion); 1316 DetectionContextMap.erase(It.first); 1317 ExpandedRegion = 1318 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion()); 1319 } 1320 } 1321 1322 DEBUG({ 1323 if (LastValidRegion) 1324 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n"; 1325 else 1326 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n"; 1327 }); 1328 1329 return LastValidRegion.release(); 1330 } 1331 static bool regionWithoutLoops(Region &R, LoopInfo &LI) { 1332 for (const BasicBlock *BB : R.blocks()) 1333 if (R.contains(LI.getLoopFor(BB))) 1334 return false; 1335 1336 return true; 1337 } 1338 1339 void ScopDetection::removeCachedResultsRecursively(const Region &R) { 1340 for (auto &SubRegion : R) { 1341 if (ValidRegions.count(SubRegion.get())) { 1342 removeCachedResults(*SubRegion.get()); 1343 } else 1344 removeCachedResultsRecursively(*SubRegion); 1345 } 1346 } 1347 1348 void ScopDetection::removeCachedResults(const Region &R) { 1349 ValidRegions.remove(&R); 1350 } 1351 1352 void ScopDetection::findScops(Region &R) { 1353 const auto &It = DetectionContextMap.insert(std::make_pair( 1354 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/))); 1355 DetectionContext &Context = It.first->second; 1356 1357 bool RegionIsValid = false; 1358 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) 1359 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R); 1360 else 1361 RegionIsValid = isValidRegion(Context); 1362 1363 bool HasErrors = !RegionIsValid || Context.Log.size() > 0; 1364 1365 if (HasErrors) { 1366 removeCachedResults(R); 1367 } else { 1368 ValidRegions.insert(&R); 1369 return; 1370 } 1371 1372 for (auto &SubRegion : R) 1373 findScops(*SubRegion); 1374 1375 // Try to expand regions. 1376 // 1377 // As the region tree normally only contains canonical regions, non canonical 1378 // regions that form a Scop are not found. Therefore, those non canonical 1379 // regions are checked by expanding the canonical ones. 1380 1381 std::vector<Region *> ToExpand; 1382 1383 for (auto &SubRegion : R) 1384 ToExpand.push_back(SubRegion.get()); 1385 1386 for (Region *CurrentRegion : ToExpand) { 1387 // Skip invalid regions. Regions may become invalid, if they are element of 1388 // an already expanded region. 1389 if (!ValidRegions.count(CurrentRegion)) 1390 continue; 1391 1392 // Skip regions that had errors. 1393 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors(); 1394 if (HadErrors) 1395 continue; 1396 1397 Region *ExpandedR = expandRegion(*CurrentRegion); 1398 1399 if (!ExpandedR) 1400 continue; 1401 1402 R.addSubRegion(ExpandedR, true); 1403 ValidRegions.insert(ExpandedR); 1404 removeCachedResults(*CurrentRegion); 1405 removeCachedResultsRecursively(*ExpandedR); 1406 } 1407 } 1408 1409 bool ScopDetection::allBlocksValid(DetectionContext &Context) const { 1410 Region &CurRegion = Context.CurRegion; 1411 1412 for (const BasicBlock *BB : CurRegion.blocks()) { 1413 Loop *L = LI.getLoopFor(BB); 1414 if (L && L->getHeader() == BB) { 1415 if (CurRegion.contains(L)) { 1416 if (!isValidLoop(L, Context) && !KeepGoing) 1417 return false; 1418 } else { 1419 SmallVector<BasicBlock *, 1> Latches; 1420 L->getLoopLatches(Latches); 1421 for (BasicBlock *Latch : Latches) 1422 if (CurRegion.contains(Latch)) 1423 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true, 1424 L); 1425 } 1426 } 1427 } 1428 1429 for (BasicBlock *BB : CurRegion.blocks()) { 1430 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT); 1431 1432 // Also check exception blocks (and possibly register them as non-affine 1433 // regions). Even though exception blocks are not modeled, we use them 1434 // to forward-propagate domain constraints during ScopInfo construction. 1435 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing) 1436 return false; 1437 1438 if (IsErrorBlock) 1439 continue; 1440 1441 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I) 1442 if (!isValidInstruction(*I, Context) && !KeepGoing) 1443 return false; 1444 } 1445 1446 if (!hasAffineMemoryAccesses(Context)) 1447 return false; 1448 1449 return true; 1450 } 1451 1452 bool ScopDetection::hasSufficientCompute(DetectionContext &Context, 1453 int NumLoops) const { 1454 int InstCount = 0; 1455 1456 if (NumLoops == 0) 1457 return false; 1458 1459 for (auto *BB : Context.CurRegion.blocks()) 1460 if (Context.CurRegion.contains(LI.getLoopFor(BB))) 1461 InstCount += BB->size(); 1462 1463 InstCount = InstCount / NumLoops; 1464 1465 return InstCount >= ProfitabilityMinPerLoopInstructions; 1466 } 1467 1468 bool ScopDetection::hasPossiblyDistributableLoop( 1469 DetectionContext &Context) const { 1470 for (auto *BB : Context.CurRegion.blocks()) { 1471 auto *L = LI.getLoopFor(BB); 1472 if (!Context.CurRegion.contains(L)) 1473 continue; 1474 if (Context.BoxedLoopsSet.count(L)) 1475 continue; 1476 unsigned StmtsWithStoresInLoops = 0; 1477 for (auto *LBB : L->blocks()) { 1478 bool MemStore = false; 1479 for (auto &I : *LBB) 1480 MemStore |= isa<StoreInst>(&I); 1481 StmtsWithStoresInLoops += MemStore; 1482 } 1483 return (StmtsWithStoresInLoops > 1); 1484 } 1485 return false; 1486 } 1487 1488 bool ScopDetection::isProfitableRegion(DetectionContext &Context) const { 1489 Region &CurRegion = Context.CurRegion; 1490 1491 if (PollyProcessUnprofitable) 1492 return true; 1493 1494 // We can probably not do a lot on scops that only write or only read 1495 // data. 1496 if (!Context.hasStores || !Context.hasLoads) 1497 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion); 1498 1499 int NumLoops = 1500 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops; 1501 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size(); 1502 1503 // Scops with at least two loops may allow either loop fusion or tiling and 1504 // are consequently interesting to look at. 1505 if (NumAffineLoops >= 2) 1506 return true; 1507 1508 // A loop with multiple non-trivial blocks might be amendable to distribution. 1509 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context)) 1510 return true; 1511 1512 // Scops that contain a loop with a non-trivial amount of computation per 1513 // loop-iteration are interesting as we may be able to parallelize such 1514 // loops. Individual loops that have only a small amount of computation 1515 // per-iteration are performance-wise very fragile as any change to the 1516 // loop induction variables may affect performance. To not cause spurious 1517 // performance regressions, we do not consider such loops. 1518 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops)) 1519 return true; 1520 1521 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion); 1522 } 1523 1524 bool ScopDetection::isValidRegion(DetectionContext &Context) const { 1525 Region &CurRegion = Context.CurRegion; 1526 1527 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t"); 1528 1529 if (!AllowFullFunction && CurRegion.isTopLevelRegion()) { 1530 DEBUG(dbgs() << "Top level region is invalid\n"); 1531 return false; 1532 } 1533 1534 DebugLoc DbgLoc; 1535 if (CurRegion.getExit() && 1536 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) { 1537 DEBUG(dbgs() << "Unreachable in exit\n"); 1538 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true, 1539 CurRegion.getExit(), DbgLoc); 1540 } 1541 1542 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) { 1543 DEBUG({ 1544 dbgs() << "Region entry does not match -polly-region-only"; 1545 dbgs() << "\n"; 1546 }); 1547 return false; 1548 } 1549 1550 // SCoP cannot contain the entry block of the function, because we need 1551 // to insert alloca instruction there when translate scalar to array. 1552 if (!AllowFullFunction && 1553 CurRegion.getEntry() == 1554 &(CurRegion.getEntry()->getParent()->getEntryBlock())) 1555 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry()); 1556 1557 if (!allBlocksValid(Context)) 1558 return false; 1559 1560 if (!isReducibleRegion(CurRegion, DbgLoc)) 1561 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true, 1562 &CurRegion, DbgLoc); 1563 1564 DEBUG(dbgs() << "OK\n"); 1565 return true; 1566 } 1567 1568 void ScopDetection::markFunctionAsInvalid(Function *F) { 1569 F->addFnAttr(PollySkipFnAttr); 1570 } 1571 1572 bool ScopDetection::isValidFunction(llvm::Function &F) { 1573 return !F.hasFnAttribute(PollySkipFnAttr); 1574 } 1575 1576 void ScopDetection::printLocations(llvm::Function &F) { 1577 for (const Region *R : *this) { 1578 unsigned LineEntry, LineExit; 1579 std::string FileName; 1580 1581 getDebugLocation(R, LineEntry, LineExit, FileName); 1582 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit); 1583 F.getContext().diagnose(Diagnostic); 1584 } 1585 } 1586 1587 void ScopDetection::emitMissedRemarks(const Function &F) { 1588 for (auto &DIt : DetectionContextMap) { 1589 auto &DC = DIt.getSecond(); 1590 if (DC.Log.hasErrors()) 1591 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE); 1592 } 1593 } 1594 1595 bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const { 1596 /// Enum for coloring BBs in Region. 1597 /// 1598 /// WHITE - Unvisited BB in DFS walk. 1599 /// GREY - BBs which are currently on the DFS stack for processing. 1600 /// BLACK - Visited and completely processed BB. 1601 enum Color { WHITE, GREY, BLACK }; 1602 1603 BasicBlock *REntry = R.getEntry(); 1604 BasicBlock *RExit = R.getExit(); 1605 // Map to match the color of a BasicBlock during the DFS walk. 1606 DenseMap<const BasicBlock *, Color> BBColorMap; 1607 // Stack keeping track of current BB and index of next child to be processed. 1608 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack; 1609 1610 unsigned AdjacentBlockIndex = 0; 1611 BasicBlock *CurrBB, *SuccBB; 1612 CurrBB = REntry; 1613 1614 // Initialize the map for all BB with WHITE color. 1615 for (auto *BB : R.blocks()) 1616 BBColorMap[BB] = WHITE; 1617 1618 // Process the entry block of the Region. 1619 BBColorMap[CurrBB] = GREY; 1620 DFSStack.push(std::make_pair(CurrBB, 0)); 1621 1622 while (!DFSStack.empty()) { 1623 // Get next BB on stack to be processed. 1624 CurrBB = DFSStack.top().first; 1625 AdjacentBlockIndex = DFSStack.top().second; 1626 DFSStack.pop(); 1627 1628 // Loop to iterate over the successors of current BB. 1629 const TerminatorInst *TInst = CurrBB->getTerminator(); 1630 unsigned NSucc = TInst->getNumSuccessors(); 1631 for (unsigned I = AdjacentBlockIndex; I < NSucc; 1632 ++I, ++AdjacentBlockIndex) { 1633 SuccBB = TInst->getSuccessor(I); 1634 1635 // Checks for region exit block and self-loops in BB. 1636 if (SuccBB == RExit || SuccBB == CurrBB) 1637 continue; 1638 1639 // WHITE indicates an unvisited BB in DFS walk. 1640 if (BBColorMap[SuccBB] == WHITE) { 1641 // Push the current BB and the index of the next child to be visited. 1642 DFSStack.push(std::make_pair(CurrBB, I + 1)); 1643 // Push the next BB to be processed. 1644 DFSStack.push(std::make_pair(SuccBB, 0)); 1645 // First time the BB is being processed. 1646 BBColorMap[SuccBB] = GREY; 1647 break; 1648 } else if (BBColorMap[SuccBB] == GREY) { 1649 // GREY indicates a loop in the control flow. 1650 // If the destination dominates the source, it is a natural loop 1651 // else, an irreducible control flow in the region is detected. 1652 if (!DT.dominates(SuccBB, CurrBB)) { 1653 // Get debug info of instruction which causes irregular control flow. 1654 DbgLoc = TInst->getDebugLoc(); 1655 return false; 1656 } 1657 } 1658 } 1659 1660 // If all children of current BB have been processed, 1661 // then mark that BB as fully processed. 1662 if (AdjacentBlockIndex == NSucc) 1663 BBColorMap[CurrBB] = BLACK; 1664 } 1665 1666 return true; 1667 } 1668 1669 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats, 1670 bool OnlyProfitable) { 1671 if (!OnlyProfitable) { 1672 NumLoopsInScop += Stats.NumLoops; 1673 MaxNumLoopsInScop = 1674 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops); 1675 if (Stats.MaxDepth == 1) 1676 NumScopsDepthOne++; 1677 else if (Stats.MaxDepth == 2) 1678 NumScopsDepthTwo++; 1679 else if (Stats.MaxDepth == 3) 1680 NumScopsDepthThree++; 1681 else if (Stats.MaxDepth == 4) 1682 NumScopsDepthFour++; 1683 else if (Stats.MaxDepth == 5) 1684 NumScopsDepthFive++; 1685 else 1686 NumScopsDepthLarger++; 1687 } else { 1688 NumLoopsInProfScop += Stats.NumLoops; 1689 MaxNumLoopsInProfScop = 1690 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops); 1691 if (Stats.MaxDepth == 1) 1692 NumProfScopsDepthOne++; 1693 else if (Stats.MaxDepth == 2) 1694 NumProfScopsDepthTwo++; 1695 else if (Stats.MaxDepth == 3) 1696 NumProfScopsDepthThree++; 1697 else if (Stats.MaxDepth == 4) 1698 NumProfScopsDepthFour++; 1699 else if (Stats.MaxDepth == 5) 1700 NumProfScopsDepthFive++; 1701 else 1702 NumProfScopsDepthLarger++; 1703 } 1704 } 1705 1706 ScopDetection::DetectionContext * 1707 ScopDetection::getDetectionContext(const Region *R) const { 1708 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R)); 1709 if (DCMIt == DetectionContextMap.end()) 1710 return nullptr; 1711 return &DCMIt->second; 1712 } 1713 1714 const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const { 1715 const DetectionContext *DC = getDetectionContext(R); 1716 return DC ? &DC->Log : nullptr; 1717 } 1718 1719 void polly::ScopDetection::verifyRegion(const Region &R) const { 1720 assert(isMaxRegionInScop(R) && "Expect R is a valid region."); 1721 1722 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/); 1723 isValidRegion(Context); 1724 } 1725 1726 void polly::ScopDetection::verifyAnalysis() const { 1727 if (!VerifyScops) 1728 return; 1729 1730 for (const Region *R : ValidRegions) 1731 verifyRegion(*R); 1732 } 1733 1734 bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) { 1735 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1736 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo(); 1737 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1738 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1739 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1740 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 1741 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE)); 1742 return false; 1743 } 1744 1745 void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1746 AU.addRequired<LoopInfoWrapperPass>(); 1747 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 1748 AU.addRequired<DominatorTreeWrapperPass>(); 1749 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1750 // We also need AA and RegionInfo when we are verifying analysis. 1751 AU.addRequiredTransitive<AAResultsWrapperPass>(); 1752 AU.addRequiredTransitive<RegionInfoPass>(); 1753 AU.setPreservesAll(); 1754 } 1755 1756 void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const { 1757 for (const Region *R : Result->ValidRegions) 1758 OS << "Valid Region for Scop: " << R->getNameStr() << '\n'; 1759 1760 OS << "\n"; 1761 } 1762 1763 ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) { 1764 // Disable runtime alias checks if we ignore aliasing all together. 1765 if (IgnoreAliasing) 1766 PollyUseRuntimeAliasChecks = false; 1767 } 1768 1769 void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); } 1770 1771 char ScopDetectionWrapperPass::ID; 1772 1773 AnalysisKey ScopAnalysis::Key; 1774 1775 ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) { 1776 auto &LI = FAM.getResult<LoopAnalysis>(F); 1777 auto &RI = FAM.getResult<RegionInfoAnalysis>(F); 1778 auto &AA = FAM.getResult<AAManager>(F); 1779 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F); 1780 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 1781 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1782 return {F, DT, SE, LI, RI, AA, ORE}; 1783 } 1784 1785 PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F, 1786 FunctionAnalysisManager &FAM) { 1787 auto &SD = FAM.getResult<ScopAnalysis>(F); 1788 for (const Region *R : SD.ValidRegions) 1789 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n'; 1790 1791 Stream << "\n"; 1792 return PreservedAnalyses::all(); 1793 } 1794 1795 Pass *polly::createScopDetectionWrapperPassPass() { 1796 return new ScopDetectionWrapperPass(); 1797 } 1798 1799 INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect", 1800 "Polly - Detect static control parts (SCoPs)", false, 1801 false); 1802 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 1803 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 1804 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 1805 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 1806 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 1807 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass); 1808 INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect", 1809 "Polly - Detect static control parts (SCoPs)", false, false) 1810