1//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the interface to tear out a code region, such as an
10// individual loop or a parallel section, into a new function, replacing it with
11// a call to the new function.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/CodeExtractor.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
26#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/CFG.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DIBuilder.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugInfo.h"
34#include "llvm/IR/DebugInfoMetadata.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/InstIterator.h"
40#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/MDBuilder.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/PatternMatch.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/IR/Verifier.h"
53#include "llvm/Support/BlockFrequency.h"
54#include "llvm/Support/BranchProbability.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/CommandLine.h"
57#include "llvm/Support/Debug.h"
58#include "llvm/Support/ErrorHandling.h"
59#include "llvm/Support/raw_ostream.h"
60#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include <cassert>
62#include <cstdint>
63#include <iterator>
64#include <map>
65#include <vector>
66
67using namespace llvm;
68using namespace llvm::PatternMatch;
69
70#define DEBUG_TYPE "code-extractor"
71
72// Provide a command-line option to aggregate function arguments into a struct
73// for functions produced by the code extractor. This is useful when converting
74// extracted functions to pthread-based code, as only one argument (void*) can
75// be passed in to pthread_create().
76static cl::opt<bool>
77AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
78 cl::desc("Aggregate arguments to code-extracted functions"));
79
80/// Test whether a block is valid for extraction.
81static bool isBlockValidForExtraction(const BasicBlock &BB,
82 const SetVector<BasicBlock *> &Result,
83 bool AllowVarArgs, bool AllowAlloca) {
84 // taking the address of a basic block moved to another function is illegal
85 if (BB.hasAddressTaken())
86 return false;
87
88 // don't hoist code that uses another basicblock address, as it's likely to
89 // lead to unexpected behavior, like cross-function jumps
90 SmallPtrSet<User const *, 16> Visited;
91 SmallVector<User const *, 16> ToVisit(llvm::make_pointer_range(Range: BB));
92
93 while (!ToVisit.empty()) {
94 User const *Curr = ToVisit.pop_back_val();
95 if (!Visited.insert(Ptr: Curr).second)
96 continue;
97 if (isa<BlockAddress const>(Val: Curr))
98 return false; // even a reference to self is likely to be not compatible
99
100 if (isa<Instruction>(Val: Curr) && cast<Instruction>(Val: Curr)->getParent() != &BB)
101 continue;
102
103 for (auto const &U : Curr->operands()) {
104 if (auto *UU = dyn_cast<User>(Val: U))
105 ToVisit.push_back(Elt: UU);
106 }
107 }
108
109 // If explicitly requested, allow vastart and alloca. For invoke instructions
110 // verify that extraction is valid.
111 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
112 if (isa<AllocaInst>(Val: I)) {
113 if (!AllowAlloca)
114 return false;
115 continue;
116 }
117
118 if (const auto *II = dyn_cast<InvokeInst>(Val&: I)) {
119 // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
120 // must be a part of the subgraph which is being extracted.
121 if (auto *UBB = II->getUnwindDest())
122 if (!Result.count(key: UBB))
123 return false;
124 continue;
125 }
126
127 // All catch handlers of a catchswitch instruction as well as the unwind
128 // destination must be in the subgraph.
129 if (const auto *CSI = dyn_cast<CatchSwitchInst>(Val&: I)) {
130 if (auto *UBB = CSI->getUnwindDest())
131 if (!Result.count(key: UBB))
132 return false;
133 for (const auto *HBB : CSI->handlers())
134 if (!Result.count(key: const_cast<BasicBlock*>(HBB)))
135 return false;
136 continue;
137 }
138
139 // Make sure that entire catch handler is within subgraph. It is sufficient
140 // to check that catch return's block is in the list.
141 if (const auto *CPI = dyn_cast<CatchPadInst>(Val&: I)) {
142 for (const auto *U : CPI->users())
143 if (const auto *CRI = dyn_cast<CatchReturnInst>(Val: U))
144 if (!Result.count(key: const_cast<BasicBlock*>(CRI->getParent())))
145 return false;
146 continue;
147 }
148
149 // And do similar checks for cleanup handler - the entire handler must be
150 // in subgraph which is going to be extracted. For cleanup return should
151 // additionally check that the unwind destination is also in the subgraph.
152 if (const auto *CPI = dyn_cast<CleanupPadInst>(Val&: I)) {
153 for (const auto *U : CPI->users())
154 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val: U))
155 if (!Result.count(key: const_cast<BasicBlock*>(CRI->getParent())))
156 return false;
157 continue;
158 }
159 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val&: I)) {
160 if (auto *UBB = CRI->getUnwindDest())
161 if (!Result.count(key: UBB))
162 return false;
163 continue;
164 }
165
166 // llvm.experimental.deoptimize must return the enclosing function's return
167 // type. Extraction changes the outlined function signature, which can make
168 // the deoptimize call invalid.
169 if (BB.getTerminatingDeoptimizeCall())
170 return false;
171
172 if (const CallInst *CI = dyn_cast<CallInst>(Val&: I)) {
173 // musttail calls have several restrictions, generally enforcing matching
174 // calling conventions between the caller parent and musttail callee.
175 // We can't usually honor them, because the extracted function has a
176 // different signature altogether, taking inputs/outputs and returning
177 // a control-flow identifier rather than the actual return value.
178 if (CI->isMustTailCall())
179 return false;
180
181 if (const Function *F = CI->getCalledFunction()) {
182 auto IID = F->getIntrinsicID();
183 if (IID == Intrinsic::vastart) {
184 if (AllowVarArgs)
185 continue;
186 else
187 return false;
188 }
189
190 // Currently, we miscompile outlined copies of eh_typid_for. There are
191 // proposals for fixing this in llvm.org/PR39545.
192 if (IID == Intrinsic::eh_typeid_for)
193 return false;
194 }
195 }
196 }
197
198 return true;
199}
200
201/// Build a set of blocks to extract if the input blocks are viable.
202static SetVector<BasicBlock *>
203buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
204 bool AllowVarArgs, bool AllowAlloca) {
205 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
206 SetVector<BasicBlock *> Result;
207
208 // Loop over the blocks, adding them to our set-vector, and aborting with an
209 // empty set if we encounter invalid blocks.
210 for (BasicBlock *BB : BBs) {
211 // If this block is dead, don't process it.
212 if (DT && !DT->isReachableFromEntry(A: BB))
213 continue;
214
215 if (!Result.insert(X: BB))
216 llvm_unreachable("Repeated basic blocks in extraction input");
217 }
218
219 LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()
220 << '\n');
221
222 for (auto *BB : Result) {
223 if (!isBlockValidForExtraction(BB: *BB, Result, AllowVarArgs, AllowAlloca))
224 return {};
225
226 // Make sure that the first block is not a landing pad.
227 if (BB == Result.front()) {
228 if (BB->isEHPad()) {
229 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
230 return {};
231 }
232 continue;
233 }
234
235 // All blocks other than the first must not have predecessors outside of
236 // the subgraph which is being extracted.
237 for (auto *PBB : predecessors(BB))
238 if (!Result.count(key: PBB)) {
239 LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "
240 "outside the region except for the first block!\n"
241 << "Problematic source BB: " << BB->getName() << "\n"
242 << "Problematic destination BB: " << PBB->getName()
243 << "\n");
244 return {};
245 }
246 }
247
248 return Result;
249}
250
251/// isAlignmentPreservedForAddrCast - Return true if the cast operation
252/// for specified target preserves original alignment
253static bool isAlignmentPreservedForAddrCast(const Triple &TargetTriple) {
254 switch (TargetTriple.getArch()) {
255 case Triple::ArchType::amdgpu:
256 case Triple::ArchType::r600:
257 return true;
258 // TODO: Add other architectures for which we are certain that alignment
259 // is preserved during address space cast operations.
260 default:
261 return false;
262 }
263 return false;
264}
265
266CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
267 bool AggregateArgs, BlockFrequencyInfo *BFI,
268 BranchProbabilityInfo *BPI, AssumptionCache *AC,
269 bool AllowVarArgs, bool AllowAlloca,
270 BasicBlock *AllocationBlock,
271 ArrayRef<BasicBlock *> DeallocationBlocks,
272 std::string Suffix, bool ArgsInZeroAddressSpace,
273 bool VoidReturnWithSingleOutput)
274 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
275 BPI(BPI), AC(AC), AllocationBlock(AllocationBlock),
276 DeallocationBlocks(DeallocationBlocks), AllowVarArgs(AllowVarArgs),
277 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
278 Suffix(Suffix), ArgsInZeroAddressSpace(ArgsInZeroAddressSpace),
279 VoidReturnWithSingleOutput(VoidReturnWithSingleOutput) {}
280
281/// definedInRegion - Return true if the specified value is defined in the
282/// extracted region.
283static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
284 if (Instruction *I = dyn_cast<Instruction>(Val: V))
285 if (Blocks.count(key: I->getParent()))
286 return true;
287 return false;
288}
289
290/// definedInCaller - Return true if the specified value is defined in the
291/// function being code extracted, but not in the region being extracted.
292/// These values must be passed in as live-ins to the function.
293static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
294 if (isa<Argument>(Val: V)) return true;
295 if (Instruction *I = dyn_cast<Instruction>(Val: V))
296 if (!Blocks.count(key: I->getParent()))
297 return true;
298 return false;
299}
300
301static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
302 BasicBlock *CommonExitBlock = nullptr;
303 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
304 for (auto *Succ : successors(BB: Block)) {
305 // Internal edges, ok.
306 if (Blocks.count(key: Succ))
307 continue;
308 if (!CommonExitBlock) {
309 CommonExitBlock = Succ;
310 continue;
311 }
312 if (CommonExitBlock != Succ)
313 return true;
314 }
315 return false;
316 };
317
318 if (any_of(Range: Blocks, P: hasNonCommonExitSucc))
319 return nullptr;
320
321 return CommonExitBlock;
322}
323
324CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) {
325 for (BasicBlock &BB : F) {
326 for (Instruction &II : BB)
327 if (auto *AI = dyn_cast<AllocaInst>(Val: &II))
328 Allocas.push_back(Elt: AI);
329
330 findSideEffectInfoForBlock(BB);
331 }
332}
333
334void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {
335 for (Instruction &II : BB) {
336 unsigned Opcode = II.getOpcode();
337 Value *MemAddr = nullptr;
338 switch (Opcode) {
339 case Instruction::Store:
340 case Instruction::Load: {
341 if (Opcode == Instruction::Store) {
342 StoreInst *SI = cast<StoreInst>(Val: &II);
343 MemAddr = SI->getPointerOperand();
344 } else {
345 LoadInst *LI = cast<LoadInst>(Val: &II);
346 MemAddr = LI->getPointerOperand();
347 }
348 // Global variable can not be aliased with locals.
349 if (isa<Constant>(Val: MemAddr))
350 break;
351 Value *Base = MemAddr->stripInBoundsConstantOffsets();
352 if (!isa<AllocaInst>(Val: Base)) {
353 SideEffectingBlocks.insert(V: &BB);
354 return;
355 }
356 BaseMemAddrs[&BB].insert(V: Base);
357 break;
358 }
359 default: {
360 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(Val: &II);
361 if (IntrInst) {
362 if (IntrInst->isLifetimeStartOrEnd() || isa<PseudoProbeInst>(Val: IntrInst))
363 break;
364 SideEffectingBlocks.insert(V: &BB);
365 return;
366 }
367 // Treat all the other cases conservatively if it has side effects.
368 if (II.mayHaveSideEffects()) {
369 SideEffectingBlocks.insert(V: &BB);
370 return;
371 }
372 }
373 }
374 }
375}
376
377bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr(
378 BasicBlock &BB, AllocaInst *Addr) const {
379 if (SideEffectingBlocks.count(V: &BB))
380 return true;
381 auto It = BaseMemAddrs.find(Val: &BB);
382 if (It != BaseMemAddrs.end())
383 return It->second.count(V: Addr);
384 return false;
385}
386
387bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
388 const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {
389 AllocaInst *AI = cast<AllocaInst>(Val: Addr->stripInBoundsConstantOffsets());
390 Function *Func = (*Blocks.begin())->getParent();
391 for (BasicBlock &BB : *Func) {
392 if (Blocks.count(key: &BB))
393 continue;
394 if (CEAC.doesBlockContainClobberOfAddr(BB, Addr: AI))
395 return false;
396 }
397 return true;
398}
399
400BasicBlock *
401CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
402 BasicBlock *SinglePredFromOutlineRegion = nullptr;
403 assert(!Blocks.count(CommonExitBlock) &&
404 "Expect a block outside the region!");
405 for (auto *Pred : predecessors(BB: CommonExitBlock)) {
406 if (!Blocks.count(key: Pred))
407 continue;
408 if (!SinglePredFromOutlineRegion) {
409 SinglePredFromOutlineRegion = Pred;
410 } else if (SinglePredFromOutlineRegion != Pred) {
411 SinglePredFromOutlineRegion = nullptr;
412 break;
413 }
414 }
415
416 if (SinglePredFromOutlineRegion)
417 return SinglePredFromOutlineRegion;
418
419#ifndef NDEBUG
420 auto getFirstPHI = [](BasicBlock *BB) {
421 BasicBlock::iterator I = BB->begin();
422 PHINode *FirstPhi = nullptr;
423 while (I != BB->end()) {
424 PHINode *Phi = dyn_cast<PHINode>(I);
425 if (!Phi)
426 break;
427 if (!FirstPhi) {
428 FirstPhi = Phi;
429 break;
430 }
431 }
432 return FirstPhi;
433 };
434 // If there are any phi nodes, the single pred either exists or has already
435 // be created before code extraction.
436 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
437#endif
438
439 BasicBlock *NewExitBlock =
440 CommonExitBlock->splitBasicBlock(I: CommonExitBlock->getFirstNonPHIIt());
441
442 for (BasicBlock *Pred :
443 llvm::make_early_inc_range(Range: predecessors(BB: CommonExitBlock))) {
444 if (Blocks.count(key: Pred))
445 continue;
446 Pred->getTerminator()->replaceUsesOfWith(From: CommonExitBlock, To: NewExitBlock);
447 }
448 // Now add the old exit block to the outline region.
449 Blocks.insert(X: CommonExitBlock);
450 return CommonExitBlock;
451}
452
453Instruction *CodeExtractor::allocateVar(IRBuilder<>::InsertPoint AllocaIP,
454 DebugLoc, Type *VarType,
455 const Twine &Name,
456 AddrSpaceCastInst **CastedAlloc) {
457 // An alloca needs no debug location, so the one passed in goes unused here.
458 BasicBlock *BB = AllocaIP.getNodeParent();
459 const DataLayout &DL = BB->getDataLayout();
460 Instruction *Alloca =
461 new AllocaInst(VarType, DL.getAllocaAddrSpace(), nullptr, Name, AllocaIP);
462
463 if (CastedAlloc && ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) {
464 *CastedAlloc = new AddrSpaceCastInst(
465 Alloca, PointerType::get(C&: BB->getContext(), AddressSpace: 0), Name + ".ascast");
466 (*CastedAlloc)->insertAfter(InsertPos: Alloca->getIterator());
467 }
468 return Alloca;
469}
470
471Instruction *CodeExtractor::deallocateVar(IRBuilder<>::InsertPoint, DebugLoc,
472 Value *, Type *) {
473 // Default alloca instructions created by allocateVar are released implicitly.
474 return nullptr;
475}
476
477// Find the pair of life time markers for address 'Addr' that are either
478// defined inside the outline region or can legally be shrinkwrapped into the
479// outline region. If there are not other untracked uses of the address, return
480// the pair of markers if found; otherwise return a pair of nullptr.
481CodeExtractor::LifetimeMarkerInfo
482CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
483 Instruction *Addr,
484 BasicBlock *ExitBlock) const {
485 LifetimeMarkerInfo Info;
486
487 for (User *U : Addr->users()) {
488 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(Val: U);
489 if (IntrInst) {
490 // We don't model addresses with multiple start/end markers, but the
491 // markers do not need to be in the region.
492 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
493 if (Info.LifeStart)
494 return {};
495 Info.LifeStart = IntrInst;
496 continue;
497 }
498 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
499 if (Info.LifeEnd)
500 return {};
501 Info.LifeEnd = IntrInst;
502 continue;
503 }
504 }
505 // Find untracked uses of the address, bail.
506 if (!definedInRegion(Blocks, V: U))
507 return {};
508 }
509
510 if (!Info.LifeStart || !Info.LifeEnd)
511 return {};
512
513 Info.SinkLifeStart = !definedInRegion(Blocks, V: Info.LifeStart);
514 Info.HoistLifeEnd = !definedInRegion(Blocks, V: Info.LifeEnd);
515 // Do legality check.
516 if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
517 !isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr))
518 return {};
519
520 // Check to see if we have a place to do hoisting, if not, bail.
521 if (Info.HoistLifeEnd && !ExitBlock)
522 return {};
523
524 return Info;
525}
526
527void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC,
528 ValueSet &SinkCands, ValueSet &HoistCands,
529 BasicBlock *&ExitBlock) const {
530 Function *Func = (*Blocks.begin())->getParent();
531 ExitBlock = getCommonExitBlock(Blocks);
532
533 auto moveOrIgnoreLifetimeMarkers =
534 [&](const LifetimeMarkerInfo &LMI) -> bool {
535 if (!LMI.LifeStart)
536 return false;
537 if (LMI.SinkLifeStart) {
538 LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart
539 << "\n");
540 SinkCands.insert(X: LMI.LifeStart);
541 }
542 if (LMI.HoistLifeEnd) {
543 LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");
544 HoistCands.insert(X: LMI.LifeEnd);
545 }
546 return true;
547 };
548
549 // Look up allocas in the original function in CodeExtractorAnalysisCache, as
550 // this is much faster than walking all the instructions.
551 for (AllocaInst *AI : CEAC.getAllocas()) {
552 BasicBlock *BB = AI->getParent();
553 if (Blocks.count(key: BB))
554 continue;
555
556 // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,
557 // check whether it is actually still in the original function.
558 Function *AIFunc = BB->getParent();
559 if (AIFunc != Func)
560 continue;
561
562 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, Addr: AI, ExitBlock);
563 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
564 if (Moved) {
565 LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");
566 SinkCands.insert(X: AI);
567 continue;
568 }
569 }
570}
571
572bool CodeExtractor::isEligible() const {
573 if (Blocks.empty())
574 return false;
575 BasicBlock *Header = *Blocks.begin();
576 Function *F = Header->getParent();
577
578 // For functions with varargs, check that varargs handling is only done in the
579 // outlined function, i.e vastart and vaend are only used in outlined blocks.
580 if (AllowVarArgs && F->getFunctionType()->isVarArg()) {
581 auto containsVarArgIntrinsic = [](const Instruction &I) {
582 if (const CallInst *CI = dyn_cast<CallInst>(Val: &I))
583 if (const Function *Callee = CI->getCalledFunction())
584 return Callee->getIntrinsicID() == Intrinsic::vastart ||
585 Callee->getIntrinsicID() == Intrinsic::vaend;
586 return false;
587 };
588
589 for (auto &BB : *F) {
590 if (Blocks.count(key: &BB))
591 continue;
592 if (llvm::any_of(Range&: BB, P: containsVarArgIntrinsic))
593 return false;
594 }
595 }
596 // stacksave as input implies stackrestore in the outlined function.
597 // This can confuse prolog epilog insertion phase.
598 // stacksave's uses must not cross outlined function.
599 for (BasicBlock *BB : Blocks) {
600 for (Instruction &I : *BB) {
601 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: &I);
602 if (!II)
603 continue;
604 bool IsSave = II->getIntrinsicID() == Intrinsic::stacksave;
605 bool IsRestore = II->getIntrinsicID() == Intrinsic::stackrestore;
606 if (IsSave && any_of(Range: II->users(), P: [&Blks = this->Blocks](User *U) {
607 return !definedInRegion(Blocks: Blks, V: U);
608 }))
609 return false;
610 if (IsRestore && !definedInRegion(Blocks, V: II->getArgOperand(i: 0)))
611 return false;
612 }
613 }
614 return true;
615}
616
617void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
618 const ValueSet &SinkCands,
619 bool CollectGlobalInputs) {
620 for (BasicBlock *BB : Blocks) {
621 // If a used value is defined outside the region, it's an input. If an
622 // instruction is used outside the region, it's an output.
623 for (Instruction &II : *BB) {
624 for (auto &OI : II.operands()) {
625 Value *V = OI;
626 if (!SinkCands.count(key: V) &&
627 (definedInCaller(Blocks, V) ||
628 (CollectGlobalInputs && llvm::isa<llvm::GlobalVariable>(Val: V))))
629 Inputs.insert(X: V);
630 }
631
632 for (User *U : II.users())
633 if (!definedInRegion(Blocks, V: U)) {
634 Outputs.insert(X: &II);
635 break;
636 }
637 }
638 }
639
640 // Reset stale state from any prior call in HotColdSplitting; the CFG may
641 // have changed since.
642 FuncRetVal = nullptr;
643 if (!VoidReturnWithSingleOutput && !AggregateArgs && Outputs.size() == 1 &&
644 getCommonExitBlock(Blocks)) {
645 FuncRetVal = Outputs[0];
646 Outputs.clear();
647 }
648}
649
650/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
651/// of the region, we need to split the entry block of the region so that the
652/// PHI node is easier to deal with.
653void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
654 unsigned NumPredsFromRegion = 0;
655 unsigned NumPredsOutsideRegion = 0;
656
657 if (Header != &Header->getParent()->getEntryBlock()) {
658 PHINode *PN = dyn_cast<PHINode>(Val: Header->begin());
659 if (!PN) return; // No PHI nodes.
660
661 // If the header node contains any PHI nodes, check to see if there is more
662 // than one entry from outside the region. If so, we need to sever the
663 // header block into two.
664 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
665 if (Blocks.count(key: PN->getIncomingBlock(i)))
666 ++NumPredsFromRegion;
667 else
668 ++NumPredsOutsideRegion;
669
670 // If there is one (or fewer) predecessor from outside the region, we don't
671 // need to do anything special.
672 if (NumPredsOutsideRegion <= 1) return;
673 }
674
675 // Otherwise, we need to split the header block into two pieces: one
676 // containing PHI nodes merging values from outside of the region, and a
677 // second that contains all of the code for the block and merges back any
678 // incoming values from inside of the region.
679 BasicBlock *NewBB = SplitBlock(Old: Header, SplitPt: Header->getFirstNonPHIIt(), DT);
680
681 // We only want to code extract the second block now, and it becomes the new
682 // header of the region.
683 BasicBlock *OldPred = Header;
684 Blocks.remove(X: OldPred);
685 Blocks.insert(X: NewBB);
686 Header = NewBB;
687
688 // Okay, now we need to adjust the PHI nodes and any branches from within the
689 // region to go to the new header block instead of the old header block.
690 if (NumPredsFromRegion) {
691 PHINode *PN = cast<PHINode>(Val: OldPred->begin());
692 // Loop over all of the predecessors of OldPred that are in the region,
693 // changing them to branch to NewBB instead.
694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
695 if (Blocks.count(key: PN->getIncomingBlock(i))) {
696 Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
697 TI->replaceUsesOfWith(From: OldPred, To: NewBB);
698 }
699
700 // Okay, everything within the region is now branching to the right block, we
701 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
702 BasicBlock::iterator AfterPHIs;
703 for (AfterPHIs = OldPred->begin(); isa<PHINode>(Val: AfterPHIs); ++AfterPHIs) {
704 PHINode *PN = cast<PHINode>(Val&: AfterPHIs);
705 // Create a new PHI node in the new region, which has an incoming value
706 // from OldPred of PN.
707 PHINode *NewPN = PHINode::Create(Ty: PN->getType(), NumReservedValues: 1 + NumPredsFromRegion,
708 NameStr: PN->getName() + ".ce");
709 NewPN->insertBefore(InsertPos: NewBB->begin());
710 PN->replaceAllUsesWith(V: NewPN);
711 NewPN->addIncoming(V: PN, BB: OldPred);
712
713 // Loop over all of the incoming value in PN, moving them to NewPN if they
714 // are from the extracted region.
715 PN->removeIncomingValueIf(Predicate: [&](unsigned i) {
716 if (Blocks.count(key: PN->getIncomingBlock(i))) {
717 NewPN->addIncoming(V: PN->getIncomingValue(i), BB: PN->getIncomingBlock(i));
718 return true;
719 }
720 return false;
721 });
722 }
723 }
724}
725
726/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
727/// outlined region, we split these PHIs on two: one with inputs from region
728/// and other with remaining incoming blocks; then first PHIs are placed in
729/// outlined region.
730void CodeExtractor::severSplitPHINodesOfExits() {
731 for (BasicBlock *ExitBB : ExtractedFuncRetVals) {
732 BasicBlock *NewBB = nullptr;
733
734 for (PHINode &PN : ExitBB->phis()) {
735 // Find all incoming values from the outlining region.
736 SmallVector<unsigned, 2> IncomingVals;
737 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
738 if (Blocks.count(key: PN.getIncomingBlock(i)))
739 IncomingVals.push_back(Elt: i);
740
741 // Do not process PHI if there is one (or fewer) predecessor from region.
742 // If PHI has exactly one predecessor from region, only this one incoming
743 // will be replaced on codeRepl block, so it should be safe to skip PHI.
744 if (IncomingVals.size() <= 1)
745 continue;
746
747 // Create block for new PHIs and add it to the list of outlined if it
748 // wasn't done before.
749 if (!NewBB) {
750 NewBB = BasicBlock::Create(Context&: ExitBB->getContext(),
751 Name: ExitBB->getName() + ".split",
752 Parent: ExitBB->getParent(), InsertBefore: ExitBB);
753 SmallVector<BasicBlock *, 4> Preds(predecessors(BB: ExitBB));
754 for (BasicBlock *PredBB : Preds)
755 if (Blocks.count(key: PredBB))
756 PredBB->getTerminator()->replaceUsesOfWith(From: ExitBB, To: NewBB);
757 UncondBrInst::Create(Target: ExitBB, InsertBefore: NewBB);
758 Blocks.insert(X: NewBB);
759 }
760
761 // Split this PHI.
762 PHINode *NewPN = PHINode::Create(Ty: PN.getType(), NumReservedValues: IncomingVals.size(),
763 NameStr: PN.getName() + ".ce");
764 NewPN->insertBefore(InsertPos: NewBB->getFirstNonPHIIt());
765 for (unsigned i : IncomingVals)
766 NewPN->addIncoming(V: PN.getIncomingValue(i), BB: PN.getIncomingBlock(i));
767 for (unsigned i : reverse(C&: IncomingVals))
768 PN.removeIncomingValue(Idx: i, DeletePHIIfEmpty: false);
769 PN.addIncoming(V: NewPN, BB: NewBB);
770 }
771 }
772}
773
774void CodeExtractor::splitReturnBlocks() {
775 for (BasicBlock *Block : Blocks)
776 if (ReturnInst *RI = dyn_cast<ReturnInst>(Val: Block->getTerminator())) {
777 BasicBlock *New =
778 Block->splitBasicBlock(I: RI->getIterator(), BBName: Block->getName() + ".ret");
779 if (DT) {
780 // Old dominates New. New node dominates all other nodes dominated
781 // by Old.
782 DomTreeNode *OldNode = DT->getNode(BB: Block);
783 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
784 OldNode->end());
785
786 DomTreeNode *NewNode = DT->addNewBlock(BB: New, DomBB: Block);
787
788 for (DomTreeNode *I : Children)
789 DT->changeImmediateDominator(N: I, NewIDom: NewNode);
790 }
791 }
792}
793
794Function *CodeExtractor::constructFunctionDeclaration(
795 const ValueSet &inputs, const ValueSet &outputs, BlockFrequency EntryFreq,
796 const Twine &Name, ValueSet &StructValues, StructType *&StructTy) {
797 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
798 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
799
800 Function *oldFunction = Blocks.front()->getParent();
801 Module *M = Blocks.front()->getModule();
802
803 // Assemble the function's parameter lists.
804 std::vector<Type *> ParamTy;
805 std::vector<Type *> AggParamTy;
806 const DataLayout &DL = M->getDataLayout();
807
808 // Add the types of the input values to the function's argument list
809 for (Value *value : inputs) {
810 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
811 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(key: value)) {
812 AggParamTy.push_back(x: value->getType());
813 StructValues.insert(X: value);
814 } else
815 ParamTy.push_back(x: value->getType());
816 }
817
818 // Add the types of the output values to the function's argument list.
819 for (Value *output : outputs) {
820 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
821 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(key: output)) {
822 AggParamTy.push_back(x: output->getType());
823 StructValues.insert(X: output);
824 } else
825 ParamTy.push_back(
826 x: PointerType::get(C&: output->getContext(), AddressSpace: DL.getAllocaAddrSpace()));
827 }
828
829 assert(
830 (ParamTy.size() + AggParamTy.size()) ==
831 (inputs.size() + outputs.size()) &&
832 "Number of scalar and aggregate params does not match inputs, outputs");
833 assert((StructValues.empty() || AggregateArgs) &&
834 "Expeced StructValues only with AggregateArgs set");
835
836 // Concatenate scalar and aggregate params in ParamTy.
837 if (!AggParamTy.empty()) {
838 StructTy = StructType::get(Context&: M->getContext(), Elements: AggParamTy);
839 ParamTy.push_back(x: PointerType::get(
840 C&: M->getContext(), AddressSpace: ArgsInZeroAddressSpace ? 0 : DL.getAllocaAddrSpace()));
841 }
842
843 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
844 LLVM_DEBUG({
845 dbgs() << "Function type: " << *RetTy << " f(";
846 for (Type *i : ParamTy)
847 dbgs() << *i << ", ";
848 dbgs() << ")\n";
849 });
850
851 FunctionType *funcType = FunctionType::get(
852 Result: RetTy, Params: ParamTy, isVarArg: AllowVarArgs && oldFunction->isVarArg());
853
854 // Create the new function
855 Function *newFunction =
856 Function::Create(Ty: funcType, Linkage: GlobalValue::InternalLinkage,
857 AddrSpace: oldFunction->getAddressSpace(), N: Name, M);
858
859 // Propagate personality info to the new function if there is one.
860 if (oldFunction->hasPersonalityFn())
861 newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
862
863 // Inherit all of the target dependent attributes and white-listed
864 // target independent attributes.
865 // (e.g. If the extracted region contains a call to an x86.sse
866 // instruction we need to make sure that the extracted region has the
867 // "target-features" attribute allowing it to be lowered.
868 // FIXME: This should be changed to check to see if a specific
869 // attribute can not be inherited.
870 for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) {
871 if (Attr.isStringAttribute()) {
872 if (Attr.getKindAsString() == "thunk")
873 continue;
874 } else
875 switch (Attr.getKindAsEnum()) {
876 // Those attributes cannot be propagated safely. Explicitly list them
877 // here so we get a warning if new attributes are added.
878 case Attribute::AllocSize:
879 case Attribute::Builtin:
880 case Attribute::Convergent:
881 case Attribute::JumpTable:
882 case Attribute::Naked:
883 case Attribute::NoBuiltin:
884 case Attribute::NoMerge:
885 case Attribute::NoReturn:
886 case Attribute::NoSync:
887 case Attribute::ReturnsTwice:
888 case Attribute::Speculatable:
889 case Attribute::StackAlignment:
890 case Attribute::WillReturn:
891 case Attribute::AllocKind:
892 case Attribute::PresplitCoroutine:
893 case Attribute::Memory:
894 case Attribute::NoFPClass:
895 case Attribute::CoroDestroyOnlyWhenComplete:
896 case Attribute::CoroElideSafe:
897 case Attribute::NoDivergenceSource:
898 case Attribute::NoCreateUndefOrPoison:
899 continue;
900 // Those attributes should be safe to propagate to the extracted function.
901 case Attribute::AlwaysInline:
902 case Attribute::Cold:
903 case Attribute::DisableSanitizerInstrumentation:
904 case Attribute::Flatten:
905 case Attribute::FnRetThunkExtern:
906 case Attribute::Hot:
907 case Attribute::HybridPatchable:
908 case Attribute::NoRecurse:
909 case Attribute::InlineHint:
910 case Attribute::LikelyModuleLocal:
911 case Attribute::MinSize:
912 case Attribute::NoCallback:
913 case Attribute::NoDuplicate:
914 case Attribute::NoFree:
915 case Attribute::NoImplicitFloat:
916 case Attribute::NoInline:
917 case Attribute::NoIPA:
918 case Attribute::NoOutline:
919 case Attribute::NonLazyBind:
920 case Attribute::NoRedZone:
921 case Attribute::NoUnwind:
922 case Attribute::NoSanitizeBounds:
923 case Attribute::NoSanitizeCoverage:
924 case Attribute::NullPointerIsValid:
925 case Attribute::OptimizeForDebugging:
926 case Attribute::OptForFuzzing:
927 case Attribute::OptimizeNone:
928 case Attribute::OptimizeForSize:
929 case Attribute::SafeStack:
930 case Attribute::ShadowCallStack:
931 case Attribute::SanitizeAddress:
932 case Attribute::SanitizeMemory:
933 case Attribute::SanitizeNumericalStability:
934 case Attribute::SanitizeThread:
935 case Attribute::SanitizeConcurrency:
936 case Attribute::SanitizeType:
937 case Attribute::SanitizeHWAddress:
938 case Attribute::SanitizeMemTag:
939 case Attribute::SanitizeRealtime:
940 case Attribute::SanitizeRealtimeBlocking:
941 case Attribute::SanitizeAllocToken:
942 case Attribute::SpeculativeLoadHardening:
943 case Attribute::StackProtect:
944 case Attribute::StackProtectReq:
945 case Attribute::StackProtectStrong:
946 case Attribute::StrictFP:
947 case Attribute::UWTable:
948 case Attribute::VScaleRange:
949 case Attribute::NoCfCheck:
950 case Attribute::MustProgress:
951 case Attribute::NoProfile:
952 case Attribute::SkipProfile:
953 case Attribute::DenormalFPEnv:
954 break;
955 // These attributes cannot be applied to functions.
956 case Attribute::Alignment:
957 case Attribute::AllocatedPointer:
958 case Attribute::AllocAlign:
959 case Attribute::ByVal:
960 case Attribute::Captures:
961 case Attribute::Dereferenceable:
962 case Attribute::DereferenceableOrNull:
963 case Attribute::ElementType:
964 case Attribute::InAlloca:
965 case Attribute::InReg:
966 case Attribute::Nest:
967 case Attribute::NoAlias:
968 case Attribute::NoUndef:
969 case Attribute::NonNull:
970 case Attribute::Preallocated:
971 case Attribute::ReadNone:
972 case Attribute::ReadOnly:
973 case Attribute::Returned:
974 case Attribute::SExt:
975 case Attribute::StructRet:
976 case Attribute::SwiftError:
977 case Attribute::SwiftSelf:
978 case Attribute::SwiftAsync:
979 case Attribute::ZExt:
980 case Attribute::ImmArg:
981 case Attribute::ByRef:
982 case Attribute::WriteOnly:
983 case Attribute::Writable:
984 case Attribute::DeadOnUnwind:
985 case Attribute::Range:
986 case Attribute::Initializes:
987 case Attribute::NoExt:
988 case Attribute::NoFreeObj:
989 // These are not really attributes.
990 case Attribute::None:
991 case Attribute::EndAttrKinds:
992 case Attribute::EmptyKey:
993 case Attribute::TombstoneKey:
994 case Attribute::DeadOnReturn:
995 llvm_unreachable("Not a function attribute");
996 }
997
998 newFunction->addFnAttr(Attr);
999 }
1000
1001 // Create scalar and aggregate iterators to name all of the arguments we
1002 // inserted.
1003 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1004
1005 // Set names and attributes for input and output arguments.
1006 ScalarAI = newFunction->arg_begin();
1007 for (Value *input : inputs) {
1008 if (StructValues.contains(key: input))
1009 continue;
1010
1011 ScalarAI->setName(input->getName());
1012 if (input->isSwiftError())
1013 newFunction->addParamAttr(ArgNo: ScalarAI - newFunction->arg_begin(),
1014 Kind: Attribute::SwiftError);
1015 ++ScalarAI;
1016 }
1017 for (Value *output : outputs) {
1018 if (StructValues.contains(key: output))
1019 continue;
1020
1021 ScalarAI->setName(output->getName() + ".out");
1022 ++ScalarAI;
1023 }
1024
1025 // Update the entry count of the function.
1026 if (BFI) {
1027 auto Count = BFI->getProfileCountFromFreq(Freq: EntryFreq);
1028 if (Count.has_value())
1029 newFunction->setEntryCount(Count: *Count);
1030 }
1031
1032 return newFunction;
1033}
1034
1035/// If the original function has debug info, we have to add a debug location
1036/// to the new branch instruction from the artificial entry block.
1037/// We use the debug location of the first instruction in the extracted
1038/// blocks, as there is no other equivalent line in the source code.
1039static void applyFirstDebugLoc(Function *oldFunction,
1040 ArrayRef<BasicBlock *> Blocks,
1041 Instruction *BranchI) {
1042 if (oldFunction->getSubprogram()) {
1043 any_of(Range&: Blocks, P: [&BranchI](const BasicBlock *BB) {
1044 return any_of(Range: *BB, P: [&BranchI](const Instruction &I) {
1045 if (!I.getDebugLoc())
1046 return false;
1047 BranchI->setDebugLoc(I.getDebugLoc());
1048 return true;
1049 });
1050 });
1051 }
1052}
1053
1054/// Erase lifetime.start markers which reference inputs to the extraction
1055/// region, and insert the referenced memory into \p LifetimesStart.
1056///
1057/// The extraction region is defined by a set of blocks (\p Blocks), and a set
1058/// of allocas which will be moved from the caller function into the extracted
1059/// function (\p SunkAllocas).
1060static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
1061 const SetVector<Value *> &SunkAllocas,
1062 SetVector<Value *> &LifetimesStart) {
1063 for (BasicBlock *BB : Blocks) {
1064 for (Instruction &I : llvm::make_early_inc_range(Range&: *BB)) {
1065 auto *II = dyn_cast<LifetimeIntrinsic>(Val: &I);
1066 if (!II)
1067 continue;
1068
1069 // Get the memory operand of the lifetime marker. If the underlying
1070 // object is a sunk alloca, or is otherwise defined in the extraction
1071 // region, the lifetime marker must not be erased.
1072 Value *Mem = II->getOperand(i_nocapture: 0);
1073 if (SunkAllocas.count(key: Mem) || definedInRegion(Blocks, V: Mem))
1074 continue;
1075
1076 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1077 LifetimesStart.insert(X: Mem);
1078 II->eraseFromParent();
1079 }
1080 }
1081}
1082
1083/// Insert lifetime start/end markers surrounding the call to the new function
1084/// for objects defined in the caller.
1085static void insertLifetimeMarkersSurroundingCall(
1086 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
1087 CallInst *TheCall) {
1088 Instruction *Term = TheCall->getParent()->getTerminator();
1089
1090 // Emit lifetime markers for the pointers given in \p Objects. Insert the
1091 // markers before the call if \p InsertBefore, and after the call otherwise.
1092 auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects,
1093 bool InsertBefore) {
1094 for (Value *Mem : Objects) {
1095 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==
1096 TheCall->getFunction()) &&
1097 "Input memory not defined in original function");
1098
1099 Function *Func =
1100 Intrinsic::getOrInsertDeclaration(M, id: MarkerFunc, OverloadTys: Mem->getType());
1101 auto Marker = CallInst::Create(Func, Args: Mem);
1102 if (InsertBefore)
1103 Marker->insertBefore(InsertPos: TheCall->getIterator());
1104 else
1105 Marker->insertBefore(InsertPos: Term->getIterator());
1106 }
1107 };
1108
1109 if (!LifetimesStart.empty()) {
1110 insertMarkers(Intrinsic::lifetime_start, LifetimesStart,
1111 /*InsertBefore=*/true);
1112 }
1113
1114 if (!LifetimesEnd.empty()) {
1115 insertMarkers(Intrinsic::lifetime_end, LifetimesEnd,
1116 /*InsertBefore=*/false);
1117 }
1118}
1119
1120void CodeExtractor::moveCodeToFunction(Function *newFunction) {
1121 auto newFuncIt = newFunction->begin();
1122 for (BasicBlock *Block : Blocks) {
1123 // Delete the basic block from the old function, and the list of blocks
1124 Block->removeFromParent();
1125
1126 // Insert this basic block into the new function
1127 // Insert the original blocks after the entry block created
1128 // for the new function. The entry block may be followed
1129 // by a set of exit blocks at this point, but these exit
1130 // blocks better be placed at the end of the new function.
1131 newFuncIt = newFunction->insert(Position: std::next(x: newFuncIt), BB: Block);
1132 }
1133}
1134
1135void CodeExtractor::calculateNewCallTerminatorWeights(
1136 BasicBlock *CodeReplacer,
1137 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1138 BranchProbabilityInfo *BPI) {
1139 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1140 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
1141
1142 // Update the branch weights for the exit block.
1143 Instruction *TI = CodeReplacer->getTerminator();
1144 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1145
1146 // Block Frequency distribution with dummy node.
1147 Distribution BranchDist;
1148
1149 SmallVector<BranchProbability, 4> EdgeProbabilities(
1150 TI->getNumSuccessors(), BranchProbability::getUnknown());
1151
1152 // Add each of the frequencies of the successors.
1153 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1154 BlockNode ExitNode(i);
1155 uint64_t ExitFreq = ExitWeights.lookup(Val: TI->getSuccessor(Idx: i)).getFrequency();
1156 if (ExitFreq != 0)
1157 BranchDist.addExit(Node: ExitNode, Amount: ExitFreq);
1158 else
1159 EdgeProbabilities[i] = BranchProbability::getZero();
1160 }
1161
1162 // Check for no total weight.
1163 if (BranchDist.Total == 0) {
1164 BPI->setEdgeProbability(Src: CodeReplacer, Probs: EdgeProbabilities);
1165 return;
1166 }
1167
1168 // Normalize the distribution so that they can fit in unsigned.
1169 BranchDist.normalize();
1170
1171 // Create normalized branch weights and set the metadata.
1172 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1173 const auto &Weight = BranchDist.Weights[I];
1174
1175 // Get the weight and update the current BFI.
1176 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1177 BranchProbability BP(Weight.Amount, BranchDist.Total);
1178 EdgeProbabilities[Weight.TargetNode.Index] = BP;
1179 }
1180 BPI->setEdgeProbability(Src: CodeReplacer, Probs: EdgeProbabilities);
1181 TI->setMetadata(
1182 KindID: LLVMContext::MD_prof,
1183 Node: MDBuilder(TI->getContext()).createBranchWeights(Weights: BranchWeights));
1184}
1185
1186/// Erase debug info intrinsics which refer to values in \p F but aren't in
1187/// \p F.
1188static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) {
1189 for (Instruction &I : instructions(F)) {
1190 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1191 findDbgUsers(V: &I, DbgVariableRecords);
1192 for (DbgVariableRecord *DVR : DbgVariableRecords)
1193 if (DVR->getFunction() != &F)
1194 DVR->eraseFromParent();
1195 }
1196}
1197
1198/// Fix up the debug info in the old and new functions. Following changes are
1199/// done.
1200/// 1. If a debug record points to a value that has been replaced, update the
1201/// record to use the new value.
1202/// 2. If an Input value that has been replaced was used as a location of a
1203/// debug record in the Parent function, then materealize a similar record in
1204/// the new function.
1205/// 3. Point line locations and debug intrinsics to the new subprogram scope
1206/// 4. Remove intrinsics which point to values outside of the new function.
1207static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
1208 CallInst &TheCall,
1209 const SetVector<Value *> &Inputs,
1210 ArrayRef<Value *> NewValues) {
1211 DISubprogram *OldSP = OldFunc.getSubprogram();
1212 LLVMContext &Ctx = OldFunc.getContext();
1213
1214 if (!OldSP) {
1215 // Erase any debug info the new function contains.
1216 stripDebugInfo(F&: NewFunc);
1217 // Make sure the old function doesn't contain any non-local metadata refs.
1218 eraseDebugIntrinsicsWithNonLocalRefs(F&: NewFunc);
1219 return;
1220 }
1221
1222 // Create a subprogram for the new function. Leave out a description of the
1223 // function arguments, as the parameters don't correspond to anything at the
1224 // source level.
1225 assert(OldSP->getUnit() && "Missing compile unit for subprogram");
1226 DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,
1227 OldSP->getUnit());
1228 auto SPType = DIB.createSubroutineType(ParameterTypes: DIB.getOrCreateTypeArray(Elements: {}));
1229 DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |
1230 DISubprogram::SPFlagOptimized |
1231 DISubprogram::SPFlagLocalToUnit;
1232 auto NewSP = DIB.createFunction(
1233 Scope: OldSP->getUnit(), Name: NewFunc.getName(), LinkageName: NewFunc.getName(), File: OldSP->getFile(),
1234 /*LineNo=*/0, Ty: SPType, /*ScopeLine=*/0, Flags: DINode::FlagZero, SPFlags);
1235 NewFunc.setSubprogram(NewSP);
1236
1237 auto UpdateOrInsertDebugRecord = [&](auto *DR, Value *OldLoc, Value *NewLoc,
1238 DIExpression *Expr, bool Declare) {
1239 if (DR->getParent()->getParent() == &NewFunc) {
1240 DR->replaceVariableLocationOp(OldLoc, NewLoc);
1241 return;
1242 }
1243 if (Declare) {
1244 DIB.insertDeclare(NewLoc, DR->getVariable(), Expr, DR->getDebugLoc(),
1245 &NewFunc.getEntryBlock());
1246 return;
1247 }
1248 DIB.insertDbgValue(Val: NewLoc, VarInfo: DR->getVariable(), Expr, DL: DR->getDebugLoc(),
1249 InsertPt: NewFunc.getEntryBlock().getTerminator()->getIterator());
1250 };
1251 for (auto [Input, NewVal] : zip_equal(t: Inputs, u&: NewValues)) {
1252 SmallVector<DbgVariableRecord *, 1> DPUsers;
1253 findDbgUsers(V: Input, DbgVariableRecords&: DPUsers);
1254
1255 // Iterate the debug users of the Input values. If they are in the extracted
1256 // function then update their location with the new value. If they are in
1257 // the parent function then create a similar debug record.
1258 for (auto *DVR : DPUsers) {
1259 DIExpression *Expr = DVR->getNumVariableLocationOps() == 1
1260 ? DVR->getExpression()
1261 : DIB.createExpression();
1262 UpdateOrInsertDebugRecord(DVR, Input, NewVal, Expr, DVR->isDbgDeclare());
1263 }
1264 }
1265
1266 auto IsInvalidLocation = [&NewFunc](Value *Location) {
1267 // Location is invalid if it isn't a constant, an instruction or an
1268 // argument, or is an instruction/argument but isn't in the new function.
1269 if (!Location || (!isa<Constant>(Val: Location) && !isa<Argument>(Val: Location) &&
1270 !isa<Instruction>(Val: Location)))
1271 return true;
1272
1273 if (Argument *Arg = dyn_cast<Argument>(Val: Location))
1274 return Arg->getParent() != &NewFunc;
1275 if (Instruction *LocationInst = dyn_cast<Instruction>(Val: Location))
1276 return LocationInst->getFunction() != &NewFunc;
1277 return false;
1278 };
1279
1280 // Debug intrinsics in the new function need to be updated in one of two
1281 // ways:
1282 // 1) They need to be deleted, because they describe a value in the old
1283 // function.
1284 // 2) They need to point to fresh metadata, e.g. because they currently
1285 // point to a variable in the wrong scope.
1286 SmallDenseMap<DINode *, DINode *> RemappedMetadata;
1287 SmallVector<DbgVariableRecord *, 4> DVRsToDelete;
1288 DenseMap<const MDNode *, MDNode *> Cache;
1289
1290 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) {
1291 DINode *&NewVar = RemappedMetadata[OldVar];
1292 if (!NewVar) {
1293 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(
1294 RootScope&: *OldVar->getScope(), NewSP&: *NewSP, Ctx, Cache);
1295 NewVar = DIB.createAutoVariable(
1296 Scope: NewScope, Name: OldVar->getName(), File: OldVar->getFile(), LineNo: OldVar->getLine(),
1297 Ty: OldVar->getType(), /*AlwaysPreserve=*/false, Flags: DINode::FlagZero,
1298 AlignInBits: OldVar->getAlignInBits());
1299 }
1300 return cast<DILocalVariable>(Val: NewVar);
1301 };
1302
1303 auto UpdateDbgLabel = [&](auto *LabelRecord) {
1304 // Point the label record to a fresh label within the new function if
1305 // the record was not inlined from some other function.
1306 if (LabelRecord->getDebugLoc().getInlinedAt())
1307 return;
1308 DILabel *OldLabel = LabelRecord->getLabel();
1309 DINode *&NewLabel = RemappedMetadata[OldLabel];
1310 if (!NewLabel) {
1311 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(
1312 RootScope&: *OldLabel->getScope(), NewSP&: *NewSP, Ctx, Cache);
1313 NewLabel =
1314 DILabel::get(Context&: Ctx, Scope: NewScope, Name: OldLabel->getName(), File: OldLabel->getFile(),
1315 Line: OldLabel->getLine(), Column: OldLabel->getColumn(),
1316 IsArtificial: OldLabel->isArtificial(), CoroSuspendIdx: OldLabel->getCoroSuspendIdx());
1317 }
1318 LabelRecord->setLabel(cast<DILabel>(Val: NewLabel));
1319 };
1320
1321 auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void {
1322 for (DbgRecord &DR : I.getDbgRecordRange()) {
1323 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1324 UpdateDbgLabel(DLR);
1325 continue;
1326 }
1327
1328 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1329 // If any of the used locations are invalid, delete the record.
1330 if (any_of(Range: DVR.location_ops(), P: IsInvalidLocation)) {
1331 DVRsToDelete.push_back(Elt: &DVR);
1332 continue;
1333 }
1334
1335 // DbgAssign intrinsics have an extra Value argument:
1336 if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) {
1337 DVRsToDelete.push_back(Elt: &DVR);
1338 continue;
1339 }
1340
1341 // If the variable was in the scope of the old function, i.e. it was not
1342 // inlined, point the intrinsic to a fresh variable within the new
1343 // function.
1344 if (!DVR.getDebugLoc().getInlinedAt())
1345 DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable()));
1346 }
1347 };
1348
1349 for (Instruction &I : instructions(F&: NewFunc))
1350 UpdateDbgRecordsOnInst(I);
1351
1352 for (auto *DVR : DVRsToDelete)
1353 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(I: DVR);
1354 DIB.finalizeSubprogram(SP: NewSP);
1355
1356 // Fix up the scope information attached to the line locations and the
1357 // debug assignment metadata in the new function.
1358 DenseMap<DIAssignID *, DIAssignID *> AssignmentIDMap;
1359 for (Instruction &I : instructions(F&: NewFunc)) {
1360 if (const DebugLoc &DL = I.getDebugLoc())
1361 I.setDebugLoc(
1362 DebugLoc::replaceInlinedAtSubprogram(DL, NewSP&: *NewSP, Ctx, Cache));
1363 for (DbgRecord &DR : I.getDbgRecordRange())
1364 DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DL: DR.getDebugLoc(),
1365 NewSP&: *NewSP, Ctx, Cache));
1366
1367 // Loop info metadata may contain line locations. Fix them up.
1368 auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * {
1369 if (auto *Loc = dyn_cast_or_null<DILocation>(Val: MD))
1370 return DebugLoc::replaceInlinedAtSubprogram(DL: Loc, NewSP&: *NewSP, Ctx, Cache);
1371 return MD;
1372 };
1373 updateLoopMetadataDebugLocations(I, Updater: updateLoopInfoLoc);
1374 at::remapAssignID(Map&: AssignmentIDMap, I);
1375 }
1376 if (!TheCall.getDebugLoc())
1377 TheCall.setDebugLoc(DILocation::get(Context&: Ctx, Line: 0, Column: 0, Scope: OldSP));
1378
1379 eraseDebugIntrinsicsWithNonLocalRefs(F&: NewFunc);
1380}
1381
1382Function *
1383CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) {
1384 ValueSet Inputs, Outputs;
1385 return extractCodeRegion(CEAC, Inputs, Outputs);
1386}
1387
1388Function *
1389CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC,
1390 ValueSet &inputs, ValueSet &outputs) {
1391 if (!isEligible())
1392 return nullptr;
1393
1394 // Assumption: this is a single-entry code region, and the header is the first
1395 // block in the region.
1396 BasicBlock *header = *Blocks.begin();
1397 Function *oldFunction = header->getParent();
1398
1399 normalizeCFGForExtraction(header);
1400
1401 // Remove @llvm.assume calls that will be moved to the new function from the
1402 // old function's assumption cache.
1403 for (BasicBlock *Block : Blocks) {
1404 for (Instruction &I : llvm::make_early_inc_range(Range&: *Block)) {
1405 if (auto *AI = dyn_cast<AssumeInst>(Val: &I)) {
1406 if (AC)
1407 AC->unregisterAssumption(CI: AI);
1408 AI->eraseFromParent();
1409 }
1410 }
1411 }
1412
1413 ValueSet SinkingCands, HoistingCands;
1414 BasicBlock *CommonExit = nullptr;
1415 findAllocas(CEAC, SinkCands&: SinkingCands, HoistCands&: HoistingCands, ExitBlock&: CommonExit);
1416 assert(HoistingCands.empty() || CommonExit);
1417
1418 // Find inputs to, outputs from the code region.
1419 findInputsOutputs(Inputs&: inputs, Outputs&: outputs, SinkCands: SinkingCands);
1420
1421 // Collect objects which are inputs to the extraction region and also
1422 // referenced by lifetime start markers within it. The effects of these
1423 // markers must be replicated in the calling function to prevent the stack
1424 // coloring pass from merging slots which store input objects.
1425 ValueSet LifetimesStart;
1426 eraseLifetimeMarkersOnInputs(Blocks, SunkAllocas: SinkingCands, LifetimesStart);
1427
1428 if (!HoistingCands.empty()) {
1429 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExitBlock: CommonExit);
1430 Instruction *TI = HoistToBlock->getTerminator();
1431 for (auto *II : HoistingCands)
1432 cast<Instruction>(Val: II)->moveBefore(InsertPos: TI->getIterator());
1433 computeExtractedFuncRetVals();
1434 }
1435
1436 // CFG/ExitBlocks must not change hereafter
1437
1438 // Calculate the entry frequency of the new function before we change the root
1439 // block.
1440 BlockFrequency EntryFreq;
1441 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1442 if (BFI) {
1443 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1444 for (BasicBlock *Pred : predecessors(BB: header)) {
1445 if (Blocks.count(key: Pred))
1446 continue;
1447 EntryFreq +=
1448 BFI->getBlockFreq(BB: Pred) * BPI->getEdgeProbability(Src: Pred, Dst: header);
1449 }
1450
1451 for (BasicBlock *Succ : ExtractedFuncRetVals) {
1452 for (BasicBlock *Block : predecessors(BB: Succ)) {
1453 if (!Blocks.count(key: Block))
1454 continue;
1455
1456 // Update the branch weight for this successor.
1457 BlockFrequency &BF = ExitWeights[Succ];
1458 BF += BFI->getBlockFreq(BB: Block) * BPI->getEdgeProbability(Src: Block, Dst: Succ);
1459 }
1460 }
1461 }
1462
1463 // Determine position for the replacement code. Do so before header is moved
1464 // to the new function.
1465 BasicBlock *ReplIP = header;
1466 while (ReplIP && Blocks.count(key: ReplIP))
1467 ReplIP = ReplIP->getNextNode();
1468
1469 // Construct new function based on inputs/outputs & add allocas for all defs.
1470 std::string SuffixToUse =
1471 Suffix.empty()
1472 ? (header->getName().empty() ? "extracted" : header->getName().str())
1473 : Suffix;
1474
1475 ValueSet StructValues;
1476 StructType *StructTy = nullptr;
1477 Function *newFunction = constructFunctionDeclaration(
1478 inputs, outputs, EntryFreq, Name: oldFunction->getName() + "." + SuffixToUse,
1479 StructValues, StructTy);
1480 SmallVector<Value *> NewValues;
1481
1482 emitFunctionBody(inputs, outputs, StructValues, newFunction, StructArgTy: StructTy, header,
1483 SinkingCands, NewValues);
1484
1485 std::vector<Value *> Reloads;
1486 CallInst *TheCall = emitReplacerCall(
1487 inputs, outputs, StructValues, newFunction, StructArgTy: StructTy, oldFunction, ReplIP,
1488 EntryFreq, LifetimesStart: LifetimesStart.getArrayRef(), Reloads);
1489
1490 insertReplacerCall(oldFunction, header, ReplacerCall: TheCall, outputs, Reloads,
1491 ExitWeights);
1492
1493 fixupDebugInfoPostExtraction(OldFunc&: *oldFunction, NewFunc&: *newFunction, TheCall&: *TheCall, Inputs: inputs,
1494 NewValues);
1495
1496 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - newFunction:\n");
1497 LLVM_DEBUG(newFunction->dump());
1498 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - oldFunction:\n");
1499 LLVM_DEBUG(oldFunction->dump());
1500#ifndef NDEBUG
1501 if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))
1502 report_fatal_error("Stale Asumption cache for old Function!");
1503#endif
1504 return newFunction;
1505}
1506
1507void CodeExtractor::normalizeCFGForExtraction(BasicBlock *&header) {
1508 // If we have any return instructions in the region, split those blocks so
1509 // that the return is not in the region.
1510 splitReturnBlocks();
1511
1512 // If we have to split PHI nodes of the entry or exit blocks, do so now.
1513 severSplitPHINodesOfEntry(Header&: header);
1514
1515 // If a PHI in an exit block has multiple incoming values from the outlined
1516 // region, create a new PHI for those values within the region such that only
1517 // PHI itself becomes an output value, not each of its incoming values
1518 // individually.
1519 computeExtractedFuncRetVals();
1520 severSplitPHINodesOfExits();
1521}
1522
1523void CodeExtractor::computeExtractedFuncRetVals() {
1524 ExtractedFuncRetVals.clear();
1525
1526 SmallPtrSet<BasicBlock *, 2> ExitBlocks;
1527 for (BasicBlock *Block : Blocks) {
1528 for (BasicBlock *Succ : successors(BB: Block)) {
1529 if (Blocks.count(key: Succ))
1530 continue;
1531
1532 bool IsNew = ExitBlocks.insert(Ptr: Succ).second;
1533 if (IsNew)
1534 ExtractedFuncRetVals.push_back(Elt: Succ);
1535 }
1536 }
1537}
1538
1539Type *CodeExtractor::getSwitchType() {
1540 LLVMContext &Context = Blocks.front()->getContext();
1541
1542 assert(ExtractedFuncRetVals.size() < 0xffff &&
1543 "too many exit blocks for switch");
1544 switch (ExtractedFuncRetVals.size()) {
1545 case 0:
1546 case 1:
1547 return Type::getVoidTy(C&: Context);
1548 case 2:
1549 // Conditional branch, return a bool
1550 return Type::getInt1Ty(C&: Context);
1551 default:
1552 return Type::getInt16Ty(C&: Context);
1553 }
1554}
1555
1556void CodeExtractor::emitFunctionBody(
1557 const ValueSet &inputs, const ValueSet &outputs,
1558 const ValueSet &StructValues, Function *newFunction,
1559 StructType *StructArgTy, BasicBlock *header, const ValueSet &SinkingCands,
1560 SmallVectorImpl<Value *> &NewValues) {
1561 Function *oldFunction = header->getParent();
1562 LLVMContext &Context = oldFunction->getContext();
1563
1564 // The new function needs a root node because other nodes can branch to the
1565 // head of the region, but the entry node of a function cannot have preds.
1566 BasicBlock *newFuncRoot =
1567 BasicBlock::Create(Context, Name: "newFuncRoot", Parent: newFunction);
1568
1569 // Now sink all instructions which only have non-phi uses inside the region.
1570 // Group the allocas at the start of the block, so that any bitcast uses of
1571 // the allocas are well-defined.
1572 for (auto *II : SinkingCands) {
1573 if (!isa<AllocaInst>(Val: II)) {
1574 cast<Instruction>(Val: II)->moveBefore(BB&: *newFuncRoot,
1575 I: newFuncRoot->getFirstInsertionPt());
1576 }
1577 }
1578 for (auto *II : SinkingCands) {
1579 if (auto *AI = dyn_cast<AllocaInst>(Val: II)) {
1580 AI->moveBefore(BB&: *newFuncRoot, I: newFuncRoot->getFirstInsertionPt());
1581 }
1582 }
1583
1584 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1585 Argument *AggArg = StructValues.empty()
1586 ? nullptr
1587 : newFunction->getArg(i: newFunction->arg_size() - 1);
1588
1589 // Rewrite all users of the inputs in the extracted region to use the
1590 // arguments (or appropriate addressing into struct) instead.
1591 for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) {
1592 Value *RewriteVal;
1593 if (StructValues.contains(key: inputs[i])) {
1594 Value *Idx[2];
1595 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: header->getContext()));
1596 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: header->getContext()), V: aggIdx);
1597 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1598 PointeeType: StructArgTy, Ptr: AggArg, IdxList: Idx, NameStr: "gep_" + inputs[i]->getName(), InsertBefore: newFuncRoot);
1599 LoadInst *LoadGEP =
1600 new LoadInst(StructArgTy->getElementType(N: aggIdx), GEP,
1601 "loadgep_" + inputs[i]->getName(), newFuncRoot);
1602 // If we load pointer, we can add optional !align metadata
1603 // The existence of the !align metadata on the instruction tells
1604 // the optimizer that the value loaded is known to be aligned to
1605 // a boundary specified by the integer value in the metadata node.
1606 // Example:
1607 // %res = load ptr, ptr %input, align 8, !align !align_md_node
1608 // ^ ^
1609 // | |
1610 // alignment of %input address |
1611 // |
1612 // alignment of %res object
1613 if (StructArgTy->getElementType(N: aggIdx)->isPointerTy()) {
1614 unsigned AlignmentValue;
1615 const Triple &TargetTriple =
1616 newFunction->getParent()->getTargetTriple();
1617 const DataLayout &DL = header->getDataLayout();
1618 // Pointers without casting can provide more information about
1619 // alignment. Use pointers without casts if given target preserves
1620 // alignment information for cast the operation.
1621 if (isAlignmentPreservedForAddrCast(TargetTriple))
1622 AlignmentValue =
1623 inputs[i]->stripPointerCasts()->getPointerAlignment(DL).value();
1624 else
1625 AlignmentValue = inputs[i]->getPointerAlignment(DL).value();
1626 MDBuilder MDB(header->getContext());
1627 LoadGEP->setMetadata(
1628 KindID: LLVMContext::MD_align,
1629 Node: MDNode::get(
1630 Context&: header->getContext(),
1631 MDs: MDB.createConstant(C: ConstantInt::get(
1632 Ty: Type::getInt64Ty(C&: header->getContext()), V: AlignmentValue))));
1633 }
1634 RewriteVal = LoadGEP;
1635 ++aggIdx;
1636 } else
1637 RewriteVal = &*ScalarAI++;
1638
1639 NewValues.push_back(Elt: RewriteVal);
1640 }
1641
1642 moveCodeToFunction(newFunction);
1643
1644 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
1645 Value *RewriteVal = NewValues[i];
1646
1647 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
1648 for (User *use : Users)
1649 if (Instruction *inst = dyn_cast<Instruction>(Val: use))
1650 if (Blocks.count(key: inst->getParent()))
1651 inst->replaceUsesOfWith(From: inputs[i], To: RewriteVal);
1652 }
1653
1654 // Since there may be multiple exits from the original region, make the new
1655 // function return an unsigned, switch on that number. This loop iterates
1656 // over all of the blocks in the extracted region, updating any terminator
1657 // instructions in the to-be-extracted region that branch to blocks that are
1658 // not in the region to be extracted.
1659 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1660
1661 // Iterate over the previously collected targets, and create new blocks inside
1662 // the function to branch to.
1663 for (auto P : enumerate(First&: ExtractedFuncRetVals)) {
1664 BasicBlock *OldTarget = P.value();
1665 size_t SuccNum = P.index();
1666
1667 BasicBlock *NewTarget = BasicBlock::Create(
1668 Context, Name: OldTarget->getName() + ".exitStub", Parent: newFunction);
1669 ExitBlockMap[OldTarget] = NewTarget;
1670
1671 Value *brVal = nullptr;
1672 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
1673 assert(ExtractedFuncRetVals.size() < 0xffff &&
1674 "too many exit blocks for switch");
1675 switch (ExtractedFuncRetVals.size()) {
1676 case 0:
1677 // No value needed.
1678 break;
1679 case 1:
1680 if (FuncRetVal)
1681 brVal = FuncRetVal;
1682 break;
1683 case 2: // Conditional branch, return a bool
1684 brVal = ConstantInt::get(Ty: RetTy, V: !SuccNum);
1685 break;
1686 default:
1687 brVal = ConstantInt::get(Ty: RetTy, V: SuccNum);
1688 break;
1689 }
1690
1691 ReturnInst::Create(C&: Context, retVal: brVal, InsertBefore: NewTarget);
1692 }
1693
1694 for (BasicBlock *Block : Blocks) {
1695 Instruction *TI = Block->getTerminator();
1696 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1697 if (Blocks.count(key: TI->getSuccessor(Idx: i)))
1698 continue;
1699 BasicBlock *OldTarget = TI->getSuccessor(Idx: i);
1700 // add a new basic block which returns the appropriate value
1701 BasicBlock *NewTarget = ExitBlockMap[OldTarget];
1702 assert(NewTarget && "Unknown target block!");
1703
1704 // rewrite the original branch instruction with this new target
1705 TI->setSuccessor(Idx: i, BB: NewTarget);
1706 }
1707 }
1708
1709 // Loop over all of the PHI nodes in the header and exit blocks, and change
1710 // any references to the old incoming edge to be the new incoming edge.
1711 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(Val: I); ++I) {
1712 PHINode *PN = cast<PHINode>(Val&: I);
1713 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1714 if (!Blocks.count(key: PN->getIncomingBlock(i)))
1715 PN->setIncomingBlock(i, BB: newFuncRoot);
1716 }
1717
1718 // Connect newFunction entry block to new header.
1719 UncondBrInst *BranchI = UncondBrInst::Create(Target: header, InsertBefore: newFuncRoot);
1720 applyFirstDebugLoc(oldFunction, Blocks: Blocks.getArrayRef(), BranchI);
1721
1722 // Store the arguments right after the definition of output value.
1723 // This should be proceeded after creating exit stubs to be ensure that invoke
1724 // result restore will be placed in the outlined function.
1725 ScalarAI = newFunction->arg_begin();
1726 unsigned AggIdx = 0;
1727
1728 for (Value *Input : inputs) {
1729 if (StructValues.contains(key: Input))
1730 ++AggIdx;
1731 else
1732 ++ScalarAI;
1733 }
1734
1735 for (Value *Output : outputs) {
1736 // Find proper insertion point.
1737 // In case Output is an invoke, we insert the store at the beginning in the
1738 // 'normal destination' BB. Otherwise we insert the store right after
1739 // Output.
1740 BasicBlock::iterator InsertPt;
1741 if (auto *InvokeI = dyn_cast<InvokeInst>(Val: Output))
1742 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1743 else if (auto *Phi = dyn_cast<PHINode>(Val: Output))
1744 InsertPt = Phi->getParent()->getFirstInsertionPt();
1745 else if (auto *OutI = dyn_cast<Instruction>(Val: Output))
1746 InsertPt = std::next(x: OutI->getIterator());
1747 else {
1748 // Globals don't need to be updated, just advance to the next argument.
1749 if (StructValues.contains(key: Output))
1750 ++AggIdx;
1751 else
1752 ++ScalarAI;
1753 continue;
1754 }
1755
1756 assert((InsertPt->getFunction() == newFunction ||
1757 Blocks.count(InsertPt->getParent())) &&
1758 "InsertPt should be in new function");
1759
1760 if (StructValues.contains(key: Output)) {
1761 assert(AggArg && "Number of aggregate output arguments should match "
1762 "the number of defined values");
1763 Value *Idx[2];
1764 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1765 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1766 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1767 PointeeType: StructArgTy, Ptr: AggArg, IdxList: Idx, NameStr: "gep_" + Output->getName(), InsertBefore: InsertPt);
1768 new StoreInst(Output, GEP, InsertPt);
1769 ++AggIdx;
1770 } else {
1771 assert(ScalarAI != newFunction->arg_end() &&
1772 "Number of scalar output arguments should match "
1773 "the number of defined values");
1774 new StoreInst(Output, &*ScalarAI, InsertPt);
1775 ++ScalarAI;
1776 }
1777 }
1778
1779 if (ExtractedFuncRetVals.empty()) {
1780 // Mark the new function `noreturn` if applicable. Terminators which resume
1781 // exception propagation are treated as returning instructions. This is to
1782 // avoid inserting traps after calls to outlined functions which unwind.
1783 if (none_of(Range&: Blocks, P: [](const BasicBlock *BB) {
1784 const Instruction *Term = BB->getTerminator();
1785 return isa<ReturnInst>(Val: Term) || isa<ResumeInst>(Val: Term);
1786 }))
1787 newFunction->setDoesNotReturn();
1788 }
1789}
1790
1791CallInst *CodeExtractor::emitReplacerCall(
1792 const ValueSet &inputs, const ValueSet &outputs,
1793 const ValueSet &StructValues, Function *newFunction,
1794 StructType *StructArgTy, Function *oldFunction, BasicBlock *ReplIP,
1795 BlockFrequency EntryFreq, ArrayRef<Value *> LifetimesStart,
1796 std::vector<Value *> &Reloads) {
1797 LLVMContext &Context = oldFunction->getContext();
1798 Module *M = oldFunction->getParent();
1799
1800 // This takes place of the original loop
1801 BasicBlock *codeReplacer =
1802 BasicBlock::Create(Context, Name: "codeRepl", Parent: oldFunction, InsertBefore: ReplIP);
1803 if (AllocationBlock)
1804 assert(AllocationBlock->getParent() == oldFunction &&
1805 "AllocationBlock is not in the same function");
1806 BasicBlock *AllocaBlock =
1807 AllocationBlock ? AllocationBlock : &oldFunction->getEntryBlock();
1808
1809 // If the original function has debug info, the terminator of the entry block
1810 // of the extracted function contains the first debug location of the
1811 // extracted function, set in extractCodeRegion.
1812 DebugLoc DL;
1813 if (oldFunction->getSubprogram())
1814 DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc();
1815
1816 // Update the entry count of the function.
1817 if (BFI)
1818 BFI->setBlockFreq(BB: codeReplacer, Freq: EntryFreq);
1819
1820 std::vector<Value *> params;
1821
1822 // Add inputs as params, or to be filled into the struct
1823 for (Value *input : inputs) {
1824 if (StructValues.contains(key: input))
1825 continue;
1826
1827 params.push_back(x: input);
1828 }
1829
1830 // Create allocas for the outputs
1831 std::vector<Value *> ReloadOutputs;
1832 for (Value *output : outputs) {
1833 if (StructValues.contains(key: output))
1834 continue;
1835
1836 Value *OutAlloc =
1837 allocateVar(AllocaIP: AllocaBlock->getFirstInsertionPt(), DL, VarType: output->getType(),
1838 Name: output->getName() + ".loc");
1839 params.push_back(x: OutAlloc);
1840 ReloadOutputs.push_back(x: OutAlloc);
1841 }
1842
1843 Instruction *Struct = nullptr;
1844 if (!StructValues.empty()) {
1845 AddrSpaceCastInst *StructSpaceCast = nullptr;
1846 Struct = allocateVar(AllocaIP: AllocaBlock->getFirstInsertionPt(), DL, VarType: StructArgTy,
1847 Name: "structArg", CastedAlloc: &StructSpaceCast);
1848 if (StructSpaceCast)
1849 params.push_back(x: StructSpaceCast);
1850 else
1851 params.push_back(x: Struct);
1852
1853 unsigned AggIdx = 0;
1854 for (Value *input : inputs) {
1855 if (!StructValues.contains(key: input))
1856 continue;
1857
1858 Value *Idx[2];
1859 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1860 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1861 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1862 PointeeType: StructArgTy, Ptr: Struct, IdxList: Idx, NameStr: "gep_" + input->getName());
1863 GEP->insertInto(ParentBB: codeReplacer, It: codeReplacer->end());
1864 new StoreInst(input, GEP, codeReplacer);
1865
1866 ++AggIdx;
1867 }
1868 }
1869
1870 // Emit the call to the function
1871 CallInst *call = CallInst::Create(
1872 Func: newFunction, Args: params, NameStr: ExtractedFuncRetVals.size() > 1 ? "targetBlock" : "",
1873 InsertBefore: codeReplacer);
1874
1875 // Set swifterror parameter attributes.
1876 unsigned ParamIdx = 0;
1877 unsigned AggIdx = 0;
1878 for (auto input : inputs) {
1879 if (StructValues.contains(key: input)) {
1880 ++AggIdx;
1881 } else {
1882 if (input->isSwiftError())
1883 call->addParamAttr(ArgNo: ParamIdx, Kind: Attribute::SwiftError);
1884 ++ParamIdx;
1885 }
1886 }
1887
1888 // Add debug location to the new call, if the original function has debug
1889 // info.
1890 if (DL)
1891 call->setDebugLoc(DL);
1892
1893 // Reload the outputs passed in by reference, use the struct if output is in
1894 // the aggregate or reload from the scalar argument.
1895 for (unsigned i = 0, e = outputs.size(), scalarIdx = 0; i != e; ++i) {
1896 Value *Output = nullptr;
1897 if (StructValues.contains(key: outputs[i])) {
1898 Value *Idx[2];
1899 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1900 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1901 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1902 PointeeType: StructArgTy, Ptr: Struct, IdxList: Idx, NameStr: "gep_reload_" + outputs[i]->getName());
1903 GEP->insertInto(ParentBB: codeReplacer, It: codeReplacer->end());
1904 Output = GEP;
1905 ++AggIdx;
1906 } else {
1907 Output = ReloadOutputs[scalarIdx];
1908 ++scalarIdx;
1909 }
1910 LoadInst *load =
1911 new LoadInst(outputs[i]->getType(), Output,
1912 outputs[i]->getName() + ".reload", codeReplacer);
1913 Reloads.push_back(x: load);
1914 }
1915
1916 // Now we can emit a switch statement using the call as a value.
1917 SwitchInst *TheSwitch =
1918 SwitchInst::Create(Value: Constant::getNullValue(Ty: Type::getInt16Ty(C&: Context)),
1919 Default: codeReplacer, NumCases: 0, InsertBefore: codeReplacer);
1920 for (auto P : enumerate(First&: ExtractedFuncRetVals)) {
1921 BasicBlock *OldTarget = P.value();
1922 size_t SuccNum = P.index();
1923
1924 TheSwitch->addCase(OnVal: ConstantInt::get(Ty: Type::getInt16Ty(C&: Context), V: SuccNum),
1925 Dest: OldTarget);
1926 }
1927
1928 // Now that we've done the deed, simplify the switch instruction.
1929 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
1930 switch (ExtractedFuncRetVals.size()) {
1931 case 0:
1932 // There are no successors (the block containing the switch itself), which
1933 // means that previously this was the last part of the function, and hence
1934 // this should be rewritten as a `ret` or `unreachable`.
1935 if (newFunction->doesNotReturn()) {
1936 // If fn is no return, end with an unreachable terminator.
1937 (void)new UnreachableInst(Context, TheSwitch->getIterator());
1938 } else if (OldFnRetTy->isVoidTy()) {
1939 // We have no return value.
1940 ReturnInst::Create(C&: Context, retVal: nullptr,
1941 InsertBefore: TheSwitch->getIterator()); // Return void
1942 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
1943 // return what we have
1944 ReturnInst::Create(C&: Context, retVal: TheSwitch->getCondition(),
1945 InsertBefore: TheSwitch->getIterator());
1946 } else {
1947 // Otherwise we must have code extracted an unwind or something, just
1948 // return whatever we want.
1949 ReturnInst::Create(C&: Context, retVal: Constant::getNullValue(Ty: OldFnRetTy),
1950 InsertBefore: TheSwitch->getIterator());
1951 }
1952
1953 TheSwitch->eraseFromParent();
1954 break;
1955 case 1:
1956 // Only a single destination, change the switch into an unconditional
1957 // branch.
1958 UncondBrInst::Create(Target: TheSwitch->getSuccessor(idx: 1), InsertBefore: TheSwitch->getIterator());
1959 TheSwitch->eraseFromParent();
1960 break;
1961 case 2:
1962 // Only two destinations, convert to a condition branch.
1963 // Remark: This also swaps the target branches:
1964 // 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1)
1965 CondBrInst::Create(Cond: call, IfTrue: TheSwitch->getSuccessor(idx: 1),
1966 IfFalse: TheSwitch->getSuccessor(idx: 2), InsertBefore: TheSwitch->getIterator());
1967 TheSwitch->eraseFromParent();
1968 break;
1969 default:
1970 // Otherwise, make the default destination of the switch instruction be one
1971 // of the other successors.
1972 TheSwitch->setCondition(call);
1973 TheSwitch->setDefaultDest(
1974 TheSwitch->getSuccessor(idx: ExtractedFuncRetVals.size()));
1975 // Remove redundant case
1976 TheSwitch->removeCase(
1977 I: SwitchInst::CaseIt(TheSwitch, ExtractedFuncRetVals.size() - 1));
1978 break;
1979 }
1980
1981 // Insert lifetime markers around the reloads of any output values. The
1982 // allocas output values are stored in are only in-use in the codeRepl block.
1983 insertLifetimeMarkersSurroundingCall(M, LifetimesStart: ReloadOutputs, LifetimesEnd: ReloadOutputs, TheCall: call);
1984
1985 // Replicate the effects of any lifetime start/end markers which referenced
1986 // input objects in the extraction region by placing markers around the call.
1987 insertLifetimeMarkersSurroundingCall(M: oldFunction->getParent(), LifetimesStart,
1988 LifetimesEnd: {}, TheCall: call);
1989
1990 // Deallocate intermediate variables if they need explicit deallocation.
1991 auto deallocVars = [&](BasicBlock::iterator DeallocIP) {
1992 int Index = 0;
1993 for (Value *Output : outputs) {
1994 if (!StructValues.contains(key: Output))
1995 deallocateVar(DeallocIP, DL, ReloadOutputs[Index++], Output->getType());
1996 }
1997
1998 if (Struct)
1999 deallocateVar(DeallocIP, DL, Struct, StructArgTy);
2000 };
2001
2002 if (DeallocationBlocks.empty()) {
2003 deallocVars(codeReplacer->end());
2004 } else {
2005 for (BasicBlock *DeallocationBlock : DeallocationBlocks)
2006 deallocVars(DeallocationBlock->getFirstInsertionPt());
2007 }
2008
2009 return call;
2010}
2011
2012void CodeExtractor::insertReplacerCall(
2013 Function *oldFunction, BasicBlock *header, CallInst *ReplacerCall,
2014 const ValueSet &outputs, ArrayRef<Value *> Reloads,
2015 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights) {
2016
2017 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
2018 // within the new function. This must be done before we lose track of which
2019 // blocks were originally in the code region.
2020 BasicBlock *codeReplacer = ReplacerCall->getParent();
2021 std::vector<User *> Users(header->user_begin(), header->user_end());
2022 for (auto &U : Users)
2023 // The BasicBlock which contains the branch is not in the region
2024 // modify the branch target to a new block
2025 if (Instruction *I = dyn_cast<Instruction>(Val: U))
2026 if (I->isTerminator() && I->getFunction() == oldFunction &&
2027 !Blocks.count(key: I->getParent()))
2028 I->replaceUsesOfWith(From: header, To: codeReplacer);
2029
2030 // When moving the code region it is sufficient to replace all uses to the
2031 // extracted function values. Since the original definition's block
2032 // dominated its use, it will also be dominated by codeReplacer's switch
2033 // which joined multiple exit blocks.
2034 for (BasicBlock *ExitBB : ExtractedFuncRetVals)
2035 for (PHINode &PN : ExitBB->phis()) {
2036 Value *IncomingCodeReplacerVal = nullptr;
2037 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2038 // Ignore incoming values from outside of the extracted region.
2039 if (!Blocks.count(key: PN.getIncomingBlock(i)))
2040 continue;
2041
2042 // Ensure that there is only one incoming value from codeReplacer.
2043 if (!IncomingCodeReplacerVal) {
2044 PN.setIncomingBlock(i, BB: codeReplacer);
2045 IncomingCodeReplacerVal = PN.getIncomingValue(i);
2046 } else
2047 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
2048 "PHI has two incompatbile incoming values from codeRepl");
2049 }
2050 }
2051
2052 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
2053 Value *load = Reloads[i];
2054 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
2055 for (User *U : Users) {
2056 Instruction *inst = cast<Instruction>(Val: U);
2057 if (inst->getParent()->getParent() == oldFunction)
2058 inst->replaceUsesOfWith(From: outputs[i], To: load);
2059 }
2060 }
2061
2062 if (FuncRetVal)
2063 FuncRetVal->replaceUsesWithIf(New: ReplacerCall, ShouldReplace: [&](Use &U) {
2064 return cast<Instruction>(Val: U.getUser())->getFunction() == oldFunction;
2065 });
2066
2067 // Update the branch weights for the exit block.
2068 if (BFI && ExtractedFuncRetVals.size() > 1)
2069 calculateNewCallTerminatorWeights(CodeReplacer: codeReplacer, ExitWeights, BPI);
2070}
2071
2072bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
2073 const Function &NewFunc,
2074 AssumptionCache *AC) {
2075 for (auto AssumeVH : AC->assumptions()) {
2076 auto *I = dyn_cast_or_null<CallInst>(Val&: AssumeVH);
2077 if (!I)
2078 continue;
2079
2080 // There shouldn't be any llvm.assume intrinsics in the new function.
2081 if (I->getFunction() != &OldFunc)
2082 return true;
2083
2084 // There shouldn't be any stale affected values in the assumption cache
2085 // that were previously in the old function, but that have now been moved
2086 // to the new function.
2087 for (auto AffectedValVH : AC->assumptionsFor(V: I->getOperand(i_nocapture: 0))) {
2088 auto *AffectedCI = dyn_cast_or_null<CallInst>(Val&: AffectedValVH);
2089 if (!AffectedCI)
2090 continue;
2091 if (AffectedCI->getFunction() != &OldFunc)
2092 return true;
2093 auto *AssumedInst = dyn_cast<Instruction>(Val: AffectedCI->getOperand(i_nocapture: 0));
2094 if (AssumedInst && AssumedInst->getFunction() != &OldFunc)
2095 return true;
2096 }
2097 }
2098 return false;
2099}
2100
2101void CodeExtractor::excludeArgFromAggregate(Value *Arg) {
2102 ExcludeArgsFromAggregate.insert(X: Arg);
2103}
2104