blob: b81484277eb899c9d7cc977ca6c9228548572d3a [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +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//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the interface to tear out a code region, such as an
11// individual loop or a parallel section, into a new function, replacing it with
12// a call to the new function.
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruth0fde0012012-05-04 10:18:49 +000016#include "llvm/Transforms/Utils/CodeExtractor.h"
Jakub Staszakf23980a2013-02-09 01:04:28 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/Analysis/RegionInfo.h"
22#include "llvm/Analysis/RegionIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000030#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000031#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000037#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000038#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000039using namespace llvm;
40
Misha Brukman3596f0a2004-04-23 23:54:17 +000041// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000042// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000043// extracted functions to pthread-based code, as only one argument (void*) can
44// be passed in to pthread_create().
45static cl::opt<bool>
46AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
47 cl::desc("Aggregate arguments to code-extracted functions"));
48
Chandler Carruth0fde0012012-05-04 10:18:49 +000049/// \brief Test whether a block is valid for extraction.
50static bool isBlockValidForExtraction(const BasicBlock &BB) {
51 // Landing pads must be in the function where they were inserted for cleanup.
52 if (BB.isLandingPad())
53 return false;
Chris Lattner37de2572004-03-18 03:49:40 +000054
Chandler Carruth0fde0012012-05-04 10:18:49 +000055 // Don't hoist code containing allocas, invokes, or vastarts.
56 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
57 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +000058 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000059 if (const CallInst *CI = dyn_cast<CallInst>(I))
60 if (const Function *F = CI->getCalledFunction())
61 if (F->getIntrinsicID() == Intrinsic::vastart)
62 return false;
63 }
64
65 return true;
66}
67
68/// \brief Build a set of blocks to extract if the input blocks are viable.
Chandler Carruth67818212012-05-04 21:33:30 +000069template <typename IteratorT>
70static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
71 IteratorT BBEnd) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000072 SetVector<BasicBlock *> Result;
73
Chandler Carruth67818212012-05-04 21:33:30 +000074 assert(BBBegin != BBEnd);
Chandler Carruth2f5d0192012-05-04 10:26:45 +000075
Chandler Carruth0fde0012012-05-04 10:18:49 +000076 // Loop over the blocks, adding them to our set-vector, and aborting with an
77 // empty set if we encounter invalid blocks.
Chandler Carruth67818212012-05-04 21:33:30 +000078 for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000079 if (!Result.insert(*I))
Chandler Carruth44e13912012-05-04 11:17:06 +000080 llvm_unreachable("Repeated basic blocks in extraction input");
Chandler Carruth0fde0012012-05-04 10:18:49 +000081
82 if (!isBlockValidForExtraction(**I)) {
83 Result.clear();
Chandler Carruth0a570552012-05-04 11:14:19 +000084 return Result;
Chris Lattner3b2917b2004-05-12 06:01:40 +000085 }
Chandler Carruth0fde0012012-05-04 10:18:49 +000086 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000087
Chandler Carruth2f5d0192012-05-04 10:26:45 +000088#ifndef NDEBUG
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +000089 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
Chandler Carruth67818212012-05-04 21:33:30 +000090 E = Result.end();
Chandler Carruth2f5d0192012-05-04 10:26:45 +000091 I != E; ++I)
92 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
93 PI != PE; ++PI)
94 assert(Result.count(*PI) &&
95 "No blocks in this region may have entries from outside the region"
96 " except for the first block!");
97#endif
98
Chandler Carruth0fde0012012-05-04 10:18:49 +000099 return Result;
100}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000101
Chandler Carruth67818212012-05-04 21:33:30 +0000102/// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
103static SetVector<BasicBlock *>
104buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
105 return buildExtractionBlockSet(BBs.begin(), BBs.end());
106}
107
108/// \brief Helper to call buildExtractionBlockSet with a RegionNode.
109static SetVector<BasicBlock *>
110buildExtractionBlockSet(const RegionNode &RN) {
111 if (!RN.isSubRegion())
112 // Just a single BasicBlock.
113 return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>());
114
115 const Region &R = *RN.getNodeAs<Region>();
116
117 return buildExtractionBlockSet(R.block_begin(), R.block_end());
118}
119
Chandler Carruth0fde0012012-05-04 10:18:49 +0000120CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
121 : DT(0), AggregateArgs(AggregateArgs||AggregateArgsOpt),
122 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000123
Chandler Carruth0fde0012012-05-04 10:18:49 +0000124CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
125 bool AggregateArgs)
126 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
127 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000128
Chandler Carruth0fde0012012-05-04 10:18:49 +0000129CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
130 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
131 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000132
Chandler Carruth67818212012-05-04 21:33:30 +0000133CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN,
134 bool AggregateArgs)
135 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
136 Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {}
137
Chandler Carruth0fde0012012-05-04 10:18:49 +0000138/// definedInRegion - Return true if the specified value is defined in the
139/// extracted region.
140static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
141 if (Instruction *I = dyn_cast<Instruction>(V))
142 if (Blocks.count(I->getParent()))
143 return true;
144 return false;
145}
146
147/// definedInCaller - Return true if the specified value is defined in the
148/// function being code extracted, but not in the region being extracted.
149/// These values must be passed in as live-ins to the function.
150static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
151 if (isa<Argument>(V)) return true;
152 if (Instruction *I = dyn_cast<Instruction>(V))
153 if (!Blocks.count(I->getParent()))
154 return true;
155 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000156}
157
Chandler Carruth14316fc2012-05-04 11:20:27 +0000158void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
159 ValueSet &Outputs) const {
160 for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(),
161 E = Blocks.end();
162 I != E; ++I) {
163 BasicBlock *BB = *I;
164
165 // If a used value is defined outside the region, it's an input. If an
166 // instruction is used outside the region, it's an output.
167 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
168 II != IE; ++II) {
169 for (User::op_iterator OI = II->op_begin(), OE = II->op_end();
170 OI != OE; ++OI)
171 if (definedInCaller(Blocks, *OI))
172 Inputs.insert(*OI);
173
Chandler Carruthcdf47882014-03-09 03:16:01 +0000174 for (User *U : II->users())
175 if (!definedInRegion(Blocks, U)) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000176 Outputs.insert(II);
177 break;
178 }
179 }
180 }
181}
182
Chris Lattner3b2917b2004-05-12 06:01:40 +0000183/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
184/// region, we need to split the entry block of the region so that the PHI node
185/// is easier to deal with.
186void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000187 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000188 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000189
Dan Gohmandcb291f2007-03-22 16:38:57 +0000190 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000191 PHINode *PN = dyn_cast<PHINode>(Header->begin());
192 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000193
Chris Lattner795c9932004-05-12 15:29:13 +0000194 // If the header node contains any PHI nodes, check to see if there is more
195 // than one entry from outside the region. If so, we need to sever the
196 // header block into two.
197 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000198 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000199 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000200 else
201 ++NumPredsOutsideRegion;
202
203 // If there is one (or fewer) predecessor from outside the region, we don't
204 // need to do anything special.
205 if (NumPredsOutsideRegion <= 1) return;
206 }
207
208 // Otherwise, we need to split the header block into two pieces: one
209 // containing PHI nodes merging values from outside of the region, and a
210 // second that contains all of the code for the block and merges back any
211 // incoming values from inside of the region.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000212 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
Chris Lattner795c9932004-05-12 15:29:13 +0000213 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
214 Header->getName()+".ce");
215
216 // We only want to code extract the second block now, and it becomes the new
217 // header of the region.
218 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000219 Blocks.remove(OldPred);
220 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000221 Header = NewBB;
222
223 // Okay, update dominator sets. The blocks that dominate the new one are the
224 // blocks that dominate TIBB plus the new block itself.
Devang Pateld5258a232007-06-21 17:23:45 +0000225 if (DT)
226 DT->splitBlock(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000227
228 // Okay, now we need to adjust the PHI nodes and any branches from within the
229 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000230 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000231 PHINode *PN = cast<PHINode>(OldPred->begin());
232 // Loop over all of the predecessors of OldPred that are in the region,
233 // changing them to branch to NewBB instead.
234 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000235 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000236 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
237 TI->replaceUsesOfWith(OldPred, NewBB);
238 }
239
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000240 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000241 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Reid Spencer66149462004-09-15 17:06:42 +0000242 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
243 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000244 // Create a new PHI node in the new region, which has an incoming value
245 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000246 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
247 PN->getName()+".ce", NewBB->begin());
Chris Lattner795c9932004-05-12 15:29:13 +0000248 NewPN->addIncoming(PN, OldPred);
249
250 // Loop over all of the incoming value in PN, moving them to NewPN if they
251 // are from the extracted region.
252 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000253 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000254 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
255 PN->removeIncomingValue(i);
256 --i;
257 }
258 }
259 }
260 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000261}
Chris Lattner795c9932004-05-12 15:29:13 +0000262
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000263void CodeExtractor::splitReturnBlocks() {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000264 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
265 I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000266 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
267 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
268 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000269 // Old dominates New. New node dominates all other nodes dominated
270 // by Old.
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000271 DomTreeNode *OldNode = DT->getNode(*I);
Owen Andersonf18cae42009-08-25 17:35:37 +0000272 SmallVector<DomTreeNode*, 8> Children;
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000273 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
274 DI != DE; ++DI)
275 Children.push_back(*DI);
276
277 DomTreeNode *NewNode = DT->addNewBlock(New, *I);
278
Craig Topperaf0dea12013-07-04 01:31:24 +0000279 for (SmallVectorImpl<DomTreeNode *>::iterator I = Children.begin(),
280 E = Children.end(); I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000281 DT->changeImmediateDominator(*I, NewNode);
282 }
283 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000284}
285
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000286/// constructFunction - make a function based on inputs and outputs, as follows:
287/// f(in0, ..., inN, out0, ..., outN)
288///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000289Function *CodeExtractor::constructFunction(const ValueSet &inputs,
290 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000291 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000292 BasicBlock *newRootNode,
293 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000294 Function *oldFunction,
295 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000296 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
297 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000298
299 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000300 switch (NumExitBlocks) {
301 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000302 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
303 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
304 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000305 }
306
Jay Foadb804a2b2011-07-12 14:06:48 +0000307 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000308
309 // Add the types of the input values to the function's argument list
Chandler Carruth0fde0012012-05-04 10:18:49 +0000310 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
311 i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000312 const Value *value = *i;
David Greene0ad6dce2010-01-05 01:26:44 +0000313 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000314 paramTy.push_back(value->getType());
315 }
316
Chris Lattner37de2572004-03-18 03:49:40 +0000317 // Add the types of the output values to the function's argument list.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000318 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
Chris Lattner37de2572004-03-18 03:49:40 +0000319 I != E; ++I) {
David Greene0ad6dce2010-01-05 01:26:44 +0000320 DEBUG(dbgs() << "instr used in func: " << **I << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000321 if (AggregateArgs)
322 paramTy.push_back((*I)->getType());
323 else
Owen Anderson4056ca92009-07-29 22:17:13 +0000324 paramTy.push_back(PointerType::getUnqual((*I)->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000325 }
326
David Greene0ad6dce2010-01-05 01:26:44 +0000327 DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
Jay Foadb804a2b2011-07-12 14:06:48 +0000328 for (std::vector<Type*>::iterator i = paramTy.begin(),
Bill Wendling4ae40102006-11-26 10:17:54 +0000329 e = paramTy.end(); i != e; ++i)
David Greene0ad6dce2010-01-05 01:26:44 +0000330 DEBUG(dbgs() << **i << ", ");
331 DEBUG(dbgs() << ")\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000332
Misha Brukman3596f0a2004-04-23 23:54:17 +0000333 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Owen Andersone70b6372009-07-05 22:41:43 +0000334 PointerType *StructPtr =
Owen Anderson03cb69f2009-08-05 23:16:16 +0000335 PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000336 paramTy.clear();
337 paramTy.push_back(StructPtr);
338 }
Chris Lattner229907c2011-07-18 04:54:35 +0000339 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000340 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000341
342 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000343 Function *newFunction = Function::Create(funcType,
344 GlobalValue::InternalLinkage,
345 oldFunction->getName() + "_" +
346 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000347 // If the old function is no-throw, so is the new one.
348 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000349 newFunction->setDoesNotThrow();
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000350
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000351 newFunction->getBasicBlockList().push_back(newRootNode);
352
Chris Lattner37de2572004-03-18 03:49:40 +0000353 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000354 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000355
356 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000357 // arguments (or appropriate addressing into struct) instead.
358 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
359 Value *RewriteVal;
360 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000361 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000362 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
363 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000364 TerminatorInst *TI = newFunction->begin()->getTerminator();
Daniel Dunbar123686852009-07-24 08:24:36 +0000365 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000366 GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000367 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000368 } else
369 RewriteVal = AI++;
370
Chandler Carruthcdf47882014-03-09 03:16:01 +0000371 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000372 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000373 use != useE; ++use)
374 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000375 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000376 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000377 }
378
Misha Brukman3596f0a2004-04-23 23:54:17 +0000379 // Set names for input and output arguments.
380 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000381 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000382 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000383 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000384 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000385 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000386 }
Chris Lattner37de2572004-03-18 03:49:40 +0000387
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000388 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
389 // within the new function. This must be done before we lose track of which
390 // blocks were originally in the code region.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000391 std::vector<User*> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000392 for (unsigned i = 0, e = Users.size(); i != e; ++i)
393 // The BasicBlock which contains the branch is not in the region
394 // modify the branch target to a new block
395 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000396 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000397 TI->getParent()->getParent() == oldFunction)
398 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000399
400 return newFunction;
401}
402
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000403/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
404/// that uses the value within the basic block, and return the predecessor
405/// block associated with that use, or return 0 if none is found.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000406static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000407 for (Use &U : Used->uses()) {
408 PHINode *P = dyn_cast<PHINode>(U.getUser());
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000409 if (P && P->getParent() == BB)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000410 return P->getIncomingBlock(U);
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000411 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000412
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000413 return 0;
414}
415
Chris Lattner3b2917b2004-05-12 06:01:40 +0000416/// emitCallAndSwitchStatement - This method sets up the caller side by adding
417/// the call instruction, splitting any PHI nodes in the header block as
418/// necessary.
419void CodeExtractor::
420emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000421 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000422 // Emit a call to the new function, passing in: *pointer to struct (if
423 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000424 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Owen Anderson55f1c092009-08-13 21:58:54 +0000425
426 LLVMContext &Context = newFunction->getContext();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000427
Misha Brukman3596f0a2004-04-23 23:54:17 +0000428 // Add inputs as params, or to be filled into the struct
Chandler Carruth0fde0012012-05-04 10:18:49 +0000429 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000430 if (AggregateArgs)
431 StructValues.push_back(*i);
432 else
433 params.push_back(*i);
434
435 // Create allocas for the outputs
Chandler Carruth0fde0012012-05-04 10:18:49 +0000436 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000437 if (AggregateArgs) {
438 StructValues.push_back(*i);
439 } else {
440 AllocaInst *alloca =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000441 new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
Misha Brukman3596f0a2004-04-23 23:54:17 +0000442 codeReplacer->getParent()->begin()->begin());
443 ReloadOutputs.push_back(alloca);
444 params.push_back(alloca);
445 }
446 }
447
448 AllocaInst *Struct = 0;
449 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000450 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000451 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000452 ve = StructValues.end(); v != ve; ++v)
453 ArgTypes.push_back((*v)->getType());
454
455 // Allocate a struct at the beginning of this function
Owen Anderson03cb69f2009-08-05 23:16:16 +0000456 Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457 Struct =
Owen Anderson4fdeba92009-07-15 23:53:25 +0000458 new AllocaInst(StructArgTy, 0, "structArg",
Chris Lattner37de2572004-03-18 03:49:40 +0000459 codeReplacer->getParent()->begin()->begin());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000460 params.push_back(Struct);
461
462 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000463 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000464 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
465 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000466 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000467 GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000468 "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000469 codeReplacer->getInstList().push_back(GEP);
470 StoreInst *SI = new StoreInst(StructValues[i], GEP);
471 codeReplacer->getInstList().push_back(SI);
472 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000473 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000474
475 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000476 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000477 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000478 codeReplacer->getInstList().push_back(call);
479
Chris Lattner531f9e92005-03-15 04:54:21 +0000480 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000481 unsigned FirstOut = inputs.size();
482 if (!AggregateArgs)
483 std::advance(OutputArgBegin, inputs.size());
484
485 // Reload the outputs passed in by reference
486 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
487 Value *Output = 0;
488 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000489 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000490 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
491 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000492 GetElementPtrInst *GEP
Jay Foadd1b78492011-07-25 09:48:08 +0000493 = GetElementPtrInst::Create(Struct, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000494 "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000495 codeReplacer->getInstList().push_back(GEP);
496 Output = GEP;
497 } else {
498 Output = ReloadOutputs[i];
499 }
500 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000501 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000502 codeReplacer->getInstList().push_back(load);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000503 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +0000504 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
505 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000506 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000507 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000508 }
509 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000510
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000511 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000512 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000513 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000514 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000515
516 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000517 // function return an unsigned, switch on that number. This loop iterates
518 // over all of the blocks in the extracted region, updating any terminator
519 // instructions in the to-be-extracted region that branch to blocks that are
520 // not in the region to be extracted.
521 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
522
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000523 unsigned switchVal = 0;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000524 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
525 e = Blocks.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000526 TerminatorInst *TI = (*i)->getTerminator();
527 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000528 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000529 BasicBlock *OldTarget = TI->getSuccessor(i);
530 // add a new basic block which returns the appropriate value
531 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
532 if (!NewTarget) {
533 // If we don't already have an exit stub for this non-extracted
534 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000535 NewTarget = BasicBlock::Create(Context,
536 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000537 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000538 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000539
Chris Lattnerffc49262004-05-12 04:14:24 +0000540 Value *brVal = 0;
541 switch (NumExitBlocks) {
542 case 0:
543 case 1: break; // No value needed.
544 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000545 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000546 break;
547 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000548 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000549 break;
550 }
551
Owen Anderson55f1c092009-08-13 21:58:54 +0000552 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000553
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000554 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000555 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
556 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000557 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000558
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000559 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000560 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000561 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
562 // For an invoke, the normal destination is the only one that is
563 // dominated by the result of the invocation
564 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000565
566 bool DominatesDef = true;
567
Chris Lattner5bcca602004-11-12 23:50:44 +0000568 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000569 DefBlock = Invoke->getNormalDest();
Chris Lattner5bcca602004-11-12 23:50:44 +0000570
571 // Make sure we are looking at the original successor block, not
572 // at a newly inserted exit block, which won't be in the dominator
573 // info.
574 for (std::map<BasicBlock*, BasicBlock*>::iterator I =
575 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
576 if (DefBlock == I->second) {
577 DefBlock = I->first;
578 break;
579 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000580
581 // In the extract block case, if the block we are extracting ends
582 // with an invoke instruction, make sure that we don't emit a
583 // store of the invoke value for the unwind block.
Devang Patelcf470e52007-06-07 22:17:16 +0000584 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000585 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000586 }
587
Owen Anderson34e61482009-08-25 00:54:39 +0000588 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000589 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000590
591 // If the output value is used by a phi in the target block,
592 // then we need to test for dominance of the phi's predecessor
593 // instead. Unfortunately, this a little complicated since we
594 // have already rewritten uses of the value to uses of the reload.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000595 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
596 OldTarget);
597 if (pred && DT && DT->dominates(DefBlock, pred))
598 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000599 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000600
601 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000602 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000603 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000604 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
605 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
606 FirstOut+out);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000607 GetElementPtrInst *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000608 GetElementPtrInst::Create(OAI, Idx,
Gabor Greife9ecc682008-04-06 20:25:17 +0000609 "gep_" + outputs[out]->getName(),
610 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000611 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000612 } else {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000613 new StoreInst(outputs[out], OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000614 }
615 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000616 // Advance output iterator even if we don't emit a store
617 if (!AggregateArgs) ++OAI;
618 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000619 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000620
621 // rewrite the original branch instruction with this new target
622 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000623 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000624 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000625
Chris Lattner3d1ca672004-05-12 03:22:33 +0000626 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000627 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000628 switch (NumExitBlocks) {
629 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000630 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000631 // means that previously this was the last part of the function, and hence
632 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000633
Misha Brukman3596f0a2004-04-23 23:54:17 +0000634 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000635 if (OldFnRetTy->isVoidTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000636 ReturnInst::Create(Context, 0, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000637 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000638 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000639 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000640 } else {
641 // Otherwise we must have code extracted an unwind or something, just
642 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000643 ReturnInst::Create(Context,
644 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000645 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000646
Dan Gohman158ff2c2008-06-21 22:08:46 +0000647 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000648 break;
649 case 1:
650 // Only a single destination, change the switch into an unconditional
651 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000652 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000653 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000654 break;
655 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000656 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
657 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000658 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000659 break;
660 default:
661 // Otherwise, make the default destination of the switch instruction be one
662 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000663 TheSwitch->setCondition(call);
664 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000665 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +0000666 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000667 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000668 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000669}
670
Chris Lattner3b2917b2004-05-12 06:01:40 +0000671void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000672 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000673 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
674 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
675
Chandler Carruth0fde0012012-05-04 10:18:49 +0000676 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
677 e = Blocks.end(); i != e; ++i) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000678 // Delete the basic block from the old function, and the list of blocks
679 oldBlocks.remove(*i);
680
681 // Insert this basic block into the new function
682 newBlocks.push_back(*i);
683 }
684}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000685
Chandler Carruth0fde0012012-05-04 10:18:49 +0000686Function *CodeExtractor::extractCodeRegion() {
687 if (!isEligible())
Misha Brukman3596f0a2004-04-23 23:54:17 +0000688 return 0;
689
Chandler Carruth0fde0012012-05-04 10:18:49 +0000690 ValueSet inputs, outputs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000691
692 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000693 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000694 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000695
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000696 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +0000697 severSplitPHINodes(header);
698
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000699 // If we have any return instructions in the region, split those blocks so
700 // that the return is not in the region.
701 splitReturnBlocks();
702
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000703 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000704
705 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +0000706 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
707 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +0000708 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000709
710 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +0000711 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +0000712 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
713 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +0000714 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000715
Chris Lattner3b2917b2004-05-12 06:01:40 +0000716 // Find inputs to, outputs from the code region.
717 findInputsOutputs(inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000718
Chandler Carruth14316fc2012-05-04 11:20:27 +0000719 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
720 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
721 I != E; ++I)
722 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
723 if (!Blocks.count(*SI))
724 ExitBlocks.insert(*SI);
725 NumExitBlocks = ExitBlocks.size();
726
Chris Lattner3b2917b2004-05-12 06:01:40 +0000727 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +0000728 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +0000729 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000730 codeReplacer, oldFunction,
731 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000732
Chris Lattner9c431f62004-03-14 22:34:55 +0000733 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000734
Chris Lattner9c431f62004-03-14 22:34:55 +0000735 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000736
Chris Lattner795c9932004-05-12 15:29:13 +0000737 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +0000738 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +0000739 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
740 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +0000741 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000742 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +0000743 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +0000744 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000745
Chris Lattneracd75982004-03-18 05:38:31 +0000746 // Look at all successors of the codeReplacer block. If any of these blocks
747 // had PHI nodes in them, we need to update the "from" block to be the code
748 // replacer, not the original block in the extracted region.
749 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
750 succ_end(codeReplacer));
751 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +0000752 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
753 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +0000754 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +0000755 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000756 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +0000757 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
758 PN->setIncomingBlock(i, codeReplacer);
759 else {
760 // There were multiple entries in the PHI for this block, now there
761 // is only one, so remove the duplicated entries.
762 PN->removeIncomingValue(i, false);
763 --i; --e;
764 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000765 }
Chris Lattner56273822004-08-13 03:27:07 +0000766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000767
Bill Wendlingf3baad32006-12-07 01:30:32 +0000768 //cerr << "NEW FUNCTION: " << *newFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000769 // verifyFunction(*newFunction);
770
Bill Wendlingf3baad32006-12-07 01:30:32 +0000771 // cerr << "OLD FUNCTION: " << *oldFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000772 // verifyFunction(*oldFunction);
Chris Lattneracd75982004-03-18 05:38:31 +0000773
Torok Edwinccb29cd2009-07-11 13:10:19 +0000774 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000775 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000776 return newFunction;
777}