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