blob: da83f0ac59196d071f9002e8c97955815fd5d79b [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"
Sean Silvaf8015752016-08-02 02:15:45 +000020#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
22#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/RegionInfo.h"
25#include "llvm/Analysis/RegionIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
Sean Silvaf8015752016-08-02 02:15:45 +000032#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000035#include "llvm/Pass.h"
Sean Silvaf8015752016-08-02 02:15:45 +000036#include "llvm/Support/BlockFrequency.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000039#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000040#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000042#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000043#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000044using namespace llvm;
45
Chandler Carruthe96dd892014-04-21 22:55:11 +000046#define DEBUG_TYPE "code-extractor"
47
Misha Brukman3596f0a2004-04-23 23:54:17 +000048// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000049// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000050// extracted functions to pthread-based code, as only one argument (void*) can
51// be passed in to pthread_create().
52static cl::opt<bool>
53AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
54 cl::desc("Aggregate arguments to code-extracted functions"));
55
Chandler Carruth0fde0012012-05-04 10:18:49 +000056/// \brief Test whether a block is valid for extraction.
Sean Silva285e0972016-07-27 08:02:46 +000057bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000058 // Landing pads must be in the function where they were inserted for cleanup.
David Majnemereb518bd2015-08-04 08:21:40 +000059 if (BB.isEHPad())
Chandler Carruth0fde0012012-05-04 10:18:49 +000060 return false;
Chris Lattner37de2572004-03-18 03:49:40 +000061
Chandler Carruth0fde0012012-05-04 10:18:49 +000062 // Don't hoist code containing allocas, invokes, or vastarts.
63 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
64 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +000065 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000066 if (const CallInst *CI = dyn_cast<CallInst>(I))
67 if (const Function *F = CI->getCalledFunction())
68 if (F->getIntrinsicID() == Intrinsic::vastart)
69 return false;
70 }
71
72 return true;
73}
74
75/// \brief Build a set of blocks to extract if the input blocks are viable.
Chandler Carruth67818212012-05-04 21:33:30 +000076template <typename IteratorT>
77static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin,
78 IteratorT BBEnd) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000079 SetVector<BasicBlock *> Result;
80
Chandler Carruth67818212012-05-04 21:33:30 +000081 assert(BBBegin != BBEnd);
Chandler Carruth2f5d0192012-05-04 10:26:45 +000082
Chandler Carruth0fde0012012-05-04 10:18:49 +000083 // Loop over the blocks, adding them to our set-vector, and aborting with an
84 // empty set if we encounter invalid blocks.
Benjamin Kramer4fed9282016-05-27 12:30:51 +000085 do {
86 if (!Result.insert(*BBBegin))
Chandler Carruth44e13912012-05-04 11:17:06 +000087 llvm_unreachable("Repeated basic blocks in extraction input");
Chandler Carruth0fde0012012-05-04 10:18:49 +000088
Sean Silva285e0972016-07-27 08:02:46 +000089 if (!CodeExtractor::isBlockValidForExtraction(**BBBegin)) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000090 Result.clear();
Chandler Carruth0a570552012-05-04 11:14:19 +000091 return Result;
Chris Lattner3b2917b2004-05-12 06:01:40 +000092 }
Benjamin Kramer4fed9282016-05-27 12:30:51 +000093 } while (++BBBegin != BBEnd);
Misha Brukmanb1c93172005-04-21 23:48:37 +000094
Chandler Carruth2f5d0192012-05-04 10:26:45 +000095#ifndef NDEBUG
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +000096 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
Chandler Carruth67818212012-05-04 21:33:30 +000097 E = Result.end();
Chandler Carruth2f5d0192012-05-04 10:26:45 +000098 I != E; ++I)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +000099 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
100 PI != PE; ++PI)
101 assert(Result.count(*PI) &&
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000102 "No blocks in this region may have entries from outside the region"
103 " except for the first block!");
104#endif
105
Chandler Carruth0fde0012012-05-04 10:18:49 +0000106 return Result;
107}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000108
Chandler Carruth67818212012-05-04 21:33:30 +0000109/// \brief Helper to call buildExtractionBlockSet with an ArrayRef.
110static SetVector<BasicBlock *>
111buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) {
112 return buildExtractionBlockSet(BBs.begin(), BBs.end());
113}
114
Chandler Carruth0fde0012012-05-04 10:18:49 +0000115CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sean Silvaf8015752016-08-02 02:15:45 +0000116 bool AggregateArgs, BlockFrequencyInfo *BFI,
117 BranchProbabilityInfo *BPI)
118 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
119 BPI(BPI), Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000120
Sean Silvaf8015752016-08-02 02:15:45 +0000121CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
122 BlockFrequencyInfo *BFI,
123 BranchProbabilityInfo *BPI)
124 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
125 BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks())),
126 NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000127
Chandler Carruth0fde0012012-05-04 10:18:49 +0000128/// definedInRegion - Return true if the specified value is defined in the
129/// extracted region.
130static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
131 if (Instruction *I = dyn_cast<Instruction>(V))
132 if (Blocks.count(I->getParent()))
133 return true;
134 return false;
135}
136
137/// definedInCaller - Return true if the specified value is defined in the
138/// function being code extracted, but not in the region being extracted.
139/// These values must be passed in as live-ins to the function.
140static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
141 if (isa<Argument>(V)) return true;
142 if (Instruction *I = dyn_cast<Instruction>(V))
143 if (!Blocks.count(I->getParent()))
144 return true;
145 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000146}
147
Chandler Carruth14316fc2012-05-04 11:20:27 +0000148void CodeExtractor::findInputsOutputs(ValueSet &Inputs,
149 ValueSet &Outputs) const {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000150 for (BasicBlock *BB : Blocks) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000151 // If a used value is defined outside the region, it's an input. If an
152 // instruction is used outside the region, it's an output.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000153 for (Instruction &II : *BB) {
154 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
155 ++OI)
Chandler Carruth14316fc2012-05-04 11:20:27 +0000156 if (definedInCaller(Blocks, *OI))
157 Inputs.insert(*OI);
158
Benjamin Kramer135f7352016-06-26 12:28:59 +0000159 for (User *U : II.users())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000160 if (!definedInRegion(Blocks, U)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000161 Outputs.insert(&II);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000162 break;
163 }
164 }
165 }
166}
167
Chris Lattner3b2917b2004-05-12 06:01:40 +0000168/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
169/// region, we need to split the entry block of the region so that the PHI node
170/// is easier to deal with.
171void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000172 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000173 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000174
Dan Gohmandcb291f2007-03-22 16:38:57 +0000175 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000176 PHINode *PN = dyn_cast<PHINode>(Header->begin());
177 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000178
Chris Lattner795c9932004-05-12 15:29:13 +0000179 // If the header node contains any PHI nodes, check to see if there is more
180 // than one entry from outside the region. If so, we need to sever the
181 // header block into two.
182 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000183 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000184 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000185 else
186 ++NumPredsOutsideRegion;
187
188 // If there is one (or fewer) predecessor from outside the region, we don't
189 // need to do anything special.
190 if (NumPredsOutsideRegion <= 1) return;
191 }
192
193 // Otherwise, we need to split the header block into two pieces: one
194 // containing PHI nodes merging values from outside of the region, and a
195 // second that contains all of the code for the block and merges back any
196 // incoming values from inside of the region.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000197 BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT);
Chris Lattner795c9932004-05-12 15:29:13 +0000198
199 // We only want to code extract the second block now, and it becomes the new
200 // header of the region.
201 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000202 Blocks.remove(OldPred);
203 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000204 Header = NewBB;
205
Chris Lattner795c9932004-05-12 15:29:13 +0000206 // Okay, now we need to adjust the PHI nodes and any branches from within the
207 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000208 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000209 PHINode *PN = cast<PHINode>(OldPred->begin());
210 // Loop over all of the predecessors of OldPred that are in the region,
211 // changing them to branch to NewBB instead.
212 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000213 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000214 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
215 TI->replaceUsesOfWith(OldPred, NewBB);
216 }
217
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000218 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000219 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000220 BasicBlock::iterator AfterPHIs;
Reid Spencer66149462004-09-15 17:06:42 +0000221 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
222 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000223 // Create a new PHI node in the new region, which has an incoming value
224 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000225 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000226 PN->getName() + ".ce", &NewBB->front());
Chris Lattner795c9932004-05-12 15:29:13 +0000227 NewPN->addIncoming(PN, OldPred);
228
229 // Loop over all of the incoming value in PN, moving them to NewPN if they
230 // are from the extracted region.
231 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000232 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000233 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
234 PN->removeIncomingValue(i);
235 --i;
236 }
237 }
238 }
239 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000240}
Chris Lattner795c9932004-05-12 15:29:13 +0000241
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000242void CodeExtractor::splitReturnBlocks() {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000243 for (BasicBlock *Block : Blocks)
244 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000245 BasicBlock *New =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000246 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000247 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000248 // Old dominates New. New node dominates all other nodes dominated
249 // by Old.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000250 DomTreeNode *OldNode = DT->getNode(Block);
251 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
252 OldNode->end());
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000253
Benjamin Kramer135f7352016-06-26 12:28:59 +0000254 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000255
Benjamin Kramer135f7352016-06-26 12:28:59 +0000256 for (DomTreeNode *I : Children)
257 DT->changeImmediateDominator(I, NewNode);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000258 }
259 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000260}
261
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000262/// constructFunction - make a function based on inputs and outputs, as follows:
263/// f(in0, ..., inN, out0, ..., outN)
264///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000265Function *CodeExtractor::constructFunction(const ValueSet &inputs,
266 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000267 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000268 BasicBlock *newRootNode,
269 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000270 Function *oldFunction,
271 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000272 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
273 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000274
275 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000276 switch (NumExitBlocks) {
277 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000278 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
279 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
280 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000281 }
282
Jay Foadb804a2b2011-07-12 14:06:48 +0000283 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000284
285 // Add the types of the input values to the function's argument list
Benjamin Kramer135f7352016-06-26 12:28:59 +0000286 for (Value *value : inputs) {
David Greene0ad6dce2010-01-05 01:26:44 +0000287 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000288 paramTy.push_back(value->getType());
289 }
290
Chris Lattner37de2572004-03-18 03:49:40 +0000291 // Add the types of the output values to the function's argument list.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000292 for (Value *output : outputs) {
293 DEBUG(dbgs() << "instr used in func: " << *output << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000294 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000295 paramTy.push_back(output->getType());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000296 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000297 paramTy.push_back(PointerType::getUnqual(output->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000298 }
299
Benjamin Kramer706e48832016-06-26 13:39:33 +0000300 DEBUG({
301 dbgs() << "Function type: " << *RetTy << " f(";
302 for (Type *i : paramTy)
303 dbgs() << *i << ", ";
304 dbgs() << ")\n";
305 });
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000306
David Blaikie741c8f82015-03-14 01:53:18 +0000307 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000308 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000309 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000310 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000311 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000312 }
Chris Lattner229907c2011-07-18 04:54:35 +0000313 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000314 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000315
316 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000317 Function *newFunction = Function::Create(funcType,
318 GlobalValue::InternalLinkage,
319 oldFunction->getName() + "_" +
320 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000321 // If the old function is no-throw, so is the new one.
322 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000323 newFunction->setDoesNotThrow();
Sean Silvaa0a802a2016-08-01 03:15:32 +0000324
325 // Inherit the uwtable attribute if we need to.
326 if (oldFunction->hasUWTable())
327 newFunction->setHasUWTable();
328
329 // Inherit all of the target dependent attributes.
330 // (e.g. If the extracted region contains a call to an x86.sse
331 // instruction we need to make sure that the extracted region has the
332 // "target-features" attribute allowing it to be lowered.
333 // FIXME: This should be changed to check to see if a specific
334 // attribute can not be inherited.
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000335 AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
Sean Silva9011aca2017-02-22 06:34:04 +0000336 for (const auto &Attr : AB.td_attrs())
Sean Silvaa0a802a2016-08-01 03:15:32 +0000337 newFunction->addFnAttr(Attr.first, Attr.second);
338
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000339 newFunction->getBasicBlockList().push_back(newRootNode);
340
Chris Lattner37de2572004-03-18 03:49:40 +0000341 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000342 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000343
344 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000345 // arguments (or appropriate addressing into struct) instead.
346 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
347 Value *RewriteVal;
348 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000349 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000350 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
351 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000352 TerminatorInst *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000353 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000354 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000355 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000356 } else
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000357 RewriteVal = &*AI++;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000358
Chandler Carruthcdf47882014-03-09 03:16:01 +0000359 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000360 for (User *use : Users)
361 if (Instruction *inst = dyn_cast<Instruction>(use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000362 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000363 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000364 }
365
Misha Brukman3596f0a2004-04-23 23:54:17 +0000366 // Set names for input and output arguments.
367 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000368 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000369 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000370 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000371 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000372 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000373 }
Chris Lattner37de2572004-03-18 03:49:40 +0000374
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000375 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
376 // within the new function. This must be done before we lose track of which
377 // blocks were originally in the code region.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000378 std::vector<User*> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000379 for (unsigned i = 0, e = Users.size(); i != e; ++i)
380 // The BasicBlock which contains the branch is not in the region
381 // modify the branch target to a new block
382 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000383 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000384 TI->getParent()->getParent() == oldFunction)
385 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000386
387 return newFunction;
388}
389
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000390/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
391/// that uses the value within the basic block, and return the predecessor
392/// block associated with that use, or return 0 if none is found.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000393static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000394 for (Use &U : Used->uses()) {
395 PHINode *P = dyn_cast<PHINode>(U.getUser());
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000396 if (P && P->getParent() == BB)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000397 return P->getIncomingBlock(U);
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000398 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399
Craig Topperf40110f2014-04-25 05:29:35 +0000400 return nullptr;
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000401}
402
Chris Lattner3b2917b2004-05-12 06:01:40 +0000403/// emitCallAndSwitchStatement - This method sets up the caller side by adding
404/// the call instruction, splitting any PHI nodes in the header block as
405/// necessary.
406void CodeExtractor::
407emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000408 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000409 // Emit a call to the new function, passing in: *pointer to struct (if
410 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000411 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000412
413 Module *M = newFunction->getParent();
414 LLVMContext &Context = M->getContext();
415 const DataLayout &DL = M->getDataLayout();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000416
Misha Brukman3596f0a2004-04-23 23:54:17 +0000417 // Add inputs as params, or to be filled into the struct
Benjamin Kramer135f7352016-06-26 12:28:59 +0000418 for (Value *input : inputs)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000419 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000420 StructValues.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000421 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000422 params.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000423
424 // Create allocas for the outputs
Benjamin Kramer135f7352016-06-26 12:28:59 +0000425 for (Value *output : outputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000426 if (AggregateArgs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000427 StructValues.push_back(output);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000428 } else {
429 AllocaInst *alloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000430 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
431 nullptr, output->getName() + ".loc",
432 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000433 ReloadOutputs.push_back(alloca);
434 params.push_back(alloca);
435 }
436 }
437
David Blaikie741c8f82015-03-14 01:53:18 +0000438 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000439 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000440 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000441 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000442 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000443 ve = StructValues.end(); v != ve; ++v)
444 ArgTypes.push_back((*v)->getType());
445
446 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +0000447 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000448 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
449 "structArg",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000450 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000451 params.push_back(Struct);
452
453 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000454 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000455 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
456 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +0000457 GetElementPtrInst *GEP = GetElementPtrInst::Create(
458 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000459 codeReplacer->getInstList().push_back(GEP);
460 StoreInst *SI = new StoreInst(StructValues[i], GEP);
461 codeReplacer->getInstList().push_back(SI);
462 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000463 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000464
465 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000466 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000467 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000468 codeReplacer->getInstList().push_back(call);
469
Chris Lattner531f9e92005-03-15 04:54:21 +0000470 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000471 unsigned FirstOut = inputs.size();
472 if (!AggregateArgs)
473 std::advance(OutputArgBegin, inputs.size());
474
475 // Reload the outputs passed in by reference
476 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000477 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000478 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000479 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000480 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
481 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +0000482 GetElementPtrInst *GEP = GetElementPtrInst::Create(
483 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000484 codeReplacer->getInstList().push_back(GEP);
485 Output = GEP;
486 } else {
487 Output = ReloadOutputs[i];
488 }
489 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000490 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000491 codeReplacer->getInstList().push_back(load);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000492 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +0000493 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
494 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000495 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000496 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000497 }
498 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000499
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000500 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000501 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000502 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000503 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000504
505 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000506 // function return an unsigned, switch on that number. This loop iterates
507 // over all of the blocks in the extracted region, updating any terminator
508 // instructions in the to-be-extracted region that branch to blocks that are
509 // not in the region to be extracted.
510 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
511
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000512 unsigned switchVal = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000513 for (BasicBlock *Block : Blocks) {
514 TerminatorInst *TI = Block->getTerminator();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000515 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000516 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000517 BasicBlock *OldTarget = TI->getSuccessor(i);
518 // add a new basic block which returns the appropriate value
519 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
520 if (!NewTarget) {
521 // If we don't already have an exit stub for this non-extracted
522 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000523 NewTarget = BasicBlock::Create(Context,
524 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000525 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000526 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000527
Craig Topperf40110f2014-04-25 05:29:35 +0000528 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +0000529 switch (NumExitBlocks) {
530 case 0:
531 case 1: break; // No value needed.
532 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000533 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000534 break;
535 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000536 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000537 break;
538 }
539
Owen Anderson55f1c092009-08-13 21:58:54 +0000540 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000541
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000542 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000543 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
544 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000545 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000546
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000547 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000548 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000549 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000550 // For an invoke, the normal destination is the only one that is
551 // dominated by the result of the invocation
Misha Brukman3596f0a2004-04-23 23:54:17 +0000552 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000553
554 bool DominatesDef = true;
555
David Majnemer0bc0eef2015-08-15 02:46:08 +0000556 BasicBlock *NormalDest = nullptr;
557 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
558 NormalDest = Invoke->getNormalDest();
David Majnemer0bc0eef2015-08-15 02:46:08 +0000559
560 if (NormalDest) {
561 DefBlock = NormalDest;
Chris Lattner5bcca602004-11-12 23:50:44 +0000562
563 // Make sure we are looking at the original successor block, not
564 // at a newly inserted exit block, which won't be in the dominator
565 // info.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000566 for (const auto &I : ExitBlockMap)
567 if (DefBlock == I.second) {
568 DefBlock = I.first;
Chris Lattner5bcca602004-11-12 23:50:44 +0000569 break;
570 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000571
572 // In the extract block case, if the block we are extracting ends
573 // with an invoke instruction, make sure that we don't emit a
574 // store of the invoke value for the unwind block.
Devang Patelcf470e52007-06-07 22:17:16 +0000575 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000576 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000577 }
578
Owen Anderson34e61482009-08-25 00:54:39 +0000579 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000580 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000581
582 // If the output value is used by a phi in the target block,
583 // then we need to test for dominance of the phi's predecessor
584 // instead. Unfortunately, this a little complicated since we
585 // have already rewritten uses of the value to uses of the reload.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000586 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
587 OldTarget);
588 if (pred && DT && DT->dominates(DefBlock, pred))
589 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000590 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000591
592 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000593 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000594 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000595 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
596 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
597 FirstOut+out);
David Blaikie741c8f82015-03-14 01:53:18 +0000598 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000599 StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
David Blaikie741c8f82015-03-14 01:53:18 +0000600 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000601 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000602 } else {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000603 new StoreInst(outputs[out], &*OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000604 }
605 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000606 // Advance output iterator even if we don't emit a store
607 if (!AggregateArgs) ++OAI;
608 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000609 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000610
611 // rewrite the original branch instruction with this new target
612 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000613 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000614 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000615
Chris Lattner3d1ca672004-05-12 03:22:33 +0000616 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000617 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000618 switch (NumExitBlocks) {
619 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000620 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000621 // means that previously this was the last part of the function, and hence
622 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000623
Misha Brukman3596f0a2004-04-23 23:54:17 +0000624 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000625 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000626 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000627 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000628 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000629 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000630 } else {
631 // Otherwise we must have code extracted an unwind or something, just
632 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000633 ReturnInst::Create(Context,
634 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000635 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000636
Dan Gohman158ff2c2008-06-21 22:08:46 +0000637 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000638 break;
639 case 1:
640 // Only a single destination, change the switch into an unconditional
641 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000642 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000643 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000644 break;
645 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000646 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
647 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000648 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000649 break;
650 default:
651 // Otherwise, make the default destination of the switch instruction be one
652 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000653 TheSwitch->setCondition(call);
654 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000655 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +0000656 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000657 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000658 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000659}
660
Chris Lattner3b2917b2004-05-12 06:01:40 +0000661void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000662 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000663 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
664 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
665
Benjamin Kramer135f7352016-06-26 12:28:59 +0000666 for (BasicBlock *Block : Blocks) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000667 // Delete the basic block from the old function, and the list of blocks
Benjamin Kramer135f7352016-06-26 12:28:59 +0000668 oldBlocks.remove(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000669
670 // Insert this basic block into the new function
Benjamin Kramer135f7352016-06-26 12:28:59 +0000671 newBlocks.push_back(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000672 }
673}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000674
Sean Silvaf8015752016-08-02 02:15:45 +0000675void CodeExtractor::calculateNewCallTerminatorWeights(
676 BasicBlock *CodeReplacer,
677 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
678 BranchProbabilityInfo *BPI) {
679 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
680 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
681
682 // Update the branch weights for the exit block.
683 TerminatorInst *TI = CodeReplacer->getTerminator();
684 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
685
686 // Block Frequency distribution with dummy node.
687 Distribution BranchDist;
688
689 // Add each of the frequencies of the successors.
690 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
691 BlockNode ExitNode(i);
692 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
693 if (ExitFreq != 0)
694 BranchDist.addExit(ExitNode, ExitFreq);
695 else
696 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
697 }
698
699 // Check for no total weight.
700 if (BranchDist.Total == 0)
701 return;
702
703 // Normalize the distribution so that they can fit in unsigned.
704 BranchDist.normalize();
705
706 // Create normalized branch weights and set the metadata.
707 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
708 const auto &Weight = BranchDist.Weights[I];
709
710 // Get the weight and update the current BFI.
711 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
712 BranchProbability BP(Weight.Amount, BranchDist.Total);
713 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
714 }
715 TI->setMetadata(
716 LLVMContext::MD_prof,
717 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
718}
719
Chandler Carruth0fde0012012-05-04 10:18:49 +0000720Function *CodeExtractor::extractCodeRegion() {
721 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +0000722 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000723
Chandler Carruth0fde0012012-05-04 10:18:49 +0000724 ValueSet inputs, outputs;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000725
726 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000727 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000728 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000729
Sean Silvaf8015752016-08-02 02:15:45 +0000730 // Calculate the entry frequency of the new function before we change the root
731 // block.
732 BlockFrequency EntryFreq;
733 if (BFI) {
734 assert(BPI && "Both BPI and BFI are required to preserve profile info");
735 for (BasicBlock *Pred : predecessors(header)) {
736 if (Blocks.count(Pred))
737 continue;
738 EntryFreq +=
739 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
740 }
741 }
742
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000743 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +0000744 severSplitPHINodes(header);
745
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000746 // If we have any return instructions in the region, split those blocks so
747 // that the return is not in the region.
748 splitReturnBlocks();
749
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000750 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000751
752 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +0000753 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
754 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +0000755 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000756
757 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +0000758 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +0000759 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
760 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +0000761 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000762
Chris Lattner3b2917b2004-05-12 06:01:40 +0000763 // Find inputs to, outputs from the code region.
764 findInputsOutputs(inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000765
Sean Silvaf8015752016-08-02 02:15:45 +0000766 // Calculate the exit blocks for the extracted region and the total exit
767 // weights for each of those blocks.
768 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
Chandler Carruth14316fc2012-05-04 11:20:27 +0000769 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
Sean Silvaf8015752016-08-02 02:15:45 +0000770 for (BasicBlock *Block : Blocks) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000771 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
Sean Silvaf8015752016-08-02 02:15:45 +0000772 ++SI) {
773 if (!Blocks.count(*SI)) {
774 // Update the branch weight for this successor.
775 if (BFI) {
776 BlockFrequency &BF = ExitWeights[*SI];
777 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
778 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000779 ExitBlocks.insert(*SI);
Sean Silvaf8015752016-08-02 02:15:45 +0000780 }
781 }
782 }
Chandler Carruth14316fc2012-05-04 11:20:27 +0000783 NumExitBlocks = ExitBlocks.size();
784
Chris Lattner3b2917b2004-05-12 06:01:40 +0000785 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +0000786 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +0000787 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000788 codeReplacer, oldFunction,
789 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000790
Sean Silvaf8015752016-08-02 02:15:45 +0000791 // Update the entry count of the function.
792 if (BFI) {
793 Optional<uint64_t> EntryCount =
794 BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
795 if (EntryCount.hasValue())
796 newFunction->setEntryCount(EntryCount.getValue());
797 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
798 }
799
Chris Lattner9c431f62004-03-14 22:34:55 +0000800 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000801
Chris Lattner9c431f62004-03-14 22:34:55 +0000802 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000803
Sean Silvaf8015752016-08-02 02:15:45 +0000804 // Update the branch weights for the exit block.
805 if (BFI && NumExitBlocks > 1)
806 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
807
Chris Lattner795c9932004-05-12 15:29:13 +0000808 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +0000809 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +0000810 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
811 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +0000812 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000813 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +0000814 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +0000815 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000816
Chris Lattneracd75982004-03-18 05:38:31 +0000817 // Look at all successors of the codeReplacer block. If any of these blocks
818 // had PHI nodes in them, we need to update the "from" block to be the code
819 // replacer, not the original block in the extracted region.
820 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
821 succ_end(codeReplacer));
822 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +0000823 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
824 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +0000825 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +0000826 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000827 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +0000828 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
829 PN->setIncomingBlock(i, codeReplacer);
830 else {
831 // There were multiple entries in the PHI for this block, now there
832 // is only one, so remove the duplicated entries.
833 PN->removeIncomingValue(i, false);
834 --i; --e;
835 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000836 }
Chris Lattner56273822004-08-13 03:27:07 +0000837 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000838
Bill Wendlingf3baad32006-12-07 01:30:32 +0000839 //cerr << "NEW FUNCTION: " << *newFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000840 // verifyFunction(*newFunction);
841
Bill Wendlingf3baad32006-12-07 01:30:32 +0000842 // cerr << "OLD FUNCTION: " << *oldFunction;
Chris Lattner795c9932004-05-12 15:29:13 +0000843 // verifyFunction(*oldFunction);
Chris Lattneracd75982004-03-18 05:38:31 +0000844
Torok Edwinccb29cd2009-07-11 13:10:19 +0000845 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000846 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000847 return newFunction;
848}