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 functions.
34 // * switch from n^2 pair-wise comparisons to an n-way comparison for each
37 // * be smarter about bitcasts.
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 look through bitcasts.
44 //===----------------------------------------------------------------------===//
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/ADT/DenseSet.h"
48 #include "llvm/ADT/FoldingSet.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SmallSet.h"
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm/IR/CallSite.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InlineAsm.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/raw_ostream.h"
69 #define DEBUG_TYPE "mergefunc"
71 STATISTIC(NumFunctionsMerged, "Number of functions merged");
72 STATISTIC(NumThunksWritten, "Number of thunks generated");
73 STATISTIC(NumAliasesWritten, "Number of aliases generated");
74 STATISTIC(NumDoubleWeak, "Number of new functions created");
76 /// Returns the type id for a type to be hashed. We turn pointer types into
77 /// integers here because the actual compare logic below considers pointers and
78 /// integers of the same size as equal.
79 static Type::TypeID getTypeIDForHash(Type *Ty) {
80 if (Ty->isPointerTy())
81 return Type::IntegerTyID;
82 return Ty->getTypeID();
85 /// Creates a hash-code for the function which is the same for any two
86 /// functions that will compare equal, without looking at the instructions
87 /// inside the function.
88 static unsigned profileFunction(const Function *F) {
89 FunctionType *FTy = F->getFunctionType();
92 ID.AddInteger(F->size());
93 ID.AddInteger(F->getCallingConv());
94 ID.AddBoolean(F->hasGC());
95 ID.AddBoolean(FTy->isVarArg());
96 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
97 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
98 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
99 return ID.ComputeHash();
104 /// ComparableFunction - A struct that pairs together functions with a
105 /// DataLayout so that we can keep them together as elements in the DenseSet.
106 class ComparableFunction {
108 static const ComparableFunction EmptyKey;
109 static const ComparableFunction TombstoneKey;
110 static DataLayout * const LookupOnly;
112 ComparableFunction(Function *Func, const DataLayout *DL)
113 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
115 Function *getFunc() const { return Func; }
116 unsigned getHash() const { return Hash; }
117 const DataLayout *getDataLayout() const { return DL; }
119 // Drops AssertingVH reference to the function. Outside of debug mode, this
123 "Attempted to release function twice, or release empty/tombstone!");
128 explicit ComparableFunction(unsigned Hash)
129 : Func(nullptr), Hash(Hash), DL(nullptr) {}
131 AssertingVH<Function> Func;
133 const DataLayout *DL;
136 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
137 const ComparableFunction ComparableFunction::TombstoneKey =
138 ComparableFunction(1);
139 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
145 struct DenseMapInfo<ComparableFunction> {
146 static ComparableFunction getEmptyKey() {
147 return ComparableFunction::EmptyKey;
149 static ComparableFunction getTombstoneKey() {
150 return ComparableFunction::TombstoneKey;
152 static unsigned getHashValue(const ComparableFunction &CF) {
155 static bool isEqual(const ComparableFunction &LHS,
156 const ComparableFunction &RHS);
162 /// FunctionComparator - Compares two functions to determine whether or not
163 /// they will generate machine code with the same behaviour. DataLayout is
164 /// used if available. The comparator always fails conservatively (erring on the
165 /// side of claiming that two functions are different).
166 class FunctionComparator {
168 FunctionComparator(const DataLayout *DL, const Function *F1,
170 : F1(F1), F2(F2), DL(DL) {}
172 /// Test whether the two functions have equivalent behaviour.
176 /// Test whether two basic blocks have equivalent behaviour.
177 bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
179 /// Constants comparison.
180 /// Its analog to lexicographical comparison between hypothetical numbers
182 /// <bitcastability-trait><raw-bit-contents>
184 /// 1. Bitcastability.
185 /// Check whether L's type could be losslessly bitcasted to R's type.
186 /// On this stage method, in case when lossless bitcast is not possible
187 /// method returns -1 or 1, thus also defining which type is greater in
188 /// context of bitcastability.
189 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
190 /// to the contents comparison.
191 /// If types differ, remember types comparison result and check
192 /// whether we still can bitcast types.
193 /// Stage 1: Types that satisfies isFirstClassType conditions are always
194 /// greater then others.
195 /// Stage 2: Vector is greater then non-vector.
196 /// If both types are vectors, then vector with greater bitwidth is
198 /// If both types are vectors with the same bitwidth, then types
199 /// are bitcastable, and we can skip other stages, and go to contents
201 /// Stage 3: Pointer types are greater than non-pointers. If both types are
202 /// pointers of the same address space - go to contents comparison.
203 /// Different address spaces: pointer with greater address space is
205 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
206 /// We don't know how to bitcast them. So, we better don't do it,
207 /// and return types comparison result (so it determines the
208 /// relationship among constants we don't know how to bitcast).
210 /// Just for clearance, let's see how the set of constants could look
211 /// on single dimension axis:
213 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
214 /// Where: NFCT - Not a FirstClassType
215 /// FCT - FirstClassTyp:
217 /// 2. Compare raw contents.
218 /// It ignores types on this stage and only compares bits from L and R.
219 /// Returns 0, if L and R has equivalent contents.
220 /// -1 or 1 if values are different.
222 /// 2.1. If contents are numbers, compare numbers.
223 /// Ints with greater bitwidth are greater. Ints with same bitwidths
224 /// compared by their contents.
225 /// 2.2. "And so on". Just to avoid discrepancies with comments
226 /// perhaps it would be better to read the implementation itself.
227 /// 3. And again about overall picture. Let's look back at how the ordered set
228 /// of constants will look like:
229 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
231 /// Now look, what could be inside [FCT, "others"], for example:
232 /// [FCT, "others"] =
234 /// [double 0.1], [double 1.23],
235 /// [i32 1], [i32 2],
236 /// { double 1.0 }, ; StructTyID, NumElements = 1
237 /// { i32 1 }, ; StructTyID, NumElements = 1
238 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
239 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
242 /// Let's explain the order. Float numbers will be less than integers, just
243 /// because of cmpType terms: FloatTyID < IntegerTyID.
244 /// Floats (with same fltSemantics) are sorted according to their value.
245 /// Then you can see integers, and they are, like a floats,
246 /// could be easy sorted among each others.
247 /// The structures. Structures are grouped at the tail, again because of their
248 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
249 /// Structures with greater number of elements are greater. Structures with
250 /// greater elements going first are greater.
251 /// The same logic with vectors, arrays and other possible complex types.
253 /// Bitcastable constants.
254 /// Let's assume, that some constant, belongs to some group of
255 /// "so-called-equal" values with different types, and at the same time
256 /// belongs to another group of constants with equal types
257 /// and "really" equal values.
259 /// Now, prove that this is impossible:
261 /// If constant A with type TyA is bitcastable to B with type TyB, then:
262 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
263 /// those should be vectors (if TyA is vector), pointers
264 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
266 /// 2. All constants with non-equal, but bitcastable types to TyA, are
267 /// bitcastable to B.
268 /// Once again, just because we allow it to vectors and pointers only.
269 /// This statement could be expanded as below:
270 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
271 /// vector B, and thus bitcastable to B as well.
272 /// 2.2. All pointers of the same address space, no matter what they point to,
273 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
274 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
277 /// In another words, for pointers and vectors, we ignore top-level type and
278 /// look at their particular properties (bit-width for vectors, and
279 /// address space for pointers).
280 /// If these properties are equal - compare their contents.
281 int cmpConstants(const Constant *L, const Constant *R);
283 /// Assign or look up previously assigned numbers for the two values, and
284 /// return whether the numbers are equal. Numbers are assigned in the order
286 bool enumerate(const Value *V1, const Value *V2);
288 /// Compare two Instructions for equivalence, similar to
289 /// Instruction::isSameOperationAs but with modifications to the type
291 bool isEquivalentOperation(const Instruction *I1,
292 const Instruction *I2) const;
294 /// Compare two GEPs for equivalent pointer arithmetic.
295 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
296 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
297 const GetElementPtrInst *GEP2) {
298 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
301 /// cmpType - compares two types,
302 /// defines total ordering among the types set.
305 /// 0 if types are equal,
306 /// -1 if Left is less than Right,
307 /// +1 if Left is greater than Right.
310 /// Comparison is broken onto stages. Like in lexicographical comparison
311 /// stage coming first has higher priority.
312 /// On each explanation stage keep in mind total ordering properties.
314 /// 0. Before comparison we coerce pointer types of 0 address space to
316 /// We also don't bother with same type at left and right, so
317 /// just return 0 in this case.
319 /// 1. If types are of different kind (different type IDs).
320 /// Return result of type IDs comparison, treating them as numbers.
321 /// 2. If types are vectors or integers, compare Type* values as numbers.
322 /// 3. Types has same ID, so check whether they belongs to the next group:
331 /// If so - return 0, yes - we can treat these types as equal only because
332 /// their IDs are same.
333 /// 4. If Left and Right are pointers, return result of address space
334 /// comparison (numbers comparison). We can treat pointer types of same
335 /// address space as equal.
336 /// 5. If types are complex.
337 /// Then both Left and Right are to be expanded and their element types will
338 /// be checked with the same way. If we get Res != 0 on some stage, return it.
339 /// Otherwise return 0.
340 /// 6. For all other cases put llvm_unreachable.
341 int cmpType(Type *TyL, Type *TyR) const;
343 bool isEquivalentType(Type *Ty1, Type *Ty2) const {
344 return cmpType(Ty1, Ty2) == 0;
347 int cmpNumbers(uint64_t L, uint64_t R) const;
349 int cmpAPInt(const APInt &L, const APInt &R) const;
350 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
352 // The two functions undergoing comparison.
353 const Function *F1, *F2;
355 const DataLayout *DL;
357 DenseMap<const Value *, const Value *> id_map;
358 DenseSet<const Value *> seen_values;
363 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
364 if (L < R) return -1;
369 int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
370 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
372 if (L.ugt(R)) return 1;
373 if (R.ugt(L)) return -1;
377 int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
378 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
379 (uint64_t)&R.getSemantics()))
381 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
384 /// Constants comparison:
385 /// 1. Check whether type of L constant could be losslessly bitcasted to R
387 /// 2. Compare constant contents.
388 /// For more details see declaration comments.
389 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
391 Type *TyL = L->getType();
392 Type *TyR = R->getType();
394 // Check whether types are bitcastable. This part is just re-factored
395 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
396 // we also pack into result which type is "less" for us.
397 int TypesRes = cmpType(TyL, TyR);
399 // Types are different, but check whether we can bitcast them.
400 if (!TyL->isFirstClassType()) {
401 if (TyR->isFirstClassType())
403 // Neither TyL nor TyR are values of first class type. Return the result
404 // of comparing the types
407 if (!TyR->isFirstClassType()) {
408 if (TyL->isFirstClassType())
413 // Vector -> Vector conversions are always lossless if the two vector types
414 // have the same size, otherwise not.
415 unsigned TyLWidth = 0;
416 unsigned TyRWidth = 0;
418 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
419 TyLWidth = VecTyL->getBitWidth();
420 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
421 TyRWidth = VecTyR->getBitWidth();
423 if (TyLWidth != TyRWidth)
424 return cmpNumbers(TyLWidth, TyRWidth);
426 // Zero bit-width means neither TyL nor TyR are vectors.
428 PointerType *PTyL = dyn_cast<PointerType>(TyL);
429 PointerType *PTyR = dyn_cast<PointerType>(TyR);
431 unsigned AddrSpaceL = PTyL->getAddressSpace();
432 unsigned AddrSpaceR = PTyR->getAddressSpace();
433 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
441 // TyL and TyR aren't vectors, nor pointers. We don't know how to
447 // OK, types are bitcastable, now check constant contents.
449 if (L->isNullValue() && R->isNullValue())
451 if (L->isNullValue() && !R->isNullValue())
453 if (!L->isNullValue() && R->isNullValue())
456 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
459 switch (L->getValueID()) {
460 case Value::UndefValueVal: return TypesRes;
461 case Value::ConstantIntVal: {
462 const APInt &LInt = cast<ConstantInt>(L)->getValue();
463 const APInt &RInt = cast<ConstantInt>(R)->getValue();
464 return cmpAPInt(LInt, RInt);
466 case Value::ConstantFPVal: {
467 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
468 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
469 return cmpAPFloat(LAPF, RAPF);
471 case Value::ConstantArrayVal: {
472 const ConstantArray *LA = cast<ConstantArray>(L);
473 const ConstantArray *RA = cast<ConstantArray>(R);
474 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
475 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
476 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
478 for (uint64_t i = 0; i < NumElementsL; ++i) {
479 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
480 cast<Constant>(RA->getOperand(i))))
485 case Value::ConstantStructVal: {
486 const ConstantStruct *LS = cast<ConstantStruct>(L);
487 const ConstantStruct *RS = cast<ConstantStruct>(R);
488 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
489 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
490 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
492 for (unsigned i = 0; i != NumElementsL; ++i) {
493 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
494 cast<Constant>(RS->getOperand(i))))
499 case Value::ConstantVectorVal: {
500 const ConstantVector *LV = cast<ConstantVector>(L);
501 const ConstantVector *RV = cast<ConstantVector>(R);
502 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
503 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
504 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
506 for (uint64_t i = 0; i < NumElementsL; ++i) {
507 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
508 cast<Constant>(RV->getOperand(i))))
513 case Value::ConstantExprVal: {
514 const ConstantExpr *LE = cast<ConstantExpr>(L);
515 const ConstantExpr *RE = cast<ConstantExpr>(R);
516 unsigned NumOperandsL = LE->getNumOperands();
517 unsigned NumOperandsR = RE->getNumOperands();
518 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
520 for (unsigned i = 0; i < NumOperandsL; ++i) {
521 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
522 cast<Constant>(RE->getOperand(i))))
527 case Value::FunctionVal:
528 case Value::GlobalVariableVal:
529 case Value::GlobalAliasVal:
530 default: // Unknown constant, cast L and R pointers to numbers and compare.
531 return cmpNumbers((uint64_t)L, (uint64_t)R);
535 /// cmpType - compares two types,
536 /// defines total ordering among the types set.
537 /// See method declaration comments for more details.
538 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
540 PointerType *PTyL = dyn_cast<PointerType>(TyL);
541 PointerType *PTyR = dyn_cast<PointerType>(TyR);
544 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
545 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
551 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
554 switch (TyL->getTypeID()) {
556 llvm_unreachable("Unknown type!");
557 // Fall through in Release mode.
558 case Type::IntegerTyID:
559 case Type::VectorTyID:
560 // TyL == TyR would have returned true earlier.
561 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
564 case Type::FloatTyID:
565 case Type::DoubleTyID:
566 case Type::X86_FP80TyID:
567 case Type::FP128TyID:
568 case Type::PPC_FP128TyID:
569 case Type::LabelTyID:
570 case Type::MetadataTyID:
573 case Type::PointerTyID: {
574 assert(PTyL && PTyR && "Both types must be pointers here.");
575 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
578 case Type::StructTyID: {
579 StructType *STyL = cast<StructType>(TyL);
580 StructType *STyR = cast<StructType>(TyR);
581 if (STyL->getNumElements() != STyR->getNumElements())
582 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
584 if (STyL->isPacked() != STyR->isPacked())
585 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
587 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
588 if (int Res = cmpType(STyL->getElementType(i),
589 STyR->getElementType(i)))
595 case Type::FunctionTyID: {
596 FunctionType *FTyL = cast<FunctionType>(TyL);
597 FunctionType *FTyR = cast<FunctionType>(TyR);
598 if (FTyL->getNumParams() != FTyR->getNumParams())
599 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
601 if (FTyL->isVarArg() != FTyR->isVarArg())
602 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
604 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
607 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
608 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
614 case Type::ArrayTyID: {
615 ArrayType *ATyL = cast<ArrayType>(TyL);
616 ArrayType *ATyR = cast<ArrayType>(TyR);
617 if (ATyL->getNumElements() != ATyR->getNumElements())
618 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
619 return cmpType(ATyL->getElementType(), ATyR->getElementType());
624 // Determine whether the two operations are the same except that pointer-to-A
625 // and pointer-to-B are equivalent. This should be kept in sync with
626 // Instruction::isSameOperationAs.
627 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
628 const Instruction *I2) const {
629 // Differences from Instruction::isSameOperationAs:
630 // * replace type comparison with calls to isEquivalentType.
631 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
632 // * because of the above, we don't test for the tail bit on calls later on
633 if (I1->getOpcode() != I2->getOpcode() ||
634 I1->getNumOperands() != I2->getNumOperands() ||
635 !isEquivalentType(I1->getType(), I2->getType()) ||
636 !I1->hasSameSubclassOptionalData(I2))
639 // We have two instructions of identical opcode and #operands. Check to see
640 // if all operands are the same type
641 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
642 if (!isEquivalentType(I1->getOperand(i)->getType(),
643 I2->getOperand(i)->getType()))
646 // Check special state that is a part of some instructions.
647 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
648 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
649 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
650 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
651 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
652 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
653 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
654 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
655 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
656 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
657 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
658 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
659 if (const CallInst *CI = dyn_cast<CallInst>(I1))
660 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
661 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
662 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
663 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
664 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
665 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
666 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
667 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
668 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
669 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
670 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
671 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
672 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
673 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
674 CXI->getSuccessOrdering() ==
675 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
676 CXI->getFailureOrdering() ==
677 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
678 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
679 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
680 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
681 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
682 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
683 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
688 // Determine whether two GEP operations perform the same underlying arithmetic.
689 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
690 const GEPOperator *GEP2) {
691 unsigned AS = GEP1->getPointerAddressSpace();
692 if (AS != GEP2->getPointerAddressSpace())
696 // When we have target data, we can reduce the GEP down to the value in bytes
697 // added to the address.
698 unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
699 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
700 if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
701 GEP2->accumulateConstantOffset(*DL, Offset2)) {
702 return Offset1 == Offset2;
706 if (GEP1->getPointerOperand()->getType() !=
707 GEP2->getPointerOperand()->getType())
710 if (GEP1->getNumOperands() != GEP2->getNumOperands())
713 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
714 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
721 // Compare two values used by the two functions under pair-wise comparison. If
722 // this is the first time the values are seen, they're added to the mapping so
723 // that we will detect mismatches on next use.
724 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
725 // Check for function @f1 referring to itself and function @f2 referring to
726 // itself, or referring to each other, or both referring to either of them.
727 // They're all equivalent if the two functions are otherwise equivalent.
728 if (V1 == F1 && V2 == F2)
730 if (V1 == F2 && V2 == F1)
733 if (const Constant *C1 = dyn_cast<Constant>(V1)) {
734 if (V1 == V2) return true;
735 const Constant *C2 = dyn_cast<Constant>(V2);
736 if (!C2) return false;
737 // TODO: constant expressions with GEP or references to F1 or F2.
738 if (C1->isNullValue() && C2->isNullValue() &&
739 isEquivalentType(C1->getType(), C2->getType()))
742 // Compare constants:
743 // Check whether type of C1 is bitcastable to C2's type.
744 // If the bitcast is possible then compare raw constants contents.
745 return cmpConstants(C1, C2) == 0;
748 if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
751 // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
752 // check whether it's equal to V2. When there is no mapping then we need to
753 // ensure that V2 isn't already equivalent to something else. For this
754 // purpose, we track the V2 values in a set.
756 const Value *&map_elem = id_map[V1];
758 return map_elem == V2;
759 if (!seen_values.insert(V2).second)
765 // Test whether two basic blocks have equivalent behaviour.
766 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
767 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
768 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
771 if (!enumerate(F1I, F2I))
774 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
775 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
779 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
782 if (!isEquivalentGEP(GEP1, GEP2))
785 if (!isEquivalentOperation(F1I, F2I))
788 assert(F1I->getNumOperands() == F2I->getNumOperands());
789 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
790 Value *OpF1 = F1I->getOperand(i);
791 Value *OpF2 = F2I->getOperand(i);
793 if (!enumerate(OpF1, OpF2))
796 if (OpF1->getValueID() != OpF2->getValueID() ||
797 !isEquivalentType(OpF1->getType(), OpF2->getType()))
803 } while (F1I != F1E && F2I != F2E);
805 return F1I == F1E && F2I == F2E;
808 // Test whether the two functions have equivalent behaviour.
809 bool FunctionComparator::compare() {
810 // We need to recheck everything, but check the things that weren't included
811 // in the hash first.
813 if (F1->getAttributes() != F2->getAttributes())
816 if (F1->hasGC() != F2->hasGC())
819 if (F1->hasGC() && F1->getGC() != F2->getGC())
822 if (F1->hasSection() != F2->hasSection())
825 if (F1->hasSection() && F1->getSection() != F2->getSection())
828 if (F1->isVarArg() != F2->isVarArg())
831 // TODO: if it's internal and only used in direct calls, we could handle this
833 if (F1->getCallingConv() != F2->getCallingConv())
836 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
839 assert(F1->arg_size() == F2->arg_size() &&
840 "Identically typed functions have different numbers of args!");
842 // Visit the arguments so that they get enumerated in the order they're
844 for (Function::const_arg_iterator f1i = F1->arg_begin(),
845 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
846 if (!enumerate(f1i, f2i))
847 llvm_unreachable("Arguments repeat!");
850 // We do a CFG-ordered walk since the actual ordering of the blocks in the
851 // linked list is immaterial. Our walk starts at the entry block for both
852 // functions, then takes each block from each terminator in order. As an
853 // artifact, this also means that unreachable blocks are ignored.
854 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
855 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
857 F1BBs.push_back(&F1->getEntryBlock());
858 F2BBs.push_back(&F2->getEntryBlock());
860 VisitedBBs.insert(F1BBs[0]);
861 while (!F1BBs.empty()) {
862 const BasicBlock *F1BB = F1BBs.pop_back_val();
863 const BasicBlock *F2BB = F2BBs.pop_back_val();
865 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
868 const TerminatorInst *F1TI = F1BB->getTerminator();
869 const TerminatorInst *F2TI = F2BB->getTerminator();
871 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
872 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
873 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
876 F1BBs.push_back(F1TI->getSuccessor(i));
877 F2BBs.push_back(F2TI->getSuccessor(i));
885 /// MergeFunctions finds functions which will generate identical machine code,
886 /// by considering all pointer types to be equivalent. Once identified,
887 /// MergeFunctions will fold them by replacing a call to one to a call to a
888 /// bitcast of the other.
890 class MergeFunctions : public ModulePass {
894 : ModulePass(ID), HasGlobalAliases(false) {
895 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
898 bool runOnModule(Module &M) override;
901 typedef DenseSet<ComparableFunction> FnSetType;
903 /// A work queue of functions that may have been modified and should be
905 std::vector<WeakVH> Deferred;
907 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
908 /// equal to one that's already present.
909 bool insert(ComparableFunction &NewF);
911 /// Remove a Function from the FnSet and queue it up for a second sweep of
913 void remove(Function *F);
915 /// Find the functions that use this Value and remove them from FnSet and
916 /// queue the functions.
917 void removeUsers(Value *V);
919 /// Replace all direct calls of Old with calls of New. Will bitcast New if
920 /// necessary to make types match.
921 void replaceDirectCallers(Function *Old, Function *New);
923 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
924 /// be converted into a thunk. In either case, it should never be visited
926 void mergeTwoFunctions(Function *F, Function *G);
928 /// Replace G with a thunk or an alias to F. Deletes G.
929 void writeThunkOrAlias(Function *F, Function *G);
931 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
932 /// of G with bitcast(F). Deletes G.
933 void writeThunk(Function *F, Function *G);
935 /// Replace G with an alias to F. Deletes G.
936 void writeAlias(Function *F, Function *G);
938 /// The set of all distinct functions. Use the insert() and remove() methods
942 /// DataLayout for more accurate GEP comparisons. May be NULL.
943 const DataLayout *DL;
945 /// Whether or not the target supports global aliases.
946 bool HasGlobalAliases;
949 } // end anonymous namespace
951 char MergeFunctions::ID = 0;
952 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
954 ModulePass *llvm::createMergeFunctionsPass() {
955 return new MergeFunctions();
958 bool MergeFunctions::runOnModule(Module &M) {
959 bool Changed = false;
960 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
961 DL = DLP ? &DLP->getDataLayout() : nullptr;
963 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
964 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
965 Deferred.push_back(WeakVH(I));
967 FnSet.resize(Deferred.size());
970 std::vector<WeakVH> Worklist;
971 Deferred.swap(Worklist);
973 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
974 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
976 // Insert only strong functions and merge them. Strong function merging
977 // always deletes one of them.
978 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
979 E = Worklist.end(); I != E; ++I) {
981 Function *F = cast<Function>(*I);
982 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
983 !F->mayBeOverridden()) {
984 ComparableFunction CF = ComparableFunction(F, DL);
985 Changed |= insert(CF);
989 // Insert only weak functions and merge them. By doing these second we
990 // create thunks to the strong function when possible. When two weak
991 // functions are identical, we create a new strong function with two weak
992 // weak thunks to it which are identical but not mergable.
993 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
994 E = Worklist.end(); I != E; ++I) {
996 Function *F = cast<Function>(*I);
997 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
998 F->mayBeOverridden()) {
999 ComparableFunction CF = ComparableFunction(F, DL);
1000 Changed |= insert(CF);
1003 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1004 } while (!Deferred.empty());
1011 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1012 const ComparableFunction &RHS) {
1013 if (LHS.getFunc() == RHS.getFunc() &&
1014 LHS.getHash() == RHS.getHash())
1016 if (!LHS.getFunc() || !RHS.getFunc())
1019 // One of these is a special "underlying pointer comparison only" object.
1020 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1021 RHS.getDataLayout() == ComparableFunction::LookupOnly)
1024 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
1025 "Comparing functions for different targets");
1027 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
1028 RHS.getFunc()).compare();
1031 // Replace direct callers of Old with New.
1032 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1033 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1034 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1037 CallSite CS(U->getUser());
1038 if (CS && CS.isCallee(U)) {
1039 remove(CS.getInstruction()->getParent()->getParent());
1045 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1046 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1047 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1048 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1049 G->hasWeakLinkage()) {
1058 // Helper for writeThunk,
1059 // Selects proper bitcast operation,
1060 // but a bit simpler then CastInst::getCastOpcode.
1061 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1062 Type *SrcTy = V->getType();
1063 if (SrcTy->isStructTy()) {
1064 assert(DestTy->isStructTy());
1065 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1066 Value *Result = UndefValue::get(DestTy);
1067 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1068 Value *Element = createCast(
1069 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1070 DestTy->getStructElementType(I));
1073 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1077 assert(!DestTy->isStructTy());
1078 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1079 return Builder.CreateIntToPtr(V, DestTy);
1080 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1081 return Builder.CreatePtrToInt(V, DestTy);
1083 return Builder.CreateBitCast(V, DestTy);
1086 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1087 // of G with bitcast(F). Deletes G.
1088 void MergeFunctions::writeThunk(Function *F, Function *G) {
1089 if (!G->mayBeOverridden()) {
1090 // Redirect direct callers of G to F.
1091 replaceDirectCallers(G, F);
1094 // If G was internal then we may have replaced all uses of G with F. If so,
1095 // stop here and delete G. There's no need for a thunk.
1096 if (G->hasLocalLinkage() && G->use_empty()) {
1097 G->eraseFromParent();
1101 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1103 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1104 IRBuilder<false> Builder(BB);
1106 SmallVector<Value *, 16> Args;
1108 FunctionType *FFTy = F->getFunctionType();
1109 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1111 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1115 CallInst *CI = Builder.CreateCall(F, Args);
1117 CI->setCallingConv(F->getCallingConv());
1118 if (NewG->getReturnType()->isVoidTy()) {
1119 Builder.CreateRetVoid();
1121 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1124 NewG->copyAttributesFrom(G);
1127 G->replaceAllUsesWith(NewG);
1128 G->eraseFromParent();
1130 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1134 // Replace G with an alias to F and delete G.
1135 void MergeFunctions::writeAlias(Function *F, Function *G) {
1136 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
1137 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
1138 BitcastF, G->getParent());
1139 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1141 GA->setVisibility(G->getVisibility());
1143 G->replaceAllUsesWith(GA);
1144 G->eraseFromParent();
1146 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1147 ++NumAliasesWritten;
1150 // Merge two equivalent functions. Upon completion, Function G is deleted.
1151 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1152 if (F->mayBeOverridden()) {
1153 assert(G->mayBeOverridden());
1155 if (HasGlobalAliases) {
1156 // Make them both thunks to the same internal function.
1157 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1159 H->copyAttributesFrom(F);
1162 F->replaceAllUsesWith(H);
1164 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1169 F->setAlignment(MaxAlignment);
1170 F->setLinkage(GlobalValue::PrivateLinkage);
1172 // We can't merge them. Instead, pick one and update all direct callers
1173 // to call it and hope that we improve the instruction cache hit rate.
1174 replaceDirectCallers(G, F);
1179 writeThunkOrAlias(F, G);
1182 ++NumFunctionsMerged;
1185 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1186 // that was already inserted.
1187 bool MergeFunctions::insert(ComparableFunction &NewF) {
1188 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
1189 if (Result.second) {
1190 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
1194 const ComparableFunction &OldF = *Result.first;
1196 // Don't merge tiny functions, since it can just end up making the function
1198 // FIXME: Should still merge them if they are unnamed_addr and produce an
1200 if (NewF.getFunc()->size() == 1) {
1201 if (NewF.getFunc()->front().size() <= 2) {
1202 DEBUG(dbgs() << NewF.getFunc()->getName()
1203 << " is to small to bother merging\n");
1208 // Never thunk a strong function to a weak function.
1209 assert(!OldF.getFunc()->mayBeOverridden() ||
1210 NewF.getFunc()->mayBeOverridden());
1212 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
1213 << NewF.getFunc()->getName() << '\n');
1215 Function *DeleteF = NewF.getFunc();
1217 mergeTwoFunctions(OldF.getFunc(), DeleteF);
1221 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1222 // so that we'll look at it in the next round.
1223 void MergeFunctions::remove(Function *F) {
1224 // We need to make sure we remove F, not a function "equal" to F per the
1225 // function equality comparator.
1227 // The special "lookup only" ComparableFunction bypasses the expensive
1228 // function comparison in favour of a pointer comparison on the underlying
1230 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
1231 if (FnSet.erase(CF)) {
1232 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
1233 Deferred.push_back(F);
1237 // For each instruction used by the value, remove() the function that contains
1238 // the instruction. This should happen right before a call to RAUW.
1239 void MergeFunctions::removeUsers(Value *V) {
1240 std::vector<Value *> Worklist;
1241 Worklist.push_back(V);
1242 while (!Worklist.empty()) {
1243 Value *V = Worklist.back();
1244 Worklist.pop_back();
1246 for (User *U : V->users()) {
1247 if (Instruction *I = dyn_cast<Instruction>(U)) {
1248 remove(I->getParent()->getParent());
1249 } else if (isa<GlobalValue>(U)) {
1251 } else if (Constant *C = dyn_cast<Constant>(U)) {
1252 for (User *UU : C->users())
1253 Worklist.push_back(UU);