MergeFunctions.cpp revision c25e7581b9b8088910da31702d4ca21c4734c6d7
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. We can only fold two
21// functions when we know that the definition of one of them is not
22// overridable.
23//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
28// * fold vector<T*>::push_back and vector<S*>::push_back.
29//
30// These two functions have different types, but in a way that doesn't matter
31// to us. As long as we never see an S or T itself, using S* and S** is the
32// same as using a T* and T**.
33//
34// * virtual functions.
35//
36// Many functions have their address taken by the virtual function table for
37// the object they belong to. However, as long as it's only used for a lookup
38// and call, this is irrelevant, and we'd like to fold such implementations.
39//
40//===----------------------------------------------------------------------===//
41
42#define DEBUG_TYPE "mergefunc"
43#include "llvm/Transforms/IPO.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/FoldingSet.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/Constants.h"
48#include "llvm/InlineAsm.h"
49#include "llvm/Instructions.h"
50#include "llvm/LLVMContext.h"
51#include "llvm/Module.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/CallSite.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include <map>
58#include <vector>
59using namespace llvm;
60
61STATISTIC(NumFunctionsMerged, "Number of functions merged");
62
63namespace {
64  struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass {
65    static char ID; // Pass identification, replacement for typeid
66    MergeFunctions() : ModulePass((intptr_t)&ID) {}
67
68    bool runOnModule(Module &M);
69  };
70}
71
72char MergeFunctions::ID = 0;
73static RegisterPass<MergeFunctions>
74X("mergefunc", "Merge Functions");
75
76ModulePass *llvm::createMergeFunctionsPass() {
77  return new MergeFunctions();
78}
79
80// ===----------------------------------------------------------------------===
81// Comparison of functions
82// ===----------------------------------------------------------------------===
83
84static unsigned long hash(const Function *F) {
85  const FunctionType *FTy = F->getFunctionType();
86
87  FoldingSetNodeID ID;
88  ID.AddInteger(F->size());
89  ID.AddInteger(F->getCallingConv());
90  ID.AddBoolean(F->hasGC());
91  ID.AddBoolean(FTy->isVarArg());
92  ID.AddInteger(FTy->getReturnType()->getTypeID());
93  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
94    ID.AddInteger(FTy->getParamType(i)->getTypeID());
95  return ID.ComputeHash();
96}
97
98/// IgnoreBitcasts - given a bitcast, returns the first non-bitcast found by
99/// walking the chain of cast operands. Otherwise, returns the argument.
100static Value* IgnoreBitcasts(Value *V) {
101  while (BitCastInst *BC = dyn_cast<BitCastInst>(V))
102    V = BC->getOperand(0);
103
104  return V;
105}
106
107/// isEquivalentType - any two pointers are equivalent. Otherwise, standard
108/// type equivalence rules apply.
109static bool isEquivalentType(const Type *Ty1, const Type *Ty2) {
110  if (Ty1 == Ty2)
111    return true;
112  if (Ty1->getTypeID() != Ty2->getTypeID())
113    return false;
114
115  switch(Ty1->getTypeID()) {
116  case Type::VoidTyID:
117  case Type::FloatTyID:
118  case Type::DoubleTyID:
119  case Type::X86_FP80TyID:
120  case Type::FP128TyID:
121  case Type::PPC_FP128TyID:
122  case Type::LabelTyID:
123  case Type::MetadataTyID:
124    return true;
125
126  case Type::IntegerTyID:
127  case Type::OpaqueTyID:
128    // Ty1 == Ty2 would have returned true earlier.
129    return false;
130
131  default:
132    LLVM_UNREACHABLE("Unknown type!");
133    return false;
134
135  case Type::PointerTyID: {
136    const PointerType *PTy1 = cast<PointerType>(Ty1);
137    const PointerType *PTy2 = cast<PointerType>(Ty2);
138    return PTy1->getAddressSpace() == PTy2->getAddressSpace();
139  }
140
141  case Type::StructTyID: {
142    const StructType *STy1 = cast<StructType>(Ty1);
143    const StructType *STy2 = cast<StructType>(Ty2);
144    if (STy1->getNumElements() != STy2->getNumElements())
145      return false;
146
147    if (STy1->isPacked() != STy2->isPacked())
148      return false;
149
150    for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
151      if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
152        return false;
153    }
154    return true;
155  }
156
157  case Type::FunctionTyID: {
158    const FunctionType *FTy1 = cast<FunctionType>(Ty1);
159    const FunctionType *FTy2 = cast<FunctionType>(Ty2);
160    if (FTy1->getNumParams() != FTy2->getNumParams() ||
161        FTy1->isVarArg() != FTy2->isVarArg())
162      return false;
163
164    if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
165      return false;
166
167    for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
168      if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
169        return false;
170    }
171    return true;
172  }
173
174  case Type::ArrayTyID:
175  case Type::VectorTyID: {
176    const SequentialType *STy1 = cast<SequentialType>(Ty1);
177    const SequentialType *STy2 = cast<SequentialType>(Ty2);
178    return isEquivalentType(STy1->getElementType(), STy2->getElementType());
179  }
180  }
181}
182
183/// isEquivalentOperation - determine whether the two operations are the same
184/// except that pointer-to-A and pointer-to-B are equivalent. This should be
185/// kept in sync with Instruction::isSameOperationAs.
186static bool
187isEquivalentOperation(const Instruction *I1, const Instruction *I2) {
188  if (I1->getOpcode() != I2->getOpcode() ||
189      I1->getNumOperands() != I2->getNumOperands() ||
190      !isEquivalentType(I1->getType(), I2->getType()))
191    return false;
192
193  // We have two instructions of identical opcode and #operands.  Check to see
194  // if all operands are the same type
195  for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
196    if (!isEquivalentType(I1->getOperand(i)->getType(),
197                          I2->getOperand(i)->getType()))
198      return false;
199
200  // Check special state that is a part of some instructions.
201  if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
202    return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
203           LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
204  if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
205    return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
206           SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
207  if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
208    return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
209  if (const CallInst *CI = dyn_cast<CallInst>(I1))
210    return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
211           CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
212           CI->getAttributes().getRawPointer() ==
213             cast<CallInst>(I2)->getAttributes().getRawPointer();
214  if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
215    return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
216           CI->getAttributes().getRawPointer() ==
217             cast<InvokeInst>(I2)->getAttributes().getRawPointer();
218  if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
219    if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
220      return false;
221    for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
222      if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
223        return false;
224    return true;
225  }
226  if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
227    if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
228      return false;
229    for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
230      if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
231        return false;
232    return true;
233  }
234
235  return true;
236}
237
238static bool compare(const Value *V, const Value *U) {
239  assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
240         "Must not compare basic blocks.");
241
242  assert(isEquivalentType(V->getType(), U->getType()) &&
243        "Two of the same operation have operands of different type.");
244
245  // TODO: If the constant is an expression of F, we should accept that it's
246  // equal to the same expression in terms of G.
247  if (isa<Constant>(V))
248    return V == U;
249
250  // The caller has ensured that ValueMap[V] != U. Since Arguments are
251  // pre-loaded into the ValueMap, and Instructions are added as we go, we know
252  // that this can only be a mis-match.
253  if (isa<Instruction>(V) || isa<Argument>(V))
254    return false;
255
256  if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
257    const InlineAsm *IAF = cast<InlineAsm>(V);
258    const InlineAsm *IAG = cast<InlineAsm>(U);
259    return IAF->getAsmString() == IAG->getAsmString() &&
260           IAF->getConstraintString() == IAG->getConstraintString();
261  }
262
263  return false;
264}
265
266static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
267                   DenseMap<const Value *, const Value *> &ValueMap,
268                   DenseMap<const Value *, const Value *> &SpeculationMap) {
269  // Speculatively add it anyways. If it's false, we'll notice a difference
270  // later, and this won't matter.
271  ValueMap[BB1] = BB2;
272
273  BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
274  BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
275
276  do {
277    if (isa<BitCastInst>(FI)) {
278      ++FI;
279      continue;
280    }
281    if (isa<BitCastInst>(GI)) {
282      ++GI;
283      continue;
284    }
285
286    if (!isEquivalentOperation(FI, GI))
287      return false;
288
289    if (isa<GetElementPtrInst>(FI)) {
290      const GetElementPtrInst *GEPF = cast<GetElementPtrInst>(FI);
291      const GetElementPtrInst *GEPG = cast<GetElementPtrInst>(GI);
292      if (GEPF->hasAllZeroIndices() && GEPG->hasAllZeroIndices()) {
293        // It's effectively a bitcast.
294        ++FI, ++GI;
295        continue;
296      }
297
298      // TODO: we only really care about the elements before the index
299      if (FI->getOperand(0)->getType() != GI->getOperand(0)->getType())
300        return false;
301    }
302
303    if (ValueMap[FI] == GI) {
304      ++FI, ++GI;
305      continue;
306    }
307
308    if (ValueMap[FI] != NULL)
309      return false;
310
311    for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
312      Value *OpF = IgnoreBitcasts(FI->getOperand(i));
313      Value *OpG = IgnoreBitcasts(GI->getOperand(i));
314
315      if (ValueMap[OpF] == OpG)
316        continue;
317
318      if (ValueMap[OpF] != NULL)
319        return false;
320
321      if (OpF->getValueID() != OpG->getValueID() ||
322          !isEquivalentType(OpF->getType(), OpG->getType()))
323        return false;
324
325      if (isa<PHINode>(FI)) {
326        if (SpeculationMap[OpF] == NULL)
327          SpeculationMap[OpF] = OpG;
328        else if (SpeculationMap[OpF] != OpG)
329          return false;
330        continue;
331      } else if (isa<BasicBlock>(OpF)) {
332        assert(isa<TerminatorInst>(FI) &&
333               "BasicBlock referenced by non-Terminator non-PHI");
334        // This call changes the ValueMap, hence we can't use
335        // Value *& = ValueMap[...]
336        if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
337                    SpeculationMap))
338          return false;
339      } else {
340        if (!compare(OpF, OpG))
341          return false;
342      }
343
344      ValueMap[OpF] = OpG;
345    }
346
347    ValueMap[FI] = GI;
348    ++FI, ++GI;
349  } while (FI != FE && GI != GE);
350
351  return FI == FE && GI == GE;
352}
353
354static bool equals(const Function *F, const Function *G) {
355  // We need to recheck everything, but check the things that weren't included
356  // in the hash first.
357
358  if (F->getAttributes() != G->getAttributes())
359    return false;
360
361  if (F->hasGC() != G->hasGC())
362    return false;
363
364  if (F->hasGC() && F->getGC() != G->getGC())
365    return false;
366
367  if (F->hasSection() != G->hasSection())
368    return false;
369
370  if (F->hasSection() && F->getSection() != G->getSection())
371    return false;
372
373  if (F->isVarArg() != G->isVarArg())
374    return false;
375
376  // TODO: if it's internal and only used in direct calls, we could handle this
377  // case too.
378  if (F->getCallingConv() != G->getCallingConv())
379    return false;
380
381  if (!isEquivalentType(F->getFunctionType(), G->getFunctionType()))
382    return false;
383
384  DenseMap<const Value *, const Value *> ValueMap;
385  DenseMap<const Value *, const Value *> SpeculationMap;
386  ValueMap[F] = G;
387
388  assert(F->arg_size() == G->arg_size() &&
389         "Identical functions have a different number of args.");
390
391  for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
392         fe = F->arg_end(); fi != fe; ++fi, ++gi)
393    ValueMap[fi] = gi;
394
395  if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
396              SpeculationMap))
397    return false;
398
399  for (DenseMap<const Value *, const Value *>::iterator
400         I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
401    if (ValueMap[I->first] != I->second)
402      return false;
403  }
404
405  return true;
406}
407
408// ===----------------------------------------------------------------------===
409// Folding of functions
410// ===----------------------------------------------------------------------===
411
412// Cases:
413// * F is external strong, G is external strong:
414//   turn G into a thunk to F    (1)
415// * F is external strong, G is external weak:
416//   turn G into a thunk to F    (1)
417// * F is external weak, G is external weak:
418//   unfoldable
419// * F is external strong, G is internal:
420//   address of G taken:
421//     turn G into a thunk to F  (1)
422//   address of G not taken:
423//     make G an alias to F      (2)
424// * F is internal, G is external weak
425//   address of F is taken:
426//     turn G into a thunk to F  (1)
427//   address of F is not taken:
428//     make G an alias of F      (2)
429// * F is internal, G is internal:
430//   address of F and G are taken:
431//     turn G into a thunk to F  (1)
432//   address of G is not taken:
433//     make G an alias to F      (2)
434//
435// alias requires linkage == (external,local,weak) fallback to creating a thunk
436// external means 'externally visible' linkage != (internal,private)
437// internal means linkage == (internal,private)
438// weak means linkage mayBeOverridable
439// being external implies that the address is taken
440//
441// 1. turn G into a thunk to F
442// 2. make G an alias to F
443
444enum LinkageCategory {
445  ExternalStrong,
446  ExternalWeak,
447  Internal
448};
449
450static LinkageCategory categorize(const Function *F) {
451  switch (F->getLinkage()) {
452  case GlobalValue::InternalLinkage:
453  case GlobalValue::PrivateLinkage:
454    return Internal;
455
456  case GlobalValue::WeakAnyLinkage:
457  case GlobalValue::WeakODRLinkage:
458  case GlobalValue::ExternalWeakLinkage:
459    return ExternalWeak;
460
461  case GlobalValue::ExternalLinkage:
462  case GlobalValue::AvailableExternallyLinkage:
463  case GlobalValue::LinkOnceAnyLinkage:
464  case GlobalValue::LinkOnceODRLinkage:
465  case GlobalValue::AppendingLinkage:
466  case GlobalValue::DLLImportLinkage:
467  case GlobalValue::DLLExportLinkage:
468  case GlobalValue::GhostLinkage:
469  case GlobalValue::CommonLinkage:
470    return ExternalStrong;
471  }
472
473  LLVM_UNREACHABLE("Unknown LinkageType.");
474  return ExternalWeak;
475}
476
477static void ThunkGToF(Function *F, Function *G) {
478  Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
479                                    G->getParent());
480  BasicBlock *BB = BasicBlock::Create("", NewG);
481
482  std::vector<Value *> Args;
483  unsigned i = 0;
484  const FunctionType *FFTy = F->getFunctionType();
485  for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
486       AI != AE; ++AI) {
487    if (FFTy->getParamType(i) == AI->getType())
488      Args.push_back(AI);
489    else {
490      Value *BCI = new BitCastInst(AI, FFTy->getParamType(i), "", BB);
491      Args.push_back(BCI);
492    }
493    ++i;
494  }
495
496  CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
497  CI->setTailCall();
498  CI->setCallingConv(F->getCallingConv());
499  if (NewG->getReturnType() == Type::VoidTy) {
500    ReturnInst::Create(BB);
501  } else if (CI->getType() != NewG->getReturnType()) {
502    Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
503    ReturnInst::Create(BCI, BB);
504  } else {
505    ReturnInst::Create(CI, BB);
506  }
507
508  NewG->copyAttributesFrom(G);
509  NewG->takeName(G);
510  G->replaceAllUsesWith(NewG);
511  G->eraseFromParent();
512
513  // TODO: look at direct callers to G and make them all direct callers to F.
514}
515
516static void AliasGToF(Function *F, Function *G) {
517  if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
518    return ThunkGToF(F, G);
519
520  GlobalAlias *GA = new GlobalAlias(
521    G->getType(), G->getLinkage(), "",
522    F->getContext()->getConstantExprBitCast(F, G->getType()), G->getParent());
523  F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
524  GA->takeName(G);
525  GA->setVisibility(G->getVisibility());
526  G->replaceAllUsesWith(GA);
527  G->eraseFromParent();
528}
529
530static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
531  Function *F = FnVec[i];
532  Function *G = FnVec[j];
533
534  LinkageCategory catF = categorize(F);
535  LinkageCategory catG = categorize(G);
536
537  if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
538    std::swap(FnVec[i], FnVec[j]);
539    std::swap(F, G);
540    std::swap(catF, catG);
541  }
542
543  switch (catF) {
544    case ExternalStrong:
545      switch (catG) {
546        case ExternalStrong:
547        case ExternalWeak:
548          ThunkGToF(F, G);
549          break;
550        case Internal:
551          if (G->hasAddressTaken())
552            ThunkGToF(F, G);
553          else
554            AliasGToF(F, G);
555          break;
556      }
557      break;
558
559    case ExternalWeak: {
560      assert(catG == ExternalWeak);
561
562      // Make them both thunks to the same internal function.
563      F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
564      Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
565                                     F->getParent());
566      H->copyAttributesFrom(F);
567      H->takeName(F);
568      F->replaceAllUsesWith(H);
569
570      ThunkGToF(F, G);
571      ThunkGToF(F, H);
572
573      F->setLinkage(GlobalValue::InternalLinkage);
574    } break;
575
576    case Internal:
577      switch (catG) {
578        case ExternalStrong:
579          llvm_unreachable();
580          // fall-through
581        case ExternalWeak:
582	  if (F->hasAddressTaken())
583            ThunkGToF(F, G);
584          else
585            AliasGToF(F, G);
586	  break;
587        case Internal: {
588          bool addrTakenF = F->hasAddressTaken();
589          bool addrTakenG = G->hasAddressTaken();
590          if (!addrTakenF && addrTakenG) {
591            std::swap(FnVec[i], FnVec[j]);
592            std::swap(F, G);
593	    std::swap(addrTakenF, addrTakenG);
594	  }
595
596          if (addrTakenF && addrTakenG) {
597            ThunkGToF(F, G);
598          } else {
599            assert(!addrTakenG);
600            AliasGToF(F, G);
601          }
602	} break;
603      }
604      break;
605  }
606
607  ++NumFunctionsMerged;
608  return true;
609}
610
611// ===----------------------------------------------------------------------===
612// Pass definition
613// ===----------------------------------------------------------------------===
614
615bool MergeFunctions::runOnModule(Module &M) {
616  bool Changed = false;
617
618  std::map<unsigned long, std::vector<Function *> > FnMap;
619
620  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
621    if (F->isDeclaration() || F->isIntrinsic())
622      continue;
623
624    FnMap[hash(F)].push_back(F);
625  }
626
627  // TODO: instead of running in a loop, we could also fold functions in
628  // callgraph order. Constructing the CFG probably isn't cheaper than just
629  // running in a loop, unless it happened to already be available.
630
631  bool LocalChanged;
632  do {
633    LocalChanged = false;
634    DOUT << "size: " << FnMap.size() << "\n";
635    for (std::map<unsigned long, std::vector<Function *> >::iterator
636         I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
637      std::vector<Function *> &FnVec = I->second;
638      DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
639
640      for (int i = 0, e = FnVec.size(); i != e; ++i) {
641        for (int j = i + 1; j != e; ++j) {
642          bool isEqual = equals(FnVec[i], FnVec[j]);
643
644          DOUT << "  " << FnVec[i]->getName()
645               << (isEqual ? " == " : " != ")
646               << FnVec[j]->getName() << "\n";
647
648          if (isEqual) {
649            if (fold(FnVec, i, j)) {
650              LocalChanged = true;
651              FnVec.erase(FnVec.begin() + j);
652              --j, --e;
653            }
654          }
655        }
656      }
657
658    }
659    Changed |= LocalChanged;
660  } while (LocalChanged);
661
662  return Changed;
663}
664