1 //===----- 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 
47 #include "polly/CodeGen/BlockGenerators.h"
48 #include "polly/LinkAllPasses.h"
49 #include "polly/ScopDetection.h"
50 #include "polly/Support/ScopHelper.h"
51 #include "polly/Support/SCEVValidator.h"
52 
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/RegionIterator.h"
58 #include "llvm/Analysis/ScalarEvolution.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/DebugInfo.h"
61 #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 
67 #include <set>
68 
69 using namespace llvm;
70 using namespace polly;
71 
72 static cl::opt<std::string>
73 OnlyFunction("polly-detect-only", cl::desc("Only detect scops in function"),
74              cl::Hidden, cl::value_desc("The function name to detect scops in"),
75              cl::ValueRequired, cl::init(""));
76 
77 static cl::opt<bool>
78 IgnoreAliasing("polly-ignore-aliasing",
79                cl::desc("Ignore possible aliasing of the array bases"),
80                cl::Hidden, cl::init(false));
81 
82 static cl::opt<bool>
83 ReportLevel("polly-report", cl::desc("Print information about Polly"),
84             cl::Hidden, cl::init(false));
85 
86 static cl::opt<bool>
87 AllowNonAffine("polly-allow-nonaffine",
88                cl::desc("Allow non affine access functions in arrays"),
89                cl::Hidden, cl::init(false));
90 
91 //===----------------------------------------------------------------------===//
92 // Statistics.
93 
94 STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
95 
96 #define BADSCOP_STAT(NAME, DESC)                                               \
97   STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
98 
99 #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;                                                              \
112   } while (0)
113 
114 #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;                                                              \
127   } while (0)
128 
129 BADSCOP_STAT(CFG, "CFG too complex");
130 BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
131 BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
132 BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
133 BADSCOP_STAT(AffFunc, "Expression not affine");
134 BADSCOP_STAT(Scalar, "Found scalar dependency");
135 BADSCOP_STAT(Alias, "Found base address alias");
136 BADSCOP_STAT(SimpleRegion, "Region not simple");
137 BADSCOP_STAT(Other, "Others");
138 
139 //===----------------------------------------------------------------------===//
140 // ScopDetection.
141 bool 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 
146 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
147   if (!InvalidRegions.count(R))
148     return "";
149 
150   return InvalidRegions.find(R)->second;
151 }
152 
153 bool ScopDetection::isValidCFG(BasicBlock &BB,
154                                DetectionContext &Context) const {
155   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 
164   if (!Br)
165     INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
166 
167   if (Br->isUnconditional())
168     return true;
169 
170   Value *Condition = Br->getCondition();
171 
172   // UndefValue is not allowed as condition.
173   if (isa<UndefValue>(Condition))
174     INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
175 
176   // Only Constant and ICmpInst are allowed as condition.
177   if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
178     INVALID(AffFunc, "Condition in BB '" + BB.getName() + "' neither "
179                      "constant nor an icmp instruction");
180 
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.
190     if (ICmp->isUnsigned())
191       return false;
192 
193     // Are both operands of the ICmp affine?
194     if (isa<UndefValue>(ICmp->getOperand(0)) ||
195         isa<UndefValue>(ICmp->getOperand(1)))
196       INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
197 
198     const SCEV *LHS = SE->getSCEV(ICmp->getOperand(0));
199     const SCEV *RHS = SE->getSCEV(ICmp->getOperand(1));
200 
201     if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
202         !isAffineExpr(&Context.CurRegion, RHS, *SE))
203       INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
204                         << "' with LHS: " << *LHS << " and RHS: " << *RHS);
205   }
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);
214   if (R->getEntry() != &BB)
215     INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
216 
217   return true;
218 }
219 
220 bool 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 
237 bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
238                                         DetectionContext &Context) const {
239   Value *Ptr = getPointerOperand(Inst);
240   const SCEV *AccessFunction = SE->getSCEV(Ptr);
241   const SCEVUnknown *BasePointer;
242   Value *BaseValue;
243 
244   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 
256   if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue) &&
257       !AllowNonAffine)
258     INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
259 
260   // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
261   // created by IndependentBlocks Pass.
262   if (isa<IntToPtrInst>(BaseValue))
263     INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
264 
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 =
268       Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
269                                         Inst.getMetadata(LLVMContext::MD_tbaa));
270 
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.
278   if (!AS.isMustAlias() && !IgnoreAliasing) {
279     std::string Message;
280     raw_string_ostream OS(Message);
281 
282     OS << "Possible aliasing: ";
283 
284     std::vector<Value *> Pointers;
285 
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 
291     for (std::vector<Value *>::iterator PI = Pointers.begin(),
292                                         PE = Pointers.end();
293          ;) {
294       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 
309     INVALID_NOVERIFY(Alias, OS.str());
310   }
311 
312   return true;
313 }
314 
315 bool 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 
339 bool ScopDetection::isValidInstruction(Instruction &Inst,
340                                        DetectionContext &Context) const {
341   if (PHINode *PN = dyn_cast<PHINode>(&Inst))
342     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     }
349 
350   // Scalar dependencies are not allowed.
351   if (hasScalarDependency(Inst, Context.CurRegion))
352     INVALID(Scalar, "Scalar dependency found: " << Inst);
353 
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 
359     INVALID(FuncCall, "Call instruction: " << Inst);
360   }
361 
362   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
363     if (isa<AllocaInst>(Inst))
364       INVALID(Other, "Alloca instruction: " << Inst);
365 
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.
374   INVALID(Other, "Unknown instruction: " << Inst);
375 }
376 
377 bool 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 
394 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
395   PHINode *IndVar = L->getCanonicalInductionVariable();
396   // No canonical induction variable.
397   if (!IndVar)
398     INVALID(IndVar, "No canonical IV at loop header: "
399                     << L->getHeader()->getName());
400 
401   // Is the loop count affine?
402   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
403   if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
404     INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
405                        << L->getHeader()->getName());
406 
407   return true;
408 }
409 
410 Region *ScopDetection::expandRegion(Region &R) {
411   // Initial no valid region was found (greater than R)
412   Region *LastValidRegion = NULL;
413   Region *ExpandedRegion = R.getExpandedRegion();
414 
415   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
416 
417   while (ExpandedRegion) {
418     DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
419     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
420 
421     // Check the exit first (cheap)
422     if (isValidExit(Context)) {
423       // If the exit is valid check all blocks
424       //  - if true, a valid region was found => store it + keep expanding
425       //  - if false, .tbd. => stop  (should this really end the loop?)
426       if (!allBlocksValid(Context))
427         break;
428 
429       // Delete unnecessary regions (allocated by getExpandedRegion)
430       if (LastValidRegion)
431         delete LastValidRegion;
432 
433       // Store this region, because it is the greatest valid (encountered so far)
434       LastValidRegion = ExpandedRegion;
435 
436       // Create and test the next greater region (if any)
437       ExpandedRegion = ExpandedRegion->getExpandedRegion();
438 
439     } else {
440       // Create and test the next greater region (if any)
441       Region *TmpRegion = ExpandedRegion->getExpandedRegion();
442 
443       // Delete unnecessary regions (allocated by getExpandedRegion)
444       delete ExpandedRegion;
445 
446       ExpandedRegion = TmpRegion;
447     }
448   }
449 
450   DEBUG(
451   if (LastValidRegion)
452     dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
453   else
454     dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
455   );
456 
457   return LastValidRegion;
458 }
459 
460 void ScopDetection::findScops(Region &R) {
461   DetectionContext Context(R, *AA, false /*verifying*/);
462 
463   LastFailure = "";
464 
465   if (isValidRegion(Context)) {
466     ++ValidRegion;
467     ValidRegions.insert(&R);
468     return;
469   }
470 
471   InvalidRegions[&R] = LastFailure;
472 
473   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
474     findScops(**I);
475 
476   // Try to expand regions.
477   //
478   // As the region tree normally only contains canonical regions, non canonical
479   // regions that form a Scop are not found. Therefore, those non canonical
480   // regions are checked by expanding the canonical ones.
481 
482   std::vector<Region *> ToExpand;
483 
484   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
485     ToExpand.push_back(*I);
486 
487   for (std::vector<Region *>::iterator RI = ToExpand.begin(),
488                                        RE = ToExpand.end();
489        RI != RE; ++RI) {
490     Region *CurrentRegion = *RI;
491 
492     // Skip invalid regions. Regions may become invalid, if they are element of
493     // an already expanded region.
494     if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
495       continue;
496 
497     Region *ExpandedR = expandRegion(*CurrentRegion);
498 
499     if (!ExpandedR)
500       continue;
501 
502     R.addSubRegion(ExpandedR, true);
503     ValidRegions.insert(ExpandedR);
504     ValidRegions.erase(CurrentRegion);
505 
506     for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
507          ++I)
508       ValidRegions.erase(*I);
509   }
510 }
511 
512 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
513   Region &R = Context.CurRegion;
514 
515   for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
516        ++I)
517     if (!isValidBasicBlock(**I, Context))
518       return false;
519 
520   return true;
521 }
522 
523 bool ScopDetection::isValidExit(DetectionContext &Context) const {
524   Region &R = Context.CurRegion;
525 
526   // PHI nodes are not allowed in the exit basic block.
527   if (BasicBlock *Exit = R.getExit()) {
528     BasicBlock::iterator I = Exit->begin();
529     if (I != Exit->end() && isa<PHINode>(*I))
530       INVALID(Other, "PHI node in exit BB");
531   }
532 
533   return true;
534 }
535 
536 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
537   Region &R = Context.CurRegion;
538 
539   DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
540 
541   // The toplevel region is no valid region.
542   if (!R.getParent()) {
543     DEBUG(dbgs() << "Top level region is invalid";
544           dbgs() << "\n");
545     return false;
546   }
547 
548   // SCoP cannot contain the entry block of the function, because we need
549   // to insert alloca instruction there when translate scalar to array.
550   if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
551     INVALID(Other, "Region containing entry block of function is invalid!");
552 
553   // Only a simple region is allowed.
554   if (!R.isSimple())
555     INVALID(SimpleRegion, "Region not simple: " << R.getNameStr());
556 
557   if (!isValidExit(Context))
558     return false;
559 
560   if (!allBlocksValid(Context))
561     return false;
562 
563   DEBUG(dbgs() << "OK\n");
564   return true;
565 }
566 
567 bool ScopDetection::isValidFunction(llvm::Function &F) {
568   return !InvalidFunctions.count(&F);
569 }
570 
571 void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
572                                      unsigned &LineEnd, std::string &FileName) {
573   LineBegin = -1;
574   LineEnd = 0;
575 
576   for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
577        RI != RE; ++RI)
578     for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
579          ++BI) {
580       DebugLoc DL = BI->getDebugLoc();
581       if (DL.isUnknown())
582         continue;
583 
584       DIScope Scope(DL.getScope(BI->getContext()));
585 
586       if (FileName.empty())
587         FileName = Scope.getFilename();
588 
589       unsigned NewLine = DL.getLine();
590 
591       LineBegin = std::min(LineBegin, NewLine);
592       LineEnd = std::max(LineEnd, NewLine);
593       break;
594     }
595 }
596 
597 void ScopDetection::printLocations(llvm::Function &F) {
598   int NumberOfScops = std::distance(begin(), end());
599 
600   if (NumberOfScops)
601     outs() << ":: Static control regions in " << F.getName() << "\n";
602 
603   for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
604     unsigned LineEntry, LineExit;
605     std::string FileName;
606 
607     getDebugLocation(*RI, LineEntry, LineExit, FileName);
608 
609     if (FileName.empty()) {
610       outs() << "Scop detected at unknown location. Compile with debug info "
611                 "(-g) to get more precise information. \n";
612       return;
613     }
614 
615     outs() << FileName << ":" << LineEntry
616            << ": Start of static control region\n";
617     outs() << FileName << ":" << LineExit << ": End of static control region\n";
618   }
619 }
620 
621 bool ScopDetection::runOnFunction(llvm::Function &F) {
622   AA = &getAnalysis<AliasAnalysis>();
623   SE = &getAnalysis<ScalarEvolution>();
624   LI = &getAnalysis<LoopInfo>();
625   RI = &getAnalysis<RegionInfo>();
626   Region *TopRegion = RI->getTopLevelRegion();
627 
628   releaseMemory();
629 
630   if (OnlyFunction != "" && F.getName() != OnlyFunction)
631     return false;
632 
633   if (!isValidFunction(F))
634     return false;
635 
636   findScops(*TopRegion);
637 
638   if (ReportLevel >= 1)
639     printLocations(F);
640 
641   return false;
642 }
643 
644 void polly::ScopDetection::verifyRegion(const Region &R) const {
645   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
646   DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
647   isValidRegion(Context);
648 }
649 
650 void polly::ScopDetection::verifyAnalysis() const {
651   for (RegionSet::const_iterator I = ValidRegions.begin(),
652                                  E = ValidRegions.end();
653        I != E; ++I)
654     verifyRegion(**I);
655 }
656 
657 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
658   AU.addRequired<DominatorTree>();
659   AU.addRequired<PostDominatorTree>();
660   AU.addRequired<LoopInfo>();
661   AU.addRequired<ScalarEvolution>();
662   // We also need AA and RegionInfo when we are verifying analysis.
663   AU.addRequiredTransitive<AliasAnalysis>();
664   AU.addRequiredTransitive<RegionInfo>();
665   AU.setPreservesAll();
666 }
667 
668 void ScopDetection::print(raw_ostream &OS, const Module *)const {
669   for (RegionSet::const_iterator I = ValidRegions.begin(),
670                                  E = ValidRegions.end();
671        I != E; ++I)
672     OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
673 
674   OS << "\n";
675 }
676 
677 void ScopDetection::releaseMemory() {
678   ValidRegions.clear();
679   InvalidRegions.clear();
680   // Do not clear the invalid function set.
681 }
682 
683 char ScopDetection::ID = 0;
684 
685 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
686                       "Polly - Detect static control parts (SCoPs)", false,
687                       false)
688 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
689 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
690 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
691 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
692 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
693 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
694 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
695                     "Polly - Detect static control parts (SCoPs)", false, false)
696 
697 Pass *polly::createScopDetectionPass() {
698   return new ScopDetection();
699 }
700