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/CommandLine.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
70 #define DEBUG_TYPE "mergefunc"
72 STATISTIC(NumFunctionsMerged, "Number of functions merged");
73 STATISTIC(NumThunksWritten, "Number of thunks generated");
74 STATISTIC(NumAliasesWritten, "Number of aliases generated");
75 STATISTIC(NumDoubleWeak, "Number of new functions created");
77 static cl::opt<unsigned> NumFunctionsForSanityCheck(
79 cl::desc("How many functions in module could be used for "
80 "MergeFunctions pass sanity check. "
81 "'0' disables this check. Works only with '-debug' key."),
82 cl::init(0), cl::Hidden);
84 /// Returns the type id for a type to be hashed. We turn pointer types into
85 /// integers here because the actual compare logic below considers pointers and
86 /// integers of the same size as equal.
87 static Type::TypeID getTypeIDForHash(Type *Ty) {
88 if (Ty->isPointerTy())
89 return Type::IntegerTyID;
90 return Ty->getTypeID();
93 /// Creates a hash-code for the function which is the same for any two
94 /// functions that will compare equal, without looking at the instructions
95 /// inside the function.
96 static unsigned profileFunction(const Function *F) {
97 FunctionType *FTy = F->getFunctionType();
100 ID.AddInteger(F->size());
101 ID.AddInteger(F->getCallingConv());
102 ID.AddBoolean(F->hasGC());
103 ID.AddBoolean(FTy->isVarArg());
104 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
105 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
106 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
107 return ID.ComputeHash();
112 /// ComparableFunction - A struct that pairs together functions with a
113 /// DataLayout so that we can keep them together as elements in the DenseSet.
114 class ComparableFunction {
116 static const ComparableFunction EmptyKey;
117 static const ComparableFunction TombstoneKey;
118 static DataLayout * const LookupOnly;
120 ComparableFunction(Function *Func, const DataLayout *DL)
121 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
123 Function *getFunc() const { return Func; }
124 unsigned getHash() const { return Hash; }
125 const DataLayout *getDataLayout() const { return DL; }
127 // Drops AssertingVH reference to the function. Outside of debug mode, this
131 "Attempted to release function twice, or release empty/tombstone!");
136 explicit ComparableFunction(unsigned Hash)
137 : Func(nullptr), Hash(Hash), DL(nullptr) {}
139 AssertingVH<Function> Func;
141 const DataLayout *DL;
144 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
145 const ComparableFunction ComparableFunction::TombstoneKey =
146 ComparableFunction(1);
147 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
153 struct DenseMapInfo<ComparableFunction> {
154 static ComparableFunction getEmptyKey() {
155 return ComparableFunction::EmptyKey;
157 static ComparableFunction getTombstoneKey() {
158 return ComparableFunction::TombstoneKey;
160 static unsigned getHashValue(const ComparableFunction &CF) {
163 static bool isEqual(const ComparableFunction &LHS,
164 const ComparableFunction &RHS);
170 /// FunctionComparator - Compares two functions to determine whether or not
171 /// they will generate machine code with the same behaviour. DataLayout is
172 /// used if available. The comparator always fails conservatively (erring on the
173 /// side of claiming that two functions are different).
174 class FunctionComparator {
176 FunctionComparator(const DataLayout *DL, const Function *F1,
178 : FnL(F1), FnR(F2), DL(DL) {}
180 /// Test whether the two functions have equivalent behaviour.
184 /// Test whether two basic blocks have equivalent behaviour.
185 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
187 /// Constants comparison.
188 /// Its analog to lexicographical comparison between hypothetical numbers
190 /// <bitcastability-trait><raw-bit-contents>
192 /// 1. Bitcastability.
193 /// Check whether L's type could be losslessly bitcasted to R's type.
194 /// On this stage method, in case when lossless bitcast is not possible
195 /// method returns -1 or 1, thus also defining which type is greater in
196 /// context of bitcastability.
197 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
198 /// to the contents comparison.
199 /// If types differ, remember types comparison result and check
200 /// whether we still can bitcast types.
201 /// Stage 1: Types that satisfies isFirstClassType conditions are always
202 /// greater then others.
203 /// Stage 2: Vector is greater then non-vector.
204 /// If both types are vectors, then vector with greater bitwidth is
206 /// If both types are vectors with the same bitwidth, then types
207 /// are bitcastable, and we can skip other stages, and go to contents
209 /// Stage 3: Pointer types are greater than non-pointers. If both types are
210 /// pointers of the same address space - go to contents comparison.
211 /// Different address spaces: pointer with greater address space is
213 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
214 /// We don't know how to bitcast them. So, we better don't do it,
215 /// and return types comparison result (so it determines the
216 /// relationship among constants we don't know how to bitcast).
218 /// Just for clearance, let's see how the set of constants could look
219 /// on single dimension axis:
221 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
222 /// Where: NFCT - Not a FirstClassType
223 /// FCT - FirstClassTyp:
225 /// 2. Compare raw contents.
226 /// It ignores types on this stage and only compares bits from L and R.
227 /// Returns 0, if L and R has equivalent contents.
228 /// -1 or 1 if values are different.
230 /// 2.1. If contents are numbers, compare numbers.
231 /// Ints with greater bitwidth are greater. Ints with same bitwidths
232 /// compared by their contents.
233 /// 2.2. "And so on". Just to avoid discrepancies with comments
234 /// perhaps it would be better to read the implementation itself.
235 /// 3. And again about overall picture. Let's look back at how the ordered set
236 /// of constants will look like:
237 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
239 /// Now look, what could be inside [FCT, "others"], for example:
240 /// [FCT, "others"] =
242 /// [double 0.1], [double 1.23],
243 /// [i32 1], [i32 2],
244 /// { double 1.0 }, ; StructTyID, NumElements = 1
245 /// { i32 1 }, ; StructTyID, NumElements = 1
246 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
247 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
250 /// Let's explain the order. Float numbers will be less than integers, just
251 /// because of cmpType terms: FloatTyID < IntegerTyID.
252 /// Floats (with same fltSemantics) are sorted according to their value.
253 /// Then you can see integers, and they are, like a floats,
254 /// could be easy sorted among each others.
255 /// The structures. Structures are grouped at the tail, again because of their
256 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
257 /// Structures with greater number of elements are greater. Structures with
258 /// greater elements going first are greater.
259 /// The same logic with vectors, arrays and other possible complex types.
261 /// Bitcastable constants.
262 /// Let's assume, that some constant, belongs to some group of
263 /// "so-called-equal" values with different types, and at the same time
264 /// belongs to another group of constants with equal types
265 /// and "really" equal values.
267 /// Now, prove that this is impossible:
269 /// If constant A with type TyA is bitcastable to B with type TyB, then:
270 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
271 /// those should be vectors (if TyA is vector), pointers
272 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
274 /// 2. All constants with non-equal, but bitcastable types to TyA, are
275 /// bitcastable to B.
276 /// Once again, just because we allow it to vectors and pointers only.
277 /// This statement could be expanded as below:
278 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
279 /// vector B, and thus bitcastable to B as well.
280 /// 2.2. All pointers of the same address space, no matter what they point to,
281 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
282 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
285 /// In another words, for pointers and vectors, we ignore top-level type and
286 /// look at their particular properties (bit-width for vectors, and
287 /// address space for pointers).
288 /// If these properties are equal - compare their contents.
289 int cmpConstants(const Constant *L, const Constant *R);
291 /// Assign or look up previously assigned numbers for the two values, and
292 /// return whether the numbers are equal. Numbers are assigned in the order
294 /// Comparison order:
295 /// Stage 0: Value that is function itself is always greater then others.
296 /// If left and right values are references to their functions, then
298 /// Stage 1: Constants are greater than non-constants.
299 /// If both left and right are constants, then the result of
300 /// cmpConstants is used as cmpValues result.
301 /// Stage 2: InlineAsm instances are greater than others. If both left and
302 /// right are InlineAsm instances, InlineAsm* pointers casted to
303 /// integers and compared as numbers.
304 /// Stage 3: For all other cases we compare order we meet these values in
305 /// their functions. If right value was met first during scanning,
306 /// then left value is greater.
307 /// In another words, we compare serial numbers, for more details
308 /// see comments for sn_mapL and sn_mapR.
309 int cmpValues(const Value *L, const Value *R);
311 /// Compare two Instructions for equivalence, similar to
312 /// Instruction::isSameOperationAs but with modifications to the type
314 /// Stages are listed in "most significant stage first" order:
315 /// On each stage below, we do comparison between some left and right
316 /// operation parts. If parts are non-equal, we assign parts comparison
317 /// result to the operation comparison result and exit from method.
318 /// Otherwise we proceed to the next stage.
320 /// 1. Operations opcodes. Compared as numbers.
321 /// 2. Number of operands.
322 /// 3. Operation types. Compared with cmpType method.
323 /// 4. Compare operation subclass optional data as stream of bytes:
324 /// just convert it to integers and call cmpNumbers.
325 /// 5. Compare in operation operand types with cmpType in
326 /// most significant operand first order.
327 /// 6. Last stage. Check operations for some specific attributes.
328 /// For example, for Load it would be:
329 /// 6.1.Load: volatile (as boolean flag)
330 /// 6.2.Load: alignment (as integer numbers)
331 /// 6.3.Load: synch-scope (as integer numbers)
332 /// 6.4.Load: range metadata (as integer numbers)
333 /// On this stage its better to see the code, since its not more than 10-15
334 /// strings for particular instruction, and could change sometimes.
335 int cmpOperation(const Instruction *L, const Instruction *R) const;
337 /// Compare two GEPs for equivalent pointer arithmetic.
338 /// Parts to be compared for each comparison stage,
339 /// most significant stage first:
340 /// 1. Address space. As numbers.
341 /// 2. Constant offset, (if "DataLayout *DL" field is not NULL,
342 /// using GEPOperator::accumulateConstantOffset method).
343 /// 3. Pointer operand type (using cmpType method).
344 /// 4. Number of operands.
345 /// 5. Compare operands, using cmpValues method.
346 int cmpGEP(const GEPOperator *GEPL, const GEPOperator *GEPR);
347 int cmpGEP(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
348 return cmpGEP(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
351 /// cmpType - compares two types,
352 /// defines total ordering among the types set.
355 /// 0 if types are equal,
356 /// -1 if Left is less than Right,
357 /// +1 if Left is greater than Right.
360 /// Comparison is broken onto stages. Like in lexicographical comparison
361 /// stage coming first has higher priority.
362 /// On each explanation stage keep in mind total ordering properties.
364 /// 0. Before comparison we coerce pointer types of 0 address space to
366 /// We also don't bother with same type at left and right, so
367 /// just return 0 in this case.
369 /// 1. If types are of different kind (different type IDs).
370 /// Return result of type IDs comparison, treating them as numbers.
371 /// 2. If types are vectors or integers, compare Type* values as numbers.
372 /// 3. Types has same ID, so check whether they belongs to the next group:
381 /// If so - return 0, yes - we can treat these types as equal only because
382 /// their IDs are same.
383 /// 4. If Left and Right are pointers, return result of address space
384 /// comparison (numbers comparison). We can treat pointer types of same
385 /// address space as equal.
386 /// 5. If types are complex.
387 /// Then both Left and Right are to be expanded and their element types will
388 /// be checked with the same way. If we get Res != 0 on some stage, return it.
389 /// Otherwise return 0.
390 /// 6. For all other cases put llvm_unreachable.
391 int cmpType(Type *TyL, Type *TyR) const;
393 int cmpNumbers(uint64_t L, uint64_t R) const;
395 int cmpAPInt(const APInt &L, const APInt &R) const;
396 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
397 int cmpStrings(StringRef L, StringRef R) const;
398 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
400 // The two functions undergoing comparison.
401 const Function *FnL, *FnR;
403 const DataLayout *DL;
405 /// Assign serial numbers to values from left function, and values from
408 /// Being comparing functions we need to compare values we meet at left and
410 /// Its easy to sort things out for external values. It just should be
411 /// the same value at left and right.
412 /// But for local values (those were introduced inside function body)
413 /// we have to ensure they were introduced at exactly the same place,
414 /// and plays the same role.
415 /// Let's assign serial number to each value when we meet it first time.
416 /// Values that were met at same place will be with same serial numbers.
417 /// In this case it would be good to explain few points about values assigned
418 /// to BBs and other ways of implementation (see below).
420 /// 1. Safety of BB reordering.
421 /// It's safe to change the order of BasicBlocks in function.
422 /// Relationship with other functions and serial numbering will not be
423 /// changed in this case.
424 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
425 /// from the entry, and then take each terminator. So it doesn't matter how in
426 /// fact BBs are ordered in function. And since cmpValues are called during
427 /// this walk, the numbering depends only on how BBs located inside the CFG.
428 /// So the answer is - yes. We will get the same numbering.
430 /// 2. Impossibility to use dominance properties of values.
431 /// If we compare two instruction operands: first is usage of local
432 /// variable AL from function FL, and second is usage of local variable AR
433 /// from FR, we could compare their origins and check whether they are
434 /// defined at the same place.
435 /// But, we are still not able to compare operands of PHI nodes, since those
436 /// could be operands from further BBs we didn't scan yet.
437 /// So it's impossible to use dominance properties in general.
438 DenseMap<const Value*, int> sn_mapL, sn_mapR;
443 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
444 if (L < R) return -1;
449 int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
450 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
452 if (L.ugt(R)) return 1;
453 if (R.ugt(L)) return -1;
457 int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
458 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
459 (uint64_t)&R.getSemantics()))
461 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
464 int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
465 // Prevent heavy comparison, compare sizes first.
466 if (int Res = cmpNumbers(L.size(), R.size()))
469 // Compare strings lexicographically only when it is necessary: only when
470 // strings are equal in size.
474 int FunctionComparator::cmpAttrs(const AttributeSet L,
475 const AttributeSet R) const {
476 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
479 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
480 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
482 for (; LI != LE && RI != RE; ++LI, ++RI) {
498 /// Constants comparison:
499 /// 1. Check whether type of L constant could be losslessly bitcasted to R
501 /// 2. Compare constant contents.
502 /// For more details see declaration comments.
503 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
505 Type *TyL = L->getType();
506 Type *TyR = R->getType();
508 // Check whether types are bitcastable. This part is just re-factored
509 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
510 // we also pack into result which type is "less" for us.
511 int TypesRes = cmpType(TyL, TyR);
513 // Types are different, but check whether we can bitcast them.
514 if (!TyL->isFirstClassType()) {
515 if (TyR->isFirstClassType())
517 // Neither TyL nor TyR are values of first class type. Return the result
518 // of comparing the types
521 if (!TyR->isFirstClassType()) {
522 if (TyL->isFirstClassType())
527 // Vector -> Vector conversions are always lossless if the two vector types
528 // have the same size, otherwise not.
529 unsigned TyLWidth = 0;
530 unsigned TyRWidth = 0;
532 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
533 TyLWidth = VecTyL->getBitWidth();
534 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
535 TyRWidth = VecTyR->getBitWidth();
537 if (TyLWidth != TyRWidth)
538 return cmpNumbers(TyLWidth, TyRWidth);
540 // Zero bit-width means neither TyL nor TyR are vectors.
542 PointerType *PTyL = dyn_cast<PointerType>(TyL);
543 PointerType *PTyR = dyn_cast<PointerType>(TyR);
545 unsigned AddrSpaceL = PTyL->getAddressSpace();
546 unsigned AddrSpaceR = PTyR->getAddressSpace();
547 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
555 // TyL and TyR aren't vectors, nor pointers. We don't know how to
561 // OK, types are bitcastable, now check constant contents.
563 if (L->isNullValue() && R->isNullValue())
565 if (L->isNullValue() && !R->isNullValue())
567 if (!L->isNullValue() && R->isNullValue())
570 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
573 switch (L->getValueID()) {
574 case Value::UndefValueVal: return TypesRes;
575 case Value::ConstantIntVal: {
576 const APInt &LInt = cast<ConstantInt>(L)->getValue();
577 const APInt &RInt = cast<ConstantInt>(R)->getValue();
578 return cmpAPInt(LInt, RInt);
580 case Value::ConstantFPVal: {
581 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
582 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
583 return cmpAPFloat(LAPF, RAPF);
585 case Value::ConstantArrayVal: {
586 const ConstantArray *LA = cast<ConstantArray>(L);
587 const ConstantArray *RA = cast<ConstantArray>(R);
588 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
589 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
590 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
592 for (uint64_t i = 0; i < NumElementsL; ++i) {
593 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
594 cast<Constant>(RA->getOperand(i))))
599 case Value::ConstantStructVal: {
600 const ConstantStruct *LS = cast<ConstantStruct>(L);
601 const ConstantStruct *RS = cast<ConstantStruct>(R);
602 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
603 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
604 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
606 for (unsigned i = 0; i != NumElementsL; ++i) {
607 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
608 cast<Constant>(RS->getOperand(i))))
613 case Value::ConstantVectorVal: {
614 const ConstantVector *LV = cast<ConstantVector>(L);
615 const ConstantVector *RV = cast<ConstantVector>(R);
616 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
617 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
618 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
620 for (uint64_t i = 0; i < NumElementsL; ++i) {
621 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
622 cast<Constant>(RV->getOperand(i))))
627 case Value::ConstantExprVal: {
628 const ConstantExpr *LE = cast<ConstantExpr>(L);
629 const ConstantExpr *RE = cast<ConstantExpr>(R);
630 unsigned NumOperandsL = LE->getNumOperands();
631 unsigned NumOperandsR = RE->getNumOperands();
632 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
634 for (unsigned i = 0; i < NumOperandsL; ++i) {
635 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
636 cast<Constant>(RE->getOperand(i))))
641 case Value::FunctionVal:
642 case Value::GlobalVariableVal:
643 case Value::GlobalAliasVal:
644 default: // Unknown constant, cast L and R pointers to numbers and compare.
645 return cmpNumbers((uint64_t)L, (uint64_t)R);
649 /// cmpType - compares two types,
650 /// defines total ordering among the types set.
651 /// See method declaration comments for more details.
652 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
654 PointerType *PTyL = dyn_cast<PointerType>(TyL);
655 PointerType *PTyR = dyn_cast<PointerType>(TyR);
658 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
659 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
665 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
668 switch (TyL->getTypeID()) {
670 llvm_unreachable("Unknown type!");
671 // Fall through in Release mode.
672 case Type::IntegerTyID:
673 case Type::VectorTyID:
674 // TyL == TyR would have returned true earlier.
675 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
678 case Type::FloatTyID:
679 case Type::DoubleTyID:
680 case Type::X86_FP80TyID:
681 case Type::FP128TyID:
682 case Type::PPC_FP128TyID:
683 case Type::LabelTyID:
684 case Type::MetadataTyID:
687 case Type::PointerTyID: {
688 assert(PTyL && PTyR && "Both types must be pointers here.");
689 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
692 case Type::StructTyID: {
693 StructType *STyL = cast<StructType>(TyL);
694 StructType *STyR = cast<StructType>(TyR);
695 if (STyL->getNumElements() != STyR->getNumElements())
696 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
698 if (STyL->isPacked() != STyR->isPacked())
699 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
701 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
702 if (int Res = cmpType(STyL->getElementType(i),
703 STyR->getElementType(i)))
709 case Type::FunctionTyID: {
710 FunctionType *FTyL = cast<FunctionType>(TyL);
711 FunctionType *FTyR = cast<FunctionType>(TyR);
712 if (FTyL->getNumParams() != FTyR->getNumParams())
713 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
715 if (FTyL->isVarArg() != FTyR->isVarArg())
716 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
718 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
721 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
722 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
728 case Type::ArrayTyID: {
729 ArrayType *ATyL = cast<ArrayType>(TyL);
730 ArrayType *ATyR = cast<ArrayType>(TyR);
731 if (ATyL->getNumElements() != ATyR->getNumElements())
732 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
733 return cmpType(ATyL->getElementType(), ATyR->getElementType());
738 // Determine whether the two operations are the same except that pointer-to-A
739 // and pointer-to-B are equivalent. This should be kept in sync with
740 // Instruction::isSameOperationAs.
741 // Read method declaration comments for more details.
742 int FunctionComparator::cmpOperation(const Instruction *L,
743 const Instruction *R) const {
744 // Differences from Instruction::isSameOperationAs:
745 // * replace type comparison with calls to isEquivalentType.
746 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
747 // * because of the above, we don't test for the tail bit on calls later on
748 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
751 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
754 if (int Res = cmpType(L->getType(), R->getType()))
757 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
758 R->getRawSubclassOptionalData()))
761 // We have two instructions of identical opcode and #operands. Check to see
762 // if all operands are the same type
763 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
765 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
769 // Check special state that is a part of some instructions.
770 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
771 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
774 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
777 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
780 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
782 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
783 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
785 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
787 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
790 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
793 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
795 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
797 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
798 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
799 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
800 if (int Res = cmpNumbers(CI->getCallingConv(),
801 cast<CallInst>(R)->getCallingConv()))
803 return cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes());
805 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
806 if (int Res = cmpNumbers(CI->getCallingConv(),
807 cast<InvokeInst>(R)->getCallingConv()))
809 return cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes());
811 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
812 ArrayRef<unsigned> LIndices = IVI->getIndices();
813 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
814 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
816 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
817 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
821 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
822 ArrayRef<unsigned> LIndices = EVI->getIndices();
823 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
824 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
826 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
827 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
831 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
833 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
835 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
838 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
839 if (int Res = cmpNumbers(CXI->isVolatile(),
840 cast<AtomicCmpXchgInst>(R)->isVolatile()))
842 if (int Res = cmpNumbers(CXI->isWeak(),
843 cast<AtomicCmpXchgInst>(R)->isWeak()))
845 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
846 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
848 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
849 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
851 return cmpNumbers(CXI->getSynchScope(),
852 cast<AtomicCmpXchgInst>(R)->getSynchScope());
854 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
855 if (int Res = cmpNumbers(RMWI->getOperation(),
856 cast<AtomicRMWInst>(R)->getOperation()))
858 if (int Res = cmpNumbers(RMWI->isVolatile(),
859 cast<AtomicRMWInst>(R)->isVolatile()))
861 if (int Res = cmpNumbers(RMWI->getOrdering(),
862 cast<AtomicRMWInst>(R)->getOrdering()))
864 return cmpNumbers(RMWI->getSynchScope(),
865 cast<AtomicRMWInst>(R)->getSynchScope());
870 // Determine whether two GEP operations perform the same underlying arithmetic.
871 // Read method declaration comments for more details.
872 int FunctionComparator::cmpGEP(const GEPOperator *GEPL,
873 const GEPOperator *GEPR) {
875 unsigned int ASL = GEPL->getPointerAddressSpace();
876 unsigned int ASR = GEPR->getPointerAddressSpace();
878 if (int Res = cmpNumbers(ASL, ASR))
881 // When we have target data, we can reduce the GEP down to the value in bytes
882 // added to the address.
884 unsigned BitWidth = DL->getPointerSizeInBits(ASL);
885 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
886 if (GEPL->accumulateConstantOffset(*DL, OffsetL) &&
887 GEPR->accumulateConstantOffset(*DL, OffsetR))
888 return cmpAPInt(OffsetL, OffsetR);
891 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
892 (uint64_t)GEPR->getPointerOperand()->getType()))
895 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
898 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
899 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
906 /// Compare two values used by the two functions under pair-wise comparison. If
907 /// this is the first time the values are seen, they're added to the mapping so
908 /// that we will detect mismatches on next use.
909 /// See comments in declaration for more details.
910 int FunctionComparator::cmpValues(const Value *L, const Value *R) {
911 // Catch self-reference case.
923 const Constant *ConstL = dyn_cast<Constant>(L);
924 const Constant *ConstR = dyn_cast<Constant>(R);
925 if (ConstL && ConstR) {
928 return cmpConstants(ConstL, ConstR);
936 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
937 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
939 if (InlineAsmL && InlineAsmR)
940 return cmpNumbers((uint64_t)L, (uint64_t)R);
946 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
947 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
949 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
951 // Test whether two basic blocks have equivalent behaviour.
952 int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
953 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
954 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
957 if (int Res = cmpValues(InstL, InstR))
960 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
961 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
970 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
972 if (int Res = cmpGEP(GEPL, GEPR))
975 if (int Res = cmpOperation(InstL, InstR))
977 assert(InstL->getNumOperands() == InstR->getNumOperands());
979 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
980 Value *OpL = InstL->getOperand(i);
981 Value *OpR = InstR->getOperand(i);
982 if (int Res = cmpValues(OpL, OpR))
984 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
986 // TODO: Already checked in cmpOperation
987 if (int Res = cmpType(OpL->getType(), OpR->getType()))
993 } while (InstL != InstLE && InstR != InstRE);
995 if (InstL != InstLE && InstR == InstRE)
997 if (InstL == InstLE && InstR != InstRE)
1002 // Test whether the two functions have equivalent behaviour.
1003 int FunctionComparator::compare() {
1008 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1011 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1015 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1019 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1022 if (FnL->hasSection()) {
1023 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1027 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1030 // TODO: if it's internal and only used in direct calls, we could handle this
1032 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1035 if (int Res = cmpType(FnL->getFunctionType(), FnR->getFunctionType()))
1038 assert(FnL->arg_size() == FnR->arg_size() &&
1039 "Identically typed functions have different numbers of args!");
1041 // Visit the arguments so that they get enumerated in the order they're
1043 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1044 ArgRI = FnR->arg_begin(),
1045 ArgLE = FnL->arg_end();
1046 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1047 if (cmpValues(ArgLI, ArgRI) != 0)
1048 llvm_unreachable("Arguments repeat!");
1051 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1052 // linked list is immaterial. Our walk starts at the entry block for both
1053 // functions, then takes each block from each terminator in order. As an
1054 // artifact, this also means that unreachable blocks are ignored.
1055 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
1056 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
1058 FnLBBs.push_back(&FnL->getEntryBlock());
1059 FnRBBs.push_back(&FnR->getEntryBlock());
1061 VisitedBBs.insert(FnLBBs[0]);
1062 while (!FnLBBs.empty()) {
1063 const BasicBlock *BBL = FnLBBs.pop_back_val();
1064 const BasicBlock *BBR = FnRBBs.pop_back_val();
1066 if (int Res = cmpValues(BBL, BBR))
1069 if (int Res = compare(BBL, BBR))
1072 const TerminatorInst *TermL = BBL->getTerminator();
1073 const TerminatorInst *TermR = BBR->getTerminator();
1075 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1076 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1077 if (!VisitedBBs.insert(TermL->getSuccessor(i)))
1080 FnLBBs.push_back(TermL->getSuccessor(i));
1081 FnRBBs.push_back(TermR->getSuccessor(i));
1089 /// MergeFunctions finds functions which will generate identical machine code,
1090 /// by considering all pointer types to be equivalent. Once identified,
1091 /// MergeFunctions will fold them by replacing a call to one to a call to a
1092 /// bitcast of the other.
1094 class MergeFunctions : public ModulePass {
1098 : ModulePass(ID), HasGlobalAliases(false) {
1099 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1102 bool runOnModule(Module &M) override;
1105 typedef DenseSet<ComparableFunction> FnSetType;
1107 /// A work queue of functions that may have been modified and should be
1109 std::vector<WeakVH> Deferred;
1111 /// Checks the rules of order relation introduced among functions set.
1112 /// Returns true, if sanity check has been passed, and false if failed.
1113 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1115 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
1116 /// equal to one that's already present.
1117 bool insert(ComparableFunction &NewF);
1119 /// Remove a Function from the FnSet and queue it up for a second sweep of
1121 void remove(Function *F);
1123 /// Find the functions that use this Value and remove them from FnSet and
1124 /// queue the functions.
1125 void removeUsers(Value *V);
1127 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1128 /// necessary to make types match.
1129 void replaceDirectCallers(Function *Old, Function *New);
1131 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1132 /// be converted into a thunk. In either case, it should never be visited
1134 void mergeTwoFunctions(Function *F, Function *G);
1136 /// Replace G with a thunk or an alias to F. Deletes G.
1137 void writeThunkOrAlias(Function *F, Function *G);
1139 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1140 /// of G with bitcast(F). Deletes G.
1141 void writeThunk(Function *F, Function *G);
1143 /// Replace G with an alias to F. Deletes G.
1144 void writeAlias(Function *F, Function *G);
1146 /// The set of all distinct functions. Use the insert() and remove() methods
1150 /// DataLayout for more accurate GEP comparisons. May be NULL.
1151 const DataLayout *DL;
1153 /// Whether or not the target supports global aliases.
1154 bool HasGlobalAliases;
1157 } // end anonymous namespace
1159 char MergeFunctions::ID = 0;
1160 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1162 ModulePass *llvm::createMergeFunctionsPass() {
1163 return new MergeFunctions();
1166 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1167 if (const unsigned Max = NumFunctionsForSanityCheck) {
1168 unsigned TripleNumber = 0;
1171 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1174 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1175 I != E && i < Max; ++I, ++i) {
1177 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1178 Function *F1 = cast<Function>(*I);
1179 Function *F2 = cast<Function>(*J);
1180 int Res1 = FunctionComparator(DL, F1, F2).compare();
1181 int Res2 = FunctionComparator(DL, F2, F1).compare();
1183 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1184 if (Res1 != -Res2) {
1185 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1196 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1197 ++k, ++K, ++TripleNumber) {
1201 Function *F3 = cast<Function>(*K);
1202 int Res3 = FunctionComparator(DL, F1, F3).compare();
1203 int Res4 = FunctionComparator(DL, F2, F3).compare();
1205 bool Transitive = true;
1207 if (Res1 != 0 && Res1 == Res4) {
1208 // F1 > F2, F2 > F3 => F1 > F3
1209 Transitive = Res3 == Res1;
1210 } else if (Res3 != 0 && Res3 == -Res4) {
1211 // F1 > F3, F3 > F2 => F1 > F2
1212 Transitive = Res3 == Res1;
1213 } else if (Res4 != 0 && -Res3 == Res4) {
1214 // F2 > F3, F3 > F1 => F2 > F1
1215 Transitive = Res4 == -Res1;
1219 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1220 << TripleNumber << "\n";
1221 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1232 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1238 bool MergeFunctions::runOnModule(Module &M) {
1239 bool Changed = false;
1240 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1241 DL = DLP ? &DLP->getDataLayout() : nullptr;
1243 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1244 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1245 Deferred.push_back(WeakVH(I));
1247 FnSet.resize(Deferred.size());
1250 std::vector<WeakVH> Worklist;
1251 Deferred.swap(Worklist);
1253 DEBUG(doSanityCheck(Worklist));
1255 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1256 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1258 // Insert only strong functions and merge them. Strong function merging
1259 // always deletes one of them.
1260 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1261 E = Worklist.end(); I != E; ++I) {
1263 Function *F = cast<Function>(*I);
1264 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1265 !F->mayBeOverridden()) {
1266 ComparableFunction CF = ComparableFunction(F, DL);
1267 Changed |= insert(CF);
1271 // Insert only weak functions and merge them. By doing these second we
1272 // create thunks to the strong function when possible. When two weak
1273 // functions are identical, we create a new strong function with two weak
1274 // weak thunks to it which are identical but not mergable.
1275 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1276 E = Worklist.end(); I != E; ++I) {
1278 Function *F = cast<Function>(*I);
1279 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1280 F->mayBeOverridden()) {
1281 ComparableFunction CF = ComparableFunction(F, DL);
1282 Changed |= insert(CF);
1285 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1286 } while (!Deferred.empty());
1293 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1294 const ComparableFunction &RHS) {
1295 if (LHS.getFunc() == RHS.getFunc() &&
1296 LHS.getHash() == RHS.getHash())
1298 if (!LHS.getFunc() || !RHS.getFunc())
1301 // One of these is a special "underlying pointer comparison only" object.
1302 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1303 RHS.getDataLayout() == ComparableFunction::LookupOnly)
1306 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
1307 "Comparing functions for different targets");
1309 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(), RHS.getFunc())
1313 // Replace direct callers of Old with New.
1314 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1315 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1316 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1319 CallSite CS(U->getUser());
1320 if (CS && CS.isCallee(U)) {
1321 remove(CS.getInstruction()->getParent()->getParent());
1327 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1328 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1329 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1330 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1331 G->hasWeakLinkage()) {
1340 // Helper for writeThunk,
1341 // Selects proper bitcast operation,
1342 // but a bit simpler then CastInst::getCastOpcode.
1343 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1344 Type *SrcTy = V->getType();
1345 if (SrcTy->isStructTy()) {
1346 assert(DestTy->isStructTy());
1347 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1348 Value *Result = UndefValue::get(DestTy);
1349 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1350 Value *Element = createCast(
1351 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1352 DestTy->getStructElementType(I));
1355 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1359 assert(!DestTy->isStructTy());
1360 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1361 return Builder.CreateIntToPtr(V, DestTy);
1362 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1363 return Builder.CreatePtrToInt(V, DestTy);
1365 return Builder.CreateBitCast(V, DestTy);
1368 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1369 // of G with bitcast(F). Deletes G.
1370 void MergeFunctions::writeThunk(Function *F, Function *G) {
1371 if (!G->mayBeOverridden()) {
1372 // Redirect direct callers of G to F.
1373 replaceDirectCallers(G, F);
1376 // If G was internal then we may have replaced all uses of G with F. If so,
1377 // stop here and delete G. There's no need for a thunk.
1378 if (G->hasLocalLinkage() && G->use_empty()) {
1379 G->eraseFromParent();
1383 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1385 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1386 IRBuilder<false> Builder(BB);
1388 SmallVector<Value *, 16> Args;
1390 FunctionType *FFTy = F->getFunctionType();
1391 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1393 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1397 CallInst *CI = Builder.CreateCall(F, Args);
1399 CI->setCallingConv(F->getCallingConv());
1400 if (NewG->getReturnType()->isVoidTy()) {
1401 Builder.CreateRetVoid();
1403 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1406 NewG->copyAttributesFrom(G);
1409 G->replaceAllUsesWith(NewG);
1410 G->eraseFromParent();
1412 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1416 // Replace G with an alias to F and delete G.
1417 void MergeFunctions::writeAlias(Function *F, Function *G) {
1418 PointerType *PTy = G->getType();
1419 auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1420 G->getLinkage(), "", F);
1421 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1423 GA->setVisibility(G->getVisibility());
1425 G->replaceAllUsesWith(GA);
1426 G->eraseFromParent();
1428 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1429 ++NumAliasesWritten;
1432 // Merge two equivalent functions. Upon completion, Function G is deleted.
1433 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1434 if (F->mayBeOverridden()) {
1435 assert(G->mayBeOverridden());
1437 if (HasGlobalAliases) {
1438 // Make them both thunks to the same internal function.
1439 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1441 H->copyAttributesFrom(F);
1444 F->replaceAllUsesWith(H);
1446 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1451 F->setAlignment(MaxAlignment);
1452 F->setLinkage(GlobalValue::PrivateLinkage);
1454 // We can't merge them. Instead, pick one and update all direct callers
1455 // to call it and hope that we improve the instruction cache hit rate.
1456 replaceDirectCallers(G, F);
1461 writeThunkOrAlias(F, G);
1464 ++NumFunctionsMerged;
1467 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1468 // that was already inserted.
1469 bool MergeFunctions::insert(ComparableFunction &NewF) {
1470 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
1471 if (Result.second) {
1472 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
1476 const ComparableFunction &OldF = *Result.first;
1478 // Don't merge tiny functions, since it can just end up making the function
1480 // FIXME: Should still merge them if they are unnamed_addr and produce an
1482 if (NewF.getFunc()->size() == 1) {
1483 if (NewF.getFunc()->front().size() <= 2) {
1484 DEBUG(dbgs() << NewF.getFunc()->getName()
1485 << " is to small to bother merging\n");
1490 // Never thunk a strong function to a weak function.
1491 assert(!OldF.getFunc()->mayBeOverridden() ||
1492 NewF.getFunc()->mayBeOverridden());
1494 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
1495 << NewF.getFunc()->getName() << '\n');
1497 Function *DeleteF = NewF.getFunc();
1499 mergeTwoFunctions(OldF.getFunc(), DeleteF);
1503 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1504 // so that we'll look at it in the next round.
1505 void MergeFunctions::remove(Function *F) {
1506 // We need to make sure we remove F, not a function "equal" to F per the
1507 // function equality comparator.
1509 // The special "lookup only" ComparableFunction bypasses the expensive
1510 // function comparison in favour of a pointer comparison on the underlying
1512 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
1513 if (FnSet.erase(CF)) {
1514 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
1515 Deferred.push_back(F);
1519 // For each instruction used by the value, remove() the function that contains
1520 // the instruction. This should happen right before a call to RAUW.
1521 void MergeFunctions::removeUsers(Value *V) {
1522 std::vector<Value *> Worklist;
1523 Worklist.push_back(V);
1524 while (!Worklist.empty()) {
1525 Value *V = Worklist.back();
1526 Worklist.pop_back();
1528 for (User *U : V->users()) {
1529 if (Instruction *I = dyn_cast<Instruction>(U)) {
1530 remove(I->getParent()->getParent());
1531 } else if (isa<GlobalValue>(U)) {
1533 } else if (Constant *C = dyn_cast<Constant>(U)) {
1534 for (User *UU : C->users())
1535 Worklist.push_back(UU);