blob: 8555d2c85af959fe85595f4799e66e9676c5a12f [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
Nick Lewyckybe04fde2010-08-08 05:04:23 +000032// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewycky579a0242008-11-02 05:52:50 +000033//
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//
Nick Lewyckybe04fde2010-08-08 05:04:23 +000037// * be smarter about bitcasts.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000038//
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
Nick Lewyckybe04fde2010-08-08 05:04:23 +000042// other doesn't. We should learn to look through bitcasts.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000043//
Nick Lewycky579a0242008-11-02 05:52:50 +000044//===----------------------------------------------------------------------===//
45
46#define DEBUG_TYPE "mergefunc"
47#include "llvm/Transforms/IPO.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000048#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/SmallSet.h"
52#include "llvm/ADT/Statistic.h"
Stephen Hines36b56882014-04-23 16:57:46 -070053#include "llvm/IR/CallSite.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000054#include "llvm/IR/Constants.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
58#include "llvm/IR/Instructions.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/Operator.h"
Stephen Hines36b56882014-04-23 16:57:46 -070062#include "llvm/IR/ValueHandle.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000063#include "llvm/Pass.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000064#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000065#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000066#include "llvm/Support/raw_ostream.h"
Nick Lewycky65a0af32010-08-31 08:29:37 +000067#include <vector>
Nick Lewycky579a0242008-11-02 05:52:50 +000068using namespace llvm;
69
70STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky2b6c01b2010-09-07 01:42:10 +000071STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyb38824f2011-01-25 08:56:50 +000072STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky2b6c01b2010-09-07 01:42:10 +000073STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewycky579a0242008-11-02 05:52:50 +000074
Benjamin Kramer24a5f302013-04-19 23:06:44 +000075/// Returns the type id for a type to be hashed. We turn pointer types into
76/// integers here because the actual compare logic below considers pointers and
77/// integers of the same size as equal.
78static Type::TypeID getTypeIDForHash(Type *Ty) {
79 if (Ty->isPointerTy())
80 return Type::IntegerTyID;
81 return Ty->getTypeID();
82}
83
Nick Lewycky468ee0a2011-01-28 08:43:14 +000084/// Creates a hash-code for the function which is the same for any two
85/// functions that will compare equal, without looking at the instructions
86/// inside the function.
87static unsigned profileFunction(const Function *F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000088 FunctionType *FTy = F->getFunctionType();
Nick Lewyckybe04fde2010-08-08 05:04:23 +000089
Nick Lewyckyb0104e12010-09-05 08:22:49 +000090 FoldingSetNodeID ID;
91 ID.AddInteger(F->size());
92 ID.AddInteger(F->getCallingConv());
93 ID.AddBoolean(F->hasGC());
94 ID.AddBoolean(FTy->isVarArg());
Benjamin Kramer24a5f302013-04-19 23:06:44 +000095 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
Nick Lewyckyb0104e12010-09-05 08:22:49 +000096 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramer24a5f302013-04-19 23:06:44 +000097 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
Nick Lewyckyb0104e12010-09-05 08:22:49 +000098 return ID.ComputeHash();
Nick Lewycky579a0242008-11-02 05:52:50 +000099}
100
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000101namespace {
102
Nick Lewycky8b596432011-01-28 08:19:00 +0000103/// ComparableFunction - A struct that pairs together functions with a
Micah Villmow3574eca2012-10-08 16:38:25 +0000104/// DataLayout so that we can keep them together as elements in the DenseSet.
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000105class ComparableFunction {
106public:
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000107 static const ComparableFunction EmptyKey;
108 static const ComparableFunction TombstoneKey;
Micah Villmow3574eca2012-10-08 16:38:25 +0000109 static DataLayout * const LookupOnly;
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000110
Stephen Hines36b56882014-04-23 16:57:46 -0700111 ComparableFunction(Function *Func, const DataLayout *DL)
112 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000113
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000114 Function *getFunc() const { return Func; }
115 unsigned getHash() const { return Hash; }
Stephen Hines36b56882014-04-23 16:57:46 -0700116 const DataLayout *getDataLayout() const { return DL; }
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000117
118 // Drops AssertingVH reference to the function. Outside of debug mode, this
119 // does nothing.
120 void release() {
121 assert(Func &&
122 "Attempted to release function twice, or release empty/tombstone!");
123 Func = NULL;
124 }
125
126private:
127 explicit ComparableFunction(unsigned Hash)
Stephen Hines36b56882014-04-23 16:57:46 -0700128 : Func(NULL), Hash(Hash), DL(NULL) {}
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000129
130 AssertingVH<Function> Func;
131 unsigned Hash;
Stephen Hines36b56882014-04-23 16:57:46 -0700132 const DataLayout *DL;
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000133};
134
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000135const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
136const ComparableFunction ComparableFunction::TombstoneKey =
137 ComparableFunction(1);
Micah Villmow3574eca2012-10-08 16:38:25 +0000138DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000139
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000140}
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000141
142namespace llvm {
143 template <>
144 struct DenseMapInfo<ComparableFunction> {
145 static ComparableFunction getEmptyKey() {
146 return ComparableFunction::EmptyKey;
147 }
148 static ComparableFunction getTombstoneKey() {
149 return ComparableFunction::TombstoneKey;
150 }
151 static unsigned getHashValue(const ComparableFunction &CF) {
152 return CF.getHash();
153 }
154 static bool isEqual(const ComparableFunction &LHS,
155 const ComparableFunction &RHS);
156 };
157}
158
159namespace {
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000160
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000161/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmow3574eca2012-10-08 16:38:25 +0000162/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000163/// used if available. The comparator always fails conservatively (erring on the
164/// side of claiming that two functions are different).
Nick Lewycky78d43302010-08-02 05:23:03 +0000165class FunctionComparator {
166public:
Stephen Hines36b56882014-04-23 16:57:46 -0700167 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewyckyf53de862010-08-31 05:53:05 +0000168 const Function *F2)
Stephen Hines36b56882014-04-23 16:57:46 -0700169 : F1(F1), F2(F2), DL(DL) {}
Nick Lewycky287de602009-06-12 08:04:51 +0000170
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000171 /// Test whether the two functions have equivalent behaviour.
172 bool compare();
Nick Lewycky78d43302010-08-02 05:23:03 +0000173
174private:
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000175 /// Test whether two basic blocks have equivalent behaviour.
176 bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
Nick Lewycky78d43302010-08-02 05:23:03 +0000177
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000178 /// Assign or look up previously assigned numbers for the two values, and
179 /// return whether the numbers are equal. Numbers are assigned in the order
180 /// visited.
181 bool enumerate(const Value *V1, const Value *V2);
Nick Lewycky78d43302010-08-02 05:23:03 +0000182
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000183 /// Compare two Instructions for equivalence, similar to
184 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000185 /// comparison.
Nick Lewycky78d43302010-08-02 05:23:03 +0000186 bool isEquivalentOperation(const Instruction *I1,
187 const Instruction *I2) const;
188
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000189 /// Compare two GEPs for equivalent pointer arithmetic.
Nick Lewycky78d43302010-08-02 05:23:03 +0000190 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
191 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000192 const GetElementPtrInst *GEP2) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000193 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
194 }
195
Stephen Hines36b56882014-04-23 16:57:46 -0700196 /// cmpType - compares two types,
197 /// defines total ordering among the types set.
198 ///
199 /// Return values:
200 /// 0 if types are equal,
201 /// -1 if Left is less than Right,
202 /// +1 if Left is greater than Right.
203 ///
204 /// Description:
205 /// Comparison is broken onto stages. Like in lexicographical comparison
206 /// stage coming first has higher priority.
207 /// On each explanation stage keep in mind total ordering properties.
208 ///
209 /// 0. Before comparison we coerce pointer types of 0 address space to
210 /// integer.
211 /// We also don't bother with same type at left and right, so
212 /// just return 0 in this case.
213 ///
214 /// 1. If types are of different kind (different type IDs).
215 /// Return result of type IDs comparison, treating them as numbers.
216 /// 2. If types are vectors or integers, compare Type* values as numbers.
217 /// 3. Types has same ID, so check whether they belongs to the next group:
218 /// * Void
219 /// * Float
220 /// * Double
221 /// * X86_FP80
222 /// * FP128
223 /// * PPC_FP128
224 /// * Label
225 /// * Metadata
226 /// If so - return 0, yes - we can treat these types as equal only because
227 /// their IDs are same.
228 /// 4. If Left and Right are pointers, return result of address space
229 /// comparison (numbers comparison). We can treat pointer types of same
230 /// address space as equal.
231 /// 5. If types are complex.
232 /// Then both Left and Right are to be expanded and their element types will
233 /// be checked with the same way. If we get Res != 0 on some stage, return it.
234 /// Otherwise return 0.
235 /// 6. For all other cases put llvm_unreachable.
236 int cmpType(Type *TyL, Type *TyR) const;
237
238 bool isEquivalentType(Type *Ty1, Type *Ty2) const {
239 return cmpType(Ty1, Ty2) == 0;
240 }
241
242 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewycky78d43302010-08-02 05:23:03 +0000243
244 // The two functions undergoing comparison.
Nick Lewyckyf53de862010-08-31 05:53:05 +0000245 const Function *F1, *F2;
Nick Lewycky78d43302010-08-02 05:23:03 +0000246
Stephen Hines36b56882014-04-23 16:57:46 -0700247 const DataLayout *DL;
Nick Lewycky78d43302010-08-02 05:23:03 +0000248
Nick Lewyckyeafe8632011-02-20 08:11:03 +0000249 DenseMap<const Value *, const Value *> id_map;
250 DenseSet<const Value *> seen_values;
Nick Lewycky78d43302010-08-02 05:23:03 +0000251};
Nick Lewycky285cf802011-01-28 07:36:21 +0000252
Nick Lewycky78d43302010-08-02 05:23:03 +0000253}
254
Stephen Hines36b56882014-04-23 16:57:46 -0700255int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
256 if (L < R) return -1;
257 if (L > R) return 1;
258 return 0;
259}
Bill Wendlingfcb80cc2013-11-27 04:52:57 +0000260
Stephen Hines36b56882014-04-23 16:57:46 -0700261/// cmpType - compares two types,
262/// defines total ordering among the types set.
263/// See method declaration comments for more details.
264int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
Bill Wendlingfcb80cc2013-11-27 04:52:57 +0000265
Stephen Hines36b56882014-04-23 16:57:46 -0700266 PointerType *PTyL = dyn_cast<PointerType>(TyL);
267 PointerType *PTyR = dyn_cast<PointerType>(TyR);
268
269 if (DL) {
270 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
271 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Bill Wendlingfcb80cc2013-11-27 04:52:57 +0000272 }
273
Stephen Hines36b56882014-04-23 16:57:46 -0700274 if (TyL == TyR)
275 return 0;
Matt Arsenault432bdf62013-11-10 01:44:37 +0000276
Stephen Hines36b56882014-04-23 16:57:46 -0700277 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
278 return Res;
Nick Lewycky287de602009-06-12 08:04:51 +0000279
Stephen Hines36b56882014-04-23 16:57:46 -0700280 switch (TyL->getTypeID()) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000281 default:
282 llvm_unreachable("Unknown type!");
Duncan Sands8246adc2010-07-07 07:48:00 +0000283 // Fall through in Release mode.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000284 case Type::IntegerTyID:
Nick Lewycky388f4912011-01-26 08:50:18 +0000285 case Type::VectorTyID:
Stephen Hines36b56882014-04-23 16:57:46 -0700286 // TyL == TyR would have returned true earlier.
287 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000288
Nick Lewycky287de602009-06-12 08:04:51 +0000289 case Type::VoidTyID:
290 case Type::FloatTyID:
291 case Type::DoubleTyID:
292 case Type::X86_FP80TyID:
293 case Type::FP128TyID:
294 case Type::PPC_FP128TyID:
295 case Type::LabelTyID:
296 case Type::MetadataTyID:
Stephen Hines36b56882014-04-23 16:57:46 -0700297 return 0;
Nick Lewycky287de602009-06-12 08:04:51 +0000298
Nick Lewycky287de602009-06-12 08:04:51 +0000299 case Type::PointerTyID: {
Stephen Hines36b56882014-04-23 16:57:46 -0700300 assert(PTyL && PTyR && "Both types must be pointers here.");
301 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewycky287de602009-06-12 08:04:51 +0000302 }
303
304 case Type::StructTyID: {
Stephen Hines36b56882014-04-23 16:57:46 -0700305 StructType *STyL = cast<StructType>(TyL);
306 StructType *STyR = cast<StructType>(TyR);
307 if (STyL->getNumElements() != STyR->getNumElements())
308 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewycky287de602009-06-12 08:04:51 +0000309
Stephen Hines36b56882014-04-23 16:57:46 -0700310 if (STyL->isPacked() != STyR->isPacked())
311 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewycky287de602009-06-12 08:04:51 +0000312
Stephen Hines36b56882014-04-23 16:57:46 -0700313 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
314 if (int Res = cmpType(STyL->getElementType(i),
315 STyR->getElementType(i)))
316 return Res;
Nick Lewycky287de602009-06-12 08:04:51 +0000317 }
Stephen Hines36b56882014-04-23 16:57:46 -0700318 return 0;
Nick Lewycky287de602009-06-12 08:04:51 +0000319 }
320
321 case Type::FunctionTyID: {
Stephen Hines36b56882014-04-23 16:57:46 -0700322 FunctionType *FTyL = cast<FunctionType>(TyL);
323 FunctionType *FTyR = cast<FunctionType>(TyR);
324 if (FTyL->getNumParams() != FTyR->getNumParams())
325 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewycky287de602009-06-12 08:04:51 +0000326
Stephen Hines36b56882014-04-23 16:57:46 -0700327 if (FTyL->isVarArg() != FTyR->isVarArg())
328 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Nick Lewycky287de602009-06-12 08:04:51 +0000329
Stephen Hines36b56882014-04-23 16:57:46 -0700330 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
331 return Res;
332
333 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
334 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
335 return Res;
Nick Lewycky287de602009-06-12 08:04:51 +0000336 }
Stephen Hines36b56882014-04-23 16:57:46 -0700337 return 0;
Nick Lewycky287de602009-06-12 08:04:51 +0000338 }
339
Nick Lewycky394ce412010-07-16 06:31:12 +0000340 case Type::ArrayTyID: {
Stephen Hines36b56882014-04-23 16:57:46 -0700341 ArrayType *ATyL = cast<ArrayType>(TyL);
342 ArrayType *ATyR = cast<ArrayType>(TyR);
343 if (ATyL->getNumElements() != ATyR->getNumElements())
344 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
345 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky394ce412010-07-16 06:31:12 +0000346 }
Nick Lewycky287de602009-06-12 08:04:51 +0000347 }
348}
349
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000350// Determine whether the two operations are the same except that pointer-to-A
351// and pointer-to-B are equivalent. This should be kept in sync with
352// Instruction::isSameOperationAs.
Nick Lewycky78d43302010-08-02 05:23:03 +0000353bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
354 const Instruction *I2) const {
Nick Lewycky39c33e32011-02-06 05:04:00 +0000355 // Differences from Instruction::isSameOperationAs:
356 // * replace type comparison with calls to isEquivalentType.
357 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
358 // * because of the above, we don't test for the tail bit on calls later on
Nick Lewycky287de602009-06-12 08:04:51 +0000359 if (I1->getOpcode() != I2->getOpcode() ||
360 I1->getNumOperands() != I2->getNumOperands() ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000361 !isEquivalentType(I1->getType(), I2->getType()) ||
362 !I1->hasSameSubclassOptionalData(I2))
Nick Lewycky287de602009-06-12 08:04:51 +0000363 return false;
364
365 // We have two instructions of identical opcode and #operands. Check to see
366 // if all operands are the same type
367 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
368 if (!isEquivalentType(I1->getOperand(i)->getType(),
369 I2->getOperand(i)->getType()))
370 return false;
371
372 // Check special state that is a part of some instructions.
373 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
374 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
Eli Friedman3d30b432011-08-15 22:16:46 +0000375 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
376 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
377 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
Nick Lewycky287de602009-06-12 08:04:51 +0000378 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
379 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
Eli Friedman3d30b432011-08-15 22:16:46 +0000380 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
381 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
382 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
Nick Lewycky287de602009-06-12 08:04:51 +0000383 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
384 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
385 if (const CallInst *CI = dyn_cast<CallInst>(I1))
Nick Lewycky39c33e32011-02-06 05:04:00 +0000386 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
Nick Lewyckyf6c63c22011-01-26 09:23:19 +0000387 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
Nick Lewycky287de602009-06-12 08:04:51 +0000388 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
389 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
Nick Lewyckyf6c63c22011-01-26 09:23:19 +0000390 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
Eli Friedman55ba8162011-07-29 03:05:32 +0000391 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
392 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
393 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
394 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
395 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
396 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
397 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
398 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
399 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
Stephen Hines36b56882014-04-23 16:57:46 -0700400 CXI->getSuccessOrdering() ==
401 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
402 CXI->getFailureOrdering() ==
403 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
Eli Friedman55ba8162011-07-29 03:05:32 +0000404 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
405 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
406 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
407 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
408 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
409 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
Nick Lewycky287de602009-06-12 08:04:51 +0000410
411 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000412}
413
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000414// Determine whether two GEP operations perform the same underlying arithmetic.
Nick Lewycky78d43302010-08-02 05:23:03 +0000415bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
416 const GEPOperator *GEP2) {
Matt Arsenault432bdf62013-11-10 01:44:37 +0000417 unsigned AS = GEP1->getPointerAddressSpace();
418 if (AS != GEP2->getPointerAddressSpace())
419 return false;
420
Stephen Hines36b56882014-04-23 16:57:46 -0700421 if (DL) {
Matt Arsenault432bdf62013-11-10 01:44:37 +0000422 // When we have target data, we can reduce the GEP down to the value in bytes
423 // added to the address.
Stephen Hines36b56882014-04-23 16:57:46 -0700424 unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
Matt Arsenault432bdf62013-11-10 01:44:37 +0000425 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
Stephen Hines36b56882014-04-23 16:57:46 -0700426 if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
427 GEP2->accumulateConstantOffset(*DL, Offset2)) {
Matt Arsenault432bdf62013-11-10 01:44:37 +0000428 return Offset1 == Offset2;
429 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000430 }
431
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000432 if (GEP1->getPointerOperand()->getType() !=
433 GEP2->getPointerOperand()->getType())
434 return false;
435
436 if (GEP1->getNumOperands() != GEP2->getNumOperands())
437 return false;
438
439 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000440 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000441 return false;
442 }
443
444 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000445}
446
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000447// Compare two values used by the two functions under pair-wise comparison. If
448// this is the first time the values are seen, they're added to the mapping so
449// that we will detect mismatches on next use.
450bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000451 // Check for function @f1 referring to itself and function @f2 referring to
452 // itself, or referring to each other, or both referring to either of them.
453 // They're all equivalent if the two functions are otherwise equivalent.
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000454 if (V1 == F1 && V2 == F2)
455 return true;
456 if (V1 == F2 && V2 == F1)
457 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000458
Benjamin Kramer9c1858c2011-01-27 20:30:54 +0000459 if (const Constant *C1 = dyn_cast<Constant>(V1)) {
Nick Lewycky25296e22011-01-27 08:38:19 +0000460 if (V1 == V2) return true;
Nick Lewycky25296e22011-01-27 08:38:19 +0000461 const Constant *C2 = dyn_cast<Constant>(V2);
462 if (!C2) return false;
463 // TODO: constant expressions with GEP or references to F1 or F2.
464 if (C1->isNullValue() && C2->isNullValue() &&
Bill Wendling56cb2292012-07-19 00:11:40 +0000465 isEquivalentType(C1->getType(), C2->getType()))
Nick Lewycky25296e22011-01-27 08:38:19 +0000466 return true;
Nick Lewyckyc9d69482011-01-27 19:51:31 +0000467 // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1
468 // then they must have equal bit patterns.
Nick Lewycky25296e22011-01-27 08:38:19 +0000469 return C1->getType()->canLosslesslyBitCastTo(C2->getType()) &&
470 C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType());
471 }
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000472
Nick Lewyckyd4893322011-02-06 04:33:50 +0000473 if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
474 return V1 == V2;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000475
Nick Lewyckyeafe8632011-02-20 08:11:03 +0000476 // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
477 // check whether it's equal to V2. When there is no mapping then we need to
478 // ensure that V2 isn't already equivalent to something else. For this
479 // purpose, we track the V2 values in a set.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000480
Nick Lewyckyeafe8632011-02-20 08:11:03 +0000481 const Value *&map_elem = id_map[V1];
482 if (map_elem)
483 return map_elem == V2;
484 if (!seen_values.insert(V2).second)
485 return false;
486 map_elem = V2;
487 return true;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000488}
489
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000490// Test whether two basic blocks have equivalent behaviour.
491bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000492 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
493 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
Nick Lewycky579a0242008-11-02 05:52:50 +0000494
495 do {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000496 if (!enumerate(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000497 return false;
498
Nick Lewycky78d43302010-08-02 05:23:03 +0000499 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
500 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
501 if (!GEP2)
502 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000503
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000504 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
Nick Lewycky911ae392010-05-13 06:45:13 +0000505 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000506
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000507 if (!isEquivalentGEP(GEP1, GEP2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000508 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000509 } else {
Nick Lewycky78d43302010-08-02 05:23:03 +0000510 if (!isEquivalentOperation(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000511 return false;
512
Nick Lewycky78d43302010-08-02 05:23:03 +0000513 assert(F1I->getNumOperands() == F2I->getNumOperands());
514 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
515 Value *OpF1 = F1I->getOperand(i);
516 Value *OpF2 = F2I->getOperand(i);
Nick Lewycky579a0242008-11-02 05:52:50 +0000517
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000518 if (!enumerate(OpF1, OpF2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000519 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000520
Nick Lewycky78d43302010-08-02 05:23:03 +0000521 if (OpF1->getValueID() != OpF2->getValueID() ||
522 !isEquivalentType(OpF1->getType(), OpF2->getType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000523 return false;
524 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000525 }
526
Nick Lewycky78d43302010-08-02 05:23:03 +0000527 ++F1I, ++F2I;
528 } while (F1I != F1E && F2I != F2E);
Nick Lewycky579a0242008-11-02 05:52:50 +0000529
Nick Lewycky78d43302010-08-02 05:23:03 +0000530 return F1I == F1E && F2I == F2E;
Nick Lewycky579a0242008-11-02 05:52:50 +0000531}
532
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000533// Test whether the two functions have equivalent behaviour.
534bool FunctionComparator::compare() {
Nick Lewycky579a0242008-11-02 05:52:50 +0000535 // We need to recheck everything, but check the things that weren't included
536 // in the hash first.
537
Nick Lewycky78d43302010-08-02 05:23:03 +0000538 if (F1->getAttributes() != F2->getAttributes())
Nick Lewycky579a0242008-11-02 05:52:50 +0000539 return false;
540
Nick Lewycky78d43302010-08-02 05:23:03 +0000541 if (F1->hasGC() != F2->hasGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000542 return false;
543
Nick Lewycky78d43302010-08-02 05:23:03 +0000544 if (F1->hasGC() && F1->getGC() != F2->getGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000545 return false;
546
Nick Lewycky78d43302010-08-02 05:23:03 +0000547 if (F1->hasSection() != F2->hasSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000548 return false;
549
Nick Lewycky78d43302010-08-02 05:23:03 +0000550 if (F1->hasSection() && F1->getSection() != F2->getSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000551 return false;
552
Nick Lewycky78d43302010-08-02 05:23:03 +0000553 if (F1->isVarArg() != F2->isVarArg())
Nick Lewycky287de602009-06-12 08:04:51 +0000554 return false;
555
Nick Lewycky579a0242008-11-02 05:52:50 +0000556 // TODO: if it's internal and only used in direct calls, we could handle this
557 // case too.
Nick Lewycky78d43302010-08-02 05:23:03 +0000558 if (F1->getCallingConv() != F2->getCallingConv())
Nick Lewycky579a0242008-11-02 05:52:50 +0000559 return false;
560
Nick Lewycky78d43302010-08-02 05:23:03 +0000561 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000562 return false;
563
Nick Lewycky78d43302010-08-02 05:23:03 +0000564 assert(F1->arg_size() == F2->arg_size() &&
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000565 "Identically typed functions have different numbers of args!");
Nick Lewycky579a0242008-11-02 05:52:50 +0000566
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000567 // Visit the arguments so that they get enumerated in the order they're
568 // passed in.
Nick Lewycky78d43302010-08-02 05:23:03 +0000569 for (Function::const_arg_iterator f1i = F1->arg_begin(),
570 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000571 if (!enumerate(f1i, f2i))
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000572 llvm_unreachable("Arguments repeat!");
Nick Lewycky579a0242008-11-02 05:52:50 +0000573 }
574
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000575 // We do a CFG-ordered walk since the actual ordering of the blocks in the
576 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewycky78d43302010-08-02 05:23:03 +0000577 // functions, then takes each block from each terminator in order. As an
578 // artifact, this also means that unreachable blocks are ignored.
579 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
580 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000581
Nick Lewycky78d43302010-08-02 05:23:03 +0000582 F1BBs.push_back(&F1->getEntryBlock());
583 F2BBs.push_back(&F2->getEntryBlock());
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000584
Nick Lewycky78d43302010-08-02 05:23:03 +0000585 VisitedBBs.insert(F1BBs[0]);
586 while (!F1BBs.empty()) {
587 const BasicBlock *F1BB = F1BBs.pop_back_val();
588 const BasicBlock *F2BB = F2BBs.pop_back_val();
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000589
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000590 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000591 return false;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000592
Nick Lewycky78d43302010-08-02 05:23:03 +0000593 const TerminatorInst *F1TI = F1BB->getTerminator();
594 const TerminatorInst *F2TI = F2BB->getTerminator();
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000595
Nick Lewycky78d43302010-08-02 05:23:03 +0000596 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
597 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
598 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
Nick Lewycky911ae392010-05-13 06:45:13 +0000599 continue;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000600
Nick Lewycky78d43302010-08-02 05:23:03 +0000601 F1BBs.push_back(F1TI->getSuccessor(i));
602 F2BBs.push_back(F2TI->getSuccessor(i));
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000603 }
604 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000605 return true;
606}
607
Nick Lewycky285cf802011-01-28 07:36:21 +0000608namespace {
609
610/// MergeFunctions finds functions which will generate identical machine code,
611/// by considering all pointer types to be equivalent. Once identified,
612/// MergeFunctions will fold them by replacing a call to one to a call to a
613/// bitcast of the other.
614///
615class MergeFunctions : public ModulePass {
616public:
617 static char ID;
618 MergeFunctions()
619 : ModulePass(ID), HasGlobalAliases(false) {
620 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
621 }
622
Stephen Hines36b56882014-04-23 16:57:46 -0700623 bool runOnModule(Module &M) override;
Nick Lewycky285cf802011-01-28 07:36:21 +0000624
625private:
626 typedef DenseSet<ComparableFunction> FnSetType;
627
628 /// A work queue of functions that may have been modified and should be
629 /// analyzed again.
630 std::vector<WeakVH> Deferred;
631
632 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
633 /// equal to one that's already present.
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000634 bool insert(ComparableFunction &NewF);
Nick Lewycky285cf802011-01-28 07:36:21 +0000635
636 /// Remove a Function from the FnSet and queue it up for a second sweep of
637 /// analysis.
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000638 void remove(Function *F);
Nick Lewycky285cf802011-01-28 07:36:21 +0000639
640 /// Find the functions that use this Value and remove them from FnSet and
641 /// queue the functions.
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000642 void removeUsers(Value *V);
Nick Lewycky285cf802011-01-28 07:36:21 +0000643
644 /// Replace all direct calls of Old with calls of New. Will bitcast New if
645 /// necessary to make types match.
646 void replaceDirectCallers(Function *Old, Function *New);
647
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000648 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
649 /// be converted into a thunk. In either case, it should never be visited
650 /// again.
651 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky285cf802011-01-28 07:36:21 +0000652
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000653 /// Replace G with a thunk or an alias to F. Deletes G.
654 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky285cf802011-01-28 07:36:21 +0000655
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000656 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
657 /// of G with bitcast(F). Deletes G.
658 void writeThunk(Function *F, Function *G);
Nick Lewycky285cf802011-01-28 07:36:21 +0000659
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000660 /// Replace G with an alias to F. Deletes G.
661 void writeAlias(Function *F, Function *G);
Nick Lewycky285cf802011-01-28 07:36:21 +0000662
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000663 /// The set of all distinct functions. Use the insert() and remove() methods
664 /// to modify it.
Nick Lewycky285cf802011-01-28 07:36:21 +0000665 FnSetType FnSet;
666
Micah Villmow3574eca2012-10-08 16:38:25 +0000667 /// DataLayout for more accurate GEP comparisons. May be NULL.
Stephen Hines36b56882014-04-23 16:57:46 -0700668 const DataLayout *DL;
Nick Lewycky285cf802011-01-28 07:36:21 +0000669
670 /// Whether or not the target supports global aliases.
671 bool HasGlobalAliases;
672};
673
674} // end anonymous namespace
675
676char MergeFunctions::ID = 0;
677INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
678
679ModulePass *llvm::createMergeFunctionsPass() {
680 return new MergeFunctions();
681}
682
683bool MergeFunctions::runOnModule(Module &M) {
684 bool Changed = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700685 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
686 DL = DLP ? &DLP->getDataLayout() : 0;
Nick Lewycky285cf802011-01-28 07:36:21 +0000687
688 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
689 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
690 Deferred.push_back(WeakVH(I));
691 }
692 FnSet.resize(Deferred.size());
693
694 do {
695 std::vector<WeakVH> Worklist;
696 Deferred.swap(Worklist);
697
698 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
699 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
700
701 // Insert only strong functions and merge them. Strong function merging
702 // always deletes one of them.
703 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
704 E = Worklist.end(); I != E; ++I) {
705 if (!*I) continue;
706 Function *F = cast<Function>(*I);
707 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
708 !F->mayBeOverridden()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700709 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000710 Changed |= insert(CF);
Nick Lewycky285cf802011-01-28 07:36:21 +0000711 }
712 }
713
714 // Insert only weak functions and merge them. By doing these second we
715 // create thunks to the strong function when possible. When two weak
716 // functions are identical, we create a new strong function with two weak
717 // weak thunks to it which are identical but not mergable.
718 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
719 E = Worklist.end(); I != E; ++I) {
720 if (!*I) continue;
721 Function *F = cast<Function>(*I);
722 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
723 F->mayBeOverridden()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700724 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000725 Changed |= insert(CF);
Nick Lewycky285cf802011-01-28 07:36:21 +0000726 }
727 }
728 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
729 } while (!Deferred.empty());
730
731 FnSet.clear();
732
733 return Changed;
734}
735
736bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
737 const ComparableFunction &RHS) {
738 if (LHS.getFunc() == RHS.getFunc() &&
739 LHS.getHash() == RHS.getHash())
740 return true;
741 if (!LHS.getFunc() || !RHS.getFunc())
742 return false;
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000743
744 // One of these is a special "underlying pointer comparison only" object.
Stephen Hines36b56882014-04-23 16:57:46 -0700745 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
746 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000747 return false;
748
Stephen Hines36b56882014-04-23 16:57:46 -0700749 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky285cf802011-01-28 07:36:21 +0000750 "Comparing functions for different targets");
751
Stephen Hines36b56882014-04-23 16:57:46 -0700752 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
Nick Lewycky8eb3e542011-02-02 05:31:01 +0000753 RHS.getFunc()).compare();
Nick Lewycky285cf802011-01-28 07:36:21 +0000754}
755
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000756// Replace direct callers of Old with New.
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000757void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
758 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Stephen Hines36b56882014-04-23 16:57:46 -0700759 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
760 Use *U = &*UI;
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000761 ++UI;
Stephen Hines36b56882014-04-23 16:57:46 -0700762 CallSite CS(U->getUser());
763 if (CS && CS.isCallee(U)) {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000764 remove(CS.getInstruction()->getParent()->getParent());
Stephen Hines36b56882014-04-23 16:57:46 -0700765 U->set(BitcastNew);
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000766 }
767 }
768}
769
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000770// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
771void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000772 if (HasGlobalAliases && G->hasUnnamedAddr()) {
773 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
774 G->hasWeakLinkage()) {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000775 writeAlias(F, G);
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000776 return;
777 }
778 }
779
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000780 writeThunk(F, G);
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000781}
782
Stepan Dyatkovskiy80361492013-09-17 09:36:11 +0000783// Helper for writeThunk,
784// Selects proper bitcast operation,
Stephen Hines36b56882014-04-23 16:57:46 -0700785// but a bit simpler then CastInst::getCastOpcode.
Stepan Dyatkovskiy80361492013-09-17 09:36:11 +0000786static Value* createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
787 Type *SrcTy = V->getType();
788 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
789 return Builder.CreateIntToPtr(V, DestTy);
790 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
791 return Builder.CreatePtrToInt(V, DestTy);
792 else
793 return Builder.CreateBitCast(V, DestTy);
794}
795
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000796// Replace G with a simple tail call to bitcast(F). Also replace direct uses
797// of G with bitcast(F). Deletes G.
798void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000799 if (!G->mayBeOverridden()) {
800 // Redirect direct callers of G to F.
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000801 replaceDirectCallers(G, F);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000802 }
803
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000804 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000805 // stop here and delete G. There's no need for a thunk.
806 if (G->hasLocalLinkage() && G->use_empty()) {
807 G->eraseFromParent();
808 return;
809 }
810
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000811 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
812 G->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000813 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000814 IRBuilder<false> Builder(BB);
Nick Lewycky287de602009-06-12 08:04:51 +0000815
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000816 SmallVector<Value *, 16> Args;
Nick Lewycky287de602009-06-12 08:04:51 +0000817 unsigned i = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000818 FunctionType *FFTy = F->getFunctionType();
Nick Lewycky287de602009-06-12 08:04:51 +0000819 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
820 AI != AE; ++AI) {
Stepan Dyatkovskiy80361492013-09-17 09:36:11 +0000821 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewycky287de602009-06-12 08:04:51 +0000822 ++i;
823 }
824
Jay Foada3efbb12011-07-15 08:37:34 +0000825 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewycky287de602009-06-12 08:04:51 +0000826 CI->setTailCall();
Nick Lewyckyb3c36c92009-06-12 16:04:00 +0000827 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerf0127052010-01-05 13:12:22 +0000828 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000829 Builder.CreateRetVoid();
Nick Lewycky287de602009-06-12 08:04:51 +0000830 } else {
Stepan Dyatkovskiy80361492013-09-17 09:36:11 +0000831 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewycky287de602009-06-12 08:04:51 +0000832 }
833
834 NewG->copyAttributesFrom(G);
835 NewG->takeName(G);
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000836 removeUsers(G);
Nick Lewycky287de602009-06-12 08:04:51 +0000837 G->replaceAllUsesWith(NewG);
838 G->eraseFromParent();
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000839
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000840 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000841 ++NumThunksWritten;
Nick Lewycky287de602009-06-12 08:04:51 +0000842}
843
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000844// Replace G with an alias to F and delete G.
845void MergeFunctions::writeAlias(Function *F, Function *G) {
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000846 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
847 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
848 BitcastF, G->getParent());
849 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
850 GA->takeName(G);
851 GA->setVisibility(G->getVisibility());
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000852 removeUsers(G);
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000853 G->replaceAllUsesWith(GA);
854 G->eraseFromParent();
855
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000856 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000857 ++NumAliasesWritten;
858}
859
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000860// Merge two equivalent functions. Upon completion, Function G is deleted.
861void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000862 if (F->mayBeOverridden()) {
863 assert(G->mayBeOverridden());
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000864
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000865 if (HasGlobalAliases) {
866 // Make them both thunks to the same internal function.
867 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
868 F->getParent());
869 H->copyAttributesFrom(F);
870 H->takeName(F);
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000871 removeUsers(F);
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000872 F->replaceAllUsesWith(H);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000873
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000874 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewycky32218342010-08-09 21:03:28 +0000875
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000876 writeAlias(F, G);
877 writeAlias(F, H);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000878
Nick Lewyckyb38824f2011-01-25 08:56:50 +0000879 F->setAlignment(MaxAlignment);
880 F->setLinkage(GlobalValue::PrivateLinkage);
881 } else {
882 // We can't merge them. Instead, pick one and update all direct callers
883 // to call it and hope that we improve the instruction cache hit rate.
884 replaceDirectCallers(G, F);
885 }
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000886
887 ++NumDoubleWeak;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000888 } else {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000889 writeThunkOrAlias(F, G);
Nick Lewycky6feb3332008-11-02 16:46:26 +0000890 }
891
Nick Lewycky287de602009-06-12 08:04:51 +0000892 ++NumFunctionsMerged;
Nick Lewycky579a0242008-11-02 05:52:50 +0000893}
894
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000895// Insert a ComparableFunction into the FnSet, or merge it away if equal to one
896// that was already inserted.
897bool MergeFunctions::insert(ComparableFunction &NewF) {
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000898 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000899 if (Result.second) {
900 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000901 return false;
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000902 }
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000903
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000904 const ComparableFunction &OldF = *Result.first;
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000905
Matt Arsenault187c7742013-10-01 18:05:30 +0000906 // Don't merge tiny functions, since it can just end up making the function
907 // larger.
908 // FIXME: Should still merge them if they are unnamed_addr and produce an
909 // alias.
910 if (NewF.getFunc()->size() == 1) {
911 if (NewF.getFunc()->front().size() <= 2) {
912 DEBUG(dbgs() << NewF.getFunc()->getName()
913 << " is to small to bother merging\n");
914 return false;
915 }
916 }
917
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000918 // Never thunk a strong function to a weak function.
Nick Lewycky2b6c01b2010-09-07 01:42:10 +0000919 assert(!OldF.getFunc()->mayBeOverridden() ||
920 NewF.getFunc()->mayBeOverridden());
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000921
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000922 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
923 << NewF.getFunc()->getName() << '\n');
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000924
Nick Lewyckyb0e17772010-09-05 09:00:32 +0000925 Function *DeleteF = NewF.getFunc();
926 NewF.release();
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000927 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000928 return true;
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000929}
Nick Lewycky579a0242008-11-02 05:52:50 +0000930
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000931// Remove a function from FnSet. If it was already in FnSet, add it to Deferred
932// so that we'll look at it in the next round.
933void MergeFunctions::remove(Function *F) {
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000934 // We need to make sure we remove F, not a function "equal" to F per the
935 // function equality comparator.
936 //
937 // The special "lookup only" ComparableFunction bypasses the expensive
938 // function comparison in favour of a pointer comparison on the underlying
939 // Function*'s.
940 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
Nick Lewyckyabd6c752011-01-02 02:46:33 +0000941 if (FnSet.erase(CF)) {
Nick Lewycky3ba974a2011-02-09 06:32:02 +0000942 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
Nick Lewyckyabd6c752011-01-02 02:46:33 +0000943 Deferred.push_back(F);
Nick Lewyckyf53de862010-08-31 05:53:05 +0000944 }
Nick Lewyckyabd6c752011-01-02 02:46:33 +0000945}
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000946
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000947// For each instruction used by the value, remove() the function that contains
948// the instruction. This should happen right before a call to RAUW.
949void MergeFunctions::removeUsers(Value *V) {
Nick Lewyckyd081b042011-01-02 19:16:44 +0000950 std::vector<Value *> Worklist;
951 Worklist.push_back(V);
952 while (!Worklist.empty()) {
953 Value *V = Worklist.back();
954 Worklist.pop_back();
955
Stephen Hines36b56882014-04-23 16:57:46 -0700956 for (User *U : V->users()) {
957 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewycky468ee0a2011-01-28 08:43:14 +0000958 remove(I->getParent()->getParent());
Stephen Hines36b56882014-04-23 16:57:46 -0700959 } else if (isa<GlobalValue>(U)) {
Nick Lewyckye8f81392011-01-15 10:16:23 +0000960 // do nothing
Stephen Hines36b56882014-04-23 16:57:46 -0700961 } else if (Constant *C = dyn_cast<Constant>(U)) {
962 for (User *UU : C->users())
963 Worklist.push_back(UU);
Nick Lewyckyd081b042011-01-02 19:16:44 +0000964 }
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000965 }
Nick Lewyckyf53de862010-08-31 05:53:05 +0000966 }
Nick Lewyckyb0104e12010-09-05 08:22:49 +0000967}