blob: 5563f87a723cf22e25d7e6dd3f1bfa5f1b15566a [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 Grosser75805372011-04-29 06:27:02 +000059#include "llvm/Assembly/Writer.h"
Tobias Grosser83628182013-05-07 08:11:54 +000060#include "llvm/DebugInfo.h"
61#include "llvm/IR/LLVMContext.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosser75805372011-04-29 06:27:02 +000064
65#define DEBUG_TYPE "polly-detect"
66#include "llvm/Support/Debug.h"
67
Tobias Grosser60b54f12011-11-08 15:41:28 +000068#include <set>
69
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Sebastian Pop8fe6d112013-05-30 17:47:32 +000073static cl::opt<bool>
74DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
75 cl::desc("Detect scops in functions without loops"),
76 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
77
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"),
81 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
82
Tobias Grosser2ff87232011-10-23 11:17:06 +000083static cl::opt<std::string>
Tobias Grosser637bd632013-05-07 07:31:10 +000084OnlyFunction("polly-only-func", cl::desc("Only run on a single function"),
85 cl::value_desc("function-name"), cl::ValueRequired, cl::init(""),
86 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000087
Tobias Grosser60cd9322011-11-10 12:47:26 +000088static cl::opt<bool>
89IgnoreAliasing("polly-ignore-aliasing",
90 cl::desc("Ignore possible aliasing of the array bases"),
Tobias Grosser637bd632013-05-07 07:31:10 +000091 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000092
Tobias Grosser637bd632013-05-07 07:31:10 +000093static cl::opt<bool>
94ReportLevel("polly-report",
95 cl::desc("Print information about the activities of Polly"),
96 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +000097
98static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000099AllowNonAffine("polly-allow-nonaffine",
100 cl::desc("Allow non affine access functions in arrays"),
Tobias Grosser637bd632013-05-07 07:31:10 +0000101 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000102
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000103static cl::opt<bool, true>
104TrackFailures("polly-detect-track-failures",
105 cl::desc("Track failure strings in detecting scop regions"),
106 cl::location(PollyTrackFailures), cl::Hidden, cl::init(false),
107 cl::cat(PollyCategory));
108
109bool polly::PollyTrackFailures = false;
110
Tobias Grosser75805372011-04-29 06:27:02 +0000111//===----------------------------------------------------------------------===//
112// Statistics.
113
114STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
115
Tobias Grosser74394f02013-01-14 22:40:23 +0000116#define BADSCOP_STAT(NAME, DESC) \
117 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +0000118
Tobias Grosser74394f02013-01-14 22:40:23 +0000119#define INVALID(NAME, MESSAGE) \
120 do { \
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000121 if (PollyTrackFailures) { \
122 std::string Buf; \
123 raw_string_ostream fmt(Buf); \
124 fmt << MESSAGE; \
125 fmt.flush(); \
126 LastFailure = Buf; \
127 } \
Tobias Grosser74394f02013-01-14 22:40:23 +0000128 DEBUG(dbgs() << MESSAGE); \
129 DEBUG(dbgs() << "\n"); \
Tobias Grosser1c84d802013-11-16 01:07:06 +0000130 assert(!Context.Verifying && #NAME); \
Tobias Grosser74394f02013-01-14 22:40:23 +0000131 if (!Context.Verifying) \
132 ++Bad##NAME##ForScop; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000133 } while (0)
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000134
Tobias Grosser74394f02013-01-14 22:40:23 +0000135#define INVALID_NOVERIFY(NAME, MESSAGE) \
136 do { \
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000137 if (PollyTrackFailures) { \
138 std::string Buf; \
139 raw_string_ostream fmt(Buf); \
140 fmt << MESSAGE; \
141 fmt.flush(); \
142 LastFailure = Buf; \
143 } \
Tobias Grosser74394f02013-01-14 22:40:23 +0000144 DEBUG(dbgs() << MESSAGE); \
145 DEBUG(dbgs() << "\n"); \
146 /* DISABLED: assert(!Context.Verifying && #NAME); */ \
147 if (!Context.Verifying) \
148 ++Bad##NAME##ForScop; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000149 } while (0)
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000150
Tobias Grosser74394f02013-01-14 22:40:23 +0000151BADSCOP_STAT(CFG, "CFG too complex");
152BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
Sebastian Pop9d632342013-06-11 22:20:40 +0000153BADSCOP_STAT(IndEdge, "Found invalid region entering edges");
Tobias Grosser74394f02013-01-14 22:40:23 +0000154BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
155BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
156BADSCOP_STAT(AffFunc, "Expression not affine");
Tobias Grosser74394f02013-01-14 22:40:23 +0000157BADSCOP_STAT(Alias, "Found base address alias");
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000158BADSCOP_STAT(SimpleLoop, "Loop not in -loop-simplify form");
Tobias Grosser74394f02013-01-14 22:40:23 +0000159BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000160
Tobias Grosser8519f892013-12-18 10:49:53 +0000161class DiagnosticScopFound : public DiagnosticInfo {
162private:
163 static int PluginDiagnosticKind;
164
165 Function &F;
166 std::string FileName;
167 unsigned EntryLine, ExitLine;
168
169public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000170 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
171 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000172 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000173 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000174
175 virtual void print(DiagnosticPrinter &DP) const;
176
177 static bool classof(const DiagnosticInfo *DI) {
178 return DI->getKind() == PluginDiagnosticKind;
179 }
180};
181
182int DiagnosticScopFound::PluginDiagnosticKind = 10;
183
Tobias Grosser8519f892013-12-18 10:49:53 +0000184void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
185
Tobias Grosser1b12f462013-12-18 11:14:36 +0000186 DP << "Polly detected an optimizable loop region (scop) in function '" << F
187 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000188
189 if (FileName.empty()) {
190 DP << "Scop location is unknown. Compile with debug info "
191 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000192 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000193 }
194
195 DP << FileName << ":" << EntryLine << ": Start of scop\n";
196 DP << FileName << ":" << ExitLine << ": End of scop";
197}
198
Tobias Grosser75805372011-04-29 06:27:02 +0000199//===----------------------------------------------------------------------===//
200// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000201bool ScopDetection::isMaxRegionInScop(const Region &R) const {
202 // The Region is valid only if it could be found in the set.
203 return ValidRegions.count(&R);
204}
205
Tobias Grosser4f129a62011-10-08 00:30:55 +0000206std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
207 if (!InvalidRegions.count(R))
208 return "";
209
210 return InvalidRegions.find(R)->second;
211}
212
Tobias Grossere602a072013-05-07 07:30:56 +0000213bool ScopDetection::isValidCFG(BasicBlock &BB,
214 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000215 Region &RefRegion = Context.CurRegion;
216 TerminatorInst *TI = BB.getTerminator();
217
218 // Return instructions are only valid if the region is the top level region.
219 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
220 return true;
221
222 BranchInst *Br = dyn_cast<BranchInst>(TI);
223
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000224 if (!Br) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000225 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000226 return false;
227 }
Tobias Grosser75805372011-04-29 06:27:02 +0000228
Tobias Grosser74394f02013-01-14 22:40:23 +0000229 if (Br->isUnconditional())
230 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000231
232 Value *Condition = Br->getCondition();
233
234 // UndefValue is not allowed as condition.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000235 if (isa<UndefValue>(Condition)) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000236 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000237 return false;
238 }
Tobias Grosser75805372011-04-29 06:27:02 +0000239
240 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000241 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000242 INVALID(AffFunc, "Condition in BB '" + BB.getName() +
Tobias Grosserd7e58642013-04-10 06:55:45 +0000243 "' neither constant nor an icmp instruction");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000244 return false;
245 }
Tobias Grosser75805372011-04-29 06:27:02 +0000246
247 // Allow perfectly nested conditions.
248 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
249
250 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
251 // Unsigned comparisons are not allowed. They trigger overflow problems
252 // in the code generation.
253 //
254 // TODO: This is not sufficient and just hides bugs. However it does pretty
255 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000256 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000257 return false;
258
259 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000260 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000261 isa<UndefValue>(ICmp->getOperand(1))) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000262 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000263 return false;
264 }
Tobias Grosser75805372011-04-29 06:27:02 +0000265
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000266 Loop *L = LI->getLoopFor(ICmp->getParent());
267 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
268 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000270 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000271 !isAffineExpr(&Context.CurRegion, RHS, *SE)) {
Tobias Grosser983e7852013-07-28 09:05:20 +0000272 INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
273 << "' with LHS: " << *LHS
274 << " and RHS: " << *RHS);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000275 return false;
276 }
Tobias Grosser75805372011-04-29 06:27:02 +0000277 }
278
279 // Allow loop exit conditions.
280 Loop *L = LI->getLoopFor(&BB);
281 if (L && L->getExitingBlock() == &BB)
282 return true;
283
284 // Allow perfectly nested conditions.
285 Region *R = RI->getRegionFor(&BB);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000286 if (R->getEntry() != &BB) {
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000287 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000288 return false;
289 }
Tobias Grosser75805372011-04-29 06:27:02 +0000290
291 return true;
292}
293
294bool ScopDetection::isValidCallInst(CallInst &CI) {
295 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
296 return false;
297
298 if (CI.doesNotAccessMemory())
299 return true;
300
301 Function *CalledFunction = CI.getCalledFunction();
302
303 // Indirect calls are not supported.
304 if (CalledFunction == 0)
305 return false;
306
307 // TODO: Intrinsics.
308 return false;
309}
310
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000311std::string ScopDetection::formatInvalidAlias(AliasSet &AS) const {
312 std::string Message;
313 raw_string_ostream OS(Message);
314
315 OS << "Possible aliasing: ";
316
317 std::vector<Value *> Pointers;
318
319 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
320 Pointers.push_back(AI.getPointer());
321
322 std::sort(Pointers.begin(), Pointers.end());
323
324 for (std::vector<Value *>::iterator PI = Pointers.begin(),
325 PE = Pointers.end();
326 ;) {
327 Value *V = *PI;
328
329 if (V->getName().size() == 0)
330 OS << "\"" << *V << "\"";
331 else
332 OS << "\"" << V->getName() << "\"";
333
334 ++PI;
335
336 if (PI != PE)
337 OS << ", ";
338 else
339 break;
340 }
341
342 return OS.str();
343}
344
Tobias Grosser75805372011-04-29 06:27:02 +0000345bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
346 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000347 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000348 Loop *L = LI->getLoopFor(Inst.getParent());
349 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000350 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000351 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000352
Tobias Grosserb8710b52011-11-10 12:44:50 +0000353 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
354
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000355 if (!BasePointer) {
Tobias Grosserb8710b52011-11-10 12:44:50 +0000356 INVALID(AffFunc, "No base pointer");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000357 return false;
358 }
Tobias Grosserb8710b52011-11-10 12:44:50 +0000359
360 BaseValue = BasePointer->getValue();
361
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000362 if (isa<UndefValue>(BaseValue)) {
Tobias Grosserb8710b52011-11-10 12:44:50 +0000363 INVALID(AffFunc, "Undefined base pointer");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000364 return false;
365 }
Tobias Grosserb8710b52011-11-10 12:44:50 +0000366
367 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
368
Tobias Grosser58032cb2013-06-23 01:29:29 +0000369 if (!AllowNonAffine &&
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000370 !isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue)) {
Tobias Grossereeb776a2012-09-08 14:00:37 +0000371 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000372 return false;
373 }
Tobias Grosser75805372011-04-29 06:27:02 +0000374
375 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
376 // created by IndependentBlocks Pass.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000377 if (isa<IntToPtrInst>(BaseValue)) {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000378 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000379 return false;
380 }
Tobias Grosser75805372011-04-29 06:27:02 +0000381
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000382 if (IgnoreAliasing)
383 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000384
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000385 // Check if the base pointer of the memory access does alias with
386 // any other pointer. This cannot be handled at the moment.
Tobias Grosser298a7642013-07-14 18:09:43 +0000387 AliasSet &AS =
388 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
389 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000390
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000391 // INVALID triggers an assertion in verifying mode, if it detects that a
392 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
393 // a pass that stated it would preserve the SCoPs. We disable this check as
394 // the independent blocks pass may create memory references which seem to
395 // alias, if -basicaa is not available. They actually do not, but as we can
396 // not proof this without -basicaa we would fail. We disable this check to
397 // not cause irrelevant verification failures.
398 if (!AS.isMustAlias()) {
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000399 INVALID_NOVERIFY(Alias, formatInvalidAlias(AS));
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000400 return false;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000401 }
Tobias Grosser75805372011-04-29 06:27:02 +0000402
403 return true;
404}
405
Tobias Grosser75805372011-04-29 06:27:02 +0000406bool ScopDetection::isValidInstruction(Instruction &Inst,
407 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000408 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000409 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000410 if (SCEVCodegen) {
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000411 INVALID(IndVar,
412 "SCEV of PHI node refers to SSA names in region: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000413 return false;
414
415 } else {
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000416 INVALID(IndVar, "Non canonical PHI node: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000417 return false;
418 }
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000419 }
Tobias Grosser75805372011-04-29 06:27:02 +0000420
Tobias Grosser75805372011-04-29 06:27:02 +0000421 // We only check the call instruction but not invoke instruction.
422 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
423 if (isValidCallInst(*CI))
424 return true;
425
Tobias Grosserb43ba822011-10-08 00:49:30 +0000426 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000427 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000428 }
429
430 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000431 if (!isa<AllocaInst>(Inst))
432 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000433
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000434 INVALID(Other, "Alloca instruction: " << Inst);
435 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000436 }
437
438 // Check the access function.
439 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
440 return isValidMemoryAccess(Inst, Context);
441
442 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000443 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000444 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000445}
446
Tobias Grosser75805372011-04-29 06:27:02 +0000447bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000448 if (!SCEVCodegen) {
449 // If code generation is not in scev based mode, we need to ensure that
450 // each loop has a canonical induction variable.
451 PHINode *IndVar = L->getCanonicalInductionVariable();
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000452 if (!IndVar) {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000453 INVALID(IndVar,
454 "No canonical IV at loop header: " << L->getHeader()->getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000455 return false;
456 }
Tobias Grosser826b2af2013-03-21 16:14:50 +0000457 }
Tobias Grosser75805372011-04-29 06:27:02 +0000458
459 // Is the loop count affine?
460 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000461 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE)) {
Tobias Grosser58032cb2013-06-23 01:29:29 +0000462 INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
463 << L->getHeader()->getName());
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000464 return false;
465 }
Tobias Grosser75805372011-04-29 06:27:02 +0000466
467 return true;
468}
469
470Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000471 // Initial no valid region was found (greater than R)
472 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000473 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000474
475 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
476
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000477 while (ExpandedRegion) {
478 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
479 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000480
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000481 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000482 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000483 // If the exit is valid check all blocks
484 // - if true, a valid region was found => store it + keep expanding
485 // - if false, .tbd. => stop (should this really end the loop?)
486 if (!allBlocksValid(Context))
487 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000488
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000489 // Delete unnecessary regions (allocated by getExpandedRegion)
490 if (LastValidRegion)
491 delete LastValidRegion;
492
Tobias Grosserd7e58642013-04-10 06:55:45 +0000493 // Store this region, because it is the greatest valid (encountered so
494 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000495 LastValidRegion = ExpandedRegion;
496
497 // Create and test the next greater region (if any)
498 ExpandedRegion = ExpandedRegion->getExpandedRegion();
499
500 } else {
501 // Create and test the next greater region (if any)
502 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
503
504 // Delete unnecessary regions (allocated by getExpandedRegion)
505 delete ExpandedRegion;
506
507 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000508 }
Tobias Grosser75805372011-04-29 06:27:02 +0000509 }
510
Tobias Grosser378a9f22013-11-16 19:34:11 +0000511 DEBUG({
512 if (LastValidRegion)
513 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
514 else
515 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
516 });
Tobias Grosser75805372011-04-29 06:27:02 +0000517
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000518 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000519}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000520static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
521 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
522 ++I)
523 if (R.contains(LI->getLoopFor(*I)))
524 return false;
525
526 return true;
527}
Tobias Grosser75805372011-04-29 06:27:02 +0000528
Tobias Grosser75805372011-04-29 06:27:02 +0000529void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000530
531 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
532 return;
533
Tobias Grosser75805372011-04-29 06:27:02 +0000534 DetectionContext Context(R, *AA, false /*verifying*/);
535
Tobias Grosser4eb73812011-11-10 12:45:15 +0000536 LastFailure = "";
537
Tobias Grosser75805372011-04-29 06:27:02 +0000538 if (isValidRegion(Context)) {
539 ++ValidRegion;
540 ValidRegions.insert(&R);
541 return;
542 }
543
Tobias Grosser4f129a62011-10-08 00:30:55 +0000544 InvalidRegions[&R] = LastFailure;
545
Tobias Grosser75805372011-04-29 06:27:02 +0000546 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
547 findScops(**I);
548
549 // Try to expand regions.
550 //
551 // As the region tree normally only contains canonical regions, non canonical
552 // regions that form a Scop are not found. Therefore, those non canonical
553 // regions are checked by expanding the canonical ones.
554
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000555 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000556
557 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
558 ToExpand.push_back(*I);
559
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000560 for (std::vector<Region *>::iterator RI = ToExpand.begin(),
561 RE = ToExpand.end();
562 RI != RE; ++RI) {
Tobias Grosser75805372011-04-29 06:27:02 +0000563 Region *CurrentRegion = *RI;
564
565 // Skip invalid regions. Regions may become invalid, if they are element of
566 // an already expanded region.
567 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
568 continue;
569
570 Region *ExpandedR = expandRegion(*CurrentRegion);
571
572 if (!ExpandedR)
573 continue;
574
575 R.addSubRegion(ExpandedR, true);
576 ValidRegions.insert(ExpandedR);
577 ValidRegions.erase(CurrentRegion);
578
579 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
580 ++I)
581 ValidRegions.erase(*I);
582 }
583}
584
585bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
586 Region &R = Context.CurRegion;
587
588 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000589 ++I) {
590 Loop *L = LI->getLoopFor(*I);
591 if (L && L->getHeader() == *I && !isValidLoop(L, Context))
592 return false;
593 }
594
595 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Tobias Grosser75805372011-04-29 06:27:02 +0000596 ++I)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000597 if (!isValidCFG(**I, Context))
598 return false;
599
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000600 for (Region::block_iterator BI = R.block_begin(), E = R.block_end(); BI != E;
601 ++BI)
602 for (BasicBlock::iterator I = (*BI)->begin(), E = --(*BI)->end(); I != E;
603 ++I)
604 if (!isValidInstruction(*I, Context))
605 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000606
607 return true;
608}
609
610bool ScopDetection::isValidExit(DetectionContext &Context) const {
611 Region &R = Context.CurRegion;
612
613 // PHI nodes are not allowed in the exit basic block.
614 if (BasicBlock *Exit = R.getExit()) {
615 BasicBlock::iterator I = Exit->begin();
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000616 if (I != Exit->end() && isa<PHINode>(*I)) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000617 INVALID(Other, "PHI node in exit BB");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000618 return false;
619 }
Tobias Grosser75805372011-04-29 06:27:02 +0000620 }
621
622 return true;
623}
624
625bool ScopDetection::isValidRegion(DetectionContext &Context) const {
626 Region &R = Context.CurRegion;
627
628 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
629
630 // The toplevel region is no valid region.
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000631 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000632 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000633 return false;
634 }
635
Tobias Grossere602a072013-05-07 07:30:56 +0000636 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000637 BasicBlock *entry = R.getEntry();
638 Loop *L = LI->getLoopFor(entry);
639
640 if (L) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000641 if (!L->isLoopSimplifyForm()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000642 INVALID(SimpleLoop, "Loop not in simplify form is invalid!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000643 return false;
644 }
Sebastian Pop9d632342013-06-11 22:20:40 +0000645
646 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
647 ++PI) {
648 // Region entering edges come from the same loop but outside the region
649 // are not allowed.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000650 if (L->contains(*PI) && !R.contains(*PI)) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000651 INVALID(IndEdge, "Region has invalid entering edges!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000652 return false;
653 }
Sebastian Pop9d632342013-06-11 22:20:40 +0000654 }
655 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000656 }
657
Tobias Grosserd654c252012-04-10 18:12:19 +0000658 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000659 // to insert alloca instruction there when translate scalar to array.
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000660 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock())) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000661 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000662 return false;
663 }
Tobias Grosser75805372011-04-29 06:27:02 +0000664
Hongbin Zheng94868e62012-04-07 12:29:17 +0000665 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000666 return false;
667
Hongbin Zheng94868e62012-04-07 12:29:17 +0000668 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000669 return false;
670
671 DEBUG(dbgs() << "OK\n");
672 return true;
673}
674
675bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000676 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000677}
678
Tobias Grosser531891e2012-11-01 16:45:20 +0000679void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
680 unsigned &LineEnd, std::string &FileName) {
681 LineBegin = -1;
682 LineEnd = 0;
683
684 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
685 RI != RE; ++RI)
686 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
687 ++BI) {
688 DebugLoc DL = BI->getDebugLoc();
689 if (DL.isUnknown())
690 continue;
691
692 DIScope Scope(DL.getScope(BI->getContext()));
693
694 if (FileName.empty())
695 FileName = Scope.getFilename();
696
697 unsigned NewLine = DL.getLine();
698
699 LineBegin = std::min(LineBegin, NewLine);
700 LineEnd = std::max(LineEnd, NewLine);
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000701 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000702}
703
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000704void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000705 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
706 unsigned LineEntry, LineExit;
707 std::string FileName;
708
709 getDebugLocation(*RI, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000710 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
711 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000712 }
713}
714
Tobias Grosser75805372011-04-29 06:27:02 +0000715bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000716 LI = &getAnalysis<LoopInfo>();
717 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 RI = &getAnalysis<RegionInfo>();
723 Region *TopRegion = RI->getTopLevelRegion();
724
Tobias Grosser2ff87232011-10-23 11:17:06 +0000725 releaseMemory();
726
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000727 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000728 return false;
729
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000730 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000731 return false;
732
733 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000734
735 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000736 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000737
Tobias Grosser75805372011-04-29 06:27:02 +0000738 return false;
739}
740
Tobias Grosser75805372011-04-29 06:27:02 +0000741void polly::ScopDetection::verifyRegion(const Region &R) const {
742 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000743 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000744 isValidRegion(Context);
745}
746
747void polly::ScopDetection::verifyAnalysis() const {
748 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000749 E = ValidRegions.end();
750 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000751 verifyRegion(**I);
752}
753
754void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
755 AU.addRequired<DominatorTree>();
756 AU.addRequired<PostDominatorTree>();
757 AU.addRequired<LoopInfo>();
758 AU.addRequired<ScalarEvolution>();
759 // We also need AA and RegionInfo when we are verifying analysis.
760 AU.addRequiredTransitive<AliasAnalysis>();
761 AU.addRequiredTransitive<RegionInfo>();
762 AU.setPreservesAll();
763}
764
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000765void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000766 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000767 E = ValidRegions.end();
768 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000769 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
770
771 OS << "\n";
772}
773
774void ScopDetection::releaseMemory() {
775 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000776 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000777 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000778}
779
780char ScopDetection::ID = 0;
781
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000782Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
783
Tobias Grosser73600b82011-10-08 00:30:40 +0000784INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
785 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000786 false);
787INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
788INITIALIZE_PASS_DEPENDENCY(DominatorTree);
789INITIALIZE_PASS_DEPENDENCY(LoopInfo);
790INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
791INITIALIZE_PASS_DEPENDENCY(RegionInfo);
792INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000793INITIALIZE_PASS_END(ScopDetection, "polly-detect",
794 "Polly - Detect static control parts (SCoPs)", false, false)