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 // Only function calls and intrinsics that do not have side effects are allowed
38 // (readnone).
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/CodeGen/BlockGenerators.h"
48 #include "polly/LinkAllPasses.h"
49 #include "polly/Options.h"
50 #include "polly/ScopDetectionDiagnostic.h"
51 #include "polly/ScopDetection.h"
52 #include "polly/Support/SCEVValidator.h"
53 #include "polly/Support/ScopHelper.h"
54 #include "polly/CodeGen/CodeGeneration.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/LoopInfo.h"
58 #include "llvm/Analysis/PostDominators.h"
59 #include "llvm/Analysis/RegionIterator.h"
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
62 #include "llvm/IR/DebugInfo.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/DiagnosticInfo.h"
65 #include "llvm/IR/DiagnosticPrinter.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/Support/Debug.h"
68 #include <set>
69 
70 using namespace llvm;
71 using namespace polly;
72 
73 #define DEBUG_TYPE "polly-detect"
74 
75 static cl::opt<bool>
76     DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
77                             cl::desc("Detect scops in functions without loops"),
78                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
79                             cl::cat(PollyCategory));
80 
81 static cl::opt<bool>
82     DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
83                               cl::desc("Detect scops in regions without loops"),
84                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
85                               cl::cat(PollyCategory));
86 
87 static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
88                                         cl::desc("Detect unprofitable scops"),
89                                         cl::Hidden, cl::init(false),
90                                         cl::ZeroOrMore, 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::PollyUseRuntimeAliasChecks;
112 static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
113     "polly-use-runtime-alias-checks",
114     cl::desc("Use runtime alias checks to resolve possible aliasing."),
115     cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
116     cl::init(true), cl::cat(PollyCategory));
117 
118 static cl::opt<bool>
119     ReportLevel("polly-report",
120                 cl::desc("Print information about the activities of Polly"),
121                 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
122 
123 static cl::opt<bool>
124     AllowNonAffine("polly-allow-nonaffine",
125                    cl::desc("Allow non affine access functions in arrays"),
126                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
127                    cl::cat(PollyCategory));
128 
129 static cl::opt<bool> AllowNonAffineSubRegions(
130     "polly-allow-nonaffine-branches",
131     cl::desc("Allow non affine conditions for branches"), cl::Hidden,
132     cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
133 
134 static cl::opt<bool>
135     AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
136                            cl::desc("Allow non affine conditions for loops"),
137                            cl::Hidden, cl::init(false), cl::ZeroOrMore,
138                            cl::cat(PollyCategory));
139 
140 static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
141                                    cl::desc("Allow unsigned expressions"),
142                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
143                                    cl::cat(PollyCategory));
144 
145 static cl::opt<bool, true>
146     TrackFailures("polly-detect-track-failures",
147                   cl::desc("Track failure strings in detecting scop regions"),
148                   cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
149                   cl::init(true), cl::cat(PollyCategory));
150 
151 static cl::opt<bool> KeepGoing("polly-detect-keep-going",
152                                cl::desc("Do not fail on the first error."),
153                                cl::Hidden, cl::ZeroOrMore, cl::init(false),
154                                cl::cat(PollyCategory));
155 
156 static cl::opt<bool, true>
157     PollyDelinearizeX("polly-delinearize",
158                       cl::desc("Delinearize array access functions"),
159                       cl::location(PollyDelinearize), cl::Hidden,
160                       cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
161 
162 static cl::opt<bool>
163     VerifyScops("polly-detect-verify",
164                 cl::desc("Verify the detected SCoPs after each transformation"),
165                 cl::Hidden, cl::init(false), cl::ZeroOrMore,
166                 cl::cat(PollyCategory));
167 
168 static cl::opt<bool, true> XPollyModelPHINodes(
169     "polly-model-phi-nodes",
170     cl::desc("Allow PHI nodes in the input [Unsafe with code-generation!]."),
171     cl::location(PollyModelPHINodes), cl::Hidden, cl::ZeroOrMore,
172     cl::init(false), cl::cat(PollyCategory));
173 
174 bool polly::PollyModelPHINodes = false;
175 bool polly::PollyTrackFailures = false;
176 bool polly::PollyDelinearize = false;
177 StringRef polly::PollySkipFnAttr = "polly.skip.fn";
178 
179 //===----------------------------------------------------------------------===//
180 // Statistics.
181 
182 STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
183 
184 class DiagnosticScopFound : public DiagnosticInfo {
185 private:
186   static int PluginDiagnosticKind;
187 
188   Function &F;
189   std::string FileName;
190   unsigned EntryLine, ExitLine;
191 
192 public:
193   DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
194                       unsigned ExitLine)
195       : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
196         EntryLine(EntryLine), ExitLine(ExitLine) {}
197 
198   virtual void print(DiagnosticPrinter &DP) const;
199 
200   static bool classof(const DiagnosticInfo *DI) {
201     return DI->getKind() == PluginDiagnosticKind;
202   }
203 };
204 
205 int DiagnosticScopFound::PluginDiagnosticKind = 10;
206 
207 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
208   DP << "Polly detected an optimizable loop region (scop) in function '" << F
209      << "'\n";
210 
211   if (FileName.empty()) {
212     DP << "Scop location is unknown. Compile with debug info "
213           "(-g) to get more precise information. ";
214     return;
215   }
216 
217   DP << FileName << ":" << EntryLine << ": Start of scop\n";
218   DP << FileName << ":" << ExitLine << ": End of scop";
219 }
220 
221 //===----------------------------------------------------------------------===//
222 // ScopDetection.
223 
224 ScopDetection::ScopDetection() : FunctionPass(ID) {
225   if (!PollyUseRuntimeAliasChecks)
226     return;
227 
228   // Disable runtime alias checks if we ignore aliasing all together.
229   if (IgnoreAliasing) {
230     PollyUseRuntimeAliasChecks = false;
231     return;
232   }
233 
234   if (AllowNonAffine) {
235     DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
236                     "accesses are enabled.\n");
237     PollyUseRuntimeAliasChecks = false;
238   }
239 }
240 
241 template <class RR, typename... Args>
242 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
243                                    Args &&... Arguments) const {
244 
245   if (!Context.Verifying) {
246     RejectLog &Log = Context.Log;
247     std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
248 
249     if (PollyTrackFailures)
250       Log.report(RejectReason);
251 
252     DEBUG(dbgs() << RejectReason->getMessage());
253     DEBUG(dbgs() << "\n");
254   } else {
255     assert(!Assert && "Verification of detected scop failed");
256   }
257 
258   return false;
259 }
260 
261 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
262   if (!ValidRegions.count(&R))
263     return false;
264 
265   if (Verify) {
266     BoxedLoopsSetTy DummyBoxedLoopsSet;
267     NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
268     DetectionContext Context(const_cast<Region &>(R), *AA,
269                              DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
270                              false /*verifying*/);
271     return isValidRegion(Context);
272   }
273 
274   return true;
275 }
276 
277 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
278   if (!RejectLogs.count(R))
279     return "";
280 
281   // Get the first error we found. Even in keep-going mode, this is the first
282   // reason that caused the candidate to be rejected.
283   RejectLog Errors = RejectLogs.at(R);
284 
285   // This can happen when we marked a region invalid, but didn't track
286   // an error for it.
287   if (Errors.size() == 0)
288     return "";
289 
290   RejectReasonPtr RR = *Errors.begin();
291   return RR->getMessage();
292 }
293 
294 bool ScopDetection::addOverApproximatedRegion(Region *AR,
295                                               DetectionContext &Context) const {
296 
297   // If we already know about Ar we can exit.
298   if (!Context.NonAffineSubRegionSet.insert(AR))
299     return true;
300 
301   // All loops in the region have to be overapproximated too if there
302   // are accesses that depend on the iteration count.
303   for (BasicBlock *BB : AR->blocks()) {
304     Loop *L = LI->getLoopFor(BB);
305     if (AR->contains(L))
306       Context.BoxedLoopsSet.insert(L);
307   }
308 
309   return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
310 }
311 
312 bool ScopDetection::isValidCFG(BasicBlock &BB,
313                                DetectionContext &Context) const {
314   Region &CurRegion = Context.CurRegion;
315 
316   TerminatorInst *TI = BB.getTerminator();
317 
318   // Return instructions are only valid if the region is the top level region.
319   if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
320     return true;
321 
322   BranchInst *Br = dyn_cast<BranchInst>(TI);
323 
324   if (!Br)
325     return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
326 
327   if (Br->isUnconditional())
328     return true;
329 
330   Value *Condition = Br->getCondition();
331 
332   // UndefValue is not allowed as condition.
333   if (isa<UndefValue>(Condition))
334     return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
335 
336   // Only Constant and ICmpInst are allowed as condition.
337   if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
338     if (!AllowNonAffineSubRegions ||
339         !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
340       return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
341   }
342 
343   // Allow perfectly nested conditions.
344   assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
345 
346   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
347     // Unsigned comparisons are not allowed. They trigger overflow problems
348     // in the code generation.
349     //
350     // TODO: This is not sufficient and just hides bugs. However it does pretty
351     // well.
352     if (ICmp->isUnsigned() && !AllowUnsigned)
353       return false;
354 
355     // Are both operands of the ICmp affine?
356     if (isa<UndefValue>(ICmp->getOperand(0)) ||
357         isa<UndefValue>(ICmp->getOperand(1)))
358       return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
359 
360     Loop *L = LI->getLoopFor(ICmp->getParent());
361     const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
362     const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
363 
364     if (!isAffineExpr(&CurRegion, LHS, *SE) ||
365         !isAffineExpr(&CurRegion, RHS, *SE)) {
366       if (!AllowNonAffineSubRegions ||
367           !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
368         return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
369                                            RHS, ICmp);
370     }
371   }
372 
373   // Allow loop exit conditions.
374   Loop *L = LI->getLoopFor(&BB);
375   if (L && L->getExitingBlock() == &BB)
376     return true;
377 
378   // Allow perfectly nested conditions.
379   Region *R = RI->getRegionFor(&BB);
380   if (R->getEntry() != &BB)
381     return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
382 
383   return true;
384 }
385 
386 bool ScopDetection::isValidCallInst(CallInst &CI) {
387   if (CI.doesNotReturn())
388     return false;
389 
390   if (CI.doesNotAccessMemory())
391     return true;
392 
393   Function *CalledFunction = CI.getCalledFunction();
394 
395   // Indirect calls are not supported.
396   if (CalledFunction == 0)
397     return false;
398 
399   // Check if we can handle the intrinsic call.
400   if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
401     switch (IT->getIntrinsicID()) {
402     // Lifetime markers are supported/ignored.
403     case llvm::Intrinsic::lifetime_start:
404     case llvm::Intrinsic::lifetime_end:
405     // Invariant markers are supported/ignored.
406     case llvm::Intrinsic::invariant_start:
407     case llvm::Intrinsic::invariant_end:
408     // Some misc annotations are supported/ignored.
409     case llvm::Intrinsic::var_annotation:
410     case llvm::Intrinsic::ptr_annotation:
411     case llvm::Intrinsic::annotation:
412     case llvm::Intrinsic::donothing:
413     case llvm::Intrinsic::assume:
414     case llvm::Intrinsic::expect:
415       return true;
416     default:
417       // Other intrinsics which may access the memory are not yet supported.
418       break;
419     }
420   }
421 
422   return false;
423 }
424 
425 bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
426   // A reference to function argument or constant value is invariant.
427   if (isa<Argument>(Val) || isa<Constant>(Val))
428     return true;
429 
430   const Instruction *I = dyn_cast<Instruction>(&Val);
431   if (!I)
432     return false;
433 
434   if (!Reg.contains(I))
435     return true;
436 
437   if (I->mayHaveSideEffects())
438     return false;
439 
440   // When Val is a Phi node, it is likely not invariant. We do not check whether
441   // Phi nodes are actually invariant, we assume that Phi nodes are usually not
442   // invariant. Recursively checking the operators of Phi nodes would lead to
443   // infinite recursion.
444   if (isa<PHINode>(*I))
445     return false;
446 
447   for (const Use &Operand : I->operands())
448     if (!isInvariant(*Operand, Reg))
449       return false;
450 
451   // When the instruction is a load instruction, check that no write to memory
452   // in the region aliases with the load.
453   if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
454     AliasAnalysis::Location Loc = AA->getLocation(LI);
455 
456     // Check if any basic block in the region can modify the location pointed to
457     // by 'Loc'.  If so, 'Val' is (likely) not invariant in the region.
458     for (const BasicBlock *BB : Reg.blocks())
459       if (AA->canBasicBlockModify(*BB, Loc))
460         return false;
461   }
462 
463   return true;
464 }
465 
466 MapInsnToMemAcc InsnToMemAcc;
467 
468 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
469   Region &CurRegion = Context.CurRegion;
470 
471   for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
472     Value *BaseValue = BasePointer->getValue();
473     ArrayShape *Shape = new ArrayShape(BasePointer);
474     bool BasePtrHasNonAffine = false;
475 
476     // First step: collect parametric terms in all array references.
477     SmallVector<const SCEV *, 4> Terms;
478     for (const auto &Pair : Context.Accesses[BasePointer]) {
479       const SCEVAddRecExpr *AccessFunction =
480           dyn_cast<SCEVAddRecExpr>(Pair.second);
481 
482       if (AccessFunction)
483         AccessFunction->collectParametricTerms(*SE, Terms);
484     }
485 
486     // Second step: find array shape.
487     SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
488                             Context.ElementSize[BasePointer]);
489 
490     // No array shape derived.
491     if (Shape->DelinearizedSizes.empty()) {
492       if (AllowNonAffine)
493         continue;
494 
495       for (const auto &Pair : Context.Accesses[BasePointer]) {
496         const Instruction *Insn = Pair.first;
497         const SCEV *AF = Pair.second;
498 
499         if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
500           invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
501                                          BaseValue);
502           if (!KeepGoing)
503             return false;
504         }
505       }
506       continue;
507     }
508 
509     // Third step: compute the access functions for each subscript.
510     //
511     // We first store the resulting memory accesses in TempMemoryAccesses. Only
512     // if the access functions for all memory accesses have been successfully
513     // delinearized we continue. Otherwise, we either report a failure or, if
514     // non-affine accesses are allowed, we drop the information. In case the
515     // information is dropped the memory accesses need to be overapproximated
516     // when translated to a polyhedral representation.
517     MapInsnToMemAcc TempMemoryAccesses;
518     for (const auto &Pair : Context.Accesses[BasePointer]) {
519       const Instruction *Insn = Pair.first;
520       const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(Pair.second);
521       bool IsNonAffine = false;
522       MemAcc *Acc = new MemAcc(Insn, Shape);
523       TempMemoryAccesses.insert({Insn, Acc});
524 
525       if (!AF) {
526         if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
527           Acc->DelinearizedSubscripts.push_back(Pair.second);
528         else
529           IsNonAffine = true;
530       } else {
531         AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
532                                    Shape->DelinearizedSizes);
533         if (Acc->DelinearizedSubscripts.size() == 0)
534           IsNonAffine = true;
535         for (const SCEV *S : Acc->DelinearizedSubscripts)
536           if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
537             IsNonAffine = true;
538       }
539 
540       // (Possibly) report non affine access
541       if (IsNonAffine) {
542         BasePtrHasNonAffine = true;
543         if (!AllowNonAffine)
544           invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
545                                          Insn, BaseValue);
546         if (!KeepGoing && !AllowNonAffine)
547           return false;
548       }
549     }
550 
551     if (!BasePtrHasNonAffine)
552       InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
553   }
554   return true;
555 }
556 
557 bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
558                                         DetectionContext &Context) const {
559   Region &CurRegion = Context.CurRegion;
560 
561   Value *Ptr = getPointerOperand(Inst);
562   Loop *L = LI->getLoopFor(Inst.getParent());
563   const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
564   const SCEVUnknown *BasePointer;
565   Value *BaseValue;
566 
567   BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
568 
569   if (!BasePointer)
570     return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
571 
572   BaseValue = BasePointer->getValue();
573 
574   if (isa<UndefValue>(BaseValue))
575     return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
576 
577   // Check that the base address of the access is invariant in the current
578   // region.
579   if (!isInvariant(*BaseValue, CurRegion))
580     // Verification of this property is difficult as the independent blocks
581     // pass may introduce aliasing that we did not have when running the
582     // scop detection.
583     return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
584                                          &Inst);
585 
586   AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
587 
588   const SCEV *Size = SE->getElementSize(&Inst);
589   if (Context.ElementSize.count(BasePointer)) {
590     if (Context.ElementSize[BasePointer] != Size)
591       return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
592                                                       &Inst, BaseValue);
593   } else {
594     Context.ElementSize[BasePointer] = Size;
595   }
596 
597   bool isVariantInNonAffineLoop = false;
598   SetVector<const Loop *> Loops;
599   findLoops(AccessFunction, Loops);
600   for (const Loop *L : Loops)
601     if (Context.BoxedLoopsSet.count(L))
602       isVariantInNonAffineLoop = true;
603 
604   if (PollyDelinearize && !isVariantInNonAffineLoop) {
605     Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
606 
607     if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
608       Context.NonAffineAccesses.insert(BasePointer);
609   } else if (!AllowNonAffine) {
610     if (isVariantInNonAffineLoop ||
611         !isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
612       return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
613                                             AccessFunction, &Inst, BaseValue);
614   }
615 
616   // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
617   // created by IndependentBlocks Pass.
618   if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
619     return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
620 
621   if (IgnoreAliasing)
622     return true;
623 
624   // Check if the base pointer of the memory access does alias with
625   // any other pointer. This cannot be handled at the moment.
626   AAMDNodes AATags;
627   Inst.getAAMetadata(AATags);
628   AliasSet &AS = Context.AST.getAliasSetForPointer(
629       BaseValue, AliasAnalysis::UnknownSize, AATags);
630 
631   // INVALID triggers an assertion in verifying mode, if it detects that a
632   // SCoP was detected by SCoP detection and that this SCoP was invalidated by
633   // a pass that stated it would preserve the SCoPs. We disable this check as
634   // the independent blocks pass may create memory references which seem to
635   // alias, if -basicaa is not available. They actually do not, but as we can
636   // not proof this without -basicaa we would fail. We disable this check to
637   // not cause irrelevant verification failures.
638   if (!AS.isMustAlias()) {
639     if (PollyUseRuntimeAliasChecks) {
640       bool CanBuildRunTimeCheck = true;
641       // The run-time alias check places code that involves the base pointer at
642       // the beginning of the SCoP. This breaks if the base pointer is defined
643       // inside the scop. Hence, we can only create a run-time check if we are
644       // sure the base pointer is not an instruction defined inside the scop.
645       for (const auto &Ptr : AS) {
646         Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
647         if (Inst && CurRegion.contains(Inst)) {
648           CanBuildRunTimeCheck = false;
649           break;
650         }
651       }
652 
653       if (CanBuildRunTimeCheck)
654         return true;
655     }
656     return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
657   }
658 
659   return true;
660 }
661 
662 bool ScopDetection::isValidInstruction(Instruction &Inst,
663                                        DetectionContext &Context) const {
664   if (PHINode *PN = dyn_cast<PHINode>(&Inst))
665     if (!PollyModelPHINodes && !canSynthesize(PN, LI, SE, &Context.CurRegion)) {
666       return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true, &Inst);
667     }
668 
669   // We only check the call instruction but not invoke instruction.
670   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
671     if (isValidCallInst(*CI))
672       return true;
673 
674     return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
675   }
676 
677   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
678     if (!isa<AllocaInst>(Inst))
679       return true;
680 
681     return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
682   }
683 
684   // Check the access function.
685   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
686     Context.hasStores |= isa<StoreInst>(Inst);
687     Context.hasLoads |= isa<LoadInst>(Inst);
688     return isValidMemoryAccess(Inst, Context);
689   }
690 
691   // We do not know this instruction, therefore we assume it is invalid.
692   return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
693 }
694 
695 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
696   // Is the loop count affine?
697   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
698   if (isAffineExpr(&Context.CurRegion, LoopCount, *SE)) {
699     Context.hasAffineLoops = true;
700     return true;
701   }
702 
703   if (AllowNonAffineSubRegions) {
704     Region *R = RI->getRegionFor(L->getHeader());
705     if (R->contains(L))
706       if (addOverApproximatedRegion(R, Context))
707         return true;
708   }
709 
710   return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
711 }
712 
713 Region *ScopDetection::expandRegion(Region &R) {
714   // Initial no valid region was found (greater than R)
715   Region *LastValidRegion = nullptr;
716   Region *ExpandedRegion = R.getExpandedRegion();
717 
718   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
719 
720   while (ExpandedRegion) {
721     DetectionContext Context(
722         *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion],
723         BoxedLoopsMap[ExpandedRegion], false /* verifying */);
724     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
725     // Only expand when we did not collect errors.
726 
727     // Check the exit first (cheap)
728     if (isValidExit(Context) && !Context.Log.hasErrors()) {
729       // If the exit is valid check all blocks
730       //  - if true, a valid region was found => store it + keep expanding
731       //  - if false, .tbd. => stop  (should this really end the loop?)
732       if (!allBlocksValid(Context) || Context.Log.hasErrors())
733         break;
734 
735       if (Context.Log.hasErrors())
736         break;
737 
738       // Delete unnecessary regions (allocated by getExpandedRegion)
739       if (LastValidRegion)
740         delete LastValidRegion;
741 
742       // Store this region, because it is the greatest valid (encountered so
743       // far).
744       LastValidRegion = ExpandedRegion;
745 
746       // Create and test the next greater region (if any)
747       ExpandedRegion = ExpandedRegion->getExpandedRegion();
748 
749     } else {
750       // Create and test the next greater region (if any)
751       Region *TmpRegion = ExpandedRegion->getExpandedRegion();
752 
753       // Delete unnecessary regions (allocated by getExpandedRegion)
754       delete ExpandedRegion;
755 
756       ExpandedRegion = TmpRegion;
757     }
758   }
759 
760   DEBUG({
761     if (LastValidRegion)
762       dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
763     else
764       dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
765   });
766 
767   return LastValidRegion;
768 }
769 static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
770   for (const BasicBlock *BB : R.blocks())
771     if (R.contains(LI->getLoopFor(BB)))
772       return false;
773 
774   return true;
775 }
776 
777 // Remove all direct and indirect children of region R from the region set Regs,
778 // but do not recurse further if the first child has been found.
779 //
780 // Return the number of regions erased from Regs.
781 static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
782                                  const Region &R) {
783   unsigned Count = 0;
784   for (auto &SubRegion : R) {
785     if (Regs.count(SubRegion.get())) {
786       ++Count;
787       Regs.remove(SubRegion.get());
788     } else {
789       Count += eraseAllChildren(Regs, *SubRegion);
790     }
791   }
792   return Count;
793 }
794 
795 void ScopDetection::findScops(Region &R) {
796   DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
797                            false /*verifying*/);
798 
799   bool RegionIsValid = false;
800   if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
801     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
802   else
803     RegionIsValid = isValidRegion(Context);
804 
805   bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
806 
807   if (PollyTrackFailures && HasErrors)
808     RejectLogs.insert(std::make_pair(&R, Context.Log));
809 
810   if (!HasErrors) {
811     ++ValidRegion;
812     ValidRegions.insert(&R);
813     return;
814   }
815 
816   for (auto &SubRegion : R)
817     findScops(*SubRegion);
818 
819   // Try to expand regions.
820   //
821   // As the region tree normally only contains canonical regions, non canonical
822   // regions that form a Scop are not found. Therefore, those non canonical
823   // regions are checked by expanding the canonical ones.
824 
825   std::vector<Region *> ToExpand;
826 
827   for (auto &SubRegion : R)
828     ToExpand.push_back(SubRegion.get());
829 
830   for (Region *CurrentRegion : ToExpand) {
831     // Skip regions that had errors.
832     bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
833     if (HadErrors)
834       continue;
835 
836     // Skip invalid regions. Regions may become invalid, if they are element of
837     // an already expanded region.
838     if (!ValidRegions.count(CurrentRegion))
839       continue;
840 
841     Region *ExpandedR = expandRegion(*CurrentRegion);
842 
843     if (!ExpandedR)
844       continue;
845 
846     R.addSubRegion(ExpandedR, true);
847     ValidRegions.insert(ExpandedR);
848     ValidRegions.remove(CurrentRegion);
849 
850     // Erase all (direct and indirect) children of ExpandedR from the valid
851     // regions and update the number of valid regions.
852     ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
853   }
854 }
855 
856 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
857   Region &CurRegion = Context.CurRegion;
858 
859   for (const BasicBlock *BB : CurRegion.blocks()) {
860     Loop *L = LI->getLoopFor(BB);
861     if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
862       return false;
863   }
864 
865   for (BasicBlock *BB : CurRegion.blocks())
866     if (!isValidCFG(*BB, Context) && !KeepGoing)
867       return false;
868 
869   for (BasicBlock *BB : CurRegion.blocks())
870     for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
871       if (!isValidInstruction(*I, Context) && !KeepGoing)
872         return false;
873 
874   if (!hasAffineMemoryAccesses(Context))
875     return false;
876 
877   return true;
878 }
879 
880 bool ScopDetection::isValidExit(DetectionContext &Context) const {
881 
882   // PHI nodes are not allowed in the exit basic block.
883   if (BasicBlock *Exit = Context.CurRegion.getExit()) {
884     BasicBlock::iterator I = Exit->begin();
885     if (I != Exit->end() && isa<PHINode>(*I))
886       return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
887   }
888 
889   return true;
890 }
891 
892 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
893   Region &CurRegion = Context.CurRegion;
894 
895   DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
896 
897   if (CurRegion.isTopLevelRegion()) {
898     DEBUG(dbgs() << "Top level region is invalid\n");
899     return false;
900   }
901 
902   if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
903     DEBUG({
904       dbgs() << "Region entry does not match -polly-region-only";
905       dbgs() << "\n";
906     });
907     return false;
908   }
909 
910   if (!CurRegion.getEnteringBlock()) {
911     BasicBlock *entry = CurRegion.getEntry();
912     Loop *L = LI->getLoopFor(entry);
913 
914     if (L) {
915       if (!L->isLoopSimplifyForm())
916         return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
917 
918       for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
919            ++PI) {
920         // Region entering edges come from the same loop but outside the region
921         // are not allowed.
922         if (L->contains(*PI) && !CurRegion.contains(*PI))
923           return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
924       }
925     }
926   }
927 
928   // SCoP cannot contain the entry block of the function, because we need
929   // to insert alloca instruction there when translate scalar to array.
930   if (CurRegion.getEntry() ==
931       &(CurRegion.getEntry()->getParent()->getEntryBlock()))
932     return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
933 
934   if (!isValidExit(Context))
935     return false;
936 
937   if (!allBlocksValid(Context))
938     return false;
939 
940   // We can probably not do a lot on scops that only write or only read
941   // data.
942   if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
943     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
944 
945   // Check if there was at least one non-overapproximated loop in the region or
946   // we allow regions without loops.
947   if (!DetectRegionsWithoutLoops && !Context.hasAffineLoops)
948     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
949 
950   DEBUG(dbgs() << "OK\n");
951   return true;
952 }
953 
954 void ScopDetection::markFunctionAsInvalid(Function *F) const {
955   F->addFnAttr(PollySkipFnAttr);
956 }
957 
958 bool ScopDetection::isValidFunction(llvm::Function &F) {
959   return !F.hasFnAttribute(PollySkipFnAttr);
960 }
961 
962 void ScopDetection::printLocations(llvm::Function &F) {
963   for (const Region *R : *this) {
964     unsigned LineEntry, LineExit;
965     std::string FileName;
966 
967     getDebugLocation(R, LineEntry, LineExit, FileName);
968     DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
969     F.getContext().diagnose(Diagnostic);
970   }
971 }
972 
973 void ScopDetection::emitMissedRemarksForValidRegions(
974     const Function &F, const RegionSet &ValidRegions) {
975   for (const Region *R : ValidRegions) {
976     const Region *Parent = R->getParent();
977     if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
978       emitRejectionRemarks(F, RejectLogs.at(Parent));
979   }
980 }
981 
982 void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
983                                                const Region *R) {
984   for (const std::unique_ptr<Region> &Child : *R) {
985     bool IsValid = ValidRegions.count(Child.get());
986     if (IsValid)
987       continue;
988 
989     bool IsLeaf = Child->begin() == Child->end();
990     if (!IsLeaf)
991       emitMissedRemarksForLeaves(F, Child.get());
992     else {
993       if (RejectLogs.count(Child.get())) {
994         emitRejectionRemarks(F, RejectLogs.at(Child.get()));
995       }
996     }
997   }
998 }
999 
1000 bool ScopDetection::runOnFunction(llvm::Function &F) {
1001   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1002   RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1003   if (!DetectScopsWithoutLoops && LI->empty())
1004     return false;
1005 
1006   AA = &getAnalysis<AliasAnalysis>();
1007   SE = &getAnalysis<ScalarEvolution>();
1008   Region *TopRegion = RI->getTopLevelRegion();
1009 
1010   releaseMemory();
1011 
1012   if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
1013     return false;
1014 
1015   if (!isValidFunction(F))
1016     return false;
1017 
1018   findScops(*TopRegion);
1019 
1020   // Only makes sense when we tracked errors.
1021   if (PollyTrackFailures) {
1022     emitMissedRemarksForValidRegions(F, ValidRegions);
1023     emitMissedRemarksForLeaves(F, TopRegion);
1024   }
1025 
1026   for (const Region *R : ValidRegions)
1027     emitValidRemarks(F, R);
1028 
1029   if (ReportLevel)
1030     printLocations(F);
1031 
1032   return false;
1033 }
1034 
1035 bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1036                                          const Region *ScopR) const {
1037   return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1038 }
1039 
1040 const ScopDetection::BoxedLoopsSetTy *
1041 ScopDetection::getBoxedLoops(const Region *R) const {
1042   auto BLMIt = BoxedLoopsMap.find(R);
1043   if (BLMIt == BoxedLoopsMap.end())
1044     return nullptr;
1045   return &BLMIt->second;
1046 }
1047 
1048 void polly::ScopDetection::verifyRegion(const Region &R) const {
1049   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1050 
1051   BoxedLoopsSetTy DummyBoxedLoopsSet;
1052   NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1053   DetectionContext Context(const_cast<Region &>(R), *AA,
1054                            DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
1055                            true /*verifying*/);
1056   isValidRegion(Context);
1057 }
1058 
1059 void polly::ScopDetection::verifyAnalysis() const {
1060   if (!VerifyScops)
1061     return;
1062 
1063   for (const Region *R : ValidRegions)
1064     verifyRegion(*R);
1065 }
1066 
1067 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
1068   AU.addRequired<LoopInfoWrapperPass>();
1069   AU.addRequired<ScalarEvolution>();
1070   // We also need AA and RegionInfo when we are verifying analysis.
1071   AU.addRequiredTransitive<AliasAnalysis>();
1072   AU.addRequiredTransitive<RegionInfoPass>();
1073   AU.setPreservesAll();
1074 }
1075 
1076 void ScopDetection::print(raw_ostream &OS, const Module *) const {
1077   for (const Region *R : ValidRegions)
1078     OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1079 
1080   OS << "\n";
1081 }
1082 
1083 void ScopDetection::releaseMemory() {
1084   ValidRegions.clear();
1085   RejectLogs.clear();
1086   NonAffineSubRegionMap.clear();
1087   InsnToMemAcc.clear();
1088 
1089   // Do not clear the invalid function set.
1090 }
1091 
1092 char ScopDetection::ID = 0;
1093 
1094 Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1095 
1096 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1097                       "Polly - Detect static control parts (SCoPs)", false,
1098                       false);
1099 INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
1100 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1101 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1102 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1103 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1104                     "Polly - Detect static control parts (SCoPs)", false, false)
1105