MergeFunctions.cpp revision f50a75f75ce2a1cb834c4fb7b13ddac11cd9b9d4
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 implementations.
33//
34// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
36//
37// * be smarter about bitcast.
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 peer through bitcasts without imposing bad
43// performance properties.
44//
45// * emit aliases for ELF
46//
47// ELF supports symbol aliases which are represented with GlobalAlias in the
48// Module, and we could emit them in the case that the addresses don't need to
49// be distinct. The problem is that not all object formats support equivalent
50// functionality. There's a few approaches to this problem;
51//   a) teach codegen to lower global aliases to thunks on platforms which don't
52//      support them.
53//   b) always emit thunks, and create a separate thunk-to-alias pass which
54//      runs on ELF systems. This has the added benefit of transforming other
55//      thunks such as those produced by a C++ frontend into aliases when legal
56//      to do so.
57//
58//===----------------------------------------------------------------------===//
59
60#define DEBUG_TYPE "mergefunc"
61#include "llvm/Transforms/IPO.h"
62#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/FoldingSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/Constants.h"
67#include "llvm/InlineAsm.h"
68#include "llvm/Instructions.h"
69#include "llvm/LLVMContext.h"
70#include "llvm/Module.h"
71#include "llvm/Pass.h"
72#include "llvm/Support/CallSite.h"
73#include "llvm/Support/Debug.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/raw_ostream.h"
76#include "llvm/Target/TargetData.h"
77#include <map>
78#include <vector>
79using namespace llvm;
80
81STATISTIC(NumFunctionsMerged, "Number of functions merged");
82
83namespace {
84  /// MergeFunctions finds functions which will generate identical machine code,
85  /// by considering all pointer types to be equivalent. Once identified,
86  /// MergeFunctions will fold them by replacing a call to one to a call to a
87  /// bitcast of the other.
88  ///
89  struct MergeFunctions : public ModulePass {
90    static char ID; // Pass identification, replacement for typeid
91    MergeFunctions() : ModulePass(&ID) {}
92
93    bool runOnModule(Module &M);
94  };
95}
96
97char MergeFunctions::ID = 0;
98INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false);
99
100ModulePass *llvm::createMergeFunctionsPass() {
101  return new MergeFunctions();
102}
103
104// ===----------------------------------------------------------------------===
105// Comparison of functions
106// ===----------------------------------------------------------------------===
107namespace {
108class FunctionComparator {
109public:
110  FunctionComparator(TargetData *TD, Function *F1, Function *F2)
111    : TD(TD), F1(F1), F2(F2) {}
112
113  // Compare - test whether the two functions have equivalent behaviour.
114  bool Compare();
115
116private:
117  // Compare - test whether two basic blocks have equivalent behaviour.
118  bool Compare(const BasicBlock *BB1, const BasicBlock *BB2);
119
120  // getDomain - a value's domain is its parent function if it is specific to a
121  // function, or NULL otherwise.
122  const Function *getDomain(const Value *V) const;
123
124  // Enumerate - Assign or look up previously assigned numbers for the two
125  // values, and return whether the numbers are equal. Numbers are assigned in
126  // the order visited.
127  bool Enumerate(const Value *V1, const Value *V2);
128
129  // isEquivalentOperation - Compare two Instructions for equivalence, similar
130  // to Instruction::isSameOperationAs but with modifications to the type
131  // comparison.
132  bool isEquivalentOperation(const Instruction *I1,
133                             const Instruction *I2) const;
134
135  // isEquivalentGEP - Compare two GEPs for equivalent pointer arithmetic.
136  bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
137  bool isEquivalentGEP(const GetElementPtrInst *GEP1,
138		       const GetElementPtrInst *GEP2) {
139    return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
140  }
141
142  // isEquivalentType - Compare two Types, treating all pointer types as equal.
143  bool isEquivalentType(const Type *Ty1, const Type *Ty2) const;
144
145  // The two functions undergoing comparison.
146  Function *F1, *F2;
147
148  TargetData *TD;
149
150  typedef DenseMap<const Value *, unsigned long> IDMap;
151  IDMap Map;
152  DenseMap<const Function *, IDMap> Domains;
153  DenseMap<const Function *, unsigned long> DomainCount;
154};
155}
156
157/// Compute a number which is guaranteed to be equal for two equivalent
158/// functions, but is very likely to be different for different functions. This
159/// needs to be computed as efficiently as possible.
160static unsigned long ProfileFunction(const Function *F) {
161  const FunctionType *FTy = F->getFunctionType();
162
163  FoldingSetNodeID ID;
164  ID.AddInteger(F->size());
165  ID.AddInteger(F->getCallingConv());
166  ID.AddBoolean(F->hasGC());
167  ID.AddBoolean(FTy->isVarArg());
168  ID.AddInteger(FTy->getReturnType()->getTypeID());
169  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
170    ID.AddInteger(FTy->getParamType(i)->getTypeID());
171  return ID.ComputeHash();
172}
173
174/// isEquivalentType - any two pointers are equivalent. Otherwise, standard
175/// type equivalence rules apply.
176bool FunctionComparator::isEquivalentType(const Type *Ty1,
177                                          const Type *Ty2) const {
178  if (Ty1 == Ty2)
179    return true;
180  if (Ty1->getTypeID() != Ty2->getTypeID())
181    return false;
182
183  switch(Ty1->getTypeID()) {
184  default:
185    llvm_unreachable("Unknown type!");
186    // Fall through in Release mode.
187  case Type::IntegerTyID:
188  case Type::OpaqueTyID:
189    // Ty1 == Ty2 would have returned true earlier.
190    return false;
191
192  case Type::VoidTyID:
193  case Type::FloatTyID:
194  case Type::DoubleTyID:
195  case Type::X86_FP80TyID:
196  case Type::FP128TyID:
197  case Type::PPC_FP128TyID:
198  case Type::LabelTyID:
199  case Type::MetadataTyID:
200    return true;
201
202  case Type::PointerTyID: {
203    const PointerType *PTy1 = cast<PointerType>(Ty1);
204    const PointerType *PTy2 = cast<PointerType>(Ty2);
205    return PTy1->getAddressSpace() == PTy2->getAddressSpace();
206  }
207
208  case Type::StructTyID: {
209    const StructType *STy1 = cast<StructType>(Ty1);
210    const StructType *STy2 = cast<StructType>(Ty2);
211    if (STy1->getNumElements() != STy2->getNumElements())
212      return false;
213
214    if (STy1->isPacked() != STy2->isPacked())
215      return false;
216
217    for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
218      if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
219        return false;
220    }
221    return true;
222  }
223
224  case Type::UnionTyID: {
225    const UnionType *UTy1 = cast<UnionType>(Ty1);
226    const UnionType *UTy2 = cast<UnionType>(Ty2);
227
228    // TODO: we could be fancy with union(A, union(A, B)) === union(A, B), etc.
229    if (UTy1->getNumElements() != UTy2->getNumElements())
230      return false;
231
232    for (unsigned i = 0, e = UTy1->getNumElements(); i != e; ++i) {
233      if (!isEquivalentType(UTy1->getElementType(i), UTy2->getElementType(i)))
234        return false;
235    }
236    return true;
237  }
238
239  case Type::FunctionTyID: {
240    const FunctionType *FTy1 = cast<FunctionType>(Ty1);
241    const FunctionType *FTy2 = cast<FunctionType>(Ty2);
242    if (FTy1->getNumParams() != FTy2->getNumParams() ||
243        FTy1->isVarArg() != FTy2->isVarArg())
244      return false;
245
246    if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
247      return false;
248
249    for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
250      if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
251        return false;
252    }
253    return true;
254  }
255
256  case Type::ArrayTyID: {
257    const ArrayType *ATy1 = cast<ArrayType>(Ty1);
258    const ArrayType *ATy2 = cast<ArrayType>(Ty2);
259    return ATy1->getNumElements() == ATy2->getNumElements() &&
260           isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
261  }
262  case Type::VectorTyID: {
263    const VectorType *VTy1 = cast<VectorType>(Ty1);
264    const VectorType *VTy2 = cast<VectorType>(Ty2);
265    return VTy1->getNumElements() == VTy2->getNumElements() &&
266           isEquivalentType(VTy1->getElementType(), VTy2->getElementType());
267  }
268  }
269}
270
271/// isEquivalentOperation - determine whether the two operations are the same
272/// except that pointer-to-A and pointer-to-B are equivalent. This should be
273/// kept in sync with Instruction::isSameOperationAs.
274bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
275                                               const Instruction *I2) const {
276  if (I1->getOpcode() != I2->getOpcode() ||
277      I1->getNumOperands() != I2->getNumOperands() ||
278      !isEquivalentType(I1->getType(), I2->getType()) ||
279      !I1->hasSameSubclassOptionalData(I2))
280    return false;
281
282  // We have two instructions of identical opcode and #operands.  Check to see
283  // if all operands are the same type
284  for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
285    if (!isEquivalentType(I1->getOperand(i)->getType(),
286                          I2->getOperand(i)->getType()))
287      return false;
288
289  // Check special state that is a part of some instructions.
290  if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
291    return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
292           LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
293  if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
294    return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
295           SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
296  if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
297    return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
298  if (const CallInst *CI = dyn_cast<CallInst>(I1))
299    return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
300           CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
301           CI->getAttributes().getRawPointer() ==
302             cast<CallInst>(I2)->getAttributes().getRawPointer();
303  if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
304    return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
305           CI->getAttributes().getRawPointer() ==
306             cast<InvokeInst>(I2)->getAttributes().getRawPointer();
307  if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
308    if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
309      return false;
310    for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
311      if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
312        return false;
313    return true;
314  }
315  if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
316    if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
317      return false;
318    for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
319      if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
320        return false;
321    return true;
322  }
323
324  return true;
325}
326
327/// isEquivalentGEP - determine whether two GEP operations perform the same
328/// underlying arithmetic.
329bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
330                                         const GEPOperator *GEP2) {
331  // When we have target data, we can reduce the GEP down to the value in bytes
332  // added to the address.
333  if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) {
334    SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end());
335    SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end());
336    uint64_t Offset1 = TD->getIndexedOffset(GEP1->getPointerOperandType(),
337                                            Indices1.data(), Indices1.size());
338    uint64_t Offset2 = TD->getIndexedOffset(GEP2->getPointerOperandType(),
339                                            Indices2.data(), Indices2.size());
340    return Offset1 == Offset2;
341  }
342
343  if (GEP1->getPointerOperand()->getType() !=
344      GEP2->getPointerOperand()->getType())
345    return false;
346
347  if (GEP1->getNumOperands() != GEP2->getNumOperands())
348    return false;
349
350  for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
351    if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
352      return false;
353  }
354
355  return true;
356}
357
358/// getDomain - a value's domain is its parent function if it is specific to a
359/// function, or NULL otherwise.
360const Function *FunctionComparator::getDomain(const Value *V) const {
361  if (const Argument *A = dyn_cast<Argument>(V)) {
362    return A->getParent();
363  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
364    return BB->getParent();
365  } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
366    return I->getParent()->getParent();
367  }
368  return NULL;
369}
370
371/// Enumerate - Compare two values used by the two functions under pair-wise
372/// comparison. If this is the first time the values are seen, they're added to
373/// the mapping so that we will detect mismatches on next use.
374bool FunctionComparator::Enumerate(const Value *V1, const Value *V2) {
375  // Check for function @f1 referring to itself and function @f2 referring to
376  // itself, or referring to each other, or both referring to either of them.
377  // They're all equivalent if the two functions are otherwise equivalent.
378  if (V1 == F1 || V1 == F2)
379    if (V2 == F1 || V2 == F2)
380      return true;
381
382  // TODO: constant expressions with GEP or references to F1 or F2.
383  if (isa<Constant>(V1))
384    return V1 == V2;
385
386  if (isa<InlineAsm>(V1) && isa<InlineAsm>(V2)) {
387    const InlineAsm *IA1 = cast<InlineAsm>(V1);
388    const InlineAsm *IA2 = cast<InlineAsm>(V2);
389    return IA1->getAsmString() == IA2->getAsmString() &&
390           IA1->getConstraintString() == IA2->getConstraintString();
391  }
392
393  // We enumerate constants globally and arguments, basic blocks or
394  // instructions within the function they belong to.
395  const Function *Domain1 = getDomain(V1);
396  const Function *Domain2 = getDomain(V2);
397
398  // The domains have to either be both NULL, or F1, F2.
399  if (Domain1 != Domain2)
400    if (Domain1 != F1 && Domain1 != F2)
401      return false;
402
403  IDMap &Map1 = Domains[Domain1];
404  unsigned long &ID1 = Map1[V1];
405  if (!ID1)
406    ID1 = ++DomainCount[Domain1];
407
408  IDMap &Map2 = Domains[Domain2];
409  unsigned long &ID2 = Map2[V2];
410  if (!ID2)
411    ID2 = ++DomainCount[Domain2];
412
413  return ID1 == ID2;
414}
415
416// Compare - test whether two basic blocks have equivalent behaviour.
417bool FunctionComparator::Compare(const BasicBlock *BB1, const BasicBlock *BB2) {
418  BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
419  BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
420
421  do {
422    if (!Enumerate(F1I, F2I))
423      return false;
424
425    if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
426      const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
427      if (!GEP2)
428        return false;
429
430      if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
431        return false;
432
433      if (!isEquivalentGEP(GEP1, GEP2))
434        return false;
435    } else {
436      if (!isEquivalentOperation(F1I, F2I))
437        return false;
438
439      assert(F1I->getNumOperands() == F2I->getNumOperands());
440      for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
441        Value *OpF1 = F1I->getOperand(i);
442        Value *OpF2 = F2I->getOperand(i);
443
444        if (!Enumerate(OpF1, OpF2))
445          return false;
446
447        if (OpF1->getValueID() != OpF2->getValueID() ||
448            !isEquivalentType(OpF1->getType(), OpF2->getType()))
449          return false;
450      }
451    }
452
453    ++F1I, ++F2I;
454  } while (F1I != F1E && F2I != F2E);
455
456  return F1I == F1E && F2I == F2E;
457}
458
459bool FunctionComparator::Compare() {
460  // We need to recheck everything, but check the things that weren't included
461  // in the hash first.
462
463  if (F1->getAttributes() != F2->getAttributes())
464    return false;
465
466  if (F1->hasGC() != F2->hasGC())
467    return false;
468
469  if (F1->hasGC() && F1->getGC() != F2->getGC())
470    return false;
471
472  if (F1->hasSection() != F2->hasSection())
473    return false;
474
475  if (F1->hasSection() && F1->getSection() != F2->getSection())
476    return false;
477
478  if (F1->isVarArg() != F2->isVarArg())
479    return false;
480
481  // TODO: if it's internal and only used in direct calls, we could handle this
482  // case too.
483  if (F1->getCallingConv() != F2->getCallingConv())
484    return false;
485
486  if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
487    return false;
488
489  assert(F1->arg_size() == F2->arg_size() &&
490         "Identical functions have a different number of args.");
491
492  // Visit the arguments so that they get enumerated in the order they're
493  // passed in.
494  for (Function::const_arg_iterator f1i = F1->arg_begin(),
495         f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
496    if (!Enumerate(f1i, f2i))
497      llvm_unreachable("Arguments repeat");
498  }
499
500  // We need to do an ordered walk since the actual ordering of the blocks in
501  // the linked list is immaterial. Our walk starts at the entry block for both
502  // functions, then takes each block from each terminator in order. As an
503  // artifact, this also means that unreachable blocks are ignored.
504  SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
505  SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
506  F1BBs.push_back(&F1->getEntryBlock());
507  F2BBs.push_back(&F2->getEntryBlock());
508  VisitedBBs.insert(F1BBs[0]);
509  while (!F1BBs.empty()) {
510    const BasicBlock *F1BB = F1BBs.pop_back_val();
511    const BasicBlock *F2BB = F2BBs.pop_back_val();
512    if (!Enumerate(F1BB, F2BB) || !Compare(F1BB, F2BB))
513      return false;
514    const TerminatorInst *F1TI = F1BB->getTerminator();
515    const TerminatorInst *F2TI = F2BB->getTerminator();
516    assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
517    for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
518      if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
519        continue;
520      F1BBs.push_back(F1TI->getSuccessor(i));
521      F2BBs.push_back(F2TI->getSuccessor(i));
522    }
523  }
524  return true;
525}
526
527// ===----------------------------------------------------------------------===
528// Folding of functions
529// ===----------------------------------------------------------------------===
530
531// Cases:
532// * F is external strong, G is external strong:
533//   turn G into a thunk to F    (1)
534// * F is external strong, G is external weak:
535//   turn G into a thunk to F    (1)
536// * F is external weak, G is external weak:
537//   unfoldable
538// * F is external strong, G is internal:
539//   address of G taken:
540//     turn G into a thunk to F  (1)
541//   address of G not taken:
542//     make G an alias to F      (2)
543// * F is internal, G is external weak
544//   address of F is taken:
545//     turn G into a thunk to F  (1)
546//   address of F is not taken:
547//     make G an alias of F      (2)
548// * F is internal, G is internal:
549//   address of F and G are taken:
550//     turn G into a thunk to F  (1)
551//   address of G is not taken:
552//     make G an alias to F      (2)
553//
554// alias requires linkage == (external,local,weak) fallback to creating a thunk
555// external means 'externally visible' linkage != (internal,private)
556// internal means linkage == (internal,private)
557// weak means linkage mayBeOverridable
558// being external implies that the address is taken
559//
560// 1. turn G into a thunk to F
561// 2. make G an alias to F
562
563enum LinkageCategory {
564  ExternalStrong,
565  ExternalWeak,
566  Internal
567};
568
569static LinkageCategory categorize(const Function *F) {
570  switch (F->getLinkage()) {
571  case GlobalValue::InternalLinkage:
572  case GlobalValue::PrivateLinkage:
573  case GlobalValue::LinkerPrivateLinkage:
574    return Internal;
575
576  case GlobalValue::WeakAnyLinkage:
577  case GlobalValue::WeakODRLinkage:
578  case GlobalValue::ExternalWeakLinkage:
579  case GlobalValue::LinkerPrivateWeakLinkage:
580    return ExternalWeak;
581
582  case GlobalValue::ExternalLinkage:
583  case GlobalValue::AvailableExternallyLinkage:
584  case GlobalValue::LinkOnceAnyLinkage:
585  case GlobalValue::LinkOnceODRLinkage:
586  case GlobalValue::AppendingLinkage:
587  case GlobalValue::DLLImportLinkage:
588  case GlobalValue::DLLExportLinkage:
589  case GlobalValue::CommonLinkage:
590    return ExternalStrong;
591  }
592
593  llvm_unreachable("Unknown LinkageType.");
594  return ExternalWeak;
595}
596
597static void ThunkGToF(Function *F, Function *G) {
598  if (!G->mayBeOverridden()) {
599    // Redirect direct callers of G to F.
600    Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
601    for (Value::use_iterator UI = G->use_begin(), UE = G->use_end();
602         UI != UE;) {
603      Value::use_iterator TheIter = UI;
604      ++UI;
605      CallSite CS(*TheIter);
606      if (CS && CS.isCallee(TheIter))
607        TheIter.getUse().set(BitcastF);
608    }
609  }
610
611  Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
612                                    G->getParent());
613  BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
614
615  SmallVector<Value *, 16> Args;
616  unsigned i = 0;
617  const FunctionType *FFTy = F->getFunctionType();
618  for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
619       AI != AE; ++AI) {
620    if (FFTy->getParamType(i) == AI->getType()) {
621      Args.push_back(AI);
622    } else {
623      Args.push_back(new BitCastInst(AI, FFTy->getParamType(i), "", BB));
624    }
625    ++i;
626  }
627
628  CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
629  CI->setTailCall();
630  CI->setCallingConv(F->getCallingConv());
631  if (NewG->getReturnType()->isVoidTy()) {
632    ReturnInst::Create(F->getContext(), BB);
633  } else if (CI->getType() != NewG->getReturnType()) {
634    Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
635    ReturnInst::Create(F->getContext(), BCI, BB);
636  } else {
637    ReturnInst::Create(F->getContext(), CI, BB);
638  }
639
640  NewG->copyAttributesFrom(G);
641  NewG->takeName(G);
642  G->replaceAllUsesWith(NewG);
643  G->eraseFromParent();
644}
645
646static void AliasGToF(Function *F, Function *G) {
647  // Darwin will trigger llvm_unreachable if asked to codegen an alias.
648  return ThunkGToF(F, G);
649
650#if 0
651  if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
652    return ThunkGToF(F, G);
653
654  GlobalAlias *GA = new GlobalAlias(
655    G->getType(), G->getLinkage(), "",
656    ConstantExpr::getBitCast(F, G->getType()), G->getParent());
657  F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
658  GA->takeName(G);
659  GA->setVisibility(G->getVisibility());
660  G->replaceAllUsesWith(GA);
661  G->eraseFromParent();
662#endif
663}
664
665static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
666  Function *F = FnVec[i];
667  Function *G = FnVec[j];
668
669  LinkageCategory catF = categorize(F);
670  LinkageCategory catG = categorize(G);
671
672  if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
673    std::swap(FnVec[i], FnVec[j]);
674    std::swap(F, G);
675    std::swap(catF, catG);
676  }
677
678  switch (catF) {
679  case ExternalStrong:
680    switch (catG) {
681    case ExternalStrong:
682    case ExternalWeak:
683      ThunkGToF(F, G);
684      break;
685    case Internal:
686      if (G->hasAddressTaken())
687        ThunkGToF(F, G);
688      else
689        AliasGToF(F, G);
690      break;
691    }
692    break;
693
694  case ExternalWeak: {
695    assert(catG == ExternalWeak);
696
697    // Make them both thunks to the same internal function.
698    F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
699    Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
700                                   F->getParent());
701    H->copyAttributesFrom(F);
702    H->takeName(F);
703    F->replaceAllUsesWith(H);
704
705    ThunkGToF(F, G);
706    ThunkGToF(F, H);
707
708    F->setLinkage(GlobalValue::InternalLinkage);
709  } break;
710
711  case Internal:
712    switch (catG) {
713    case ExternalStrong:
714      llvm_unreachable(0);
715      // fall-through
716    case ExternalWeak:
717      if (F->hasAddressTaken())
718        ThunkGToF(F, G);
719      else
720        AliasGToF(F, G);
721      break;
722    case Internal: {
723      bool addrTakenF = F->hasAddressTaken();
724      bool addrTakenG = G->hasAddressTaken();
725      if (!addrTakenF && addrTakenG) {
726        std::swap(FnVec[i], FnVec[j]);
727        std::swap(F, G);
728        std::swap(addrTakenF, addrTakenG);
729      }
730
731      if (addrTakenF && addrTakenG) {
732        ThunkGToF(F, G);
733      } else {
734        assert(!addrTakenG);
735        AliasGToF(F, G);
736      }
737    } break;
738  } break;
739  }
740
741  ++NumFunctionsMerged;
742  return true;
743}
744
745// ===----------------------------------------------------------------------===
746// Pass definition
747// ===----------------------------------------------------------------------===
748
749bool MergeFunctions::runOnModule(Module &M) {
750  bool Changed = false;
751
752  std::map<unsigned long, std::vector<Function *> > FnMap;
753
754  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
755    if (F->isDeclaration())
756      continue;
757
758    FnMap[ProfileFunction(F)].push_back(F);
759  }
760
761  TargetData *TD = getAnalysisIfAvailable<TargetData>();
762
763  bool LocalChanged;
764  do {
765    LocalChanged = false;
766    DEBUG(dbgs() << "size: " << FnMap.size() << "\n");
767    for (std::map<unsigned long, std::vector<Function *> >::iterator
768           I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
769      std::vector<Function *> &FnVec = I->second;
770      DEBUG(dbgs() << "hash (" << I->first << "): " << FnVec.size() << "\n");
771
772      for (int i = 0, e = FnVec.size(); i != e; ++i) {
773        for (int j = i + 1; j != e; ++j) {
774          bool isEqual = FunctionComparator(TD, FnVec[i], FnVec[j]).Compare();
775
776          DEBUG(dbgs() << "  " << FnVec[i]->getName()
777                << (isEqual ? " == " : " != ")
778                << FnVec[j]->getName() << "\n");
779
780          if (isEqual) {
781            if (fold(FnVec, i, j)) {
782              LocalChanged = true;
783              FnVec.erase(FnVec.begin() + j);
784              --j, --e;
785            }
786          }
787        }
788      }
789
790    }
791    Changed |= LocalChanged;
792  } while (LocalChanged);
793
794  return Changed;
795}
796