blob: e5704c6fc20068d3a0cfe689b3f6ec099b008636 [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 Grosserecfe21b2013-03-20 18:03:18 +000049#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include "polly/Support/ScopHelper.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grosser75805372011-04-29 06:27:02 +000052
Chandler Carruth535d52c2013-01-02 11:47:44 +000053#include "llvm/IR/LLVMContext.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"
Tobias Grosser531891e2012-11-01 16:45:20 +000060#include "llvm/DebugInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000061#include "llvm/Support/CommandLine.h"
62#include "llvm/Assembly/Writer.h"
63
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
Tobias Grosser2ff87232011-10-23 11:17:06 +000072static cl::opt<std::string>
Tobias Grosseraf3c00b82013-02-05 09:40:22 +000073OnlyFunction("polly-detect-only", cl::desc("Only detect scops in function"),
74 cl::Hidden, cl::value_desc("The function name to detect scops in"),
Tobias Grosser2ff87232011-10-23 11:17:06 +000075 cl::ValueRequired, cl::init(""));
76
Tobias Grosser60cd9322011-11-10 12:47:26 +000077static cl::opt<bool>
78IgnoreAliasing("polly-ignore-aliasing",
79 cl::desc("Ignore possible aliasing of the array bases"),
80 cl::Hidden, cl::init(false));
Tobias Grosser2ff87232011-10-23 11:17:06 +000081
Tobias Grossera1879642011-12-20 10:43:14 +000082static cl::opt<bool>
Tobias Grosseraf3c00b82013-02-05 09:40:22 +000083ReportLevel("polly-report", cl::desc("Print information about Polly"),
Tobias Grosser531891e2012-11-01 16:45:20 +000084 cl::Hidden, cl::init(false));
85
86static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000087AllowNonAffine("polly-allow-nonaffine",
88 cl::desc("Allow non affine access functions in arrays"),
89 cl::Hidden, cl::init(false));
90
Tobias Grosser75805372011-04-29 06:27:02 +000091//===----------------------------------------------------------------------===//
92// Statistics.
93
94STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
95
Tobias Grosser74394f02013-01-14 22:40:23 +000096#define BADSCOP_STAT(NAME, DESC) \
97 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +000098
Tobias Grosser74394f02013-01-14 22:40:23 +000099#define INVALID(NAME, MESSAGE) \
100 do { \
101 std::string Buf; \
102 raw_string_ostream fmt(Buf); \
103 fmt << MESSAGE; \
104 fmt.flush(); \
105 LastFailure = Buf; \
106 DEBUG(dbgs() << MESSAGE); \
107 DEBUG(dbgs() << "\n"); \
108 assert(!Context.Verifying && #NAME); \
109 if (!Context.Verifying) \
110 ++Bad##NAME##ForScop; \
111 return false; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000112 } while (0)
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000113
Tobias Grosser74394f02013-01-14 22:40:23 +0000114#define INVALID_NOVERIFY(NAME, MESSAGE) \
115 do { \
116 std::string Buf; \
117 raw_string_ostream fmt(Buf); \
118 fmt << MESSAGE; \
119 fmt.flush(); \
120 LastFailure = Buf; \
121 DEBUG(dbgs() << MESSAGE); \
122 DEBUG(dbgs() << "\n"); \
123 /* DISABLED: assert(!Context.Verifying && #NAME); */ \
124 if (!Context.Verifying) \
125 ++Bad##NAME##ForScop; \
126 return false; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000127 } while (0)
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000128
Tobias Grosser74394f02013-01-14 22:40:23 +0000129BADSCOP_STAT(CFG, "CFG too complex");
130BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
131BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
132BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
133BADSCOP_STAT(AffFunc, "Expression not affine");
134BADSCOP_STAT(Scalar, "Found scalar dependency");
135BADSCOP_STAT(Alias, "Found base address alias");
136BADSCOP_STAT(SimpleRegion, "Region not simple");
137BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000138
139//===----------------------------------------------------------------------===//
140// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000141bool ScopDetection::isMaxRegionInScop(const Region &R) const {
142 // The Region is valid only if it could be found in the set.
143 return ValidRegions.count(&R);
144}
145
Tobias Grosser4f129a62011-10-08 00:30:55 +0000146std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
147 if (!InvalidRegions.count(R))
148 return "";
149
150 return InvalidRegions.find(R)->second;
151}
152
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000153bool ScopDetection::isValidCFG(BasicBlock &BB,
154 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000155 Region &RefRegion = Context.CurRegion;
156 TerminatorInst *TI = BB.getTerminator();
157
158 // Return instructions are only valid if the region is the top level region.
159 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
160 return true;
161
162 BranchInst *Br = dyn_cast<BranchInst>(TI);
163
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000164 if (!Br)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000165 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000166
Tobias Grosser74394f02013-01-14 22:40:23 +0000167 if (Br->isUnconditional())
168 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000169
170 Value *Condition = Br->getCondition();
171
172 // UndefValue is not allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000173 if (isa<UndefValue>(Condition))
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000174 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000175
176 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000177 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000178 INVALID(AffFunc, "Condition in BB '" + BB.getName() + "' neither "
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000179 "constant nor an icmp instruction");
Tobias Grosser75805372011-04-29 06:27:02 +0000180
181 // Allow perfectly nested conditions.
182 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
183
184 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
185 // Unsigned comparisons are not allowed. They trigger overflow problems
186 // in the code generation.
187 //
188 // TODO: This is not sufficient and just hides bugs. However it does pretty
189 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000190 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000191 return false;
192
193 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000194 if (isa<UndefValue>(ICmp->getOperand(0)) ||
195 isa<UndefValue>(ICmp->getOperand(1)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000196 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000197
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000198 const SCEV *LHS = SE->getSCEV(ICmp->getOperand(0));
199 const SCEV *RHS = SE->getSCEV(ICmp->getOperand(1));
Tobias Grosser75805372011-04-29 06:27:02 +0000200
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000201 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
202 !isAffineExpr(&Context.CurRegion, RHS, *SE))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000203 INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000204 << "' with LHS: " << *LHS << " and RHS: " << *RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000205 }
206
207 // Allow loop exit conditions.
208 Loop *L = LI->getLoopFor(&BB);
209 if (L && L->getExitingBlock() == &BB)
210 return true;
211
212 // Allow perfectly nested conditions.
213 Region *R = RI->getRegionFor(&BB);
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000214 if (R->getEntry() != &BB)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000215 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000216
217 return true;
218}
219
220bool ScopDetection::isValidCallInst(CallInst &CI) {
221 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
222 return false;
223
224 if (CI.doesNotAccessMemory())
225 return true;
226
227 Function *CalledFunction = CI.getCalledFunction();
228
229 // Indirect calls are not supported.
230 if (CalledFunction == 0)
231 return false;
232
233 // TODO: Intrinsics.
234 return false;
235}
236
237bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
238 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000239 Value *Ptr = getPointerOperand(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000240 const SCEV *AccessFunction = SE->getSCEV(Ptr);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000241 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000242 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000243
Tobias Grosserb8710b52011-11-10 12:44:50 +0000244 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
245
246 if (!BasePointer)
247 INVALID(AffFunc, "No base pointer");
248
249 BaseValue = BasePointer->getValue();
250
251 if (isa<UndefValue>(BaseValue))
252 INVALID(AffFunc, "Undefined base pointer");
253
254 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
255
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000256 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue) &&
257 !AllowNonAffine)
Tobias Grossereeb776a2012-09-08 14:00:37 +0000258 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000259
260 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
261 // created by IndependentBlocks Pass.
Tobias Grossere5e171e2011-11-10 12:45:03 +0000262 if (isa<IntToPtrInst>(BaseValue))
263 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser75805372011-04-29 06:27:02 +0000264
265 // Check if the base pointer of the memory access does alias with
266 // any other pointer. This cannot be handled at the moment.
267 AliasSet &AS =
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000268 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
269 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000270
271 // INVALID triggers an assertion in verifying mode, if it detects that a SCoP
272 // was detected by SCoP detection and that this SCoP was invalidated by a pass
273 // that stated it would preserve the SCoPs.
274 // We disable this check as the independent blocks pass may create memory
275 // references which seem to alias, if -basicaa is not available. They actually
276 // do not, but as we can not proof this without -basicaa we would fail. We
277 // disable this check to not cause irrelevant verification failures.
Tobias Grosser428b3e42013-02-04 15:46:25 +0000278 if (!AS.isMustAlias() && !IgnoreAliasing) {
279 std::string Message;
280 raw_string_ostream OS(Message);
281
282 OS << "Possible aliasing: ";
283
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000284 std::vector<Value *> Pointers;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000285
286 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
287 Pointers.push_back(AI.getPointer());
288
289 std::sort(Pointers.begin(), Pointers.end());
290
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000291 for (std::vector<Value *>::iterator PI = Pointers.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000292 PE = Pointers.end();
293 ;) {
Tobias Grosser428b3e42013-02-04 15:46:25 +0000294 Value *V = *PI;
295
296 if (V->getName().size() == 0)
297 OS << "\"" << *V << "\"";
298 else
299 OS << "\"" << V->getName() << "\"";
300
301 ++PI;
302
303 if (PI != PE)
304 OS << ", ";
305 else
306 break;
307 }
308
Tobias Grosser84b81de2013-03-19 21:44:07 +0000309 INVALID_NOVERIFY(Alias, OS.str());
Tobias Grosser428b3e42013-02-04 15:46:25 +0000310 }
Tobias Grosser75805372011-04-29 06:27:02 +0000311
312 return true;
313}
314
Tobias Grosser75805372011-04-29 06:27:02 +0000315bool ScopDetection::hasScalarDependency(Instruction &Inst,
316 Region &RefRegion) const {
317 for (Instruction::use_iterator UI = Inst.use_begin(), UE = Inst.use_end();
318 UI != UE; ++UI)
319 if (Instruction *Use = dyn_cast<Instruction>(*UI))
320 if (!RefRegion.contains(Use->getParent())) {
321 // DirtyHack 1: PHINode user outside the Scop is not allow, if this
322 // PHINode is induction variable, the scalar to array transform may
323 // break it and introduce a non-indvar PHINode, which is not allow in
324 // Scop.
325 // This can be fix by:
326 // Introduce a IndependentBlockPrepare pass, which translate all
327 // PHINodes not in Scop to array.
328 // The IndependentBlockPrepare pass can also split the entry block of
329 // the function to hold the alloca instruction created by scalar to
330 // array. and split the exit block of the Scop so the new create load
331 // instruction for escape users will not break other Scops.
332 if (isa<PHINode>(Use))
333 return true;
334 }
335
336 return false;
337}
338
339bool ScopDetection::isValidInstruction(Instruction &Inst,
340 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000341 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000342 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
343 if (SCEVCodegen)
344 INVALID(IndVar,
345 "SCEV of PHI node refers to SSA names in region: " << Inst);
346 else
347 INVALID(IndVar, "Non canonical PHI node: " << Inst);
348 }
Tobias Grosser75805372011-04-29 06:27:02 +0000349
350 // Scalar dependencies are not allowed.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000351 if (hasScalarDependency(Inst, Context.CurRegion))
352 INVALID(Scalar, "Scalar dependency found: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000353
354 // We only check the call instruction but not invoke instruction.
355 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
356 if (isValidCallInst(*CI))
357 return true;
358
Tobias Grosserb43ba822011-10-08 00:49:30 +0000359 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000360 }
361
362 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000363 if (isa<AllocaInst>(Inst))
Tobias Grosserb43ba822011-10-08 00:49:30 +0000364 INVALID(Other, "Alloca instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000365
366 return true;
367 }
368
369 // Check the access function.
370 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
371 return isValidMemoryAccess(Inst, Context);
372
373 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000374 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000375}
376
377bool ScopDetection::isValidBasicBlock(BasicBlock &BB,
378 DetectionContext &Context) const {
379 if (!isValidCFG(BB, Context))
380 return false;
381
382 // Check all instructions, except the terminator instruction.
383 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
384 if (!isValidInstruction(*I, Context))
385 return false;
386
387 Loop *L = LI->getLoopFor(&BB);
388 if (L && L->getHeader() == &BB && !isValidLoop(L, Context))
389 return false;
390
391 return true;
392}
393
394bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000395 if (!SCEVCodegen) {
396 // If code generation is not in scev based mode, we need to ensure that
397 // each loop has a canonical induction variable.
398 PHINode *IndVar = L->getCanonicalInductionVariable();
399 if (!IndVar)
400 INVALID(IndVar,
401 "No canonical IV at loop header: " << L->getHeader()->getName());
402 }
Tobias Grosser75805372011-04-29 06:27:02 +0000403
404 // Is the loop count affine?
405 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser120db6b2011-11-07 12:58:54 +0000406 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
Tobias Grosserbd54f322011-10-26 01:27:49 +0000407 INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000408 << L->getHeader()->getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000409
410 return true;
411}
412
413Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000414 // Initial no valid region was found (greater than R)
415 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000416 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000417
418 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
419
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000420 while (ExpandedRegion) {
421 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
422 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000423
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000424 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000425 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000426 // If the exit is valid check all blocks
427 // - if true, a valid region was found => store it + keep expanding
428 // - if false, .tbd. => stop (should this really end the loop?)
429 if (!allBlocksValid(Context))
430 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000431
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000432 // Delete unnecessary regions (allocated by getExpandedRegion)
433 if (LastValidRegion)
434 delete LastValidRegion;
435
436 // Store this region, because it is the greatest valid (encountered so far)
437 LastValidRegion = ExpandedRegion;
438
439 // Create and test the next greater region (if any)
440 ExpandedRegion = ExpandedRegion->getExpandedRegion();
441
442 } else {
443 // Create and test the next greater region (if any)
444 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
445
446 // Delete unnecessary regions (allocated by getExpandedRegion)
447 delete ExpandedRegion;
448
449 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000450 }
Tobias Grosser75805372011-04-29 06:27:02 +0000451 }
452
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000453 DEBUG(
454 if (LastValidRegion)
455 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
456 else
457 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
458 );
Tobias Grosser75805372011-04-29 06:27:02 +0000459
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000460 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000461}
462
Tobias Grosser75805372011-04-29 06:27:02 +0000463void ScopDetection::findScops(Region &R) {
464 DetectionContext Context(R, *AA, false /*verifying*/);
465
Tobias Grosser4eb73812011-11-10 12:45:15 +0000466 LastFailure = "";
467
Tobias Grosser75805372011-04-29 06:27:02 +0000468 if (isValidRegion(Context)) {
469 ++ValidRegion;
470 ValidRegions.insert(&R);
471 return;
472 }
473
Tobias Grosser4f129a62011-10-08 00:30:55 +0000474 InvalidRegions[&R] = LastFailure;
475
Tobias Grosser75805372011-04-29 06:27:02 +0000476 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
477 findScops(**I);
478
479 // Try to expand regions.
480 //
481 // As the region tree normally only contains canonical regions, non canonical
482 // regions that form a Scop are not found. Therefore, those non canonical
483 // regions are checked by expanding the canonical ones.
484
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000485 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000486
487 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
488 ToExpand.push_back(*I);
489
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000490 for (std::vector<Region *>::iterator RI = ToExpand.begin(),
491 RE = ToExpand.end();
492 RI != RE; ++RI) {
Tobias Grosser75805372011-04-29 06:27:02 +0000493 Region *CurrentRegion = *RI;
494
495 // Skip invalid regions. Regions may become invalid, if they are element of
496 // an already expanded region.
497 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
498 continue;
499
500 Region *ExpandedR = expandRegion(*CurrentRegion);
501
502 if (!ExpandedR)
503 continue;
504
505 R.addSubRegion(ExpandedR, true);
506 ValidRegions.insert(ExpandedR);
507 ValidRegions.erase(CurrentRegion);
508
509 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
510 ++I)
511 ValidRegions.erase(*I);
512 }
513}
514
515bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
516 Region &R = Context.CurRegion;
517
518 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
519 ++I)
Chandler Carruth30dfdfc2012-05-04 21:24:27 +0000520 if (!isValidBasicBlock(**I, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000521 return false;
522
523 return true;
524}
525
526bool ScopDetection::isValidExit(DetectionContext &Context) const {
527 Region &R = Context.CurRegion;
528
529 // PHI nodes are not allowed in the exit basic block.
530 if (BasicBlock *Exit = R.getExit()) {
531 BasicBlock::iterator I = Exit->begin();
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000532 if (I != Exit->end() && isa<PHINode>(*I))
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000533 INVALID(Other, "PHI node in exit BB");
Tobias Grosser75805372011-04-29 06:27:02 +0000534 }
535
536 return true;
537}
538
539bool ScopDetection::isValidRegion(DetectionContext &Context) const {
540 Region &R = Context.CurRegion;
541
542 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
543
544 // The toplevel region is no valid region.
545 if (!R.getParent()) {
546 DEBUG(dbgs() << "Top level region is invalid";
547 dbgs() << "\n");
548 return false;
549 }
550
Tobias Grosserd654c252012-04-10 18:12:19 +0000551 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000552 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000553 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
554 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser75805372011-04-29 06:27:02 +0000555
556 // Only a simple region is allowed.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000557 if (!R.isSimple())
558 INVALID(SimpleRegion, "Region not simple: " << R.getNameStr());
Tobias Grosser75805372011-04-29 06:27:02 +0000559
Hongbin Zheng94868e62012-04-07 12:29:17 +0000560 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000561 return false;
562
Hongbin Zheng94868e62012-04-07 12:29:17 +0000563 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000564 return false;
565
566 DEBUG(dbgs() << "OK\n");
567 return true;
568}
569
570bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000571 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000572}
573
Tobias Grosser531891e2012-11-01 16:45:20 +0000574void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
575 unsigned &LineEnd, std::string &FileName) {
576 LineBegin = -1;
577 LineEnd = 0;
578
579 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
580 RI != RE; ++RI)
581 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
582 ++BI) {
583 DebugLoc DL = BI->getDebugLoc();
584 if (DL.isUnknown())
585 continue;
586
587 DIScope Scope(DL.getScope(BI->getContext()));
588
589 if (FileName.empty())
590 FileName = Scope.getFilename();
591
592 unsigned NewLine = DL.getLine();
593
594 LineBegin = std::min(LineBegin, NewLine);
595 LineEnd = std::max(LineEnd, NewLine);
596 break;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000597 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000598}
599
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000600void ScopDetection::printLocations(llvm::Function &F) {
601 int NumberOfScops = std::distance(begin(), end());
602
603 if (NumberOfScops)
604 outs() << ":: Static control regions in " << F.getName() << "\n";
605
Tobias Grosser531891e2012-11-01 16:45:20 +0000606 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
607 unsigned LineEntry, LineExit;
608 std::string FileName;
609
610 getDebugLocation(*RI, LineEntry, LineExit, FileName);
611
612 if (FileName.empty()) {
613 outs() << "Scop detected at unknown location. Compile with debug info "
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000614 "(-g) to get more precise information. \n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000615 return;
616 }
617
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000618 outs() << FileName << ":" << LineEntry
619 << ": Start of static control region\n";
620 outs() << FileName << ":" << LineExit << ": End of static control region\n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000621 }
622}
623
Tobias Grosser75805372011-04-29 06:27:02 +0000624bool ScopDetection::runOnFunction(llvm::Function &F) {
625 AA = &getAnalysis<AliasAnalysis>();
626 SE = &getAnalysis<ScalarEvolution>();
627 LI = &getAnalysis<LoopInfo>();
628 RI = &getAnalysis<RegionInfo>();
629 Region *TopRegion = RI->getTopLevelRegion();
630
Tobias Grosser2ff87232011-10-23 11:17:06 +0000631 releaseMemory();
632
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000633 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000634 return false;
635
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000636 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000637 return false;
638
639 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000640
641 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000642 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000643
Tobias Grosser75805372011-04-29 06:27:02 +0000644 return false;
645}
646
Tobias Grosser75805372011-04-29 06:27:02 +0000647void polly::ScopDetection::verifyRegion(const Region &R) const {
648 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000649 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000650 isValidRegion(Context);
651}
652
653void polly::ScopDetection::verifyAnalysis() const {
654 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000655 E = ValidRegions.end();
656 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000657 verifyRegion(**I);
658}
659
660void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
661 AU.addRequired<DominatorTree>();
662 AU.addRequired<PostDominatorTree>();
663 AU.addRequired<LoopInfo>();
664 AU.addRequired<ScalarEvolution>();
665 // We also need AA and RegionInfo when we are verifying analysis.
666 AU.addRequiredTransitive<AliasAnalysis>();
667 AU.addRequiredTransitive<RegionInfo>();
668 AU.setPreservesAll();
669}
670
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000671void ScopDetection::print(raw_ostream &OS, const Module *)const {
Tobias Grosser75805372011-04-29 06:27:02 +0000672 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000673 E = ValidRegions.end();
674 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000675 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
676
677 OS << "\n";
678}
679
680void ScopDetection::releaseMemory() {
681 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000682 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000683 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000684}
685
686char ScopDetection::ID = 0;
687
Tobias Grosser73600b82011-10-08 00:30:40 +0000688INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
689 "Polly - Detect static control parts (SCoPs)", false,
690 false)
691INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
692INITIALIZE_PASS_DEPENDENCY(DominatorTree)
693INITIALIZE_PASS_DEPENDENCY(LoopInfo)
694INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
695INITIALIZE_PASS_DEPENDENCY(RegionInfo)
696INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
697INITIALIZE_PASS_END(ScopDetection, "polly-detect",
698 "Polly - Detect static control parts (SCoPs)", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +0000699
Tobias Grosser83f5c432011-08-23 22:35:08 +0000700Pass *polly::createScopDetectionPass() {
701 return new ScopDetection();
702}