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