1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for equivalent functions that are mergable and folds them.
12 // A hash is computed from the function, based on its type and number of
15 // Once all hashes are computed, we perform an expensive equality comparison
16 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
17 // important that the hash function be high quality. The equality comparison
18 // iterates through each instruction in each basic block.
20 // When a match is found the functions are folded. If both functions are
21 // overridable, we move the functionality into a new internal function and
22 // leave two overridable thunks to it.
24 //===----------------------------------------------------------------------===//
28 // * virtual functions.
30 // Many functions have their address taken by the virtual function table for
31 // the object they belong to. However, as long as it's only used for a lookup
32 // and call, this is irrelevant, and we'd like to fold such implementations.
34 // * switch from n^2 pair-wise comparisons to an n-way comparison for each
37 // * be smarter about bitcast.
39 // In order to fold functions, we will sometimes add either bitcast instructions
40 // or bitcast constant expressions. Unfortunately, this can confound further
41 // analysis since the two functions differ where one has a bitcast and the
42 // other doesn't. We should learn to peer through bitcasts without imposing bad
43 // performance properties.
45 //===----------------------------------------------------------------------===//
47 #define DEBUG_TYPE "mergefunc"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/FoldingSet.h"
51 #include "llvm/ADT/SmallSet.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/Constants.h"
54 #include "llvm/InlineAsm.h"
55 #include "llvm/Instructions.h"
56 #include "llvm/LLVMContext.h"
57 #include "llvm/Module.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/CallSite.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetData.h"
68 STATISTIC(NumFunctionsMerged, "Number of functions merged");
71 /// MergeFunctions finds functions which will generate identical machine code,
72 /// by considering all pointer types to be equivalent. Once identified,
73 /// MergeFunctions will fold them by replacing a call to one to a call to a
74 /// bitcast of the other.
76 struct MergeFunctions : public ModulePass {
77 static char ID; // Pass identification, replacement for typeid
78 MergeFunctions() : ModulePass(ID) {}
80 bool runOnModule(Module &M);
84 char MergeFunctions::ID = 0;
85 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false);
87 ModulePass *llvm::createMergeFunctionsPass() {
88 return new MergeFunctions();
91 // ===----------------------------------------------------------------------===
92 // Comparison of functions
93 // ===----------------------------------------------------------------------===
95 class FunctionComparator {
97 FunctionComparator(TargetData *TD, Function *F1, Function *F2)
98 : F1(F1), F2(F2), TD(TD), IDMap1Count(0), IDMap2Count(0) {}
100 // Compare - test whether the two functions have equivalent behaviour.
104 // Compare - test whether two basic blocks have equivalent behaviour.
105 bool Compare(const BasicBlock *BB1, const BasicBlock *BB2);
107 // Enumerate - Assign or look up previously assigned numbers for the two
108 // values, and return whether the numbers are equal. Numbers are assigned in
109 // the order visited.
110 bool Enumerate(const Value *V1, const Value *V2);
112 // isEquivalentOperation - Compare two Instructions for equivalence, similar
113 // to Instruction::isSameOperationAs but with modifications to the type
115 bool isEquivalentOperation(const Instruction *I1,
116 const Instruction *I2) const;
118 // isEquivalentGEP - Compare two GEPs for equivalent pointer arithmetic.
119 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
121 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
122 const GetElementPtrInst *GEP2) {
123 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
126 // isEquivalentType - Compare two Types, treating all pointer types as equal.
127 bool isEquivalentType(const Type *Ty1, const Type *Ty2) const;
129 // The two functions undergoing comparison.
134 typedef DenseMap<const Value *, unsigned long> IDMap;
136 unsigned long IDMap1Count, IDMap2Count;
140 /// Compute a number which is guaranteed to be equal for two equivalent
141 /// functions, but is very likely to be different for different functions. This
142 /// needs to be computed as efficiently as possible.
143 static unsigned long ProfileFunction(const Function *F) {
144 const FunctionType *FTy = F->getFunctionType();
147 ID.AddInteger(F->size());
148 ID.AddInteger(F->getCallingConv());
149 ID.AddBoolean(F->hasGC());
150 ID.AddBoolean(FTy->isVarArg());
151 ID.AddInteger(FTy->getReturnType()->getTypeID());
152 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
153 ID.AddInteger(FTy->getParamType(i)->getTypeID());
154 return ID.ComputeHash();
157 /// isEquivalentType - any two pointers in the same address space are
158 /// equivalent. Otherwise, standard type equivalence rules apply.
159 bool FunctionComparator::isEquivalentType(const Type *Ty1,
160 const Type *Ty2) const {
163 if (Ty1->getTypeID() != Ty2->getTypeID())
166 switch(Ty1->getTypeID()) {
168 llvm_unreachable("Unknown type!");
169 // Fall through in Release mode.
170 case Type::IntegerTyID:
171 case Type::OpaqueTyID:
172 // Ty1 == Ty2 would have returned true earlier.
176 case Type::FloatTyID:
177 case Type::DoubleTyID:
178 case Type::X86_FP80TyID:
179 case Type::FP128TyID:
180 case Type::PPC_FP128TyID:
181 case Type::LabelTyID:
182 case Type::MetadataTyID:
185 case Type::PointerTyID: {
186 const PointerType *PTy1 = cast<PointerType>(Ty1);
187 const PointerType *PTy2 = cast<PointerType>(Ty2);
188 return PTy1->getAddressSpace() == PTy2->getAddressSpace();
191 case Type::StructTyID: {
192 const StructType *STy1 = cast<StructType>(Ty1);
193 const StructType *STy2 = cast<StructType>(Ty2);
194 if (STy1->getNumElements() != STy2->getNumElements())
197 if (STy1->isPacked() != STy2->isPacked())
200 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
201 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
207 case Type::UnionTyID: {
208 const UnionType *UTy1 = cast<UnionType>(Ty1);
209 const UnionType *UTy2 = cast<UnionType>(Ty2);
211 // TODO: we could be fancy with union(A, union(A, B)) === union(A, B), etc.
212 if (UTy1->getNumElements() != UTy2->getNumElements())
215 for (unsigned i = 0, e = UTy1->getNumElements(); i != e; ++i) {
216 if (!isEquivalentType(UTy1->getElementType(i), UTy2->getElementType(i)))
222 case Type::FunctionTyID: {
223 const FunctionType *FTy1 = cast<FunctionType>(Ty1);
224 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
225 if (FTy1->getNumParams() != FTy2->getNumParams() ||
226 FTy1->isVarArg() != FTy2->isVarArg())
229 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
232 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
233 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
239 case Type::ArrayTyID: {
240 const ArrayType *ATy1 = cast<ArrayType>(Ty1);
241 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
242 return ATy1->getNumElements() == ATy2->getNumElements() &&
243 isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
246 case Type::VectorTyID: {
247 const VectorType *VTy1 = cast<VectorType>(Ty1);
248 const VectorType *VTy2 = cast<VectorType>(Ty2);
249 return VTy1->getNumElements() == VTy2->getNumElements() &&
250 isEquivalentType(VTy1->getElementType(), VTy2->getElementType());
255 /// isEquivalentOperation - determine whether the two operations are the same
256 /// except that pointer-to-A and pointer-to-B are equivalent. This should be
257 /// kept in sync with Instruction::isSameOperationAs.
258 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
259 const Instruction *I2) const {
260 if (I1->getOpcode() != I2->getOpcode() ||
261 I1->getNumOperands() != I2->getNumOperands() ||
262 !isEquivalentType(I1->getType(), I2->getType()) ||
263 !I1->hasSameSubclassOptionalData(I2))
266 // We have two instructions of identical opcode and #operands. Check to see
267 // if all operands are the same type
268 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
269 if (!isEquivalentType(I1->getOperand(i)->getType(),
270 I2->getOperand(i)->getType()))
273 // Check special state that is a part of some instructions.
274 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
275 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
276 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
277 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
278 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
279 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
280 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
281 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
282 if (const CallInst *CI = dyn_cast<CallInst>(I1))
283 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
284 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
285 CI->getAttributes().getRawPointer() ==
286 cast<CallInst>(I2)->getAttributes().getRawPointer();
287 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
288 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
289 CI->getAttributes().getRawPointer() ==
290 cast<InvokeInst>(I2)->getAttributes().getRawPointer();
291 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
292 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
294 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
295 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
299 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
300 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
302 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
303 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
311 /// isEquivalentGEP - determine whether two GEP operations perform the same
312 /// underlying arithmetic.
313 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
314 const GEPOperator *GEP2) {
315 // When we have target data, we can reduce the GEP down to the value in bytes
316 // added to the address.
317 if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) {
318 SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end());
319 SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end());
320 uint64_t Offset1 = TD->getIndexedOffset(GEP1->getPointerOperandType(),
321 Indices1.data(), Indices1.size());
322 uint64_t Offset2 = TD->getIndexedOffset(GEP2->getPointerOperandType(),
323 Indices2.data(), Indices2.size());
324 return Offset1 == Offset2;
327 if (GEP1->getPointerOperand()->getType() !=
328 GEP2->getPointerOperand()->getType())
331 if (GEP1->getNumOperands() != GEP2->getNumOperands())
334 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
335 if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
342 /// Enumerate - Compare two values used by the two functions under pair-wise
343 /// comparison. If this is the first time the values are seen, they're added to
344 /// the mapping so that we will detect mismatches on next use.
345 bool FunctionComparator::Enumerate(const Value *V1, const Value *V2) {
346 // Check for function @f1 referring to itself and function @f2 referring to
347 // itself, or referring to each other, or both referring to either of them.
348 // They're all equivalent if the two functions are otherwise equivalent.
349 if (V1 == F1 && V2 == F2)
351 if (V1 == F2 && V2 == F1)
354 // TODO: constant expressions with GEP or references to F1 or F2.
355 if (isa<Constant>(V1))
358 if (isa<InlineAsm>(V1) && isa<InlineAsm>(V2)) {
359 const InlineAsm *IA1 = cast<InlineAsm>(V1);
360 const InlineAsm *IA2 = cast<InlineAsm>(V2);
361 return IA1->getAsmString() == IA2->getAsmString() &&
362 IA1->getConstraintString() == IA2->getConstraintString();
365 unsigned long &ID1 = Map1[V1];
369 unsigned long &ID2 = Map2[V2];
376 // Compare - test whether two basic blocks have equivalent behaviour.
377 bool FunctionComparator::Compare(const BasicBlock *BB1, const BasicBlock *BB2) {
378 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
379 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
382 if (!Enumerate(F1I, F2I))
385 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
386 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
390 if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
393 if (!isEquivalentGEP(GEP1, GEP2))
396 if (!isEquivalentOperation(F1I, F2I))
399 assert(F1I->getNumOperands() == F2I->getNumOperands());
400 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
401 Value *OpF1 = F1I->getOperand(i);
402 Value *OpF2 = F2I->getOperand(i);
404 if (!Enumerate(OpF1, OpF2))
407 if (OpF1->getValueID() != OpF2->getValueID() ||
408 !isEquivalentType(OpF1->getType(), OpF2->getType()))
414 } while (F1I != F1E && F2I != F2E);
416 return F1I == F1E && F2I == F2E;
419 bool FunctionComparator::Compare() {
420 // We need to recheck everything, but check the things that weren't included
421 // in the hash first.
423 if (F1->getAttributes() != F2->getAttributes())
426 if (F1->hasGC() != F2->hasGC())
429 if (F1->hasGC() && F1->getGC() != F2->getGC())
432 if (F1->hasSection() != F2->hasSection())
435 if (F1->hasSection() && F1->getSection() != F2->getSection())
438 if (F1->isVarArg() != F2->isVarArg())
441 // TODO: if it's internal and only used in direct calls, we could handle this
443 if (F1->getCallingConv() != F2->getCallingConv())
446 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
449 assert(F1->arg_size() == F2->arg_size() &&
450 "Identical functions have a different number of args.");
452 // Visit the arguments so that they get enumerated in the order they're
454 for (Function::const_arg_iterator f1i = F1->arg_begin(),
455 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
456 if (!Enumerate(f1i, f2i))
457 llvm_unreachable("Arguments repeat");
460 // We need to do an ordered walk since the actual ordering of the blocks in
461 // the linked list is immaterial. Our walk starts at the entry block for both
462 // functions, then takes each block from each terminator in order. As an
463 // artifact, this also means that unreachable blocks are ignored.
464 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
465 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
467 F1BBs.push_back(&F1->getEntryBlock());
468 F2BBs.push_back(&F2->getEntryBlock());
470 VisitedBBs.insert(F1BBs[0]);
471 while (!F1BBs.empty()) {
472 const BasicBlock *F1BB = F1BBs.pop_back_val();
473 const BasicBlock *F2BB = F2BBs.pop_back_val();
475 if (!Enumerate(F1BB, F2BB) || !Compare(F1BB, F2BB))
478 const TerminatorInst *F1TI = F1BB->getTerminator();
479 const TerminatorInst *F2TI = F2BB->getTerminator();
481 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
482 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
483 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
486 F1BBs.push_back(F1TI->getSuccessor(i));
487 F2BBs.push_back(F2TI->getSuccessor(i));
493 // ===----------------------------------------------------------------------===
494 // Folding of functions
495 // ===----------------------------------------------------------------------===
498 // * F is external strong, G is external strong:
499 // turn G into a thunk to F
500 // * F is external strong, G is external weak:
501 // turn G into a thunk to F
502 // * F is external weak, G is external weak:
504 // * F is external strong, G is internal:
505 // turn G into a thunk to F
506 // * F is internal, G is external weak
507 // turn G into a thunk to F
508 // * F is internal, G is internal:
509 // turn G into a thunk to F
511 // external means 'externally visible' linkage != (internal,private)
512 // internal means linkage == (internal,private)
513 // weak means linkage mayBeOverridable
515 /// ThunkGToF - Replace G with a simple tail call to bitcast(F). Also replace
516 /// direct uses of G with bitcast(F).
517 static void ThunkGToF(Function *F, Function *G) {
518 if (!G->mayBeOverridden()) {
519 // Redirect direct callers of G to F.
520 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
521 for (Value::use_iterator UI = G->use_begin(), UE = G->use_end();
523 Value::use_iterator TheIter = UI;
525 CallSite CS(*TheIter);
526 if (CS && CS.isCallee(TheIter))
527 TheIter.getUse().set(BitcastF);
531 // If G was internal then we may have replaced all uses if G with F. If so,
532 // stop here and delete G. There's no need for a thunk.
533 if (G->hasLocalLinkage() && G->use_empty()) {
534 G->eraseFromParent();
538 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
540 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
542 SmallVector<Value *, 16> Args;
544 const FunctionType *FFTy = F->getFunctionType();
545 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
547 if (FFTy->getParamType(i) == AI->getType()) {
550 Args.push_back(new BitCastInst(AI, FFTy->getParamType(i), "", BB));
555 CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
557 CI->setCallingConv(F->getCallingConv());
558 if (NewG->getReturnType()->isVoidTy()) {
559 ReturnInst::Create(F->getContext(), BB);
560 } else if (CI->getType() != NewG->getReturnType()) {
561 Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
562 ReturnInst::Create(F->getContext(), BCI, BB);
564 ReturnInst::Create(F->getContext(), CI, BB);
567 NewG->copyAttributesFrom(G);
569 G->replaceAllUsesWith(NewG);
570 G->eraseFromParent();
573 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
574 Function *F = FnVec[i];
575 Function *G = FnVec[j];
577 if (F->isWeakForLinker() && !G->isWeakForLinker()) {
578 std::swap(FnVec[i], FnVec[j]);
582 if (F->isWeakForLinker()) {
583 assert(G->isWeakForLinker());
585 // Make them both thunks to the same internal function.
586 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
588 H->copyAttributesFrom(F);
590 F->replaceAllUsesWith(H);
595 F->setAlignment(std::max(G->getAlignment(), H->getAlignment()));
596 F->setLinkage(GlobalValue::InternalLinkage);
601 ++NumFunctionsMerged;
605 // ===----------------------------------------------------------------------===
607 // ===----------------------------------------------------------------------===
609 bool MergeFunctions::runOnModule(Module &M) {
610 bool Changed = false;
612 std::map<unsigned long, std::vector<Function *> > FnMap;
614 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
615 if (F->isDeclaration() || F->hasAvailableExternallyLinkage())
618 FnMap[ProfileFunction(F)].push_back(F);
621 TargetData *TD = getAnalysisIfAvailable<TargetData>();
625 LocalChanged = false;
626 DEBUG(dbgs() << "size: " << FnMap.size() << "\n");
627 for (std::map<unsigned long, std::vector<Function *> >::iterator
628 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
629 std::vector<Function *> &FnVec = I->second;
630 DEBUG(dbgs() << "hash (" << I->first << "): " << FnVec.size() << "\n");
632 for (int i = 0, e = FnVec.size(); i != e; ++i) {
633 for (int j = i + 1; j != e; ++j) {
634 bool isEqual = FunctionComparator(TD, FnVec[i], FnVec[j]).Compare();
636 DEBUG(dbgs() << " " << FnVec[i]->getName()
637 << (isEqual ? " == " : " != ")
638 << FnVec[j]->getName() << "\n");
641 if (fold(FnVec, i, j)) {
643 FnVec.erase(FnVec.begin() + j);
651 Changed |= LocalChanged;
652 } while (LocalChanged);