blob: 2e3ed06b34284302b0d5a454c82298b9cc3bbc83 [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 Grosser75805372011-04-29 06:27:02 +000051#include "polly/Support/ScopHelper.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053
Chandler Carruth535d52c2013-01-02 11:47:44 +000054#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser531891e2012-11-01 16:45:20 +000061#include "llvm/DebugInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000062#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 Grosser637bd632013-05-07 07:31:10 +000073OnlyFunction("polly-only-func", cl::desc("Only run on a single function"),
74 cl::value_desc("function-name"), cl::ValueRequired, cl::init(""),
75 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000076
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"),
Tobias Grosser637bd632013-05-07 07:31:10 +000080 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000081
Tobias Grosser637bd632013-05-07 07:31:10 +000082static cl::opt<bool>
83ReportLevel("polly-report",
84 cl::desc("Print information about the activities of Polly"),
85 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +000086
87static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000088AllowNonAffine("polly-allow-nonaffine",
89 cl::desc("Allow non affine access functions in arrays"),
Tobias Grosser637bd632013-05-07 07:31:10 +000090 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +000091
Tobias Grosser75805372011-04-29 06:27:02 +000092//===----------------------------------------------------------------------===//
93// Statistics.
94
95STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
96
Tobias Grosser74394f02013-01-14 22:40:23 +000097#define BADSCOP_STAT(NAME, DESC) \
98 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +000099
Tobias Grosser74394f02013-01-14 22:40:23 +0000100#define INVALID(NAME, MESSAGE) \
101 do { \
102 std::string Buf; \
103 raw_string_ostream fmt(Buf); \
104 fmt << MESSAGE; \
105 fmt.flush(); \
106 LastFailure = Buf; \
107 DEBUG(dbgs() << MESSAGE); \
108 DEBUG(dbgs() << "\n"); \
109 assert(!Context.Verifying && #NAME); \
110 if (!Context.Verifying) \
111 ++Bad##NAME##ForScop; \
112 return false; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000113 } while (0)
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000114
Tobias Grosser74394f02013-01-14 22:40:23 +0000115#define INVALID_NOVERIFY(NAME, MESSAGE) \
116 do { \
117 std::string Buf; \
118 raw_string_ostream fmt(Buf); \
119 fmt << MESSAGE; \
120 fmt.flush(); \
121 LastFailure = Buf; \
122 DEBUG(dbgs() << MESSAGE); \
123 DEBUG(dbgs() << "\n"); \
124 /* DISABLED: assert(!Context.Verifying && #NAME); */ \
125 if (!Context.Verifying) \
126 ++Bad##NAME##ForScop; \
127 return false; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000128 } while (0)
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000129
Tobias Grosser74394f02013-01-14 22:40:23 +0000130BADSCOP_STAT(CFG, "CFG too complex");
131BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
132BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
133BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
134BADSCOP_STAT(AffFunc, "Expression not affine");
135BADSCOP_STAT(Scalar, "Found scalar dependency");
136BADSCOP_STAT(Alias, "Found base address alias");
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000137BADSCOP_STAT(SimpleLoop, "Loop not in -loop-simplify form");
Tobias Grosser74394f02013-01-14 22:40:23 +0000138BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000139
140//===----------------------------------------------------------------------===//
141// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000142bool ScopDetection::isMaxRegionInScop(const Region &R) const {
143 // The Region is valid only if it could be found in the set.
144 return ValidRegions.count(&R);
145}
146
Tobias Grosser4f129a62011-10-08 00:30:55 +0000147std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
148 if (!InvalidRegions.count(R))
149 return "";
150
151 return InvalidRegions.find(R)->second;
152}
153
Tobias Grossere602a072013-05-07 07:30:56 +0000154bool ScopDetection::isValidCFG(BasicBlock &BB,
155 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000156 Region &RefRegion = Context.CurRegion;
157 TerminatorInst *TI = BB.getTerminator();
158
159 // Return instructions are only valid if the region is the top level region.
160 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
161 return true;
162
163 BranchInst *Br = dyn_cast<BranchInst>(TI);
164
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000165 if (!Br)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000166 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000167
Tobias Grosser74394f02013-01-14 22:40:23 +0000168 if (Br->isUnconditional())
169 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000170
171 Value *Condition = Br->getCondition();
172
173 // UndefValue is not allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000174 if (isa<UndefValue>(Condition))
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000175 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000176
177 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000178 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000179 INVALID(AffFunc, "Condition in BB '" + BB.getName() +
Tobias Grosserd7e58642013-04-10 06:55:45 +0000180 "' neither constant nor an icmp instruction");
Tobias Grosser75805372011-04-29 06:27:02 +0000181
182 // Allow perfectly nested conditions.
183 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
184
185 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
186 // Unsigned comparisons are not allowed. They trigger overflow problems
187 // in the code generation.
188 //
189 // TODO: This is not sufficient and just hides bugs. However it does pretty
190 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000191 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000192 return false;
193
194 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000195 if (isa<UndefValue>(ICmp->getOperand(0)) ||
196 isa<UndefValue>(ICmp->getOperand(1)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000197 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000198
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000199 Loop *L = LI->getLoopFor(ICmp->getParent());
200 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
201 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000202
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000203 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
204 !isAffineExpr(&Context.CurRegion, RHS, *SE))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000205 INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000206 << "' with LHS: " << *LHS
207 << " and RHS: " << *RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000208 }
209
210 // Allow loop exit conditions.
211 Loop *L = LI->getLoopFor(&BB);
212 if (L && L->getExitingBlock() == &BB)
213 return true;
214
215 // Allow perfectly nested conditions.
216 Region *R = RI->getRegionFor(&BB);
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000217 if (R->getEntry() != &BB)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000218 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000219
220 return true;
221}
222
223bool ScopDetection::isValidCallInst(CallInst &CI) {
224 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
225 return false;
226
227 if (CI.doesNotAccessMemory())
228 return true;
229
230 Function *CalledFunction = CI.getCalledFunction();
231
232 // Indirect calls are not supported.
233 if (CalledFunction == 0)
234 return false;
235
236 // TODO: Intrinsics.
237 return false;
238}
239
240bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
241 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000242 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000243 Loop *L = LI->getLoopFor(Inst.getParent());
244 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000245 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000246 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000247
Tobias Grosserb8710b52011-11-10 12:44:50 +0000248 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
249
250 if (!BasePointer)
251 INVALID(AffFunc, "No base pointer");
252
253 BaseValue = BasePointer->getValue();
254
255 if (isa<UndefValue>(BaseValue))
256 INVALID(AffFunc, "Undefined base pointer");
257
258 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
259
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000260 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue) &&
261 !AllowNonAffine)
Tobias Grossereeb776a2012-09-08 14:00:37 +0000262 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000263
264 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
265 // created by IndependentBlocks Pass.
Tobias Grossere5e171e2011-11-10 12:45:03 +0000266 if (isa<IntToPtrInst>(BaseValue))
267 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser75805372011-04-29 06:27:02 +0000268
269 // Check if the base pointer of the memory access does alias with
270 // any other pointer. This cannot be handled at the moment.
271 AliasSet &AS =
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000272 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
273 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000274
275 // INVALID triggers an assertion in verifying mode, if it detects that a SCoP
276 // was detected by SCoP detection and that this SCoP was invalidated by a pass
277 // that stated it would preserve the SCoPs.
278 // We disable this check as the independent blocks pass may create memory
279 // references which seem to alias, if -basicaa is not available. They actually
280 // do not, but as we can not proof this without -basicaa we would fail. We
281 // disable this check to not cause irrelevant verification failures.
Tobias Grosser428b3e42013-02-04 15:46:25 +0000282 if (!AS.isMustAlias() && !IgnoreAliasing) {
283 std::string Message;
284 raw_string_ostream OS(Message);
285
286 OS << "Possible aliasing: ";
287
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000288 std::vector<Value *> Pointers;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000289
290 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
291 Pointers.push_back(AI.getPointer());
292
293 std::sort(Pointers.begin(), Pointers.end());
294
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000295 for (std::vector<Value *>::iterator PI = Pointers.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000296 PE = Pointers.end();
297 ;) {
Tobias Grosser428b3e42013-02-04 15:46:25 +0000298 Value *V = *PI;
299
300 if (V->getName().size() == 0)
301 OS << "\"" << *V << "\"";
302 else
303 OS << "\"" << V->getName() << "\"";
304
305 ++PI;
306
307 if (PI != PE)
308 OS << ", ";
309 else
310 break;
311 }
312
Tobias Grosser84b81de2013-03-19 21:44:07 +0000313 INVALID_NOVERIFY(Alias, OS.str());
Tobias Grosser428b3e42013-02-04 15:46:25 +0000314 }
Tobias Grosser75805372011-04-29 06:27:02 +0000315
316 return true;
317}
318
Tobias Grossere602a072013-05-07 07:30:56 +0000319bool ScopDetection::hasScalarDependency(Instruction &Inst,
320 Region &RefRegion) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000321 for (Instruction::use_iterator UI = Inst.use_begin(), UE = Inst.use_end();
322 UI != UE; ++UI)
323 if (Instruction *Use = dyn_cast<Instruction>(*UI))
324 if (!RefRegion.contains(Use->getParent())) {
325 // DirtyHack 1: PHINode user outside the Scop is not allow, if this
326 // PHINode is induction variable, the scalar to array transform may
327 // break it and introduce a non-indvar PHINode, which is not allow in
328 // Scop.
329 // This can be fix by:
330 // Introduce a IndependentBlockPrepare pass, which translate all
331 // PHINodes not in Scop to array.
332 // The IndependentBlockPrepare pass can also split the entry block of
333 // the function to hold the alloca instruction created by scalar to
334 // array. and split the exit block of the Scop so the new create load
335 // instruction for escape users will not break other Scops.
336 if (isa<PHINode>(Use))
337 return true;
338 }
339
340 return false;
341}
342
343bool ScopDetection::isValidInstruction(Instruction &Inst,
344 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000345 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000346 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
347 if (SCEVCodegen)
348 INVALID(IndVar,
349 "SCEV of PHI node refers to SSA names in region: " << Inst);
350 else
351 INVALID(IndVar, "Non canonical PHI node: " << Inst);
352 }
Tobias Grosser75805372011-04-29 06:27:02 +0000353
354 // Scalar dependencies are not allowed.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000355 if (hasScalarDependency(Inst, Context.CurRegion))
356 INVALID(Scalar, "Scalar dependency found: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000357
358 // We only check the call instruction but not invoke instruction.
359 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
360 if (isValidCallInst(*CI))
361 return true;
362
Tobias Grosserb43ba822011-10-08 00:49:30 +0000363 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000364 }
365
366 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000367 if (isa<AllocaInst>(Inst))
Tobias Grosserb43ba822011-10-08 00:49:30 +0000368 INVALID(Other, "Alloca instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000369
370 return true;
371 }
372
373 // Check the access function.
374 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
375 return isValidMemoryAccess(Inst, Context);
376
377 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000378 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000379}
380
381bool ScopDetection::isValidBasicBlock(BasicBlock &BB,
382 DetectionContext &Context) const {
383 if (!isValidCFG(BB, Context))
384 return false;
385
386 // Check all instructions, except the terminator instruction.
387 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
388 if (!isValidInstruction(*I, Context))
389 return false;
390
391 Loop *L = LI->getLoopFor(&BB);
392 if (L && L->getHeader() == &BB && !isValidLoop(L, Context))
393 return false;
394
395 return true;
396}
397
398bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000399 if (!SCEVCodegen) {
400 // If code generation is not in scev based mode, we need to ensure that
401 // each loop has a canonical induction variable.
402 PHINode *IndVar = L->getCanonicalInductionVariable();
403 if (!IndVar)
404 INVALID(IndVar,
405 "No canonical IV at loop header: " << L->getHeader()->getName());
406 }
Tobias Grosser75805372011-04-29 06:27:02 +0000407
408 // Is the loop count affine?
409 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser120db6b2011-11-07 12:58:54 +0000410 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000411 INVALID(LoopBound,
412 "Non affine loop bound '"
Tobias Grosserd7e58642013-04-10 06:55:45 +0000413 << *LoopCount << "' in loop: " << L->getHeader()->getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000414
415 return true;
416}
417
418Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000419 // Initial no valid region was found (greater than R)
420 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000421 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000422
423 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
424
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000425 while (ExpandedRegion) {
426 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
427 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000428
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000429 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000430 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000431 // If the exit is valid check all blocks
432 // - if true, a valid region was found => store it + keep expanding
433 // - if false, .tbd. => stop (should this really end the loop?)
434 if (!allBlocksValid(Context))
435 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000437 // Delete unnecessary regions (allocated by getExpandedRegion)
438 if (LastValidRegion)
439 delete LastValidRegion;
440
Tobias Grosserd7e58642013-04-10 06:55:45 +0000441 // Store this region, because it is the greatest valid (encountered so
442 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000443 LastValidRegion = ExpandedRegion;
444
445 // Create and test the next greater region (if any)
446 ExpandedRegion = ExpandedRegion->getExpandedRegion();
447
448 } else {
449 // Create and test the next greater region (if any)
450 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
451
452 // Delete unnecessary regions (allocated by getExpandedRegion)
453 delete ExpandedRegion;
454
455 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000456 }
Tobias Grosser75805372011-04-29 06:27:02 +0000457 }
458
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000459 DEBUG(if (LastValidRegion)
Tobias Grosserd7e58642013-04-10 06:55:45 +0000460 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000461 else dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";);
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000463 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000464}
465
Tobias Grosser75805372011-04-29 06:27:02 +0000466void ScopDetection::findScops(Region &R) {
467 DetectionContext Context(R, *AA, false /*verifying*/);
468
Tobias Grosser4eb73812011-11-10 12:45:15 +0000469 LastFailure = "";
470
Tobias Grosser75805372011-04-29 06:27:02 +0000471 if (isValidRegion(Context)) {
472 ++ValidRegion;
473 ValidRegions.insert(&R);
474 return;
475 }
476
Tobias Grosser4f129a62011-10-08 00:30:55 +0000477 InvalidRegions[&R] = LastFailure;
478
Tobias Grosser75805372011-04-29 06:27:02 +0000479 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
480 findScops(**I);
481
482 // Try to expand regions.
483 //
484 // As the region tree normally only contains canonical regions, non canonical
485 // regions that form a Scop are not found. Therefore, those non canonical
486 // regions are checked by expanding the canonical ones.
487
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000488 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000489
490 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
491 ToExpand.push_back(*I);
492
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000493 for (std::vector<Region *>::iterator RI = ToExpand.begin(),
494 RE = ToExpand.end();
495 RI != RE; ++RI) {
Tobias Grosser75805372011-04-29 06:27:02 +0000496 Region *CurrentRegion = *RI;
497
498 // Skip invalid regions. Regions may become invalid, if they are element of
499 // an already expanded region.
500 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
501 continue;
502
503 Region *ExpandedR = expandRegion(*CurrentRegion);
504
505 if (!ExpandedR)
506 continue;
507
508 R.addSubRegion(ExpandedR, true);
509 ValidRegions.insert(ExpandedR);
510 ValidRegions.erase(CurrentRegion);
511
512 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
513 ++I)
514 ValidRegions.erase(*I);
515 }
516}
517
518bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
519 Region &R = Context.CurRegion;
520
521 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
522 ++I)
Chandler Carruth30dfdfc2012-05-04 21:24:27 +0000523 if (!isValidBasicBlock(**I, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000524 return false;
525
526 return true;
527}
528
529bool ScopDetection::isValidExit(DetectionContext &Context) const {
530 Region &R = Context.CurRegion;
531
532 // PHI nodes are not allowed in the exit basic block.
533 if (BasicBlock *Exit = R.getExit()) {
534 BasicBlock::iterator I = Exit->begin();
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000535 if (I != Exit->end() && isa<PHINode>(*I))
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000536 INVALID(Other, "PHI node in exit BB");
Tobias Grosser75805372011-04-29 06:27:02 +0000537 }
538
539 return true;
540}
541
542bool ScopDetection::isValidRegion(DetectionContext &Context) const {
543 Region &R = Context.CurRegion;
544
545 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
546
547 // The toplevel region is no valid region.
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000548 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000549 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000550 return false;
551 }
552
Tobias Grossere602a072013-05-07 07:30:56 +0000553 if (!R.getEnteringBlock()) {
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000554 Loop *L = LI->getLoopFor(R.getEntry());
555 if (L && !L->isLoopSimplifyForm())
556 INVALID(SimpleLoop, "Loop not in simplify form is invalid!");
557 }
558
Tobias Grosserd654c252012-04-10 18:12:19 +0000559 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000560 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000561 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
562 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser75805372011-04-29 06:27:02 +0000563
Hongbin Zheng94868e62012-04-07 12:29:17 +0000564 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000565 return false;
566
Hongbin Zheng94868e62012-04-07 12:29:17 +0000567 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000568 return false;
569
570 DEBUG(dbgs() << "OK\n");
571 return true;
572}
573
574bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000575 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000576}
577
Tobias Grosser531891e2012-11-01 16:45:20 +0000578void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
579 unsigned &LineEnd, std::string &FileName) {
580 LineBegin = -1;
581 LineEnd = 0;
582
583 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
584 RI != RE; ++RI)
585 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
586 ++BI) {
587 DebugLoc DL = BI->getDebugLoc();
588 if (DL.isUnknown())
589 continue;
590
591 DIScope Scope(DL.getScope(BI->getContext()));
592
593 if (FileName.empty())
594 FileName = Scope.getFilename();
595
596 unsigned NewLine = DL.getLine();
597
598 LineBegin = std::min(LineBegin, NewLine);
599 LineEnd = std::max(LineEnd, NewLine);
600 break;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000601 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000602}
603
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000604void ScopDetection::printLocations(llvm::Function &F) {
605 int NumberOfScops = std::distance(begin(), end());
606
607 if (NumberOfScops)
608 outs() << ":: Static control regions in " << F.getName() << "\n";
609
Tobias Grosser531891e2012-11-01 16:45:20 +0000610 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
611 unsigned LineEntry, LineExit;
612 std::string FileName;
613
614 getDebugLocation(*RI, LineEntry, LineExit, FileName);
615
616 if (FileName.empty()) {
617 outs() << "Scop detected at unknown location. Compile with debug info "
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000618 "(-g) to get more precise information. \n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000619 return;
620 }
621
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000622 outs() << FileName << ":" << LineEntry
623 << ": Start of static control region\n";
624 outs() << FileName << ":" << LineExit << ": End of static control region\n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000625 }
626}
627
Tobias Grosser75805372011-04-29 06:27:02 +0000628bool ScopDetection::runOnFunction(llvm::Function &F) {
629 AA = &getAnalysis<AliasAnalysis>();
630 SE = &getAnalysis<ScalarEvolution>();
631 LI = &getAnalysis<LoopInfo>();
632 RI = &getAnalysis<RegionInfo>();
633 Region *TopRegion = RI->getTopLevelRegion();
634
Tobias Grosser2ff87232011-10-23 11:17:06 +0000635 releaseMemory();
636
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000637 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000638 return false;
639
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000640 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000641 return false;
642
643 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000644
645 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000646 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000647
Tobias Grosser75805372011-04-29 06:27:02 +0000648 return false;
649}
650
Tobias Grosser75805372011-04-29 06:27:02 +0000651void polly::ScopDetection::verifyRegion(const Region &R) const {
652 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000653 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000654 isValidRegion(Context);
655}
656
657void polly::ScopDetection::verifyAnalysis() const {
658 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000659 E = ValidRegions.end();
660 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000661 verifyRegion(**I);
662}
663
664void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
665 AU.addRequired<DominatorTree>();
666 AU.addRequired<PostDominatorTree>();
667 AU.addRequired<LoopInfo>();
668 AU.addRequired<ScalarEvolution>();
669 // We also need AA and RegionInfo when we are verifying analysis.
670 AU.addRequiredTransitive<AliasAnalysis>();
671 AU.addRequiredTransitive<RegionInfo>();
672 AU.setPreservesAll();
673}
674
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000675void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000676 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000677 E = ValidRegions.end();
678 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000679 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
680
681 OS << "\n";
682}
683
684void ScopDetection::releaseMemory() {
685 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000686 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000687 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000688}
689
690char ScopDetection::ID = 0;
691
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000692Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
693
Tobias Grosser73600b82011-10-08 00:30:40 +0000694INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
695 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000696 false);
697INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
698INITIALIZE_PASS_DEPENDENCY(DominatorTree);
699INITIALIZE_PASS_DEPENDENCY(LoopInfo);
700INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
701INITIALIZE_PASS_DEPENDENCY(RegionInfo);
702INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000703INITIALIZE_PASS_END(ScopDetection, "polly-detect",
704 "Polly - Detect static control parts (SCoPs)", false, false)