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