blob: 20414aa05b4dbf554be6bae3802f6e7873ac2f43 [file] [log] [blame]
Misha Brukman03a11342004-02-28 03:33:01 +00001//===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner692a47a2004-03-14 02:34:07 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner692a47a2004-03-14 02:34:07 +00008//===----------------------------------------------------------------------===//
Misha Brukman03a11342004-02-28 03:33:01 +00009//
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
Misha Brukmanf272f9b2004-03-02 00:19:09 +000012// given function, it is not touched. This is a pass most useful for debugging
13// via bugpoint.
Misha Brukman03a11342004-02-28 03:33:01 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner78a996a2004-03-14 02:37:16 +000017#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000020#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
Misha Brukman03a11342004-02-28 03:33:01 +000023#include "llvm/Pass.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000024#include "llvm/Support/CommandLine.h"
Chris Lattner6c3e8c72004-03-14 04:01:06 +000025#include "llvm/Transforms/Scalar.h"
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth0fde0012012-05-04 10:18:49 +000027#include "llvm/Transforms/Utils/CodeExtractor.h"
Nick Lewyckyc6243022007-11-14 06:47:06 +000028#include <fstream>
29#include <set>
Misha Brukman03a11342004-02-28 03:33:01 +000030using namespace llvm;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "loop-extract"
33
Chris Lattner1631bcb2006-12-19 22:09:18 +000034STATISTIC(NumExtracted, "Number of loops extracted");
Misha Brukmanb1c93172005-04-21 23:48:37 +000035
Chris Lattner1631bcb2006-12-19 22:09:18 +000036namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 struct LoopExtractor : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000038 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000039 unsigned NumLoops;
40
Dan Gohman34d442f2007-08-01 15:32:29 +000041 explicit LoopExtractor(unsigned numLoops = ~0)
Owen Anderson6c18d1a2010-10-19 17:21:58 +000042 : LoopPass(ID), NumLoops(numLoops) {
43 initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
44 }
Chris Lattnera1672c12004-03-14 20:01:36 +000045
Craig Topper3e4c6972014-03-05 09:10:37 +000046 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Misha Brukmanb1c93172005-04-21 23:48:37 +000047
Craig Topper3e4c6972014-03-05 09:10:37 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner5bce0c82004-03-18 05:43:18 +000049 AU.addRequiredID(BreakCriticalEdgesID);
50 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +000051 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner692a47a2004-03-14 02:34:07 +000052 }
53 };
Dan Gohmand78c4002008-05-13 00:00:25 +000054}
Misha Brukman03a11342004-02-28 03:33:01 +000055
Dan Gohmand78c4002008-05-13 00:00:25 +000056char LoopExtractor::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000057INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000058 "Extract loops into new functions", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +000059INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
60INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth73523022014-01-13 13:07:17 +000061INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000062INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
Bill Wendlingc1da6ea2011-09-20 19:10:24 +000063 "Extract loops into new functions", false, false)
Chris Lattnera1672c12004-03-14 20:01:36 +000064
Dan Gohmand78c4002008-05-13 00:00:25 +000065namespace {
Chris Lattnera1672c12004-03-14 20:01:36 +000066 /// SingleLoopExtractor - For bugpoint.
67 struct SingleLoopExtractor : public LoopExtractor {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Chris Lattnera1672c12004-03-14 20:01:36 +000069 SingleLoopExtractor() : LoopExtractor(1) {}
70 };
Misha Brukmanb1c93172005-04-21 23:48:37 +000071} // End anonymous namespace
Misha Brukman03a11342004-02-28 03:33:01 +000072
Dan Gohmand78c4002008-05-13 00:00:25 +000073char SingleLoopExtractor::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +000074INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
Owen Andersondf7a4f22010-10-07 22:25:06 +000075 "Extract at most one loop into a new function", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000076
Jeff Cohen677babc2005-01-08 17:21:40 +000077// createLoopExtractorPass - This pass extracts all natural loops from the
78// program into a function if it can.
79//
Dan Gohman9a7320c2009-09-28 14:37:51 +000080Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
Jeff Cohen677babc2005-01-08 17:21:40 +000081
Dan Gohman9a7320c2009-09-28 14:37:51 +000082bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +000083 if (skipOptnoneFunction(L))
84 return false;
85
Dan Gohman9a7320c2009-09-28 14:37:51 +000086 // Only visit top-level loops.
87 if (L->getParentLoop())
Misha Brukman03a11342004-02-28 03:33:01 +000088 return false;
89
Dan Gohmana83ac2d2009-11-05 21:11:53 +000090 // If LoopSimplify form is not available, stay out of trouble.
91 if (!L->isLoopSimplifyForm())
92 return false;
93
Chandler Carruth73523022014-01-13 13:07:17 +000094 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Dan Gohman9a7320c2009-09-28 14:37:51 +000095 bool Changed = false;
Chris Lattnere9235d22004-03-18 03:48:06 +000096
Chris Lattner2f155d82004-03-15 00:02:02 +000097 // If there is more than one top-level loop in this function, extract all of
Dan Gohman9a7320c2009-09-28 14:37:51 +000098 // the loops. Otherwise there is exactly one top-level loop; in this case if
99 // this function is more than a minimal wrapper around the loop, extract
100 // the loop.
101 bool ShouldExtractLoop = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000102
Dan Gohman9a7320c2009-09-28 14:37:51 +0000103 // Extract the loop if the entry block doesn't branch to the loop header.
104 TerminatorInst *EntryTI =
105 L->getHeader()->getParent()->getEntryBlock().getTerminator();
106 if (!isa<BranchInst>(EntryTI) ||
107 !cast<BranchInst>(EntryTI)->isUnconditional() ||
Bill Wendling00585202011-09-20 22:23:09 +0000108 EntryTI->getSuccessor(0) != L->getHeader()) {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000109 ShouldExtractLoop = true;
Bill Wendling00585202011-09-20 22:23:09 +0000110 } else {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000111 // Check to see if any exits from the loop are more than just return
Bill Wendling04289fc2011-09-20 22:27:16 +0000112 // blocks.
113 SmallVector<BasicBlock*, 8> ExitBlocks;
114 L->getExitBlocks(ExitBlocks);
115 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
116 if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
117 ShouldExtractLoop = true;
118 break;
119 }
120 }
121
122 if (ShouldExtractLoop) {
123 // We must omit landing pads. Landing pads must accompany the invoke
124 // instruction. But this would result in a loop in the extracted
Bill Wendling00585202011-09-20 22:23:09 +0000125 // function. An infinite cycle occurs when it tries to extract that loop as
126 // well.
Dan Gohman9a7320c2009-09-28 14:37:51 +0000127 SmallVector<BasicBlock*, 8> ExitBlocks;
128 L->getExitBlocks(ExitBlocks);
Bill Wendling04289fc2011-09-20 22:27:16 +0000129 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Bill Wendling00585202011-09-20 22:23:09 +0000130 if (ExitBlocks[i]->isLandingPad()) {
131 ShouldExtractLoop = false;
Dan Gohman9a7320c2009-09-28 14:37:51 +0000132 break;
Chris Lattner2f155d82004-03-15 00:02:02 +0000133 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000134 }
Bill Wendling04289fc2011-09-20 22:27:16 +0000135
Dan Gohman9a7320c2009-09-28 14:37:51 +0000136 if (ShouldExtractLoop) {
137 if (NumLoops == 0) return Changed;
138 --NumLoops;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000139 CodeExtractor Extractor(DT, *L);
Craig Topperf40110f2014-04-25 05:29:35 +0000140 if (Extractor.extractCodeRegion() != nullptr) {
Dan Gohman9a7320c2009-09-28 14:37:51 +0000141 Changed = true;
142 // After extraction, the loop is replaced by a function call, so
143 // we shouldn't try to run any more loop passes on it.
144 LPM.deleteLoopFromQueue(L);
Chris Lattner2f155d82004-03-15 00:02:02 +0000145 }
Dan Gohman9a7320c2009-09-28 14:37:51 +0000146 ++NumExtracted;
Chris Lattnera1672c12004-03-14 20:01:36 +0000147 }
Misha Brukman03a11342004-02-28 03:33:01 +0000148
149 return Changed;
150}
151
Chris Lattnera1672c12004-03-14 20:01:36 +0000152// createSingleLoopExtractorPass - This pass extracts one natural loop from the
153// program into a function if it can. This is used by bugpoint.
154//
Dan Gohman9a7320c2009-09-28 14:37:51 +0000155Pass *llvm::createSingleLoopExtractorPass() {
Chris Lattnera1672c12004-03-14 20:01:36 +0000156 return new SingleLoopExtractor();
Misha Brukman03a11342004-02-28 03:33:01 +0000157}
Chris Lattner7386e632004-08-13 03:05:17 +0000158
159
Dan Gohmand78c4002008-05-13 00:00:25 +0000160// BlockFile - A file which contains a list of blocks that should not be
161// extracted.
162static cl::opt<std::string>
163BlockFile("extract-blocks-file", cl::value_desc("filename"),
164 cl::desc("A file containing list of basic blocks to not extract"),
165 cl::Hidden);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000166
Dan Gohmand78c4002008-05-13 00:00:25 +0000167namespace {
Chris Lattner7386e632004-08-13 03:05:17 +0000168 /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
169 /// from the module into their own functions except for those specified by the
170 /// BlocksToNotExtract list.
Chris Lattner4f2cf032004-09-20 04:48:05 +0000171 class BlockExtractorPass : public ModulePass {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000172 void LoadFile(const char *Filename);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000173 void SplitLandingPadPreds(Function *F);
Nick Lewyckyc6243022007-11-14 06:47:06 +0000174
Chris Lattner7386e632004-08-13 03:05:17 +0000175 std::vector<BasicBlock*> BlocksToNotExtract;
Nick Lewyckyc6243022007-11-14 06:47:06 +0000176 std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
Chris Lattner7386e632004-08-13 03:05:17 +0000177 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000178 static char ID; // Pass identification, replacement for typeid
Owen Andersona7aed182010-08-06 18:33:48 +0000179 BlockExtractorPass() : ModulePass(ID) {
Nick Lewyckyc6243022007-11-14 06:47:06 +0000180 if (!BlockFile.empty())
181 LoadFile(BlockFile.c_str());
182 }
Chris Lattner7386e632004-08-13 03:05:17 +0000183
Craig Topper3e4c6972014-03-05 09:10:37 +0000184 bool runOnModule(Module &M) override;
Chris Lattner7386e632004-08-13 03:05:17 +0000185 };
Chris Lattner7386e632004-08-13 03:05:17 +0000186}
187
Dan Gohmand78c4002008-05-13 00:00:25 +0000188char BlockExtractorPass::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +0000189INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
190 "Extract Basic Blocks From Module (for bugpoint use)",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000191 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000192
Chris Lattner7386e632004-08-13 03:05:17 +0000193// createBlockExtractorPass - This pass extracts all blocks (except those
194// specified in the argument list) from the functions in the module.
195//
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000196ModulePass *llvm::createBlockExtractorPass() {
Rafael Espindola40f18832010-07-31 00:32:17 +0000197 return new BlockExtractorPass();
Chris Lattner7386e632004-08-13 03:05:17 +0000198}
199
Nick Lewyckyc6243022007-11-14 06:47:06 +0000200void BlockExtractorPass::LoadFile(const char *Filename) {
201 // Load the BlockFile...
202 std::ifstream In(Filename);
203 if (!In.good()) {
Chris Lattner4883d902009-08-23 07:19:13 +0000204 errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
205 << "'!\n";
Nick Lewyckyc6243022007-11-14 06:47:06 +0000206 return;
207 }
208 while (In) {
209 std::string FunctionName, BlockName;
210 In >> FunctionName;
211 In >> BlockName;
212 if (!BlockName.empty())
213 BlocksToNotExtractByName.push_back(
214 std::make_pair(FunctionName, BlockName));
215 }
216}
217
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000218/// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
219/// instruction. The critical edge breaker will refuse to break critical edges
220/// to a landing pad. So do them here. After this method runs, all landing pads
221/// should have only one predecessor.
222void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
223 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
224 InvokeInst *II = dyn_cast<InvokeInst>(I);
225 if (!II) continue;
226 BasicBlock *Parent = II->getParent();
227 BasicBlock *LPad = II->getUnwindDest();
228
229 // Look through the landing pad's predecessors. If one of them ends in an
230 // 'invoke', then we want to split the landing pad.
231 bool Split = false;
232 for (pred_iterator
233 PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
234 BasicBlock *BB = *PI;
235 if (BB->isLandingPad() && BB != Parent &&
236 isa<InvokeInst>(Parent->getTerminator())) {
237 Split = true;
238 break;
239 }
240 }
241
242 if (!Split) continue;
243
244 SmallVector<BasicBlock*, 2> NewBBs;
Craig Topperf40110f2014-04-25 05:29:35 +0000245 SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", nullptr, NewBBs);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000246 }
247}
248
Chris Lattner4f2cf032004-09-20 04:48:05 +0000249bool BlockExtractorPass::runOnModule(Module &M) {
Chris Lattner7386e632004-08-13 03:05:17 +0000250 std::set<BasicBlock*> TranslatedBlocksToNotExtract;
251 for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
252 BasicBlock *BB = BlocksToNotExtract[i];
253 Function *F = BB->getParent();
254
255 // Map the corresponding function in this module.
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000256 Function *MF = M.getFunction(F->getName());
257 assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
Chris Lattner7386e632004-08-13 03:05:17 +0000258
259 // Figure out which index the basic block is in its function.
260 Function::iterator BBI = MF->begin();
261 std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
262 TranslatedBlocksToNotExtract.insert(BBI);
263 }
264
Nick Lewyckyc6243022007-11-14 06:47:06 +0000265 while (!BlocksToNotExtractByName.empty()) {
266 // There's no way to find BBs by name without looking at every BB inside
267 // every Function. Fortunately, this is always empty except when used by
268 // bugpoint in which case correctness is more important than performance.
269
270 std::string &FuncName = BlocksToNotExtractByName.back().first;
271 std::string &BlockName = BlocksToNotExtractByName.back().second;
272
273 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
274 Function &F = *FI;
275 if (F.getName() != FuncName) continue;
276
277 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
278 BasicBlock &BB = *BI;
279 if (BB.getName() != BlockName) continue;
280
281 TranslatedBlocksToNotExtract.insert(BI);
282 }
283 }
284
285 BlocksToNotExtractByName.pop_back();
286 }
287
Chris Lattner7386e632004-08-13 03:05:17 +0000288 // Now that we know which blocks to not extract, figure out which ones we WANT
289 // to extract.
290 std::vector<BasicBlock*> BlocksToExtract;
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000291 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
292 SplitLandingPadPreds(&*F);
Chris Lattner7386e632004-08-13 03:05:17 +0000293 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
294 if (!TranslatedBlocksToNotExtract.count(BB))
295 BlocksToExtract.push_back(BB);
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000296 }
Chris Lattner7386e632004-08-13 03:05:17 +0000297
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000298 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
299 SmallVector<BasicBlock*, 2> BlocksToExtractVec;
300 BlocksToExtractVec.push_back(BlocksToExtract[i]);
Bill Wendling3d48f592011-09-20 20:20:50 +0000301 if (const InvokeInst *II =
302 dyn_cast<InvokeInst>(BlocksToExtract[i]->getTerminator()))
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000303 BlocksToExtractVec.push_back(II->getUnwindDest());
Chandler Carruth0fde0012012-05-04 10:18:49 +0000304 CodeExtractor(BlocksToExtractVec).extractCodeRegion();
Bill Wendlingc1da6ea2011-09-20 19:10:24 +0000305 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000306
Chris Lattner7386e632004-08-13 03:05:17 +0000307 return !BlocksToExtract.empty();
308}