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