blob: 1189714dfab10be5c18f89309cf6971aeccf8a04 [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"
Xinliang David Li74480ad2017-05-30 21:22:18 +000030#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
Sean Silvaf8015752016-08-02 02:15:45 +000033#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000036#include "llvm/Pass.h"
Sean Silvaf8015752016-08-02 02:15:45 +000037#include "llvm/Support/BlockFrequency.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000043#include <algorithm>
Chris Lattner9c431f62004-03-14 22:34:55 +000044#include <set>
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000045using namespace llvm;
46
Chandler Carruthe96dd892014-04-21 22:55:11 +000047#define DEBUG_TYPE "code-extractor"
48
Misha Brukman3596f0a2004-04-23 23:54:17 +000049// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000050// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000051// extracted functions to pthread-based code, as only one argument (void*) can
52// be passed in to pthread_create().
53static cl::opt<bool>
54AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
55 cl::desc("Aggregate arguments to code-extracted functions"));
56
Chandler Carruth0fde0012012-05-04 10:18:49 +000057/// \brief Test whether a block is valid for extraction.
Sean Silva285e0972016-07-27 08:02:46 +000058bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000059 // Landing pads must be in the function where they were inserted for cleanup.
David Majnemereb518bd2015-08-04 08:21:40 +000060 if (BB.isEHPad())
Chandler Carruth0fde0012012-05-04 10:18:49 +000061 return false;
Serge Guelton7bc405a2017-06-27 18:57:53 +000062 // taking the address of a basic block moved to another function is illegal
63 if (BB.hasAddressTaken())
64 return false;
65
66 // don't hoist code that uses another basicblock address, as it's likely to
67 // lead to unexpected behavior, like cross-function jumps
68 SmallPtrSet<User const *, 16> Visited;
69 SmallVector<User const *, 16> ToVisit;
70
71 for (Instruction const &Inst : BB)
72 ToVisit.push_back(&Inst);
73
74 while (!ToVisit.empty()) {
75 User const *Curr = ToVisit.pop_back_val();
76 if (!Visited.insert(Curr).second)
77 continue;
78 if (isa<BlockAddress const>(Curr))
79 return false; // even a reference to self is likely to be not compatible
80
81 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
82 continue;
83
84 for (auto const &U : Curr->operands()) {
85 if (auto *UU = dyn_cast<User>(U))
86 ToVisit.push_back(UU);
87 }
88 }
Chris Lattner37de2572004-03-18 03:49:40 +000089
Chandler Carruth0fde0012012-05-04 10:18:49 +000090 // Don't hoist code containing allocas, invokes, or vastarts.
91 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
92 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +000093 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +000094 if (const CallInst *CI = dyn_cast<CallInst>(I))
95 if (const Function *F = CI->getCalledFunction())
96 if (F->getIntrinsicID() == Intrinsic::vastart)
97 return false;
98 }
99
100 return true;
101}
102
103/// \brief Build a set of blocks to extract if the input blocks are viable.
Davide Italiano059574c2017-04-21 00:21:09 +0000104static SetVector<BasicBlock *>
Davide Italianofa15de32017-04-21 04:25:00 +0000105buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT) {
106 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
Davide Italiano059574c2017-04-21 00:21:09 +0000107 SetVector<BasicBlock *> Result;
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000108
Chandler Carruth0fde0012012-05-04 10:18:49 +0000109 // Loop over the blocks, adding them to our set-vector, and aborting with an
110 // empty set if we encounter invalid blocks.
Davide Italianofa15de32017-04-21 04:25:00 +0000111 for (BasicBlock *BB : BBs) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000112
Davide Italianofa15de32017-04-21 04:25:00 +0000113 // If this block is dead, don't process it.
114 if (DT && !DT->isReachableFromEntry(BB))
115 continue;
116
117 if (!Result.insert(BB))
118 llvm_unreachable("Repeated basic blocks in extraction input");
119 if (!CodeExtractor::isBlockValidForExtraction(*BB)) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000120 Result.clear();
Chandler Carruth0a570552012-05-04 11:14:19 +0000121 return Result;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000122 }
Davide Italianofa15de32017-04-21 04:25:00 +0000123 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000124
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000125#ifndef NDEBUG
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000126 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
Chandler Carruth67818212012-05-04 21:33:30 +0000127 E = Result.end();
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000128 I != E; ++I)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000129 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
130 PI != PE; ++PI)
131 assert(Result.count(*PI) &&
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000132 "No blocks in this region may have entries from outside the region"
133 " except for the first block!");
134#endif
135
Chandler Carruth0fde0012012-05-04 10:18:49 +0000136 return Result;
137}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000138
Chandler Carruth0fde0012012-05-04 10:18:49 +0000139CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sean Silvaf8015752016-08-02 02:15:45 +0000140 bool AggregateArgs, BlockFrequencyInfo *BFI,
141 BranchProbabilityInfo *BPI)
142 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Davide Italianofa15de32017-04-21 04:25:00 +0000143 BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)), NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000144
Sean Silvaf8015752016-08-02 02:15:45 +0000145CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
146 BlockFrequencyInfo *BFI,
147 BranchProbabilityInfo *BPI)
148 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Davide Italianofa15de32017-04-21 04:25:00 +0000149 BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)),
Sean Silvaf8015752016-08-02 02:15:45 +0000150 NumExitBlocks(~0U) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000151
Chandler Carruth0fde0012012-05-04 10:18:49 +0000152/// definedInRegion - Return true if the specified value is defined in the
153/// extracted region.
154static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
155 if (Instruction *I = dyn_cast<Instruction>(V))
156 if (Blocks.count(I->getParent()))
157 return true;
158 return false;
159}
160
161/// definedInCaller - Return true if the specified value is defined in the
162/// function being code extracted, but not in the region being extracted.
163/// These values must be passed in as live-ins to the function.
164static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
165 if (isa<Argument>(V)) return true;
166 if (Instruction *I = dyn_cast<Instruction>(V))
167 if (!Blocks.count(I->getParent()))
168 return true;
169 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000170}
171
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000172static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
173 BasicBlock *CommonExitBlock = nullptr;
174 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
175 for (auto *Succ : successors(Block)) {
176 // Internal edges, ok.
177 if (Blocks.count(Succ))
178 continue;
179 if (!CommonExitBlock) {
180 CommonExitBlock = Succ;
181 continue;
182 }
183 if (CommonExitBlock == Succ)
184 continue;
185
186 return true;
187 }
188 return false;
189 };
190
191 if (any_of(Blocks, hasNonCommonExitSucc))
192 return nullptr;
193
194 return CommonExitBlock;
195}
196
197bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
198 Instruction *Addr) const {
199 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
Xinliang David Li74480ad2017-05-30 21:22:18 +0000200 Function *Func = (*Blocks.begin())->getParent();
201 for (BasicBlock &BB : *Func) {
202 if (Blocks.count(&BB))
203 continue;
204 for (Instruction &II : BB) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000205
206 if (isa<DbgInfoIntrinsic>(II))
207 continue;
208
209 unsigned Opcode = II.getOpcode();
210 Value *MemAddr = nullptr;
211 switch (Opcode) {
212 case Instruction::Store:
213 case Instruction::Load: {
214 if (Opcode == Instruction::Store) {
215 StoreInst *SI = cast<StoreInst>(&II);
216 MemAddr = SI->getPointerOperand();
217 } else {
218 LoadInst *LI = cast<LoadInst>(&II);
219 MemAddr = LI->getPointerOperand();
220 }
221 // Global variable can not be aliased with locals.
222 if (dyn_cast<Constant>(MemAddr))
223 break;
224 Value *Base = MemAddr->stripInBoundsConstantOffsets();
225 if (!dyn_cast<AllocaInst>(Base) || Base == AI)
226 return false;
227 break;
228 }
229 default: {
230 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
231 if (IntrInst) {
232 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start ||
233 IntrInst->getIntrinsicID() == Intrinsic::lifetime_end)
234 break;
235 return false;
236 }
237 // Treat all the other cases conservatively if it has side effects.
238 if (II.mayHaveSideEffects())
239 return false;
240 }
241 }
242 }
243 }
244
245 return true;
246}
247
248BasicBlock *
249CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
250 BasicBlock *SinglePredFromOutlineRegion = nullptr;
251 assert(!Blocks.count(CommonExitBlock) &&
252 "Expect a block outside the region!");
253 for (auto *Pred : predecessors(CommonExitBlock)) {
254 if (!Blocks.count(Pred))
255 continue;
256 if (!SinglePredFromOutlineRegion) {
257 SinglePredFromOutlineRegion = Pred;
258 } else if (SinglePredFromOutlineRegion != Pred) {
259 SinglePredFromOutlineRegion = nullptr;
260 break;
261 }
262 }
263
264 if (SinglePredFromOutlineRegion)
265 return SinglePredFromOutlineRegion;
266
267#ifndef NDEBUG
268 auto getFirstPHI = [](BasicBlock *BB) {
269 BasicBlock::iterator I = BB->begin();
270 PHINode *FirstPhi = nullptr;
271 while (I != BB->end()) {
272 PHINode *Phi = dyn_cast<PHINode>(I);
273 if (!Phi)
274 break;
275 if (!FirstPhi) {
276 FirstPhi = Phi;
277 break;
278 }
279 }
280 return FirstPhi;
281 };
282 // If there are any phi nodes, the single pred either exists or has already
283 // be created before code extraction.
284 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
285#endif
286
287 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
288 CommonExitBlock->getFirstNonPHI()->getIterator());
289
290 for (auto *Pred : predecessors(CommonExitBlock)) {
291 if (Blocks.count(Pred))
292 continue;
293 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
294 }
295 // Now add the old exit block to the outline region.
296 Blocks.insert(CommonExitBlock);
297 return CommonExitBlock;
298}
299
300void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
301 BasicBlock *&ExitBlock) const {
302 Function *Func = (*Blocks.begin())->getParent();
303 ExitBlock = getCommonExitBlock(Blocks);
304
305 for (BasicBlock &BB : *Func) {
306 if (Blocks.count(&BB))
307 continue;
308 for (Instruction &II : BB) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000309 auto *AI = dyn_cast<AllocaInst>(&II);
310 if (!AI)
311 continue;
312
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000313 // Find the pair of life time markers for address 'Addr' that are either
314 // defined inside the outline region or can legally be shrinkwrapped into
315 // the outline region. If there are not other untracked uses of the
316 // address, return the pair of markers if found; otherwise return a pair
317 // of nullptr.
318 auto GetLifeTimeMarkers =
319 [&](Instruction *Addr, bool &SinkLifeStart,
320 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000321 Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000322
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000323 for (User *U : Addr->users()) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000324 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
325 if (IntrInst) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000326 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
327 // Do not handle the case where AI has multiple start markers.
328 if (LifeStart)
329 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000330 LifeStart = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000331 }
332 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
333 if (LifeEnd)
334 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000335 LifeEnd = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000336 }
337 continue;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000338 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000339 // Find untracked uses of the address, bail.
340 if (!definedInRegion(Blocks, U))
341 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000342 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000343
344 if (!LifeStart || !LifeEnd)
345 return std::make_pair<Instruction *>(nullptr, nullptr);
346
347 SinkLifeStart = !definedInRegion(Blocks, LifeStart);
348 HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
349 // Do legality Check.
350 if ((SinkLifeStart || HoistLifeEnd) &&
351 !isLegalToShrinkwrapLifetimeMarkers(Addr))
352 return std::make_pair<Instruction *>(nullptr, nullptr);
353
354 // Check to see if we have a place to do hoisting, if not, bail.
355 if (HoistLifeEnd && !ExitBlock)
356 return std::make_pair<Instruction *>(nullptr, nullptr);
357
358 return std::make_pair(LifeStart, LifeEnd);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000359 };
360
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000361 bool SinkLifeStart = false, HoistLifeEnd = false;
362 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
363
364 if (Markers.first) {
365 if (SinkLifeStart)
366 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000367 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000368 if (HoistLifeEnd)
369 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000370 continue;
371 }
372
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000373 // Follow the bitcast.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000374 Instruction *MarkerAddr = nullptr;
375 for (User *U : AI->users()) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000376
377 if (U->stripInBoundsConstantOffsets() == AI) {
378 SinkLifeStart = false;
379 HoistLifeEnd = false;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000380 Instruction *Bitcast = cast<Instruction>(U);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000381 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
382 if (Markers.first) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000383 MarkerAddr = Bitcast;
384 continue;
385 }
386 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000387
388 // Found unknown use of AI.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000389 if (!definedInRegion(Blocks, U)) {
390 MarkerAddr = nullptr;
391 break;
392 }
393 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000394
Xinliang David Li74480ad2017-05-30 21:22:18 +0000395 if (MarkerAddr) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000396 if (SinkLifeStart)
397 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000398 if (!definedInRegion(Blocks, MarkerAddr))
399 SinkCands.insert(MarkerAddr);
400 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000401 if (HoistLifeEnd)
402 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000403 }
404 }
405 }
406}
407
408void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
409 const ValueSet &SinkCands) const {
410
Benjamin Kramer135f7352016-06-26 12:28:59 +0000411 for (BasicBlock *BB : Blocks) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000412 // If a used value is defined outside the region, it's an input. If an
413 // instruction is used outside the region, it's an output.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000414 for (Instruction &II : *BB) {
415 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000416 ++OI) {
417 Value *V = *OI;
418 if (!SinkCands.count(V) && definedInCaller(Blocks, V))
419 Inputs.insert(V);
420 }
Chandler Carruth14316fc2012-05-04 11:20:27 +0000421
Benjamin Kramer135f7352016-06-26 12:28:59 +0000422 for (User *U : II.users())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000423 if (!definedInRegion(Blocks, U)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000424 Outputs.insert(&II);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000425 break;
426 }
427 }
428 }
429}
430
Chris Lattner3b2917b2004-05-12 06:01:40 +0000431/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
432/// region, we need to split the entry block of the region so that the PHI node
433/// is easier to deal with.
434void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000435 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000436 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000437
Dan Gohmandcb291f2007-03-22 16:38:57 +0000438 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000439 PHINode *PN = dyn_cast<PHINode>(Header->begin());
440 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000441
Chris Lattner795c9932004-05-12 15:29:13 +0000442 // If the header node contains any PHI nodes, check to see if there is more
443 // than one entry from outside the region. If so, we need to sever the
444 // header block into two.
445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000446 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000447 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000448 else
449 ++NumPredsOutsideRegion;
450
451 // If there is one (or fewer) predecessor from outside the region, we don't
452 // need to do anything special.
453 if (NumPredsOutsideRegion <= 1) return;
454 }
455
456 // Otherwise, we need to split the header block into two pieces: one
457 // containing PHI nodes merging values from outside of the region, and a
458 // second that contains all of the code for the block and merges back any
459 // incoming values from inside of the region.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000460 BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT);
Chris Lattner795c9932004-05-12 15:29:13 +0000461
462 // We only want to code extract the second block now, and it becomes the new
463 // header of the region.
464 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000465 Blocks.remove(OldPred);
466 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000467 Header = NewBB;
468
Chris Lattner795c9932004-05-12 15:29:13 +0000469 // Okay, now we need to adjust the PHI nodes and any branches from within the
470 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000471 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000472 PHINode *PN = cast<PHINode>(OldPred->begin());
473 // Loop over all of the predecessors of OldPred that are in the region,
474 // changing them to branch to NewBB instead.
475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000476 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000477 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
478 TI->replaceUsesOfWith(OldPred, NewBB);
479 }
480
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000481 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000482 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000483 BasicBlock::iterator AfterPHIs;
Reid Spencer66149462004-09-15 17:06:42 +0000484 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
485 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000486 // Create a new PHI node in the new region, which has an incoming value
487 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000488 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000489 PN->getName() + ".ce", &NewBB->front());
Xinliang David Lif12a0fa2017-04-25 04:51:19 +0000490 PN->replaceAllUsesWith(NewPN);
Chris Lattner795c9932004-05-12 15:29:13 +0000491 NewPN->addIncoming(PN, OldPred);
492
493 // Loop over all of the incoming value in PN, moving them to NewPN if they
494 // are from the extracted region.
495 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000496 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000497 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
498 PN->removeIncomingValue(i);
499 --i;
500 }
501 }
502 }
503 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000504}
Chris Lattner795c9932004-05-12 15:29:13 +0000505
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000506void CodeExtractor::splitReturnBlocks() {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000507 for (BasicBlock *Block : Blocks)
508 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000509 BasicBlock *New =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000510 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000511 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000512 // Old dominates New. New node dominates all other nodes dominated
513 // by Old.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000514 DomTreeNode *OldNode = DT->getNode(Block);
515 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
516 OldNode->end());
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000517
Benjamin Kramer135f7352016-06-26 12:28:59 +0000518 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000519
Benjamin Kramer135f7352016-06-26 12:28:59 +0000520 for (DomTreeNode *I : Children)
521 DT->changeImmediateDominator(I, NewNode);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000522 }
523 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000524}
525
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000526/// constructFunction - make a function based on inputs and outputs, as follows:
527/// f(in0, ..., inN, out0, ..., outN)
528///
Chandler Carruth0fde0012012-05-04 10:18:49 +0000529Function *CodeExtractor::constructFunction(const ValueSet &inputs,
530 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000531 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000532 BasicBlock *newRootNode,
533 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000534 Function *oldFunction,
535 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000536 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
537 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000538
539 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000540 switch (NumExitBlocks) {
541 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000542 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
543 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
544 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000545 }
546
Jay Foadb804a2b2011-07-12 14:06:48 +0000547 std::vector<Type*> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000548
549 // Add the types of the input values to the function's argument list
Benjamin Kramer135f7352016-06-26 12:28:59 +0000550 for (Value *value : inputs) {
David Greene0ad6dce2010-01-05 01:26:44 +0000551 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000552 paramTy.push_back(value->getType());
553 }
554
Chris Lattner37de2572004-03-18 03:49:40 +0000555 // Add the types of the output values to the function's argument list.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000556 for (Value *output : outputs) {
557 DEBUG(dbgs() << "instr used in func: " << *output << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000558 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000559 paramTy.push_back(output->getType());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000560 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000561 paramTy.push_back(PointerType::getUnqual(output->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000562 }
563
Benjamin Kramer706e48832016-06-26 13:39:33 +0000564 DEBUG({
565 dbgs() << "Function type: " << *RetTy << " f(";
566 for (Type *i : paramTy)
567 dbgs() << *i << ", ";
568 dbgs() << ")\n";
569 });
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000570
David Blaikie741c8f82015-03-14 01:53:18 +0000571 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000572 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000573 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000574 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000575 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000576 }
Chris Lattner229907c2011-07-18 04:54:35 +0000577 FunctionType *funcType =
Owen Anderson4056ca92009-07-29 22:17:13 +0000578 FunctionType::get(RetTy, paramTy, false);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000579
580 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000581 Function *newFunction = Function::Create(funcType,
582 GlobalValue::InternalLinkage,
583 oldFunction->getName() + "_" +
584 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000585 // If the old function is no-throw, so is the new one.
586 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000587 newFunction->setDoesNotThrow();
Sean Silvaa0a802a2016-08-01 03:15:32 +0000588
589 // Inherit the uwtable attribute if we need to.
590 if (oldFunction->hasUWTable())
591 newFunction->setHasUWTable();
592
593 // Inherit all of the target dependent attributes.
594 // (e.g. If the extracted region contains a call to an x86.sse
595 // instruction we need to make sure that the extracted region has the
596 // "target-features" attribute allowing it to be lowered.
597 // FIXME: This should be changed to check to see if a specific
598 // attribute can not be inherited.
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000599 AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
Sean Silva9011aca2017-02-22 06:34:04 +0000600 for (const auto &Attr : AB.td_attrs())
Sean Silvaa0a802a2016-08-01 03:15:32 +0000601 newFunction->addFnAttr(Attr.first, Attr.second);
602
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000603 newFunction->getBasicBlockList().push_back(newRootNode);
604
Chris Lattner37de2572004-03-18 03:49:40 +0000605 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000606 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000607
608 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000609 // arguments (or appropriate addressing into struct) instead.
610 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
611 Value *RewriteVal;
612 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000613 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000614 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
615 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000616 TerminatorInst *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000617 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000618 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000619 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000620 } else
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000621 RewriteVal = &*AI++;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000622
Chandler Carruthcdf47882014-03-09 03:16:01 +0000623 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000624 for (User *use : Users)
625 if (Instruction *inst = dyn_cast<Instruction>(use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000626 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000627 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000628 }
629
Misha Brukman3596f0a2004-04-23 23:54:17 +0000630 // Set names for input and output arguments.
631 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000632 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000633 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000634 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000635 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000636 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000637 }
Chris Lattner37de2572004-03-18 03:49:40 +0000638
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000639 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
640 // within the new function. This must be done before we lose track of which
641 // blocks were originally in the code region.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000642 std::vector<User*> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000643 for (unsigned i = 0, e = Users.size(); i != e; ++i)
644 // The BasicBlock which contains the branch is not in the region
645 // modify the branch target to a new block
646 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000647 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000648 TI->getParent()->getParent() == oldFunction)
649 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000650
651 return newFunction;
652}
653
Owen Anderson4e9ac2a2009-08-25 17:42:07 +0000654/// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
655/// that uses the value within the basic block, and return the predecessor
656/// block associated with that use, or return 0 if none is found.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000657static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000658 for (Use &U : Used->uses()) {
659 PHINode *P = dyn_cast<PHINode>(U.getUser());
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000660 if (P && P->getParent() == BB)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000661 return P->getIncomingBlock(U);
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000662 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000663
Craig Topperf40110f2014-04-25 05:29:35 +0000664 return nullptr;
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000665}
666
Chris Lattner3b2917b2004-05-12 06:01:40 +0000667/// emitCallAndSwitchStatement - This method sets up the caller side by adding
668/// the call instruction, splitting any PHI nodes in the header block as
669/// necessary.
670void CodeExtractor::
671emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000672 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000673 // Emit a call to the new function, passing in: *pointer to struct (if
674 // aggregating parameters), or plan inputs and allocated memory for outputs
Owen Anderson34e61482009-08-25 00:54:39 +0000675 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000676
677 Module *M = newFunction->getParent();
678 LLVMContext &Context = M->getContext();
679 const DataLayout &DL = M->getDataLayout();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000680
Misha Brukman3596f0a2004-04-23 23:54:17 +0000681 // Add inputs as params, or to be filled into the struct
Benjamin Kramer135f7352016-06-26 12:28:59 +0000682 for (Value *input : inputs)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000683 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000684 StructValues.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000685 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000686 params.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000687
688 // Create allocas for the outputs
Benjamin Kramer135f7352016-06-26 12:28:59 +0000689 for (Value *output : outputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000690 if (AggregateArgs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000691 StructValues.push_back(output);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000692 } else {
693 AllocaInst *alloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000694 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
695 nullptr, output->getName() + ".loc",
696 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000697 ReloadOutputs.push_back(alloca);
698 params.push_back(alloca);
699 }
700 }
701
David Blaikie741c8f82015-03-14 01:53:18 +0000702 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000703 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000704 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000705 std::vector<Type*> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000706 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000707 ve = StructValues.end(); v != ve; ++v)
708 ArgTypes.push_back((*v)->getType());
709
710 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +0000711 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000712 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
713 "structArg",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000714 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000715 params.push_back(Struct);
716
717 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000718 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000719 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
720 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +0000721 GetElementPtrInst *GEP = GetElementPtrInst::Create(
722 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000723 codeReplacer->getInstList().push_back(GEP);
724 StoreInst *SI = new StoreInst(StructValues[i], GEP);
725 codeReplacer->getInstList().push_back(SI);
726 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000727 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000728
729 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000730 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000731 NumExitBlocks > 1 ? "targetBlock" : "");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000732 codeReplacer->getInstList().push_back(call);
733
Chris Lattner531f9e92005-03-15 04:54:21 +0000734 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000735 unsigned FirstOut = inputs.size();
736 if (!AggregateArgs)
737 std::advance(OutputArgBegin, inputs.size());
738
739 // Reload the outputs passed in by reference
740 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000741 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000742 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000743 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000744 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
745 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +0000746 GetElementPtrInst *GEP = GetElementPtrInst::Create(
747 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000748 codeReplacer->getInstList().push_back(GEP);
749 Output = GEP;
750 } else {
751 Output = ReloadOutputs[i];
752 }
753 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000754 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000755 codeReplacer->getInstList().push_back(load);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000756 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +0000757 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
758 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000759 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000760 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000761 }
762 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000763
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000764 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000765 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000766 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000767 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000768
769 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000770 // function return an unsigned, switch on that number. This loop iterates
771 // over all of the blocks in the extracted region, updating any terminator
772 // instructions in the to-be-extracted region that branch to blocks that are
773 // not in the region to be extracted.
774 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
775
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000776 unsigned switchVal = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000777 for (BasicBlock *Block : Blocks) {
778 TerminatorInst *TI = Block->getTerminator();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000779 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000780 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000781 BasicBlock *OldTarget = TI->getSuccessor(i);
782 // add a new basic block which returns the appropriate value
783 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
784 if (!NewTarget) {
785 // If we don't already have an exit stub for this non-extracted
786 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000787 NewTarget = BasicBlock::Create(Context,
788 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000789 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000790 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000791
Craig Topperf40110f2014-04-25 05:29:35 +0000792 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +0000793 switch (NumExitBlocks) {
794 case 0:
795 case 1: break; // No value needed.
796 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000797 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000798 break;
799 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000800 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000801 break;
802 }
803
Owen Anderson55f1c092009-08-13 21:58:54 +0000804 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000805
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000806 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000807 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
808 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000809 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000810
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000811 // Restore values just before we exit
Chris Lattner531f9e92005-03-15 04:54:21 +0000812 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000813 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000814 // For an invoke, the normal destination is the only one that is
815 // dominated by the result of the invocation
Misha Brukman3596f0a2004-04-23 23:54:17 +0000816 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
Chris Lattner9b0291b2004-11-13 00:06:45 +0000817
818 bool DominatesDef = true;
819
David Majnemer0bc0eef2015-08-15 02:46:08 +0000820 BasicBlock *NormalDest = nullptr;
821 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
822 NormalDest = Invoke->getNormalDest();
David Majnemer0bc0eef2015-08-15 02:46:08 +0000823
824 if (NormalDest) {
825 DefBlock = NormalDest;
Chris Lattner5bcca602004-11-12 23:50:44 +0000826
827 // Make sure we are looking at the original successor block, not
828 // at a newly inserted exit block, which won't be in the dominator
829 // info.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000830 for (const auto &I : ExitBlockMap)
831 if (DefBlock == I.second) {
832 DefBlock = I.first;
Chris Lattner5bcca602004-11-12 23:50:44 +0000833 break;
834 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000835
836 // In the extract block case, if the block we are extracting ends
837 // with an invoke instruction, make sure that we don't emit a
838 // store of the invoke value for the unwind block.
Devang Patelcf470e52007-06-07 22:17:16 +0000839 if (!DT && DefBlock != OldTarget)
Chris Lattner9b0291b2004-11-13 00:06:45 +0000840 DominatesDef = false;
Chris Lattner5bcca602004-11-12 23:50:44 +0000841 }
842
Owen Anderson34e61482009-08-25 00:54:39 +0000843 if (DT) {
Devang Patelcf470e52007-06-07 22:17:16 +0000844 DominatesDef = DT->dominates(DefBlock, OldTarget);
Owen Anderson34e61482009-08-25 00:54:39 +0000845
846 // If the output value is used by a phi in the target block,
847 // then we need to test for dominance of the phi's predecessor
848 // instead. Unfortunately, this a little complicated since we
849 // have already rewritten uses of the value to uses of the reload.
Owen Anderson5e39d1d2009-08-25 17:26:32 +0000850 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
851 OldTarget);
852 if (pred && DT && DT->dominates(DefBlock, pred))
853 DominatesDef = true;
Owen Anderson34e61482009-08-25 00:54:39 +0000854 }
Chris Lattner9b0291b2004-11-13 00:06:45 +0000855
856 if (DominatesDef) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000857 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000858 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000859 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
860 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
861 FirstOut+out);
David Blaikie741c8f82015-03-14 01:53:18 +0000862 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000863 StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
David Blaikie741c8f82015-03-14 01:53:18 +0000864 NTRet);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000865 new StoreInst(outputs[out], GEP, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000866 } else {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000867 new StoreInst(outputs[out], &*OAI, NTRet);
Chris Lattner9b0291b2004-11-13 00:06:45 +0000868 }
869 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000870 // Advance output iterator even if we don't emit a store
871 if (!AggregateArgs) ++OAI;
872 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000873 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000874
875 // rewrite the original branch instruction with this new target
876 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000877 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000878 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000879
Chris Lattner3d1ca672004-05-12 03:22:33 +0000880 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000881 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000882 switch (NumExitBlocks) {
883 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000884 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000885 // means that previously this was the last part of the function, and hence
886 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000887
Misha Brukman3596f0a2004-04-23 23:54:17 +0000888 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000889 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000890 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000891 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000892 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000893 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000894 } else {
895 // Otherwise we must have code extracted an unwind or something, just
896 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000897 ReturnInst::Create(Context,
898 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000899 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000900
Dan Gohman158ff2c2008-06-21 22:08:46 +0000901 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000902 break;
903 case 1:
904 // Only a single destination, change the switch into an unconditional
905 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000906 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000907 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000908 break;
909 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000910 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
911 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000912 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000913 break;
914 default:
915 // Otherwise, make the default destination of the switch instruction be one
916 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000917 TheSwitch->setCondition(call);
918 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000919 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +0000920 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000921 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000922 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000923}
924
Chris Lattner3b2917b2004-05-12 06:01:40 +0000925void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000926 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000927 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
928 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
929
Benjamin Kramer135f7352016-06-26 12:28:59 +0000930 for (BasicBlock *Block : Blocks) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000931 // Delete the basic block from the old function, and the list of blocks
Benjamin Kramer135f7352016-06-26 12:28:59 +0000932 oldBlocks.remove(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000933
934 // Insert this basic block into the new function
Benjamin Kramer135f7352016-06-26 12:28:59 +0000935 newBlocks.push_back(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000936 }
937}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000938
Sean Silvaf8015752016-08-02 02:15:45 +0000939void CodeExtractor::calculateNewCallTerminatorWeights(
940 BasicBlock *CodeReplacer,
941 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
942 BranchProbabilityInfo *BPI) {
943 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
944 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
945
946 // Update the branch weights for the exit block.
947 TerminatorInst *TI = CodeReplacer->getTerminator();
948 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
949
950 // Block Frequency distribution with dummy node.
951 Distribution BranchDist;
952
953 // Add each of the frequencies of the successors.
954 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
955 BlockNode ExitNode(i);
956 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
957 if (ExitFreq != 0)
958 BranchDist.addExit(ExitNode, ExitFreq);
959 else
960 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
961 }
962
963 // Check for no total weight.
964 if (BranchDist.Total == 0)
965 return;
966
967 // Normalize the distribution so that they can fit in unsigned.
968 BranchDist.normalize();
969
970 // Create normalized branch weights and set the metadata.
971 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
972 const auto &Weight = BranchDist.Weights[I];
973
974 // Get the weight and update the current BFI.
975 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
976 BranchProbability BP(Weight.Amount, BranchDist.Total);
977 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
978 }
979 TI->setMetadata(
980 LLVMContext::MD_prof,
981 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
982}
983
Chandler Carruth0fde0012012-05-04 10:18:49 +0000984Function *CodeExtractor::extractCodeRegion() {
985 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000987
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000988 ValueSet inputs, outputs, SinkingCands, HoistingCands;
989 BasicBlock *CommonExit = nullptr;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000990
991 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +0000992 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000993 BasicBlock *header = *Blocks.begin();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000994
Sean Silvaf8015752016-08-02 02:15:45 +0000995 // Calculate the entry frequency of the new function before we change the root
996 // block.
997 BlockFrequency EntryFreq;
998 if (BFI) {
999 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1000 for (BasicBlock *Pred : predecessors(header)) {
1001 if (Blocks.count(Pred))
1002 continue;
1003 EntryFreq +=
1004 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1005 }
1006 }
1007
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001008 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +00001009 severSplitPHINodes(header);
1010
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001011 // If we have any return instructions in the region, split those blocks so
1012 // that the return is not in the region.
1013 splitReturnBlocks();
1014
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001015 Function *oldFunction = header->getParent();
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001016
1017 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +00001018 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
1019 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +00001020 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001021
1022 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +00001023 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +00001024 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
1025 "newFuncRoot");
Gabor Greife9ecc682008-04-06 20:25:17 +00001026 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001027
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001028 findAllocas(SinkingCands, HoistingCands, CommonExit);
1029 assert(HoistingCands.empty() || CommonExit);
Xinliang David Li74480ad2017-05-30 21:22:18 +00001030
Chris Lattner3b2917b2004-05-12 06:01:40 +00001031 // Find inputs to, outputs from the code region.
Xinliang David Li74480ad2017-05-30 21:22:18 +00001032 findInputsOutputs(inputs, outputs, SinkingCands);
1033
1034 // Now sink all instructions which only have non-phi uses inside the region
1035 for (auto *II : SinkingCands)
1036 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1037 newFuncRoot->getFirstInsertionPt());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001038
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001039 if (!HoistingCands.empty()) {
1040 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1041 Instruction *TI = HoistToBlock->getTerminator();
1042 for (auto *II : HoistingCands)
1043 cast<Instruction>(II)->moveBefore(TI);
1044 }
1045
Sean Silvaf8015752016-08-02 02:15:45 +00001046 // Calculate the exit blocks for the extracted region and the total exit
1047 // weights for each of those blocks.
1048 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
Chandler Carruth14316fc2012-05-04 11:20:27 +00001049 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
Sean Silvaf8015752016-08-02 02:15:45 +00001050 for (BasicBlock *Block : Blocks) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001051 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
Sean Silvaf8015752016-08-02 02:15:45 +00001052 ++SI) {
1053 if (!Blocks.count(*SI)) {
1054 // Update the branch weight for this successor.
1055 if (BFI) {
1056 BlockFrequency &BF = ExitWeights[*SI];
1057 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1058 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001059 ExitBlocks.insert(*SI);
Sean Silvaf8015752016-08-02 02:15:45 +00001060 }
1061 }
1062 }
Chandler Carruth14316fc2012-05-04 11:20:27 +00001063 NumExitBlocks = ExitBlocks.size();
1064
Chris Lattner3b2917b2004-05-12 06:01:40 +00001065 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +00001066 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +00001067 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +00001068 codeReplacer, oldFunction,
1069 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001070
Sean Silvaf8015752016-08-02 02:15:45 +00001071 // Update the entry count of the function.
1072 if (BFI) {
1073 Optional<uint64_t> EntryCount =
1074 BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1075 if (EntryCount.hasValue())
1076 newFunction->setEntryCount(EntryCount.getValue());
1077 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1078 }
1079
Chris Lattner9c431f62004-03-14 22:34:55 +00001080 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001081
Chris Lattner9c431f62004-03-14 22:34:55 +00001082 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001083
Sean Silvaf8015752016-08-02 02:15:45 +00001084 // Update the branch weights for the exit block.
1085 if (BFI && NumExitBlocks > 1)
1086 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1087
Chris Lattner795c9932004-05-12 15:29:13 +00001088 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +00001089 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +00001090 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1091 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +00001092 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001093 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +00001094 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +00001095 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001096
Chris Lattneracd75982004-03-18 05:38:31 +00001097 // Look at all successors of the codeReplacer block. If any of these blocks
1098 // had PHI nodes in them, we need to update the "from" block to be the code
1099 // replacer, not the original block in the extracted region.
1100 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
1101 succ_end(codeReplacer));
1102 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +00001103 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
1104 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +00001105 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +00001106 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001107 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +00001108 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
1109 PN->setIncomingBlock(i, codeReplacer);
1110 else {
1111 // There were multiple entries in the PHI for this block, now there
1112 // is only one, so remove the duplicated entries.
1113 PN->removeIncomingValue(i, false);
1114 --i; --e;
1115 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00001116 }
Chris Lattner56273822004-08-13 03:27:07 +00001117 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118
Torok Edwinccb29cd2009-07-11 13:10:19 +00001119 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +00001120 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001121 return newFunction;
1122}