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