[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / polly / lib / Analysis / ScopDetection.cpp
blob2a7e276ac62d80f389a29423c4b36db005c76c34
1 //===- ScopDetection.cpp - Detect Scops -----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Detect the maximal Scops of a function.
11 // A static control part (Scop) is a subgraph of the control flow graph (CFG)
12 // that only has statically known control flow and can therefore be described
13 // within the polyhedral model.
15 // Every Scop fulfills these restrictions:
17 // * It is a single entry single exit region
19 // * Only affine linear bounds in the loops
21 // Every natural loop in a Scop must have a number of loop iterations that can
22 // be described as an affine linear function in surrounding loop iterators or
23 // parameters. (A parameter is a scalar that does not change its value during
24 // execution of the Scop).
26 // * Only comparisons of affine linear expressions in conditions
28 // * All loops and conditions perfectly nested
30 // The control flow needs to be structured such that it could be written using
31 // just 'for' and 'if' statements, without the need for any 'goto', 'break' or
32 // 'continue'.
34 // * Side effect free functions call
36 // Function calls and intrinsics that do not have side effects (readnone)
37 // or memory intrinsics (memset, memcpy, memmove) are allowed.
39 // The Scop detection finds the largest Scops by checking if the largest
40 // region is a Scop. If this is not the case, its canonical subregions are
41 // checked until a region is a Scop. It is now tried to extend this Scop by
42 // creating a larger non canonical region.
44 //===----------------------------------------------------------------------===//
46 #include "polly/ScopDetection.h"
47 #include "polly/LinkAllPasses.h"
48 #include "polly/Options.h"
49 #include "polly/ScopDetectionDiagnostic.h"
50 #include "polly/Support/SCEVValidator.h"
51 #include "polly/Support/ScopHelper.h"
52 #include "polly/Support/ScopLocation.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/Delinearization.h"
57 #include "llvm/Analysis/Loads.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
60 #include "llvm/Analysis/RegionInfo.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/DebugLoc.h"
65 #include "llvm/IR/DerivedTypes.h"
66 #include "llvm/IR/DiagnosticInfo.h"
67 #include "llvm/IR/DiagnosticPrinter.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/Function.h"
70 #include "llvm/IR/InstrTypes.h"
71 #include "llvm/IR/Instruction.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/Metadata.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/PassManager.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/Regex.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include <algorithm>
84 #include <cassert>
85 #include <memory>
86 #include <stack>
87 #include <string>
88 #include <utility>
89 #include <vector>
91 using namespace llvm;
92 using namespace polly;
94 #define DEBUG_TYPE "polly-detect"
96 // This option is set to a very high value, as analyzing such loops increases
97 // compile time on several cases. For experiments that enable this option,
98 // a value of around 40 has been working to avoid run-time regressions with
99 // Polly while still exposing interesting optimization opportunities.
100 static cl::opt<int> ProfitabilityMinPerLoopInstructions(
101 "polly-detect-profitability-min-per-loop-insts",
102 cl::desc("The minimal number of per-loop instructions before a single loop "
103 "region is considered profitable"),
104 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
106 bool polly::PollyProcessUnprofitable;
108 static cl::opt<bool, true> XPollyProcessUnprofitable(
109 "polly-process-unprofitable",
110 cl::desc(
111 "Process scops that are unlikely to benefit from Polly optimizations."),
112 cl::location(PollyProcessUnprofitable), cl::cat(PollyCategory));
114 static cl::list<std::string> OnlyFunctions(
115 "polly-only-func",
116 cl::desc("Only run on functions that match a regex. "
117 "Multiple regexes can be comma separated. "
118 "Scop detection will run on all functions that match "
119 "ANY of the regexes provided."),
120 cl::CommaSeparated, cl::cat(PollyCategory));
122 static cl::list<std::string> IgnoredFunctions(
123 "polly-ignore-func",
124 cl::desc("Ignore functions that match a regex. "
125 "Multiple regexes can be comma separated. "
126 "Scop detection will ignore all functions that match "
127 "ANY of the regexes provided."),
128 cl::CommaSeparated, cl::cat(PollyCategory));
130 bool polly::PollyAllowFullFunction;
132 static cl::opt<bool, true>
133 XAllowFullFunction("polly-detect-full-functions",
134 cl::desc("Allow the detection of full functions"),
135 cl::location(polly::PollyAllowFullFunction),
136 cl::init(false), cl::cat(PollyCategory));
138 static cl::opt<std::string> OnlyRegion(
139 "polly-only-region",
140 cl::desc("Only run on certain regions (The provided identifier must "
141 "appear in the name of the region's entry block"),
142 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
143 cl::cat(PollyCategory));
145 static cl::opt<bool>
146 IgnoreAliasing("polly-ignore-aliasing",
147 cl::desc("Ignore possible aliasing of the array bases"),
148 cl::Hidden, cl::cat(PollyCategory));
150 bool polly::PollyAllowUnsignedOperations;
152 static cl::opt<bool, true> XPollyAllowUnsignedOperations(
153 "polly-allow-unsigned-operations",
154 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
155 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::init(true),
156 cl::cat(PollyCategory));
158 bool polly::PollyUseRuntimeAliasChecks;
160 static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
161 "polly-use-runtime-alias-checks",
162 cl::desc("Use runtime alias checks to resolve possible aliasing."),
163 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::init(true),
164 cl::cat(PollyCategory));
166 static cl::opt<bool>
167 ReportLevel("polly-report",
168 cl::desc("Print information about the activities of Polly"),
169 cl::cat(PollyCategory));
171 static cl::opt<bool> AllowDifferentTypes(
172 "polly-allow-differing-element-types",
173 cl::desc("Allow different element types for array accesses"), cl::Hidden,
174 cl::init(true), cl::cat(PollyCategory));
176 static cl::opt<bool>
177 AllowNonAffine("polly-allow-nonaffine",
178 cl::desc("Allow non affine access functions in arrays"),
179 cl::Hidden, cl::cat(PollyCategory));
181 static cl::opt<bool>
182 AllowModrefCall("polly-allow-modref-calls",
183 cl::desc("Allow functions with known modref behavior"),
184 cl::Hidden, cl::cat(PollyCategory));
186 static cl::opt<bool> AllowNonAffineSubRegions(
187 "polly-allow-nonaffine-branches",
188 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
189 cl::init(true), cl::cat(PollyCategory));
191 static cl::opt<bool>
192 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
193 cl::desc("Allow non affine conditions for loops"),
194 cl::Hidden, cl::cat(PollyCategory));
196 static cl::opt<bool, true>
197 TrackFailures("polly-detect-track-failures",
198 cl::desc("Track failure strings in detecting scop regions"),
199 cl::location(PollyTrackFailures), cl::Hidden, cl::init(true),
200 cl::cat(PollyCategory));
202 static cl::opt<bool> KeepGoing("polly-detect-keep-going",
203 cl::desc("Do not fail on the first error."),
204 cl::Hidden, cl::cat(PollyCategory));
206 static cl::opt<bool, true>
207 PollyDelinearizeX("polly-delinearize",
208 cl::desc("Delinearize array access functions"),
209 cl::location(PollyDelinearize), cl::Hidden,
210 cl::init(true), cl::cat(PollyCategory));
212 static cl::opt<bool>
213 VerifyScops("polly-detect-verify",
214 cl::desc("Verify the detected SCoPs after each transformation"),
215 cl::Hidden, cl::cat(PollyCategory));
217 bool polly::PollyInvariantLoadHoisting;
219 static cl::opt<bool, true>
220 XPollyInvariantLoadHoisting("polly-invariant-load-hoisting",
221 cl::desc("Hoist invariant loads."),
222 cl::location(PollyInvariantLoadHoisting),
223 cl::Hidden, cl::cat(PollyCategory));
225 static cl::opt<bool> PollyAllowErrorBlocks(
226 "polly-allow-error-blocks",
227 cl::desc("Allow to speculate on the execution of 'error blocks'."),
228 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
230 /// The minimal trip count under which loops are considered unprofitable.
231 static const unsigned MIN_LOOP_TRIP_COUNT = 8;
233 bool polly::PollyTrackFailures = false;
234 bool polly::PollyDelinearize = false;
235 StringRef polly::PollySkipFnAttr = "polly.skip.fn";
237 //===----------------------------------------------------------------------===//
238 // Statistics.
240 STATISTIC(NumScopRegions, "Number of scops");
241 STATISTIC(NumLoopsInScop, "Number of loops in scops");
242 STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
243 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
244 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
245 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
246 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
247 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
248 STATISTIC(NumScopsDepthLarger,
249 "Number of scops with maximal loop depth 6 and larger");
250 STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
251 STATISTIC(NumLoopsInProfScop,
252 "Number of loops in scops (profitable scops only)");
253 STATISTIC(NumLoopsOverall, "Number of total loops");
254 STATISTIC(NumProfScopsDepthZero,
255 "Number of scops with maximal loop depth 0 (profitable scops only)");
256 STATISTIC(NumProfScopsDepthOne,
257 "Number of scops with maximal loop depth 1 (profitable scops only)");
258 STATISTIC(NumProfScopsDepthTwo,
259 "Number of scops with maximal loop depth 2 (profitable scops only)");
260 STATISTIC(NumProfScopsDepthThree,
261 "Number of scops with maximal loop depth 3 (profitable scops only)");
262 STATISTIC(NumProfScopsDepthFour,
263 "Number of scops with maximal loop depth 4 (profitable scops only)");
264 STATISTIC(NumProfScopsDepthFive,
265 "Number of scops with maximal loop depth 5 (profitable scops only)");
266 STATISTIC(NumProfScopsDepthLarger,
267 "Number of scops with maximal loop depth 6 and larger "
268 "(profitable scops only)");
269 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
270 STATISTIC(MaxNumLoopsInProfScop,
271 "Maximal number of loops in scops (profitable scops only)");
273 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
274 bool OnlyProfitable);
276 namespace {
278 class DiagnosticScopFound final : public DiagnosticInfo {
279 private:
280 static int PluginDiagnosticKind;
282 Function &F;
283 std::string FileName;
284 unsigned EntryLine, ExitLine;
286 public:
287 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
288 unsigned ExitLine)
289 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
290 EntryLine(EntryLine), ExitLine(ExitLine) {}
292 void print(DiagnosticPrinter &DP) const override;
294 static bool classof(const DiagnosticInfo *DI) {
295 return DI->getKind() == PluginDiagnosticKind;
298 } // namespace
300 int DiagnosticScopFound::PluginDiagnosticKind =
301 getNextAvailablePluginDiagnosticKind();
303 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
304 DP << "Polly detected an optimizable loop region (scop) in function '" << F
305 << "'\n";
307 if (FileName.empty()) {
308 DP << "Scop location is unknown. Compile with debug info "
309 "(-g) to get more precise information. ";
310 return;
313 DP << FileName << ":" << EntryLine << ": Start of scop\n";
314 DP << FileName << ":" << ExitLine << ": End of scop";
317 /// Check if a string matches any regex in a list of regexes.
318 /// @param Str the input string to match against.
319 /// @param RegexList a list of strings that are regular expressions.
320 static bool doesStringMatchAnyRegex(StringRef Str,
321 const cl::list<std::string> &RegexList) {
322 for (auto RegexStr : RegexList) {
323 Regex R(RegexStr);
325 std::string Err;
326 if (!R.isValid(Err))
327 report_fatal_error(Twine("invalid regex given as input to polly: ") + Err,
328 true);
330 if (R.match(Str))
331 return true;
333 return false;
336 //===----------------------------------------------------------------------===//
337 // ScopDetection.
339 ScopDetection::ScopDetection(const DominatorTree &DT, ScalarEvolution &SE,
340 LoopInfo &LI, RegionInfo &RI, AAResults &AA,
341 OptimizationRemarkEmitter &ORE)
342 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {}
344 void ScopDetection::detect(Function &F) {
345 assert(ValidRegions.empty() && "Detection must run only once");
347 if (!PollyProcessUnprofitable && LI.empty())
348 return;
350 Region *TopRegion = RI.getTopLevelRegion();
352 if (!OnlyFunctions.empty() &&
353 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
354 return;
356 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
357 return;
359 if (!isValidFunction(F))
360 return;
362 findScops(*TopRegion);
364 NumScopRegions += ValidRegions.size();
366 // Prune non-profitable regions.
367 for (auto &DIt : DetectionContextMap) {
368 DetectionContext &DC = *DIt.getSecond().get();
369 if (DC.Log.hasErrors())
370 continue;
371 if (!ValidRegions.count(&DC.CurRegion))
372 continue;
373 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
374 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
375 if (isProfitableRegion(DC)) {
376 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
377 continue;
380 ValidRegions.remove(&DC.CurRegion);
383 NumProfScopRegions += ValidRegions.size();
384 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
386 // Only makes sense when we tracked errors.
387 if (PollyTrackFailures)
388 emitMissedRemarks(F);
390 if (ReportLevel)
391 printLocations(F);
393 assert(ValidRegions.size() <= DetectionContextMap.size() &&
394 "Cached more results than valid regions");
397 template <class RR, typename... Args>
398 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
399 Args &&...Arguments) const {
400 if (!Context.Verifying) {
401 RejectLog &Log = Context.Log;
402 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
403 Context.IsInvalid = true;
405 // Log even if PollyTrackFailures is false, the log entries are also used in
406 // canUseISLTripCount().
407 Log.report(RejectReason);
409 LLVM_DEBUG(dbgs() << RejectReason->getMessage());
410 LLVM_DEBUG(dbgs() << "\n");
411 } else {
412 assert(!Assert && "Verification of detected scop failed");
415 return false;
418 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) {
419 if (!ValidRegions.count(&R))
420 return false;
422 if (Verify) {
423 BBPair P = getBBPairForRegion(&R);
424 std::unique_ptr<DetectionContext> &Entry = DetectionContextMap[P];
426 // Free previous DetectionContext for the region and create and verify a new
427 // one. Be sure that the DetectionContext is not still used by a ScopInfop.
428 // Due to changes but CodeGeneration of another Scop, the Region object and
429 // the BBPair might not match anymore.
430 Entry = std::make_unique<DetectionContext>(const_cast<Region &>(R), AA,
431 /*Verifying=*/false);
433 return isValidRegion(*Entry.get());
436 return true;
439 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
440 // Get the first error we found. Even in keep-going mode, this is the first
441 // reason that caused the candidate to be rejected.
442 auto *Log = lookupRejectionLog(R);
444 // This can happen when we marked a region invalid, but didn't track
445 // an error for it.
446 if (!Log || !Log->hasErrors())
447 return "";
449 RejectReasonPtr RR = *Log->begin();
450 return RR->getMessage();
453 bool ScopDetection::addOverApproximatedRegion(Region *AR,
454 DetectionContext &Context) const {
455 // If we already know about Ar we can exit.
456 if (!Context.NonAffineSubRegionSet.insert(AR))
457 return true;
459 // All loops in the region have to be overapproximated too if there
460 // are accesses that depend on the iteration count.
462 for (BasicBlock *BB : AR->blocks()) {
463 Loop *L = LI.getLoopFor(BB);
464 if (AR->contains(L))
465 Context.BoxedLoopsSet.insert(L);
468 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
471 bool ScopDetection::onlyValidRequiredInvariantLoads(
472 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
473 Region &CurRegion = Context.CurRegion;
474 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
476 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
477 return false;
479 for (LoadInst *Load : RequiredILS) {
480 // If we already know a load has been accepted as required invariant, we
481 // already run the validation below once and consequently don't need to
482 // run it again. Hence, we return early. For certain test cases (e.g.,
483 // COSMO this avoids us spending 50% of scop-detection time in this
484 // very function (and its children).
485 if (Context.RequiredILS.count(Load))
486 continue;
487 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
488 return false;
490 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
491 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
492 Load->getType(), Load->getAlign(), DL))
493 continue;
495 if (NonAffineRegion->contains(Load) &&
496 Load->getParent() != NonAffineRegion->getEntry())
497 return false;
501 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
503 return true;
506 bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
507 Loop *Scope) const {
508 SetVector<Value *> Values;
509 findValues(S0, SE, Values);
510 if (S1)
511 findValues(S1, SE, Values);
513 SmallPtrSet<Value *, 8> PtrVals;
514 for (auto *V : Values) {
515 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
516 V = P2I->getOperand(0);
518 if (!V->getType()->isPointerTy())
519 continue;
521 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
522 if (isa<SCEVConstant>(PtrSCEV))
523 continue;
525 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
526 if (!BasePtr)
527 return true;
529 auto *BasePtrVal = BasePtr->getValue();
530 if (PtrVals.insert(BasePtrVal).second) {
531 for (auto *PtrVal : PtrVals)
532 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
533 return true;
537 return false;
540 bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
541 DetectionContext &Context) const {
542 InvariantLoadsSetTy AccessILS;
543 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
544 return false;
546 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
547 return false;
549 return true;
552 bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
553 Value *Condition, bool IsLoopBranch,
554 DetectionContext &Context) const {
555 Loop *L = LI.getLoopFor(&BB);
556 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
558 if (IsLoopBranch && L->isLoopLatch(&BB))
559 return false;
561 // Check for invalid usage of different pointers in one expression.
562 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
563 return false;
565 if (isAffine(ConditionSCEV, L, Context))
566 return true;
568 if (AllowNonAffineSubRegions &&
569 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
570 return true;
572 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
573 ConditionSCEV, ConditionSCEV, SI);
576 bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
577 Value *Condition, bool IsLoopBranch,
578 DetectionContext &Context) {
579 // Constant integer conditions are always affine.
580 if (isa<ConstantInt>(Condition))
581 return true;
583 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
584 auto Opcode = BinOp->getOpcode();
585 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
586 Value *Op0 = BinOp->getOperand(0);
587 Value *Op1 = BinOp->getOperand(1);
588 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
589 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
593 if (auto PHI = dyn_cast<PHINode>(Condition)) {
594 auto *Unique = dyn_cast_or_null<ConstantInt>(
595 getUniqueNonErrorValue(PHI, &Context.CurRegion, this));
596 if (Unique && (Unique->isZero() || Unique->isOne()))
597 return true;
600 if (auto Load = dyn_cast<LoadInst>(Condition))
601 if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
602 Context.RequiredILS.insert(Load);
603 return true;
606 // Non constant conditions of branches need to be ICmpInst.
607 if (!isa<ICmpInst>(Condition)) {
608 if (!IsLoopBranch && AllowNonAffineSubRegions &&
609 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
610 return true;
611 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
614 ICmpInst *ICmp = cast<ICmpInst>(Condition);
616 // Are both operands of the ICmp affine?
617 if (isa<UndefValue>(ICmp->getOperand(0)) ||
618 isa<UndefValue>(ICmp->getOperand(1)))
619 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
621 Loop *L = LI.getLoopFor(&BB);
622 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
623 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
625 LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, this);
626 RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, this);
628 // If unsigned operations are not allowed try to approximate the region.
629 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
630 return !IsLoopBranch && AllowNonAffineSubRegions &&
631 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
633 // Check for invalid usage of different pointers in one expression.
634 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
635 involvesMultiplePtrs(RHS, nullptr, L))
636 return false;
638 // Check for invalid usage of different pointers in a relational comparison.
639 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
640 return false;
642 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
643 return true;
645 if (!IsLoopBranch && AllowNonAffineSubRegions &&
646 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
647 return true;
649 if (IsLoopBranch)
650 return false;
652 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
653 ICmp);
656 bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
657 bool AllowUnreachable,
658 DetectionContext &Context) {
659 Region &CurRegion = Context.CurRegion;
661 Instruction *TI = BB.getTerminator();
663 if (AllowUnreachable && isa<UnreachableInst>(TI))
664 return true;
666 // Return instructions are only valid if the region is the top level region.
667 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
668 return true;
670 Value *Condition = getConditionFromTerminator(TI);
672 if (!Condition)
673 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
675 // UndefValue is not allowed as condition.
676 if (isa<UndefValue>(Condition))
677 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
679 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
680 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
682 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
683 assert(SI && "Terminator was neither branch nor switch");
685 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
688 bool ScopDetection::isValidCallInst(CallInst &CI,
689 DetectionContext &Context) const {
690 if (CI.doesNotReturn())
691 return false;
693 if (CI.doesNotAccessMemory())
694 return true;
696 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
697 if (isValidIntrinsicInst(*II, Context))
698 return true;
700 Function *CalledFunction = CI.getCalledFunction();
702 // Indirect calls are not supported.
703 if (CalledFunction == nullptr)
704 return false;
706 if (isDebugCall(&CI)) {
707 LLVM_DEBUG(dbgs() << "Allow call to debug function: "
708 << CalledFunction->getName() << '\n');
709 return true;
712 if (AllowModrefCall) {
713 MemoryEffects ME = AA.getMemoryEffects(CalledFunction);
714 if (ME.onlyAccessesArgPointees()) {
715 for (const auto &Arg : CI.args()) {
716 if (!Arg->getType()->isPointerTy())
717 continue;
719 // Bail if a pointer argument has a base address not known to
720 // ScalarEvolution. Note that a zero pointer is acceptable.
721 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
722 if (ArgSCEV->isZero())
723 continue;
725 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
726 if (!BP)
727 return false;
729 // Implicitly disable delinearization since we have an unknown
730 // accesses with an unknown access function.
731 Context.HasUnknownAccess = true;
734 // Explicitly use addUnknown so we don't put a loop-variant
735 // pointer into the alias set.
736 Context.AST.addUnknown(&CI);
737 return true;
740 if (ME.onlyReadsMemory()) {
741 // Implicitly disable delinearization since we have an unknown
742 // accesses with an unknown access function.
743 Context.HasUnknownAccess = true;
744 // Explicitly use addUnknown so we don't put a loop-variant
745 // pointer into the alias set.
746 Context.AST.addUnknown(&CI);
747 return true;
749 return false;
752 return false;
755 bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
756 DetectionContext &Context) const {
757 if (isIgnoredIntrinsic(&II))
758 return true;
760 // The closest loop surrounding the call instruction.
761 Loop *L = LI.getLoopFor(II.getParent());
763 // The access function and base pointer for memory intrinsics.
764 const SCEV *AF;
765 const SCEVUnknown *BP;
767 switch (II.getIntrinsicID()) {
768 // Memory intrinsics that can be represented are supported.
769 case Intrinsic::memmove:
770 case Intrinsic::memcpy:
771 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
772 if (!AF->isZero()) {
773 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
774 // Bail if the source pointer is not valid.
775 if (!isValidAccess(&II, AF, BP, Context))
776 return false;
778 [[fallthrough]];
779 case Intrinsic::memset:
780 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
781 if (!AF->isZero()) {
782 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
783 // Bail if the destination pointer is not valid.
784 if (!isValidAccess(&II, AF, BP, Context))
785 return false;
788 // Bail if the length is not affine.
789 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
790 Context))
791 return false;
793 return true;
794 default:
795 break;
798 return false;
801 bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
802 DetectionContext &Ctx) const {
803 // A reference to function argument or constant value is invariant.
804 if (isa<Argument>(Val) || isa<Constant>(Val))
805 return true;
807 Instruction *I = dyn_cast<Instruction>(&Val);
808 if (!I)
809 return false;
811 if (!Reg.contains(I))
812 return true;
814 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
815 // is not hoistable, it will be rejected later, but here we assume it is and
816 // that makes the value invariant.
817 if (auto LI = dyn_cast<LoadInst>(I)) {
818 Ctx.RequiredILS.insert(LI);
819 return true;
822 return false;
825 namespace {
827 /// Remove smax of smax(0, size) expressions from a SCEV expression and
828 /// register the '...' components.
830 /// Array access expressions as they are generated by GFortran contain smax(0,
831 /// size) expressions that confuse the 'normal' delinearization algorithm.
832 /// However, if we extract such expressions before the normal delinearization
833 /// takes place they can actually help to identify array size expressions in
834 /// Fortran accesses. For the subsequently following delinearization the smax(0,
835 /// size) component can be replaced by just 'size'. This is correct as we will
836 /// always add and verify the assumption that for all subscript expressions
837 /// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
838 /// that 0 <= size, which means smax(0, size) == size.
839 class SCEVRemoveMax final : public SCEVRewriteVisitor<SCEVRemoveMax> {
840 public:
841 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
842 : SCEVRewriteVisitor(SE), Terms(Terms) {}
844 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
845 std::vector<const SCEV *> *Terms = nullptr) {
846 SCEVRemoveMax Rewriter(SE, Terms);
847 return Rewriter.visit(Scev);
850 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
851 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
852 auto Res = visit(Expr->getOperand(1));
853 if (Terms)
854 (*Terms).push_back(Res);
855 return Res;
858 return Expr;
861 private:
862 std::vector<const SCEV *> *Terms;
864 } // namespace
866 SmallVector<const SCEV *, 4>
867 ScopDetection::getDelinearizationTerms(DetectionContext &Context,
868 const SCEVUnknown *BasePointer) const {
869 SmallVector<const SCEV *, 4> Terms;
870 for (const auto &Pair : Context.Accesses[BasePointer]) {
871 std::vector<const SCEV *> MaxTerms;
872 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
873 if (!MaxTerms.empty()) {
874 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
875 continue;
877 // In case the outermost expression is a plain add, we check if any of its
878 // terms has the form 4 * %inst * %param * %param ..., aka a term that
879 // contains a product between a parameter and an instruction that is
880 // inside the scop. Such instructions, if allowed at all, are instructions
881 // SCEV can not represent, but Polly is still looking through. As a
882 // result, these instructions can depend on induction variables and are
883 // most likely no array sizes. However, terms that are multiplied with
884 // them are likely candidates for array sizes.
885 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
886 for (auto Op : AF->operands()) {
887 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
888 collectParametricTerms(SE, AF2, Terms);
889 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
890 SmallVector<const SCEV *, 0> Operands;
892 for (auto *MulOp : AF2->operands()) {
893 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
894 Operands.push_back(Const);
895 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
896 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
897 if (!Context.CurRegion.contains(Inst))
898 Operands.push_back(MulOp);
900 } else {
901 Operands.push_back(MulOp);
905 if (Operands.size())
906 Terms.push_back(SE.getMulExpr(Operands));
910 if (Terms.empty())
911 collectParametricTerms(SE, Pair.second, Terms);
913 return Terms;
916 bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
917 SmallVectorImpl<const SCEV *> &Sizes,
918 const SCEVUnknown *BasePointer,
919 Loop *Scope) const {
920 // If no sizes were found, all sizes are trivially valid. We allow this case
921 // to make it possible to pass known-affine accesses to the delinearization to
922 // try to recover some interesting multi-dimensional accesses, but to still
923 // allow the already known to be affine access in case the delinearization
924 // fails. In such situations, the delinearization will just return a Sizes
925 // array of size zero.
926 if (Sizes.size() == 0)
927 return true;
929 Value *BaseValue = BasePointer->getValue();
930 Region &CurRegion = Context.CurRegion;
931 for (const SCEV *DelinearizedSize : Sizes) {
932 // Don't pass down the scope to isAfffine; array dimensions must be
933 // invariant across the entire scop.
934 if (!isAffine(DelinearizedSize, nullptr, Context)) {
935 Sizes.clear();
936 break;
938 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
939 auto *V = dyn_cast<Value>(Unknown->getValue());
940 if (auto *Load = dyn_cast<LoadInst>(V)) {
941 if (Context.CurRegion.contains(Load) &&
942 isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
943 Context.RequiredILS.insert(Load);
944 continue;
947 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
948 Context.RequiredILS))
949 return invalid<ReportNonAffineAccess>(
950 Context, /*Assert=*/true, DelinearizedSize,
951 Context.Accesses[BasePointer].front().first, BaseValue);
954 // No array shape derived.
955 if (Sizes.empty()) {
956 if (AllowNonAffine)
957 return true;
959 for (const auto &Pair : Context.Accesses[BasePointer]) {
960 const Instruction *Insn = Pair.first;
961 const SCEV *AF = Pair.second;
963 if (!isAffine(AF, Scope, Context)) {
964 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
965 BaseValue);
966 if (!KeepGoing)
967 return false;
970 return false;
972 return true;
975 // We first store the resulting memory accesses in TempMemoryAccesses. Only
976 // if the access functions for all memory accesses have been successfully
977 // delinearized we continue. Otherwise, we either report a failure or, if
978 // non-affine accesses are allowed, we drop the information. In case the
979 // information is dropped the memory accesses need to be overapproximated
980 // when translated to a polyhedral representation.
981 bool ScopDetection::computeAccessFunctions(
982 DetectionContext &Context, const SCEVUnknown *BasePointer,
983 std::shared_ptr<ArrayShape> Shape) const {
984 Value *BaseValue = BasePointer->getValue();
985 bool BasePtrHasNonAffine = false;
986 MapInsnToMemAcc TempMemoryAccesses;
987 for (const auto &Pair : Context.Accesses[BasePointer]) {
988 const Instruction *Insn = Pair.first;
989 auto *AF = Pair.second;
990 AF = SCEVRemoveMax::rewrite(AF, SE);
991 bool IsNonAffine = false;
992 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
993 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
994 auto *Scope = LI.getLoopFor(Insn->getParent());
996 if (!AF) {
997 if (isAffine(Pair.second, Scope, Context))
998 Acc->DelinearizedSubscripts.push_back(Pair.second);
999 else
1000 IsNonAffine = true;
1001 } else {
1002 if (Shape->DelinearizedSizes.size() == 0) {
1003 Acc->DelinearizedSubscripts.push_back(AF);
1004 } else {
1005 llvm::computeAccessFunctions(SE, AF, Acc->DelinearizedSubscripts,
1006 Shape->DelinearizedSizes);
1007 if (Acc->DelinearizedSubscripts.size() == 0)
1008 IsNonAffine = true;
1010 for (const SCEV *S : Acc->DelinearizedSubscripts)
1011 if (!isAffine(S, Scope, Context))
1012 IsNonAffine = true;
1015 // (Possibly) report non affine access
1016 if (IsNonAffine) {
1017 BasePtrHasNonAffine = true;
1018 if (!AllowNonAffine) {
1019 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1020 Insn, BaseValue);
1021 if (!KeepGoing)
1022 return false;
1027 if (!BasePtrHasNonAffine)
1028 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1029 TempMemoryAccesses.end());
1031 return true;
1034 bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1035 const SCEVUnknown *BasePointer,
1036 Loop *Scope) const {
1037 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1039 auto Terms = getDelinearizationTerms(Context, BasePointer);
1041 findArrayDimensions(SE, Terms, Shape->DelinearizedSizes,
1042 Context.ElementSize[BasePointer]);
1044 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1045 Scope))
1046 return false;
1048 return computeAccessFunctions(Context, BasePointer, Shape);
1051 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
1052 // TODO: If we have an unknown access and other non-affine accesses we do
1053 // not try to delinearize them for now.
1054 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1055 return AllowNonAffine;
1057 for (auto &Pair : Context.NonAffineAccesses) {
1058 auto *BasePointer = Pair.first;
1059 auto *Scope = Pair.second;
1060 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
1061 Context.IsInvalid = true;
1062 if (!KeepGoing)
1063 return false;
1066 return true;
1069 bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1070 const SCEVUnknown *BP,
1071 DetectionContext &Context) const {
1073 if (!BP)
1074 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
1076 auto *BV = BP->getValue();
1077 if (isa<UndefValue>(BV))
1078 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
1080 // FIXME: Think about allowing IntToPtrInst
1081 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1082 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1084 // Check that the base address of the access is invariant in the current
1085 // region.
1086 if (!isInvariant(*BV, Context.CurRegion, Context))
1087 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
1089 AF = SE.getMinusSCEV(AF, BP);
1091 const SCEV *Size;
1092 if (!isa<MemIntrinsic>(Inst)) {
1093 Size = SE.getElementSize(Inst);
1094 } else {
1095 auto *SizeTy =
1096 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1097 Size = SE.getConstant(SizeTy, 8);
1100 if (Context.ElementSize[BP]) {
1101 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1102 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1103 Inst, BV);
1105 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
1106 } else {
1107 Context.ElementSize[BP] = Size;
1110 bool IsVariantInNonAffineLoop = false;
1111 SetVector<const Loop *> Loops;
1112 findLoops(AF, Loops);
1113 for (const Loop *L : Loops)
1114 if (Context.BoxedLoopsSet.count(L))
1115 IsVariantInNonAffineLoop = true;
1117 auto *Scope = LI.getLoopFor(Inst->getParent());
1118 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
1119 // Do not try to delinearize memory intrinsics and force them to be affine.
1120 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1121 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1122 BV);
1123 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1124 Context.Accesses[BP].push_back({Inst, AF});
1126 if (!IsAffine)
1127 Context.NonAffineAccesses.insert(
1128 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
1129 } else if (!AllowNonAffine && !IsAffine) {
1130 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1131 BV);
1134 if (IgnoreAliasing)
1135 return true;
1137 // Check if the base pointer of the memory access does alias with
1138 // any other pointer. This cannot be handled at the moment.
1139 AAMDNodes AATags = Inst->getAAMetadata();
1140 AliasSet &AS = Context.AST.getAliasSetFor(
1141 MemoryLocation::getBeforeOrAfter(BP->getValue(), AATags));
1143 if (!AS.isMustAlias()) {
1144 if (PollyUseRuntimeAliasChecks) {
1145 bool CanBuildRunTimeCheck = true;
1146 // The run-time alias check places code that involves the base pointer at
1147 // the beginning of the SCoP. This breaks if the base pointer is defined
1148 // inside the scop. Hence, we can only create a run-time check if we are
1149 // sure the base pointer is not an instruction defined inside the scop.
1150 // However, we can ignore loads that will be hoisted.
1152 InvariantLoadsSetTy VariantLS, InvariantLS;
1153 // In order to detect loads which are dependent on other invariant loads
1154 // as invariant, we use fixed-point iteration method here i.e we iterate
1155 // over the alias set for arbitrary number of times until it is safe to
1156 // assume that all the invariant loads have been detected
1157 while (true) {
1158 const unsigned int VariantSize = VariantLS.size(),
1159 InvariantSize = InvariantLS.size();
1161 for (const auto &Ptr : AS) {
1162 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1163 if (Inst && Context.CurRegion.contains(Inst)) {
1164 auto *Load = dyn_cast<LoadInst>(Inst);
1165 if (Load && InvariantLS.count(Load))
1166 continue;
1167 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT,
1168 InvariantLS)) {
1169 if (VariantLS.count(Load))
1170 VariantLS.remove(Load);
1171 Context.RequiredILS.insert(Load);
1172 InvariantLS.insert(Load);
1173 } else {
1174 CanBuildRunTimeCheck = false;
1175 VariantLS.insert(Load);
1180 if (InvariantSize == InvariantLS.size() &&
1181 VariantSize == VariantLS.size())
1182 break;
1185 if (CanBuildRunTimeCheck)
1186 return true;
1188 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
1191 return true;
1194 bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1195 DetectionContext &Context) const {
1196 Value *Ptr = Inst.getPointerOperand();
1197 Loop *L = LI.getLoopFor(Inst->getParent());
1198 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
1199 const SCEVUnknown *BasePointer;
1201 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1203 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1206 bool ScopDetection::isValidInstruction(Instruction &Inst,
1207 DetectionContext &Context) {
1208 for (auto &Op : Inst.operands()) {
1209 auto *OpInst = dyn_cast<Instruction>(&Op);
1211 if (!OpInst)
1212 continue;
1214 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion)) {
1215 auto *PHI = dyn_cast<PHINode>(OpInst);
1216 if (PHI) {
1217 for (User *U : PHI->users()) {
1218 auto *UI = dyn_cast<Instruction>(U);
1219 if (!UI || !UI->isTerminator())
1220 return false;
1222 } else {
1223 return false;
1228 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1229 return false;
1231 // We only check the call instruction but not invoke instruction.
1232 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1233 if (isValidCallInst(*CI, Context))
1234 return true;
1236 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
1239 if (!Inst.mayReadOrWriteMemory()) {
1240 if (!isa<AllocaInst>(Inst))
1241 return true;
1243 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
1246 // Check the access function.
1247 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
1248 Context.hasStores |= isa<StoreInst>(MemInst);
1249 Context.hasLoads |= isa<LoadInst>(MemInst);
1250 if (!MemInst.isSimple())
1251 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1252 &Inst);
1254 return isValidMemoryAccess(MemInst, Context);
1257 // We do not know this instruction, therefore we assume it is invalid.
1258 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
1261 /// Check whether @p L has exiting blocks.
1263 /// @param L The loop of interest
1265 /// @return True if the loop has exiting blocks, false otherwise.
1266 static bool hasExitingBlocks(Loop *L) {
1267 SmallVector<BasicBlock *, 4> ExitingBlocks;
1268 L->getExitingBlocks(ExitingBlocks);
1269 return !ExitingBlocks.empty();
1272 bool ScopDetection::canUseISLTripCount(Loop *L, DetectionContext &Context) {
1273 // FIXME: Yes, this is bad. isValidCFG() may call invalid<Reason>() which
1274 // causes the SCoP to be rejected regardless on whether non-ISL trip counts
1275 // could be used. We currently preserve the legacy behaviour of rejecting
1276 // based on Context.Log.size() added by isValidCFG() or before, regardless on
1277 // whether the ISL trip count can be used or can be used as a non-affine
1278 // region. However, we allow rejections by isValidCFG() that do not result in
1279 // an error log entry.
1280 bool OldIsInvalid = Context.IsInvalid;
1282 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1283 // need to overapproximate it as a boxed loop.
1284 SmallVector<BasicBlock *, 4> LoopControlBlocks;
1285 L->getExitingBlocks(LoopControlBlocks);
1286 L->getLoopLatches(LoopControlBlocks);
1287 for (BasicBlock *ControlBB : LoopControlBlocks) {
1288 if (!isValidCFG(*ControlBB, true, false, Context)) {
1289 Context.IsInvalid = OldIsInvalid || Context.Log.size();
1290 return false;
1294 // We can use ISL to compute the trip count of L.
1295 Context.IsInvalid = OldIsInvalid || Context.Log.size();
1296 return true;
1299 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) {
1300 // Loops that contain part but not all of the blocks of a region cannot be
1301 // handled by the schedule generation. Such loop constructs can happen
1302 // because a region can contain BBs that have no path to the exit block
1303 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1304 // loop.
1306 // _______________
1307 // | Loop Header | <-----------.
1308 // --------------- |
1309 // | |
1310 // _______________ ______________
1311 // | RegionEntry |-----> | RegionExit |----->
1312 // --------------- --------------
1313 // |
1314 // _______________
1315 // | EndlessLoop | <--.
1316 // --------------- |
1317 // | |
1318 // \------------/
1320 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1321 // neither entirely contained in the region RegionEntry->RegionExit
1322 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1323 // in the loop.
1324 // The block EndlessLoop is contained in the region because Region::contains
1325 // tests whether it is not dominated by RegionExit. This is probably to not
1326 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1327 // end can also be formed by an UnreachableInst. This case is already caught
1328 // by isErrorBlock(). We hence only have to reject endless loops here.
1329 if (!hasExitingBlocks(L))
1330 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1332 // The algorithm for domain construction assumes that loops has only a single
1333 // exit block (and hence corresponds to a subregion). Note that we cannot use
1334 // L->getExitBlock() because it does not check whether all exiting edges point
1335 // to the same BB.
1336 SmallVector<BasicBlock *, 4> ExitBlocks;
1337 L->getExitBlocks(ExitBlocks);
1338 BasicBlock *TheExitBlock = ExitBlocks[0];
1339 for (BasicBlock *ExitBB : ExitBlocks) {
1340 if (TheExitBlock != ExitBB)
1341 return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L);
1344 if (canUseISLTripCount(L, Context))
1345 return true;
1347 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
1348 Region *R = RI.getRegionFor(L->getHeader());
1349 while (R != &Context.CurRegion && !R->contains(L))
1350 R = R->getParent();
1352 if (addOverApproximatedRegion(R, Context))
1353 return true;
1356 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
1357 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
1360 /// Return the number of loops in @p L (incl. @p L) that have a trip
1361 /// count that is not known to be less than @MinProfitableTrips.
1362 ScopDetection::LoopStats
1363 ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1364 unsigned MinProfitableTrips) {
1365 auto *TripCount = SE.getBackedgeTakenCount(L);
1367 int NumLoops = 1;
1368 int MaxLoopDepth = 1;
1369 if (MinProfitableTrips > 0)
1370 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1371 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1372 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1373 NumLoops -= 1;
1375 for (auto &SubLoop : *L) {
1376 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1377 NumLoops += Stats.NumLoops;
1378 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1381 return {NumLoops, MaxLoopDepth};
1384 ScopDetection::LoopStats
1385 ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1386 LoopInfo &LI, unsigned MinProfitableTrips) {
1387 int LoopNum = 0;
1388 int MaxLoopDepth = 0;
1390 auto L = LI.getLoopFor(R->getEntry());
1392 // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1393 // L is either nullptr or already surrounding R.
1394 if (L && R->contains(L)) {
1395 L = R->outermostLoopInRegion(L);
1396 L = L->getParentLoop();
1399 auto SubLoops =
1400 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
1402 for (auto &SubLoop : SubLoops)
1403 if (R->contains(SubLoop)) {
1404 LoopStats Stats =
1405 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1406 LoopNum += Stats.NumLoops;
1407 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1410 return {LoopNum, MaxLoopDepth};
1413 static bool isErrorBlockImpl(BasicBlock &BB, const Region &R, LoopInfo &LI,
1414 const DominatorTree &DT) {
1415 if (isa<UnreachableInst>(BB.getTerminator()))
1416 return true;
1418 if (LI.isLoopHeader(&BB))
1419 return false;
1421 // Don't consider something outside the SCoP as error block. It will precede
1422 // the code versioning runtime check.
1423 if (!R.contains(&BB))
1424 return false;
1426 // Basic blocks that are always executed are not considered error blocks,
1427 // as their execution can not be a rare event.
1428 bool DominatesAllPredecessors = true;
1429 if (R.isTopLevelRegion()) {
1430 for (BasicBlock &I : *R.getEntry()->getParent()) {
1431 if (isa<ReturnInst>(I.getTerminator()) && !DT.dominates(&BB, &I)) {
1432 DominatesAllPredecessors = false;
1433 break;
1436 } else {
1437 for (auto Pred : predecessors(R.getExit())) {
1438 if (R.contains(Pred) && !DT.dominates(&BB, Pred)) {
1439 DominatesAllPredecessors = false;
1440 break;
1445 if (DominatesAllPredecessors)
1446 return false;
1448 for (Instruction &Inst : BB)
1449 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1450 if (isDebugCall(CI))
1451 continue;
1453 if (isIgnoredIntrinsic(CI))
1454 continue;
1456 // memset, memcpy and memmove are modeled intrinsics.
1457 if (isa<MemSetInst>(CI) || isa<MemTransferInst>(CI))
1458 continue;
1460 if (!CI->doesNotAccessMemory())
1461 return true;
1462 if (CI->doesNotReturn())
1463 return true;
1466 return false;
1469 bool ScopDetection::isErrorBlock(llvm::BasicBlock &BB, const llvm::Region &R) {
1470 if (!PollyAllowErrorBlocks)
1471 return false;
1473 auto It = ErrorBlockCache.insert({std::make_pair(&BB, &R), false});
1474 if (!It.second)
1475 return It.first->getSecond();
1477 bool Result = isErrorBlockImpl(BB, R, LI, DT);
1478 It.first->second = Result;
1479 return Result;
1482 Region *ScopDetection::expandRegion(Region &R) {
1483 // Initial no valid region was found (greater than R)
1484 std::unique_ptr<Region> LastValidRegion;
1485 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
1487 LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1489 while (ExpandedRegion) {
1490 BBPair P = getBBPairForRegion(ExpandedRegion.get());
1491 std::unique_ptr<DetectionContext> &Entry = DetectionContextMap[P];
1492 Entry = std::make_unique<DetectionContext>(*ExpandedRegion, AA,
1493 /*Verifying=*/false);
1494 DetectionContext &Context = *Entry.get();
1496 LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
1497 // Only expand when we did not collect errors.
1499 if (!Context.Log.hasErrors()) {
1500 // If the exit is valid check all blocks
1501 // - if true, a valid region was found => store it + keep expanding
1502 // - if false, .tbd. => stop (should this really end the loop?)
1503 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1504 removeCachedResults(*ExpandedRegion);
1505 DetectionContextMap.erase(P);
1506 break;
1509 // Store this region, because it is the greatest valid (encountered so
1510 // far).
1511 if (LastValidRegion) {
1512 removeCachedResults(*LastValidRegion);
1513 DetectionContextMap.erase(P);
1515 LastValidRegion = std::move(ExpandedRegion);
1517 // Create and test the next greater region (if any)
1518 ExpandedRegion =
1519 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
1521 } else {
1522 // Create and test the next greater region (if any)
1523 removeCachedResults(*ExpandedRegion);
1524 DetectionContextMap.erase(P);
1525 ExpandedRegion =
1526 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
1530 LLVM_DEBUG({
1531 if (LastValidRegion)
1532 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1533 else
1534 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1537 return LastValidRegion.release();
1540 static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
1541 for (const BasicBlock *BB : R.blocks())
1542 if (R.contains(LI.getLoopFor(BB)))
1543 return false;
1545 return true;
1548 void ScopDetection::removeCachedResultsRecursively(const Region &R) {
1549 for (auto &SubRegion : R) {
1550 if (ValidRegions.count(SubRegion.get())) {
1551 removeCachedResults(*SubRegion.get());
1552 } else
1553 removeCachedResultsRecursively(*SubRegion);
1557 void ScopDetection::removeCachedResults(const Region &R) {
1558 ValidRegions.remove(&R);
1561 void ScopDetection::findScops(Region &R) {
1562 std::unique_ptr<DetectionContext> &Entry =
1563 DetectionContextMap[getBBPairForRegion(&R)];
1564 Entry = std::make_unique<DetectionContext>(R, AA, /*Verifying=*/false);
1565 DetectionContext &Context = *Entry.get();
1567 bool DidBailout = true;
1568 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
1569 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
1570 else
1571 DidBailout = !isValidRegion(Context);
1573 (void)DidBailout;
1574 if (KeepGoing) {
1575 assert((!DidBailout || Context.IsInvalid) &&
1576 "With -polly-detect-keep-going, it is sufficient that if "
1577 "isValidRegion short-circuited, that SCoP is invalid");
1578 } else {
1579 assert(DidBailout == Context.IsInvalid &&
1580 "isValidRegion must short-circuit iff the ScoP is invalid");
1583 if (Context.IsInvalid) {
1584 removeCachedResults(R);
1585 } else {
1586 ValidRegions.insert(&R);
1587 return;
1590 for (auto &SubRegion : R)
1591 findScops(*SubRegion);
1593 // Try to expand regions.
1595 // As the region tree normally only contains canonical regions, non canonical
1596 // regions that form a Scop are not found. Therefore, those non canonical
1597 // regions are checked by expanding the canonical ones.
1599 std::vector<Region *> ToExpand;
1601 for (auto &SubRegion : R)
1602 ToExpand.push_back(SubRegion.get());
1604 for (Region *CurrentRegion : ToExpand) {
1605 // Skip invalid regions. Regions may become invalid, if they are element of
1606 // an already expanded region.
1607 if (!ValidRegions.count(CurrentRegion))
1608 continue;
1610 // Skip regions that had errors.
1611 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1612 if (HadErrors)
1613 continue;
1615 Region *ExpandedR = expandRegion(*CurrentRegion);
1617 if (!ExpandedR)
1618 continue;
1620 R.addSubRegion(ExpandedR, true);
1621 ValidRegions.insert(ExpandedR);
1622 removeCachedResults(*CurrentRegion);
1623 removeCachedResultsRecursively(*ExpandedR);
1627 bool ScopDetection::allBlocksValid(DetectionContext &Context) {
1628 Region &CurRegion = Context.CurRegion;
1630 for (const BasicBlock *BB : CurRegion.blocks()) {
1631 Loop *L = LI.getLoopFor(BB);
1632 if (L && L->getHeader() == BB) {
1633 if (CurRegion.contains(L)) {
1634 if (!isValidLoop(L, Context)) {
1635 Context.IsInvalid = true;
1636 if (!KeepGoing)
1637 return false;
1639 } else {
1640 SmallVector<BasicBlock *, 1> Latches;
1641 L->getLoopLatches(Latches);
1642 for (BasicBlock *Latch : Latches)
1643 if (CurRegion.contains(Latch))
1644 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1650 for (BasicBlock *BB : CurRegion.blocks()) {
1651 bool IsErrorBlock = isErrorBlock(*BB, CurRegion);
1653 // Also check exception blocks (and possibly register them as non-affine
1654 // regions). Even though exception blocks are not modeled, we use them
1655 // to forward-propagate domain constraints during ScopInfo construction.
1656 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1657 return false;
1659 if (IsErrorBlock)
1660 continue;
1662 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
1663 if (!isValidInstruction(*I, Context)) {
1664 Context.IsInvalid = true;
1665 if (!KeepGoing)
1666 return false;
1670 if (!hasAffineMemoryAccesses(Context))
1671 return false;
1673 return true;
1676 bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1677 int NumLoops) const {
1678 int InstCount = 0;
1680 if (NumLoops == 0)
1681 return false;
1683 for (auto *BB : Context.CurRegion.blocks())
1684 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
1685 InstCount += BB->size();
1687 InstCount = InstCount / NumLoops;
1689 return InstCount >= ProfitabilityMinPerLoopInstructions;
1692 bool ScopDetection::hasPossiblyDistributableLoop(
1693 DetectionContext &Context) const {
1694 for (auto *BB : Context.CurRegion.blocks()) {
1695 auto *L = LI.getLoopFor(BB);
1696 if (!Context.CurRegion.contains(L))
1697 continue;
1698 if (Context.BoxedLoopsSet.count(L))
1699 continue;
1700 unsigned StmtsWithStoresInLoops = 0;
1701 for (auto *LBB : L->blocks()) {
1702 bool MemStore = false;
1703 for (auto &I : *LBB)
1704 MemStore |= isa<StoreInst>(&I);
1705 StmtsWithStoresInLoops += MemStore;
1707 return (StmtsWithStoresInLoops > 1);
1709 return false;
1712 bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1713 Region &CurRegion = Context.CurRegion;
1715 if (PollyProcessUnprofitable)
1716 return true;
1718 // We can probably not do a lot on scops that only write or only read
1719 // data.
1720 if (!Context.hasStores || !Context.hasLoads)
1721 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1723 int NumLoops =
1724 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
1725 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
1727 // Scops with at least two loops may allow either loop fusion or tiling and
1728 // are consequently interesting to look at.
1729 if (NumAffineLoops >= 2)
1730 return true;
1732 // A loop with multiple non-trivial blocks might be amendable to distribution.
1733 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1734 return true;
1736 // Scops that contain a loop with a non-trivial amount of computation per
1737 // loop-iteration are interesting as we may be able to parallelize such
1738 // loops. Individual loops that have only a small amount of computation
1739 // per-iteration are performance-wise very fragile as any change to the
1740 // loop induction variables may affect performance. To not cause spurious
1741 // performance regressions, we do not consider such loops.
1742 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1743 return true;
1745 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1748 bool ScopDetection::isValidRegion(DetectionContext &Context) {
1749 Region &CurRegion = Context.CurRegion;
1751 LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
1753 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
1754 LLVM_DEBUG(dbgs() << "Top level region is invalid\n");
1755 Context.IsInvalid = true;
1756 return false;
1759 DebugLoc DbgLoc;
1760 if (CurRegion.getExit() &&
1761 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1762 LLVM_DEBUG(dbgs() << "Unreachable in exit\n");
1763 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1764 CurRegion.getExit(), DbgLoc);
1767 if (!OnlyRegion.empty() &&
1768 !CurRegion.getEntry()->getName().count(OnlyRegion)) {
1769 LLVM_DEBUG({
1770 dbgs() << "Region entry does not match -polly-only-region";
1771 dbgs() << "\n";
1773 Context.IsInvalid = true;
1774 return false;
1777 for (BasicBlock *Pred : predecessors(CurRegion.getEntry())) {
1778 Instruction *PredTerm = Pred->getTerminator();
1779 if (isa<IndirectBrInst>(PredTerm) || isa<CallBrInst>(PredTerm))
1780 return invalid<ReportIndirectPredecessor>(
1781 Context, /*Assert=*/true, PredTerm, PredTerm->getDebugLoc());
1784 // SCoP cannot contain the entry block of the function, because we need
1785 // to insert alloca instruction there when translate scalar to array.
1786 if (!PollyAllowFullFunction &&
1787 CurRegion.getEntry() ==
1788 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1789 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
1791 if (!allBlocksValid(Context)) {
1792 // TODO: Every failure condition within allBlocksValid should call
1793 // invalid<Reason>(). Otherwise we reject SCoPs without giving feedback to
1794 // the user.
1795 Context.IsInvalid = true;
1796 return false;
1799 if (!isReducibleRegion(CurRegion, DbgLoc))
1800 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1801 &CurRegion, DbgLoc);
1803 LLVM_DEBUG(dbgs() << "OK\n");
1804 return true;
1807 void ScopDetection::markFunctionAsInvalid(Function *F) {
1808 F->addFnAttr(PollySkipFnAttr);
1811 bool ScopDetection::isValidFunction(Function &F) {
1812 return !F.hasFnAttribute(PollySkipFnAttr);
1815 void ScopDetection::printLocations(Function &F) {
1816 for (const Region *R : *this) {
1817 unsigned LineEntry, LineExit;
1818 std::string FileName;
1820 getDebugLocation(R, LineEntry, LineExit, FileName);
1821 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1822 F.getContext().diagnose(Diagnostic);
1826 void ScopDetection::emitMissedRemarks(const Function &F) {
1827 for (auto &DIt : DetectionContextMap) {
1828 DetectionContext &DC = *DIt.getSecond().get();
1829 if (DC.Log.hasErrors())
1830 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
1834 bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1835 /// Enum for coloring BBs in Region.
1837 /// WHITE - Unvisited BB in DFS walk.
1838 /// GREY - BBs which are currently on the DFS stack for processing.
1839 /// BLACK - Visited and completely processed BB.
1840 enum Color { WHITE, GREY, BLACK };
1842 BasicBlock *REntry = R.getEntry();
1843 BasicBlock *RExit = R.getExit();
1844 // Map to match the color of a BasicBlock during the DFS walk.
1845 DenseMap<const BasicBlock *, Color> BBColorMap;
1846 // Stack keeping track of current BB and index of next child to be processed.
1847 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1849 unsigned AdjacentBlockIndex = 0;
1850 BasicBlock *CurrBB, *SuccBB;
1851 CurrBB = REntry;
1853 // Initialize the map for all BB with WHITE color.
1854 for (auto *BB : R.blocks())
1855 BBColorMap[BB] = WHITE;
1857 // Process the entry block of the Region.
1858 BBColorMap[CurrBB] = GREY;
1859 DFSStack.push(std::make_pair(CurrBB, 0));
1861 while (!DFSStack.empty()) {
1862 // Get next BB on stack to be processed.
1863 CurrBB = DFSStack.top().first;
1864 AdjacentBlockIndex = DFSStack.top().second;
1865 DFSStack.pop();
1867 // Loop to iterate over the successors of current BB.
1868 const Instruction *TInst = CurrBB->getTerminator();
1869 unsigned NSucc = TInst->getNumSuccessors();
1870 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1871 ++I, ++AdjacentBlockIndex) {
1872 SuccBB = TInst->getSuccessor(I);
1874 // Checks for region exit block and self-loops in BB.
1875 if (SuccBB == RExit || SuccBB == CurrBB)
1876 continue;
1878 // WHITE indicates an unvisited BB in DFS walk.
1879 if (BBColorMap[SuccBB] == WHITE) {
1880 // Push the current BB and the index of the next child to be visited.
1881 DFSStack.push(std::make_pair(CurrBB, I + 1));
1882 // Push the next BB to be processed.
1883 DFSStack.push(std::make_pair(SuccBB, 0));
1884 // First time the BB is being processed.
1885 BBColorMap[SuccBB] = GREY;
1886 break;
1887 } else if (BBColorMap[SuccBB] == GREY) {
1888 // GREY indicates a loop in the control flow.
1889 // If the destination dominates the source, it is a natural loop
1890 // else, an irreducible control flow in the region is detected.
1891 if (!DT.dominates(SuccBB, CurrBB)) {
1892 // Get debug info of instruction which causes irregular control flow.
1893 DbgLoc = TInst->getDebugLoc();
1894 return false;
1899 // If all children of current BB have been processed,
1900 // then mark that BB as fully processed.
1901 if (AdjacentBlockIndex == NSucc)
1902 BBColorMap[CurrBB] = BLACK;
1905 return true;
1908 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1909 bool OnlyProfitable) {
1910 if (!OnlyProfitable) {
1911 NumLoopsInScop += Stats.NumLoops;
1912 MaxNumLoopsInScop =
1913 std::max(MaxNumLoopsInScop.getValue(), (uint64_t)Stats.NumLoops);
1914 if (Stats.MaxDepth == 0)
1915 NumScopsDepthZero++;
1916 else if (Stats.MaxDepth == 1)
1917 NumScopsDepthOne++;
1918 else if (Stats.MaxDepth == 2)
1919 NumScopsDepthTwo++;
1920 else if (Stats.MaxDepth == 3)
1921 NumScopsDepthThree++;
1922 else if (Stats.MaxDepth == 4)
1923 NumScopsDepthFour++;
1924 else if (Stats.MaxDepth == 5)
1925 NumScopsDepthFive++;
1926 else
1927 NumScopsDepthLarger++;
1928 } else {
1929 NumLoopsInProfScop += Stats.NumLoops;
1930 MaxNumLoopsInProfScop =
1931 std::max(MaxNumLoopsInProfScop.getValue(), (uint64_t)Stats.NumLoops);
1932 if (Stats.MaxDepth == 0)
1933 NumProfScopsDepthZero++;
1934 else if (Stats.MaxDepth == 1)
1935 NumProfScopsDepthOne++;
1936 else if (Stats.MaxDepth == 2)
1937 NumProfScopsDepthTwo++;
1938 else if (Stats.MaxDepth == 3)
1939 NumProfScopsDepthThree++;
1940 else if (Stats.MaxDepth == 4)
1941 NumProfScopsDepthFour++;
1942 else if (Stats.MaxDepth == 5)
1943 NumProfScopsDepthFive++;
1944 else
1945 NumProfScopsDepthLarger++;
1949 ScopDetection::DetectionContext *
1950 ScopDetection::getDetectionContext(const Region *R) const {
1951 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
1952 if (DCMIt == DetectionContextMap.end())
1953 return nullptr;
1954 return DCMIt->second.get();
1957 const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1958 const DetectionContext *DC = getDetectionContext(R);
1959 return DC ? &DC->Log : nullptr;
1962 void ScopDetection::verifyRegion(const Region &R) {
1963 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1965 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
1966 isValidRegion(Context);
1969 void ScopDetection::verifyAnalysis() {
1970 if (!VerifyScops)
1971 return;
1973 for (const Region *R : ValidRegions)
1974 verifyRegion(*R);
1977 bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
1978 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1979 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1980 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1981 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1982 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1983 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1985 Result = std::make_unique<ScopDetection>(DT, SE, LI, RI, AA, ORE);
1986 Result->detect(F);
1987 return false;
1990 void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1991 AU.addRequired<LoopInfoWrapperPass>();
1992 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1993 AU.addRequired<DominatorTreeWrapperPass>();
1994 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1995 // We also need AA and RegionInfo when we are verifying analysis.
1996 AU.addRequiredTransitive<AAResultsWrapperPass>();
1997 AU.addRequiredTransitive<RegionInfoPass>();
1998 AU.setPreservesAll();
2001 void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
2002 for (const Region *R : Result->ValidRegions)
2003 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
2005 OS << "\n";
2008 ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
2009 // Disable runtime alias checks if we ignore aliasing all together.
2010 if (IgnoreAliasing)
2011 PollyUseRuntimeAliasChecks = false;
2014 ScopAnalysis::ScopAnalysis() {
2015 // Disable runtime alias checks if we ignore aliasing all together.
2016 if (IgnoreAliasing)
2017 PollyUseRuntimeAliasChecks = false;
2020 void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
2022 char ScopDetectionWrapperPass::ID;
2024 AnalysisKey ScopAnalysis::Key;
2026 ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
2027 auto &LI = FAM.getResult<LoopAnalysis>(F);
2028 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
2029 auto &AA = FAM.getResult<AAManager>(F);
2030 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
2031 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2032 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2034 ScopDetection Result(DT, SE, LI, RI, AA, ORE);
2035 Result.detect(F);
2036 return Result;
2039 PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
2040 FunctionAnalysisManager &FAM) {
2041 OS << "Detected Scops in Function " << F.getName() << "\n";
2042 auto &SD = FAM.getResult<ScopAnalysis>(F);
2043 for (const Region *R : SD.ValidRegions)
2044 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
2046 OS << "\n";
2047 return PreservedAnalyses::all();
2050 Pass *polly::createScopDetectionWrapperPassPass() {
2051 return new ScopDetectionWrapperPass();
2054 INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
2055 "Polly - Detect static control parts (SCoPs)", false,
2056 false);
2057 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
2058 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2059 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2060 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2061 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2062 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
2063 INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
2064 "Polly - Detect static control parts (SCoPs)", false, false)
2066 //===----------------------------------------------------------------------===//
2068 namespace {
2069 /// Print result from ScopDetectionWrapperPass.
2070 class ScopDetectionPrinterLegacyPass final : public FunctionPass {
2071 public:
2072 static char ID;
2074 ScopDetectionPrinterLegacyPass() : ScopDetectionPrinterLegacyPass(outs()) {}
2076 explicit ScopDetectionPrinterLegacyPass(llvm::raw_ostream &OS)
2077 : FunctionPass(ID), OS(OS) {}
2079 bool runOnFunction(Function &F) override {
2080 ScopDetectionWrapperPass &P = getAnalysis<ScopDetectionWrapperPass>();
2082 OS << "Printing analysis '" << P.getPassName() << "' for function '"
2083 << F.getName() << "':\n";
2084 P.print(OS);
2086 return false;
2089 void getAnalysisUsage(AnalysisUsage &AU) const override {
2090 FunctionPass::getAnalysisUsage(AU);
2091 AU.addRequired<ScopDetectionWrapperPass>();
2092 AU.setPreservesAll();
2095 private:
2096 llvm::raw_ostream &OS;
2099 char ScopDetectionPrinterLegacyPass::ID = 0;
2100 } // namespace
2102 Pass *polly::createScopDetectionPrinterLegacyPass(raw_ostream &OS) {
2103 return new ScopDetectionPrinterLegacyPass(OS);
2106 INITIALIZE_PASS_BEGIN(ScopDetectionPrinterLegacyPass, "polly-print-detect",
2107 "Polly - Print static control parts (SCoPs)", false,
2108 false);
2109 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
2110 INITIALIZE_PASS_END(ScopDetectionPrinterLegacyPass, "polly-print-detect",
2111 "Polly - Print static control parts (SCoPs)", false, false)