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) const {
720   Value *BaseValue = BasePointer->getValue();
721   Region &CurRegion = Context.CurRegion;
722   for (const SCEV *DelinearizedSize : Sizes) {
723     if (!isAffine(DelinearizedSize, Context, nullptr)) {
724       Sizes.clear();
725       break;
726     }
727     if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
728       auto *V = dyn_cast<Value>(Unknown->getValue());
729       if (auto *Load = dyn_cast<LoadInst>(V)) {
730         if (Context.CurRegion.contains(Load) &&
731             isHoistableLoad(Load, CurRegion, *LI, *SE))
732           Context.RequiredILS.insert(Load);
733         continue;
734       }
735     }
736     if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
737       return invalid<ReportNonAffineAccess>(
738           Context, /*Assert=*/true, DelinearizedSize,
739           Context.Accesses[BasePointer].front().first, BaseValue);
740   }
741 
742   // No array shape derived.
743   if (Sizes.empty()) {
744     if (AllowNonAffine)
745       return true;
746 
747     for (const auto &Pair : Context.Accesses[BasePointer]) {
748       const Instruction *Insn = Pair.first;
749       const SCEV *AF = Pair.second;
750 
751       if (!isAffine(AF, Context, BaseValue)) {
752         invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
753                                        BaseValue);
754         if (!KeepGoing)
755           return false;
756       }
757     }
758     return false;
759   }
760   return true;
761 }
762 
763 // We first store the resulting memory accesses in TempMemoryAccesses. Only
764 // if the access functions for all memory accesses have been successfully
765 // delinearized we continue. Otherwise, we either report a failure or, if
766 // non-affine accesses are allowed, we drop the information. In case the
767 // information is dropped the memory accesses need to be overapproximated
768 // when translated to a polyhedral representation.
769 bool ScopDetection::computeAccessFunctions(
770     DetectionContext &Context, const SCEVUnknown *BasePointer,
771     std::shared_ptr<ArrayShape> Shape) const {
772   Value *BaseValue = BasePointer->getValue();
773   bool BasePtrHasNonAffine = false;
774   MapInsnToMemAcc TempMemoryAccesses;
775   for (const auto &Pair : Context.Accesses[BasePointer]) {
776     const Instruction *Insn = Pair.first;
777     auto *AF = Pair.second;
778     AF = SCEVRemoveMax::remove(*SE, AF);
779     bool IsNonAffine = false;
780     TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
781     MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
782 
783     if (!AF) {
784       if (isAffine(Pair.second, Context, BaseValue))
785         Acc->DelinearizedSubscripts.push_back(Pair.second);
786       else
787         IsNonAffine = true;
788     } else {
789       SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
790                                  Shape->DelinearizedSizes);
791       if (Acc->DelinearizedSubscripts.size() == 0)
792         IsNonAffine = true;
793       for (const SCEV *S : Acc->DelinearizedSubscripts)
794         if (!isAffine(S, Context, BaseValue))
795           IsNonAffine = true;
796     }
797 
798     // (Possibly) report non affine access
799     if (IsNonAffine) {
800       BasePtrHasNonAffine = true;
801       if (!AllowNonAffine)
802         invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
803                                        Insn, BaseValue);
804       if (!KeepGoing && !AllowNonAffine)
805         return false;
806     }
807   }
808 
809   if (!BasePtrHasNonAffine)
810     Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
811                                 TempMemoryAccesses.end());
812 
813   return true;
814 }
815 
816 bool ScopDetection::hasBaseAffineAccesses(
817     DetectionContext &Context, const SCEVUnknown *BasePointer) 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     return false;
827 
828   return computeAccessFunctions(Context, BasePointer, Shape);
829 }
830 
831 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
832   // TODO: If we have an unknown access and other non-affine accesses we do
833   //       not try to delinearize them for now.
834   if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
835     return AllowNonAffine;
836 
837   for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
838     if (!hasBaseAffineAccesses(Context, BasePointer)) {
839       if (KeepGoing)
840         continue;
841       else
842         return false;
843     }
844   return true;
845 }
846 
847 bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
848                                   const SCEVUnknown *BP,
849                                   DetectionContext &Context) const {
850 
851   if (!BP)
852     return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
853 
854   auto *BV = BP->getValue();
855   if (isa<UndefValue>(BV))
856     return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
857 
858   // FIXME: Think about allowing IntToPtrInst
859   if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
860     return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
861 
862   // Check that the base address of the access is invariant in the current
863   // region.
864   if (!isInvariant(*BV, Context.CurRegion))
865     return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
866 
867   AF = SE->getMinusSCEV(AF, BP);
868 
869   const SCEV *Size;
870   if (!isa<MemIntrinsic>(Inst)) {
871     Size = SE->getElementSize(Inst);
872   } else {
873     auto *SizeTy =
874         SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
875     Size = SE->getConstant(SizeTy, 8);
876   }
877 
878   if (Context.ElementSize[BP]) {
879     if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
880       return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
881                                                       Inst, BV);
882 
883     Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
884   } else {
885     Context.ElementSize[BP] = Size;
886   }
887 
888   bool IsVariantInNonAffineLoop = false;
889   SetVector<const Loop *> Loops;
890   findLoops(AF, Loops);
891   for (const Loop *L : Loops)
892     if (Context.BoxedLoopsSet.count(L))
893       IsVariantInNonAffineLoop = true;
894 
895   bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Context, BV);
896   // Do not try to delinearize memory intrinsics and force them to be affine.
897   if (isa<MemIntrinsic>(Inst) && !IsAffine) {
898     return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
899                                           BV);
900   } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
901     Context.Accesses[BP].push_back({Inst, AF});
902 
903     if (!IsAffine)
904       Context.NonAffineAccesses.insert(BP);
905   } else if (!AllowNonAffine && !IsAffine) {
906     return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
907                                           BV);
908   }
909 
910   if (IgnoreAliasing)
911     return true;
912 
913   // Check if the base pointer of the memory access does alias with
914   // any other pointer. This cannot be handled at the moment.
915   AAMDNodes AATags;
916   Inst->getAAMetadata(AATags);
917   AliasSet &AS = Context.AST.getAliasSetForPointer(
918       BP->getValue(), MemoryLocation::UnknownSize, AATags);
919 
920   if (!AS.isMustAlias()) {
921     if (PollyUseRuntimeAliasChecks) {
922       bool CanBuildRunTimeCheck = true;
923       // The run-time alias check places code that involves the base pointer at
924       // the beginning of the SCoP. This breaks if the base pointer is defined
925       // inside the scop. Hence, we can only create a run-time check if we are
926       // sure the base pointer is not an instruction defined inside the scop.
927       // However, we can ignore loads that will be hoisted.
928       for (const auto &Ptr : AS) {
929         Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
930         if (Inst && Context.CurRegion.contains(Inst)) {
931           auto *Load = dyn_cast<LoadInst>(Inst);
932           if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
933             Context.RequiredILS.insert(Load);
934             continue;
935           }
936 
937           CanBuildRunTimeCheck = false;
938           break;
939         }
940       }
941 
942       if (CanBuildRunTimeCheck)
943         return true;
944     }
945     return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
946   }
947 
948   return true;
949 }
950 
951 bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
952                                         DetectionContext &Context) const {
953   Value *Ptr = Inst.getPointerOperand();
954   Loop *L = LI->getLoopFor(Inst->getParent());
955   const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
956   const SCEVUnknown *BasePointer;
957 
958   BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
959 
960   return isValidAccess(Inst, AccessFunction, BasePointer, Context);
961 }
962 
963 bool ScopDetection::isValidInstruction(Instruction &Inst,
964                                        DetectionContext &Context) const {
965   for (auto &Op : Inst.operands()) {
966     auto *OpInst = dyn_cast<Instruction>(&Op);
967 
968     if (!OpInst)
969       continue;
970 
971     if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
972       return false;
973   }
974 
975   // We only check the call instruction but not invoke instruction.
976   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
977     if (isValidCallInst(*CI, Context))
978       return true;
979 
980     return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
981   }
982 
983   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
984     if (!isa<AllocaInst>(Inst))
985       return true;
986 
987     return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
988   }
989 
990   // Check the access function.
991   if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
992     Context.hasStores |= isa<StoreInst>(MemInst);
993     Context.hasLoads |= isa<LoadInst>(MemInst);
994     if (!MemInst.isSimple())
995       return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
996                                                   &Inst);
997 
998     return isValidMemoryAccess(MemInst, Context);
999   }
1000 
1001   // We do not know this instruction, therefore we assume it is invalid.
1002   return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
1003 }
1004 
1005 bool ScopDetection::canUseISLTripCount(Loop *L,
1006                                        DetectionContext &Context) const {
1007   // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1008   // need to overapproximate it as a boxed loop.
1009   SmallVector<BasicBlock *, 4> LoopControlBlocks;
1010   L->getLoopLatches(LoopControlBlocks);
1011   L->getExitingBlocks(LoopControlBlocks);
1012   for (BasicBlock *ControlBB : LoopControlBlocks) {
1013     if (!isValidCFG(*ControlBB, true, false, Context))
1014       return false;
1015   }
1016 
1017   // We can use ISL to compute the trip count of L.
1018   return true;
1019 }
1020 
1021 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
1022   if (canUseISLTripCount(L, Context))
1023     return true;
1024 
1025   if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
1026     Region *R = RI->getRegionFor(L->getHeader());
1027     while (R != &Context.CurRegion && !R->contains(L))
1028       R = R->getParent();
1029 
1030     if (addOverApproximatedRegion(R, Context))
1031       return true;
1032   }
1033 
1034   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
1035   return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
1036 }
1037 
1038 /// @brief Return the number of loops in @p L (incl. @p L) that have a trip
1039 ///        count that is not known to be less than MIN_LOOP_TRIP_COUNT.
1040 static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
1041   auto *TripCount = SE.getBackedgeTakenCount(L);
1042 
1043   int count = 1;
1044   if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1045     if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1046       if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1047         count -= 1;
1048 
1049   for (auto &SubLoop : *L)
1050     count += countBeneficialSubLoops(SubLoop, SE);
1051 
1052   return count;
1053 }
1054 
1055 int ScopDetection::countBeneficialLoops(Region *R) const {
1056   int LoopNum = 0;
1057 
1058   auto L = LI->getLoopFor(R->getEntry());
1059   L = L ? R->outermostLoopInRegion(L) : nullptr;
1060   L = L ? L->getParentLoop() : nullptr;
1061 
1062   auto SubLoops =
1063       L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1064 
1065   for (auto &SubLoop : SubLoops)
1066     if (R->contains(SubLoop))
1067       LoopNum += countBeneficialSubLoops(SubLoop, *SE);
1068 
1069   return LoopNum;
1070 }
1071 
1072 Region *ScopDetection::expandRegion(Region &R) {
1073   // Initial no valid region was found (greater than R)
1074   std::unique_ptr<Region> LastValidRegion;
1075   auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
1076 
1077   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1078 
1079   while (ExpandedRegion) {
1080     const auto &It = DetectionContextMap.insert(std::make_pair(
1081         ExpandedRegion.get(),
1082         DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1083     DetectionContext &Context = It.first->second;
1084     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
1085     // Only expand when we did not collect errors.
1086 
1087     if (!Context.Log.hasErrors()) {
1088       // If the exit is valid check all blocks
1089       //  - if true, a valid region was found => store it + keep expanding
1090       //  - if false, .tbd. => stop  (should this really end the loop?)
1091       if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1092         removeCachedResults(*ExpandedRegion);
1093         break;
1094       }
1095 
1096       // Store this region, because it is the greatest valid (encountered so
1097       // far).
1098       removeCachedResults(*LastValidRegion);
1099       LastValidRegion = std::move(ExpandedRegion);
1100 
1101       // Create and test the next greater region (if any)
1102       ExpandedRegion =
1103           std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
1104 
1105     } else {
1106       // Create and test the next greater region (if any)
1107       removeCachedResults(*ExpandedRegion);
1108       ExpandedRegion =
1109           std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
1110     }
1111   }
1112 
1113   DEBUG({
1114     if (LastValidRegion)
1115       dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1116     else
1117       dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1118   });
1119 
1120   return LastValidRegion.release();
1121 }
1122 static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
1123   for (const BasicBlock *BB : R.blocks())
1124     if (R.contains(LI->getLoopFor(BB)))
1125       return false;
1126 
1127   return true;
1128 }
1129 
1130 unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
1131   unsigned Count = 0;
1132   for (auto &SubRegion : R) {
1133     if (ValidRegions.count(SubRegion.get())) {
1134       removeCachedResults(*SubRegion.get());
1135       ++Count;
1136     } else
1137       Count += removeCachedResultsRecursively(*SubRegion);
1138   }
1139   return Count;
1140 }
1141 
1142 void ScopDetection::removeCachedResults(const Region &R) {
1143   ValidRegions.remove(&R);
1144   DetectionContextMap.erase(&R);
1145 }
1146 
1147 void ScopDetection::findScops(Region &R) {
1148   const auto &It = DetectionContextMap.insert(
1149       std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1150   DetectionContext &Context = It.first->second;
1151 
1152   bool RegionIsValid = false;
1153   if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
1154     removeCachedResults(R);
1155     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
1156   } else
1157     RegionIsValid = isValidRegion(Context);
1158 
1159   bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
1160 
1161   if (PollyTrackFailures && HasErrors)
1162     RejectLogs.insert(std::make_pair(&R, Context.Log));
1163 
1164   if (HasErrors) {
1165     removeCachedResults(R);
1166   } else {
1167     ++ValidRegion;
1168     ValidRegions.insert(&R);
1169     return;
1170   }
1171 
1172   for (auto &SubRegion : R)
1173     findScops(*SubRegion);
1174 
1175   // Try to expand regions.
1176   //
1177   // As the region tree normally only contains canonical regions, non canonical
1178   // regions that form a Scop are not found. Therefore, those non canonical
1179   // regions are checked by expanding the canonical ones.
1180 
1181   std::vector<Region *> ToExpand;
1182 
1183   for (auto &SubRegion : R)
1184     ToExpand.push_back(SubRegion.get());
1185 
1186   for (Region *CurrentRegion : ToExpand) {
1187     // Skip regions that had errors.
1188     bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1189     if (HadErrors)
1190       continue;
1191 
1192     // Skip invalid regions. Regions may become invalid, if they are element of
1193     // an already expanded region.
1194     if (!ValidRegions.count(CurrentRegion))
1195       continue;
1196 
1197     Region *ExpandedR = expandRegion(*CurrentRegion);
1198 
1199     if (!ExpandedR)
1200       continue;
1201 
1202     R.addSubRegion(ExpandedR, true);
1203     ValidRegions.insert(ExpandedR);
1204     removeCachedResults(*CurrentRegion);
1205 
1206     // Erase all (direct and indirect) children of ExpandedR from the valid
1207     // regions and update the number of valid regions.
1208     ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
1209   }
1210 }
1211 
1212 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
1213   Region &CurRegion = Context.CurRegion;
1214 
1215   for (const BasicBlock *BB : CurRegion.blocks()) {
1216     Loop *L = LI->getLoopFor(BB);
1217     if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
1218       return false;
1219   }
1220 
1221   for (BasicBlock *BB : CurRegion.blocks()) {
1222     bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1223 
1224     // Also check exception blocks (and possibly register them as non-affine
1225     // regions). Even though exception blocks are not modeled, we use them
1226     // to forward-propagate domain constraints during ScopInfo construction.
1227     if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1228       return false;
1229 
1230     if (IsErrorBlock)
1231       continue;
1232 
1233     for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
1234       if (!isValidInstruction(*I, Context) && !KeepGoing)
1235         return false;
1236   }
1237 
1238   if (!hasAffineMemoryAccesses(Context))
1239     return false;
1240 
1241   return true;
1242 }
1243 
1244 bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1245                                          int NumLoops) const {
1246   int InstCount = 0;
1247 
1248   for (auto *BB : Context.CurRegion.blocks())
1249     if (Context.CurRegion.contains(LI->getLoopFor(BB)))
1250       InstCount += BB->size();
1251 
1252   InstCount = InstCount / NumLoops;
1253 
1254   return InstCount >= ProfitabilityMinPerLoopInstructions;
1255 }
1256 
1257 bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1258   Region &CurRegion = Context.CurRegion;
1259 
1260   if (PollyProcessUnprofitable)
1261     return true;
1262 
1263   // We can probably not do a lot on scops that only write or only read
1264   // data.
1265   if (!Context.hasStores || !Context.hasLoads)
1266     return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1267 
1268   int NumLoops = countBeneficialLoops(&CurRegion);
1269   int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
1270 
1271   // Scops with at least two loops may allow either loop fusion or tiling and
1272   // are consequently interesting to look at.
1273   if (NumAffineLoops >= 2)
1274     return true;
1275 
1276   // Scops that contain a loop with a non-trivial amount of computation per
1277   // loop-iteration are interesting as we may be able to parallelize such
1278   // loops. Individual loops that have only a small amount of computation
1279   // per-iteration are performance-wise very fragile as any change to the
1280   // loop induction variables may affect performance. To not cause spurious
1281   // performance regressions, we do not consider such loops.
1282   if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1283     return true;
1284 
1285   return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1286 }
1287 
1288 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
1289   Region &CurRegion = Context.CurRegion;
1290 
1291   DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
1292 
1293   if (CurRegion.isTopLevelRegion()) {
1294     DEBUG(dbgs() << "Top level region is invalid\n");
1295     return false;
1296   }
1297 
1298   if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
1299     DEBUG({
1300       dbgs() << "Region entry does not match -polly-region-only";
1301       dbgs() << "\n";
1302     });
1303     return false;
1304   }
1305 
1306   // SCoP cannot contain the entry block of the function, because we need
1307   // to insert alloca instruction there when translate scalar to array.
1308   if (CurRegion.getEntry() ==
1309       &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1310     return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
1311 
1312   if (!allBlocksValid(Context))
1313     return false;
1314 
1315   DebugLoc DbgLoc;
1316   if (!isReducibleRegion(CurRegion, DbgLoc))
1317     return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1318                                             &CurRegion, DbgLoc);
1319 
1320   if (!isProfitableRegion(Context))
1321     return false;
1322 
1323   DEBUG(dbgs() << "OK\n");
1324   return true;
1325 }
1326 
1327 void ScopDetection::markFunctionAsInvalid(Function *F) const {
1328   F->addFnAttr(PollySkipFnAttr);
1329 }
1330 
1331 bool ScopDetection::isValidFunction(llvm::Function &F) {
1332   return !F.hasFnAttribute(PollySkipFnAttr);
1333 }
1334 
1335 void ScopDetection::printLocations(llvm::Function &F) {
1336   for (const Region *R : *this) {
1337     unsigned LineEntry, LineExit;
1338     std::string FileName;
1339 
1340     getDebugLocation(R, LineEntry, LineExit, FileName);
1341     DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1342     F.getContext().diagnose(Diagnostic);
1343   }
1344 }
1345 
1346 void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
1347   for (const Region *R : ValidRegions) {
1348     const Region *Parent = R->getParent();
1349     if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1350       emitRejectionRemarks(F, RejectLogs.at(Parent));
1351   }
1352 }
1353 
1354 void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1355                                                const Region *R) {
1356   for (const std::unique_ptr<Region> &Child : *R) {
1357     bool IsValid = DetectionContextMap.count(Child.get());
1358     if (IsValid)
1359       continue;
1360 
1361     bool IsLeaf = Child->begin() == Child->end();
1362     if (!IsLeaf)
1363       emitMissedRemarksForLeaves(F, Child.get());
1364     else {
1365       if (RejectLogs.count(Child.get())) {
1366         emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1367       }
1368     }
1369   }
1370 }
1371 
1372 bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1373   BasicBlock *REntry = R.getEntry();
1374   BasicBlock *RExit = R.getExit();
1375   // Map to match the color of a BasicBlock during the DFS walk.
1376   DenseMap<const BasicBlock *, Color> BBColorMap;
1377   // Stack keeping track of current BB and index of next child to be processed.
1378   std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1379 
1380   unsigned AdjacentBlockIndex = 0;
1381   BasicBlock *CurrBB, *SuccBB;
1382   CurrBB = REntry;
1383 
1384   // Initialize the map for all BB with WHITE color.
1385   for (auto *BB : R.blocks())
1386     BBColorMap[BB] = ScopDetection::WHITE;
1387 
1388   // Process the entry block of the Region.
1389   BBColorMap[CurrBB] = ScopDetection::GREY;
1390   DFSStack.push(std::make_pair(CurrBB, 0));
1391 
1392   while (!DFSStack.empty()) {
1393     // Get next BB on stack to be processed.
1394     CurrBB = DFSStack.top().first;
1395     AdjacentBlockIndex = DFSStack.top().second;
1396     DFSStack.pop();
1397 
1398     // Loop to iterate over the successors of current BB.
1399     const TerminatorInst *TInst = CurrBB->getTerminator();
1400     unsigned NSucc = TInst->getNumSuccessors();
1401     for (unsigned I = AdjacentBlockIndex; I < NSucc;
1402          ++I, ++AdjacentBlockIndex) {
1403       SuccBB = TInst->getSuccessor(I);
1404 
1405       // Checks for region exit block and self-loops in BB.
1406       if (SuccBB == RExit || SuccBB == CurrBB)
1407         continue;
1408 
1409       // WHITE indicates an unvisited BB in DFS walk.
1410       if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1411         // Push the current BB and the index of the next child to be visited.
1412         DFSStack.push(std::make_pair(CurrBB, I + 1));
1413         // Push the next BB to be processed.
1414         DFSStack.push(std::make_pair(SuccBB, 0));
1415         // First time the BB is being processed.
1416         BBColorMap[SuccBB] = ScopDetection::GREY;
1417         break;
1418       } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1419         // GREY indicates a loop in the control flow.
1420         // If the destination dominates the source, it is a natural loop
1421         // else, an irreducible control flow in the region is detected.
1422         if (!DT->dominates(SuccBB, CurrBB)) {
1423           // Get debug info of instruction which causes irregular control flow.
1424           DbgLoc = TInst->getDebugLoc();
1425           return false;
1426         }
1427       }
1428     }
1429 
1430     // If all children of current BB have been processed,
1431     // then mark that BB as fully processed.
1432     if (AdjacentBlockIndex == NSucc)
1433       BBColorMap[CurrBB] = ScopDetection::BLACK;
1434   }
1435 
1436   return true;
1437 }
1438 
1439 bool ScopDetection::runOnFunction(llvm::Function &F) {
1440   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1441   RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1442   if (!PollyProcessUnprofitable && LI->empty())
1443     return false;
1444 
1445   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1446   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1447   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1448   Region *TopRegion = RI->getTopLevelRegion();
1449 
1450   releaseMemory();
1451 
1452   if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
1453     return false;
1454 
1455   if (!isValidFunction(F))
1456     return false;
1457 
1458   findScops(*TopRegion);
1459 
1460   // Only makes sense when we tracked errors.
1461   if (PollyTrackFailures) {
1462     emitMissedRemarksForValidRegions(F);
1463     emitMissedRemarksForLeaves(F, TopRegion);
1464   }
1465 
1466   if (ReportLevel)
1467     printLocations(F);
1468 
1469   assert(ValidRegions.size() == DetectionContextMap.size() &&
1470          "Cached more results than valid regions");
1471   return false;
1472 }
1473 
1474 bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1475                                          const Region *ScopR) const {
1476   const DetectionContext *DC = getDetectionContext(ScopR);
1477   assert(DC && "ScopR is no valid region!");
1478   return DC->NonAffineSubRegionSet.count(SubR);
1479 }
1480 
1481 const ScopDetection::DetectionContext *
1482 ScopDetection::getDetectionContext(const Region *R) const {
1483   auto DCMIt = DetectionContextMap.find(R);
1484   if (DCMIt == DetectionContextMap.end())
1485     return nullptr;
1486   return &DCMIt->second;
1487 }
1488 
1489 const ScopDetection::BoxedLoopsSetTy *
1490 ScopDetection::getBoxedLoops(const Region *R) const {
1491   const DetectionContext *DC = getDetectionContext(R);
1492   assert(DC && "ScopR is no valid region!");
1493   return &DC->BoxedLoopsSet;
1494 }
1495 
1496 const MapInsnToMemAcc *
1497 ScopDetection::getInsnToMemAccMap(const Region *R) const {
1498   const DetectionContext *DC = getDetectionContext(R);
1499   assert(DC && "ScopR is no valid region!");
1500   return &DC->InsnToMemAcc;
1501 }
1502 
1503 const InvariantLoadsSetTy *
1504 ScopDetection::getRequiredInvariantLoads(const Region *R) const {
1505   const DetectionContext *DC = getDetectionContext(R);
1506   assert(DC && "ScopR is no valid region!");
1507   return &DC->RequiredILS;
1508 }
1509 
1510 void polly::ScopDetection::verifyRegion(const Region &R) const {
1511   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1512 
1513   DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
1514   isValidRegion(Context);
1515 }
1516 
1517 void polly::ScopDetection::verifyAnalysis() const {
1518   if (!VerifyScops)
1519     return;
1520 
1521   for (const Region *R : ValidRegions)
1522     verifyRegion(*R);
1523 }
1524 
1525 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
1526   AU.addRequired<LoopInfoWrapperPass>();
1527   AU.addRequired<ScalarEvolutionWrapperPass>();
1528   AU.addRequired<DominatorTreeWrapperPass>();
1529   // We also need AA and RegionInfo when we are verifying analysis.
1530   AU.addRequiredTransitive<AAResultsWrapperPass>();
1531   AU.addRequiredTransitive<RegionInfoPass>();
1532   AU.setPreservesAll();
1533 }
1534 
1535 void ScopDetection::print(raw_ostream &OS, const Module *) const {
1536   for (const Region *R : ValidRegions)
1537     OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1538 
1539   OS << "\n";
1540 }
1541 
1542 void ScopDetection::releaseMemory() {
1543   RejectLogs.clear();
1544   ValidRegions.clear();
1545   DetectionContextMap.clear();
1546 
1547   // Do not clear the invalid function set.
1548 }
1549 
1550 char ScopDetection::ID = 0;
1551 
1552 Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1553 
1554 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1555                       "Polly - Detect static control parts (SCoPs)", false,
1556                       false);
1557 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
1558 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1559 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1560 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1561 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1562 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1563                     "Polly - Detect static control parts (SCoPs)", false, false)
1564