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