MergeFunctions.cpp [plain text]
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#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> NumFunctionsForSanityCheck(
"mergefunc-sanity",
cl::desc("How many functions in module could be used for "
"MergeFunctions pass sanity check. "
"'0' disables this check. Works only with '-debug' key."),
cl::init(0), cl::Hidden);
namespace {
class FunctionComparator {
public:
FunctionComparator(const Function *F1, const Function *F2)
: FnL(F1), FnR(F2) {}
int compare();
private:
int compare(const BasicBlock *BBL, const BasicBlock *BBR);
int cmpConstants(const Constant *L, const Constant *R);
int cmpValues(const Value *L, const Value *R);
int cmpOperations(const Instruction *L, const Instruction *R) const;
int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
}
int cmpTypes(Type *TyL, Type *TyR) const;
int cmpNumbers(uint64_t L, uint64_t R) const;
int cmpAPInts(const APInt &L, const APInt &R) const;
int cmpAPFloats(const APFloat &L, const APFloat &R) const;
int cmpStrings(StringRef L, StringRef R) const;
int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
const Function *FnL, *FnR;
DenseMap<const Value*, int> sn_mapL, sn_mapR;
};
class FunctionNode {
mutable AssertingVH<Function> F;
public:
FunctionNode(Function *F) : F(F) {}
Function *getFunc() const { return F; }
void replaceBy(Function *G) const {
assert(!(*this < FunctionNode(G)) && !(FunctionNode(G) < *this) &&
"The two functions must be equal");
F = G;
}
void release() { F = 0; }
bool operator<(const FunctionNode &RHS) const {
return (FunctionComparator(F, RHS.getFunc()).compare()) == -1;
}
};
}
int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
if (L < R) return -1;
if (L > R) return 1;
return 0;
}
int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
return Res;
if (L.ugt(R)) return 1;
if (R.ugt(L)) return -1;
return 0;
}
int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
(uint64_t)&R.getSemantics()))
return Res;
return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
}
int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
if (int Res = cmpNumbers(L.size(), R.size()))
return Res;
return L.compare(R);
}
int FunctionComparator::cmpAttrs(const AttributeSet L,
const AttributeSet R) const {
if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
return Res;
for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
RE = R.end(i);
for (; LI != LE && RI != RE; ++LI, ++RI) {
Attribute LA = *LI;
Attribute RA = *RI;
if (LA < RA)
return -1;
if (RA < LA)
return 1;
}
if (LI != LE)
return 1;
if (RI != RE)
return -1;
}
return 0;
}
int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
Type *TyL = L->getType();
Type *TyR = R->getType();
int TypesRes = cmpTypes(TyL, TyR);
if (TypesRes != 0) {
if (!TyL->isFirstClassType()) {
if (TyR->isFirstClassType())
return -1;
return TypesRes;
}
if (!TyR->isFirstClassType()) {
if (TyL->isFirstClassType())
return 1;
return TypesRes;
}
unsigned TyLWidth = 0;
unsigned TyRWidth = 0;
if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
TyLWidth = VecTyL->getBitWidth();
if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
TyRWidth = VecTyR->getBitWidth();
if (TyLWidth != TyRWidth)
return cmpNumbers(TyLWidth, TyRWidth);
if (!TyLWidth) {
PointerType *PTyL = dyn_cast<PointerType>(TyL);
PointerType *PTyR = dyn_cast<PointerType>(TyR);
if (PTyL && PTyR) {
unsigned AddrSpaceL = PTyL->getAddressSpace();
unsigned AddrSpaceR = PTyR->getAddressSpace();
if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
return Res;
}
if (PTyL)
return 1;
if (PTyR)
return -1;
return TypesRes;
}
}
if (L->isNullValue() && R->isNullValue())
return TypesRes;
if (L->isNullValue() && !R->isNullValue())
return 1;
if (!L->isNullValue() && R->isNullValue())
return -1;
if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
return Res;
switch (L->getValueID()) {
case Value::UndefValueVal: return TypesRes;
case Value::ConstantIntVal: {
const APInt &LInt = cast<ConstantInt>(L)->getValue();
const APInt &RInt = cast<ConstantInt>(R)->getValue();
return cmpAPInts(LInt, RInt);
}
case Value::ConstantFPVal: {
const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
return cmpAPFloats(LAPF, RAPF);
}
case Value::ConstantArrayVal: {
const ConstantArray *LA = cast<ConstantArray>(L);
const ConstantArray *RA = cast<ConstantArray>(R);
uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
if (int Res = cmpNumbers(NumElementsL, NumElementsR))
return Res;
for (uint64_t i = 0; i < NumElementsL; ++i) {
if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
cast<Constant>(RA->getOperand(i))))
return Res;
}
return 0;
}
case Value::ConstantStructVal: {
const ConstantStruct *LS = cast<ConstantStruct>(L);
const ConstantStruct *RS = cast<ConstantStruct>(R);
unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
if (int Res = cmpNumbers(NumElementsL, NumElementsR))
return Res;
for (unsigned i = 0; i != NumElementsL; ++i) {
if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
cast<Constant>(RS->getOperand(i))))
return Res;
}
return 0;
}
case Value::ConstantVectorVal: {
const ConstantVector *LV = cast<ConstantVector>(L);
const ConstantVector *RV = cast<ConstantVector>(R);
unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
if (int Res = cmpNumbers(NumElementsL, NumElementsR))
return Res;
for (uint64_t i = 0; i < NumElementsL; ++i) {
if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
cast<Constant>(RV->getOperand(i))))
return Res;
}
return 0;
}
case Value::ConstantExprVal: {
const ConstantExpr *LE = cast<ConstantExpr>(L);
const ConstantExpr *RE = cast<ConstantExpr>(R);
unsigned NumOperandsL = LE->getNumOperands();
unsigned NumOperandsR = RE->getNumOperands();
if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
return Res;
for (unsigned i = 0; i < NumOperandsL; ++i) {
if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
cast<Constant>(RE->getOperand(i))))
return Res;
}
return 0;
}
case Value::FunctionVal:
case Value::GlobalVariableVal:
case Value::GlobalAliasVal:
default: return cmpNumbers((uint64_t)L, (uint64_t)R);
}
}
int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
PointerType *PTyL = dyn_cast<PointerType>(TyL);
PointerType *PTyR = dyn_cast<PointerType>(TyR);
const DataLayout &DL = FnL->getParent()->getDataLayout();
if (PTyL && PTyL->getAddressSpace() == 0)
TyL = DL.getIntPtrType(TyL);
if (PTyR && PTyR->getAddressSpace() == 0)
TyR = DL.getIntPtrType(TyR);
if (TyL == TyR)
return 0;
if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
return Res;
switch (TyL->getTypeID()) {
default:
llvm_unreachable("Unknown type!");
case Type::IntegerTyID:
case Type::VectorTyID:
return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
case Type::VoidTyID:
case Type::FloatTyID:
case Type::DoubleTyID:
case Type::X86_FP80TyID:
case Type::FP128TyID:
case Type::PPC_FP128TyID:
case Type::LabelTyID:
case Type::MetadataTyID:
return 0;
case Type::PointerTyID: {
assert(PTyL && PTyR && "Both types must be pointers here.");
return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
}
case Type::StructTyID: {
StructType *STyL = cast<StructType>(TyL);
StructType *STyR = cast<StructType>(TyR);
if (STyL->getNumElements() != STyR->getNumElements())
return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
if (STyL->isPacked() != STyR->isPacked())
return cmpNumbers(STyL->isPacked(), STyR->isPacked());
for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
return Res;
}
return 0;
}
case Type::FunctionTyID: {
FunctionType *FTyL = cast<FunctionType>(TyL);
FunctionType *FTyR = cast<FunctionType>(TyR);
if (FTyL->getNumParams() != FTyR->getNumParams())
return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
if (FTyL->isVarArg() != FTyR->isVarArg())
return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
return Res;
for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
return Res;
}
return 0;
}
case Type::ArrayTyID: {
ArrayType *ATyL = cast<ArrayType>(TyL);
ArrayType *ATyR = cast<ArrayType>(TyR);
if (ATyL->getNumElements() != ATyR->getNumElements())
return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
}
}
}
int FunctionComparator::cmpOperations(const Instruction *L,
const Instruction *R) const {
if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
return Res;
if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
return Res;
if (int Res = cmpTypes(L->getType(), R->getType()))
return Res;
if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
R->getRawSubclassOptionalData()))
return Res;
if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
if (int Res = cmpTypes(AI->getAllocatedType(),
cast<AllocaInst>(R)->getAllocatedType()))
return Res;
if (int Res =
cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
return Res;
}
for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
if (int Res =
cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
return Res;
}
if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
return Res;
if (int Res =
cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
return Res;
if (int Res =
cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
return Res;
if (int Res =
cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
return Res;
return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
(uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
}
if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
if (int Res =
cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
return Res;
if (int Res =
cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
return Res;
if (int Res =
cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
return Res;
return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
}
if (const CmpInst *CI = dyn_cast<CmpInst>(L))
return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
if (const CallInst *CI = dyn_cast<CallInst>(L)) {
if (int Res = cmpNumbers(CI->getCallingConv(),
cast<CallInst>(R)->getCallingConv()))
return Res;
if (int Res =
cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
return Res;
return cmpNumbers(
(uint64_t)CI->getMetadata(LLVMContext::MD_range),
(uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
}
if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
if (int Res = cmpNumbers(CI->getCallingConv(),
cast<InvokeInst>(R)->getCallingConv()))
return Res;
if (int Res =
cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
return Res;
return cmpNumbers(
(uint64_t)CI->getMetadata(LLVMContext::MD_range),
(uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
}
if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
ArrayRef<unsigned> LIndices = IVI->getIndices();
ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
return Res;
for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
return Res;
}
}
if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
ArrayRef<unsigned> LIndices = EVI->getIndices();
ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
return Res;
for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
return Res;
}
}
if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
if (int Res =
cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
return Res;
return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
}
if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
if (int Res = cmpNumbers(CXI->isVolatile(),
cast<AtomicCmpXchgInst>(R)->isVolatile()))
return Res;
if (int Res = cmpNumbers(CXI->isWeak(),
cast<AtomicCmpXchgInst>(R)->isWeak()))
return Res;
if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
return Res;
if (int Res = cmpNumbers(CXI->getFailureOrdering(),
cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
return Res;
return cmpNumbers(CXI->getSynchScope(),
cast<AtomicCmpXchgInst>(R)->getSynchScope());
}
if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
if (int Res = cmpNumbers(RMWI->getOperation(),
cast<AtomicRMWInst>(R)->getOperation()))
return Res;
if (int Res = cmpNumbers(RMWI->isVolatile(),
cast<AtomicRMWInst>(R)->isVolatile()))
return Res;
if (int Res = cmpNumbers(RMWI->getOrdering(),
cast<AtomicRMWInst>(R)->getOrdering()))
return Res;
return cmpNumbers(RMWI->getSynchScope(),
cast<AtomicRMWInst>(R)->getSynchScope());
}
return 0;
}
int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
const GEPOperator *GEPR) {
unsigned int ASL = GEPL->getPointerAddressSpace();
unsigned int ASR = GEPR->getPointerAddressSpace();
if (int Res = cmpNumbers(ASL, ASR))
return Res;
const DataLayout &DL = FnL->getParent()->getDataLayout();
unsigned BitWidth = DL.getPointerSizeInBits(ASL);
APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
GEPR->accumulateConstantOffset(DL, OffsetR))
return cmpAPInts(OffsetL, OffsetR);
if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
(uint64_t)GEPR->getPointerOperand()->getType()))
return Res;
if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
return Res;
for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
return Res;
}
return 0;
}
int FunctionComparator::cmpValues(const Value *L, const Value *R) {
if (L == FnL) {
if (R == FnR)
return 0;
return -1;
}
if (R == FnR) {
if (L == FnL)
return 0;
return 1;
}
const Constant *ConstL = dyn_cast<Constant>(L);
const Constant *ConstR = dyn_cast<Constant>(R);
if (ConstL && ConstR) {
if (L == R)
return 0;
return cmpConstants(ConstL, ConstR);
}
if (ConstL)
return 1;
if (ConstR)
return -1;
const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
if (InlineAsmL && InlineAsmR)
return cmpNumbers((uint64_t)L, (uint64_t)R);
if (InlineAsmL)
return 1;
if (InlineAsmR)
return -1;
auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
return cmpNumbers(LeftSN.first->second, RightSN.first->second);
}
int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
do {
if (int Res = cmpValues(InstL, InstR))
return Res;
const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
if (GEPL && !GEPR)
return 1;
if (GEPR && !GEPL)
return -1;
if (GEPL && GEPR) {
if (int Res =
cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
return Res;
if (int Res = cmpGEPs(GEPL, GEPR))
return Res;
} else {
if (int Res = cmpOperations(InstL, InstR))
return Res;
assert(InstL->getNumOperands() == InstR->getNumOperands());
for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
Value *OpL = InstL->getOperand(i);
Value *OpR = InstR->getOperand(i);
if (int Res = cmpValues(OpL, OpR))
return Res;
if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
return Res;
if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
return Res;
}
}
++InstL, ++InstR;
} while (InstL != InstLE && InstR != InstRE);
if (InstL != InstLE && InstR == InstRE)
return 1;
if (InstL == InstLE && InstR != InstRE)
return -1;
return 0;
}
int FunctionComparator::compare() {
sn_mapL.clear();
sn_mapR.clear();
if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
return Res;
if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
return Res;
if (FnL->hasGC()) {
if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
return Res;
}
if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
return Res;
if (FnL->hasSection()) {
if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
return Res;
}
if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
return Res;
if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
return Res;
if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
return Res;
assert(FnL->arg_size() == FnR->arg_size() &&
"Identically typed functions have different numbers of args!");
for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
ArgRI = FnR->arg_begin(),
ArgLE = FnL->arg_end();
ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
if (cmpValues(ArgLI, ArgRI) != 0)
llvm_unreachable("Arguments repeat!");
}
SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
SmallSet<const BasicBlock *, 128> VisitedBBs;
FnLBBs.push_back(&FnL->getEntryBlock());
FnRBBs.push_back(&FnR->getEntryBlock());
VisitedBBs.insert(FnLBBs[0]);
while (!FnLBBs.empty()) {
const BasicBlock *BBL = FnLBBs.pop_back_val();
const BasicBlock *BBR = FnRBBs.pop_back_val();
if (int Res = cmpValues(BBL, BBR))
return Res;
if (int Res = compare(BBL, BBR))
return Res;
const TerminatorInst *TermL = BBL->getTerminator();
const TerminatorInst *TermR = BBR->getTerminator();
assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
continue;
FnLBBs.push_back(TermL->getSuccessor(i));
FnRBBs.push_back(TermR->getSuccessor(i));
}
}
return 0;
}
namespace {
class MergeFunctions : public ModulePass {
public:
static char ID;
MergeFunctions()
: ModulePass(ID), HasGlobalAliases(false) {
initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
private:
typedef std::set<FunctionNode> FnTreeType;
std::vector<WeakVH> Deferred;
bool doSanityCheck(std::vector<WeakVH> &Worklist);
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 writeThunkOrAlias(Function *F, Function *G);
void writeThunk(Function *F, Function *G);
void writeAlias(Function *F, Function *G);
void replaceFunctionInTree(FnTreeType::iterator &IterToF, Function *G);
FnTreeType FnTree;
bool HasGlobalAliases;
};
}
char MergeFunctions::ID = 0;
INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
ModulePass *llvm::createMergeFunctionsPass() {
return new MergeFunctions();
}
bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
if (const unsigned Max = NumFunctionsForSanityCheck) {
unsigned TripleNumber = 0;
bool Valid = true;
dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
unsigned i = 0;
for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
I != E && i < Max; ++I, ++i) {
unsigned j = i;
for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
Function *F1 = cast<Function>(*I);
Function *F2 = cast<Function>(*J);
int Res1 = FunctionComparator(F1, F2).compare();
int Res2 = FunctionComparator(F2, F1).compare();
if (Res1 != -Res2) {
dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
<< "\n";
F1->dump();
F2->dump();
Valid = false;
}
if (Res1 == 0)
continue;
unsigned k = j;
for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
++k, ++K, ++TripleNumber) {
if (K == J)
continue;
Function *F3 = cast<Function>(*K);
int Res3 = FunctionComparator(F1, F3).compare();
int Res4 = FunctionComparator(F2, F3).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-SANITY: Non-transitive; triple: "
<< TripleNumber << "\n";
dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
<< Res4 << "\n";
F1->dump();
F2->dump();
F3->dump();
Valid = false;
}
}
}
}
dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
return Valid;
}
return true;
}
bool MergeFunctions::runOnModule(Module &M) {
bool Changed = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
Deferred.push_back(WeakVH(I));
}
do {
std::vector<WeakVH> Worklist;
Deferred.swap(Worklist);
DEBUG(doSanityCheck(Worklist));
DEBUG(dbgs() << "size of module: " << M.size() << '\n');
DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
for (std::vector<WeakVH>::iterator I = Worklist.begin(),
E = Worklist.end(); I != E; ++I) {
if (!*I) continue;
Function *F = cast<Function>(*I);
if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
!F->mayBeOverridden()) {
Changed |= insert(F);
}
}
for (std::vector<WeakVH>::iterator I = Worklist.begin(),
E = Worklist.end(); I != E; ++I) {
if (!*I) continue;
Function *F = cast<Function>(*I);
if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
F->mayBeOverridden()) {
Changed |= insert(F);
}
}
DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
} while (!Deferred.empty());
FnTree.clear();
return Changed;
}
void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
Use *U = &*UI;
++UI;
CallSite CS(U->getUser());
if (CS && CS.isCallee(U)) {
remove(CS.getInstruction()->getParent()->getParent());
U->set(BitcastNew);
}
}
}
void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
if (HasGlobalAliases && G->hasUnnamedAddr()) {
if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
G->hasWeakLinkage()) {
writeAlias(F, G);
return;
}
}
writeThunk(F, G);
}
static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Type *SrcTy = V->getType();
if (SrcTy->isStructTy()) {
assert(DestTy->isStructTy());
assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
Value *Result = UndefValue::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::writeThunk(Function *F, Function *G) {
if (!G->mayBeOverridden()) {
replaceDirectCallers(G, F);
}
if (G->hasLocalLinkage() && G->use_empty()) {
G->eraseFromParent();
return;
}
Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
G->getParent());
BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
IRBuilder<false> Builder(BB);
SmallVector<Value *, 16> Args;
unsigned i = 0;
FunctionType *FFTy = F->getFunctionType();
for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
AI != AE; ++AI) {
Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
++i;
}
CallInst *CI = Builder.CreateCall(F, Args);
CI->setTailCall();
CI->setCallingConv(F->getCallingConv());
if (NewG->getReturnType()->isVoidTy()) {
Builder.CreateRetVoid();
} else {
Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
}
NewG->copyAttributesFrom(G);
NewG->takeName(G);
removeUsers(G);
G->replaceAllUsesWith(NewG);
G->eraseFromParent();
DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
++NumThunksWritten;
}
void MergeFunctions::writeAlias(Function *F, Function *G) {
PointerType *PTy = G->getType();
auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
G->getLinkage(), "", F);
F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
GA->takeName(G);
GA->setVisibility(G->getVisibility());
removeUsers(G);
G->replaceAllUsesWith(GA);
G->eraseFromParent();
DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
++NumAliasesWritten;
}
void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
if (F->mayBeOverridden()) {
assert(G->mayBeOverridden());
Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
F->getParent());
H->copyAttributesFrom(F);
H->takeName(F);
removeUsers(F);
F->replaceAllUsesWith(H);
unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
if (HasGlobalAliases) {
writeAlias(F, G);
writeAlias(F, H);
} else {
writeThunk(F, G);
writeThunk(F, H);
}
F->setAlignment(MaxAlignment);
F->setLinkage(GlobalValue::PrivateLinkage);
++NumDoubleWeak;
} else {
writeThunkOrAlias(F, G);
}
++NumFunctionsMerged;
}
void MergeFunctions::replaceFunctionInTree(FnTreeType::iterator &IterToF,
Function *G) {
Function *F = IterToF->getFunc();
assert(((F->mayBeOverridden() && G->mayBeOverridden()) ||
(!F->mayBeOverridden() && !G->mayBeOverridden())) &&
"Only change functions if both are strong or both are weak");
(void)F;
IterToF->replaceBy(G);
}
bool MergeFunctions::insert(Function *NewFunction) {
std::pair<FnTreeType::iterator, bool> Result =
FnTree.insert(FunctionNode(NewFunction));
if (Result.second) {
DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
return false;
}
const FunctionNode &OldF = *Result.first;
if (NewFunction->size() == 1) {
if (NewFunction->front().size() <= 2) {
DEBUG(dbgs() << NewFunction->getName()
<< " is to small to bother merging\n");
return false;
}
}
if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
(!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
if (OldF.getFunc()->getName() > NewFunction->getName()) {
Function *F = OldF.getFunc();
replaceFunctionInTree(Result.first, NewFunction);
NewFunction = F;
assert(OldF.getFunc() != F && "Must have swapped the functions.");
}
assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
DEBUG(dbgs() << " " << OldF.getFunc()->getName()
<< " == " << NewFunction->getName() << '\n');
Function *DeleteF = NewFunction;
mergeTwoFunctions(OldF.getFunc(), DeleteF);
return true;
}
void MergeFunctions::remove(Function *F) {
FnTreeType::iterator found = FnTree.find(FunctionNode(F));
size_t Erased = 0;
if (found != FnTree.end() && found->getFunc() == F) {
Erased = 1;
FnTree.erase(found);
}
if (Erased) {
DEBUG(dbgs() << "Removed " << F->getName()
<< " from set and deferred it.\n");
Deferred.push_back(F);
}
}
void MergeFunctions::removeUsers(Value *V) {
std::vector<Value *> Worklist;
Worklist.push_back(V);
while (!Worklist.empty()) {
Value *V = Worklist.back();
Worklist.pop_back();
for (User *U : V->users()) {
if (Instruction *I = dyn_cast<Instruction>(U)) {
remove(I->getParent()->getParent());
} else if (isa<GlobalValue>(U)) {
} else if (Constant *C = dyn_cast<Constant>(U)) {
for (User *UU : C->users())
Worklist.push_back(UU);
}
}
}
}