blob: ef39f21632c812265eb71be6d31d0024856d14e9 [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"
Eugene Zelenko286d5892017-10-11 21:41:43 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Optional.h"
Jakub Staszakf23980a2013-02-09 01:04:28 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Sean Silvaf8015752016-08-02 02:15:45 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000028#include "llvm/IR/Argument.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000034#include "llvm/IR/DataLayout.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000037#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Instructions.h"
Xinliang David Li74480ad2017-05-30 21:22:18 +000042#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/LLVMContext.h"
Sean Silvaf8015752016-08-02 02:15:45 +000045#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Module.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000047#include "llvm/IR/Type.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000051#include "llvm/Pass.h"
Sean Silvaf8015752016-08-02 02:15:45 +000052#include "llvm/Support/BlockFrequency.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000053#include "llvm/Support/BranchProbability.h"
54#include "llvm/Support/Casting.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000055#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000057#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000058#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000060#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <map>
Chris Lattner9c431f62004-03-14 22:34:55 +000064#include <set>
Eugene Zelenko286d5892017-10-11 21:41:43 +000065#include <utility>
66#include <vector>
67
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000068using namespace llvm;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000069using ProfileCount = Function::ProfileCount;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000070
Chandler Carruthe96dd892014-04-21 22:55:11 +000071#define DEBUG_TYPE "code-extractor"
72
Misha Brukman3596f0a2004-04-23 23:54:17 +000073// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000074// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000075// extracted functions to pthread-based code, as only one argument (void*) can
76// be passed in to pthread_create().
77static cl::opt<bool>
78AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
79 cl::desc("Aggregate arguments to code-extracted functions"));
80
Chandler Carruth0fde0012012-05-04 10:18:49 +000081/// \brief Test whether a block is valid for extraction.
Florian Hahn0e9dec62017-11-13 10:35:52 +000082bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB,
83 bool AllowVarArgs) {
Chandler Carruth0fde0012012-05-04 10:18:49 +000084 // Landing pads must be in the function where they were inserted for cleanup.
David Majnemereb518bd2015-08-04 08:21:40 +000085 if (BB.isEHPad())
Chandler Carruth0fde0012012-05-04 10:18:49 +000086 return false;
Serge Guelton7bc405a2017-06-27 18:57:53 +000087 // taking the address of a basic block moved to another function is illegal
88 if (BB.hasAddressTaken())
89 return false;
90
91 // don't hoist code that uses another basicblock address, as it's likely to
92 // lead to unexpected behavior, like cross-function jumps
93 SmallPtrSet<User const *, 16> Visited;
94 SmallVector<User const *, 16> ToVisit;
95
96 for (Instruction const &Inst : BB)
97 ToVisit.push_back(&Inst);
98
99 while (!ToVisit.empty()) {
100 User const *Curr = ToVisit.pop_back_val();
101 if (!Visited.insert(Curr).second)
102 continue;
103 if (isa<BlockAddress const>(Curr))
104 return false; // even a reference to self is likely to be not compatible
105
106 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
107 continue;
108
109 for (auto const &U : Curr->operands()) {
110 if (auto *UU = dyn_cast<User>(U))
111 ToVisit.push_back(UU);
112 }
113 }
Chris Lattner37de2572004-03-18 03:49:40 +0000114
Florian Hahn0e9dec62017-11-13 10:35:52 +0000115 // Don't hoist code containing allocas or invokes. If explicitly requested,
116 // allow vastart.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000117 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
118 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
Chris Lattner3b2917b2004-05-12 06:01:40 +0000119 return false;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000120 if (const CallInst *CI = dyn_cast<CallInst>(I))
121 if (const Function *F = CI->getCalledFunction())
Florian Hahn0e9dec62017-11-13 10:35:52 +0000122 if (F->getIntrinsicID() == Intrinsic::vastart) {
123 if (AllowVarArgs)
124 continue;
125 else
126 return false;
127 }
Chandler Carruth0fde0012012-05-04 10:18:49 +0000128 }
129
130 return true;
131}
132
133/// \brief Build a set of blocks to extract if the input blocks are viable.
Davide Italiano059574c2017-04-21 00:21:09 +0000134static SetVector<BasicBlock *>
Florian Hahn0e9dec62017-11-13 10:35:52 +0000135buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
136 bool AllowVarArgs) {
Davide Italianofa15de32017-04-21 04:25:00 +0000137 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
Davide Italiano059574c2017-04-21 00:21:09 +0000138 SetVector<BasicBlock *> Result;
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000139
Chandler Carruth0fde0012012-05-04 10:18:49 +0000140 // Loop over the blocks, adding them to our set-vector, and aborting with an
141 // empty set if we encounter invalid blocks.
Davide Italianofa15de32017-04-21 04:25:00 +0000142 for (BasicBlock *BB : BBs) {
Davide Italianofa15de32017-04-21 04:25:00 +0000143 // If this block is dead, don't process it.
144 if (DT && !DT->isReachableFromEntry(BB))
145 continue;
146
147 if (!Result.insert(BB))
148 llvm_unreachable("Repeated basic blocks in extraction input");
Florian Hahn0e9dec62017-11-13 10:35:52 +0000149 if (!CodeExtractor::isBlockValidForExtraction(*BB, AllowVarArgs)) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000150 Result.clear();
Chandler Carruth0a570552012-05-04 11:14:19 +0000151 return Result;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000152 }
Davide Italianofa15de32017-04-21 04:25:00 +0000153 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000155#ifndef NDEBUG
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000156 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
Chandler Carruth67818212012-05-04 21:33:30 +0000157 E = Result.end();
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000158 I != E; ++I)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000159 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
160 PI != PE; ++PI)
161 assert(Result.count(*PI) &&
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000162 "No blocks in this region may have entries from outside the region"
163 " except for the first block!");
164#endif
165
Chandler Carruth0fde0012012-05-04 10:18:49 +0000166 return Result;
167}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000168
Chandler Carruth0fde0012012-05-04 10:18:49 +0000169CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sean Silvaf8015752016-08-02 02:15:45 +0000170 bool AggregateArgs, BlockFrequencyInfo *BFI,
Florian Hahn0e9dec62017-11-13 10:35:52 +0000171 BranchProbabilityInfo *BPI, bool AllowVarArgs)
Sean Silvaf8015752016-08-02 02:15:45 +0000172 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Florian Hahn0e9dec62017-11-13 10:35:52 +0000173 BPI(BPI), AllowVarArgs(AllowVarArgs),
174 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs)) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000175
Sean Silvaf8015752016-08-02 02:15:45 +0000176CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
177 BlockFrequencyInfo *BFI,
178 BranchProbabilityInfo *BPI)
179 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Florian Hahn71147552017-11-13 11:08:47 +0000180 BPI(BPI), AllowVarArgs(false),
181 Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
182 /* AllowVarArgs */ false)) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000183
Chandler Carruth0fde0012012-05-04 10:18:49 +0000184/// definedInRegion - Return true if the specified value is defined in the
185/// extracted region.
186static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
187 if (Instruction *I = dyn_cast<Instruction>(V))
188 if (Blocks.count(I->getParent()))
189 return true;
190 return false;
191}
192
193/// definedInCaller - Return true if the specified value is defined in the
194/// function being code extracted, but not in the region being extracted.
195/// These values must be passed in as live-ins to the function.
196static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
197 if (isa<Argument>(V)) return true;
198 if (Instruction *I = dyn_cast<Instruction>(V))
199 if (!Blocks.count(I->getParent()))
200 return true;
201 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000202}
203
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000204static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
205 BasicBlock *CommonExitBlock = nullptr;
206 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
207 for (auto *Succ : successors(Block)) {
208 // Internal edges, ok.
209 if (Blocks.count(Succ))
210 continue;
211 if (!CommonExitBlock) {
212 CommonExitBlock = Succ;
213 continue;
214 }
215 if (CommonExitBlock == Succ)
216 continue;
217
218 return true;
219 }
220 return false;
221 };
222
223 if (any_of(Blocks, hasNonCommonExitSucc))
224 return nullptr;
225
226 return CommonExitBlock;
227}
228
229bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
230 Instruction *Addr) const {
231 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
Xinliang David Li74480ad2017-05-30 21:22:18 +0000232 Function *Func = (*Blocks.begin())->getParent();
233 for (BasicBlock &BB : *Func) {
234 if (Blocks.count(&BB))
235 continue;
236 for (Instruction &II : BB) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000237 if (isa<DbgInfoIntrinsic>(II))
238 continue;
239
240 unsigned Opcode = II.getOpcode();
241 Value *MemAddr = nullptr;
242 switch (Opcode) {
243 case Instruction::Store:
244 case Instruction::Load: {
245 if (Opcode == Instruction::Store) {
246 StoreInst *SI = cast<StoreInst>(&II);
247 MemAddr = SI->getPointerOperand();
248 } else {
249 LoadInst *LI = cast<LoadInst>(&II);
250 MemAddr = LI->getPointerOperand();
251 }
252 // Global variable can not be aliased with locals.
253 if (dyn_cast<Constant>(MemAddr))
254 break;
255 Value *Base = MemAddr->stripInBoundsConstantOffsets();
256 if (!dyn_cast<AllocaInst>(Base) || Base == AI)
257 return false;
258 break;
259 }
260 default: {
261 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
262 if (IntrInst) {
263 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start ||
264 IntrInst->getIntrinsicID() == Intrinsic::lifetime_end)
265 break;
266 return false;
267 }
268 // Treat all the other cases conservatively if it has side effects.
269 if (II.mayHaveSideEffects())
270 return false;
271 }
272 }
273 }
274 }
275
276 return true;
277}
278
279BasicBlock *
280CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
281 BasicBlock *SinglePredFromOutlineRegion = nullptr;
282 assert(!Blocks.count(CommonExitBlock) &&
283 "Expect a block outside the region!");
284 for (auto *Pred : predecessors(CommonExitBlock)) {
285 if (!Blocks.count(Pred))
286 continue;
287 if (!SinglePredFromOutlineRegion) {
288 SinglePredFromOutlineRegion = Pred;
289 } else if (SinglePredFromOutlineRegion != Pred) {
290 SinglePredFromOutlineRegion = nullptr;
291 break;
292 }
293 }
294
295 if (SinglePredFromOutlineRegion)
296 return SinglePredFromOutlineRegion;
297
298#ifndef NDEBUG
299 auto getFirstPHI = [](BasicBlock *BB) {
300 BasicBlock::iterator I = BB->begin();
301 PHINode *FirstPhi = nullptr;
302 while (I != BB->end()) {
303 PHINode *Phi = dyn_cast<PHINode>(I);
304 if (!Phi)
305 break;
306 if (!FirstPhi) {
307 FirstPhi = Phi;
308 break;
309 }
310 }
311 return FirstPhi;
312 };
313 // If there are any phi nodes, the single pred either exists or has already
314 // be created before code extraction.
315 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
316#endif
317
318 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
319 CommonExitBlock->getFirstNonPHI()->getIterator());
320
Florian Hahnb93c0632017-11-01 09:48:12 +0000321 for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
322 PI != PE;) {
323 BasicBlock *Pred = *PI++;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000324 if (Blocks.count(Pred))
325 continue;
326 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
327 }
328 // Now add the old exit block to the outline region.
329 Blocks.insert(CommonExitBlock);
330 return CommonExitBlock;
331}
332
333void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
334 BasicBlock *&ExitBlock) const {
335 Function *Func = (*Blocks.begin())->getParent();
336 ExitBlock = getCommonExitBlock(Blocks);
337
338 for (BasicBlock &BB : *Func) {
339 if (Blocks.count(&BB))
340 continue;
341 for (Instruction &II : BB) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000342 auto *AI = dyn_cast<AllocaInst>(&II);
343 if (!AI)
344 continue;
345
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000346 // Find the pair of life time markers for address 'Addr' that are either
347 // defined inside the outline region or can legally be shrinkwrapped into
348 // the outline region. If there are not other untracked uses of the
349 // address, return the pair of markers if found; otherwise return a pair
350 // of nullptr.
351 auto GetLifeTimeMarkers =
352 [&](Instruction *Addr, bool &SinkLifeStart,
353 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000354 Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000355
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000356 for (User *U : Addr->users()) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000357 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
358 if (IntrInst) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000359 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
360 // Do not handle the case where AI has multiple start markers.
361 if (LifeStart)
362 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000363 LifeStart = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000364 }
365 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
366 if (LifeEnd)
367 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000368 LifeEnd = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000369 }
370 continue;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000371 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000372 // Find untracked uses of the address, bail.
373 if (!definedInRegion(Blocks, U))
374 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000375 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000376
377 if (!LifeStart || !LifeEnd)
378 return std::make_pair<Instruction *>(nullptr, nullptr);
379
380 SinkLifeStart = !definedInRegion(Blocks, LifeStart);
381 HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
382 // Do legality Check.
383 if ((SinkLifeStart || HoistLifeEnd) &&
384 !isLegalToShrinkwrapLifetimeMarkers(Addr))
385 return std::make_pair<Instruction *>(nullptr, nullptr);
386
387 // Check to see if we have a place to do hoisting, if not, bail.
388 if (HoistLifeEnd && !ExitBlock)
389 return std::make_pair<Instruction *>(nullptr, nullptr);
390
391 return std::make_pair(LifeStart, LifeEnd);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000392 };
393
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000394 bool SinkLifeStart = false, HoistLifeEnd = false;
395 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
396
397 if (Markers.first) {
398 if (SinkLifeStart)
399 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000400 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 continue;
404 }
405
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000406 // Follow the bitcast.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000407 Instruction *MarkerAddr = nullptr;
408 for (User *U : AI->users()) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000409 if (U->stripInBoundsConstantOffsets() == AI) {
410 SinkLifeStart = false;
411 HoistLifeEnd = false;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000412 Instruction *Bitcast = cast<Instruction>(U);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000413 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
414 if (Markers.first) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000415 MarkerAddr = Bitcast;
416 continue;
417 }
418 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000419
420 // Found unknown use of AI.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000421 if (!definedInRegion(Blocks, U)) {
422 MarkerAddr = nullptr;
423 break;
424 }
425 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000426
Xinliang David Li74480ad2017-05-30 21:22:18 +0000427 if (MarkerAddr) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000428 if (SinkLifeStart)
429 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000430 if (!definedInRegion(Blocks, MarkerAddr))
431 SinkCands.insert(MarkerAddr);
432 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000433 if (HoistLifeEnd)
434 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000435 }
436 }
437 }
438}
439
440void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
441 const ValueSet &SinkCands) const {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000442 for (BasicBlock *BB : Blocks) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000443 // If a used value is defined outside the region, it's an input. If an
444 // instruction is used outside the region, it's an output.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000445 for (Instruction &II : *BB) {
446 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000447 ++OI) {
448 Value *V = *OI;
449 if (!SinkCands.count(V) && definedInCaller(Blocks, V))
450 Inputs.insert(V);
451 }
Chandler Carruth14316fc2012-05-04 11:20:27 +0000452
Benjamin Kramer135f7352016-06-26 12:28:59 +0000453 for (User *U : II.users())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000454 if (!definedInRegion(Blocks, U)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000455 Outputs.insert(&II);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000456 break;
457 }
458 }
459 }
460}
461
Chris Lattner3b2917b2004-05-12 06:01:40 +0000462/// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
463/// region, we need to split the entry block of the region so that the PHI node
464/// is easier to deal with.
465void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000466 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000467 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000468
Dan Gohmandcb291f2007-03-22 16:38:57 +0000469 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000470 PHINode *PN = dyn_cast<PHINode>(Header->begin());
471 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000472
Chris Lattner795c9932004-05-12 15:29:13 +0000473 // If the header node contains any PHI nodes, check to see if there is more
474 // than one entry from outside the region. If so, we need to sever the
475 // header block into two.
476 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000477 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000478 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000479 else
480 ++NumPredsOutsideRegion;
481
482 // If there is one (or fewer) predecessor from outside the region, we don't
483 // need to do anything special.
484 if (NumPredsOutsideRegion <= 1) return;
485 }
486
487 // Otherwise, we need to split the header block into two pieces: one
488 // containing PHI nodes merging values from outside of the region, and a
489 // second that contains all of the code for the block and merges back any
490 // incoming values from inside of the region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000491 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
Chris Lattner795c9932004-05-12 15:29:13 +0000492
493 // We only want to code extract the second block now, and it becomes the new
494 // header of the region.
495 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000496 Blocks.remove(OldPred);
497 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000498 Header = NewBB;
499
Chris Lattner795c9932004-05-12 15:29:13 +0000500 // Okay, now we need to adjust the PHI nodes and any branches from within the
501 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000502 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000503 PHINode *PN = cast<PHINode>(OldPred->begin());
504 // Loop over all of the predecessors of OldPred that are in the region,
505 // changing them to branch to NewBB instead.
506 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000507 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000508 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
509 TI->replaceUsesOfWith(OldPred, NewBB);
510 }
511
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000512 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000513 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000514 BasicBlock::iterator AfterPHIs;
Reid Spencer66149462004-09-15 17:06:42 +0000515 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
516 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000517 // Create a new PHI node in the new region, which has an incoming value
518 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000519 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000520 PN->getName() + ".ce", &NewBB->front());
Xinliang David Lif12a0fa2017-04-25 04:51:19 +0000521 PN->replaceAllUsesWith(NewPN);
Chris Lattner795c9932004-05-12 15:29:13 +0000522 NewPN->addIncoming(PN, OldPred);
523
524 // Loop over all of the incoming value in PN, moving them to NewPN if they
525 // are from the extracted region.
526 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000527 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000528 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
529 PN->removeIncomingValue(i);
530 --i;
531 }
532 }
533 }
534 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000535}
Chris Lattner795c9932004-05-12 15:29:13 +0000536
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000537void CodeExtractor::splitReturnBlocks() {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000538 for (BasicBlock *Block : Blocks)
539 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000540 BasicBlock *New =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000541 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000542 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000543 // Old dominates New. New node dominates all other nodes dominated
544 // by Old.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000545 DomTreeNode *OldNode = DT->getNode(Block);
546 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
547 OldNode->end());
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000548
Benjamin Kramer135f7352016-06-26 12:28:59 +0000549 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000550
Benjamin Kramer135f7352016-06-26 12:28:59 +0000551 for (DomTreeNode *I : Children)
552 DT->changeImmediateDominator(I, NewNode);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000553 }
554 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000555}
556
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000557/// constructFunction - make a function based on inputs and outputs, as follows:
558/// f(in0, ..., inN, out0, ..., outN)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000559Function *CodeExtractor::constructFunction(const ValueSet &inputs,
560 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000561 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000562 BasicBlock *newRootNode,
563 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000564 Function *oldFunction,
565 Module *M) {
David Greene0ad6dce2010-01-05 01:26:44 +0000566 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
567 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000568
569 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000570 switch (NumExitBlocks) {
571 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000572 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
573 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
574 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000575 }
576
Eugene Zelenko286d5892017-10-11 21:41:43 +0000577 std::vector<Type *> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000578
579 // Add the types of the input values to the function's argument list
Benjamin Kramer135f7352016-06-26 12:28:59 +0000580 for (Value *value : inputs) {
David Greene0ad6dce2010-01-05 01:26:44 +0000581 DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000582 paramTy.push_back(value->getType());
583 }
584
Chris Lattner37de2572004-03-18 03:49:40 +0000585 // Add the types of the output values to the function's argument list.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000586 for (Value *output : outputs) {
587 DEBUG(dbgs() << "instr used in func: " << *output << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000588 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000589 paramTy.push_back(output->getType());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000590 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000591 paramTy.push_back(PointerType::getUnqual(output->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000592 }
593
Benjamin Kramer706e48832016-06-26 13:39:33 +0000594 DEBUG({
595 dbgs() << "Function type: " << *RetTy << " f(";
596 for (Type *i : paramTy)
597 dbgs() << *i << ", ";
598 dbgs() << ")\n";
599 });
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000600
David Blaikie741c8f82015-03-14 01:53:18 +0000601 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000602 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000603 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000604 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000605 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000606 }
Chris Lattner229907c2011-07-18 04:54:35 +0000607 FunctionType *funcType =
Florian Hahn0e9dec62017-11-13 10:35:52 +0000608 FunctionType::get(RetTy, paramTy,
609 AllowVarArgs && oldFunction->isVarArg());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000610
611 // Create the new function
Gabor Greife9ecc682008-04-06 20:25:17 +0000612 Function *newFunction = Function::Create(funcType,
613 GlobalValue::InternalLinkage,
614 oldFunction->getName() + "_" +
615 header->getName(), M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000616 // If the old function is no-throw, so is the new one.
617 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000618 newFunction->setDoesNotThrow();
Sean Silvaa0a802a2016-08-01 03:15:32 +0000619
620 // Inherit the uwtable attribute if we need to.
621 if (oldFunction->hasUWTable())
622 newFunction->setHasUWTable();
623
Florian Hahn55be37e2018-01-07 11:22:25 +0000624 // Inherit all of the target dependent attributes and white-listed
625 // target independent attributes.
Sean Silvaa0a802a2016-08-01 03:15:32 +0000626 // (e.g. If the extracted region contains a call to an x86.sse
627 // instruction we need to make sure that the extracted region has the
628 // "target-features" attribute allowing it to be lowered.
629 // FIXME: This should be changed to check to see if a specific
630 // attribute can not be inherited.
Florian Hahn55be37e2018-01-07 11:22:25 +0000631 for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
632 if (Attr.isStringAttribute()) {
633 if (Attr.getKindAsString() == "thunk")
634 continue;
635 } else
636 switch (Attr.getKindAsEnum()) {
637 // Those attributes cannot be propagated safely. Explicitly list them
638 // here so we get a warning if new attributes are added. This list also
639 // includes non-function attributes.
640 case Attribute::Alignment:
641 case Attribute::AllocSize:
642 case Attribute::ArgMemOnly:
643 case Attribute::Builtin:
644 case Attribute::ByVal:
645 case Attribute::Convergent:
646 case Attribute::Dereferenceable:
647 case Attribute::DereferenceableOrNull:
648 case Attribute::InAlloca:
649 case Attribute::InReg:
650 case Attribute::InaccessibleMemOnly:
651 case Attribute::InaccessibleMemOrArgMemOnly:
652 case Attribute::JumpTable:
653 case Attribute::Naked:
654 case Attribute::Nest:
655 case Attribute::NoAlias:
656 case Attribute::NoBuiltin:
657 case Attribute::NoCapture:
658 case Attribute::NoReturn:
659 case Attribute::None:
660 case Attribute::NonNull:
661 case Attribute::ReadNone:
662 case Attribute::ReadOnly:
663 case Attribute::Returned:
664 case Attribute::ReturnsTwice:
665 case Attribute::SExt:
666 case Attribute::Speculatable:
667 case Attribute::StackAlignment:
668 case Attribute::StructRet:
669 case Attribute::SwiftError:
670 case Attribute::SwiftSelf:
671 case Attribute::WriteOnly:
672 case Attribute::ZExt:
673 case Attribute::EndAttrKinds:
674 continue;
675 // Those attributes should be safe to propagate to the extracted function.
676 case Attribute::AlwaysInline:
677 case Attribute::Cold:
678 case Attribute::NoRecurse:
679 case Attribute::InlineHint:
680 case Attribute::MinSize:
681 case Attribute::NoDuplicate:
682 case Attribute::NoImplicitFloat:
683 case Attribute::NoInline:
684 case Attribute::NonLazyBind:
685 case Attribute::NoRedZone:
686 case Attribute::NoUnwind:
687 case Attribute::OptimizeNone:
688 case Attribute::OptimizeForSize:
689 case Attribute::SafeStack:
690 case Attribute::SanitizeAddress:
691 case Attribute::SanitizeMemory:
692 case Attribute::SanitizeThread:
693 case Attribute::SanitizeHWAddress:
694 case Attribute::StackProtect:
695 case Attribute::StackProtectReq:
696 case Attribute::StackProtectStrong:
697 case Attribute::StrictFP:
698 case Attribute::UWTable:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000699 case Attribute::NoCfCheck:
Florian Hahn55be37e2018-01-07 11:22:25 +0000700 break;
701 }
Sean Silvaa0a802a2016-08-01 03:15:32 +0000702
Florian Hahn55be37e2018-01-07 11:22:25 +0000703 newFunction->addFnAttr(Attr);
704 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000705 newFunction->getBasicBlockList().push_back(newRootNode);
706
Chris Lattner37de2572004-03-18 03:49:40 +0000707 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000708 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000709
710 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000711 // arguments (or appropriate addressing into struct) instead.
712 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
713 Value *RewriteVal;
714 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000715 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000716 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
717 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000718 TerminatorInst *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000719 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000720 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000721 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000722 } else
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000723 RewriteVal = &*AI++;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000724
Eugene Zelenko286d5892017-10-11 21:41:43 +0000725 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000726 for (User *use : Users)
727 if (Instruction *inst = dyn_cast<Instruction>(use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000728 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000729 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000730 }
731
Misha Brukman3596f0a2004-04-23 23:54:17 +0000732 // Set names for input and output arguments.
733 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000734 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000735 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000736 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000737 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000738 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000739 }
Chris Lattner37de2572004-03-18 03:49:40 +0000740
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000741 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
742 // within the new function. This must be done before we lose track of which
743 // blocks were originally in the code region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000744 std::vector<User *> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000745 for (unsigned i = 0, e = Users.size(); i != e; ++i)
746 // The BasicBlock which contains the branch is not in the region
747 // modify the branch target to a new block
748 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000749 if (!Blocks.count(TI->getParent()) &&
Chris Lattner320d59f2004-03-18 05:28:49 +0000750 TI->getParent()->getParent() == oldFunction)
751 TI->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000752
753 return newFunction;
754}
755
Chris Lattner3b2917b2004-05-12 06:01:40 +0000756/// emitCallAndSwitchStatement - This method sets up the caller side by adding
757/// the call instruction, splitting any PHI nodes in the header block as
758/// necessary.
759void CodeExtractor::
760emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
Chandler Carruth0fde0012012-05-04 10:18:49 +0000761 ValueSet &inputs, ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000762 // Emit a call to the new function, passing in: *pointer to struct (if
763 // aggregating parameters), or plan inputs and allocated memory for outputs
Eugene Zelenko286d5892017-10-11 21:41:43 +0000764 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000765
766 Module *M = newFunction->getParent();
767 LLVMContext &Context = M->getContext();
768 const DataLayout &DL = M->getDataLayout();
Chris Lattnerd8017a32004-03-18 04:12:05 +0000769
Misha Brukman3596f0a2004-04-23 23:54:17 +0000770 // Add inputs as params, or to be filled into the struct
Benjamin Kramer135f7352016-06-26 12:28:59 +0000771 for (Value *input : inputs)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000772 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000773 StructValues.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000774 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000775 params.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000776
777 // Create allocas for the outputs
Benjamin Kramer135f7352016-06-26 12:28:59 +0000778 for (Value *output : outputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000779 if (AggregateArgs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000780 StructValues.push_back(output);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000781 } else {
782 AllocaInst *alloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000783 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
784 nullptr, output->getName() + ".loc",
785 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000786 ReloadOutputs.push_back(alloca);
787 params.push_back(alloca);
788 }
789 }
790
David Blaikie741c8f82015-03-14 01:53:18 +0000791 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000792 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000793 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Eugene Zelenko286d5892017-10-11 21:41:43 +0000794 std::vector<Type *> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000795 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000796 ve = StructValues.end(); v != ve; ++v)
797 ArgTypes.push_back((*v)->getType());
798
799 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +0000800 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000801 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
802 "structArg",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000803 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000804 params.push_back(Struct);
805
806 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +0000807 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000808 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
809 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +0000810 GetElementPtrInst *GEP = GetElementPtrInst::Create(
811 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000812 codeReplacer->getInstList().push_back(GEP);
813 StoreInst *SI = new StoreInst(StructValues[i], GEP);
814 codeReplacer->getInstList().push_back(SI);
815 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000816 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000817
818 // Emit the call to the function
Jay Foad5bd375a2011-07-15 08:37:34 +0000819 CallInst *call = CallInst::Create(newFunction, params,
Gabor Greife9ecc682008-04-06 20:25:17 +0000820 NumExitBlocks > 1 ? "targetBlock" : "");
Florian Hahne5089e22017-12-08 21:49:03 +0000821 // Add debug location to the new call, if the original function has debug
822 // info. In that case, the terminator of the entry block of the extracted
823 // function contains the first debug location of the extracted function,
824 // set in extractCodeRegion.
825 if (codeReplacer->getParent()->getSubprogram()) {
826 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
827 call->setDebugLoc(DL);
828 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000829 codeReplacer->getInstList().push_back(call);
830
Chris Lattner531f9e92005-03-15 04:54:21 +0000831 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000832 unsigned FirstOut = inputs.size();
833 if (!AggregateArgs)
834 std::advance(OutputArgBegin, inputs.size());
835
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +0000836 // Reload the outputs passed in by reference.
837 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000838 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000839 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000840 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000841 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000842 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
843 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +0000844 GetElementPtrInst *GEP = GetElementPtrInst::Create(
845 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000846 codeReplacer->getInstList().push_back(GEP);
847 Output = GEP;
848 } else {
849 Output = ReloadOutputs[i];
850 }
851 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +0000852 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +0000853 codeReplacer->getInstList().push_back(load);
Eugene Zelenko286d5892017-10-11 21:41:43 +0000854 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +0000855 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
856 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +0000857 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +0000858 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000859 }
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +0000860
861 // Store to argument right after the definition of output value.
862 auto *OutI = dyn_cast<Instruction>(outputs[i]);
863 if (!OutI)
864 continue;
865 // Find proper insertion point.
866 Instruction *InsertPt = OutI->getNextNode();
867 // Let's assume that there is no other guy interleave non-PHI in PHIs.
868 if (isa<PHINode>(InsertPt))
869 InsertPt = InsertPt->getParent()->getFirstNonPHI();
870
871 assert(OAI != newFunction->arg_end() &&
872 "Number of output arguments should match "
873 "the amount of defined values");
874 if (AggregateArgs) {
875 Value *Idx[2];
876 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
877 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
878 GetElementPtrInst *GEP = GetElementPtrInst::Create(
879 StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), InsertPt);
880 new StoreInst(outputs[i], GEP, InsertPt);
881 // Since there should be only one struct argument aggregating
882 // all the output values, we shouldn't increment OAI, which always
883 // points to the struct argument, in this case.
884 } else {
885 new StoreInst(outputs[i], &*OAI, InsertPt);
886 ++OAI;
887 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000888 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000889
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000890 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +0000891 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +0000892 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +0000893 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000894
895 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000896 // function return an unsigned, switch on that number. This loop iterates
897 // over all of the blocks in the extracted region, updating any terminator
898 // instructions in the to-be-extracted region that branch to blocks that are
899 // not in the region to be extracted.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000900 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000901
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000902 unsigned switchVal = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000903 for (BasicBlock *Block : Blocks) {
904 TerminatorInst *TI = Block->getTerminator();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000905 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000906 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000907 BasicBlock *OldTarget = TI->getSuccessor(i);
908 // add a new basic block which returns the appropriate value
909 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
910 if (!NewTarget) {
911 // If we don't already have an exit stub for this non-extracted
912 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +0000913 NewTarget = BasicBlock::Create(Context,
914 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +0000915 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +0000916 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000917
Craig Topperf40110f2014-04-25 05:29:35 +0000918 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +0000919 switch (NumExitBlocks) {
920 case 0:
921 case 1: break; // No value needed.
922 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +0000923 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000924 break;
925 default:
Owen Anderson55f1c092009-08-13 21:58:54 +0000926 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +0000927 break;
928 }
929
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +0000930 ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000931
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000932 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +0000933 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
934 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +0000935 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000936 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +0000937
938 // rewrite the original branch instruction with this new target
939 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000940 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000941 }
Chris Lattner5b2072e2004-03-14 23:43:24 +0000942
Chris Lattner3d1ca672004-05-12 03:22:33 +0000943 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +0000944 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +0000945 switch (NumExitBlocks) {
946 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000947 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +0000948 // means that previously this was the last part of the function, and hence
949 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +0000950
Misha Brukman3596f0a2004-04-23 23:54:17 +0000951 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000952 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000953 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000954 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000955 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +0000956 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000957 } else {
958 // Otherwise we must have code extracted an unwind or something, just
959 // return whatever we want.
Owen Anderson55f1c092009-08-13 21:58:54 +0000960 ReturnInst::Create(Context,
961 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +0000962 }
Misha Brukman3596f0a2004-04-23 23:54:17 +0000963
Dan Gohman158ff2c2008-06-21 22:08:46 +0000964 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000965 break;
966 case 1:
967 // Only a single destination, change the switch into an unconditional
968 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +0000969 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000970 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000971 break;
972 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +0000973 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
974 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +0000975 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +0000976 break;
977 default:
978 // Otherwise, make the default destination of the switch instruction be one
979 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000980 TheSwitch->setCondition(call);
981 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000982 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +0000983 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +0000984 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +0000985 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000986}
987
Chris Lattner3b2917b2004-05-12 06:01:40 +0000988void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000989 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +0000990 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
991 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
992
Benjamin Kramer135f7352016-06-26 12:28:59 +0000993 for (BasicBlock *Block : Blocks) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000994 // Delete the basic block from the old function, and the list of blocks
Benjamin Kramer135f7352016-06-26 12:28:59 +0000995 oldBlocks.remove(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000996
997 // Insert this basic block into the new function
Benjamin Kramer135f7352016-06-26 12:28:59 +0000998 newBlocks.push_back(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +0000999 }
1000}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001001
Sean Silvaf8015752016-08-02 02:15:45 +00001002void CodeExtractor::calculateNewCallTerminatorWeights(
1003 BasicBlock *CodeReplacer,
1004 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1005 BranchProbabilityInfo *BPI) {
Eugene Zelenko286d5892017-10-11 21:41:43 +00001006 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1007 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
Sean Silvaf8015752016-08-02 02:15:45 +00001008
1009 // Update the branch weights for the exit block.
1010 TerminatorInst *TI = CodeReplacer->getTerminator();
1011 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1012
1013 // Block Frequency distribution with dummy node.
1014 Distribution BranchDist;
1015
1016 // Add each of the frequencies of the successors.
1017 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1018 BlockNode ExitNode(i);
1019 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
1020 if (ExitFreq != 0)
1021 BranchDist.addExit(ExitNode, ExitFreq);
1022 else
1023 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
1024 }
1025
1026 // Check for no total weight.
1027 if (BranchDist.Total == 0)
1028 return;
1029
1030 // Normalize the distribution so that they can fit in unsigned.
1031 BranchDist.normalize();
1032
1033 // Create normalized branch weights and set the metadata.
1034 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1035 const auto &Weight = BranchDist.Weights[I];
1036
1037 // Get the weight and update the current BFI.
1038 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1039 BranchProbability BP(Weight.Amount, BranchDist.Total);
1040 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
1041 }
1042 TI->setMetadata(
1043 LLVMContext::MD_prof,
1044 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1045}
1046
Chandler Carruth0fde0012012-05-04 10:18:49 +00001047Function *CodeExtractor::extractCodeRegion() {
1048 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +00001049 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001050
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001051 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +00001052 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +00001053 BasicBlock *header = *Blocks.begin();
Florian Hahn0e9dec62017-11-13 10:35:52 +00001054 Function *oldFunction = header->getParent();
1055
1056 // For functions with varargs, check that varargs handling is only done in the
1057 // outlined function, i.e vastart and vaend are only used in outlined blocks.
1058 if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
1059 auto containsVarArgIntrinsic = [](Instruction &I) {
1060 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1061 if (const Function *F = CI->getCalledFunction())
1062 return F->getIntrinsicID() == Intrinsic::vastart ||
1063 F->getIntrinsicID() == Intrinsic::vaend;
1064 return false;
1065 };
1066
1067 for (auto &BB : *oldFunction) {
1068 if (Blocks.count(&BB))
1069 continue;
1070 if (llvm::any_of(BB, containsVarArgIntrinsic))
1071 return nullptr;
1072 }
1073 }
1074 ValueSet inputs, outputs, SinkingCands, HoistingCands;
1075 BasicBlock *CommonExit = nullptr;
Chris Lattner3b2917b2004-05-12 06:01:40 +00001076
Sean Silvaf8015752016-08-02 02:15:45 +00001077 // Calculate the entry frequency of the new function before we change the root
1078 // block.
1079 BlockFrequency EntryFreq;
1080 if (BFI) {
1081 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1082 for (BasicBlock *Pred : predecessors(header)) {
1083 if (Blocks.count(Pred))
1084 continue;
1085 EntryFreq +=
1086 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1087 }
1088 }
1089
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001090 // If we have to split PHI nodes or the entry block, do so now.
Chris Lattner795c9932004-05-12 15:29:13 +00001091 severSplitPHINodes(header);
1092
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001093 // If we have any return instructions in the region, split those blocks so
1094 // that the return is not in the region.
1095 splitReturnBlocks();
1096
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001097 // This takes place of the original loop
Owen Anderson55f1c092009-08-13 21:58:54 +00001098 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
1099 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +00001100 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001101
1102 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +00001103 // head of the region, but the entry node of a function cannot have preds.
Owen Anderson55f1c092009-08-13 21:58:54 +00001104 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
1105 "newFuncRoot");
Florian Hahne5089e22017-12-08 21:49:03 +00001106 auto *BranchI = BranchInst::Create(header);
1107 // If the original function has debug info, we have to add a debug location
1108 // to the new branch instruction from the artificial entry block.
1109 // We use the debug location of the first instruction in the extracted
1110 // blocks, as there is no other equivalent line in the source code.
1111 if (oldFunction->getSubprogram()) {
1112 any_of(Blocks, [&BranchI](const BasicBlock *BB) {
1113 return any_of(*BB, [&BranchI](const Instruction &I) {
1114 if (!I.getDebugLoc())
1115 return false;
1116 BranchI->setDebugLoc(I.getDebugLoc());
1117 return true;
1118 });
1119 });
1120 }
1121 newFuncRoot->getInstList().push_back(BranchI);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001122
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001123 findAllocas(SinkingCands, HoistingCands, CommonExit);
1124 assert(HoistingCands.empty() || CommonExit);
Xinliang David Li74480ad2017-05-30 21:22:18 +00001125
Chris Lattner3b2917b2004-05-12 06:01:40 +00001126 // Find inputs to, outputs from the code region.
Xinliang David Li74480ad2017-05-30 21:22:18 +00001127 findInputsOutputs(inputs, outputs, SinkingCands);
1128
1129 // Now sink all instructions which only have non-phi uses inside the region
1130 for (auto *II : SinkingCands)
1131 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1132 newFuncRoot->getFirstInsertionPt());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001133
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001134 if (!HoistingCands.empty()) {
1135 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1136 Instruction *TI = HoistToBlock->getTerminator();
1137 for (auto *II : HoistingCands)
1138 cast<Instruction>(II)->moveBefore(TI);
1139 }
1140
Sean Silvaf8015752016-08-02 02:15:45 +00001141 // Calculate the exit blocks for the extracted region and the total exit
Eugene Zelenko286d5892017-10-11 21:41:43 +00001142 // weights for each of those blocks.
Sean Silvaf8015752016-08-02 02:15:45 +00001143 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
Chandler Carruth14316fc2012-05-04 11:20:27 +00001144 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
Sean Silvaf8015752016-08-02 02:15:45 +00001145 for (BasicBlock *Block : Blocks) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001146 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
Sean Silvaf8015752016-08-02 02:15:45 +00001147 ++SI) {
1148 if (!Blocks.count(*SI)) {
1149 // Update the branch weight for this successor.
1150 if (BFI) {
1151 BlockFrequency &BF = ExitWeights[*SI];
1152 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1153 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001154 ExitBlocks.insert(*SI);
Sean Silvaf8015752016-08-02 02:15:45 +00001155 }
1156 }
1157 }
Chandler Carruth14316fc2012-05-04 11:20:27 +00001158 NumExitBlocks = ExitBlocks.size();
1159
Chris Lattner3b2917b2004-05-12 06:01:40 +00001160 // Construct new function based on inputs/outputs & add allocas for all defs.
Chris Lattner795c9932004-05-12 15:29:13 +00001161 Function *newFunction = constructFunction(inputs, outputs, header,
Misha Brukmanb1c93172005-04-21 23:48:37 +00001162 newFuncRoot,
Chris Lattner73ab1fa2004-03-15 01:18:23 +00001163 codeReplacer, oldFunction,
1164 oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001165
Sean Silvaf8015752016-08-02 02:15:45 +00001166 // Update the entry count of the function.
1167 if (BFI) {
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001168 auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1169 if (Count.hasValue())
1170 newFunction->setEntryCount(
1171 ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
Sean Silvaf8015752016-08-02 02:15:45 +00001172 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1173 }
1174
Chris Lattner9c431f62004-03-14 22:34:55 +00001175 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001176
Chris Lattner9c431f62004-03-14 22:34:55 +00001177 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001178
Sean Silvaf8015752016-08-02 02:15:45 +00001179 // Update the branch weights for the exit block.
1180 if (BFI && NumExitBlocks > 1)
1181 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1182
Chris Lattner795c9932004-05-12 15:29:13 +00001183 // Loop over all of the PHI nodes in the header block, and change any
Chris Lattner320d59f2004-03-18 05:28:49 +00001184 // references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +00001185 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1186 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +00001187 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001188 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +00001189 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +00001190 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001191
Chris Lattneracd75982004-03-18 05:38:31 +00001192 // Look at all successors of the codeReplacer block. If any of these blocks
1193 // had PHI nodes in them, we need to update the "from" block to be the code
1194 // replacer, not the original block in the extracted region.
Eugene Zelenko286d5892017-10-11 21:41:43 +00001195 std::vector<BasicBlock *> Succs(succ_begin(codeReplacer),
1196 succ_end(codeReplacer));
Chris Lattneracd75982004-03-18 05:38:31 +00001197 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Reid Spencer66149462004-09-15 17:06:42 +00001198 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
1199 PHINode *PN = cast<PHINode>(I);
Chris Lattner56273822004-08-13 03:27:07 +00001200 std::set<BasicBlock*> ProcessedPreds;
Chris Lattneracd75982004-03-18 05:38:31 +00001201 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001202 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner56273822004-08-13 03:27:07 +00001203 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
1204 PN->setIncomingBlock(i, codeReplacer);
1205 else {
1206 // There were multiple entries in the PHI for this block, now there
1207 // is only one, so remove the duplicated entries.
1208 PN->removeIncomingValue(i, false);
1209 --i; --e;
1210 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00001211 }
Chris Lattner56273822004-08-13 03:27:07 +00001212 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001213
Torok Edwinccb29cd2009-07-11 13:10:19 +00001214 DEBUG(if (verifyFunction(*newFunction))
Chris Lattner2104b8d2010-04-07 22:58:41 +00001215 report_fatal_error("verifyFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001216 return newFunction;
1217}