10b57cec5SDimitry Andric //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the interface to tear out a code region, such as an
100b57cec5SDimitry Andric // individual loop or a parallel section, into a new function, replacing it with
110b57cec5SDimitry Andric // a call to the new function.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric
150b57cec5SDimitry Andric #include "llvm/Transforms/Utils/CodeExtractor.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
280b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
290b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
300b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
310b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
320b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
345ffd83dbSDimitry Andric #include "llvm/IR/DIBuilder.h"
350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
365ffd83dbSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
370b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
390b57cec5SDimitry Andric #include "llvm/IR/Function.h"
400b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
415ffd83dbSDimitry Andric #include "llvm/IR/InstIterator.h"
420b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
430b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
450b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
460b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
470b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
480b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
490b57cec5SDimitry Andric #include "llvm/IR/Module.h"
500b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
510b57cec5SDimitry Andric #include "llvm/IR/Type.h"
520b57cec5SDimitry Andric #include "llvm/IR/User.h"
530b57cec5SDimitry Andric #include "llvm/IR/Value.h"
540b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
550b57cec5SDimitry Andric #include "llvm/Pass.h"
560b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h"
570b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
580b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
590b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
600b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
620b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
630b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
640b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
650b57cec5SDimitry Andric #include <cassert>
660b57cec5SDimitry Andric #include <cstdint>
670b57cec5SDimitry Andric #include <iterator>
680b57cec5SDimitry Andric #include <map>
690b57cec5SDimitry Andric #include <set>
700b57cec5SDimitry Andric #include <utility>
710b57cec5SDimitry Andric #include <vector>
720b57cec5SDimitry Andric
730b57cec5SDimitry Andric using namespace llvm;
740b57cec5SDimitry Andric using namespace llvm::PatternMatch;
750b57cec5SDimitry Andric using ProfileCount = Function::ProfileCount;
760b57cec5SDimitry Andric
770b57cec5SDimitry Andric #define DEBUG_TYPE "code-extractor"
780b57cec5SDimitry Andric
790b57cec5SDimitry Andric // Provide a command-line option to aggregate function arguments into a struct
800b57cec5SDimitry Andric // for functions produced by the code extractor. This is useful when converting
810b57cec5SDimitry Andric // extracted functions to pthread-based code, as only one argument (void*) can
820b57cec5SDimitry Andric // be passed in to pthread_create().
830b57cec5SDimitry Andric static cl::opt<bool>
840b57cec5SDimitry Andric AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
850b57cec5SDimitry Andric cl::desc("Aggregate arguments to code-extracted functions"));
860b57cec5SDimitry Andric
870b57cec5SDimitry Andric /// Test whether a block is valid for extraction.
isBlockValidForExtraction(const BasicBlock & BB,const SetVector<BasicBlock * > & Result,bool AllowVarArgs,bool AllowAlloca)880b57cec5SDimitry Andric static bool isBlockValidForExtraction(const BasicBlock &BB,
890b57cec5SDimitry Andric const SetVector<BasicBlock *> &Result,
900b57cec5SDimitry Andric bool AllowVarArgs, bool AllowAlloca) {
910b57cec5SDimitry Andric // taking the address of a basic block moved to another function is illegal
920b57cec5SDimitry Andric if (BB.hasAddressTaken())
930b57cec5SDimitry Andric return false;
940b57cec5SDimitry Andric
950b57cec5SDimitry Andric // don't hoist code that uses another basicblock address, as it's likely to
960b57cec5SDimitry Andric // lead to unexpected behavior, like cross-function jumps
970b57cec5SDimitry Andric SmallPtrSet<User const *, 16> Visited;
980b57cec5SDimitry Andric SmallVector<User const *, 16> ToVisit;
990b57cec5SDimitry Andric
1000b57cec5SDimitry Andric for (Instruction const &Inst : BB)
1010b57cec5SDimitry Andric ToVisit.push_back(&Inst);
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric while (!ToVisit.empty()) {
1040b57cec5SDimitry Andric User const *Curr = ToVisit.pop_back_val();
1050b57cec5SDimitry Andric if (!Visited.insert(Curr).second)
1060b57cec5SDimitry Andric continue;
1070b57cec5SDimitry Andric if (isa<BlockAddress const>(Curr))
1080b57cec5SDimitry Andric return false; // even a reference to self is likely to be not compatible
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
1110b57cec5SDimitry Andric continue;
1120b57cec5SDimitry Andric
1130b57cec5SDimitry Andric for (auto const &U : Curr->operands()) {
1140b57cec5SDimitry Andric if (auto *UU = dyn_cast<User>(U))
1150b57cec5SDimitry Andric ToVisit.push_back(UU);
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric // If explicitly requested, allow vastart and alloca. For invoke instructions
1200b57cec5SDimitry Andric // verify that extraction is valid.
1210b57cec5SDimitry Andric for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
1220b57cec5SDimitry Andric if (isa<AllocaInst>(I)) {
1230b57cec5SDimitry Andric if (!AllowAlloca)
1240b57cec5SDimitry Andric return false;
1250b57cec5SDimitry Andric continue;
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric
1280b57cec5SDimitry Andric if (const auto *II = dyn_cast<InvokeInst>(I)) {
1290b57cec5SDimitry Andric // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
1300b57cec5SDimitry Andric // must be a part of the subgraph which is being extracted.
1310b57cec5SDimitry Andric if (auto *UBB = II->getUnwindDest())
1320b57cec5SDimitry Andric if (!Result.count(UBB))
1330b57cec5SDimitry Andric return false;
1340b57cec5SDimitry Andric continue;
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric
1370b57cec5SDimitry Andric // All catch handlers of a catchswitch instruction as well as the unwind
1380b57cec5SDimitry Andric // destination must be in the subgraph.
1390b57cec5SDimitry Andric if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
1400b57cec5SDimitry Andric if (auto *UBB = CSI->getUnwindDest())
1410b57cec5SDimitry Andric if (!Result.count(UBB))
1420b57cec5SDimitry Andric return false;
1430b57cec5SDimitry Andric for (auto *HBB : CSI->handlers())
1440b57cec5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(HBB)))
1450b57cec5SDimitry Andric return false;
1460b57cec5SDimitry Andric continue;
1470b57cec5SDimitry Andric }
1480b57cec5SDimitry Andric
1490b57cec5SDimitry Andric // Make sure that entire catch handler is within subgraph. It is sufficient
1500b57cec5SDimitry Andric // to check that catch return's block is in the list.
1510b57cec5SDimitry Andric if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
1520b57cec5SDimitry Andric for (const auto *U : CPI->users())
1530b57cec5SDimitry Andric if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
1540b57cec5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
1550b57cec5SDimitry Andric return false;
1560b57cec5SDimitry Andric continue;
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric
1590b57cec5SDimitry Andric // And do similar checks for cleanup handler - the entire handler must be
1600b57cec5SDimitry Andric // in subgraph which is going to be extracted. For cleanup return should
1610b57cec5SDimitry Andric // additionally check that the unwind destination is also in the subgraph.
1620b57cec5SDimitry Andric if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
1630b57cec5SDimitry Andric for (const auto *U : CPI->users())
1640b57cec5SDimitry Andric if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
1650b57cec5SDimitry Andric if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
1660b57cec5SDimitry Andric return false;
1670b57cec5SDimitry Andric continue;
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
1700b57cec5SDimitry Andric if (auto *UBB = CRI->getUnwindDest())
1710b57cec5SDimitry Andric if (!Result.count(UBB))
1720b57cec5SDimitry Andric return false;
1730b57cec5SDimitry Andric continue;
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric
1760b57cec5SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I)) {
1770b57cec5SDimitry Andric if (const Function *F = CI->getCalledFunction()) {
1780b57cec5SDimitry Andric auto IID = F->getIntrinsicID();
1790b57cec5SDimitry Andric if (IID == Intrinsic::vastart) {
1800b57cec5SDimitry Andric if (AllowVarArgs)
1810b57cec5SDimitry Andric continue;
1820b57cec5SDimitry Andric else
1830b57cec5SDimitry Andric return false;
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric
1860b57cec5SDimitry Andric // Currently, we miscompile outlined copies of eh_typid_for. There are
1870b57cec5SDimitry Andric // proposals for fixing this in llvm.org/PR39545.
1880b57cec5SDimitry Andric if (IID == Intrinsic::eh_typeid_for)
1890b57cec5SDimitry Andric return false;
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric
1940b57cec5SDimitry Andric return true;
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric /// Build a set of blocks to extract if the input blocks are viable.
1980b57cec5SDimitry Andric static SetVector<BasicBlock *>
buildExtractionBlockSet(ArrayRef<BasicBlock * > BBs,DominatorTree * DT,bool AllowVarArgs,bool AllowAlloca)1990b57cec5SDimitry Andric buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
2000b57cec5SDimitry Andric bool AllowVarArgs, bool AllowAlloca) {
2010b57cec5SDimitry Andric assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
2020b57cec5SDimitry Andric SetVector<BasicBlock *> Result;
2030b57cec5SDimitry Andric
2040b57cec5SDimitry Andric // Loop over the blocks, adding them to our set-vector, and aborting with an
2050b57cec5SDimitry Andric // empty set if we encounter invalid blocks.
2060b57cec5SDimitry Andric for (BasicBlock *BB : BBs) {
2070b57cec5SDimitry Andric // If this block is dead, don't process it.
2080b57cec5SDimitry Andric if (DT && !DT->isReachableFromEntry(BB))
2090b57cec5SDimitry Andric continue;
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric if (!Result.insert(BB))
2120b57cec5SDimitry Andric llvm_unreachable("Repeated basic blocks in extraction input");
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric
2150b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()
2160b57cec5SDimitry Andric << '\n');
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric for (auto *BB : Result) {
2190b57cec5SDimitry Andric if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
2200b57cec5SDimitry Andric return {};
2210b57cec5SDimitry Andric
2220b57cec5SDimitry Andric // Make sure that the first block is not a landing pad.
2230b57cec5SDimitry Andric if (BB == Result.front()) {
2240b57cec5SDimitry Andric if (BB->isEHPad()) {
2250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
2260b57cec5SDimitry Andric return {};
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric continue;
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric // All blocks other than the first must not have predecessors outside of
2320b57cec5SDimitry Andric // the subgraph which is being extracted.
2330b57cec5SDimitry Andric for (auto *PBB : predecessors(BB))
2340b57cec5SDimitry Andric if (!Result.count(PBB)) {
2350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "
2360b57cec5SDimitry Andric "outside the region except for the first block!\n"
2370b57cec5SDimitry Andric << "Problematic source BB: " << BB->getName() << "\n"
2380b57cec5SDimitry Andric << "Problematic destination BB: " << PBB->getName()
2390b57cec5SDimitry Andric << "\n");
2400b57cec5SDimitry Andric return {};
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric
2440b57cec5SDimitry Andric return Result;
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric
CodeExtractor(ArrayRef<BasicBlock * > BBs,DominatorTree * DT,bool AggregateArgs,BlockFrequencyInfo * BFI,BranchProbabilityInfo * BPI,AssumptionCache * AC,bool AllowVarArgs,bool AllowAlloca,std::string Suffix)2470b57cec5SDimitry Andric CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
2480b57cec5SDimitry Andric bool AggregateArgs, BlockFrequencyInfo *BFI,
2490b57cec5SDimitry Andric BranchProbabilityInfo *BPI, AssumptionCache *AC,
2500b57cec5SDimitry Andric bool AllowVarArgs, bool AllowAlloca,
2510b57cec5SDimitry Andric std::string Suffix)
2520b57cec5SDimitry Andric : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
2530b57cec5SDimitry Andric BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs),
2540b57cec5SDimitry Andric Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
2550b57cec5SDimitry Andric Suffix(Suffix) {}
2560b57cec5SDimitry Andric
CodeExtractor(DominatorTree & DT,Loop & L,bool AggregateArgs,BlockFrequencyInfo * BFI,BranchProbabilityInfo * BPI,AssumptionCache * AC,std::string Suffix)2570b57cec5SDimitry Andric CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
2580b57cec5SDimitry Andric BlockFrequencyInfo *BFI,
2590b57cec5SDimitry Andric BranchProbabilityInfo *BPI, AssumptionCache *AC,
2600b57cec5SDimitry Andric std::string Suffix)
2610b57cec5SDimitry Andric : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
2620b57cec5SDimitry Andric BPI(BPI), AC(AC), AllowVarArgs(false),
2630b57cec5SDimitry Andric Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
2640b57cec5SDimitry Andric /* AllowVarArgs */ false,
2650b57cec5SDimitry Andric /* AllowAlloca */ false)),
2660b57cec5SDimitry Andric Suffix(Suffix) {}
2670b57cec5SDimitry Andric
2680b57cec5SDimitry Andric /// definedInRegion - Return true if the specified value is defined in the
2690b57cec5SDimitry Andric /// extracted region.
definedInRegion(const SetVector<BasicBlock * > & Blocks,Value * V)2700b57cec5SDimitry Andric static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
2710b57cec5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V))
2720b57cec5SDimitry Andric if (Blocks.count(I->getParent()))
2730b57cec5SDimitry Andric return true;
2740b57cec5SDimitry Andric return false;
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric
2770b57cec5SDimitry Andric /// definedInCaller - Return true if the specified value is defined in the
2780b57cec5SDimitry Andric /// function being code extracted, but not in the region being extracted.
2790b57cec5SDimitry Andric /// These values must be passed in as live-ins to the function.
definedInCaller(const SetVector<BasicBlock * > & Blocks,Value * V)2800b57cec5SDimitry Andric static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
2810b57cec5SDimitry Andric if (isa<Argument>(V)) return true;
2820b57cec5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V))
2830b57cec5SDimitry Andric if (!Blocks.count(I->getParent()))
2840b57cec5SDimitry Andric return true;
2850b57cec5SDimitry Andric return false;
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric
getCommonExitBlock(const SetVector<BasicBlock * > & Blocks)2880b57cec5SDimitry Andric static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
2890b57cec5SDimitry Andric BasicBlock *CommonExitBlock = nullptr;
2900b57cec5SDimitry Andric auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
2910b57cec5SDimitry Andric for (auto *Succ : successors(Block)) {
2920b57cec5SDimitry Andric // Internal edges, ok.
2930b57cec5SDimitry Andric if (Blocks.count(Succ))
2940b57cec5SDimitry Andric continue;
2950b57cec5SDimitry Andric if (!CommonExitBlock) {
2960b57cec5SDimitry Andric CommonExitBlock = Succ;
2970b57cec5SDimitry Andric continue;
2980b57cec5SDimitry Andric }
2998bcb0991SDimitry Andric if (CommonExitBlock != Succ)
3000b57cec5SDimitry Andric return true;
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric return false;
3030b57cec5SDimitry Andric };
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric if (any_of(Blocks, hasNonCommonExitSucc))
3060b57cec5SDimitry Andric return nullptr;
3070b57cec5SDimitry Andric
3080b57cec5SDimitry Andric return CommonExitBlock;
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric
CodeExtractorAnalysisCache(Function & F)3118bcb0991SDimitry Andric CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) {
3128bcb0991SDimitry Andric for (BasicBlock &BB : F) {
3138bcb0991SDimitry Andric for (Instruction &II : BB.instructionsWithoutDebug())
3148bcb0991SDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(&II))
3158bcb0991SDimitry Andric Allocas.push_back(AI);
3160b57cec5SDimitry Andric
3178bcb0991SDimitry Andric findSideEffectInfoForBlock(BB);
3188bcb0991SDimitry Andric }
3198bcb0991SDimitry Andric }
3208bcb0991SDimitry Andric
findSideEffectInfoForBlock(BasicBlock & BB)3218bcb0991SDimitry Andric void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {
3228bcb0991SDimitry Andric for (Instruction &II : BB.instructionsWithoutDebug()) {
3230b57cec5SDimitry Andric unsigned Opcode = II.getOpcode();
3240b57cec5SDimitry Andric Value *MemAddr = nullptr;
3250b57cec5SDimitry Andric switch (Opcode) {
3260b57cec5SDimitry Andric case Instruction::Store:
3270b57cec5SDimitry Andric case Instruction::Load: {
3280b57cec5SDimitry Andric if (Opcode == Instruction::Store) {
3290b57cec5SDimitry Andric StoreInst *SI = cast<StoreInst>(&II);
3300b57cec5SDimitry Andric MemAddr = SI->getPointerOperand();
3310b57cec5SDimitry Andric } else {
3320b57cec5SDimitry Andric LoadInst *LI = cast<LoadInst>(&II);
3330b57cec5SDimitry Andric MemAddr = LI->getPointerOperand();
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric // Global variable can not be aliased with locals.
336*5f7ddb14SDimitry Andric if (isa<Constant>(MemAddr))
3370b57cec5SDimitry Andric break;
3380b57cec5SDimitry Andric Value *Base = MemAddr->stripInBoundsConstantOffsets();
3398bcb0991SDimitry Andric if (!isa<AllocaInst>(Base)) {
3408bcb0991SDimitry Andric SideEffectingBlocks.insert(&BB);
3418bcb0991SDimitry Andric return;
3428bcb0991SDimitry Andric }
3438bcb0991SDimitry Andric BaseMemAddrs[&BB].insert(Base);
3440b57cec5SDimitry Andric break;
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric default: {
3470b57cec5SDimitry Andric IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
3480b57cec5SDimitry Andric if (IntrInst) {
3490b57cec5SDimitry Andric if (IntrInst->isLifetimeStartOrEnd())
3500b57cec5SDimitry Andric break;
3518bcb0991SDimitry Andric SideEffectingBlocks.insert(&BB);
3528bcb0991SDimitry Andric return;
3530b57cec5SDimitry Andric }
3540b57cec5SDimitry Andric // Treat all the other cases conservatively if it has side effects.
3558bcb0991SDimitry Andric if (II.mayHaveSideEffects()) {
3568bcb0991SDimitry Andric SideEffectingBlocks.insert(&BB);
3578bcb0991SDimitry Andric return;
3588bcb0991SDimitry Andric }
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric }
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric
doesBlockContainClobberOfAddr(BasicBlock & BB,AllocaInst * Addr) const3648bcb0991SDimitry Andric bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr(
3658bcb0991SDimitry Andric BasicBlock &BB, AllocaInst *Addr) const {
3668bcb0991SDimitry Andric if (SideEffectingBlocks.count(&BB))
3678bcb0991SDimitry Andric return true;
3688bcb0991SDimitry Andric auto It = BaseMemAddrs.find(&BB);
3698bcb0991SDimitry Andric if (It != BaseMemAddrs.end())
3708bcb0991SDimitry Andric return It->second.count(Addr);
3718bcb0991SDimitry Andric return false;
3728bcb0991SDimitry Andric }
3738bcb0991SDimitry Andric
isLegalToShrinkwrapLifetimeMarkers(const CodeExtractorAnalysisCache & CEAC,Instruction * Addr) const3748bcb0991SDimitry Andric bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
3758bcb0991SDimitry Andric const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {
3768bcb0991SDimitry Andric AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
3778bcb0991SDimitry Andric Function *Func = (*Blocks.begin())->getParent();
3788bcb0991SDimitry Andric for (BasicBlock &BB : *Func) {
3798bcb0991SDimitry Andric if (Blocks.count(&BB))
3808bcb0991SDimitry Andric continue;
3818bcb0991SDimitry Andric if (CEAC.doesBlockContainClobberOfAddr(BB, AI))
3828bcb0991SDimitry Andric return false;
3838bcb0991SDimitry Andric }
3840b57cec5SDimitry Andric return true;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric
3870b57cec5SDimitry Andric BasicBlock *
findOrCreateBlockForHoisting(BasicBlock * CommonExitBlock)3880b57cec5SDimitry Andric CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
3890b57cec5SDimitry Andric BasicBlock *SinglePredFromOutlineRegion = nullptr;
3900b57cec5SDimitry Andric assert(!Blocks.count(CommonExitBlock) &&
3910b57cec5SDimitry Andric "Expect a block outside the region!");
3920b57cec5SDimitry Andric for (auto *Pred : predecessors(CommonExitBlock)) {
3930b57cec5SDimitry Andric if (!Blocks.count(Pred))
3940b57cec5SDimitry Andric continue;
3950b57cec5SDimitry Andric if (!SinglePredFromOutlineRegion) {
3960b57cec5SDimitry Andric SinglePredFromOutlineRegion = Pred;
3970b57cec5SDimitry Andric } else if (SinglePredFromOutlineRegion != Pred) {
3980b57cec5SDimitry Andric SinglePredFromOutlineRegion = nullptr;
3990b57cec5SDimitry Andric break;
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric if (SinglePredFromOutlineRegion)
4040b57cec5SDimitry Andric return SinglePredFromOutlineRegion;
4050b57cec5SDimitry Andric
4060b57cec5SDimitry Andric #ifndef NDEBUG
4070b57cec5SDimitry Andric auto getFirstPHI = [](BasicBlock *BB) {
4080b57cec5SDimitry Andric BasicBlock::iterator I = BB->begin();
4090b57cec5SDimitry Andric PHINode *FirstPhi = nullptr;
4100b57cec5SDimitry Andric while (I != BB->end()) {
4110b57cec5SDimitry Andric PHINode *Phi = dyn_cast<PHINode>(I);
4120b57cec5SDimitry Andric if (!Phi)
4130b57cec5SDimitry Andric break;
4140b57cec5SDimitry Andric if (!FirstPhi) {
4150b57cec5SDimitry Andric FirstPhi = Phi;
4160b57cec5SDimitry Andric break;
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric return FirstPhi;
4200b57cec5SDimitry Andric };
4210b57cec5SDimitry Andric // If there are any phi nodes, the single pred either exists or has already
4220b57cec5SDimitry Andric // be created before code extraction.
4230b57cec5SDimitry Andric assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
4240b57cec5SDimitry Andric #endif
4250b57cec5SDimitry Andric
4260b57cec5SDimitry Andric BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
4270b57cec5SDimitry Andric CommonExitBlock->getFirstNonPHI()->getIterator());
4280b57cec5SDimitry Andric
429*5f7ddb14SDimitry Andric for (BasicBlock *Pred :
430*5f7ddb14SDimitry Andric llvm::make_early_inc_range(predecessors(CommonExitBlock))) {
4310b57cec5SDimitry Andric if (Blocks.count(Pred))
4320b57cec5SDimitry Andric continue;
4330b57cec5SDimitry Andric Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric // Now add the old exit block to the outline region.
4360b57cec5SDimitry Andric Blocks.insert(CommonExitBlock);
4370b57cec5SDimitry Andric return CommonExitBlock;
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric
4400b57cec5SDimitry Andric // Find the pair of life time markers for address 'Addr' that are either
4410b57cec5SDimitry Andric // defined inside the outline region or can legally be shrinkwrapped into the
4420b57cec5SDimitry Andric // outline region. If there are not other untracked uses of the address, return
4430b57cec5SDimitry Andric // the pair of markers if found; otherwise return a pair of nullptr.
4440b57cec5SDimitry Andric CodeExtractor::LifetimeMarkerInfo
getLifetimeMarkers(const CodeExtractorAnalysisCache & CEAC,Instruction * Addr,BasicBlock * ExitBlock) const4458bcb0991SDimitry Andric CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
4468bcb0991SDimitry Andric Instruction *Addr,
4470b57cec5SDimitry Andric BasicBlock *ExitBlock) const {
4480b57cec5SDimitry Andric LifetimeMarkerInfo Info;
4490b57cec5SDimitry Andric
4500b57cec5SDimitry Andric for (User *U : Addr->users()) {
4510b57cec5SDimitry Andric IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
4520b57cec5SDimitry Andric if (IntrInst) {
4535ffd83dbSDimitry Andric // We don't model addresses with multiple start/end markers, but the
4545ffd83dbSDimitry Andric // markers do not need to be in the region.
4550b57cec5SDimitry Andric if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
4560b57cec5SDimitry Andric if (Info.LifeStart)
4570b57cec5SDimitry Andric return {};
4580b57cec5SDimitry Andric Info.LifeStart = IntrInst;
4595ffd83dbSDimitry Andric continue;
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
4620b57cec5SDimitry Andric if (Info.LifeEnd)
4630b57cec5SDimitry Andric return {};
4640b57cec5SDimitry Andric Info.LifeEnd = IntrInst;
4655ffd83dbSDimitry Andric continue;
4660b57cec5SDimitry Andric }
4675ffd83dbSDimitry Andric // At this point, permit debug uses outside of the region.
4685ffd83dbSDimitry Andric // This is fixed in a later call to fixupDebugInfoPostExtraction().
4695ffd83dbSDimitry Andric if (isa<DbgInfoIntrinsic>(IntrInst))
4700b57cec5SDimitry Andric continue;
4710b57cec5SDimitry Andric }
4720b57cec5SDimitry Andric // Find untracked uses of the address, bail.
4730b57cec5SDimitry Andric if (!definedInRegion(Blocks, U))
4740b57cec5SDimitry Andric return {};
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric
4770b57cec5SDimitry Andric if (!Info.LifeStart || !Info.LifeEnd)
4780b57cec5SDimitry Andric return {};
4790b57cec5SDimitry Andric
4800b57cec5SDimitry Andric Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart);
4810b57cec5SDimitry Andric Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd);
4820b57cec5SDimitry Andric // Do legality check.
4830b57cec5SDimitry Andric if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
4848bcb0991SDimitry Andric !isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr))
4850b57cec5SDimitry Andric return {};
4860b57cec5SDimitry Andric
4870b57cec5SDimitry Andric // Check to see if we have a place to do hoisting, if not, bail.
4880b57cec5SDimitry Andric if (Info.HoistLifeEnd && !ExitBlock)
4890b57cec5SDimitry Andric return {};
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric return Info;
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric
findAllocas(const CodeExtractorAnalysisCache & CEAC,ValueSet & SinkCands,ValueSet & HoistCands,BasicBlock * & ExitBlock) const4948bcb0991SDimitry Andric void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC,
4958bcb0991SDimitry Andric ValueSet &SinkCands, ValueSet &HoistCands,
4960b57cec5SDimitry Andric BasicBlock *&ExitBlock) const {
4970b57cec5SDimitry Andric Function *Func = (*Blocks.begin())->getParent();
4980b57cec5SDimitry Andric ExitBlock = getCommonExitBlock(Blocks);
4990b57cec5SDimitry Andric
5000b57cec5SDimitry Andric auto moveOrIgnoreLifetimeMarkers =
5010b57cec5SDimitry Andric [&](const LifetimeMarkerInfo &LMI) -> bool {
5020b57cec5SDimitry Andric if (!LMI.LifeStart)
5030b57cec5SDimitry Andric return false;
5040b57cec5SDimitry Andric if (LMI.SinkLifeStart) {
5050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart
5060b57cec5SDimitry Andric << "\n");
5070b57cec5SDimitry Andric SinkCands.insert(LMI.LifeStart);
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric if (LMI.HoistLifeEnd) {
5100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");
5110b57cec5SDimitry Andric HoistCands.insert(LMI.LifeEnd);
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric return true;
5140b57cec5SDimitry Andric };
5150b57cec5SDimitry Andric
5168bcb0991SDimitry Andric // Look up allocas in the original function in CodeExtractorAnalysisCache, as
5178bcb0991SDimitry Andric // this is much faster than walking all the instructions.
5188bcb0991SDimitry Andric for (AllocaInst *AI : CEAC.getAllocas()) {
5198bcb0991SDimitry Andric BasicBlock *BB = AI->getParent();
5208bcb0991SDimitry Andric if (Blocks.count(BB))
5210b57cec5SDimitry Andric continue;
5220b57cec5SDimitry Andric
5238bcb0991SDimitry Andric // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,
5248bcb0991SDimitry Andric // check whether it is actually still in the original function.
5258bcb0991SDimitry Andric Function *AIFunc = BB->getParent();
5268bcb0991SDimitry Andric if (AIFunc != Func)
5278bcb0991SDimitry Andric continue;
5288bcb0991SDimitry Andric
5298bcb0991SDimitry Andric LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock);
5300b57cec5SDimitry Andric bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
5310b57cec5SDimitry Andric if (Moved) {
5320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");
5330b57cec5SDimitry Andric SinkCands.insert(AI);
5340b57cec5SDimitry Andric continue;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric
537af732203SDimitry Andric // Find bitcasts in the outlined region that have lifetime marker users
538af732203SDimitry Andric // outside that region. Replace the lifetime marker use with an
539af732203SDimitry Andric // outside region bitcast to avoid unnecessary alloca/reload instructions
540af732203SDimitry Andric // and extra lifetime markers.
541af732203SDimitry Andric SmallVector<Instruction *, 2> LifetimeBitcastUsers;
542af732203SDimitry Andric for (User *U : AI->users()) {
543af732203SDimitry Andric if (!definedInRegion(Blocks, U))
544af732203SDimitry Andric continue;
545af732203SDimitry Andric
546af732203SDimitry Andric if (U->stripInBoundsConstantOffsets() != AI)
547af732203SDimitry Andric continue;
548af732203SDimitry Andric
549af732203SDimitry Andric Instruction *Bitcast = cast<Instruction>(U);
550af732203SDimitry Andric for (User *BU : Bitcast->users()) {
551af732203SDimitry Andric IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(BU);
552af732203SDimitry Andric if (!IntrInst)
553af732203SDimitry Andric continue;
554af732203SDimitry Andric
555af732203SDimitry Andric if (!IntrInst->isLifetimeStartOrEnd())
556af732203SDimitry Andric continue;
557af732203SDimitry Andric
558af732203SDimitry Andric if (definedInRegion(Blocks, IntrInst))
559af732203SDimitry Andric continue;
560af732203SDimitry Andric
561af732203SDimitry Andric LLVM_DEBUG(dbgs() << "Replace use of extracted region bitcast"
562af732203SDimitry Andric << *Bitcast << " in out-of-region lifetime marker "
563af732203SDimitry Andric << *IntrInst << "\n");
564af732203SDimitry Andric LifetimeBitcastUsers.push_back(IntrInst);
565af732203SDimitry Andric }
566af732203SDimitry Andric }
567af732203SDimitry Andric
568af732203SDimitry Andric for (Instruction *I : LifetimeBitcastUsers) {
569af732203SDimitry Andric Module *M = AIFunc->getParent();
570af732203SDimitry Andric LLVMContext &Ctx = M->getContext();
571af732203SDimitry Andric auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
572af732203SDimitry Andric CastInst *CastI =
573af732203SDimitry Andric CastInst::CreatePointerCast(AI, Int8PtrTy, "lt.cast", I);
574af732203SDimitry Andric I->replaceUsesOfWith(I->getOperand(1), CastI);
575af732203SDimitry Andric }
576af732203SDimitry Andric
5770b57cec5SDimitry Andric // Follow any bitcasts.
5780b57cec5SDimitry Andric SmallVector<Instruction *, 2> Bitcasts;
5790b57cec5SDimitry Andric SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo;
5800b57cec5SDimitry Andric for (User *U : AI->users()) {
5810b57cec5SDimitry Andric if (U->stripInBoundsConstantOffsets() == AI) {
5820b57cec5SDimitry Andric Instruction *Bitcast = cast<Instruction>(U);
5838bcb0991SDimitry Andric LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Bitcast, ExitBlock);
5840b57cec5SDimitry Andric if (LMI.LifeStart) {
5850b57cec5SDimitry Andric Bitcasts.push_back(Bitcast);
5860b57cec5SDimitry Andric BitcastLifetimeInfo.push_back(LMI);
5870b57cec5SDimitry Andric continue;
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric
5910b57cec5SDimitry Andric // Found unknown use of AI.
5920b57cec5SDimitry Andric if (!definedInRegion(Blocks, U)) {
5930b57cec5SDimitry Andric Bitcasts.clear();
5940b57cec5SDimitry Andric break;
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric }
5970b57cec5SDimitry Andric
5980b57cec5SDimitry Andric // Either no bitcasts reference the alloca or there are unknown uses.
5990b57cec5SDimitry Andric if (Bitcasts.empty())
6000b57cec5SDimitry Andric continue;
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n");
6030b57cec5SDimitry Andric SinkCands.insert(AI);
6040b57cec5SDimitry Andric for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) {
6050b57cec5SDimitry Andric Instruction *BitcastAddr = Bitcasts[I];
6060b57cec5SDimitry Andric const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I];
6070b57cec5SDimitry Andric assert(LMI.LifeStart &&
6080b57cec5SDimitry Andric "Unsafe to sink bitcast without lifetime markers");
6090b57cec5SDimitry Andric moveOrIgnoreLifetimeMarkers(LMI);
6100b57cec5SDimitry Andric if (!definedInRegion(Blocks, BitcastAddr)) {
6110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr
6120b57cec5SDimitry Andric << "\n");
6130b57cec5SDimitry Andric SinkCands.insert(BitcastAddr);
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric }
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric }
6188bcb0991SDimitry Andric
isEligible() const6198bcb0991SDimitry Andric bool CodeExtractor::isEligible() const {
6208bcb0991SDimitry Andric if (Blocks.empty())
6218bcb0991SDimitry Andric return false;
6228bcb0991SDimitry Andric BasicBlock *Header = *Blocks.begin();
6238bcb0991SDimitry Andric Function *F = Header->getParent();
6248bcb0991SDimitry Andric
6258bcb0991SDimitry Andric // For functions with varargs, check that varargs handling is only done in the
6268bcb0991SDimitry Andric // outlined function, i.e vastart and vaend are only used in outlined blocks.
6278bcb0991SDimitry Andric if (AllowVarArgs && F->getFunctionType()->isVarArg()) {
6288bcb0991SDimitry Andric auto containsVarArgIntrinsic = [](const Instruction &I) {
6298bcb0991SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(&I))
6308bcb0991SDimitry Andric if (const Function *Callee = CI->getCalledFunction())
6318bcb0991SDimitry Andric return Callee->getIntrinsicID() == Intrinsic::vastart ||
6328bcb0991SDimitry Andric Callee->getIntrinsicID() == Intrinsic::vaend;
6338bcb0991SDimitry Andric return false;
6348bcb0991SDimitry Andric };
6358bcb0991SDimitry Andric
6368bcb0991SDimitry Andric for (auto &BB : *F) {
6378bcb0991SDimitry Andric if (Blocks.count(&BB))
6388bcb0991SDimitry Andric continue;
6398bcb0991SDimitry Andric if (llvm::any_of(BB, containsVarArgIntrinsic))
6408bcb0991SDimitry Andric return false;
6418bcb0991SDimitry Andric }
6428bcb0991SDimitry Andric }
6438bcb0991SDimitry Andric return true;
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric
findInputsOutputs(ValueSet & Inputs,ValueSet & Outputs,const ValueSet & SinkCands) const6460b57cec5SDimitry Andric void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
6470b57cec5SDimitry Andric const ValueSet &SinkCands) const {
6480b57cec5SDimitry Andric for (BasicBlock *BB : Blocks) {
6490b57cec5SDimitry Andric // If a used value is defined outside the region, it's an input. If an
6500b57cec5SDimitry Andric // instruction is used outside the region, it's an output.
6510b57cec5SDimitry Andric for (Instruction &II : *BB) {
6528bcb0991SDimitry Andric for (auto &OI : II.operands()) {
6538bcb0991SDimitry Andric Value *V = OI;
6540b57cec5SDimitry Andric if (!SinkCands.count(V) && definedInCaller(Blocks, V))
6550b57cec5SDimitry Andric Inputs.insert(V);
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric
6580b57cec5SDimitry Andric for (User *U : II.users())
6590b57cec5SDimitry Andric if (!definedInRegion(Blocks, U)) {
6600b57cec5SDimitry Andric Outputs.insert(&II);
6610b57cec5SDimitry Andric break;
6620b57cec5SDimitry Andric }
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric
6670b57cec5SDimitry Andric /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
6680b57cec5SDimitry Andric /// of the region, we need to split the entry block of the region so that the
6690b57cec5SDimitry Andric /// PHI node is easier to deal with.
severSplitPHINodesOfEntry(BasicBlock * & Header)6700b57cec5SDimitry Andric void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
6710b57cec5SDimitry Andric unsigned NumPredsFromRegion = 0;
6720b57cec5SDimitry Andric unsigned NumPredsOutsideRegion = 0;
6730b57cec5SDimitry Andric
6740b57cec5SDimitry Andric if (Header != &Header->getParent()->getEntryBlock()) {
6750b57cec5SDimitry Andric PHINode *PN = dyn_cast<PHINode>(Header->begin());
6760b57cec5SDimitry Andric if (!PN) return; // No PHI nodes.
6770b57cec5SDimitry Andric
6780b57cec5SDimitry Andric // If the header node contains any PHI nodes, check to see if there is more
6790b57cec5SDimitry Andric // than one entry from outside the region. If so, we need to sever the
6800b57cec5SDimitry Andric // header block into two.
6810b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6820b57cec5SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i)))
6830b57cec5SDimitry Andric ++NumPredsFromRegion;
6840b57cec5SDimitry Andric else
6850b57cec5SDimitry Andric ++NumPredsOutsideRegion;
6860b57cec5SDimitry Andric
6870b57cec5SDimitry Andric // If there is one (or fewer) predecessor from outside the region, we don't
6880b57cec5SDimitry Andric // need to do anything special.
6890b57cec5SDimitry Andric if (NumPredsOutsideRegion <= 1) return;
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric
6920b57cec5SDimitry Andric // Otherwise, we need to split the header block into two pieces: one
6930b57cec5SDimitry Andric // containing PHI nodes merging values from outside of the region, and a
6940b57cec5SDimitry Andric // second that contains all of the code for the block and merges back any
6950b57cec5SDimitry Andric // incoming values from inside of the region.
6960b57cec5SDimitry Andric BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
6970b57cec5SDimitry Andric
6980b57cec5SDimitry Andric // We only want to code extract the second block now, and it becomes the new
6990b57cec5SDimitry Andric // header of the region.
7000b57cec5SDimitry Andric BasicBlock *OldPred = Header;
7010b57cec5SDimitry Andric Blocks.remove(OldPred);
7020b57cec5SDimitry Andric Blocks.insert(NewBB);
7030b57cec5SDimitry Andric Header = NewBB;
7040b57cec5SDimitry Andric
7050b57cec5SDimitry Andric // Okay, now we need to adjust the PHI nodes and any branches from within the
7060b57cec5SDimitry Andric // region to go to the new header block instead of the old header block.
7070b57cec5SDimitry Andric if (NumPredsFromRegion) {
7080b57cec5SDimitry Andric PHINode *PN = cast<PHINode>(OldPred->begin());
7090b57cec5SDimitry Andric // Loop over all of the predecessors of OldPred that are in the region,
7100b57cec5SDimitry Andric // changing them to branch to NewBB instead.
7110b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7120b57cec5SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) {
7130b57cec5SDimitry Andric Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
7140b57cec5SDimitry Andric TI->replaceUsesOfWith(OldPred, NewBB);
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric
7170b57cec5SDimitry Andric // Okay, everything within the region is now branching to the right block, we
7180b57cec5SDimitry Andric // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
7190b57cec5SDimitry Andric BasicBlock::iterator AfterPHIs;
7200b57cec5SDimitry Andric for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
7210b57cec5SDimitry Andric PHINode *PN = cast<PHINode>(AfterPHIs);
7220b57cec5SDimitry Andric // Create a new PHI node in the new region, which has an incoming value
7230b57cec5SDimitry Andric // from OldPred of PN.
7240b57cec5SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
7250b57cec5SDimitry Andric PN->getName() + ".ce", &NewBB->front());
7260b57cec5SDimitry Andric PN->replaceAllUsesWith(NewPN);
7270b57cec5SDimitry Andric NewPN->addIncoming(PN, OldPred);
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric // Loop over all of the incoming value in PN, moving them to NewPN if they
7300b57cec5SDimitry Andric // are from the extracted region.
7310b57cec5SDimitry Andric for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
7320b57cec5SDimitry Andric if (Blocks.count(PN->getIncomingBlock(i))) {
7330b57cec5SDimitry Andric NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
7340b57cec5SDimitry Andric PN->removeIncomingValue(i);
7350b57cec5SDimitry Andric --i;
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric }
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric }
7410b57cec5SDimitry Andric
7420b57cec5SDimitry Andric /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
7430b57cec5SDimitry Andric /// outlined region, we split these PHIs on two: one with inputs from region
7440b57cec5SDimitry Andric /// and other with remaining incoming blocks; then first PHIs are placed in
7450b57cec5SDimitry Andric /// outlined region.
severSplitPHINodesOfExits(const SmallPtrSetImpl<BasicBlock * > & Exits)7460b57cec5SDimitry Andric void CodeExtractor::severSplitPHINodesOfExits(
7470b57cec5SDimitry Andric const SmallPtrSetImpl<BasicBlock *> &Exits) {
7480b57cec5SDimitry Andric for (BasicBlock *ExitBB : Exits) {
7490b57cec5SDimitry Andric BasicBlock *NewBB = nullptr;
7500b57cec5SDimitry Andric
7510b57cec5SDimitry Andric for (PHINode &PN : ExitBB->phis()) {
7520b57cec5SDimitry Andric // Find all incoming values from the outlining region.
7530b57cec5SDimitry Andric SmallVector<unsigned, 2> IncomingVals;
7540b57cec5SDimitry Andric for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
7550b57cec5SDimitry Andric if (Blocks.count(PN.getIncomingBlock(i)))
7560b57cec5SDimitry Andric IncomingVals.push_back(i);
7570b57cec5SDimitry Andric
7580b57cec5SDimitry Andric // Do not process PHI if there is one (or fewer) predecessor from region.
7590b57cec5SDimitry Andric // If PHI has exactly one predecessor from region, only this one incoming
7600b57cec5SDimitry Andric // will be replaced on codeRepl block, so it should be safe to skip PHI.
7610b57cec5SDimitry Andric if (IncomingVals.size() <= 1)
7620b57cec5SDimitry Andric continue;
7630b57cec5SDimitry Andric
7640b57cec5SDimitry Andric // Create block for new PHIs and add it to the list of outlined if it
7650b57cec5SDimitry Andric // wasn't done before.
7660b57cec5SDimitry Andric if (!NewBB) {
7670b57cec5SDimitry Andric NewBB = BasicBlock::Create(ExitBB->getContext(),
7680b57cec5SDimitry Andric ExitBB->getName() + ".split",
7690b57cec5SDimitry Andric ExitBB->getParent(), ExitBB);
770af732203SDimitry Andric SmallVector<BasicBlock *, 4> Preds(predecessors(ExitBB));
7710b57cec5SDimitry Andric for (BasicBlock *PredBB : Preds)
7720b57cec5SDimitry Andric if (Blocks.count(PredBB))
7730b57cec5SDimitry Andric PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
7740b57cec5SDimitry Andric BranchInst::Create(ExitBB, NewBB);
7750b57cec5SDimitry Andric Blocks.insert(NewBB);
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric
7780b57cec5SDimitry Andric // Split this PHI.
7790b57cec5SDimitry Andric PHINode *NewPN =
7800b57cec5SDimitry Andric PHINode::Create(PN.getType(), IncomingVals.size(),
7810b57cec5SDimitry Andric PN.getName() + ".ce", NewBB->getFirstNonPHI());
7820b57cec5SDimitry Andric for (unsigned i : IncomingVals)
7830b57cec5SDimitry Andric NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
7840b57cec5SDimitry Andric for (unsigned i : reverse(IncomingVals))
7850b57cec5SDimitry Andric PN.removeIncomingValue(i, false);
7860b57cec5SDimitry Andric PN.addIncoming(NewPN, NewBB);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric }
7900b57cec5SDimitry Andric
splitReturnBlocks()7910b57cec5SDimitry Andric void CodeExtractor::splitReturnBlocks() {
7920b57cec5SDimitry Andric for (BasicBlock *Block : Blocks)
7930b57cec5SDimitry Andric if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
7940b57cec5SDimitry Andric BasicBlock *New =
7950b57cec5SDimitry Andric Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
7960b57cec5SDimitry Andric if (DT) {
7970b57cec5SDimitry Andric // Old dominates New. New node dominates all other nodes dominated
7980b57cec5SDimitry Andric // by Old.
7990b57cec5SDimitry Andric DomTreeNode *OldNode = DT->getNode(Block);
8000b57cec5SDimitry Andric SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
8010b57cec5SDimitry Andric OldNode->end());
8020b57cec5SDimitry Andric
8030b57cec5SDimitry Andric DomTreeNode *NewNode = DT->addNewBlock(New, Block);
8040b57cec5SDimitry Andric
8050b57cec5SDimitry Andric for (DomTreeNode *I : Children)
8060b57cec5SDimitry Andric DT->changeImmediateDominator(I, NewNode);
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric /// constructFunction - make a function based on inputs and outputs, as follows:
8120b57cec5SDimitry Andric /// f(in0, ..., inN, out0, ..., outN)
constructFunction(const ValueSet & inputs,const ValueSet & outputs,BasicBlock * header,BasicBlock * newRootNode,BasicBlock * newHeader,Function * oldFunction,Module * M)8130b57cec5SDimitry Andric Function *CodeExtractor::constructFunction(const ValueSet &inputs,
8140b57cec5SDimitry Andric const ValueSet &outputs,
8150b57cec5SDimitry Andric BasicBlock *header,
8160b57cec5SDimitry Andric BasicBlock *newRootNode,
8170b57cec5SDimitry Andric BasicBlock *newHeader,
8180b57cec5SDimitry Andric Function *oldFunction,
8190b57cec5SDimitry Andric Module *M) {
8200b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
8210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
8220b57cec5SDimitry Andric
8230b57cec5SDimitry Andric // This function returns unsigned, outputs will go back by reference.
8240b57cec5SDimitry Andric switch (NumExitBlocks) {
8250b57cec5SDimitry Andric case 0:
8260b57cec5SDimitry Andric case 1: RetTy = Type::getVoidTy(header->getContext()); break;
8270b57cec5SDimitry Andric case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
8280b57cec5SDimitry Andric default: RetTy = Type::getInt16Ty(header->getContext()); break;
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric
8310b57cec5SDimitry Andric std::vector<Type *> paramTy;
8320b57cec5SDimitry Andric
8330b57cec5SDimitry Andric // Add the types of the input values to the function's argument list
8340b57cec5SDimitry Andric for (Value *value : inputs) {
8350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
8360b57cec5SDimitry Andric paramTy.push_back(value->getType());
8370b57cec5SDimitry Andric }
8380b57cec5SDimitry Andric
8390b57cec5SDimitry Andric // Add the types of the output values to the function's argument list.
8400b57cec5SDimitry Andric for (Value *output : outputs) {
8410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
8420b57cec5SDimitry Andric if (AggregateArgs)
8430b57cec5SDimitry Andric paramTy.push_back(output->getType());
8440b57cec5SDimitry Andric else
8450b57cec5SDimitry Andric paramTy.push_back(PointerType::getUnqual(output->getType()));
8460b57cec5SDimitry Andric }
8470b57cec5SDimitry Andric
8480b57cec5SDimitry Andric LLVM_DEBUG({
8490b57cec5SDimitry Andric dbgs() << "Function type: " << *RetTy << " f(";
8500b57cec5SDimitry Andric for (Type *i : paramTy)
8510b57cec5SDimitry Andric dbgs() << *i << ", ";
8520b57cec5SDimitry Andric dbgs() << ")\n";
8530b57cec5SDimitry Andric });
8540b57cec5SDimitry Andric
855480093f4SDimitry Andric StructType *StructTy = nullptr;
8560b57cec5SDimitry Andric if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
8570b57cec5SDimitry Andric StructTy = StructType::get(M->getContext(), paramTy);
8580b57cec5SDimitry Andric paramTy.clear();
8590b57cec5SDimitry Andric paramTy.push_back(PointerType::getUnqual(StructTy));
8600b57cec5SDimitry Andric }
8610b57cec5SDimitry Andric FunctionType *funcType =
8620b57cec5SDimitry Andric FunctionType::get(RetTy, paramTy,
8630b57cec5SDimitry Andric AllowVarArgs && oldFunction->isVarArg());
8640b57cec5SDimitry Andric
8650b57cec5SDimitry Andric std::string SuffixToUse =
8660b57cec5SDimitry Andric Suffix.empty()
8670b57cec5SDimitry Andric ? (header->getName().empty() ? "extracted" : header->getName().str())
8680b57cec5SDimitry Andric : Suffix;
8690b57cec5SDimitry Andric // Create the new function
8700b57cec5SDimitry Andric Function *newFunction = Function::Create(
8710b57cec5SDimitry Andric funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
8720b57cec5SDimitry Andric oldFunction->getName() + "." + SuffixToUse, M);
8730b57cec5SDimitry Andric // If the old function is no-throw, so is the new one.
8740b57cec5SDimitry Andric if (oldFunction->doesNotThrow())
8750b57cec5SDimitry Andric newFunction->setDoesNotThrow();
8760b57cec5SDimitry Andric
8770b57cec5SDimitry Andric // Inherit the uwtable attribute if we need to.
8780b57cec5SDimitry Andric if (oldFunction->hasUWTable())
8790b57cec5SDimitry Andric newFunction->setHasUWTable();
8800b57cec5SDimitry Andric
8810b57cec5SDimitry Andric // Inherit all of the target dependent attributes and white-listed
8820b57cec5SDimitry Andric // target independent attributes.
8830b57cec5SDimitry Andric // (e.g. If the extracted region contains a call to an x86.sse
8840b57cec5SDimitry Andric // instruction we need to make sure that the extracted region has the
8850b57cec5SDimitry Andric // "target-features" attribute allowing it to be lowered.
8860b57cec5SDimitry Andric // FIXME: This should be changed to check to see if a specific
8870b57cec5SDimitry Andric // attribute can not be inherited.
8880b57cec5SDimitry Andric for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
8890b57cec5SDimitry Andric if (Attr.isStringAttribute()) {
8900b57cec5SDimitry Andric if (Attr.getKindAsString() == "thunk")
8910b57cec5SDimitry Andric continue;
8920b57cec5SDimitry Andric } else
8930b57cec5SDimitry Andric switch (Attr.getKindAsEnum()) {
8940b57cec5SDimitry Andric // Those attributes cannot be propagated safely. Explicitly list them
8950b57cec5SDimitry Andric // here so we get a warning if new attributes are added. This list also
8960b57cec5SDimitry Andric // includes non-function attributes.
8970b57cec5SDimitry Andric case Attribute::Alignment:
8980b57cec5SDimitry Andric case Attribute::AllocSize:
8990b57cec5SDimitry Andric case Attribute::ArgMemOnly:
9000b57cec5SDimitry Andric case Attribute::Builtin:
9010b57cec5SDimitry Andric case Attribute::ByVal:
9020b57cec5SDimitry Andric case Attribute::Convergent:
9030b57cec5SDimitry Andric case Attribute::Dereferenceable:
9040b57cec5SDimitry Andric case Attribute::DereferenceableOrNull:
905*5f7ddb14SDimitry Andric case Attribute::ElementType:
9060b57cec5SDimitry Andric case Attribute::InAlloca:
9070b57cec5SDimitry Andric case Attribute::InReg:
9080b57cec5SDimitry Andric case Attribute::InaccessibleMemOnly:
9090b57cec5SDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly:
9100b57cec5SDimitry Andric case Attribute::JumpTable:
9110b57cec5SDimitry Andric case Attribute::Naked:
9120b57cec5SDimitry Andric case Attribute::Nest:
9130b57cec5SDimitry Andric case Attribute::NoAlias:
9140b57cec5SDimitry Andric case Attribute::NoBuiltin:
9150b57cec5SDimitry Andric case Attribute::NoCapture:
9165ffd83dbSDimitry Andric case Attribute::NoMerge:
9170b57cec5SDimitry Andric case Attribute::NoReturn:
9180b57cec5SDimitry Andric case Attribute::NoSync:
9195ffd83dbSDimitry Andric case Attribute::NoUndef:
9200b57cec5SDimitry Andric case Attribute::None:
9210b57cec5SDimitry Andric case Attribute::NonNull:
9225ffd83dbSDimitry Andric case Attribute::Preallocated:
9230b57cec5SDimitry Andric case Attribute::ReadNone:
9240b57cec5SDimitry Andric case Attribute::ReadOnly:
9250b57cec5SDimitry Andric case Attribute::Returned:
9260b57cec5SDimitry Andric case Attribute::ReturnsTwice:
9270b57cec5SDimitry Andric case Attribute::SExt:
9280b57cec5SDimitry Andric case Attribute::Speculatable:
9290b57cec5SDimitry Andric case Attribute::StackAlignment:
9300b57cec5SDimitry Andric case Attribute::StructRet:
9310b57cec5SDimitry Andric case Attribute::SwiftError:
9320b57cec5SDimitry Andric case Attribute::SwiftSelf:
933*5f7ddb14SDimitry Andric case Attribute::SwiftAsync:
9340b57cec5SDimitry Andric case Attribute::WillReturn:
9350b57cec5SDimitry Andric case Attribute::WriteOnly:
9360b57cec5SDimitry Andric case Attribute::ZExt:
9370b57cec5SDimitry Andric case Attribute::ImmArg:
938af732203SDimitry Andric case Attribute::ByRef:
9390b57cec5SDimitry Andric case Attribute::EndAttrKinds:
9405ffd83dbSDimitry Andric case Attribute::EmptyKey:
9415ffd83dbSDimitry Andric case Attribute::TombstoneKey:
9420b57cec5SDimitry Andric continue;
9430b57cec5SDimitry Andric // Those attributes should be safe to propagate to the extracted function.
9440b57cec5SDimitry Andric case Attribute::AlwaysInline:
9450b57cec5SDimitry Andric case Attribute::Cold:
946af732203SDimitry Andric case Attribute::Hot:
9470b57cec5SDimitry Andric case Attribute::NoRecurse:
9480b57cec5SDimitry Andric case Attribute::InlineHint:
9490b57cec5SDimitry Andric case Attribute::MinSize:
950af732203SDimitry Andric case Attribute::NoCallback:
9510b57cec5SDimitry Andric case Attribute::NoDuplicate:
9520b57cec5SDimitry Andric case Attribute::NoFree:
9530b57cec5SDimitry Andric case Attribute::NoImplicitFloat:
9540b57cec5SDimitry Andric case Attribute::NoInline:
9550b57cec5SDimitry Andric case Attribute::NonLazyBind:
9560b57cec5SDimitry Andric case Attribute::NoRedZone:
9570b57cec5SDimitry Andric case Attribute::NoUnwind:
958*5f7ddb14SDimitry Andric case Attribute::NoSanitizeCoverage:
9595ffd83dbSDimitry Andric case Attribute::NullPointerIsValid:
9600b57cec5SDimitry Andric case Attribute::OptForFuzzing:
9610b57cec5SDimitry Andric case Attribute::OptimizeNone:
9620b57cec5SDimitry Andric case Attribute::OptimizeForSize:
9630b57cec5SDimitry Andric case Attribute::SafeStack:
9640b57cec5SDimitry Andric case Attribute::ShadowCallStack:
9650b57cec5SDimitry Andric case Attribute::SanitizeAddress:
9660b57cec5SDimitry Andric case Attribute::SanitizeMemory:
9670b57cec5SDimitry Andric case Attribute::SanitizeThread:
9680b57cec5SDimitry Andric case Attribute::SanitizeHWAddress:
9690b57cec5SDimitry Andric case Attribute::SanitizeMemTag:
9700b57cec5SDimitry Andric case Attribute::SpeculativeLoadHardening:
9710b57cec5SDimitry Andric case Attribute::StackProtect:
9720b57cec5SDimitry Andric case Attribute::StackProtectReq:
9730b57cec5SDimitry Andric case Attribute::StackProtectStrong:
9740b57cec5SDimitry Andric case Attribute::StrictFP:
9750b57cec5SDimitry Andric case Attribute::UWTable:
976*5f7ddb14SDimitry Andric case Attribute::VScaleRange:
9770b57cec5SDimitry Andric case Attribute::NoCfCheck:
978af732203SDimitry Andric case Attribute::MustProgress:
979af732203SDimitry Andric case Attribute::NoProfile:
9800b57cec5SDimitry Andric break;
9810b57cec5SDimitry Andric }
9820b57cec5SDimitry Andric
9830b57cec5SDimitry Andric newFunction->addFnAttr(Attr);
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric newFunction->getBasicBlockList().push_back(newRootNode);
9860b57cec5SDimitry Andric
9870b57cec5SDimitry Andric // Create an iterator to name all of the arguments we inserted.
9880b57cec5SDimitry Andric Function::arg_iterator AI = newFunction->arg_begin();
9890b57cec5SDimitry Andric
9900b57cec5SDimitry Andric // Rewrite all users of the inputs in the extracted region to use the
9910b57cec5SDimitry Andric // arguments (or appropriate addressing into struct) instead.
9920b57cec5SDimitry Andric for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
9930b57cec5SDimitry Andric Value *RewriteVal;
9940b57cec5SDimitry Andric if (AggregateArgs) {
9950b57cec5SDimitry Andric Value *Idx[2];
9960b57cec5SDimitry Andric Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
9970b57cec5SDimitry Andric Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
9980b57cec5SDimitry Andric Instruction *TI = newFunction->begin()->getTerminator();
9990b57cec5SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
10000b57cec5SDimitry Andric StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
10010b57cec5SDimitry Andric RewriteVal = new LoadInst(StructTy->getElementType(i), GEP,
10020b57cec5SDimitry Andric "loadgep_" + inputs[i]->getName(), TI);
10030b57cec5SDimitry Andric } else
10040b57cec5SDimitry Andric RewriteVal = &*AI++;
10050b57cec5SDimitry Andric
10060b57cec5SDimitry Andric std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
10070b57cec5SDimitry Andric for (User *use : Users)
10080b57cec5SDimitry Andric if (Instruction *inst = dyn_cast<Instruction>(use))
10090b57cec5SDimitry Andric if (Blocks.count(inst->getParent()))
10100b57cec5SDimitry Andric inst->replaceUsesOfWith(inputs[i], RewriteVal);
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric
10130b57cec5SDimitry Andric // Set names for input and output arguments.
10140b57cec5SDimitry Andric if (!AggregateArgs) {
10150b57cec5SDimitry Andric AI = newFunction->arg_begin();
10160b57cec5SDimitry Andric for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
10170b57cec5SDimitry Andric AI->setName(inputs[i]->getName());
10180b57cec5SDimitry Andric for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
10190b57cec5SDimitry Andric AI->setName(outputs[i]->getName()+".out");
10200b57cec5SDimitry Andric }
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric // Rewrite branches to basic blocks outside of the loop to new dummy blocks
10230b57cec5SDimitry Andric // within the new function. This must be done before we lose track of which
10240b57cec5SDimitry Andric // blocks were originally in the code region.
10250b57cec5SDimitry Andric std::vector<User *> Users(header->user_begin(), header->user_end());
10268bcb0991SDimitry Andric for (auto &U : Users)
10270b57cec5SDimitry Andric // The BasicBlock which contains the branch is not in the region
10280b57cec5SDimitry Andric // modify the branch target to a new block
10298bcb0991SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(U))
10308bcb0991SDimitry Andric if (I->isTerminator() && I->getFunction() == oldFunction &&
10318bcb0991SDimitry Andric !Blocks.count(I->getParent()))
10320b57cec5SDimitry Andric I->replaceUsesOfWith(header, newHeader);
10330b57cec5SDimitry Andric
10340b57cec5SDimitry Andric return newFunction;
10350b57cec5SDimitry Andric }
10360b57cec5SDimitry Andric
10370b57cec5SDimitry Andric /// Erase lifetime.start markers which reference inputs to the extraction
10380b57cec5SDimitry Andric /// region, and insert the referenced memory into \p LifetimesStart.
10390b57cec5SDimitry Andric ///
10400b57cec5SDimitry Andric /// The extraction region is defined by a set of blocks (\p Blocks), and a set
10410b57cec5SDimitry Andric /// of allocas which will be moved from the caller function into the extracted
10420b57cec5SDimitry Andric /// function (\p SunkAllocas).
eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock * > & Blocks,const SetVector<Value * > & SunkAllocas,SetVector<Value * > & LifetimesStart)10430b57cec5SDimitry Andric static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
10440b57cec5SDimitry Andric const SetVector<Value *> &SunkAllocas,
10450b57cec5SDimitry Andric SetVector<Value *> &LifetimesStart) {
10460b57cec5SDimitry Andric for (BasicBlock *BB : Blocks) {
10470b57cec5SDimitry Andric for (auto It = BB->begin(), End = BB->end(); It != End;) {
10480b57cec5SDimitry Andric auto *II = dyn_cast<IntrinsicInst>(&*It);
10490b57cec5SDimitry Andric ++It;
10500b57cec5SDimitry Andric if (!II || !II->isLifetimeStartOrEnd())
10510b57cec5SDimitry Andric continue;
10520b57cec5SDimitry Andric
10530b57cec5SDimitry Andric // Get the memory operand of the lifetime marker. If the underlying
10540b57cec5SDimitry Andric // object is a sunk alloca, or is otherwise defined in the extraction
10550b57cec5SDimitry Andric // region, the lifetime marker must not be erased.
10560b57cec5SDimitry Andric Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
10570b57cec5SDimitry Andric if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
10580b57cec5SDimitry Andric continue;
10590b57cec5SDimitry Andric
10600b57cec5SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_start)
10610b57cec5SDimitry Andric LifetimesStart.insert(Mem);
10620b57cec5SDimitry Andric II->eraseFromParent();
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric }
10660b57cec5SDimitry Andric
10670b57cec5SDimitry Andric /// Insert lifetime start/end markers surrounding the call to the new function
10680b57cec5SDimitry Andric /// for objects defined in the caller.
insertLifetimeMarkersSurroundingCall(Module * M,ArrayRef<Value * > LifetimesStart,ArrayRef<Value * > LifetimesEnd,CallInst * TheCall)10690b57cec5SDimitry Andric static void insertLifetimeMarkersSurroundingCall(
10700b57cec5SDimitry Andric Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
10710b57cec5SDimitry Andric CallInst *TheCall) {
10720b57cec5SDimitry Andric LLVMContext &Ctx = M->getContext();
10730b57cec5SDimitry Andric auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
10740b57cec5SDimitry Andric auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
10750b57cec5SDimitry Andric Instruction *Term = TheCall->getParent()->getTerminator();
10760b57cec5SDimitry Andric
10770b57cec5SDimitry Andric // The memory argument to a lifetime marker must be a i8*. Cache any bitcasts
10780b57cec5SDimitry Andric // needed to satisfy this requirement so they may be reused.
10790b57cec5SDimitry Andric DenseMap<Value *, Value *> Bitcasts;
10800b57cec5SDimitry Andric
10810b57cec5SDimitry Andric // Emit lifetime markers for the pointers given in \p Objects. Insert the
10820b57cec5SDimitry Andric // markers before the call if \p InsertBefore, and after the call otherwise.
10830b57cec5SDimitry Andric auto insertMarkers = [&](Function *MarkerFunc, ArrayRef<Value *> Objects,
10840b57cec5SDimitry Andric bool InsertBefore) {
10850b57cec5SDimitry Andric for (Value *Mem : Objects) {
10860b57cec5SDimitry Andric assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==
10870b57cec5SDimitry Andric TheCall->getFunction()) &&
10880b57cec5SDimitry Andric "Input memory not defined in original function");
10890b57cec5SDimitry Andric Value *&MemAsI8Ptr = Bitcasts[Mem];
10900b57cec5SDimitry Andric if (!MemAsI8Ptr) {
10910b57cec5SDimitry Andric if (Mem->getType() == Int8PtrTy)
10920b57cec5SDimitry Andric MemAsI8Ptr = Mem;
10930b57cec5SDimitry Andric else
10940b57cec5SDimitry Andric MemAsI8Ptr =
10950b57cec5SDimitry Andric CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric
10980b57cec5SDimitry Andric auto Marker = CallInst::Create(MarkerFunc, {NegativeOne, MemAsI8Ptr});
10990b57cec5SDimitry Andric if (InsertBefore)
11000b57cec5SDimitry Andric Marker->insertBefore(TheCall);
11010b57cec5SDimitry Andric else
11020b57cec5SDimitry Andric Marker->insertBefore(Term);
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric };
11050b57cec5SDimitry Andric
11060b57cec5SDimitry Andric if (!LifetimesStart.empty()) {
11070b57cec5SDimitry Andric auto StartFn = llvm::Intrinsic::getDeclaration(
11080b57cec5SDimitry Andric M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
11090b57cec5SDimitry Andric insertMarkers(StartFn, LifetimesStart, /*InsertBefore=*/true);
11100b57cec5SDimitry Andric }
11110b57cec5SDimitry Andric
11120b57cec5SDimitry Andric if (!LifetimesEnd.empty()) {
11130b57cec5SDimitry Andric auto EndFn = llvm::Intrinsic::getDeclaration(
11140b57cec5SDimitry Andric M, llvm::Intrinsic::lifetime_end, Int8PtrTy);
11150b57cec5SDimitry Andric insertMarkers(EndFn, LifetimesEnd, /*InsertBefore=*/false);
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric
11190b57cec5SDimitry Andric /// emitCallAndSwitchStatement - This method sets up the caller side by adding
11200b57cec5SDimitry Andric /// the call instruction, splitting any PHI nodes in the header block as
11210b57cec5SDimitry Andric /// necessary.
emitCallAndSwitchStatement(Function * newFunction,BasicBlock * codeReplacer,ValueSet & inputs,ValueSet & outputs)11220b57cec5SDimitry Andric CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
11230b57cec5SDimitry Andric BasicBlock *codeReplacer,
11240b57cec5SDimitry Andric ValueSet &inputs,
11250b57cec5SDimitry Andric ValueSet &outputs) {
11260b57cec5SDimitry Andric // Emit a call to the new function, passing in: *pointer to struct (if
11270b57cec5SDimitry Andric // aggregating parameters), or plan inputs and allocated memory for outputs
11280b57cec5SDimitry Andric std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
11290b57cec5SDimitry Andric
11300b57cec5SDimitry Andric Module *M = newFunction->getParent();
11310b57cec5SDimitry Andric LLVMContext &Context = M->getContext();
11320b57cec5SDimitry Andric const DataLayout &DL = M->getDataLayout();
11330b57cec5SDimitry Andric CallInst *call = nullptr;
11340b57cec5SDimitry Andric
11350b57cec5SDimitry Andric // Add inputs as params, or to be filled into the struct
11360b57cec5SDimitry Andric unsigned ArgNo = 0;
11370b57cec5SDimitry Andric SmallVector<unsigned, 1> SwiftErrorArgs;
11380b57cec5SDimitry Andric for (Value *input : inputs) {
11390b57cec5SDimitry Andric if (AggregateArgs)
11400b57cec5SDimitry Andric StructValues.push_back(input);
11410b57cec5SDimitry Andric else {
11420b57cec5SDimitry Andric params.push_back(input);
11430b57cec5SDimitry Andric if (input->isSwiftError())
11440b57cec5SDimitry Andric SwiftErrorArgs.push_back(ArgNo);
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric ++ArgNo;
11470b57cec5SDimitry Andric }
11480b57cec5SDimitry Andric
11490b57cec5SDimitry Andric // Create allocas for the outputs
11500b57cec5SDimitry Andric for (Value *output : outputs) {
11510b57cec5SDimitry Andric if (AggregateArgs) {
11520b57cec5SDimitry Andric StructValues.push_back(output);
11530b57cec5SDimitry Andric } else {
11540b57cec5SDimitry Andric AllocaInst *alloca =
11550b57cec5SDimitry Andric new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
11560b57cec5SDimitry Andric nullptr, output->getName() + ".loc",
11570b57cec5SDimitry Andric &codeReplacer->getParent()->front().front());
11580b57cec5SDimitry Andric ReloadOutputs.push_back(alloca);
11590b57cec5SDimitry Andric params.push_back(alloca);
11600b57cec5SDimitry Andric }
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric
11630b57cec5SDimitry Andric StructType *StructArgTy = nullptr;
11640b57cec5SDimitry Andric AllocaInst *Struct = nullptr;
11650b57cec5SDimitry Andric if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
11660b57cec5SDimitry Andric std::vector<Type *> ArgTypes;
1167*5f7ddb14SDimitry Andric for (Value *V : StructValues)
1168*5f7ddb14SDimitry Andric ArgTypes.push_back(V->getType());
11690b57cec5SDimitry Andric
11700b57cec5SDimitry Andric // Allocate a struct at the beginning of this function
11710b57cec5SDimitry Andric StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
11720b57cec5SDimitry Andric Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
11730b57cec5SDimitry Andric "structArg",
11740b57cec5SDimitry Andric &codeReplacer->getParent()->front().front());
11750b57cec5SDimitry Andric params.push_back(Struct);
11760b57cec5SDimitry Andric
11770b57cec5SDimitry Andric for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
11780b57cec5SDimitry Andric Value *Idx[2];
11790b57cec5SDimitry Andric Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
11800b57cec5SDimitry Andric Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
11810b57cec5SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
11820b57cec5SDimitry Andric StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
11830b57cec5SDimitry Andric codeReplacer->getInstList().push_back(GEP);
11845ffd83dbSDimitry Andric new StoreInst(StructValues[i], GEP, codeReplacer);
11850b57cec5SDimitry Andric }
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric
11880b57cec5SDimitry Andric // Emit the call to the function
11890b57cec5SDimitry Andric call = CallInst::Create(newFunction, params,
11900b57cec5SDimitry Andric NumExitBlocks > 1 ? "targetBlock" : "");
11910b57cec5SDimitry Andric // Add debug location to the new call, if the original function has debug
11920b57cec5SDimitry Andric // info. In that case, the terminator of the entry block of the extracted
11930b57cec5SDimitry Andric // function contains the first debug location of the extracted function,
11940b57cec5SDimitry Andric // set in extractCodeRegion.
11950b57cec5SDimitry Andric if (codeReplacer->getParent()->getSubprogram()) {
11960b57cec5SDimitry Andric if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
11970b57cec5SDimitry Andric call->setDebugLoc(DL);
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric codeReplacer->getInstList().push_back(call);
12000b57cec5SDimitry Andric
12010b57cec5SDimitry Andric // Set swifterror parameter attributes.
12020b57cec5SDimitry Andric for (unsigned SwiftErrArgNo : SwiftErrorArgs) {
12030b57cec5SDimitry Andric call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
12040b57cec5SDimitry Andric newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric
12070b57cec5SDimitry Andric Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
12080b57cec5SDimitry Andric unsigned FirstOut = inputs.size();
12090b57cec5SDimitry Andric if (!AggregateArgs)
12100b57cec5SDimitry Andric std::advance(OutputArgBegin, inputs.size());
12110b57cec5SDimitry Andric
12120b57cec5SDimitry Andric // Reload the outputs passed in by reference.
12130b57cec5SDimitry Andric for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
12140b57cec5SDimitry Andric Value *Output = nullptr;
12150b57cec5SDimitry Andric if (AggregateArgs) {
12160b57cec5SDimitry Andric Value *Idx[2];
12170b57cec5SDimitry Andric Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
12180b57cec5SDimitry Andric Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
12190b57cec5SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
12200b57cec5SDimitry Andric StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
12210b57cec5SDimitry Andric codeReplacer->getInstList().push_back(GEP);
12220b57cec5SDimitry Andric Output = GEP;
12230b57cec5SDimitry Andric } else {
12240b57cec5SDimitry Andric Output = ReloadOutputs[i];
12250b57cec5SDimitry Andric }
12260b57cec5SDimitry Andric LoadInst *load = new LoadInst(outputs[i]->getType(), Output,
12275ffd83dbSDimitry Andric outputs[i]->getName() + ".reload",
12285ffd83dbSDimitry Andric codeReplacer);
12290b57cec5SDimitry Andric Reloads.push_back(load);
12300b57cec5SDimitry Andric std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
12310b57cec5SDimitry Andric for (unsigned u = 0, e = Users.size(); u != e; ++u) {
12320b57cec5SDimitry Andric Instruction *inst = cast<Instruction>(Users[u]);
12330b57cec5SDimitry Andric if (!Blocks.count(inst->getParent()))
12340b57cec5SDimitry Andric inst->replaceUsesOfWith(outputs[i], load);
12350b57cec5SDimitry Andric }
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric
12380b57cec5SDimitry Andric // Now we can emit a switch statement using the call as a value.
12390b57cec5SDimitry Andric SwitchInst *TheSwitch =
12400b57cec5SDimitry Andric SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
12410b57cec5SDimitry Andric codeReplacer, 0, codeReplacer);
12420b57cec5SDimitry Andric
12430b57cec5SDimitry Andric // Since there may be multiple exits from the original region, make the new
12440b57cec5SDimitry Andric // function return an unsigned, switch on that number. This loop iterates
12450b57cec5SDimitry Andric // over all of the blocks in the extracted region, updating any terminator
12460b57cec5SDimitry Andric // instructions in the to-be-extracted region that branch to blocks that are
12470b57cec5SDimitry Andric // not in the region to be extracted.
12480b57cec5SDimitry Andric std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
12490b57cec5SDimitry Andric
12500b57cec5SDimitry Andric unsigned switchVal = 0;
12510b57cec5SDimitry Andric for (BasicBlock *Block : Blocks) {
12520b57cec5SDimitry Andric Instruction *TI = Block->getTerminator();
12530b57cec5SDimitry Andric for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12540b57cec5SDimitry Andric if (!Blocks.count(TI->getSuccessor(i))) {
12550b57cec5SDimitry Andric BasicBlock *OldTarget = TI->getSuccessor(i);
12560b57cec5SDimitry Andric // add a new basic block which returns the appropriate value
12570b57cec5SDimitry Andric BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
12580b57cec5SDimitry Andric if (!NewTarget) {
12590b57cec5SDimitry Andric // If we don't already have an exit stub for this non-extracted
12600b57cec5SDimitry Andric // destination, create one now!
12610b57cec5SDimitry Andric NewTarget = BasicBlock::Create(Context,
12620b57cec5SDimitry Andric OldTarget->getName() + ".exitStub",
12630b57cec5SDimitry Andric newFunction);
12640b57cec5SDimitry Andric unsigned SuccNum = switchVal++;
12650b57cec5SDimitry Andric
12660b57cec5SDimitry Andric Value *brVal = nullptr;
12670b57cec5SDimitry Andric switch (NumExitBlocks) {
12680b57cec5SDimitry Andric case 0:
12690b57cec5SDimitry Andric case 1: break; // No value needed.
12700b57cec5SDimitry Andric case 2: // Conditional branch, return a bool
12710b57cec5SDimitry Andric brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
12720b57cec5SDimitry Andric break;
12730b57cec5SDimitry Andric default:
12740b57cec5SDimitry Andric brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
12750b57cec5SDimitry Andric break;
12760b57cec5SDimitry Andric }
12770b57cec5SDimitry Andric
12780b57cec5SDimitry Andric ReturnInst::Create(Context, brVal, NewTarget);
12790b57cec5SDimitry Andric
12800b57cec5SDimitry Andric // Update the switch instruction.
12810b57cec5SDimitry Andric TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
12820b57cec5SDimitry Andric SuccNum),
12830b57cec5SDimitry Andric OldTarget);
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric
12860b57cec5SDimitry Andric // rewrite the original branch instruction with this new target
12870b57cec5SDimitry Andric TI->setSuccessor(i, NewTarget);
12880b57cec5SDimitry Andric }
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric
12910b57cec5SDimitry Andric // Store the arguments right after the definition of output value.
12920b57cec5SDimitry Andric // This should be proceeded after creating exit stubs to be ensure that invoke
12930b57cec5SDimitry Andric // result restore will be placed in the outlined function.
12940b57cec5SDimitry Andric Function::arg_iterator OAI = OutputArgBegin;
12950b57cec5SDimitry Andric for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
12960b57cec5SDimitry Andric auto *OutI = dyn_cast<Instruction>(outputs[i]);
12970b57cec5SDimitry Andric if (!OutI)
12980b57cec5SDimitry Andric continue;
12990b57cec5SDimitry Andric
13000b57cec5SDimitry Andric // Find proper insertion point.
13010b57cec5SDimitry Andric BasicBlock::iterator InsertPt;
13020b57cec5SDimitry Andric // In case OutI is an invoke, we insert the store at the beginning in the
13030b57cec5SDimitry Andric // 'normal destination' BB. Otherwise we insert the store right after OutI.
13040b57cec5SDimitry Andric if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
13050b57cec5SDimitry Andric InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
13060b57cec5SDimitry Andric else if (auto *Phi = dyn_cast<PHINode>(OutI))
13070b57cec5SDimitry Andric InsertPt = Phi->getParent()->getFirstInsertionPt();
13080b57cec5SDimitry Andric else
13090b57cec5SDimitry Andric InsertPt = std::next(OutI->getIterator());
13100b57cec5SDimitry Andric
13110b57cec5SDimitry Andric Instruction *InsertBefore = &*InsertPt;
13120b57cec5SDimitry Andric assert((InsertBefore->getFunction() == newFunction ||
13130b57cec5SDimitry Andric Blocks.count(InsertBefore->getParent())) &&
13140b57cec5SDimitry Andric "InsertPt should be in new function");
13150b57cec5SDimitry Andric assert(OAI != newFunction->arg_end() &&
13160b57cec5SDimitry Andric "Number of output arguments should match "
13170b57cec5SDimitry Andric "the amount of defined values");
13180b57cec5SDimitry Andric if (AggregateArgs) {
13190b57cec5SDimitry Andric Value *Idx[2];
13200b57cec5SDimitry Andric Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
13210b57cec5SDimitry Andric Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
13220b57cec5SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create(
13230b57cec5SDimitry Andric StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(),
13240b57cec5SDimitry Andric InsertBefore);
13250b57cec5SDimitry Andric new StoreInst(outputs[i], GEP, InsertBefore);
13260b57cec5SDimitry Andric // Since there should be only one struct argument aggregating
13270b57cec5SDimitry Andric // all the output values, we shouldn't increment OAI, which always
13280b57cec5SDimitry Andric // points to the struct argument, in this case.
13290b57cec5SDimitry Andric } else {
13300b57cec5SDimitry Andric new StoreInst(outputs[i], &*OAI, InsertBefore);
13310b57cec5SDimitry Andric ++OAI;
13320b57cec5SDimitry Andric }
13330b57cec5SDimitry Andric }
13340b57cec5SDimitry Andric
13350b57cec5SDimitry Andric // Now that we've done the deed, simplify the switch instruction.
13360b57cec5SDimitry Andric Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
13370b57cec5SDimitry Andric switch (NumExitBlocks) {
13380b57cec5SDimitry Andric case 0:
13390b57cec5SDimitry Andric // There are no successors (the block containing the switch itself), which
13400b57cec5SDimitry Andric // means that previously this was the last part of the function, and hence
13410b57cec5SDimitry Andric // this should be rewritten as a `ret'
13420b57cec5SDimitry Andric
13430b57cec5SDimitry Andric // Check if the function should return a value
13440b57cec5SDimitry Andric if (OldFnRetTy->isVoidTy()) {
13450b57cec5SDimitry Andric ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
13460b57cec5SDimitry Andric } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
13470b57cec5SDimitry Andric // return what we have
13480b57cec5SDimitry Andric ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
13490b57cec5SDimitry Andric } else {
13500b57cec5SDimitry Andric // Otherwise we must have code extracted an unwind or something, just
13510b57cec5SDimitry Andric // return whatever we want.
13520b57cec5SDimitry Andric ReturnInst::Create(Context,
13530b57cec5SDimitry Andric Constant::getNullValue(OldFnRetTy), TheSwitch);
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric
13560b57cec5SDimitry Andric TheSwitch->eraseFromParent();
13570b57cec5SDimitry Andric break;
13580b57cec5SDimitry Andric case 1:
13590b57cec5SDimitry Andric // Only a single destination, change the switch into an unconditional
13600b57cec5SDimitry Andric // branch.
13610b57cec5SDimitry Andric BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
13620b57cec5SDimitry Andric TheSwitch->eraseFromParent();
13630b57cec5SDimitry Andric break;
13640b57cec5SDimitry Andric case 2:
13650b57cec5SDimitry Andric BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
13660b57cec5SDimitry Andric call, TheSwitch);
13670b57cec5SDimitry Andric TheSwitch->eraseFromParent();
13680b57cec5SDimitry Andric break;
13690b57cec5SDimitry Andric default:
13700b57cec5SDimitry Andric // Otherwise, make the default destination of the switch instruction be one
13710b57cec5SDimitry Andric // of the other successors.
13720b57cec5SDimitry Andric TheSwitch->setCondition(call);
13730b57cec5SDimitry Andric TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
13740b57cec5SDimitry Andric // Remove redundant case
13750b57cec5SDimitry Andric TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
13760b57cec5SDimitry Andric break;
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric
13790b57cec5SDimitry Andric // Insert lifetime markers around the reloads of any output values. The
13800b57cec5SDimitry Andric // allocas output values are stored in are only in-use in the codeRepl block.
13810b57cec5SDimitry Andric insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call);
13820b57cec5SDimitry Andric
13830b57cec5SDimitry Andric return call;
13840b57cec5SDimitry Andric }
13850b57cec5SDimitry Andric
moveCodeToFunction(Function * newFunction)13860b57cec5SDimitry Andric void CodeExtractor::moveCodeToFunction(Function *newFunction) {
13870b57cec5SDimitry Andric Function *oldFunc = (*Blocks.begin())->getParent();
13880b57cec5SDimitry Andric Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
13890b57cec5SDimitry Andric Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
13900b57cec5SDimitry Andric
13910b57cec5SDimitry Andric for (BasicBlock *Block : Blocks) {
13920b57cec5SDimitry Andric // Delete the basic block from the old function, and the list of blocks
13930b57cec5SDimitry Andric oldBlocks.remove(Block);
13940b57cec5SDimitry Andric
13950b57cec5SDimitry Andric // Insert this basic block into the new function
13960b57cec5SDimitry Andric newBlocks.push_back(Block);
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric }
13990b57cec5SDimitry Andric
calculateNewCallTerminatorWeights(BasicBlock * CodeReplacer,DenseMap<BasicBlock *,BlockFrequency> & ExitWeights,BranchProbabilityInfo * BPI)14000b57cec5SDimitry Andric void CodeExtractor::calculateNewCallTerminatorWeights(
14010b57cec5SDimitry Andric BasicBlock *CodeReplacer,
14020b57cec5SDimitry Andric DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
14030b57cec5SDimitry Andric BranchProbabilityInfo *BPI) {
14040b57cec5SDimitry Andric using Distribution = BlockFrequencyInfoImplBase::Distribution;
14050b57cec5SDimitry Andric using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
14060b57cec5SDimitry Andric
14070b57cec5SDimitry Andric // Update the branch weights for the exit block.
14080b57cec5SDimitry Andric Instruction *TI = CodeReplacer->getTerminator();
14090b57cec5SDimitry Andric SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
14100b57cec5SDimitry Andric
14110b57cec5SDimitry Andric // Block Frequency distribution with dummy node.
14120b57cec5SDimitry Andric Distribution BranchDist;
14130b57cec5SDimitry Andric
14145ffd83dbSDimitry Andric SmallVector<BranchProbability, 4> EdgeProbabilities(
14155ffd83dbSDimitry Andric TI->getNumSuccessors(), BranchProbability::getUnknown());
14165ffd83dbSDimitry Andric
14170b57cec5SDimitry Andric // Add each of the frequencies of the successors.
14180b57cec5SDimitry Andric for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
14190b57cec5SDimitry Andric BlockNode ExitNode(i);
14200b57cec5SDimitry Andric uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
14210b57cec5SDimitry Andric if (ExitFreq != 0)
14220b57cec5SDimitry Andric BranchDist.addExit(ExitNode, ExitFreq);
14230b57cec5SDimitry Andric else
14245ffd83dbSDimitry Andric EdgeProbabilities[i] = BranchProbability::getZero();
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric
14270b57cec5SDimitry Andric // Check for no total weight.
14285ffd83dbSDimitry Andric if (BranchDist.Total == 0) {
14295ffd83dbSDimitry Andric BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
14300b57cec5SDimitry Andric return;
14315ffd83dbSDimitry Andric }
14320b57cec5SDimitry Andric
14330b57cec5SDimitry Andric // Normalize the distribution so that they can fit in unsigned.
14340b57cec5SDimitry Andric BranchDist.normalize();
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric // Create normalized branch weights and set the metadata.
14370b57cec5SDimitry Andric for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
14380b57cec5SDimitry Andric const auto &Weight = BranchDist.Weights[I];
14390b57cec5SDimitry Andric
14400b57cec5SDimitry Andric // Get the weight and update the current BFI.
14410b57cec5SDimitry Andric BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
14420b57cec5SDimitry Andric BranchProbability BP(Weight.Amount, BranchDist.Total);
14435ffd83dbSDimitry Andric EdgeProbabilities[Weight.TargetNode.Index] = BP;
14440b57cec5SDimitry Andric }
14455ffd83dbSDimitry Andric BPI->setEdgeProbability(CodeReplacer, EdgeProbabilities);
14460b57cec5SDimitry Andric TI->setMetadata(
14470b57cec5SDimitry Andric LLVMContext::MD_prof,
14480b57cec5SDimitry Andric MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
14490b57cec5SDimitry Andric }
14500b57cec5SDimitry Andric
14515ffd83dbSDimitry Andric /// Erase debug info intrinsics which refer to values in \p F but aren't in
14525ffd83dbSDimitry Andric /// \p F.
eraseDebugIntrinsicsWithNonLocalRefs(Function & F)14535ffd83dbSDimitry Andric static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) {
14545ffd83dbSDimitry Andric for (Instruction &I : instructions(F)) {
14555ffd83dbSDimitry Andric SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
14565ffd83dbSDimitry Andric findDbgUsers(DbgUsers, &I);
14575ffd83dbSDimitry Andric for (DbgVariableIntrinsic *DVI : DbgUsers)
14585ffd83dbSDimitry Andric if (DVI->getFunction() != &F)
14595ffd83dbSDimitry Andric DVI->eraseFromParent();
14605ffd83dbSDimitry Andric }
14615ffd83dbSDimitry Andric }
14625ffd83dbSDimitry Andric
14635ffd83dbSDimitry Andric /// Fix up the debug info in the old and new functions by pointing line
14645ffd83dbSDimitry Andric /// locations and debug intrinsics to the new subprogram scope, and by deleting
14655ffd83dbSDimitry Andric /// intrinsics which point to values outside of the new function.
fixupDebugInfoPostExtraction(Function & OldFunc,Function & NewFunc,CallInst & TheCall)14665ffd83dbSDimitry Andric static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
14675ffd83dbSDimitry Andric CallInst &TheCall) {
14685ffd83dbSDimitry Andric DISubprogram *OldSP = OldFunc.getSubprogram();
14695ffd83dbSDimitry Andric LLVMContext &Ctx = OldFunc.getContext();
14705ffd83dbSDimitry Andric
14715ffd83dbSDimitry Andric if (!OldSP) {
14725ffd83dbSDimitry Andric // Erase any debug info the new function contains.
14735ffd83dbSDimitry Andric stripDebugInfo(NewFunc);
14745ffd83dbSDimitry Andric // Make sure the old function doesn't contain any non-local metadata refs.
14755ffd83dbSDimitry Andric eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);
14765ffd83dbSDimitry Andric return;
14775ffd83dbSDimitry Andric }
14785ffd83dbSDimitry Andric
14795ffd83dbSDimitry Andric // Create a subprogram for the new function. Leave out a description of the
14805ffd83dbSDimitry Andric // function arguments, as the parameters don't correspond to anything at the
14815ffd83dbSDimitry Andric // source level.
14825ffd83dbSDimitry Andric assert(OldSP->getUnit() && "Missing compile unit for subprogram");
1483af732203SDimitry Andric DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,
14845ffd83dbSDimitry Andric OldSP->getUnit());
14855ffd83dbSDimitry Andric auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
14865ffd83dbSDimitry Andric DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |
14875ffd83dbSDimitry Andric DISubprogram::SPFlagOptimized |
14885ffd83dbSDimitry Andric DISubprogram::SPFlagLocalToUnit;
14895ffd83dbSDimitry Andric auto NewSP = DIB.createFunction(
14905ffd83dbSDimitry Andric OldSP->getUnit(), NewFunc.getName(), NewFunc.getName(), OldSP->getFile(),
14915ffd83dbSDimitry Andric /*LineNo=*/0, SPType, /*ScopeLine=*/0, DINode::FlagZero, SPFlags);
14925ffd83dbSDimitry Andric NewFunc.setSubprogram(NewSP);
14935ffd83dbSDimitry Andric
14945ffd83dbSDimitry Andric // Debug intrinsics in the new function need to be updated in one of two
14955ffd83dbSDimitry Andric // ways:
14965ffd83dbSDimitry Andric // 1) They need to be deleted, because they describe a value in the old
14975ffd83dbSDimitry Andric // function.
14985ffd83dbSDimitry Andric // 2) They need to point to fresh metadata, e.g. because they currently
14995ffd83dbSDimitry Andric // point to a variable in the wrong scope.
15005ffd83dbSDimitry Andric SmallDenseMap<DINode *, DINode *> RemappedMetadata;
15015ffd83dbSDimitry Andric SmallVector<Instruction *, 4> DebugIntrinsicsToDelete;
15025ffd83dbSDimitry Andric for (Instruction &I : instructions(NewFunc)) {
15035ffd83dbSDimitry Andric auto *DII = dyn_cast<DbgInfoIntrinsic>(&I);
15045ffd83dbSDimitry Andric if (!DII)
15055ffd83dbSDimitry Andric continue;
15065ffd83dbSDimitry Andric
15075ffd83dbSDimitry Andric // Point the intrinsic to a fresh label within the new function.
15085ffd83dbSDimitry Andric if (auto *DLI = dyn_cast<DbgLabelInst>(&I)) {
15095ffd83dbSDimitry Andric DILabel *OldLabel = DLI->getLabel();
15105ffd83dbSDimitry Andric DINode *&NewLabel = RemappedMetadata[OldLabel];
15115ffd83dbSDimitry Andric if (!NewLabel)
15125ffd83dbSDimitry Andric NewLabel = DILabel::get(Ctx, NewSP, OldLabel->getName(),
15135ffd83dbSDimitry Andric OldLabel->getFile(), OldLabel->getLine());
15145ffd83dbSDimitry Andric DLI->setArgOperand(0, MetadataAsValue::get(Ctx, NewLabel));
15155ffd83dbSDimitry Andric continue;
15165ffd83dbSDimitry Andric }
15175ffd83dbSDimitry Andric
1518*5f7ddb14SDimitry Andric auto IsInvalidLocation = [&NewFunc](Value *Location) {
1519*5f7ddb14SDimitry Andric // Location is invalid if it isn't a constant or an instruction, or is an
1520*5f7ddb14SDimitry Andric // instruction but isn't in the new function.
15215ffd83dbSDimitry Andric if (!Location ||
1522*5f7ddb14SDimitry Andric (!isa<Constant>(Location) && !isa<Instruction>(Location)))
1523*5f7ddb14SDimitry Andric return true;
15245ffd83dbSDimitry Andric Instruction *LocationInst = dyn_cast<Instruction>(Location);
1525*5f7ddb14SDimitry Andric return LocationInst && LocationInst->getFunction() != &NewFunc;
1526*5f7ddb14SDimitry Andric };
1527*5f7ddb14SDimitry Andric
1528*5f7ddb14SDimitry Andric auto *DVI = cast<DbgVariableIntrinsic>(DII);
1529*5f7ddb14SDimitry Andric // If any of the used locations are invalid, delete the intrinsic.
1530*5f7ddb14SDimitry Andric if (any_of(DVI->location_ops(), IsInvalidLocation)) {
15315ffd83dbSDimitry Andric DebugIntrinsicsToDelete.push_back(DVI);
15325ffd83dbSDimitry Andric continue;
15335ffd83dbSDimitry Andric }
15345ffd83dbSDimitry Andric
15355ffd83dbSDimitry Andric // Point the intrinsic to a fresh variable within the new function.
15365ffd83dbSDimitry Andric DILocalVariable *OldVar = DVI->getVariable();
15375ffd83dbSDimitry Andric DINode *&NewVar = RemappedMetadata[OldVar];
15385ffd83dbSDimitry Andric if (!NewVar)
15395ffd83dbSDimitry Andric NewVar = DIB.createAutoVariable(
15405ffd83dbSDimitry Andric NewSP, OldVar->getName(), OldVar->getFile(), OldVar->getLine(),
15415ffd83dbSDimitry Andric OldVar->getType(), /*AlwaysPreserve=*/false, DINode::FlagZero,
15425ffd83dbSDimitry Andric OldVar->getAlignInBits());
1543*5f7ddb14SDimitry Andric DVI->setVariable(cast<DILocalVariable>(NewVar));
15445ffd83dbSDimitry Andric }
15455ffd83dbSDimitry Andric for (auto *DII : DebugIntrinsicsToDelete)
15465ffd83dbSDimitry Andric DII->eraseFromParent();
15475ffd83dbSDimitry Andric DIB.finalizeSubprogram(NewSP);
15485ffd83dbSDimitry Andric
15495ffd83dbSDimitry Andric // Fix up the scope information attached to the line locations in the new
15505ffd83dbSDimitry Andric // function.
15515ffd83dbSDimitry Andric for (Instruction &I : instructions(NewFunc)) {
15525ffd83dbSDimitry Andric if (const DebugLoc &DL = I.getDebugLoc())
1553af732203SDimitry Andric I.setDebugLoc(DILocation::get(Ctx, DL.getLine(), DL.getCol(), NewSP));
15545ffd83dbSDimitry Andric
15555ffd83dbSDimitry Andric // Loop info metadata may contain line locations. Fix them up.
1556*5f7ddb14SDimitry Andric auto updateLoopInfoLoc = [&Ctx, NewSP](Metadata *MD) -> Metadata * {
1557*5f7ddb14SDimitry Andric if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
1558*5f7ddb14SDimitry Andric return DILocation::get(Ctx, Loc->getLine(), Loc->getColumn(), NewSP,
15595ffd83dbSDimitry Andric nullptr);
1560*5f7ddb14SDimitry Andric return MD;
15615ffd83dbSDimitry Andric };
15625ffd83dbSDimitry Andric updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);
15635ffd83dbSDimitry Andric }
15645ffd83dbSDimitry Andric if (!TheCall.getDebugLoc())
1565af732203SDimitry Andric TheCall.setDebugLoc(DILocation::get(Ctx, 0, 0, OldSP));
15665ffd83dbSDimitry Andric
15675ffd83dbSDimitry Andric eraseDebugIntrinsicsWithNonLocalRefs(NewFunc);
15685ffd83dbSDimitry Andric }
15695ffd83dbSDimitry Andric
15708bcb0991SDimitry Andric Function *
extractCodeRegion(const CodeExtractorAnalysisCache & CEAC)15718bcb0991SDimitry Andric CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) {
15720b57cec5SDimitry Andric if (!isEligible())
15730b57cec5SDimitry Andric return nullptr;
15740b57cec5SDimitry Andric
15750b57cec5SDimitry Andric // Assumption: this is a single-entry code region, and the header is the first
15760b57cec5SDimitry Andric // block in the region.
15770b57cec5SDimitry Andric BasicBlock *header = *Blocks.begin();
15780b57cec5SDimitry Andric Function *oldFunction = header->getParent();
15790b57cec5SDimitry Andric
15800b57cec5SDimitry Andric // Calculate the entry frequency of the new function before we change the root
15810b57cec5SDimitry Andric // block.
15820b57cec5SDimitry Andric BlockFrequency EntryFreq;
15830b57cec5SDimitry Andric if (BFI) {
15840b57cec5SDimitry Andric assert(BPI && "Both BPI and BFI are required to preserve profile info");
15850b57cec5SDimitry Andric for (BasicBlock *Pred : predecessors(header)) {
15860b57cec5SDimitry Andric if (Blocks.count(Pred))
15870b57cec5SDimitry Andric continue;
15880b57cec5SDimitry Andric EntryFreq +=
15890b57cec5SDimitry Andric BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric }
15920b57cec5SDimitry Andric
15935ffd83dbSDimitry Andric // Remove @llvm.assume calls that will be moved to the new function from the
15948bcb0991SDimitry Andric // old function's assumption cache.
15955ffd83dbSDimitry Andric for (BasicBlock *Block : Blocks) {
15965ffd83dbSDimitry Andric for (auto It = Block->begin(), End = Block->end(); It != End;) {
15975ffd83dbSDimitry Andric Instruction *I = &*It;
15985ffd83dbSDimitry Andric ++It;
15995ffd83dbSDimitry Andric
1600*5f7ddb14SDimitry Andric if (auto *AI = dyn_cast<AssumeInst>(I)) {
16015ffd83dbSDimitry Andric if (AC)
1602*5f7ddb14SDimitry Andric AC->unregisterAssumption(AI);
1603*5f7ddb14SDimitry Andric AI->eraseFromParent();
16045ffd83dbSDimitry Andric }
16055ffd83dbSDimitry Andric }
16068bcb0991SDimitry Andric }
16078bcb0991SDimitry Andric
16080b57cec5SDimitry Andric // If we have any return instructions in the region, split those blocks so
16090b57cec5SDimitry Andric // that the return is not in the region.
16100b57cec5SDimitry Andric splitReturnBlocks();
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric // Calculate the exit blocks for the extracted region and the total exit
16130b57cec5SDimitry Andric // weights for each of those blocks.
16140b57cec5SDimitry Andric DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
16150b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 1> ExitBlocks;
16160b57cec5SDimitry Andric for (BasicBlock *Block : Blocks) {
1617*5f7ddb14SDimitry Andric for (BasicBlock *Succ : successors(Block)) {
1618*5f7ddb14SDimitry Andric if (!Blocks.count(Succ)) {
16190b57cec5SDimitry Andric // Update the branch weight for this successor.
16200b57cec5SDimitry Andric if (BFI) {
1621*5f7ddb14SDimitry Andric BlockFrequency &BF = ExitWeights[Succ];
1622*5f7ddb14SDimitry Andric BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, Succ);
16230b57cec5SDimitry Andric }
1624*5f7ddb14SDimitry Andric ExitBlocks.insert(Succ);
16250b57cec5SDimitry Andric }
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric NumExitBlocks = ExitBlocks.size();
16290b57cec5SDimitry Andric
16300b57cec5SDimitry Andric // If we have to split PHI nodes of the entry or exit blocks, do so now.
16310b57cec5SDimitry Andric severSplitPHINodesOfEntry(header);
16320b57cec5SDimitry Andric severSplitPHINodesOfExits(ExitBlocks);
16330b57cec5SDimitry Andric
16340b57cec5SDimitry Andric // This takes place of the original loop
16350b57cec5SDimitry Andric BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
16360b57cec5SDimitry Andric "codeRepl", oldFunction,
16370b57cec5SDimitry Andric header);
16380b57cec5SDimitry Andric
16390b57cec5SDimitry Andric // The new function needs a root node because other nodes can branch to the
16400b57cec5SDimitry Andric // head of the region, but the entry node of a function cannot have preds.
16410b57cec5SDimitry Andric BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
16420b57cec5SDimitry Andric "newFuncRoot");
16430b57cec5SDimitry Andric auto *BranchI = BranchInst::Create(header);
16440b57cec5SDimitry Andric // If the original function has debug info, we have to add a debug location
16450b57cec5SDimitry Andric // to the new branch instruction from the artificial entry block.
16460b57cec5SDimitry Andric // We use the debug location of the first instruction in the extracted
16470b57cec5SDimitry Andric // blocks, as there is no other equivalent line in the source code.
16480b57cec5SDimitry Andric if (oldFunction->getSubprogram()) {
16490b57cec5SDimitry Andric any_of(Blocks, [&BranchI](const BasicBlock *BB) {
16500b57cec5SDimitry Andric return any_of(*BB, [&BranchI](const Instruction &I) {
16510b57cec5SDimitry Andric if (!I.getDebugLoc())
16520b57cec5SDimitry Andric return false;
16530b57cec5SDimitry Andric BranchI->setDebugLoc(I.getDebugLoc());
16540b57cec5SDimitry Andric return true;
16550b57cec5SDimitry Andric });
16560b57cec5SDimitry Andric });
16570b57cec5SDimitry Andric }
16580b57cec5SDimitry Andric newFuncRoot->getInstList().push_back(BranchI);
16590b57cec5SDimitry Andric
16608bcb0991SDimitry Andric ValueSet inputs, outputs, SinkingCands, HoistingCands;
16618bcb0991SDimitry Andric BasicBlock *CommonExit = nullptr;
16628bcb0991SDimitry Andric findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
16630b57cec5SDimitry Andric assert(HoistingCands.empty() || CommonExit);
16640b57cec5SDimitry Andric
16650b57cec5SDimitry Andric // Find inputs to, outputs from the code region.
16660b57cec5SDimitry Andric findInputsOutputs(inputs, outputs, SinkingCands);
16670b57cec5SDimitry Andric
16680b57cec5SDimitry Andric // Now sink all instructions which only have non-phi uses inside the region.
16690b57cec5SDimitry Andric // Group the allocas at the start of the block, so that any bitcast uses of
16700b57cec5SDimitry Andric // the allocas are well-defined.
16710b57cec5SDimitry Andric AllocaInst *FirstSunkAlloca = nullptr;
16720b57cec5SDimitry Andric for (auto *II : SinkingCands) {
16730b57cec5SDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(II)) {
16740b57cec5SDimitry Andric AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt());
16750b57cec5SDimitry Andric if (!FirstSunkAlloca)
16760b57cec5SDimitry Andric FirstSunkAlloca = AI;
16770b57cec5SDimitry Andric }
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric assert((SinkingCands.empty() || FirstSunkAlloca) &&
16800b57cec5SDimitry Andric "Did not expect a sink candidate without any allocas");
16810b57cec5SDimitry Andric for (auto *II : SinkingCands) {
16820b57cec5SDimitry Andric if (!isa<AllocaInst>(II)) {
16830b57cec5SDimitry Andric cast<Instruction>(II)->moveAfter(FirstSunkAlloca);
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric }
16860b57cec5SDimitry Andric
16870b57cec5SDimitry Andric if (!HoistingCands.empty()) {
16880b57cec5SDimitry Andric auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
16890b57cec5SDimitry Andric Instruction *TI = HoistToBlock->getTerminator();
16900b57cec5SDimitry Andric for (auto *II : HoistingCands)
16910b57cec5SDimitry Andric cast<Instruction>(II)->moveBefore(TI);
16920b57cec5SDimitry Andric }
16930b57cec5SDimitry Andric
16940b57cec5SDimitry Andric // Collect objects which are inputs to the extraction region and also
16950b57cec5SDimitry Andric // referenced by lifetime start markers within it. The effects of these
16960b57cec5SDimitry Andric // markers must be replicated in the calling function to prevent the stack
16970b57cec5SDimitry Andric // coloring pass from merging slots which store input objects.
16980b57cec5SDimitry Andric ValueSet LifetimesStart;
16990b57cec5SDimitry Andric eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart);
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric // Construct new function based on inputs/outputs & add allocas for all defs.
17020b57cec5SDimitry Andric Function *newFunction =
17030b57cec5SDimitry Andric constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
17040b57cec5SDimitry Andric oldFunction, oldFunction->getParent());
17050b57cec5SDimitry Andric
17060b57cec5SDimitry Andric // Update the entry count of the function.
17070b57cec5SDimitry Andric if (BFI) {
17080b57cec5SDimitry Andric auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
17090b57cec5SDimitry Andric if (Count.hasValue())
17100b57cec5SDimitry Andric newFunction->setEntryCount(
17110b57cec5SDimitry Andric ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
17120b57cec5SDimitry Andric BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric CallInst *TheCall =
17160b57cec5SDimitry Andric emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
17170b57cec5SDimitry Andric
17180b57cec5SDimitry Andric moveCodeToFunction(newFunction);
17190b57cec5SDimitry Andric
17200b57cec5SDimitry Andric // Replicate the effects of any lifetime start/end markers which referenced
17210b57cec5SDimitry Andric // input objects in the extraction region by placing markers around the call.
17220b57cec5SDimitry Andric insertLifetimeMarkersSurroundingCall(
17230b57cec5SDimitry Andric oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall);
17240b57cec5SDimitry Andric
17250b57cec5SDimitry Andric // Propagate personality info to the new function if there is one.
17260b57cec5SDimitry Andric if (oldFunction->hasPersonalityFn())
17270b57cec5SDimitry Andric newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
17280b57cec5SDimitry Andric
17290b57cec5SDimitry Andric // Update the branch weights for the exit block.
17300b57cec5SDimitry Andric if (BFI && NumExitBlocks > 1)
17310b57cec5SDimitry Andric calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
17320b57cec5SDimitry Andric
17330b57cec5SDimitry Andric // Loop over all of the PHI nodes in the header and exit blocks, and change
17340b57cec5SDimitry Andric // any references to the old incoming edge to be the new incoming edge.
17350b57cec5SDimitry Andric for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
17360b57cec5SDimitry Andric PHINode *PN = cast<PHINode>(I);
17370b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
17380b57cec5SDimitry Andric if (!Blocks.count(PN->getIncomingBlock(i)))
17390b57cec5SDimitry Andric PN->setIncomingBlock(i, newFuncRoot);
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric
17420b57cec5SDimitry Andric for (BasicBlock *ExitBB : ExitBlocks)
17430b57cec5SDimitry Andric for (PHINode &PN : ExitBB->phis()) {
17440b57cec5SDimitry Andric Value *IncomingCodeReplacerVal = nullptr;
17450b57cec5SDimitry Andric for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
17460b57cec5SDimitry Andric // Ignore incoming values from outside of the extracted region.
17470b57cec5SDimitry Andric if (!Blocks.count(PN.getIncomingBlock(i)))
17480b57cec5SDimitry Andric continue;
17490b57cec5SDimitry Andric
17500b57cec5SDimitry Andric // Ensure that there is only one incoming value from codeReplacer.
17510b57cec5SDimitry Andric if (!IncomingCodeReplacerVal) {
17520b57cec5SDimitry Andric PN.setIncomingBlock(i, codeReplacer);
17530b57cec5SDimitry Andric IncomingCodeReplacerVal = PN.getIncomingValue(i);
17540b57cec5SDimitry Andric } else
17550b57cec5SDimitry Andric assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
17560b57cec5SDimitry Andric "PHI has two incompatbile incoming values from codeRepl");
17570b57cec5SDimitry Andric }
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric
17605ffd83dbSDimitry Andric fixupDebugInfoPostExtraction(*oldFunction, *newFunction, *TheCall);
17610b57cec5SDimitry Andric
17620b57cec5SDimitry Andric // Mark the new function `noreturn` if applicable. Terminators which resume
17630b57cec5SDimitry Andric // exception propagation are treated as returning instructions. This is to
17640b57cec5SDimitry Andric // avoid inserting traps after calls to outlined functions which unwind.
17650b57cec5SDimitry Andric bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
17660b57cec5SDimitry Andric const Instruction *Term = BB.getTerminator();
17670b57cec5SDimitry Andric return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
17680b57cec5SDimitry Andric });
17690b57cec5SDimitry Andric if (doesNotReturn)
17700b57cec5SDimitry Andric newFunction->setDoesNotReturn();
17710b57cec5SDimitry Andric
17720b57cec5SDimitry Andric LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
17730b57cec5SDimitry Andric newFunction->dump();
17740b57cec5SDimitry Andric report_fatal_error("verification of newFunction failed!");
17750b57cec5SDimitry Andric });
17760b57cec5SDimitry Andric LLVM_DEBUG(if (verifyFunction(*oldFunction))
17770b57cec5SDimitry Andric report_fatal_error("verification of oldFunction failed!"));
17785ffd83dbSDimitry Andric LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))
17798bcb0991SDimitry Andric report_fatal_error("Stale Asumption cache for old Function!"));
17800b57cec5SDimitry Andric return newFunction;
17810b57cec5SDimitry Andric }
17828bcb0991SDimitry Andric
verifyAssumptionCache(const Function & OldFunc,const Function & NewFunc,AssumptionCache * AC)17835ffd83dbSDimitry Andric bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
17845ffd83dbSDimitry Andric const Function &NewFunc,
17858bcb0991SDimitry Andric AssumptionCache *AC) {
17868bcb0991SDimitry Andric for (auto AssumeVH : AC->assumptions()) {
1787af732203SDimitry Andric auto *I = dyn_cast_or_null<CallInst>(AssumeVH);
17885ffd83dbSDimitry Andric if (!I)
17895ffd83dbSDimitry Andric continue;
17905ffd83dbSDimitry Andric
17915ffd83dbSDimitry Andric // There shouldn't be any llvm.assume intrinsics in the new function.
17925ffd83dbSDimitry Andric if (I->getFunction() != &OldFunc)
17938bcb0991SDimitry Andric return true;
17945ffd83dbSDimitry Andric
17955ffd83dbSDimitry Andric // There shouldn't be any stale affected values in the assumption cache
17965ffd83dbSDimitry Andric // that were previously in the old function, but that have now been moved
17975ffd83dbSDimitry Andric // to the new function.
17985ffd83dbSDimitry Andric for (auto AffectedValVH : AC->assumptionsFor(I->getOperand(0))) {
1799af732203SDimitry Andric auto *AffectedCI = dyn_cast_or_null<CallInst>(AffectedValVH);
18005ffd83dbSDimitry Andric if (!AffectedCI)
18015ffd83dbSDimitry Andric continue;
18025ffd83dbSDimitry Andric if (AffectedCI->getFunction() != &OldFunc)
18035ffd83dbSDimitry Andric return true;
1804af732203SDimitry Andric auto *AssumedInst = cast<Instruction>(AffectedCI->getOperand(0));
18055ffd83dbSDimitry Andric if (AssumedInst->getFunction() != &OldFunc)
18065ffd83dbSDimitry Andric return true;
18075ffd83dbSDimitry Andric }
18088bcb0991SDimitry Andric }
18098bcb0991SDimitry Andric return false;
18108bcb0991SDimitry Andric }
1811