Get this building on 64 bit machines (error:
[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 Function will not be analyzed if:
13 // * it is overridable at runtime (except for weak linkage), or
14 // * it is used by anything other than the callee parameter of a call/invoke
15 //
16 // A hash is computed from the function, based on its type and number of
17 // basic blocks.
18 //
19 // Once all hashes are computed, we perform an expensive equality comparison
20 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
21 // important that the hash function be high quality. The equality comparison
22 // iterates through each instruction in each basic block.
23 //
24 // When a match is found, the functions are folded. We can only fold two
25 // functions when we know that the definition of one of them is not
26 // overridable.
27 // * fold a function marked internal by replacing all of its users.
28 // * fold extern or weak functions by replacing them with a global alias
29 //
30 //===----------------------------------------------------------------------===//
31 //
32 // Future work:
33 //
34 // * fold vector<T*>::push_back and vector<S*>::push_back.
35 //
36 // These two functions have different types, but in a way that doesn't matter
37 // to us. As long as we never see an S or T itself, using S* and S** is the
38 // same as using a T* and T**.
39 //
40 // * virtual functions.
41 //
42 // Many functions have their address taken by the virtual function table for
43 // the object they belong to. However, as long as it's only used for a lookup
44 // and call, this is irrelevant, and we'd like to fold such implementations.
45 //
46 //===----------------------------------------------------------------------===//
47
48 #define DEBUG_TYPE "mergefunc"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm/Constants.h"
53 #include "llvm/InlineAsm.h"
54 #include "llvm/Instructions.h"
55 #include "llvm/Module.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include <map>
60 #include <vector>
61 using namespace llvm;
62
63 STATISTIC(NumFunctionsMerged, "Number of functions merged");
64 STATISTIC(NumMergeFails, "Number of identical function pairings not merged");
65
66 namespace {
67   struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass {
68     static char ID; // Pass identification, replacement for typeid
69     MergeFunctions() : ModulePass((intptr_t)&ID) {}
70
71     bool runOnModule(Module &M);
72   };
73 }
74
75 char MergeFunctions::ID = 0;
76 static RegisterPass<MergeFunctions>
77 X("mergefunc", "Merge Functions");
78
79 ModulePass *llvm::createMergeFunctionsPass() {
80   return new MergeFunctions();
81 }
82
83 static unsigned long hash(const Function *F) {
84   return F->size() ^ reinterpret_cast<unsigned long>(F->getType());
85   //return F->size() ^ F->arg_size() ^ F->getReturnType();
86 }
87
88 static bool compare(const Value *V, const Value *U) {
89   assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
90          "Must not compare basic blocks.");
91
92   assert(V->getType() == U->getType() &&
93         "Two of the same operation have operands of different type.");
94
95   // TODO: If the constant is an expression of F, we should accept that it's
96   // equal to the same expression in terms of G.
97   if (isa<Constant>(V))
98     return V == U;
99
100   // The caller has ensured that ValueMap[V] != U. Since Arguments are
101   // pre-loaded into the ValueMap, and Instructions are added as we go, we know
102   // that this can only be a mis-match.
103   if (isa<Instruction>(V) || isa<Argument>(V))
104     return false;
105
106   if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
107     const InlineAsm *IAF = cast<InlineAsm>(V);
108     const InlineAsm *IAG = cast<InlineAsm>(U);
109     return IAF->getAsmString() == IAG->getAsmString() &&
110            IAF->getConstraintString() == IAG->getConstraintString();
111   }
112
113   return false;
114 }
115
116 static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
117                    DenseMap<const Value *, const Value *> &ValueMap,
118                    DenseMap<const Value *, const Value *> &SpeculationMap) {
119   // Specutively add it anyways. If it's false, we'll notice a difference later, and
120   // this won't matter.
121   ValueMap[BB1] = BB2;
122
123   BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
124   BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
125
126   do {
127     if (!FI->isSameOperationAs(const_cast<Instruction *>(&*GI)))
128       return false;
129
130     if (FI->getNumOperands() != GI->getNumOperands())
131       return false;
132
133     if (ValueMap[FI] == GI) {
134       ++FI, ++GI;
135       continue;
136     }
137
138     if (ValueMap[FI] != NULL)
139       return false;
140
141     for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
142       Value *OpF = FI->getOperand(i);
143       Value *OpG = GI->getOperand(i);
144
145       if (ValueMap[OpF] == OpG)
146         continue;
147
148       if (ValueMap[OpF] != NULL)
149         return false;
150
151       assert(OpF->getType() == OpG->getType() &&
152              "Two of the same operation has operands of different type.");
153
154       if (OpF->getValueID() != OpG->getValueID())
155         return false;
156
157       if (isa<PHINode>(FI)) {
158         if (SpeculationMap[OpF] == NULL)
159           SpeculationMap[OpF] = OpG;
160         else if (SpeculationMap[OpF] != OpG)
161           return false;
162         continue;
163       } else if (isa<BasicBlock>(OpF)) {
164         assert(isa<TerminatorInst>(FI) &&
165                "BasicBlock referenced by non-Terminator non-PHI");
166         // This call changes the ValueMap, hence we can't use
167         // Value *& = ValueMap[...]
168         if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
169                     SpeculationMap))
170           return false;
171       } else {
172         if (!compare(OpF, OpG))
173           return false;
174       }
175
176       ValueMap[OpF] = OpG;
177     }
178
179     ValueMap[FI] = GI;
180     ++FI, ++GI;
181   } while (FI != FE && GI != GE);
182
183   return FI == FE && GI == GE;
184 }
185
186 static bool equals(const Function *F, const Function *G) {
187   // We need to recheck everything, but check the things that weren't included
188   // in the hash first.
189
190   if (F->getAttributes() != G->getAttributes())
191     return false;
192
193   if (F->hasGC() != G->hasGC())
194     return false;
195
196   if (F->hasGC() && F->getGC() != G->getGC())
197     return false;
198
199   if (F->hasSection() != G->hasSection())
200     return false;
201
202   if (F->hasSection() && F->getSection() != G->getSection())
203     return false;
204
205   // TODO: if it's internal and only used in direct calls, we could handle this
206   // case too.
207   if (F->getCallingConv() != G->getCallingConv())
208     return false;
209
210   // TODO: We want to permit cases where two functions take T* and S* but
211   // only load or store them into T** and S**.
212   if (F->getType() != G->getType())
213     return false;
214
215   DenseMap<const Value *, const Value *> ValueMap;
216   DenseMap<const Value *, const Value *> SpeculationMap;
217   ValueMap[F] = G;
218
219   assert(F->arg_size() == G->arg_size() &&
220          "Identical functions have a different number of args.");
221
222   for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
223          fe = F->arg_end(); fi != fe; ++fi, ++gi)
224     ValueMap[fi] = gi;
225
226   if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
227               SpeculationMap))
228     return false;
229
230   for (DenseMap<const Value *, const Value *>::iterator
231          I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
232     if (ValueMap[I->first] != I->second)
233       return false;
234   }
235
236   return true;
237 }
238
239 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
240   if (FnVec[i]->mayBeOverridden() && !FnVec[j]->mayBeOverridden())
241     std::swap(FnVec[i], FnVec[j]);
242
243   Function *F = FnVec[i];
244   Function *G = FnVec[j];
245
246   if (!F->mayBeOverridden()) {
247     if (G->hasInternalLinkage()) {
248       F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
249       G->replaceAllUsesWith(F);
250       G->eraseFromParent();
251       ++NumFunctionsMerged;
252       return true;
253     }
254
255     if (G->hasExternalLinkage() || G->hasWeakLinkage()) {
256       GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
257                                         F, G->getParent());
258       F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
259       GA->takeName(G);
260       GA->setVisibility(G->getVisibility());
261       G->replaceAllUsesWith(GA);
262       G->eraseFromParent();
263       ++NumFunctionsMerged;
264       return true;
265     }
266   }
267
268   DOUT << "Failed on " << F->getName() << " and " << G->getName() << "\n";
269
270   ++NumMergeFails;
271   return false;
272 }
273
274 static bool hasAddressTaken(User *U) {
275   for (User::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I) {
276     User *Use = *I;
277
278     // 'call (bitcast @F to ...)' happens a lot.
279     while (isa<ConstantExpr>(Use) && Use->hasOneUse()) {
280       Use = *Use->use_begin();
281     }
282
283     if (isa<ConstantExpr>(Use)) {
284       if (hasAddressTaken(Use))
285         return true;
286     }
287
288     if (!isa<CallInst>(Use) && !isa<InvokeInst>(Use))
289       return true;
290
291     // Make sure we aren't passing U as a parameter to call instead of the
292     // callee. getOperand(0) is the callee for both CallInst and InvokeInst.
293     // Check the other operands to see if any of them is F.
294     for (User::op_iterator OI = I->op_begin() + 1, OE = I->op_end(); OI != OE;
295          ++OI) {
296       if (*OI == U)
297         return true;
298     }
299   }
300
301   return false;
302 }
303
304 bool MergeFunctions::runOnModule(Module &M) {
305   bool Changed = false;
306
307   std::map<unsigned long, std::vector<Function *> > FnMap;
308
309   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
310     if (F->isDeclaration() || F->isIntrinsic())
311       continue;
312
313     if (F->hasLinkOnceLinkage() || F->hasCommonLinkage() ||
314         F->hasDLLImportLinkage() || F->hasDLLExportLinkage())
315       continue;
316
317     if (hasAddressTaken(F))
318       continue;
319
320     FnMap[hash(F)].push_back(F);
321   }
322
323   // TODO: instead of running in a loop, we could also fold functions in callgraph
324   // order. Constructing the CFG probably isn't cheaper than just running in a loop.
325
326   bool LocalChanged;
327   do {
328     LocalChanged = false;
329     for (std::map<unsigned long, std::vector<Function *> >::iterator
330          I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
331       DOUT << "size: " << FnMap.size() << "\n";
332       std::vector<Function *> &FnVec = I->second;
333       DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
334
335       for (int i = 0, e = FnVec.size(); i != e; ++i) {
336         for (int j = i + 1; j != e; ++j) {
337           bool isEqual = equals(FnVec[i], FnVec[j]);
338
339           DOUT << "  " << FnVec[i]->getName()
340                << (isEqual ? " == " : " != ")
341                << FnVec[j]->getName() << "\n";
342
343           if (isEqual) {
344             if (fold(FnVec, i, j)) {
345               LocalChanged = true;
346               FnVec.erase(FnVec.begin() + j);
347               --j, --e;
348             }
349           }
350         }
351       }
352
353     }
354     Changed |= LocalChanged;
355   } while (LocalChanged);
356
357   return Changed;
358 }