blob: 4247e279749e78371d778662de2dbd723ac5a974 [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"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000050#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000052#include "polly/Support/ScopHelper.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include "llvm/ADT/Statistic.h"
54#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000055#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000058#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser83628182013-05-07 08:11:54 +000059#include "llvm/DebugInfo.h"
60#include "llvm/IR/LLVMContext.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosser75805372011-04-29 06:27:02 +000063
64#define DEBUG_TYPE "polly-detect"
65#include "llvm/Support/Debug.h"
66
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
68
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
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"),
75 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
76
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000077static cl::opt<bool>
78DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
79 cl::desc("Detect scops in regions without loops"),
80 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
81
Tobias Grosser2ff87232011-10-23 11:17:06 +000082static cl::opt<std::string>
Tobias Grosser637bd632013-05-07 07:31:10 +000083OnlyFunction("polly-only-func", cl::desc("Only run on a single function"),
84 cl::value_desc("function-name"), cl::ValueRequired, cl::init(""),
85 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000086
Tobias Grosser60cd9322011-11-10 12:47:26 +000087static cl::opt<bool>
88IgnoreAliasing("polly-ignore-aliasing",
89 cl::desc("Ignore possible aliasing of the array bases"),
Tobias Grosser637bd632013-05-07 07:31:10 +000090 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000091
Tobias Grosser637bd632013-05-07 07:31:10 +000092static cl::opt<bool>
93ReportLevel("polly-report",
94 cl::desc("Print information about the activities of Polly"),
95 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +000096
97static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000098AllowNonAffine("polly-allow-nonaffine",
99 cl::desc("Allow non affine access functions in arrays"),
Tobias Grosser637bd632013-05-07 07:31:10 +0000100 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000101
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000102static cl::opt<bool, true>
103TrackFailures("polly-detect-track-failures",
104 cl::desc("Track failure strings in detecting scop regions"),
105 cl::location(PollyTrackFailures), cl::Hidden, cl::init(false),
106 cl::cat(PollyCategory));
107
108bool polly::PollyTrackFailures = false;
109
Tobias Grosser75805372011-04-29 06:27:02 +0000110//===----------------------------------------------------------------------===//
111// Statistics.
112
113STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
114
Tobias Grosser74394f02013-01-14 22:40:23 +0000115#define BADSCOP_STAT(NAME, DESC) \
116 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +0000117
Tobias Grosser74394f02013-01-14 22:40:23 +0000118#define INVALID(NAME, MESSAGE) \
119 do { \
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000120 if (PollyTrackFailures) { \
121 std::string Buf; \
122 raw_string_ostream fmt(Buf); \
123 fmt << MESSAGE; \
124 fmt.flush(); \
125 LastFailure = Buf; \
126 } \
Tobias Grosser74394f02013-01-14 22:40:23 +0000127 DEBUG(dbgs() << MESSAGE); \
128 DEBUG(dbgs() << "\n"); \
Tobias Grosser1c84d802013-11-16 01:07:06 +0000129 assert(!Context.Verifying && #NAME); \
Tobias Grosser74394f02013-01-14 22:40:23 +0000130 if (!Context.Verifying) \
131 ++Bad##NAME##ForScop; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000132 } while (0)
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000133
Tobias Grosser74394f02013-01-14 22:40:23 +0000134#define INVALID_NOVERIFY(NAME, MESSAGE) \
135 do { \
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000136 if (PollyTrackFailures) { \
137 std::string Buf; \
138 raw_string_ostream fmt(Buf); \
139 fmt << MESSAGE; \
140 fmt.flush(); \
141 LastFailure = Buf; \
142 } \
Tobias Grosser74394f02013-01-14 22:40:23 +0000143 DEBUG(dbgs() << MESSAGE); \
144 DEBUG(dbgs() << "\n"); \
145 /* DISABLED: assert(!Context.Verifying && #NAME); */ \
146 if (!Context.Verifying) \
147 ++Bad##NAME##ForScop; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000148 } while (0)
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000149
Tobias Grosser74394f02013-01-14 22:40:23 +0000150BADSCOP_STAT(CFG, "CFG too complex");
151BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
Sebastian Pop9d632342013-06-11 22:20:40 +0000152BADSCOP_STAT(IndEdge, "Found invalid region entering edges");
Tobias Grosser74394f02013-01-14 22:40:23 +0000153BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
154BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
155BADSCOP_STAT(AffFunc, "Expression not affine");
Tobias Grosser74394f02013-01-14 22:40:23 +0000156BADSCOP_STAT(Alias, "Found base address alias");
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000157BADSCOP_STAT(SimpleLoop, "Loop not in -loop-simplify form");
Tobias Grosser74394f02013-01-14 22:40:23 +0000158BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000159
Tobias Grosser8519f892013-12-18 10:49:53 +0000160class DiagnosticScopFound : public DiagnosticInfo {
161private:
162 static int PluginDiagnosticKind;
163
164 Function &F;
165 std::string FileName;
166 unsigned EntryLine, ExitLine;
167
168public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000169 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
170 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000171 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000172 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000173
174 virtual void print(DiagnosticPrinter &DP) const;
175
176 static bool classof(const DiagnosticInfo *DI) {
177 return DI->getKind() == PluginDiagnosticKind;
178 }
179};
180
181int DiagnosticScopFound::PluginDiagnosticKind = 10;
182
Tobias Grosser8519f892013-12-18 10:49:53 +0000183void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
184
Tobias Grosser1b12f462013-12-18 11:14:36 +0000185 DP << "Polly detected an optimizable loop region (scop) in function '" << F
186 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000187
188 if (FileName.empty()) {
189 DP << "Scop location is unknown. Compile with debug info "
190 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000191 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000192 }
193
194 DP << FileName << ":" << EntryLine << ": Start of scop\n";
195 DP << FileName << ":" << ExitLine << ": End of scop";
196}
197
Tobias Grosser75805372011-04-29 06:27:02 +0000198//===----------------------------------------------------------------------===//
199// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000200bool ScopDetection::isMaxRegionInScop(const Region &R) const {
201 // The Region is valid only if it could be found in the set.
202 return ValidRegions.count(&R);
203}
204
Tobias Grosser4f129a62011-10-08 00:30:55 +0000205std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
206 if (!InvalidRegions.count(R))
207 return "";
208
209 return InvalidRegions.find(R)->second;
210}
211
Tobias Grossere602a072013-05-07 07:30:56 +0000212bool ScopDetection::isValidCFG(BasicBlock &BB,
213 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000214 Region &RefRegion = Context.CurRegion;
215 TerminatorInst *TI = BB.getTerminator();
216
217 // Return instructions are only valid if the region is the top level region.
218 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
219 return true;
220
221 BranchInst *Br = dyn_cast<BranchInst>(TI);
222
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000223 if (!Br) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000224 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000225 return false;
226 }
Tobias Grosser75805372011-04-29 06:27:02 +0000227
Tobias Grosser74394f02013-01-14 22:40:23 +0000228 if (Br->isUnconditional())
229 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000230
231 Value *Condition = Br->getCondition();
232
233 // UndefValue is not allowed as condition.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000234 if (isa<UndefValue>(Condition)) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000235 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000236 return false;
237 }
Tobias Grosser75805372011-04-29 06:27:02 +0000238
239 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000240 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000241 INVALID(AffFunc, "Condition in BB '" + BB.getName() +
Tobias Grosserd7e58642013-04-10 06:55:45 +0000242 "' neither constant nor an icmp instruction");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000243 return false;
244 }
Tobias Grosser75805372011-04-29 06:27:02 +0000245
246 // Allow perfectly nested conditions.
247 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
248
249 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
250 // Unsigned comparisons are not allowed. They trigger overflow problems
251 // in the code generation.
252 //
253 // TODO: This is not sufficient and just hides bugs. However it does pretty
254 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000255 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000256 return false;
257
258 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000259 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000260 isa<UndefValue>(ICmp->getOperand(1))) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000261 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000262 return false;
263 }
Tobias Grosser75805372011-04-29 06:27:02 +0000264
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000265 Loop *L = LI->getLoopFor(ICmp->getParent());
266 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
267 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000268
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000269 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000270 !isAffineExpr(&Context.CurRegion, RHS, *SE)) {
Tobias Grosser983e7852013-07-28 09:05:20 +0000271 INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
272 << "' with LHS: " << *LHS
273 << " and RHS: " << *RHS);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000274 return false;
275 }
Tobias Grosser75805372011-04-29 06:27:02 +0000276 }
277
278 // Allow loop exit conditions.
279 Loop *L = LI->getLoopFor(&BB);
280 if (L && L->getExitingBlock() == &BB)
281 return true;
282
283 // Allow perfectly nested conditions.
284 Region *R = RI->getRegionFor(&BB);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000285 if (R->getEntry() != &BB) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000286 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000287 return false;
288 }
Tobias Grosser75805372011-04-29 06:27:02 +0000289
290 return true;
291}
292
293bool ScopDetection::isValidCallInst(CallInst &CI) {
294 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
295 return false;
296
297 if (CI.doesNotAccessMemory())
298 return true;
299
300 Function *CalledFunction = CI.getCalledFunction();
301
302 // Indirect calls are not supported.
303 if (CalledFunction == 0)
304 return false;
305
306 // TODO: Intrinsics.
307 return false;
308}
309
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000310std::string ScopDetection::formatInvalidAlias(AliasSet &AS) const {
311 std::string Message;
312 raw_string_ostream OS(Message);
313
314 OS << "Possible aliasing: ";
315
316 std::vector<Value *> Pointers;
317
318 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
319 Pointers.push_back(AI.getPointer());
320
321 std::sort(Pointers.begin(), Pointers.end());
322
323 for (std::vector<Value *>::iterator PI = Pointers.begin(),
324 PE = Pointers.end();
325 ;) {
326 Value *V = *PI;
327
328 if (V->getName().size() == 0)
329 OS << "\"" << *V << "\"";
330 else
331 OS << "\"" << V->getName() << "\"";
332
333 ++PI;
334
335 if (PI != PE)
336 OS << ", ";
337 else
338 break;
339 }
340
341 return OS.str();
342}
343
Tobias Grosser75805372011-04-29 06:27:02 +0000344bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
345 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000346 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000347 Loop *L = LI->getLoopFor(Inst.getParent());
348 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000349 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000350 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000351
Tobias Grosserb8710b52011-11-10 12:44:50 +0000352 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
353
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000354 if (!BasePointer) {
Tobias Grosserb8710b52011-11-10 12:44:50 +0000355 INVALID(AffFunc, "No base pointer");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000356 return false;
357 }
Tobias Grosserb8710b52011-11-10 12:44:50 +0000358
359 BaseValue = BasePointer->getValue();
360
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000361 if (isa<UndefValue>(BaseValue)) {
Tobias Grosserb8710b52011-11-10 12:44:50 +0000362 INVALID(AffFunc, "Undefined base pointer");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000363 return false;
364 }
Tobias Grosserb8710b52011-11-10 12:44:50 +0000365
366 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
367
Tobias Grosser58032cb2013-06-23 01:29:29 +0000368 if (!AllowNonAffine &&
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000369 !isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue)) {
Tobias Grossereeb776a2012-09-08 14:00:37 +0000370 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000371 return false;
372 }
Tobias Grosser75805372011-04-29 06:27:02 +0000373
374 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
375 // created by IndependentBlocks Pass.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000376 if (isa<IntToPtrInst>(BaseValue)) {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000377 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000378 return false;
379 }
Tobias Grosser75805372011-04-29 06:27:02 +0000380
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000381 if (IgnoreAliasing)
382 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000383
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000384 // Check if the base pointer of the memory access does alias with
385 // any other pointer. This cannot be handled at the moment.
Tobias Grosser298a7642013-07-14 18:09:43 +0000386 AliasSet &AS =
387 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
388 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000389
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000390 // INVALID triggers an assertion in verifying mode, if it detects that a
391 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
392 // a pass that stated it would preserve the SCoPs. We disable this check as
393 // the independent blocks pass may create memory references which seem to
394 // alias, if -basicaa is not available. They actually do not, but as we can
395 // not proof this without -basicaa we would fail. We disable this check to
396 // not cause irrelevant verification failures.
397 if (!AS.isMustAlias()) {
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000398 INVALID_NOVERIFY(Alias, formatInvalidAlias(AS));
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000399 return false;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000400 }
Tobias Grosser75805372011-04-29 06:27:02 +0000401
402 return true;
403}
404
Tobias Grosser75805372011-04-29 06:27:02 +0000405bool ScopDetection::isValidInstruction(Instruction &Inst,
406 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000407 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000408 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000409 if (SCEVCodegen) {
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000410 INVALID(IndVar,
411 "SCEV of PHI node refers to SSA names in region: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000412 return false;
413
414 } else {
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000415 INVALID(IndVar, "Non canonical PHI node: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000416 return false;
417 }
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000418 }
Tobias Grosser75805372011-04-29 06:27:02 +0000419
Tobias Grosser75805372011-04-29 06:27:02 +0000420 // We only check the call instruction but not invoke instruction.
421 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
422 if (isValidCallInst(*CI))
423 return true;
424
Tobias Grosserb43ba822011-10-08 00:49:30 +0000425 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000426 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000427 }
428
429 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000430 if (!isa<AllocaInst>(Inst))
431 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000432
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000433 INVALID(Other, "Alloca instruction: " << Inst);
434 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000435 }
436
437 // Check the access function.
438 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
439 return isValidMemoryAccess(Inst, Context);
440
441 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000442 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000443 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000444}
445
Tobias Grosser75805372011-04-29 06:27:02 +0000446bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000447 if (!SCEVCodegen) {
448 // If code generation is not in scev based mode, we need to ensure that
449 // each loop has a canonical induction variable.
450 PHINode *IndVar = L->getCanonicalInductionVariable();
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000451 if (!IndVar) {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000452 INVALID(IndVar,
453 "No canonical IV at loop header: " << L->getHeader()->getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000454 return false;
455 }
Tobias Grosser826b2af2013-03-21 16:14:50 +0000456 }
Tobias Grosser75805372011-04-29 06:27:02 +0000457
458 // Is the loop count affine?
459 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000460 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE)) {
Tobias Grosser58032cb2013-06-23 01:29:29 +0000461 INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
462 << L->getHeader()->getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000463 return false;
464 }
Tobias Grosser75805372011-04-29 06:27:02 +0000465
466 return true;
467}
468
469Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000470 // Initial no valid region was found (greater than R)
471 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000472 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000473
474 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
475
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000476 while (ExpandedRegion) {
477 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
478 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000479
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000480 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000481 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000482 // If the exit is valid check all blocks
483 // - if true, a valid region was found => store it + keep expanding
484 // - if false, .tbd. => stop (should this really end the loop?)
485 if (!allBlocksValid(Context))
486 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000487
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000488 // Delete unnecessary regions (allocated by getExpandedRegion)
489 if (LastValidRegion)
490 delete LastValidRegion;
491
Tobias Grosserd7e58642013-04-10 06:55:45 +0000492 // Store this region, because it is the greatest valid (encountered so
493 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000494 LastValidRegion = ExpandedRegion;
495
496 // Create and test the next greater region (if any)
497 ExpandedRegion = ExpandedRegion->getExpandedRegion();
498
499 } else {
500 // Create and test the next greater region (if any)
501 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
502
503 // Delete unnecessary regions (allocated by getExpandedRegion)
504 delete ExpandedRegion;
505
506 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000507 }
Tobias Grosser75805372011-04-29 06:27:02 +0000508 }
509
Tobias Grosser378a9f22013-11-16 19:34:11 +0000510 DEBUG({
511 if (LastValidRegion)
512 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
513 else
514 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
515 });
Tobias Grosser75805372011-04-29 06:27:02 +0000516
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000517 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000518}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000519static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
520 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
521 ++I)
522 if (R.contains(LI->getLoopFor(*I)))
523 return false;
524
525 return true;
526}
Tobias Grosser75805372011-04-29 06:27:02 +0000527
Tobias Grosser75805372011-04-29 06:27:02 +0000528void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000529
530 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
531 return;
532
Tobias Grosser75805372011-04-29 06:27:02 +0000533 DetectionContext Context(R, *AA, false /*verifying*/);
534
Tobias Grosser4eb73812011-11-10 12:45:15 +0000535 LastFailure = "";
536
Tobias Grosser75805372011-04-29 06:27:02 +0000537 if (isValidRegion(Context)) {
538 ++ValidRegion;
539 ValidRegions.insert(&R);
540 return;
541 }
542
Tobias Grosser4f129a62011-10-08 00:30:55 +0000543 InvalidRegions[&R] = LastFailure;
544
Tobias Grosser75805372011-04-29 06:27:02 +0000545 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
546 findScops(**I);
547
548 // Try to expand regions.
549 //
550 // As the region tree normally only contains canonical regions, non canonical
551 // regions that form a Scop are not found. Therefore, those non canonical
552 // regions are checked by expanding the canonical ones.
553
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000554 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000555
556 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
557 ToExpand.push_back(*I);
558
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000559 for (std::vector<Region *>::iterator RI = ToExpand.begin(),
560 RE = ToExpand.end();
561 RI != RE; ++RI) {
Tobias Grosser75805372011-04-29 06:27:02 +0000562 Region *CurrentRegion = *RI;
563
564 // Skip invalid regions. Regions may become invalid, if they are element of
565 // an already expanded region.
566 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
567 continue;
568
569 Region *ExpandedR = expandRegion(*CurrentRegion);
570
571 if (!ExpandedR)
572 continue;
573
574 R.addSubRegion(ExpandedR, true);
575 ValidRegions.insert(ExpandedR);
576 ValidRegions.erase(CurrentRegion);
577
578 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
579 ++I)
580 ValidRegions.erase(*I);
581 }
582}
583
584bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
585 Region &R = Context.CurRegion;
586
587 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000588 ++I) {
589 Loop *L = LI->getLoopFor(*I);
590 if (L && L->getHeader() == *I && !isValidLoop(L, Context))
591 return false;
592 }
593
594 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Tobias Grosser75805372011-04-29 06:27:02 +0000595 ++I)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000596 if (!isValidCFG(**I, Context))
597 return false;
598
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000599 for (Region::block_iterator BI = R.block_begin(), E = R.block_end(); BI != E;
600 ++BI)
601 for (BasicBlock::iterator I = (*BI)->begin(), E = --(*BI)->end(); I != E;
602 ++I)
603 if (!isValidInstruction(*I, Context))
604 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000605
606 return true;
607}
608
609bool ScopDetection::isValidExit(DetectionContext &Context) const {
610 Region &R = Context.CurRegion;
611
612 // PHI nodes are not allowed in the exit basic block.
613 if (BasicBlock *Exit = R.getExit()) {
614 BasicBlock::iterator I = Exit->begin();
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000615 if (I != Exit->end() && isa<PHINode>(*I)) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000616 INVALID(Other, "PHI node in exit BB");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000617 return false;
618 }
Tobias Grosser75805372011-04-29 06:27:02 +0000619 }
620
621 return true;
622}
623
624bool ScopDetection::isValidRegion(DetectionContext &Context) const {
625 Region &R = Context.CurRegion;
626
627 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
628
629 // The toplevel region is no valid region.
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000630 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000631 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000632 return false;
633 }
634
Tobias Grossere602a072013-05-07 07:30:56 +0000635 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000636 BasicBlock *entry = R.getEntry();
637 Loop *L = LI->getLoopFor(entry);
638
639 if (L) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000640 if (!L->isLoopSimplifyForm()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000641 INVALID(SimpleLoop, "Loop not in simplify form is invalid!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000642 return false;
643 }
Sebastian Pop9d632342013-06-11 22:20:40 +0000644
645 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
646 ++PI) {
647 // Region entering edges come from the same loop but outside the region
648 // are not allowed.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000649 if (L->contains(*PI) && !R.contains(*PI)) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000650 INVALID(IndEdge, "Region has invalid entering edges!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000651 return false;
652 }
Sebastian Pop9d632342013-06-11 22:20:40 +0000653 }
654 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000655 }
656
Tobias Grosserd654c252012-04-10 18:12:19 +0000657 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000658 // to insert alloca instruction there when translate scalar to array.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000659 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock())) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000660 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000661 return false;
662 }
Tobias Grosser75805372011-04-29 06:27:02 +0000663
Hongbin Zheng94868e62012-04-07 12:29:17 +0000664 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000665 return false;
666
Hongbin Zheng94868e62012-04-07 12:29:17 +0000667 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000668 return false;
669
670 DEBUG(dbgs() << "OK\n");
671 return true;
672}
673
674bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000675 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000676}
677
Tobias Grosser531891e2012-11-01 16:45:20 +0000678void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
679 unsigned &LineEnd, std::string &FileName) {
680 LineBegin = -1;
681 LineEnd = 0;
682
683 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
684 RI != RE; ++RI)
685 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
686 ++BI) {
687 DebugLoc DL = BI->getDebugLoc();
688 if (DL.isUnknown())
689 continue;
690
691 DIScope Scope(DL.getScope(BI->getContext()));
692
693 if (FileName.empty())
694 FileName = Scope.getFilename();
695
696 unsigned NewLine = DL.getLine();
697
698 LineBegin = std::min(LineBegin, NewLine);
699 LineEnd = std::max(LineEnd, NewLine);
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000700 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000701}
702
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000703void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000704 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
705 unsigned LineEntry, LineExit;
706 std::string FileName;
707
708 getDebugLocation(*RI, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000709 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
710 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000711 }
712}
713
Tobias Grosser75805372011-04-29 06:27:02 +0000714bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000715 LI = &getAnalysis<LoopInfo>();
Tobias Grosser9a26f292014-01-02 22:28:53 +0000716 RI = &getAnalysis<RegionInfo>();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000717 if (!DetectScopsWithoutLoops && LI->empty())
718 return false;
719
Tobias Grosser75805372011-04-29 06:27:02 +0000720 AA = &getAnalysis<AliasAnalysis>();
721 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000722 Region *TopRegion = RI->getTopLevelRegion();
723
Tobias Grosser2ff87232011-10-23 11:17:06 +0000724 releaseMemory();
725
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000726 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000727 return false;
728
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000729 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000730 return false;
731
732 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000733
734 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000735 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000736
Tobias Grosser75805372011-04-29 06:27:02 +0000737 return false;
738}
739
Tobias Grosser75805372011-04-29 06:27:02 +0000740void polly::ScopDetection::verifyRegion(const Region &R) const {
741 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000742 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000743 isValidRegion(Context);
744}
745
746void polly::ScopDetection::verifyAnalysis() const {
747 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000748 E = ValidRegions.end();
749 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000750 verifyRegion(**I);
751}
752
753void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000754 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000755 AU.addRequired<PostDominatorTree>();
756 AU.addRequired<LoopInfo>();
757 AU.addRequired<ScalarEvolution>();
758 // We also need AA and RegionInfo when we are verifying analysis.
759 AU.addRequiredTransitive<AliasAnalysis>();
760 AU.addRequiredTransitive<RegionInfo>();
761 AU.setPreservesAll();
762}
763
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000764void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000765 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000766 E = ValidRegions.end();
767 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000768 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
769
770 OS << "\n";
771}
772
773void ScopDetection::releaseMemory() {
774 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000775 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000776 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000777}
778
779char ScopDetection::ID = 0;
780
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000781Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
782
Tobias Grosser73600b82011-10-08 00:30:40 +0000783INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
784 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000785 false);
786INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser42aff302014-01-13 22:29:56 +0000787INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000788INITIALIZE_PASS_DEPENDENCY(LoopInfo);
789INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
790INITIALIZE_PASS_DEPENDENCY(RegionInfo);
791INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000792INITIALIZE_PASS_END(ScopDetection, "polly-detect",
793 "Polly - Detect static control parts (SCoPs)", false, false)