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