0ab1c7699ee33722c2605841eb9faa187a7540b8
[oota-llvm.git] / lib / Transforms / IPO / MergeFunctions.cpp
1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass looks for equivalent functions that are mergable and folds them.
11 //
12 // A hash is computed from the function, based on its type and number of
13 // basic blocks.
14 //
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.
19 //
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.
23 //
24 //===----------------------------------------------------------------------===//
25 //
26 // Future work:
27 //
28 // * virtual functions.
29 //
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.
33 //
34 // * switch from n^2 pair-wise comparisons to an n-way comparison for each
35 // bucket.
36 //
37 // * be smarter about bitcasts.
38 //
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.
43 //
44 //===----------------------------------------------------------------------===//
45
46 #define DEBUG_TYPE "mergefunc"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/ADT/DenseSet.h"
49 #include "llvm/ADT/FoldingSet.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/SmallSet.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/IR/CallSite.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InlineAsm.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/ValueHandle.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include <vector>
68 using namespace llvm;
69
70 STATISTIC(NumFunctionsMerged, "Number of functions merged");
71 STATISTIC(NumThunksWritten, "Number of thunks generated");
72 STATISTIC(NumAliasesWritten, "Number of aliases generated");
73 STATISTIC(NumDoubleWeak, "Number of new functions created");
74
75 /// Returns the type id for a type to be hashed. We turn pointer types into
76 /// integers here because the actual compare logic below considers pointers and
77 /// integers of the same size as equal.
78 static Type::TypeID getTypeIDForHash(Type *Ty) {
79   if (Ty->isPointerTy())
80     return Type::IntegerTyID;
81   return Ty->getTypeID();
82 }
83
84 /// Creates a hash-code for the function which is the same for any two
85 /// functions that will compare equal, without looking at the instructions
86 /// inside the function.
87 static unsigned profileFunction(const Function *F) {
88   FunctionType *FTy = F->getFunctionType();
89
90   FoldingSetNodeID ID;
91   ID.AddInteger(F->size());
92   ID.AddInteger(F->getCallingConv());
93   ID.AddBoolean(F->hasGC());
94   ID.AddBoolean(FTy->isVarArg());
95   ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
96   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
97     ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
98   return ID.ComputeHash();
99 }
100
101 namespace {
102
103 /// ComparableFunction - A struct that pairs together functions with a
104 /// DataLayout so that we can keep them together as elements in the DenseSet.
105 class ComparableFunction {
106 public:
107   static const ComparableFunction EmptyKey;
108   static const ComparableFunction TombstoneKey;
109   static DataLayout * const LookupOnly;
110
111   ComparableFunction(Function *Func, const DataLayout *DL)
112     : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
113
114   Function *getFunc() const { return Func; }
115   unsigned getHash() const { return Hash; }
116   const DataLayout *getDataLayout() const { return DL; }
117
118   // Drops AssertingVH reference to the function. Outside of debug mode, this
119   // does nothing.
120   void release() {
121     assert(Func &&
122            "Attempted to release function twice, or release empty/tombstone!");
123     Func = NULL;
124   }
125
126 private:
127   explicit ComparableFunction(unsigned Hash)
128     : Func(NULL), Hash(Hash), DL(NULL) {}
129
130   AssertingVH<Function> Func;
131   unsigned Hash;
132   const DataLayout *DL;
133 };
134
135 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
136 const ComparableFunction ComparableFunction::TombstoneKey =
137     ComparableFunction(1);
138 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
139
140 }
141
142 namespace llvm {
143   template <>
144   struct DenseMapInfo<ComparableFunction> {
145     static ComparableFunction getEmptyKey() {
146       return ComparableFunction::EmptyKey;
147     }
148     static ComparableFunction getTombstoneKey() {
149       return ComparableFunction::TombstoneKey;
150     }
151     static unsigned getHashValue(const ComparableFunction &CF) {
152       return CF.getHash();
153     }
154     static bool isEqual(const ComparableFunction &LHS,
155                         const ComparableFunction &RHS);
156   };
157 }
158
159 namespace {
160
161 /// FunctionComparator - Compares two functions to determine whether or not
162 /// they will generate machine code with the same behaviour. DataLayout is
163 /// used if available. The comparator always fails conservatively (erring on the
164 /// side of claiming that two functions are different).
165 class FunctionComparator {
166 public:
167   FunctionComparator(const DataLayout *DL, const Function *F1,
168                      const Function *F2)
169     : F1(F1), F2(F2), DL(DL) {}
170
171   /// Test whether the two functions have equivalent behaviour.
172   bool compare();
173
174 private:
175   /// Test whether two basic blocks have equivalent behaviour.
176   bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
177
178   /// Assign or look up previously assigned numbers for the two values, and
179   /// return whether the numbers are equal. Numbers are assigned in the order
180   /// visited.
181   bool enumerate(const Value *V1, const Value *V2);
182
183   /// Compare two Instructions for equivalence, similar to
184   /// Instruction::isSameOperationAs but with modifications to the type
185   /// comparison.
186   bool isEquivalentOperation(const Instruction *I1,
187                              const Instruction *I2) const;
188
189   /// Compare two GEPs for equivalent pointer arithmetic.
190   bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
191   bool isEquivalentGEP(const GetElementPtrInst *GEP1,
192                        const GetElementPtrInst *GEP2) {
193     return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
194   }
195
196   /// Compare two Types, treating all pointer types as equal.
197   bool isEquivalentType(Type *Ty1, Type *Ty2) const;
198
199   // The two functions undergoing comparison.
200   const Function *F1, *F2;
201
202   const DataLayout *DL;
203
204   DenseMap<const Value *, const Value *> id_map;
205   DenseSet<const Value *> seen_values;
206 };
207
208 }
209
210 // Any two pointers in the same address space are equivalent, intptr_t and
211 // pointers are equivalent. Otherwise, standard type equivalence rules apply.
212 bool FunctionComparator::isEquivalentType(Type *Ty1, Type *Ty2) const {
213
214   PointerType *PTy1 = dyn_cast<PointerType>(Ty1);
215   PointerType *PTy2 = dyn_cast<PointerType>(Ty2);
216
217   if (DL) {
218     if (PTy1 && PTy1->getAddressSpace() == 0) Ty1 = DL->getIntPtrType(Ty1);
219     if (PTy2 && PTy2->getAddressSpace() == 0) Ty2 = DL->getIntPtrType(Ty2);
220   }
221
222   if (Ty1 == Ty2)
223     return true;
224
225   if (Ty1->getTypeID() != Ty2->getTypeID())
226     return false;
227
228   switch (Ty1->getTypeID()) {
229   default:
230     llvm_unreachable("Unknown type!");
231     // Fall through in Release mode.
232   case Type::IntegerTyID:
233   case Type::VectorTyID:
234     // Ty1 == Ty2 would have returned true earlier.
235     return false;
236
237   case Type::VoidTyID:
238   case Type::FloatTyID:
239   case Type::DoubleTyID:
240   case Type::X86_FP80TyID:
241   case Type::FP128TyID:
242   case Type::PPC_FP128TyID:
243   case Type::LabelTyID:
244   case Type::MetadataTyID:
245     return true;
246
247   case Type::PointerTyID: {
248     assert(PTy1 && PTy2 && "Both types must be pointers here.");
249     return PTy1->getAddressSpace() == PTy2->getAddressSpace();
250   }
251
252   case Type::StructTyID: {
253     StructType *STy1 = cast<StructType>(Ty1);
254     StructType *STy2 = cast<StructType>(Ty2);
255     if (STy1->getNumElements() != STy2->getNumElements())
256       return false;
257
258     if (STy1->isPacked() != STy2->isPacked())
259       return false;
260
261     for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
262       if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
263         return false;
264     }
265     return true;
266   }
267
268   case Type::FunctionTyID: {
269     FunctionType *FTy1 = cast<FunctionType>(Ty1);
270     FunctionType *FTy2 = cast<FunctionType>(Ty2);
271     if (FTy1->getNumParams() != FTy2->getNumParams() ||
272         FTy1->isVarArg() != FTy2->isVarArg())
273       return false;
274
275     if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
276       return false;
277
278     for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
279       if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
280         return false;
281     }
282     return true;
283   }
284
285   case Type::ArrayTyID: {
286     ArrayType *ATy1 = cast<ArrayType>(Ty1);
287     ArrayType *ATy2 = cast<ArrayType>(Ty2);
288     return ATy1->getNumElements() == ATy2->getNumElements() &&
289            isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
290   }
291   }
292 }
293
294 // Determine whether the two operations are the same except that pointer-to-A
295 // and pointer-to-B are equivalent. This should be kept in sync with
296 // Instruction::isSameOperationAs.
297 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
298                                                const Instruction *I2) const {
299   // Differences from Instruction::isSameOperationAs:
300   //  * replace type comparison with calls to isEquivalentType.
301   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
302   //  * because of the above, we don't test for the tail bit on calls later on
303   if (I1->getOpcode() != I2->getOpcode() ||
304       I1->getNumOperands() != I2->getNumOperands() ||
305       !isEquivalentType(I1->getType(), I2->getType()) ||
306       !I1->hasSameSubclassOptionalData(I2))
307     return false;
308
309   // We have two instructions of identical opcode and #operands.  Check to see
310   // if all operands are the same type
311   for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
312     if (!isEquivalentType(I1->getOperand(i)->getType(),
313                           I2->getOperand(i)->getType()))
314       return false;
315
316   // Check special state that is a part of some instructions.
317   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
318     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
319            LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
320            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
321            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
322   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
323     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
324            SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
325            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
326            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
327   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
328     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
329   if (const CallInst *CI = dyn_cast<CallInst>(I1))
330     return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
331            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
332   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
333     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
334            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
335   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
336     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
337   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
338     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
339   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
340     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
341            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
342   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
343     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
344            CXI->getOrdering() == cast<AtomicCmpXchgInst>(I2)->getOrdering() &&
345            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
346   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
347     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
348            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
349            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
350            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
351
352   return true;
353 }
354
355 // Determine whether two GEP operations perform the same underlying arithmetic.
356 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
357                                          const GEPOperator *GEP2) {
358   unsigned AS = GEP1->getPointerAddressSpace();
359   if (AS != GEP2->getPointerAddressSpace())
360     return false;
361
362   if (DL) {
363     // When we have target data, we can reduce the GEP down to the value in bytes
364     // added to the address.
365     unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
366     APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
367     if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
368         GEP2->accumulateConstantOffset(*DL, Offset2)) {
369       return Offset1 == Offset2;
370     }
371   }
372
373   if (GEP1->getPointerOperand()->getType() !=
374       GEP2->getPointerOperand()->getType())
375     return false;
376
377   if (GEP1->getNumOperands() != GEP2->getNumOperands())
378     return false;
379
380   for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
381     if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
382       return false;
383   }
384
385   return true;
386 }
387
388 // Compare two values used by the two functions under pair-wise comparison. If
389 // this is the first time the values are seen, they're added to the mapping so
390 // that we will detect mismatches on next use.
391 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
392   // Check for function @f1 referring to itself and function @f2 referring to
393   // itself, or referring to each other, or both referring to either of them.
394   // They're all equivalent if the two functions are otherwise equivalent.
395   if (V1 == F1 && V2 == F2)
396     return true;
397   if (V1 == F2 && V2 == F1)
398     return true;
399
400   if (const Constant *C1 = dyn_cast<Constant>(V1)) {
401     if (V1 == V2) return true;
402     const Constant *C2 = dyn_cast<Constant>(V2);
403     if (!C2) return false;
404     // TODO: constant expressions with GEP or references to F1 or F2.
405     if (C1->isNullValue() && C2->isNullValue() &&
406         isEquivalentType(C1->getType(), C2->getType()))
407       return true;
408     // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1
409     // then they must have equal bit patterns.
410     return C1->getType()->canLosslesslyBitCastTo(C2->getType()) &&
411       C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType());
412   }
413
414   if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
415     return V1 == V2;
416
417   // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
418   // check whether it's equal to V2. When there is no mapping then we need to
419   // ensure that V2 isn't already equivalent to something else. For this
420   // purpose, we track the V2 values in a set.
421
422   const Value *&map_elem = id_map[V1];
423   if (map_elem)
424     return map_elem == V2;
425   if (!seen_values.insert(V2).second)
426     return false;
427   map_elem = V2;
428   return true;
429 }
430
431 // Test whether two basic blocks have equivalent behaviour.
432 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
433   BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
434   BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
435
436   do {
437     if (!enumerate(F1I, F2I))
438       return false;
439
440     if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
441       const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
442       if (!GEP2)
443         return false;
444
445       if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
446         return false;
447
448       if (!isEquivalentGEP(GEP1, GEP2))
449         return false;
450     } else {
451       if (!isEquivalentOperation(F1I, F2I))
452         return false;
453
454       assert(F1I->getNumOperands() == F2I->getNumOperands());
455       for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
456         Value *OpF1 = F1I->getOperand(i);
457         Value *OpF2 = F2I->getOperand(i);
458
459         if (!enumerate(OpF1, OpF2))
460           return false;
461
462         if (OpF1->getValueID() != OpF2->getValueID() ||
463             !isEquivalentType(OpF1->getType(), OpF2->getType()))
464           return false;
465       }
466     }
467
468     ++F1I, ++F2I;
469   } while (F1I != F1E && F2I != F2E);
470
471   return F1I == F1E && F2I == F2E;
472 }
473
474 // Test whether the two functions have equivalent behaviour.
475 bool FunctionComparator::compare() {
476   // We need to recheck everything, but check the things that weren't included
477   // in the hash first.
478
479   if (F1->getAttributes() != F2->getAttributes())
480     return false;
481
482   if (F1->hasGC() != F2->hasGC())
483     return false;
484
485   if (F1->hasGC() && F1->getGC() != F2->getGC())
486     return false;
487
488   if (F1->hasSection() != F2->hasSection())
489     return false;
490
491   if (F1->hasSection() && F1->getSection() != F2->getSection())
492     return false;
493
494   if (F1->isVarArg() != F2->isVarArg())
495     return false;
496
497   // TODO: if it's internal and only used in direct calls, we could handle this
498   // case too.
499   if (F1->getCallingConv() != F2->getCallingConv())
500     return false;
501
502   if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
503     return false;
504
505   assert(F1->arg_size() == F2->arg_size() &&
506          "Identically typed functions have different numbers of args!");
507
508   // Visit the arguments so that they get enumerated in the order they're
509   // passed in.
510   for (Function::const_arg_iterator f1i = F1->arg_begin(),
511          f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
512     if (!enumerate(f1i, f2i))
513       llvm_unreachable("Arguments repeat!");
514   }
515
516   // We do a CFG-ordered walk since the actual ordering of the blocks in the
517   // linked list is immaterial. Our walk starts at the entry block for both
518   // functions, then takes each block from each terminator in order. As an
519   // artifact, this also means that unreachable blocks are ignored.
520   SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
521   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
522
523   F1BBs.push_back(&F1->getEntryBlock());
524   F2BBs.push_back(&F2->getEntryBlock());
525
526   VisitedBBs.insert(F1BBs[0]);
527   while (!F1BBs.empty()) {
528     const BasicBlock *F1BB = F1BBs.pop_back_val();
529     const BasicBlock *F2BB = F2BBs.pop_back_val();
530
531     if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
532       return false;
533
534     const TerminatorInst *F1TI = F1BB->getTerminator();
535     const TerminatorInst *F2TI = F2BB->getTerminator();
536
537     assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
538     for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
539       if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
540         continue;
541
542       F1BBs.push_back(F1TI->getSuccessor(i));
543       F2BBs.push_back(F2TI->getSuccessor(i));
544     }
545   }
546   return true;
547 }
548
549 namespace {
550
551 /// MergeFunctions finds functions which will generate identical machine code,
552 /// by considering all pointer types to be equivalent. Once identified,
553 /// MergeFunctions will fold them by replacing a call to one to a call to a
554 /// bitcast of the other.
555 ///
556 class MergeFunctions : public ModulePass {
557 public:
558   static char ID;
559   MergeFunctions()
560     : ModulePass(ID), HasGlobalAliases(false) {
561     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
562   }
563
564   bool runOnModule(Module &M) override;
565
566 private:
567   typedef DenseSet<ComparableFunction> FnSetType;
568
569   /// A work queue of functions that may have been modified and should be
570   /// analyzed again.
571   std::vector<WeakVH> Deferred;
572
573   /// Insert a ComparableFunction into the FnSet, or merge it away if it's
574   /// equal to one that's already present.
575   bool insert(ComparableFunction &NewF);
576
577   /// Remove a Function from the FnSet and queue it up for a second sweep of
578   /// analysis.
579   void remove(Function *F);
580
581   /// Find the functions that use this Value and remove them from FnSet and
582   /// queue the functions.
583   void removeUsers(Value *V);
584
585   /// Replace all direct calls of Old with calls of New. Will bitcast New if
586   /// necessary to make types match.
587   void replaceDirectCallers(Function *Old, Function *New);
588
589   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
590   /// be converted into a thunk. In either case, it should never be visited
591   /// again.
592   void mergeTwoFunctions(Function *F, Function *G);
593
594   /// Replace G with a thunk or an alias to F. Deletes G.
595   void writeThunkOrAlias(Function *F, Function *G);
596
597   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
598   /// of G with bitcast(F). Deletes G.
599   void writeThunk(Function *F, Function *G);
600
601   /// Replace G with an alias to F. Deletes G.
602   void writeAlias(Function *F, Function *G);
603
604   /// The set of all distinct functions. Use the insert() and remove() methods
605   /// to modify it.
606   FnSetType FnSet;
607
608   /// DataLayout for more accurate GEP comparisons. May be NULL.
609   const DataLayout *DL;
610
611   /// Whether or not the target supports global aliases.
612   bool HasGlobalAliases;
613 };
614
615 }  // end anonymous namespace
616
617 char MergeFunctions::ID = 0;
618 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
619
620 ModulePass *llvm::createMergeFunctionsPass() {
621   return new MergeFunctions();
622 }
623
624 bool MergeFunctions::runOnModule(Module &M) {
625   bool Changed = false;
626   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
627   DL = DLP ? &DLP->getDataLayout() : 0;
628
629   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
630     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
631       Deferred.push_back(WeakVH(I));
632   }
633   FnSet.resize(Deferred.size());
634
635   do {
636     std::vector<WeakVH> Worklist;
637     Deferred.swap(Worklist);
638
639     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
640     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
641
642     // Insert only strong functions and merge them. Strong function merging
643     // always deletes one of them.
644     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
645            E = Worklist.end(); I != E; ++I) {
646       if (!*I) continue;
647       Function *F = cast<Function>(*I);
648       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
649           !F->mayBeOverridden()) {
650         ComparableFunction CF = ComparableFunction(F, DL);
651         Changed |= insert(CF);
652       }
653     }
654
655     // Insert only weak functions and merge them. By doing these second we
656     // create thunks to the strong function when possible. When two weak
657     // functions are identical, we create a new strong function with two weak
658     // weak thunks to it which are identical but not mergable.
659     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
660            E = Worklist.end(); I != E; ++I) {
661       if (!*I) continue;
662       Function *F = cast<Function>(*I);
663       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
664           F->mayBeOverridden()) {
665         ComparableFunction CF = ComparableFunction(F, DL);
666         Changed |= insert(CF);
667       }
668     }
669     DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
670   } while (!Deferred.empty());
671
672   FnSet.clear();
673
674   return Changed;
675 }
676
677 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
678                                                const ComparableFunction &RHS) {
679   if (LHS.getFunc() == RHS.getFunc() &&
680       LHS.getHash() == RHS.getHash())
681     return true;
682   if (!LHS.getFunc() || !RHS.getFunc())
683     return false;
684
685   // One of these is a special "underlying pointer comparison only" object.
686   if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
687       RHS.getDataLayout() == ComparableFunction::LookupOnly)
688     return false;
689
690   assert(LHS.getDataLayout() == RHS.getDataLayout() &&
691          "Comparing functions for different targets");
692
693   return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
694                             RHS.getFunc()).compare();
695 }
696
697 // Replace direct callers of Old with New.
698 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
699   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
700   for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
701        UI != UE;) {
702     Value::use_iterator TheIter = UI;
703     ++UI;
704     CallSite CS(*TheIter);
705     if (CS && CS.isCallee(TheIter)) {
706       remove(CS.getInstruction()->getParent()->getParent());
707       TheIter.getUse().set(BitcastNew);
708     }
709   }
710 }
711
712 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
713 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
714   if (HasGlobalAliases && G->hasUnnamedAddr()) {
715     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
716         G->hasWeakLinkage()) {
717       writeAlias(F, G);
718       return;
719     }
720   }
721
722   writeThunk(F, G);
723 }
724
725 // Helper for writeThunk,
726 // Selects proper bitcast operation,
727 // but a bit simpler then CastInst::getCastOpcode.
728 static Value* createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
729   Type *SrcTy = V->getType();
730   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
731     return Builder.CreateIntToPtr(V, DestTy);
732   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
733     return Builder.CreatePtrToInt(V, DestTy);
734   else
735     return Builder.CreateBitCast(V, DestTy);
736 }
737
738 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
739 // of G with bitcast(F). Deletes G.
740 void MergeFunctions::writeThunk(Function *F, Function *G) {
741   if (!G->mayBeOverridden()) {
742     // Redirect direct callers of G to F.
743     replaceDirectCallers(G, F);
744   }
745
746   // If G was internal then we may have replaced all uses of G with F. If so,
747   // stop here and delete G. There's no need for a thunk.
748   if (G->hasLocalLinkage() && G->use_empty()) {
749     G->eraseFromParent();
750     return;
751   }
752
753   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
754                                     G->getParent());
755   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
756   IRBuilder<false> Builder(BB);
757
758   SmallVector<Value *, 16> Args;
759   unsigned i = 0;
760   FunctionType *FFTy = F->getFunctionType();
761   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
762        AI != AE; ++AI) {
763     Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
764     ++i;
765   }
766
767   CallInst *CI = Builder.CreateCall(F, Args);
768   CI->setTailCall();
769   CI->setCallingConv(F->getCallingConv());
770   if (NewG->getReturnType()->isVoidTy()) {
771     Builder.CreateRetVoid();
772   } else {
773     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
774   }
775
776   NewG->copyAttributesFrom(G);
777   NewG->takeName(G);
778   removeUsers(G);
779   G->replaceAllUsesWith(NewG);
780   G->eraseFromParent();
781
782   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
783   ++NumThunksWritten;
784 }
785
786 // Replace G with an alias to F and delete G.
787 void MergeFunctions::writeAlias(Function *F, Function *G) {
788   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
789   GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
790                                     BitcastF, G->getParent());
791   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
792   GA->takeName(G);
793   GA->setVisibility(G->getVisibility());
794   removeUsers(G);
795   G->replaceAllUsesWith(GA);
796   G->eraseFromParent();
797
798   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
799   ++NumAliasesWritten;
800 }
801
802 // Merge two equivalent functions. Upon completion, Function G is deleted.
803 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
804   if (F->mayBeOverridden()) {
805     assert(G->mayBeOverridden());
806
807     if (HasGlobalAliases) {
808       // Make them both thunks to the same internal function.
809       Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
810                                      F->getParent());
811       H->copyAttributesFrom(F);
812       H->takeName(F);
813       removeUsers(F);
814       F->replaceAllUsesWith(H);
815
816       unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
817
818       writeAlias(F, G);
819       writeAlias(F, H);
820
821       F->setAlignment(MaxAlignment);
822       F->setLinkage(GlobalValue::PrivateLinkage);
823     } else {
824       // We can't merge them. Instead, pick one and update all direct callers
825       // to call it and hope that we improve the instruction cache hit rate.
826       replaceDirectCallers(G, F);
827     }
828
829     ++NumDoubleWeak;
830   } else {
831     writeThunkOrAlias(F, G);
832   }
833
834   ++NumFunctionsMerged;
835 }
836
837 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
838 // that was already inserted.
839 bool MergeFunctions::insert(ComparableFunction &NewF) {
840   std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
841   if (Result.second) {
842     DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
843     return false;
844   }
845
846   const ComparableFunction &OldF = *Result.first;
847
848   // Don't merge tiny functions, since it can just end up making the function
849   // larger.
850   // FIXME: Should still merge them if they are unnamed_addr and produce an
851   // alias.
852   if (NewF.getFunc()->size() == 1) {
853     if (NewF.getFunc()->front().size() <= 2) {
854       DEBUG(dbgs() << NewF.getFunc()->getName()
855             << " is to small to bother merging\n");
856       return false;
857     }
858   }
859
860   // Never thunk a strong function to a weak function.
861   assert(!OldF.getFunc()->mayBeOverridden() ||
862          NewF.getFunc()->mayBeOverridden());
863
864   DEBUG(dbgs() << "  " << OldF.getFunc()->getName() << " == "
865                << NewF.getFunc()->getName() << '\n');
866
867   Function *DeleteF = NewF.getFunc();
868   NewF.release();
869   mergeTwoFunctions(OldF.getFunc(), DeleteF);
870   return true;
871 }
872
873 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
874 // so that we'll look at it in the next round.
875 void MergeFunctions::remove(Function *F) {
876   // We need to make sure we remove F, not a function "equal" to F per the
877   // function equality comparator.
878   //
879   // The special "lookup only" ComparableFunction bypasses the expensive
880   // function comparison in favour of a pointer comparison on the underlying
881   // Function*'s.
882   ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
883   if (FnSet.erase(CF)) {
884     DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
885     Deferred.push_back(F);
886   }
887 }
888
889 // For each instruction used by the value, remove() the function that contains
890 // the instruction. This should happen right before a call to RAUW.
891 void MergeFunctions::removeUsers(Value *V) {
892   std::vector<Value *> Worklist;
893   Worklist.push_back(V);
894   while (!Worklist.empty()) {
895     Value *V = Worklist.back();
896     Worklist.pop_back();
897
898     for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
899          UI != UE; ++UI) {
900       Use &U = UI.getUse();
901       if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
902         remove(I->getParent()->getParent());
903       } else if (isa<GlobalValue>(U.getUser())) {
904         // do nothing
905       } else if (Constant *C = dyn_cast<Constant>(U.getUser())) {
906         for (Value::use_iterator CUI = C->use_begin(), CUE = C->use_end();
907              CUI != CUE; ++CUI)
908           Worklist.push_back(*CUI);
909       }
910     }
911   }
912 }