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