#include "llvm/Transforms/IPO/MergeFunctions.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/FunctionComparator.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <set>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "mergefunc"
STATISTIC(NumFunctionsMerged, "Number of functions merged");
STATISTIC(NumThunksWritten, "Number of thunks generated");
STATISTIC(NumAliasesWritten, "Number of aliases generated");
STATISTIC(NumDoubleWeak, "Number of new functions created");
static cl::opt<unsigned> NumFunctionsForVerificationCheck(
"mergefunc-verify",
cl::desc("How many functions in a module could be used for "
"MergeFunctions to pass a basic correctness check. "
"'0' disables this check. Works only with '-debug' key."),
cl::init(0), cl::Hidden);
static cl::opt<bool>
MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
cl::init(false),
cl::desc("Preserve debug info in thunk when mergefunc "
"transformations are made."));
static cl::opt<bool>
MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
cl::init(false),
cl::desc("Allow mergefunc to create aliases"));
namespace {
class FunctionNode {
mutable AssertingVH<Function> F;
FunctionComparator::FunctionHash Hash;
public:
FunctionNode(Function *F)
: F(F), Hash(FunctionComparator::functionHash(*F)) {}
Function *getFunc() const { return F; }
FunctionComparator::FunctionHash getHash() const { return Hash; }
void replaceBy(Function *G) const {
F = G;
}
};
class MergeFunctions {
public:
MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
}
bool runOnModule(Module &M);
private:
class FunctionNodeCmp {
GlobalNumberState* GlobalNumbers;
public:
FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
if (LHS.getHash() != RHS.getHash())
return LHS.getHash() < RHS.getHash();
FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
return FCmp.compare() == -1;
}
};
using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
GlobalNumberState GlobalNumbers;
std::vector<WeakTrackingVH> Deferred;
SmallPtrSet<GlobalValue *, 4> Used;
#ifndef NDEBUG
bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
#endif
bool insert(Function *NewFunction);
void remove(Function *F);
void removeUsers(Value *V);
void replaceDirectCallers(Function *Old, Function *New);
void mergeTwoFunctions(Function *F, Function *G);
void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
std::vector<Instruction *> &PDIUnrelatedWL);
void eraseTail(Function *G);
void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
void writeThunk(Function *F, Function *G);
void writeAlias(Function *F, Function *G);
bool writeThunkOrAlias(Function *F, Function *G);
void replaceFunctionInTree(const FunctionNode &FN, Function *G);
FnTreeType FnTree;
DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
};
class MergeFunctionsLegacyPass : public ModulePass {
public:
static char ID;
MergeFunctionsLegacyPass(): ModulePass(ID) {
initializeMergeFunctionsLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
MergeFunctions MF;
return MF.runOnModule(M);
}
};
}
char MergeFunctionsLegacyPass::ID = 0;
INITIALIZE_PASS(MergeFunctionsLegacyPass, "mergefunc",
"Merge Functions", false, false)
ModulePass *llvm::createMergeFunctionsPass() {
return new MergeFunctionsLegacyPass();
}
PreservedAnalyses MergeFunctionsPass::run(Module &M,
ModuleAnalysisManager &AM) {
MergeFunctions MF;
if (!MF.runOnModule(M))
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}
#ifndef NDEBUG
bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
if (const unsigned Max = NumFunctionsForVerificationCheck) {
unsigned TripleNumber = 0;
bool Valid = true;
dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
unsigned i = 0;
for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
E = Worklist.end();
I != E && i < Max; ++I, ++i) {
unsigned j = i;
for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
++J, ++j) {
Function *F1 = cast<Function>(*I);
Function *F2 = cast<Function>(*J);
int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
if (Res1 != -Res2) {
dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
<< "\n";
dbgs() << *F1 << '\n' << *F2 << '\n';
Valid = false;
}
if (Res1 == 0)
continue;
unsigned k = j;
for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
++k, ++K, ++TripleNumber) {
if (K == J)
continue;
Function *F3 = cast<Function>(*K);
int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
bool Transitive = true;
if (Res1 != 0 && Res1 == Res4) {
Transitive = Res3 == Res1;
} else if (Res3 != 0 && Res3 == -Res4) {
Transitive = Res3 == Res1;
} else if (Res4 != 0 && -Res3 == Res4) {
Transitive = Res4 == -Res1;
}
if (!Transitive) {
dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
<< TripleNumber << "\n";
dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
<< Res4 << "\n";
dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
Valid = false;
}
}
}
}
dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
return Valid;
}
return true;
}
#endif
static bool isEligibleForMerging(Function &F) {
return !F.isDeclaration() && !F.hasAvailableExternallyLinkage();
}
bool MergeFunctions::runOnModule(Module &M) {
bool Changed = false;
SmallVector<GlobalValue *, 4> UsedV;
collectUsedGlobalVariables(M, UsedV, false);
collectUsedGlobalVariables(M, UsedV, true);
Used.insert(UsedV.begin(), UsedV.end());
std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
HashedFuncs;
for (Function &Func : M) {
if (isEligibleForMerging(Func)) {
HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
}
}
llvm::stable_sort(HashedFuncs, less_first());
auto S = HashedFuncs.begin();
for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
if ((I != S && std::prev(I)->first == I->first) ||
(std::next(I) != IE && std::next(I)->first == I->first) ) {
Deferred.push_back(WeakTrackingVH(I->second));
}
}
do {
std::vector<WeakTrackingVH> Worklist;
Deferred.swap(Worklist);
LLVM_DEBUG(doFunctionalCheck(Worklist));
LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
for (WeakTrackingVH &I : Worklist) {
if (!I)
continue;
Function *F = cast<Function>(I);
if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Changed |= insert(F);
}
}
LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
} while (!Deferred.empty());
FnTree.clear();
FNodesInTree.clear();
GlobalNumbers.clear();
Used.clear();
return Changed;
}
void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
for (Use &U : llvm::make_early_inc_range(Old->uses())) {
CallBase *CB = dyn_cast<CallBase>(U.getUser());
if (CB && CB->isCallee(&U)) {
remove(CB->getFunction());
U.set(BitcastNew);
}
}
}
static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Type *SrcTy = V->getType();
if (SrcTy->isStructTy()) {
assert(DestTy->isStructTy());
assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
Value *Result = PoisonValue::get(DestTy);
for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
Value *Element = createCast(
Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
DestTy->getStructElementType(I));
Result =
Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
}
return Result;
}
assert(!DestTy->isStructTy());
if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
return Builder.CreateIntToPtr(V, DestTy);
else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
return Builder.CreatePtrToInt(V, DestTy);
else
return Builder.CreateBitCast(V, DestTy);
}
void MergeFunctions::eraseInstsUnrelatedToPDI(
std::vector<Instruction *> &PDIUnrelatedWL) {
LLVM_DEBUG(
dbgs() << " Erasing instructions (in reverse order of appearance in "
"entry block) unrelated to parameter debug info from entry "
"block: {\n");
while (!PDIUnrelatedWL.empty()) {
Instruction *I = PDIUnrelatedWL.back();
LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
LLVM_DEBUG(I->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
I->eraseFromParent();
PDIUnrelatedWL.pop_back();
}
LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
"debug info from entry block. \n");
}
void MergeFunctions::eraseTail(Function *G) {
std::vector<BasicBlock *> WorklistBB;
for (BasicBlock &BB : drop_begin(*G)) {
BB.dropAllReferences();
WorklistBB.push_back(&BB);
}
while (!WorklistBB.empty()) {
BasicBlock *BB = WorklistBB.back();
BB->eraseFromParent();
WorklistBB.pop_back();
}
}
void MergeFunctions::filterInstsUnrelatedToPDI(
BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
std::set<Instruction *> PDIRelated;
for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
BI != BIE; ++BI) {
if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
LLVM_DEBUG(dbgs() << " Deciding: ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
DILocalVariable *DILocVar = DVI->getVariable();
if (DILocVar->isParameter()) {
LLVM_DEBUG(dbgs() << " Include (parameter): ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIRelated.insert(&*BI);
} else {
LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
} else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
LLVM_DEBUG(dbgs() << " Deciding: ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
DILocalVariable *DILocVar = DDI->getVariable();
if (DILocVar->isParameter()) {
LLVM_DEBUG(dbgs() << " Parameter: ");
LLVM_DEBUG(DILocVar->print(dbgs()));
AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
if (AI) {
LLVM_DEBUG(dbgs() << " Processing alloca users: ");
LLVM_DEBUG(dbgs() << "\n");
for (User *U : AI->users()) {
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (Value *Arg = SI->getValueOperand()) {
if (isa<Argument>(Arg)) {
LLVM_DEBUG(dbgs() << " Include: ");
LLVM_DEBUG(AI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIRelated.insert(AI);
LLVM_DEBUG(dbgs() << " Include (parameter): ");
LLVM_DEBUG(SI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIRelated.insert(SI);
LLVM_DEBUG(dbgs() << " Include: ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIRelated.insert(&*BI);
} else {
LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
LLVM_DEBUG(SI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
}
} else {
LLVM_DEBUG(dbgs() << " Defer: ");
LLVM_DEBUG(U->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
}
} else {
LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
} else {
LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
} else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIRelated.insert(&*BI);
} else {
LLVM_DEBUG(dbgs() << " Defer: ");
LLVM_DEBUG(BI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
}
LLVM_DEBUG(
dbgs()
<< " Report parameter debug info related/related instructions: {\n");
for (Instruction &I : *GEntryBlock) {
if (PDIRelated.find(&I) == PDIRelated.end()) {
LLVM_DEBUG(dbgs() << " !PDIRelated: ");
LLVM_DEBUG(I.print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
PDIUnrelatedWL.push_back(&I);
} else {
LLVM_DEBUG(dbgs() << " PDIRelated: ");
LLVM_DEBUG(I.print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
}
}
LLVM_DEBUG(dbgs() << " }\n");
}
static bool canCreateThunkFor(Function *F) {
if (F->isVarArg())
return false;
if (F->size() == 1) {
if (F->front().size() <= 2) {
LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
<< " is too small to bother creating a thunk for\n");
return false;
}
}
return true;
}
void MergeFunctions::writeThunk(Function *F, Function *G) {
BasicBlock *GEntryBlock = nullptr;
std::vector<Instruction *> PDIUnrelatedWL;
BasicBlock *BB = nullptr;
Function *NewG = nullptr;
if (MergeFunctionsPDI) {
LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
"function as thunk; retain original: "
<< G->getName() << "()\n");
GEntryBlock = &G->getEntryBlock();
LLVM_DEBUG(
dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for "
<< G->getName() << "() {\n");
filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
GEntryBlock->getTerminator()->eraseFromParent();
BB = GEntryBlock;
} else {
NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
G->getAddressSpace(), "", G->getParent());
NewG->setComdat(G->getComdat());
BB = BasicBlock::Create(F->getContext(), "", NewG);
}
IRBuilder<> Builder(BB);
Function *H = MergeFunctionsPDI ? G : NewG;
SmallVector<Value *, 16> Args;
unsigned i = 0;
FunctionType *FFTy = F->getFunctionType();
for (Argument &AI : H->args()) {
Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
++i;
}
CallInst *CI = Builder.CreateCall(F, Args);
ReturnInst *RI = nullptr;
bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
G->getCallingConv() == CallingConv::SwiftTail;
CI->setTailCallKind(isSwiftTailCall ? llvm::CallInst::TCK_MustTail
: llvm::CallInst::TCK_Tail);
CI->setCallingConv(F->getCallingConv());
CI->setAttributes(F->getAttributes());
if (H->getReturnType()->isVoidTy()) {
RI = Builder.CreateRetVoid();
} else {
RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
}
if (MergeFunctionsPDI) {
DISubprogram *DIS = G->getSubprogram();
if (DIS) {
DebugLoc CIDbgLoc =
DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
DebugLoc RIDbgLoc =
DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
CI->setDebugLoc(CIDbgLoc);
RI->setDebugLoc(RIDbgLoc);
} else {
LLVM_DEBUG(
dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n");
}
eraseTail(G);
eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
LLVM_DEBUG(
dbgs() << "} // End of parameter related debug info filtering for: "
<< G->getName() << "()\n");
} else {
NewG->copyAttributesFrom(G);
NewG->takeName(G);
removeUsers(G);
G->replaceAllUsesWith(NewG);
G->eraseFromParent();
}
LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
++NumThunksWritten;
}
static bool canCreateAliasFor(Function *F) {
if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
return false;
assert(F->hasLocalLinkage() || F->hasExternalLinkage()
|| F->hasWeakLinkage() || F->hasLinkOnceLinkage());
return true;
}
void MergeFunctions::writeAlias(Function *F, Function *G) {
Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
PointerType *PtrType = G->getType();
auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(),
G->getLinkage(), "", BitcastF, G->getParent());
F->setAlignment(MaybeAlign(std::max(F->getAlignment(), G->getAlignment())));
GA->takeName(G);
GA->setVisibility(G->getVisibility());
GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
removeUsers(G);
G->replaceAllUsesWith(GA);
G->eraseFromParent();
LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
++NumAliasesWritten;
}
bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
if (canCreateAliasFor(G)) {
writeAlias(F, G);
return true;
}
if (canCreateThunkFor(F)) {
writeThunk(F, G);
return true;
}
return false;
}
void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
if (F->isInterposable()) {
assert(G->isInterposable());
if (!canCreateThunkFor(F) &&
(!canCreateAliasFor(F) || !canCreateAliasFor(G)))
return;
Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
F->getAddressSpace(), "", F->getParent());
NewF->copyAttributesFrom(F);
NewF->takeName(F);
removeUsers(F);
F->replaceAllUsesWith(NewF);
MaybeAlign MaxAlignment(std::max(G->getAlignment(), NewF->getAlignment()));
writeThunkOrAlias(F, G);
writeThunkOrAlias(F, NewF);
F->setAlignment(MaxAlignment);
F->setLinkage(GlobalValue::PrivateLinkage);
++NumDoubleWeak;
++NumFunctionsMerged;
} else {
if (!G->isInterposable() && !MergeFunctionsPDI) {
if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
GlobalNumbers.erase(G);
Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
removeUsers(G);
G->replaceAllUsesWith(BitcastF);
} else {
replaceDirectCallers(G, F);
}
}
if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
G->eraseFromParent();
++NumFunctionsMerged;
return;
}
if (writeThunkOrAlias(F, G)) {
++NumFunctionsMerged;
}
}
}
void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Function *G) {
Function *F = FN.getFunc();
assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
"The two functions must be equal");
auto I = FNodesInTree.find(F);
assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
FnTreeType::iterator IterToFNInFnTree = I->second;
assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
FNodesInTree.erase(I);
FNodesInTree.insert({G, IterToFNInFnTree});
FN.replaceBy(G);
}
static bool isFuncOrderCorrect(const Function *F, const Function *G) {
if (F->isInterposable() != G->isInterposable()) {
return !F->isInterposable();
}
if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
return !F->hasLocalLinkage();
}
return F->getName() <= G->getName();
}
bool MergeFunctions::insert(Function *NewFunction) {
std::pair<FnTreeType::iterator, bool> Result =
FnTree.insert(FunctionNode(NewFunction));
if (Result.second) {
assert(FNodesInTree.count(NewFunction) == 0);
FNodesInTree.insert({NewFunction, Result.first});
LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
<< '\n');
return false;
}
const FunctionNode &OldF = *Result.first;
if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
Function *F = OldF.getFunc();
replaceFunctionInTree(*Result.first, NewFunction);
NewFunction = F;
assert(OldF.getFunc() != F && "Must have swapped the functions.");
}
LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
<< " == " << NewFunction->getName() << '\n');
Function *DeleteF = NewFunction;
mergeTwoFunctions(OldF.getFunc(), DeleteF);
return true;
}
void MergeFunctions::remove(Function *F) {
auto I = FNodesInTree.find(F);
if (I != FNodesInTree.end()) {
LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
FnTree.erase(I->second);
FNodesInTree.erase(I);
Deferred.emplace_back(F);
}
}
void MergeFunctions::removeUsers(Value *V) {
for (User *U : V->users())
if (auto *I = dyn_cast<Instruction>(U))
remove(I->getFunction());
}