LLVM  6.0.0svn
LoopExtractor.cpp
Go to the documentation of this file.
1 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
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 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
11 // top-level loop into its own new function. If the loop is the ONLY loop in a
12 // given function, it is not touched. This is a pass most useful for debugging
13 // via bugpoint.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Pass.h"
24 #include "llvm/Transforms/IPO.h"
25 #include "llvm/Transforms/Scalar.h"
28 #include <fstream>
29 #include <set>
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "loop-extract"
33 
34 STATISTIC(NumExtracted, "Number of loops extracted");
35 
36 namespace {
37  struct LoopExtractor : public LoopPass {
38  static char ID; // Pass identification, replacement for typeid
39  unsigned NumLoops;
40 
41  explicit LoopExtractor(unsigned numLoops = ~0)
42  : LoopPass(ID), NumLoops(numLoops) {
44  }
45 
46  bool runOnLoop(Loop *L, LPPassManager &) override;
47 
48  void getAnalysisUsage(AnalysisUsage &AU) const override {
53  }
54  };
55 }
56 
57 char LoopExtractor::ID = 0;
58 INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
59  "Extract loops into new functions", false, false)
60 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
61 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
63 INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
64  "Extract loops into new functions", false, false)
65 
66 namespace {
67  /// SingleLoopExtractor - For bugpoint.
68  struct SingleLoopExtractor : public LoopExtractor {
69  static char ID; // Pass identification, replacement for typeid
70  SingleLoopExtractor() : LoopExtractor(1) {}
71  };
72 } // End anonymous namespace
73 
75 INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
76  "Extract at most one loop into a new function", false, false)
77 
78 // createLoopExtractorPass - This pass extracts all natural loops from the
79 // program into a function if it can.
80 //
81 Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
82 
83 bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
84  if (skipLoop(L))
85  return false;
86 
87  // Only visit top-level loops.
88  if (L->getParentLoop())
89  return false;
90 
91  // If LoopSimplify form is not available, stay out of trouble.
92  if (!L->isLoopSimplifyForm())
93  return false;
94 
95  DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
96  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
97  bool Changed = false;
98 
99  // If there is more than one top-level loop in this function, extract all of
100  // the loops. Otherwise there is exactly one top-level loop; in this case if
101  // this function is more than a minimal wrapper around the loop, extract
102  // the loop.
103  bool ShouldExtractLoop = false;
104 
105  // Extract the loop if the entry block doesn't branch to the loop header.
106  TerminatorInst *EntryTI =
108  if (!isa<BranchInst>(EntryTI) ||
109  !cast<BranchInst>(EntryTI)->isUnconditional() ||
110  EntryTI->getSuccessor(0) != L->getHeader()) {
111  ShouldExtractLoop = true;
112  } else {
113  // Check to see if any exits from the loop are more than just return
114  // blocks.
115  SmallVector<BasicBlock*, 8> ExitBlocks;
116  L->getExitBlocks(ExitBlocks);
117  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
118  if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
119  ShouldExtractLoop = true;
120  break;
121  }
122  }
123 
124  if (ShouldExtractLoop) {
125  // We must omit EH pads. EH pads must accompany the invoke
126  // instruction. But this would result in a loop in the extracted
127  // function. An infinite cycle occurs when it tries to extract that loop as
128  // well.
129  SmallVector<BasicBlock*, 8> ExitBlocks;
130  L->getExitBlocks(ExitBlocks);
131  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
132  if (ExitBlocks[i]->isEHPad()) {
133  ShouldExtractLoop = false;
134  break;
135  }
136  }
137 
138  if (ShouldExtractLoop) {
139  if (NumLoops == 0) return Changed;
140  --NumLoops;
141  CodeExtractor Extractor(DT, *L);
142  if (Extractor.extractCodeRegion() != nullptr) {
143  Changed = true;
144  // After extraction, the loop is replaced by a function call, so
145  // we shouldn't try to run any more loop passes on it.
146  LPM.markLoopAsDeleted(*L);
147  LI.erase(L);
148  }
149  ++NumExtracted;
150  }
151 
152  return Changed;
153 }
154 
155 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
156 // program into a function if it can. This is used by bugpoint.
157 //
159  return new SingleLoopExtractor();
160 }
161 
162 
163 // BlockFile - A file which contains a list of blocks that should not be
164 // extracted.
166 BlockFile("extract-blocks-file", cl::value_desc("filename"),
167  cl::desc("A file containing list of basic blocks to not extract"),
168  cl::Hidden);
169 
170 namespace {
171  /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
172  /// from the module into their own functions except for those specified by the
173  /// BlocksToNotExtract list.
174  class BlockExtractorPass : public ModulePass {
175  void LoadFile(const char *Filename);
176  void SplitLandingPadPreds(Function *F);
177 
178  std::vector<BasicBlock*> BlocksToNotExtract;
179  std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
180  public:
181  static char ID; // Pass identification, replacement for typeid
182  BlockExtractorPass() : ModulePass(ID) {
183  if (!BlockFile.empty())
184  LoadFile(BlockFile.c_str());
185  }
186 
187  bool runOnModule(Module &M) override;
188  };
189 }
190 
191 char BlockExtractorPass::ID = 0;
192 INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
193  "Extract Basic Blocks From Module (for bugpoint use)",
194  false, false)
195 
196 // createBlockExtractorPass - This pass extracts all blocks (except those
197 // specified in the argument list) from the functions in the module.
198 //
200  return new BlockExtractorPass();
201 }
202 
203 void BlockExtractorPass::LoadFile(const char *Filename) {
204  // Load the BlockFile...
205  std::ifstream In(Filename);
206  if (!In.good()) {
207  errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
208  << "'!\n";
209  return;
210  }
211  while (In) {
212  std::string FunctionName, BlockName;
213  In >> FunctionName;
214  In >> BlockName;
215  if (!BlockName.empty())
216  BlocksToNotExtractByName.push_back(
217  std::make_pair(FunctionName, BlockName));
218  }
219 }
220 
221 /// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
222 /// instruction. The critical edge breaker will refuse to break critical edges
223 /// to a landing pad. So do them here. After this method runs, all landing pads
224 /// should have only one predecessor.
225 void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
226  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
228  if (!II) continue;
229  BasicBlock *Parent = II->getParent();
230  BasicBlock *LPad = II->getUnwindDest();
231 
232  // Look through the landing pad's predecessors. If one of them ends in an
233  // 'invoke', then we want to split the landing pad.
234  bool Split = false;
235  for (pred_iterator
236  PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
237  BasicBlock *BB = *PI;
238  if (BB->isLandingPad() && BB != Parent &&
239  isa<InvokeInst>(Parent->getTerminator())) {
240  Split = true;
241  break;
242  }
243  }
244 
245  if (!Split) continue;
246 
248  SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
249  }
250 }
251 
252 bool BlockExtractorPass::runOnModule(Module &M) {
253  if (skipModule(M))
254  return false;
255 
256  std::set<BasicBlock*> TranslatedBlocksToNotExtract;
257  for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
258  BasicBlock *BB = BlocksToNotExtract[i];
259  Function *F = BB->getParent();
260 
261  // Map the corresponding function in this module.
262  Function *MF = M.getFunction(F->getName());
263  assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
264 
265  // Figure out which index the basic block is in its function.
266  Function::iterator BBI = MF->begin();
267  std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
268  TranslatedBlocksToNotExtract.insert(&*BBI);
269  }
270 
271  while (!BlocksToNotExtractByName.empty()) {
272  // There's no way to find BBs by name without looking at every BB inside
273  // every Function. Fortunately, this is always empty except when used by
274  // bugpoint in which case correctness is more important than performance.
275 
276  std::string &FuncName = BlocksToNotExtractByName.back().first;
277  std::string &BlockName = BlocksToNotExtractByName.back().second;
278 
279  for (Function &F : M) {
280  if (F.getName() != FuncName) continue;
281 
282  for (BasicBlock &BB : F) {
283  if (BB.getName() != BlockName) continue;
284 
285  TranslatedBlocksToNotExtract.insert(&BB);
286  }
287  }
288 
289  BlocksToNotExtractByName.pop_back();
290  }
291 
292  // Now that we know which blocks to not extract, figure out which ones we WANT
293  // to extract.
294  std::vector<BasicBlock*> BlocksToExtract;
295  for (Function &F : M) {
296  SplitLandingPadPreds(&F);
297  for (BasicBlock &BB : F)
298  if (!TranslatedBlocksToNotExtract.count(&BB))
299  BlocksToExtract.push_back(&BB);
300  }
301 
302  for (BasicBlock *BlockToExtract : BlocksToExtract) {
303  SmallVector<BasicBlock*, 2> BlocksToExtractVec;
304  BlocksToExtractVec.push_back(BlockToExtract);
305  if (const InvokeInst *II =
306  dyn_cast<InvokeInst>(BlockToExtract->getTerminator()))
307  BlocksToExtractVec.push_back(II->getUnwindDest());
308  CodeExtractor(BlocksToExtractVec).extractCodeRegion();
309  }
310 
311  return !BlocksToExtract.empty();
312 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
Utility class for extracting code into a new function.
Definition: CodeExtractor.h:50
bool empty() const
Definition: Function.h:594
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void initializeLoopExtractorPass(PassRegistry &)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
iterator end()
Definition: Function.h:590
Function * extractCodeRegion()
Perform the extraction, returning the new function.
Pass * createSingleLoopExtractorPass()
createSingleLoopExtractorPass - This pass extracts one natural loop from the program into a function ...
STATISTIC(NumFunctions, "Total number of functions")
F(f)
ModulePass * createBlockExtractorPass()
createBlockExtractorPass - This pass extracts all blocks (except those specified in the argument list...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
BasicBlockListType::iterator iterator
Definition: Function.h:65
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:654
BlockT * getHeader() const
Definition: LoopInfo.h:100
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:63
SingleLoopExtractor - For bugpoint.
loop Extract loops into new functions
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
iterator begin()
Definition: Function.h:588
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:140
const BasicBlock & getEntryBlock() const
Definition: Function.h:572
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
char & BreakCriticalEdgesID
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
Represent the analysis usage information of a pass.
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
char & LoopSimplifyID
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:442
Iterator for intrusive lists based on ilist_node.
INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single", "Extract at most one loop into a new function", false, false) Pass *llvm
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:298
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract", "Extract loops into new functions", false, false) INITIALIZE_PASS_END(LoopExtractor
void markLoopAsDeleted(Loop &L)
Definition: LoopPass.cpp:142
Pass * createLoopExtractorPass()
createLoopExtractorPass - This pass extracts all natural loops from the program into a function if it...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:145
loop extract
LoopT * getParentLoop() const
Definition: LoopInfo.h:101
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
Definition: LoopInfo.cpp:191
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:439
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
BasicBlock * getUnwindDest() const
static cl::opt< std::string > BlockFile("extract-blocks-file", cl::value_desc("filename"), cl::desc("A file containing list of basic blocks to not extract"), cl::Hidden)
Invoke instruction.
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:958
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:267
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
static void Split(std::vector< std::string > &V, StringRef S)
Splits a string of comma separated items in to a vector of strings.
loops
Definition: LoopInfo.cpp:750
const BasicBlock * getParent() const
Definition: Instruction.h:66