blob: e76a9d4ba2d10af1839d7bd991c2e1a258a4e153 [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
Chandler Carruthe96dd892014-04-21 22:55:11 +000041#define DEBUG_TYPE "code-extractor"
42
Misha Brukman3596f0a2004-04-23 23:54:17 +000043// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000044// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000045// extracted functions to pthread-based code, as only one argument (void*) can
46// be passed in to pthread_create().
47static cl::opt<bool>
48AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
49 cl::desc("Aggregate arguments to code-extracted functions"));
50
Chandler Carruth0fde0012012-05-04 10:18:49 +000051/// \brief Test whether a block is valid for extraction.
52static bool isBlockValidForExtraction(const BasicBlock &BB) {
53 // Landing pads must be in the function where they were inserted for cleanup.
David Majnemereb518bd2015-08-04 08:21:40 +000054 if (BB.isEHPad())
Chandler Carruth0fde0012012-05-04 10:18:49 +000055 return false;
Chris Lattner37de2572004-03-18 03:49:40 +000056
Chandler Carruth0fde0012012-05-04 10:18:49 +000057 // Don't hoist code containing allocas, invokes, or vastarts.
58 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
59 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +000060 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000061 if (const CallInst *CI = dyn_cast<CallInst>(I))
62 if (const Function *F = CI->getCalledFunction())
63 if (F->getIntrinsicID() == Intrinsic::vastart)
64 return false;
65 }
66
67 return true;
68}
69
70/// \brief Build a set of blocks to extract if the input blocks are viable.
Chandler Carruth67818212012-05-04 21:33:30 +000071template <typename IteratorT>
72static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
73 IteratorT BBEnd) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000074 SetVector<BasicBlock *> Result;
75
Chandler Carruth67818212012-05-04 21:33:30 +000076 assert(BBBegin != BBEnd);
Chandler Carruth2f5d0192012-05-04 10:26:45 +000077
Chandler Carruth0fde0012012-05-04 10:18:49 +000078 // Loop over the blocks, adding them to our set-vector, and aborting with an
79 // empty set if we encounter invalid blocks.
Chandler Carruth67818212012-05-04 21:33:30 +000080 for (IteratorT I = BBBegin, E = BBEnd; I != E; ++I) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000081 if (!Result.insert(*I))
Chandler Carruth44e13912012-05-04 11:17:06 +000082 llvm_unreachable("Repeated basic blocks in extraction input");
Chandler Carruth0fde0012012-05-04 10:18:49 +000083
84 if (!isBlockValidForExtraction(**I)) {
85 Result.clear();
Chandler Carruth0a570552012-05-04 11:14:19 +000086 return Result;
Chris Lattner3b2917b2004-05-12 06:01:40 +000087 }
Chandler Carruth0fde0012012-05-04 10:18:49 +000088 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000089
Chandler Carruth2f5d0192012-05-04 10:26:45 +000090#ifndef NDEBUG
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +000091 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
Chandler Carruth67818212012-05-04 21:33:30 +000092 E = Result.end();
Chandler Carruth2f5d0192012-05-04 10:26:45 +000093 I != E; ++I)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +000094 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
95 PI != PE; ++PI)
96 assert(Result.count(*PI) &&
Chandler Carruth2f5d0192012-05-04 10:26:45 +000097 "No blocks in this region may have entries from outside the region"
98 " except for the first block!");
99#endif
100
Chandler Carruth0fde0012012-05-04 10:18:49 +0000101 return Result;
102}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000103
Chandler Carruth67818212012-05-04 21:33:30 +0000104/// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
105static SetVector<BasicBlock *>
106buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
107 return buildExtractionBlockSet(BBs.begin(), BBs.end());
108}
109
110/// \brief Helper to call buildExtractionBlockSet with a RegionNode.
111static SetVector<BasicBlock *>
112buildExtractionBlockSet(const RegionNode &RN) {
113 if (!RN.isSubRegion())
114 // Just a single BasicBlock.
115 return buildExtractionBlockSet(RN.getNodeAs<BasicBlock>());
116
117 const Region &R = *RN.getNodeAs<Region>();
118
119 return buildExtractionBlockSet(R.block_begin(), R.block_end());
120}
121
Chandler Carruth0fde0012012-05-04 10:18:49 +0000122CodeExtractor::CodeExtractor(BasicBlock *BB, bool AggregateArgs)
Craig Topperf40110f2014-04-25 05:29:35 +0000123 : DT(nullptr), AggregateArgs(AggregateArgs||AggregateArgsOpt),
Chandler Carruth0fde0012012-05-04 10:18:49 +0000124 Blocks(buildExtractionBlockSet(BB)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000125
Chandler Carruth0fde0012012-05-04 10:18:49 +0000126CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
127 bool AggregateArgs)
128 : DT(DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
129 Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000130
Chandler Carruth0fde0012012-05-04 10:18:49 +0000131CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs)
132 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
133 Blocks(buildExtractionBlockSet(L.getBlocks())), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000134
Chandler Carruth67818212012-05-04 21:33:30 +0000135CodeExtractor::CodeExtractor(DominatorTree &DT, const RegionNode &RN,
136 bool AggregateArgs)
137 : DT(&DT), AggregateArgs(AggregateArgs||AggregateArgsOpt),
138 Blocks(buildExtractionBlockSet(RN)), NumExitBlocks(~0U) {}
139
Chandler Carruth0fde0012012-05-04 10:18:49 +0000140/// definedInRegion - Return true if the specified value is defined in the
141/// extracted region.
142static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
143 if (Instruction *I = dyn_cast<Instruction>(V))
144 if (Blocks.count(I->getParent()))
145 return true;
146 return false;
147}
148
149/// definedInCaller - Return true if the specified value is defined in the
150/// function being code extracted, but not in the region being extracted.
151/// These values must be passed in as live-ins to the function.
152static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
153 if (isa<Argument>(V)) return true;
154 if (Instruction *I = dyn_cast<Instruction>(V))
155 if (!Blocks.count(I->getParent()))
156 return true;
157 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000158}
159
Chandler Carruth14316fc2012-05-04 11:20:27 +0000160void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
161 ValueSet &Outputs) const {
162 for (SetVector<BasicBlock *>::const_iterator I = Blocks.begin(),
163 E = Blocks.end();
164 I != E; ++I) {
165 BasicBlock *BB = *I;
166
167 // If a used value is defined outside the region, it's an input. If an
168 // instruction is used outside the region, it's an output.
169 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
170 II != IE; ++II) {
171 for (User::op_iterator OI = II->op_begin(), OE = II->op_end();
172 OI != OE; ++OI)
173 if (definedInCaller(Blocks, *OI))
174 Inputs.insert(*OI);
175
Chandler Carruthcdf47882014-03-09 03:16:01 +0000176 for (User *U : II->users())
177 if (!definedInRegion(Blocks, U)) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000178 Outputs.insert(II);
179 break;
180 }
181 }
182 }
183}
184
Chris Lattner3b2917b2004-05-12 06:01:40 +0000185/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
186/// region, we need to split the entry block of the region so that the PHI node
187/// is easier to deal with.
188void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000189 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000190 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000191
Dan Gohmandcb291f2007-03-22 16:38:57 +0000192 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000193 PHINode *PN = dyn_cast<PHINode>(Header->begin());
194 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000195
Chris Lattner795c9932004-05-12 15:29:13 +0000196 // If the header node contains any PHI nodes, check to see if there is more
197 // than one entry from outside the region. If so, we need to sever the
198 // header block into two.
199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000200 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000201 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000202 else
203 ++NumPredsOutsideRegion;
204
205 // If there is one (or fewer) predecessor from outside the region, we don't
206 // need to do anything special.
207 if (NumPredsOutsideRegion <= 1) return;
208 }
209
210 // Otherwise, we need to split the header block into two pieces: one
211 // containing PHI nodes merging values from outside of the region, and a
212 // second that contains all of the code for the block and merges back any
213 // incoming values from inside of the region.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000214 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
Chris Lattner795c9932004-05-12 15:29:13 +0000215 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
216 Header->getName()+".ce");
217
218 // We only want to code extract the second block now, and it becomes the new
219 // header of the region.
220 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000221 Blocks.remove(OldPred);
222 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000223 Header = NewBB;
224
225 // Okay, update dominator sets. The blocks that dominate the new one are the
226 // blocks that dominate TIBB plus the new block itself.
Devang Pateld5258a232007-06-21 17:23:45 +0000227 if (DT)
228 DT->splitBlock(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000229
230 // Okay, now we need to adjust the PHI nodes and any branches from within the
231 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000232 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000233 PHINode *PN = cast<PHINode>(OldPred->begin());
234 // Loop over all of the predecessors of OldPred that are in the region,
235 // changing them to branch to NewBB instead.
236 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000237 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000238 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
239 TI->replaceUsesOfWith(OldPred, NewBB);
240 }
241
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000242 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000243 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Reid Spencer66149462004-09-15 17:06:42 +0000244 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
245 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000246 // Create a new PHI node in the new region, which has an incoming value
247 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000248 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
249 PN->getName()+".ce", NewBB->begin());
Chris Lattner795c9932004-05-12 15:29:13 +0000250 NewPN->addIncoming(PN, OldPred);
251
252 // Loop over all of the incoming value in PN, moving them to NewPN if they
253 // are from the extracted region.
254 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000255 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000256 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
257 PN->removeIncomingValue(i);
258 --i;
259 }
260 }
261 }
262 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000263}
Chris Lattner795c9932004-05-12 15:29:13 +0000264
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000265void CodeExtractor::splitReturnBlocks() {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000266 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
267 I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000268 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
269 BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
270 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000271 // Old dominates New. New node dominates all other nodes dominated
272 // by Old.
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000273 DomTreeNode *OldNode = DT->getNode(*I);
Owen Andersonf18cae42009-08-25 17:35:37 +0000274 SmallVector<DomTreeNode*, 8> Children;
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000275 for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
276 DI != DE; ++DI)
277 Children.push_back(*DI);
278
279 DomTreeNode *NewNode = DT->addNewBlock(New, *I);
280
Craig Topperaf0dea12013-07-04 01:31:24 +0000281 for (SmallVectorImpl<DomTreeNode *>::iterator I = Children.begin(),
282 E = Children.end(); I != E; ++I)
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000283 DT->changeImmediateDominator(*I, NewNode);
284 }
285 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000286}
287
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000288/// constructFunction - make a function based on inputs and outputs, as follows:
289/// f(in0, ..., inN, out0, ..., outN)
290///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000291Function *CodeExtractor::constructFunction(const ValueSet &inputs,
292 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000293 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000294 BasicBlock *newRootNode,
295 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000296 Function *oldFunction,
297 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000298 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
299 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000300
301 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000302 switch (NumExitBlocks) {
303 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000304 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
305 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
306 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000307 }
308
Jay Foadb804a2b2011-07-12 14:06:48 +0000309 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000310
311 // Add the types of the input values to the function's argument list
Chandler Carruth0fde0012012-05-04 10:18:49 +0000312 for (ValueSet::const_iterator i = inputs.begin(), e = inputs.end();
313 i != e; ++i) {
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000314 const Value *value = *i;
David Greene0ad6dce2010-01-05 01:26:44 +0000315 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000316 paramTy.push_back(value->getType());
317 }
318
Chris Lattner37de2572004-03-18 03:49:40 +0000319 // Add the types of the output values to the function's argument list.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000320 for (ValueSet::const_iterator I = outputs.begin(), E = outputs.end();
Chris Lattner37de2572004-03-18 03:49:40 +0000321 I != E; ++I) {
David Greene0ad6dce2010-01-05 01:26:44 +0000322 DEBUG(dbgs() << "instr used in func: " << **I << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000323 if (AggregateArgs)
324 paramTy.push_back((*I)->getType());
325 else
Owen Anderson4056ca92009-07-29 22:17:13 +0000326 paramTy.push_back(PointerType::getUnqual((*I)->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000327 }
328
David Greene0ad6dce2010-01-05 01:26:44 +0000329 DEBUG(dbgs() << "Function type: " << *RetTy << " f(");
Jay Foadb804a2b2011-07-12 14:06:48 +0000330 for (std::vector<Type*>::iterator i = paramTy.begin(),
Bill Wendling4ae40102006-11-26 10:17:54 +0000331 e = paramTy.end(); i != e; ++i)
David Greene0ad6dce2010-01-05 01:26:44 +0000332 DEBUG(dbgs() << **i << ", ");
333 DEBUG(dbgs() << ")\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000334
David Blaikie741c8f82015-03-14 01:53:18 +0000335 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000336 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000337 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000338 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000339 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000340 }
Chris Lattner229907c2011-07-18 04:54:35 +0000341 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000342 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000343
344 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000345 Function *newFunction = Function::Create(funcType,
346 GlobalValue::InternalLinkage,
347 oldFunction->getName() + "_" +
348 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000349 // If the old function is no-throw, so is the new one.
350 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000351 newFunction->setDoesNotThrow();
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000352
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000353 newFunction->getBasicBlockList().push_back(newRootNode);
354
Chris Lattner37de2572004-03-18 03:49:40 +0000355 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000356 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000357
358 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000359 // arguments (or appropriate addressing into struct) instead.
360 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
361 Value *RewriteVal;
362 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000363 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000364 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
365 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000366 TerminatorInst *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000367 GetElementPtrInst *GEP = GetElementPtrInst::Create(
368 StructTy, AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000369 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000370 } else
371 RewriteVal = AI++;
372
Chandler Carruthcdf47882014-03-09 03:16:01 +0000373 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000374 for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
Chris Lattner36844692004-03-14 03:17:22 +0000375 use != useE; ++use)
376 if (Instruction* inst = dyn_cast<Instruction>(*use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000377 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000378 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000379 }
380
Misha Brukman3596f0a2004-04-23 23:54:17 +0000381 // Set names for input and output arguments.
382 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000383 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000384 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000385 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000386 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000387 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000388 }
Chris Lattner37de2572004-03-18 03:49:40 +0000389
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000390 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
391 // within the new function. This must be done before we lose track of which
392 // blocks were originally in the code region.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000393 std::vector<User*> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000394 for (unsigned i = 0, e = Users.size(); i != e; ++i)
395 // The BasicBlock which contains the branch is not in the region
396 // modify the branch target to a new block
397 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000398 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000399 TI->getParent()->getParent() == oldFunction)
400 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000401
402 return newFunction;
403}
404
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000405/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
406/// that uses the value within the basic block, and return the predecessor
407/// block associated with that use, or return 0 if none is found.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000408static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000409 for (Use &U : Used->uses()) {
410 PHINode *P = dyn_cast<PHINode>(U.getUser());
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000411 if (P && P->getParent() == BB)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000412 return P->getIncomingBlock(U);
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000413 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000414
Craig Topperf40110f2014-04-25 05:29:35 +0000415 return nullptr;
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000416}
417
Chris Lattner3b2917b2004-05-12 06:01:40 +0000418/// emitCallAndSwitchStatement - This method sets up the caller side by adding
419/// the call instruction, splitting any PHI nodes in the header block as
420/// necessary.
421void CodeExtractor::
422emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000423 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000424 // Emit a call to the new function, passing in: *pointer to struct (if
425 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000426 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Owen Anderson55f1c092009-08-13 21:58:54 +0000427
428 LLVMContext &Context = newFunction->getContext();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000429
Misha Brukman3596f0a2004-04-23 23:54:17 +0000430 // Add inputs as params, or to be filled into the struct
Chandler Carruth0fde0012012-05-04 10:18:49 +0000431 for (ValueSet::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000432 if (AggregateArgs)
433 StructValues.push_back(*i);
434 else
435 params.push_back(*i);
436
437 // Create allocas for the outputs
Chandler Carruth0fde0012012-05-04 10:18:49 +0000438 for (ValueSet::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000439 if (AggregateArgs) {
440 StructValues.push_back(*i);
441 } else {
442 AllocaInst *alloca =
Craig Topperf40110f2014-04-25 05:29:35 +0000443 new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
Misha Brukman3596f0a2004-04-23 23:54:17 +0000444 codeReplacer->getParent()->begin()->begin());
445 ReloadOutputs.push_back(alloca);
446 params.push_back(alloca);
447 }
448 }
449
David Blaikie741c8f82015-03-14 01:53:18 +0000450 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000451 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000452 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000453 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000454 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000455 ve = StructValues.end(); v != ve; ++v)
456 ArgTypes.push_back((*v)->getType());
457
458 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +0000459 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000460 Struct =
Craig Topperf40110f2014-04-25 05:29:35 +0000461 new AllocaInst(StructArgTy, nullptr, "structArg",
Chris Lattner37de2572004-03-18 03:49:40 +0000462 codeReplacer->getParent()->begin()->begin());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000463 params.push_back(Struct);
464
465 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000466 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000467 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
468 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +0000469 GetElementPtrInst *GEP = GetElementPtrInst::Create(
470 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000471 codeReplacer->getInstList().push_back(GEP);
472 StoreInst *SI = new StoreInst(StructValues[i], GEP);
473 codeReplacer->getInstList().push_back(SI);
474 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000475 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000476
477 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000478 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000479 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000480 codeReplacer->getInstList().push_back(call);
481
Chris Lattner531f9e92005-03-15 04:54:21 +0000482 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000483 unsigned FirstOut = inputs.size();
484 if (!AggregateArgs)
485 std::advance(OutputArgBegin, inputs.size());
486
487 // Reload the outputs passed in by reference
488 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000489 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000490 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000491 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000492 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
493 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +0000494 GetElementPtrInst *GEP = GetElementPtrInst::Create(
495 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000496 codeReplacer->getInstList().push_back(GEP);
497 Output = GEP;
498 } else {
499 Output = ReloadOutputs[i];
500 }
501 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000502 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000503 codeReplacer->getInstList().push_back(load);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000504 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +0000505 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
506 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000507 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000508 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000509 }
510 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000511
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000512 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000513 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000514 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000515 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000516
517 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000518 // function return an unsigned, switch on that number. This loop iterates
519 // over all of the blocks in the extracted region, updating any terminator
520 // instructions in the to-be-extracted region that branch to blocks that are
521 // not in the region to be extracted.
522 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
523
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000524 unsigned switchVal = 0;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000525 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
526 e = Blocks.end(); i != e; ++i) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000527 TerminatorInst *TI = (*i)->getTerminator();
528 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000529 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000530 BasicBlock *OldTarget = TI->getSuccessor(i);
531 // add a new basic block which returns the appropriate value
532 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
533 if (!NewTarget) {
534 // If we don't already have an exit stub for this non-extracted
535 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000536 NewTarget = BasicBlock::Create(Context,
537 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000538 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000539 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000540
Craig Topperf40110f2014-04-25 05:29:35 +0000541 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +0000542 switch (NumExitBlocks) {
543 case 0:
544 case 1: break; // No value needed.
545 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000546 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000547 break;
548 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000549 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000550 break;
551 }
552
Owen Anderson55f1c092009-08-13 21:58:54 +0000553 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000554
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000555 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000556 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
557 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000558 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000559
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000560 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000561 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000562 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
David Majnemer0bc0eef2015-08-15 02:46:08 +0000563 // For an invoke/catchpad, the normal destination is the only one
564 // that is dominated by the result of the invocation
Misha Brukman3596f0a2004-04-23 23:54:17 +0000565 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000566
567 bool DominatesDef = true;
568
David Majnemer0bc0eef2015-08-15 02:46:08 +0000569 BasicBlock *NormalDest = nullptr;
570 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
571 NormalDest = Invoke->getNormalDest();
572 if (auto *CatchPad = dyn_cast<CatchPadInst>(outputs[out]))
573 NormalDest = CatchPad->getNormalDest();
574
575 if (NormalDest) {
576 DefBlock = NormalDest;
Chris Lattner5bcca602004-11-12 23:50:44 +0000577
578 // Make sure we are looking at the original successor block, not
579 // at a newly inserted exit block, which won't be in the dominator
580 // info.
581 for (std::map<BasicBlock*, BasicBlock*>::iterator I =
582 ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
583 if (DefBlock == I->second) {
584 DefBlock = I->first;
585 break;
586 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000587
588 // In the extract block case, if the block we are extracting ends
589 // with an invoke instruction, make sure that we don't emit a
590 // store of the invoke value for the unwind block.
Devang Patelcf470e52007-06-07 22:17:16 +0000591 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000592 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000593 }
594
Owen Anderson34e61482009-08-25 00:54:39 +0000595 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000596 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000597
598 // If the output value is used by a phi in the target block,
599 // then we need to test for dominance of the phi's predecessor
600 // instead. Unfortunately, this a little complicated since we
601 // have already rewritten uses of the value to uses of the reload.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000602 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
603 OldTarget);
604 if (pred && DT && DT->dominates(DefBlock, pred))
605 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000606 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000607
608 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000609 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000610 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000611 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
612 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
613 FirstOut+out);
David Blaikie741c8f82015-03-14 01:53:18 +0000614 GetElementPtrInst *GEP = GetElementPtrInst::Create(
615 StructArgTy, OAI, Idx, "gep_" + outputs[out]->getName(),
616 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000617 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000618 } else {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000619 new StoreInst(outputs[out], OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000620 }
621 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000622 // Advance output iterator even if we don't emit a store
623 if (!AggregateArgs) ++OAI;
624 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000625 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000626
627 // rewrite the original branch instruction with this new target
628 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000629 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000630 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000631
Chris Lattner3d1ca672004-05-12 03:22:33 +0000632 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000633 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000634 switch (NumExitBlocks) {
635 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000636 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000637 // means that previously this was the last part of the function, and hence
638 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000639
Misha Brukman3596f0a2004-04-23 23:54:17 +0000640 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000641 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000642 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000643 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000644 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000645 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000646 } else {
647 // Otherwise we must have code extracted an unwind or something, just
648 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000649 ReturnInst::Create(Context,
650 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000651 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000652
Dan Gohman158ff2c2008-06-21 22:08:46 +0000653 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000654 break;
655 case 1:
656 // Only a single destination, change the switch into an unconditional
657 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000658 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000659 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000660 break;
661 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000662 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
663 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000664 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000665 break;
666 default:
667 // Otherwise, make the default destination of the switch instruction be one
668 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000669 TheSwitch->setCondition(call);
670 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000671 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +0000672 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000673 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000674 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000675}
676
Chris Lattner3b2917b2004-05-12 06:01:40 +0000677void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000678 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000679 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
680 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
681
Chandler Carruth0fde0012012-05-04 10:18:49 +0000682 for (SetVector<BasicBlock*>::const_iterator i = Blocks.begin(),
683 e = Blocks.end(); i != e; ++i) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000684 // Delete the basic block from the old function, and the list of blocks
685 oldBlocks.remove(*i);
686
687 // Insert this basic block into the new function
688 newBlocks.push_back(*i);
689 }
690}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000691
Chandler Carruth0fde0012012-05-04 10:18:49 +0000692Function *CodeExtractor::extractCodeRegion() {
693 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +0000694 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000695
Chandler Carruth0fde0012012-05-04 10:18:49 +0000696 ValueSet inputs, outputs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000697
698 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000699 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000700 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000701
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000702 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +0000703 severSplitPHINodes(header);
704
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000705 // If we have any return instructions in the region, split those blocks so
706 // that the return is not in the region.
707 splitReturnBlocks();
708
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000709 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000710
711 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +0000712 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
713 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +0000714 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000715
716 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +0000717 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +0000718 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
719 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +0000720 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000721
Chris Lattner3b2917b2004-05-12 06:01:40 +0000722 // Find inputs to, outputs from the code region.
723 findInputsOutputs(inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000724
Chandler Carruth14316fc2012-05-04 11:20:27 +0000725 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
726 for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
727 I != E; ++I)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000728 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
729 if (!Blocks.count(*SI))
730 ExitBlocks.insert(*SI);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000731 NumExitBlocks = ExitBlocks.size();
732
Chris Lattner3b2917b2004-05-12 06:01:40 +0000733 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +0000734 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +0000735 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000736 codeReplacer, oldFunction,
737 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000738
Chris Lattner9c431f62004-03-14 22:34:55 +0000739 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000740
Chris Lattner9c431f62004-03-14 22:34:55 +0000741 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000742
Chris Lattner795c9932004-05-12 15:29:13 +0000743 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +0000744 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +0000745 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
746 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +0000747 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000748 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +0000749 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +0000750 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000751
Chris Lattneracd75982004-03-18 05:38:31 +0000752 // Look at all successors of the codeReplacer block. If any of these blocks
753 // had PHI nodes in them, we need to update the "from" block to be the code
754 // replacer, not the original block in the extracted region.
755 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
756 succ_end(codeReplacer));
757 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +0000758 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
759 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +0000760 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +0000761 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000762 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +0000763 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
764 PN->setIncomingBlock(i, codeReplacer);
765 else {
766 // There were multiple entries in the PHI for this block, now there
767 // is only one, so remove the duplicated entries.
768 PN->removeIncomingValue(i, false);
769 --i; --e;
770 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000771 }
Chris Lattner56273822004-08-13 03:27:07 +0000772 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000773
Bill Wendlingf3baad32006-12-07 01:30:32 +0000774 //cerr << "NEW FUNCTION: " << *newFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000775 // verifyFunction(*newFunction);
776
Bill Wendlingf3baad32006-12-07 01:30:32 +0000777 // cerr << "OLD FUNCTION: " << *oldFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000778 // verifyFunction(*oldFunction);
Chris Lattneracd75982004-03-18 05:38:31 +0000779
Torok Edwinccb29cd2009-07-11 13:10:19 +0000780 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000781 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000782 return newFunction;
783}