blob: d084b2a0752a07cc5c49fb33a1c2d3fa56532c51 [file] [log] [blame]
Nick Lewycky579a0242008-11-02 05:52:50 +00001//===- 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//
Nick Lewycky579a0242008-11-02 05:52:50 +000012// 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//
Nick Lewycky33ab0b12010-05-13 05:48:45 +000020// 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.
Nick Lewycky579a0242008-11-02 05:52:50 +000023//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
Nick Lewycky579a0242008-11-02 05:52:50 +000028// * 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//
Nick Lewycky78d43302010-08-02 05:23:03 +000034// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000036//
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//
Nick Lewycky78d43302010-08-02 05:23:03 +000045// * emit aliases for ELF
Nick Lewycky33ab0b12010-05-13 05:48:45 +000046//
Nick Lewycky78d43302010-08-02 05:23:03 +000047// 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;
Nick Lewycky33ab0b12010-05-13 05:48:45 +000051// 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//
Nick Lewycky579a0242008-11-02 05:52:50 +000058//===----------------------------------------------------------------------===//
59
60#define DEBUG_TYPE "mergefunc"
61#include "llvm/Transforms/IPO.h"
62#include "llvm/ADT/DenseMap.h"
Nick Lewycky287de602009-06-12 08:04:51 +000063#include "llvm/ADT/FoldingSet.h"
Nick Lewycky33ab0b12010-05-13 05:48:45 +000064#include "llvm/ADT/SmallSet.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000065#include "llvm/ADT/Statistic.h"
66#include "llvm/Constants.h"
67#include "llvm/InlineAsm.h"
68#include "llvm/Instructions.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000069#include "llvm/LLVMContext.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000070#include "llvm/Module.h"
71#include "llvm/Pass.h"
Nick Lewycky6feb3332008-11-02 16:46:26 +000072#include "llvm/Support/CallSite.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000073#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000074#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000075#include "llvm/Support/raw_ostream.h"
Nick Lewycky33ab0b12010-05-13 05:48:45 +000076#include "llvm/Target/TargetData.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000077#include <map>
78#include <vector>
79using namespace llvm;
80
81STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky579a0242008-11-02 05:52:50 +000082
83namespace {
Nick Lewycky78d43302010-08-02 05:23:03 +000084 /// 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 {
Nick Lewycky579a0242008-11-02 05:52:50 +000090 static char ID; // Pass identification, replacement for typeid
Dan Gohman1b2d0b82009-08-11 15:15:10 +000091 MergeFunctions() : ModulePass(&ID) {}
Nick Lewycky579a0242008-11-02 05:52:50 +000092
93 bool runOnModule(Module &M);
94 };
95}
96
97char MergeFunctions::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000098INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false);
Nick Lewycky579a0242008-11-02 05:52:50 +000099
100ModulePass *llvm::createMergeFunctionsPass() {
101 return new MergeFunctions();
102}
103
Nick Lewycky287de602009-06-12 08:04:51 +0000104// ===----------------------------------------------------------------------===
105// Comparison of functions
106// ===----------------------------------------------------------------------===
Nick Lewycky78d43302010-08-02 05:23:03 +0000107namespace {
108class FunctionComparator {
109public:
110 FunctionComparator(TargetData *TD, Function *F1, Function *F2)
111 : TD(TD), F1(F1), F2(F2) {}
Nick Lewycky287de602009-06-12 08:04:51 +0000112
Nick Lewycky78d43302010-08-02 05:23:03 +0000113 // 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) {
Nick Lewycky287de602009-06-12 08:04:51 +0000161 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
Nick Lewycky287de602009-06-12 08:04:51 +0000174/// isEquivalentType - any two pointers are equivalent. Otherwise, standard
175/// type equivalence rules apply.
Nick Lewycky78d43302010-08-02 05:23:03 +0000176bool FunctionComparator::isEquivalentType(const Type *Ty1,
177 const Type *Ty2) const {
Nick Lewycky287de602009-06-12 08:04:51 +0000178 if (Ty1 == Ty2)
179 return true;
180 if (Ty1->getTypeID() != Ty2->getTypeID())
181 return false;
182
183 switch(Ty1->getTypeID()) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000184 default:
185 llvm_unreachable("Unknown type!");
Duncan Sands8246adc2010-07-07 07:48:00 +0000186 // Fall through in Release mode.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000187 case Type::IntegerTyID:
188 case Type::OpaqueTyID:
189 // Ty1 == Ty2 would have returned true earlier.
190 return false;
191
Nick Lewycky287de602009-06-12 08:04:51 +0000192 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
Nick Lewycky287de602009-06-12 08:04:51 +0000202 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
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000224 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
Nick Lewycky287de602009-06-12 08:04:51 +0000239 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
Nick Lewycky394ce412010-07-16 06:31:12 +0000256 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 }
Nick Lewycky287de602009-06-12 08:04:51 +0000262 case Type::VectorTyID: {
Nick Lewycky394ce412010-07-16 06:31:12 +0000263 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());
Nick Lewycky287de602009-06-12 08:04:51 +0000267 }
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
Dan Gohman194ae782009-06-12 19:03:05 +0000273/// kept in sync with Instruction::isSameOperationAs.
Nick Lewycky78d43302010-08-02 05:23:03 +0000274bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
275 const Instruction *I2) const {
Nick Lewycky287de602009-06-12 08:04:51 +0000276 if (I1->getOpcode() != I2->getOpcode() ||
277 I1->getNumOperands() != I2->getNumOperands() ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000278 !isEquivalentType(I1->getType(), I2->getType()) ||
279 !I1->hasSameSubclassOptionalData(I2))
Nick Lewycky287de602009-06-12 08:04:51 +0000280 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;
Nick Lewycky579a0242008-11-02 05:52:50 +0000325}
326
Nick Lewycky78d43302010-08-02 05:23:03 +0000327/// 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.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000333 if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000334 SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end());
335 SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end());
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000336 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;
Nick Lewycky579a0242008-11-02 05:52:50 +0000341 }
342
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000343 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) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000351 if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000352 return false;
353 }
354
355 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000356}
357
Nick Lewycky78d43302010-08-02 05:23:03 +0000358/// 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)
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000380 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000381
Nick Lewycky78d43302010-08-02 05:23:03 +0000382 // TODO: constant expressions with GEP or references to F1 or F2.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000383 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.
Nick Lewycky78d43302010-08-02 05:23:03 +0000395 const Function *Domain1 = getDomain(V1);
396 const Function *Domain2 = getDomain(V2);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000397
Nick Lewycky78d43302010-08-02 05:23:03 +0000398 // The domains have to either be both NULL, or F1, F2.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000399 if (Domain1 != Domain2)
Nick Lewycky78d43302010-08-02 05:23:03 +0000400 if (Domain1 != F1 && Domain1 != F2)
401 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000402
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
Nick Lewycky78d43302010-08-02 05:23:03 +0000416// 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();
Nick Lewycky579a0242008-11-02 05:52:50 +0000420
421 do {
Nick Lewycky78d43302010-08-02 05:23:03 +0000422 if (!Enumerate(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000423 return false;
424
Nick Lewycky78d43302010-08-02 05:23:03 +0000425 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
426 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
427 if (!GEP2)
428 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000429
Nick Lewycky78d43302010-08-02 05:23:03 +0000430 if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
Nick Lewycky911ae392010-05-13 06:45:13 +0000431 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000432
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000433 if (!isEquivalentGEP(GEP1, GEP2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000434 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000435 } else {
Nick Lewycky78d43302010-08-02 05:23:03 +0000436 if (!isEquivalentOperation(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000437 return false;
438
Nick Lewycky78d43302010-08-02 05:23:03 +0000439 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);
Nick Lewycky579a0242008-11-02 05:52:50 +0000443
Nick Lewycky78d43302010-08-02 05:23:03 +0000444 if (!Enumerate(OpF1, OpF2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000445 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000446
Nick Lewycky78d43302010-08-02 05:23:03 +0000447 if (OpF1->getValueID() != OpF2->getValueID() ||
448 !isEquivalentType(OpF1->getType(), OpF2->getType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000449 return false;
450 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000451 }
452
Nick Lewycky78d43302010-08-02 05:23:03 +0000453 ++F1I, ++F2I;
454 } while (F1I != F1E && F2I != F2E);
Nick Lewycky579a0242008-11-02 05:52:50 +0000455
Nick Lewycky78d43302010-08-02 05:23:03 +0000456 return F1I == F1E && F2I == F2E;
Nick Lewycky579a0242008-11-02 05:52:50 +0000457}
458
Nick Lewycky78d43302010-08-02 05:23:03 +0000459bool FunctionComparator::Compare() {
Nick Lewycky579a0242008-11-02 05:52:50 +0000460 // We need to recheck everything, but check the things that weren't included
461 // in the hash first.
462
Nick Lewycky78d43302010-08-02 05:23:03 +0000463 if (F1->getAttributes() != F2->getAttributes())
Nick Lewycky579a0242008-11-02 05:52:50 +0000464 return false;
465
Nick Lewycky78d43302010-08-02 05:23:03 +0000466 if (F1->hasGC() != F2->hasGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000467 return false;
468
Nick Lewycky78d43302010-08-02 05:23:03 +0000469 if (F1->hasGC() && F1->getGC() != F2->getGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000470 return false;
471
Nick Lewycky78d43302010-08-02 05:23:03 +0000472 if (F1->hasSection() != F2->hasSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000473 return false;
474
Nick Lewycky78d43302010-08-02 05:23:03 +0000475 if (F1->hasSection() && F1->getSection() != F2->getSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000476 return false;
477
Nick Lewycky78d43302010-08-02 05:23:03 +0000478 if (F1->isVarArg() != F2->isVarArg())
Nick Lewycky287de602009-06-12 08:04:51 +0000479 return false;
480
Nick Lewycky579a0242008-11-02 05:52:50 +0000481 // TODO: if it's internal and only used in direct calls, we could handle this
482 // case too.
Nick Lewycky78d43302010-08-02 05:23:03 +0000483 if (F1->getCallingConv() != F2->getCallingConv())
Nick Lewycky579a0242008-11-02 05:52:50 +0000484 return false;
485
Nick Lewycky78d43302010-08-02 05:23:03 +0000486 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000487 return false;
488
Nick Lewycky78d43302010-08-02 05:23:03 +0000489 assert(F1->arg_size() == F2->arg_size() &&
Nick Lewycky579a0242008-11-02 05:52:50 +0000490 "Identical functions have a different number of args.");
491
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000492 // Visit the arguments so that they get enumerated in the order they're
493 // passed in.
Nick Lewycky78d43302010-08-02 05:23:03 +0000494 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))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000497 llvm_unreachable("Arguments repeat");
Nick Lewycky579a0242008-11-02 05:52:50 +0000498 }
499
Nick Lewycky78d43302010-08-02 05:23:03 +0000500 // 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))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000513 return false;
Nick Lewycky78d43302010-08-02 05:23:03 +0000514 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)))
Nick Lewycky911ae392010-05-13 06:45:13 +0000519 continue;
Nick Lewycky78d43302010-08-02 05:23:03 +0000520 F1BBs.push_back(F1TI->getSuccessor(i));
521 F2BBs.push_back(F2TI->getSuccessor(i));
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000522 }
523 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000524 return true;
525}
526
Nick Lewycky287de602009-06-12 08:04:51 +0000527// ===----------------------------------------------------------------------===
528// Folding of functions
529// ===----------------------------------------------------------------------===
Nick Lewycky579a0242008-11-02 05:52:50 +0000530
Nick Lewycky287de602009-06-12 08:04:51 +0000531// 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:
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000573 case GlobalValue::LinkerPrivateLinkage:
Nick Lewycky287de602009-06-12 08:04:51 +0000574 return Internal;
575
576 case GlobalValue::WeakAnyLinkage:
577 case GlobalValue::WeakODRLinkage:
578 case GlobalValue::ExternalWeakLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +0000579 case GlobalValue::LinkerPrivateWeakLinkage:
Nick Lewycky287de602009-06-12 08:04:51 +0000580 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:
Nick Lewycky287de602009-06-12 08:04:51 +0000589 case GlobalValue::CommonLinkage:
590 return ExternalStrong;
591 }
592
Torok Edwinc23197a2009-07-14 16:55:14 +0000593 llvm_unreachable("Unknown LinkageType.");
Nick Lewycky287de602009-06-12 08:04:51 +0000594 return ExternalWeak;
595}
596
597static void ThunkGToF(Function *F, Function *G) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000598 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
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000611 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
612 G->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000613 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewycky287de602009-06-12 08:04:51 +0000614
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000615 SmallVector<Value *, 16> Args;
Nick Lewycky287de602009-06-12 08:04:51 +0000616 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) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000620 if (FFTy->getParamType(i) == AI->getType()) {
Nick Lewycky287de602009-06-12 08:04:51 +0000621 Args.push_back(AI);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000622 } else {
623 Args.push_back(new BitCastInst(AI, FFTy->getParamType(i), "", BB));
Nick Lewycky287de602009-06-12 08:04:51 +0000624 }
625 ++i;
626 }
627
628 CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
629 CI->setTailCall();
Nick Lewyckyb3c36c92009-06-12 16:04:00 +0000630 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerf0127052010-01-05 13:12:22 +0000631 if (NewG->getReturnType()->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000632 ReturnInst::Create(F->getContext(), BB);
Nick Lewycky287de602009-06-12 08:04:51 +0000633 } else if (CI->getType() != NewG->getReturnType()) {
634 Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000635 ReturnInst::Create(F->getContext(), BCI, BB);
Nick Lewycky287de602009-06-12 08:04:51 +0000636 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +0000637 ReturnInst::Create(F->getContext(), CI, BB);
Nick Lewycky287de602009-06-12 08:04:51 +0000638 }
639
640 NewG->copyAttributesFrom(G);
641 NewG->takeName(G);
642 G->replaceAllUsesWith(NewG);
643 G->eraseFromParent();
Nick Lewycky287de602009-06-12 08:04:51 +0000644}
645
646static void AliasGToF(Function *F, Function *G) {
Nick Lewycky706f5082010-07-15 06:51:22 +0000647 // Darwin will trigger llvm_unreachable if asked to codegen an alias.
Nick Lewycky664040a2010-07-15 06:48:56 +0000648 return ThunkGToF(F, G);
649
650#if 0
Nick Lewycky287de602009-06-12 08:04:51 +0000651 if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
652 return ThunkGToF(F, G);
653
654 GlobalAlias *GA = new GlobalAlias(
655 G->getType(), G->getLinkage(), "",
Owen Andersonbaf3c402009-07-29 18:55:55 +0000656 ConstantExpr::getBitCast(F, G->getType()), G->getParent());
Nick Lewycky287de602009-06-12 08:04:51 +0000657 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
658 GA->takeName(G);
659 GA->setVisibility(G->getVisibility());
660 G->replaceAllUsesWith(GA);
661 G->eraseFromParent();
Nick Lewycky664040a2010-07-15 06:48:56 +0000662#endif
Nick Lewycky287de602009-06-12 08:04:51 +0000663}
664
665static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
Nick Lewycky579a0242008-11-02 05:52:50 +0000666 Function *F = FnVec[i];
667 Function *G = FnVec[j];
668
Nick Lewycky287de602009-06-12 08:04:51 +0000669 LinkageCategory catF = categorize(F);
670 LinkageCategory catG = categorize(G);
Nick Lewycky579a0242008-11-02 05:52:50 +0000671
Nick Lewycky287de602009-06-12 08:04:51 +0000672 if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
673 std::swap(FnVec[i], FnVec[j]);
674 std::swap(F, G);
675 std::swap(catF, catG);
Nick Lewycky579a0242008-11-02 05:52:50 +0000676 }
677
Nick Lewycky287de602009-06-12 08:04:51 +0000678 switch (catF) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000679 case ExternalStrong:
680 switch (catG) {
Nick Lewycky287de602009-06-12 08:04:51 +0000681 case ExternalStrong:
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000682 case ExternalWeak:
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000683 ThunkGToF(F, G);
Nick Lewycky287de602009-06-12 08:04:51 +0000684 break;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000685 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;
Nick Lewycky6feb3332008-11-02 16:46:26 +0000739 }
740
Nick Lewycky287de602009-06-12 08:04:51 +0000741 ++NumFunctionsMerged;
742 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000743}
744
Nick Lewycky287de602009-06-12 08:04:51 +0000745// ===----------------------------------------------------------------------===
746// Pass definition
747// ===----------------------------------------------------------------------===
Nick Lewycky579a0242008-11-02 05:52:50 +0000748
749bool MergeFunctions::runOnModule(Module &M) {
750 bool Changed = false;
751
Duncan Sands5baf8ec2008-11-02 09:00:33 +0000752 std::map<unsigned long, std::vector<Function *> > FnMap;
Nick Lewycky579a0242008-11-02 05:52:50 +0000753
754 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000755 if (F->isDeclaration())
Nick Lewycky579a0242008-11-02 05:52:50 +0000756 continue;
757
Nick Lewycky78d43302010-08-02 05:23:03 +0000758 FnMap[ProfileFunction(F)].push_back(F);
Nick Lewycky579a0242008-11-02 05:52:50 +0000759 }
760
Nick Lewycky78d43302010-08-02 05:23:03 +0000761 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky579a0242008-11-02 05:52:50 +0000762
763 bool LocalChanged;
764 do {
765 LocalChanged = false;
David Greene3a078b52010-01-05 01:28:12 +0000766 DEBUG(dbgs() << "size: " << FnMap.size() << "\n");
Duncan Sands5baf8ec2008-11-02 09:00:33 +0000767 for (std::map<unsigned long, std::vector<Function *> >::iterator
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000768 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
Nick Lewycky579a0242008-11-02 05:52:50 +0000769 std::vector<Function *> &FnVec = I->second;
David Greene3a078b52010-01-05 01:28:12 +0000770 DEBUG(dbgs() << "hash (" << I->first << "): " << FnVec.size() << "\n");
Nick Lewycky579a0242008-11-02 05:52:50 +0000771
772 for (int i = 0, e = FnVec.size(); i != e; ++i) {
773 for (int j = i + 1; j != e; ++j) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000774 bool isEqual = FunctionComparator(TD, FnVec[i], FnVec[j]).Compare();
Nick Lewycky579a0242008-11-02 05:52:50 +0000775
David Greene3a078b52010-01-05 01:28:12 +0000776 DEBUG(dbgs() << " " << FnVec[i]->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000777 << (isEqual ? " == " : " != ")
778 << FnVec[j]->getName() << "\n");
Nick Lewycky579a0242008-11-02 05:52:50 +0000779
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}