blob: 06b16c44afd6e76e63a7d61f65896685622901ac [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- 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
Tobias Grosserecfe21b2013-03-20 18:03:18 +000047#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Andreas Simbuerger01a37a02014-04-02 11:54:01 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000053#include "polly/Support/ScopHelper.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000063#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000064#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000065#include <set>
66
Tobias Grosser75805372011-04-29 06:27:02 +000067using namespace llvm;
68using namespace polly;
69
Chandler Carruth95fef942014-04-22 03:30:19 +000070#define DEBUG_TYPE "polly-detect"
71
Sebastian Pop8fe6d112013-05-30 17:47:32 +000072static cl::opt<bool>
73DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
74 cl::desc("Detect scops in functions without loops"),
Tobias Grosser64e8e372014-03-13 23:37:43 +000075 cl::Hidden, cl::init(false), cl::ZeroOrMore,
76 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000077
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000078static cl::opt<bool>
79DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
80 cl::desc("Detect scops in regions without loops"),
Tobias Grosser64e8e372014-03-13 23:37:43 +000081 cl::Hidden, cl::init(false), cl::ZeroOrMore,
82 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000083
Tobias Grosser2ff87232011-10-23 11:17:06 +000084static cl::opt<std::string>
Tobias Grossera3ab27e2014-05-07 11:23:32 +000085OnlyFunction("polly-only-func",
86 cl::desc("Only run on functions that contain a certain string"),
87 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
Tobias Grosser637bd632013-05-07 07:31:10 +000088 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000089
Tobias Grosser4449e522014-01-27 14:24:53 +000090static cl::opt<std::string>
91OnlyRegion("polly-only-region",
92 cl::desc("Only run on certain regions (The provided identifier must "
93 "appear in the name of the region's entry block"),
94 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
95 cl::cat(PollyCategory));
96
Tobias Grosser60cd9322011-11-10 12:47:26 +000097static cl::opt<bool>
98IgnoreAliasing("polly-ignore-aliasing",
99 cl::desc("Ignore possible aliasing of the array bases"),
Tobias Grosser64e8e372014-03-13 23:37:43 +0000100 cl::Hidden, cl::init(false), cl::ZeroOrMore,
101 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000102
Tobias Grosser637bd632013-05-07 07:31:10 +0000103static cl::opt<bool>
104ReportLevel("polly-report",
105 cl::desc("Print information about the activities of Polly"),
Tobias Grosser64e8e372014-03-13 23:37:43 +0000106 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000107
108static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +0000109AllowNonAffine("polly-allow-nonaffine",
110 cl::desc("Allow non affine access functions in arrays"),
Tobias Grosser64e8e372014-03-13 23:37:43 +0000111 cl::Hidden, cl::init(false), cl::ZeroOrMore,
112 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000113
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000114static cl::opt<bool, true>
115TrackFailures("polly-detect-track-failures",
116 cl::desc("Track failure strings in detecting scop regions"),
Tobias Grosser64e8e372014-03-13 23:37:43 +0000117 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
118 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000119
Andreas Simbuerger04472402014-05-24 09:25:10 +0000120static cl::opt<bool> KeepGoing("polly-detect-keep-going",
121 cl::desc("Do not fail on the first error."),
122 cl::Hidden, cl::ZeroOrMore, cl::init(false),
123 cl::cat(PollyCategory));
124
Sebastian Pop18016682014-04-08 21:20:44 +0000125static cl::opt<bool, true>
126PollyDelinearizeX("polly-delinearize",
127 cl::desc("Delinearize array access functions"),
128 cl::location(PollyDelinearize), cl::Hidden, cl::ZeroOrMore,
129 cl::init(false), cl::cat(PollyCategory));
130
Tobias Grossera1689932014-02-18 18:49:49 +0000131static cl::opt<bool>
132VerifyScops("polly-detect-verify",
133 cl::desc("Verify the detected SCoPs after each transformation"),
Tobias Grosser64e8e372014-03-13 23:37:43 +0000134 cl::Hidden, cl::init(false), cl::ZeroOrMore,
135 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000136
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000137bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000138bool polly::PollyDelinearize = false;
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000139
Tobias Grosser75805372011-04-29 06:27:02 +0000140//===----------------------------------------------------------------------===//
141// Statistics.
142
143STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
144
Tobias Grosser8519f892013-12-18 10:49:53 +0000145class DiagnosticScopFound : public DiagnosticInfo {
146private:
147 static int PluginDiagnosticKind;
148
149 Function &F;
150 std::string FileName;
151 unsigned EntryLine, ExitLine;
152
153public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000154 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
155 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000156 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000157 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000158
159 virtual void print(DiagnosticPrinter &DP) const;
160
161 static bool classof(const DiagnosticInfo *DI) {
162 return DI->getKind() == PluginDiagnosticKind;
163 }
164};
165
166int DiagnosticScopFound::PluginDiagnosticKind = 10;
167
Tobias Grosser8519f892013-12-18 10:49:53 +0000168void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000169 DP << "Polly detected an optimizable loop region (scop) in function '" << F
170 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000171
172 if (FileName.empty()) {
173 DP << "Scop location is unknown. Compile with debug info "
174 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000175 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000176 }
177
178 DP << FileName << ":" << EntryLine << ": Start of scop\n";
179 DP << FileName << ":" << ExitLine << ": End of scop";
180}
181
Tobias Grosser75805372011-04-29 06:27:02 +0000182//===----------------------------------------------------------------------===//
183// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000184
185template <class RR, typename... Args>
186inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
187 Args &&... Arguments) const {
188
189 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000190 RejectLog &Log = Context.Log;
191 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000192
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000193 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000194 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000195
196 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000197 DEBUG(dbgs() << "\n");
198 } else {
199 assert(!Assert && "Verification of detected scop failed");
200 }
201
202 return false;
203}
204
Tobias Grossera1689932014-02-18 18:49:49 +0000205bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
206 if (!ValidRegions.count(&R))
207 return false;
208
209 if (Verify)
210 return isValidRegion(const_cast<Region &>(R));
211
212 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000213}
214
Tobias Grosser4f129a62011-10-08 00:30:55 +0000215std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000216 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000217 return "";
218
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000219 // Get the first error we found. Even in keep-going mode, this is the first
220 // reason that caused the candidate to be rejected.
221 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000222
223 // This can happen when we marked a region invalid, but didn't track
224 // an error for it.
225 if (Errors.size() == 0)
226 return "";
227
228 RejectReasonPtr RR = *Errors.begin();
229 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000230}
231
Tobias Grossere602a072013-05-07 07:30:56 +0000232bool ScopDetection::isValidCFG(BasicBlock &BB,
233 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000234 Region &RefRegion = Context.CurRegion;
235 TerminatorInst *TI = BB.getTerminator();
236
237 // Return instructions are only valid if the region is the top level region.
238 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
239 return true;
240
241 BranchInst *Br = dyn_cast<BranchInst>(TI);
242
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000243 if (!Br)
244 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000245
Tobias Grosser74394f02013-01-14 22:40:23 +0000246 if (Br->isUnconditional())
247 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000248
249 Value *Condition = Br->getCondition();
250
251 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000253 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000254
255 // Only Constant and ICmpInst are allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000256 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000257 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000258
259 // Allow perfectly nested conditions.
260 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
261
262 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
263 // Unsigned comparisons are not allowed. They trigger overflow problems
264 // in the code generation.
265 //
266 // TODO: This is not sufficient and just hides bugs. However it does pretty
267 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000268 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000269 return false;
270
271 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000272 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000273 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000274 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000275
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000276 Loop *L = LI->getLoopFor(ICmp->getParent());
277 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
278 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000279
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000280 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000281 !isAffineExpr(&Context.CurRegion, RHS, *SE))
282 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000283 RHS, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000284 }
285
286 // Allow loop exit conditions.
287 Loop *L = LI->getLoopFor(&BB);
288 if (L && L->getExitingBlock() == &BB)
289 return true;
290
291 // Allow perfectly nested conditions.
292 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000293 if (R->getEntry() != &BB)
294 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000295
296 return true;
297}
298
299bool ScopDetection::isValidCallInst(CallInst &CI) {
300 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
301 return false;
302
303 if (CI.doesNotAccessMemory())
304 return true;
305
306 Function *CalledFunction = CI.getCalledFunction();
307
308 // Indirect calls are not supported.
309 if (CalledFunction == 0)
310 return false;
311
312 // TODO: Intrinsics.
313 return false;
314}
315
Tobias Grosser458fb782014-01-28 12:58:58 +0000316bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
317 // A reference to function argument or constant value is invariant.
318 if (isa<Argument>(Val) || isa<Constant>(Val))
319 return true;
320
321 const Instruction *I = dyn_cast<Instruction>(&Val);
322 if (!I)
323 return false;
324
325 if (!Reg.contains(I))
326 return true;
327
328 if (I->mayHaveSideEffects())
329 return false;
330
331 // When Val is a Phi node, it is likely not invariant. We do not check whether
332 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
333 // invariant. Recursively checking the operators of Phi nodes would lead to
334 // infinite recursion.
335 if (isa<PHINode>(*I))
336 return false;
337
Tobias Grosser26108892014-04-02 20:18:19 +0000338 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000339 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000340 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000341
342 // When the instruction is a load instruction, check that no write to memory
343 // in the region aliases with the load.
344 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
345 AliasAnalysis::Location Loc = AA->getLocation(LI);
346 const Region::const_block_iterator BE = Reg.block_end();
347 // Check if any basic block in the region can modify the location pointed to
348 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000349 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000350 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000351 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000352 }
353
354 return true;
355}
356
Sebastian Pop422e33f2014-06-03 18:16:31 +0000357MapInsnToMemAcc InsnToMemAcc;
358
Sebastian Popb57c0992014-05-12 20:24:26 +0000359bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000360 for (auto P : Context.NonAffineAccesses) {
361 const SCEVUnknown *BasePointer = P.first;
362 Value *BaseValue = BasePointer->getValue();
Sebastian Pop422e33f2014-06-03 18:16:31 +0000363 ArrayShape *Shape = new ArrayShape(BasePointer);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000364
365 // First step: collect parametric terms in all array references.
366 SmallVector<const SCEV *, 4> Terms;
Sebastian Pop422e33f2014-06-03 18:16:31 +0000367 for (PairInsnAddRec PIAF : Context.NonAffineAccesses[BasePointer])
368 PIAF.second->collectParametricTerms(*SE, Terms);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000369
Sebastian Pope8863b82014-05-12 19:02:02 +0000370 // Also collect terms from the affine memory accesses.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000371 for (PairInsnAddRec PIAF : Context.AffineAccesses[BasePointer])
372 PIAF.second->collectParametricTerms(*SE, Terms);
Sebastian Pope8863b82014-05-12 19:02:02 +0000373
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000374 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000375 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
376 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000377
378 // Third step: compute the access functions for each subscript.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000379 for (PairInsnAddRec PIAF : Context.NonAffineAccesses[BasePointer]) {
380 const SCEVAddRecExpr *AF = PIAF.second;
381 const Instruction *Insn = PIAF.first;
382 if (Shape->DelinearizedSizes.empty())
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000383 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
384 Insn);
Sebastian Pope8863b82014-05-12 19:02:02 +0000385
Sebastian Pop422e33f2014-06-03 18:16:31 +0000386 MemAcc *Acc = new MemAcc(Insn, Shape);
Tobias Grosserd79029a2014-06-03 20:20:41 +0000387 InsnToMemAcc.insert({Insn, Acc});
Sebastian Pop422e33f2014-06-03 18:16:31 +0000388 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
389 Shape->DelinearizedSizes);
390 if (Shape->DelinearizedSizes.empty() ||
391 Acc->DelinearizedSubscripts.empty())
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000392 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
393 Insn);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000394
395 // Check that the delinearized subscripts are affine.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000396 for (const SCEV *S : Acc->DelinearizedSubscripts)
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000397 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000398 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
399 Insn);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000400 }
401 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000402 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000403}
404
Tobias Grosser75805372011-04-29 06:27:02 +0000405bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
406 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000407 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000408 Loop *L = LI->getLoopFor(Inst.getParent());
409 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000410 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000411 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000412
Tobias Grosserb8710b52011-11-10 12:44:50 +0000413 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
414
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000415 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000416 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000417
418 BaseValue = BasePointer->getValue();
419
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000420 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000421 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000422
Tobias Grosser458fb782014-01-28 12:58:58 +0000423 // Check that the base address of the access is invariant in the current
424 // region.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000425 if (!isInvariant(*BaseValue, Context.CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000426 // Verification of this property is difficult as the independent blocks
427 // pass may introduce aliasing that we did not have when running the
428 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000429 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
430 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000431
Tobias Grosserb8710b52011-11-10 12:44:50 +0000432 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
433
Sebastian Pop18016682014-04-08 21:20:44 +0000434 if (AllowNonAffine) {
435 // Do not check whether AccessFunction is affine.
Sebastian Popcd3bb592014-04-10 16:08:11 +0000436 } else if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE,
437 BaseValue)) {
438 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(AccessFunction);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000439
Sebastian Popcd3bb592014-04-10 16:08:11 +0000440 if (!PollyDelinearize || !AF)
441 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000442 AccessFunction, &Inst);
Sebastian Popcd3bb592014-04-10 16:08:11 +0000443
Sebastian Popbc9009a2014-05-27 22:42:09 +0000444 const SCEV *ElementSize = SE->getElementSize(&Inst);
445 Context.ElementSize[BasePointer] = ElementSize;
446
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000447 // Collect all non affine memory accesses, and check whether they are linear
448 // at the end of scop detection. That way we can delinearize all the memory
449 // accesses to the same array in a unique step.
450 if (Context.NonAffineAccesses[BasePointer].size() == 0)
451 Context.NonAffineAccesses[BasePointer] = AFs();
Tobias Grosserd79029a2014-06-03 20:20:41 +0000452 Context.NonAffineAccesses[BasePointer].push_back({&Inst, AF});
Sebastian Pope8863b82014-05-12 19:02:02 +0000453 } else if (const SCEVAddRecExpr *AF =
454 dyn_cast<SCEVAddRecExpr>(AccessFunction)) {
455 if (Context.AffineAccesses[BasePointer].size() == 0)
456 Context.AffineAccesses[BasePointer] = AFs();
Tobias Grosserd79029a2014-06-03 20:20:41 +0000457 Context.AffineAccesses[BasePointer].push_back({&Inst, AF});
Sebastian Pop18016682014-04-08 21:20:44 +0000458 }
Tobias Grosser75805372011-04-29 06:27:02 +0000459
460 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
461 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000462 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
463 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000464
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000465 if (IgnoreAliasing)
466 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000467
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000468 // Check if the base pointer of the memory access does alias with
469 // any other pointer. This cannot be handled at the moment.
Tobias Grosser298a7642013-07-14 18:09:43 +0000470 AliasSet &AS =
471 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
472 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000473
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000474 // INVALID triggers an assertion in verifying mode, if it detects that a
475 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
476 // a pass that stated it would preserve the SCoPs. We disable this check as
477 // the independent blocks pass may create memory references which seem to
478 // alias, if -basicaa is not available. They actually do not, but as we can
479 // not proof this without -basicaa we would fail. We disable this check to
480 // not cause irrelevant verification failures.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000481 if (!AS.isMustAlias())
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000482 return invalid<ReportAlias>(Context, /*Assert=*/true, &Inst, &AS);
Tobias Grosser75805372011-04-29 06:27:02 +0000483
484 return true;
485}
486
Tobias Grosser75805372011-04-29 06:27:02 +0000487bool ScopDetection::isValidInstruction(Instruction &Inst,
488 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000489 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000490 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000491 if (SCEVCodegen)
492 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true,
493 &Inst);
494 else
495 return invalid<ReportNonCanonicalPhiNode>(Context, /*Assert=*/true,
496 &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000497 }
Tobias Grosser75805372011-04-29 06:27:02 +0000498
Tobias Grosser75805372011-04-29 06:27:02 +0000499 // We only check the call instruction but not invoke instruction.
500 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
501 if (isValidCallInst(*CI))
502 return true;
503
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000504 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000505 }
506
507 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000508 if (!isa<AllocaInst>(Inst))
509 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000510
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000511 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000512 }
513
514 // Check the access function.
515 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
516 return isValidMemoryAccess(Inst, Context);
517
518 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000519 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000520}
521
Tobias Grosser75805372011-04-29 06:27:02 +0000522bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000523 if (!SCEVCodegen) {
524 // If code generation is not in scev based mode, we need to ensure that
525 // each loop has a canonical induction variable.
526 PHINode *IndVar = L->getCanonicalInductionVariable();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000527 if (!IndVar)
528 return invalid<ReportLoopHeader>(Context, /*Assert=*/true, L);
Tobias Grosser826b2af2013-03-21 16:14:50 +0000529 }
Tobias Grosser75805372011-04-29 06:27:02 +0000530
531 // Is the loop count affine?
532 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000533 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
534 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000535
536 return true;
537}
538
539Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000540 // Initial no valid region was found (greater than R)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000541 Region *LastValidRegion = nullptr;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000542 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000543
544 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
545
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000546 while (ExpandedRegion) {
547 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
548 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000549
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000550 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000551 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000552 // If the exit is valid check all blocks
553 // - if true, a valid region was found => store it + keep expanding
554 // - if false, .tbd. => stop (should this really end the loop?)
555 if (!allBlocksValid(Context))
556 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000557
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000558 // Delete unnecessary regions (allocated by getExpandedRegion)
559 if (LastValidRegion)
560 delete LastValidRegion;
561
Tobias Grosserd7e58642013-04-10 06:55:45 +0000562 // Store this region, because it is the greatest valid (encountered so
563 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000564 LastValidRegion = ExpandedRegion;
565
566 // Create and test the next greater region (if any)
567 ExpandedRegion = ExpandedRegion->getExpandedRegion();
568
569 } else {
570 // Create and test the next greater region (if any)
571 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
572
573 // Delete unnecessary regions (allocated by getExpandedRegion)
574 delete ExpandedRegion;
575
576 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000577 }
Tobias Grosser75805372011-04-29 06:27:02 +0000578 }
579
Tobias Grosser378a9f22013-11-16 19:34:11 +0000580 DEBUG({
581 if (LastValidRegion)
582 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
583 else
584 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
585 });
Tobias Grosser75805372011-04-29 06:27:02 +0000586
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000587 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000588}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000589static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000590 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000591 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000592 return false;
593
594 return true;
595}
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Tobias Grosser28a70c52014-01-29 19:05:30 +0000597// Remove all direct and indirect children of region R from the region set Regs,
598// but do not recurse further if the first child has been found.
599//
600// Return the number of regions erased from Regs.
601static unsigned eraseAllChildren(std::set<const Region *> &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000602 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000603 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000604 for (auto &SubRegion : R) {
605 if (Regs.find(SubRegion.get()) != Regs.end()) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000606 ++Count;
David Blaikieb035f6d2014-04-15 18:45:27 +0000607 Regs.erase(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000608 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000609 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000610 }
611 }
612 return Count;
613}
614
Tobias Grosser75805372011-04-29 06:27:02 +0000615void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000616 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
617 return;
618
Andreas Simbuerger04472402014-05-24 09:25:10 +0000619 bool IsValidRegion = isValidRegion(R);
620 bool HasErrors = RejectLogs.count(&R) > 0;
621
622 if (IsValidRegion && !HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000623 ++ValidRegion;
624 ValidRegions.insert(&R);
625 return;
626 }
627
David Blaikieb035f6d2014-04-15 18:45:27 +0000628 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000629 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000630
Andreas Simbuerger04472402014-05-24 09:25:10 +0000631 // Do not expand when we had errors. Bad things may happen.
632 if (IsValidRegion && HasErrors)
633 return;
634
Tobias Grosser75805372011-04-29 06:27:02 +0000635 // Try to expand regions.
636 //
637 // As the region tree normally only contains canonical regions, non canonical
638 // regions that form a Scop are not found. Therefore, those non canonical
639 // regions are checked by expanding the canonical ones.
640
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000641 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000642
David Blaikieb035f6d2014-04-15 18:45:27 +0000643 for (auto &SubRegion : R)
644 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000645
Tobias Grosser26108892014-04-02 20:18:19 +0000646 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000647 // Skip invalid regions. Regions may become invalid, if they are element of
648 // an already expanded region.
649 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
650 continue;
651
652 Region *ExpandedR = expandRegion(*CurrentRegion);
653
654 if (!ExpandedR)
655 continue;
656
657 R.addSubRegion(ExpandedR, true);
658 ValidRegions.insert(ExpandedR);
659 ValidRegions.erase(CurrentRegion);
660
Tobias Grosser28a70c52014-01-29 19:05:30 +0000661 // Erase all (direct and indirect) children of ExpandedR from the valid
662 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000663 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000664 }
665}
666
667bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
668 Region &R = Context.CurRegion;
669
Tobias Grosser26108892014-04-02 20:18:19 +0000670 for (const BasicBlock *BB : R.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000671 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000672 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000673 return false;
674 }
675
Tobias Grosser26108892014-04-02 20:18:19 +0000676 for (BasicBlock *BB : R.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000677 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000678 return false;
679
Tobias Grosser26108892014-04-02 20:18:19 +0000680 for (BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000681 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000682 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000683 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000684
Sebastian Pope8863b82014-05-12 19:02:02 +0000685 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000686 return false;
687
Tobias Grosser75805372011-04-29 06:27:02 +0000688 return true;
689}
690
691bool ScopDetection::isValidExit(DetectionContext &Context) const {
692 Region &R = Context.CurRegion;
693
694 // PHI nodes are not allowed in the exit basic block.
695 if (BasicBlock *Exit = R.getExit()) {
696 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000697 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000698 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000699 }
700
701 return true;
702}
703
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000704bool ScopDetection::isValidRegion(Region &R) const {
705 DetectionContext Context(R, *AA, false /*verifying*/);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000706
707 bool RegionIsValid = isValidRegion(Context);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000708 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
709
710 if (PollyTrackFailures && HasErrors) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000711 // std::map::insert does not replace.
712 std::pair<reject_iterator, bool> InsertedValue =
713 RejectLogs.insert(std::make_pair(&R, Context.Log));
714 assert(InsertedValue.second && "Two logs generated for the same Region.");
715 }
716
717 return RegionIsValid;
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000718}
719
Tobias Grosser75805372011-04-29 06:27:02 +0000720bool ScopDetection::isValidRegion(DetectionContext &Context) const {
721 Region &R = Context.CurRegion;
722
723 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
724
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000725 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000726 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000727 return false;
728 }
729
Tobias Grosser4449e522014-01-27 14:24:53 +0000730 if (!R.getEntry()->getName().count(OnlyRegion)) {
731 DEBUG({
732 dbgs() << "Region entry does not match -polly-region-only";
733 dbgs() << "\n";
734 });
735 return false;
736 }
737
Tobias Grossere602a072013-05-07 07:30:56 +0000738 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000739 BasicBlock *entry = R.getEntry();
740 Loop *L = LI->getLoopFor(entry);
741
742 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000743 if (!L->isLoopSimplifyForm())
744 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000745
746 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
747 ++PI) {
748 // Region entering edges come from the same loop but outside the region
749 // are not allowed.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000750 if (L->contains(*PI) && !R.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000751 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000752 }
753 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000754 }
755
Tobias Grosserd654c252012-04-10 18:12:19 +0000756 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000757 // to insert alloca instruction there when translate scalar to array.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000758 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000759 return invalid<ReportEntry>(Context, /*Assert=*/true, R.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000760
Hongbin Zheng94868e62012-04-07 12:29:17 +0000761 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000762 return false;
763
Hongbin Zheng94868e62012-04-07 12:29:17 +0000764 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000765 return false;
766
767 DEBUG(dbgs() << "OK\n");
768 return true;
769}
770
771bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000772 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000773}
774
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000775void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000776 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000777 unsigned LineEntry, LineExit;
778 std::string FileName;
779
Tobias Grosser00dc3092014-03-02 12:02:46 +0000780 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000781 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
782 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000783 }
784}
785
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000786void
787ScopDetection::emitMissedRemarksForValidRegions(const Function &F,
788 const RegionSet &ValidRegions) {
789 for (const Region *R : ValidRegions) {
790 const Region *Parent = R->getParent();
791 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
792 emitRejectionRemarks(F, RejectLogs.at(Parent));
793 }
794}
795
796void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
797 const Region *R) {
798 for (const std::unique_ptr<Region> &Child : *R) {
799 bool IsValid = ValidRegions.count(Child.get());
800 if (IsValid)
801 continue;
802
803 bool IsLeaf = Child->begin() == Child->end();
804 if (!IsLeaf)
805 emitMissedRemarksForLeaves(F, Child.get());
806 else {
807 if (RejectLogs.count(Child.get())) {
808 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
809 }
810 }
811 }
812}
813
Tobias Grosser75805372011-04-29 06:27:02 +0000814bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000815 LI = &getAnalysis<LoopInfo>();
Tobias Grosser9a26f292014-01-02 22:28:53 +0000816 RI = &getAnalysis<RegionInfo>();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000817 if (!DetectScopsWithoutLoops && LI->empty())
818 return false;
819
Tobias Grosser75805372011-04-29 06:27:02 +0000820 AA = &getAnalysis<AliasAnalysis>();
821 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000822 Region *TopRegion = RI->getTopLevelRegion();
823
Tobias Grosser2ff87232011-10-23 11:17:06 +0000824 releaseMemory();
825
Tobias Grossera3ab27e2014-05-07 11:23:32 +0000826 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +0000827 return false;
828
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000829 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000830 return false;
831
832 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000833
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000834 // Only makes sense when we tracked errors.
835 if (PollyTrackFailures) {
836 emitMissedRemarksForValidRegions(F, ValidRegions);
837 emitMissedRemarksForLeaves(F, TopRegion);
838 }
839
840 for (const Region *R : ValidRegions)
841 emitValidRemarks(F, R);
842
Tobias Grosser531891e2012-11-01 16:45:20 +0000843 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000844 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000845
Tobias Grosser75805372011-04-29 06:27:02 +0000846 return false;
847}
848
Tobias Grosser75805372011-04-29 06:27:02 +0000849void polly::ScopDetection::verifyRegion(const Region &R) const {
850 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000851 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000852 isValidRegion(Context);
853}
854
855void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +0000856 if (!VerifyScops)
857 return;
858
Tobias Grosser26108892014-04-02 20:18:19 +0000859 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000860 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +0000861}
862
863void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000864 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000865 AU.addRequired<PostDominatorTree>();
866 AU.addRequired<LoopInfo>();
867 AU.addRequired<ScalarEvolution>();
868 // We also need AA and RegionInfo when we are verifying analysis.
869 AU.addRequiredTransitive<AliasAnalysis>();
870 AU.addRequiredTransitive<RegionInfo>();
871 AU.setPreservesAll();
872}
873
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000874void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +0000875 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000876 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +0000877
878 OS << "\n";
879}
880
881void ScopDetection::releaseMemory() {
882 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000883 RejectLogs.clear();
884
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000885 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000886}
887
888char ScopDetection::ID = 0;
889
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000890Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
891
Tobias Grosser73600b82011-10-08 00:30:40 +0000892INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
893 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000894 false);
895INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser42aff302014-01-13 22:29:56 +0000896INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000897INITIALIZE_PASS_DEPENDENCY(LoopInfo);
898INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
899INITIALIZE_PASS_DEPENDENCY(RegionInfo);
900INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000901INITIALIZE_PASS_END(ScopDetection, "polly-detect",
902 "Polly - Detect static control parts (SCoPs)", false, false)