blob: 55d199ee7bae409803febe435658d50b742ebb37 [file] [log] [blame]
Nick Lewyckyd01d42e2008-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 Lewyckyd01d42e2008-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 Lewyckyd3c6dfe2010-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 Lewyckyd01d42e2008-11-02 05:52:50 +000023//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
Nick Lewyckyd01d42e2008-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 Lewyckyfbd27572010-08-08 05:04:23 +000032// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000033//
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +000034// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000036//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000037// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-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 Lewyckyfbd27572010-08-08 05:04:23 +000042// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000043//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000044//===----------------------------------------------------------------------===//
45
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000046#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/ADT/DenseSet.h"
48#include "llvm/ADT/FoldingSet.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/SmallSet.h"
51#include "llvm/ADT/Statistic.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000052#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000061#include "llvm/IR/ValueHandle.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000062#include "llvm/Pass.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000063#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000064#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000065#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +000066#include <vector>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000067using namespace llvm;
68
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "mergefunc"
70
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000071STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +000072STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +000073STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +000074STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000075
Benjamin Kramer630e6e12013-04-19 23:06:44 +000076/// Returns the type id for a type to be hashed. We turn pointer types into
77/// integers here because the actual compare logic below considers pointers and
78/// integers of the same size as equal.
79static Type::TypeID getTypeIDForHash(Type *Ty) {
80 if (Ty->isPointerTy())
81 return Type::IntegerTyID;
82 return Ty->getTypeID();
83}
84
Nick Lewyckycfb284c2011-01-28 08:43:14 +000085/// Creates a hash-code for the function which is the same for any two
86/// functions that will compare equal, without looking at the instructions
87/// inside the function.
88static unsigned profileFunction(const Function *F) {
Chris Lattner229907c2011-07-18 04:54:35 +000089 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyfbd27572010-08-08 05:04:23 +000090
Nick Lewycky00959372010-09-05 08:22:49 +000091 FoldingSetNodeID ID;
92 ID.AddInteger(F->size());
93 ID.AddInteger(F->getCallingConv());
94 ID.AddBoolean(F->hasGC());
95 ID.AddBoolean(FTy->isVarArg());
Benjamin Kramer630e6e12013-04-19 23:06:44 +000096 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
Nick Lewycky00959372010-09-05 08:22:49 +000097 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramer630e6e12013-04-19 23:06:44 +000098 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
Nick Lewycky00959372010-09-05 08:22:49 +000099 return ID.ComputeHash();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000100}
101
Nick Lewycky71972d42010-09-07 01:42:10 +0000102namespace {
103
Nick Lewyckyaaf40122011-01-28 08:19:00 +0000104/// ComparableFunction - A struct that pairs together functions with a
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000105/// DataLayout so that we can keep them together as elements in the DenseSet.
Nick Lewycky00959372010-09-05 08:22:49 +0000106class ComparableFunction {
107public:
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000108 static const ComparableFunction EmptyKey;
109 static const ComparableFunction TombstoneKey;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000110 static DataLayout * const LookupOnly;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000111
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000112 ComparableFunction(Function *Func, const DataLayout *DL)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000113 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
Nick Lewycky00959372010-09-05 08:22:49 +0000114
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000115 Function *getFunc() const { return Func; }
116 unsigned getHash() const { return Hash; }
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000117 const DataLayout *getDataLayout() const { return DL; }
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000118
119 // Drops AssertingVH reference to the function. Outside of debug mode, this
120 // does nothing.
121 void release() {
122 assert(Func &&
123 "Attempted to release function twice, or release empty/tombstone!");
Craig Topperf40110f2014-04-25 05:29:35 +0000124 Func = nullptr;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000125 }
126
127private:
128 explicit ComparableFunction(unsigned Hash)
Craig Topperf40110f2014-04-25 05:29:35 +0000129 : Func(nullptr), Hash(Hash), DL(nullptr) {}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000130
131 AssertingVH<Function> Func;
132 unsigned Hash;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000133 const DataLayout *DL;
Nick Lewycky00959372010-09-05 08:22:49 +0000134};
135
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000136const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
137const ComparableFunction ComparableFunction::TombstoneKey =
138 ComparableFunction(1);
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000139DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000140
Nick Lewycky71972d42010-09-07 01:42:10 +0000141}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000142
143namespace llvm {
144 template <>
145 struct DenseMapInfo<ComparableFunction> {
146 static ComparableFunction getEmptyKey() {
147 return ComparableFunction::EmptyKey;
148 }
149 static ComparableFunction getTombstoneKey() {
150 return ComparableFunction::TombstoneKey;
151 }
152 static unsigned getHashValue(const ComparableFunction &CF) {
153 return CF.getHash();
154 }
155 static bool isEqual(const ComparableFunction &LHS,
156 const ComparableFunction &RHS);
157 };
158}
159
160namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000161
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000162/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000163/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000164/// used if available. The comparator always fails conservatively (erring on the
165/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000166class FunctionComparator {
167public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000168 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000169 const Function *F2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000170 : F1(F1), F2(F2), DL(DL) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000171
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000172 /// Test whether the two functions have equivalent behaviour.
173 bool compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000174
175private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000176 /// Test whether two basic blocks have equivalent behaviour.
177 bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000178
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000179 /// Constants comparison.
180 /// Its analog to lexicographical comparison between hypothetical numbers
181 /// of next format:
182 /// <bitcastability-trait><raw-bit-contents>
183 ///
184 /// 1. Bitcastability.
185 /// Check whether L's type could be losslessly bitcasted to R's type.
186 /// On this stage method, in case when lossless bitcast is not possible
187 /// method returns -1 or 1, thus also defining which type is greater in
188 /// context of bitcastability.
189 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
190 /// to the contents comparison.
191 /// If types differ, remember types comparison result and check
192 /// whether we still can bitcast types.
193 /// Stage 1: Types that satisfies isFirstClassType conditions are always
194 /// greater then others.
195 /// Stage 2: Vector is greater then non-vector.
196 /// If both types are vectors, then vector with greater bitwidth is
197 /// greater.
198 /// If both types are vectors with the same bitwidth, then types
199 /// are bitcastable, and we can skip other stages, and go to contents
200 /// comparison.
201 /// Stage 3: Pointer types are greater than non-pointers. If both types are
202 /// pointers of the same address space - go to contents comparison.
203 /// Different address spaces: pointer with greater address space is
204 /// greater.
205 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
206 /// We don't know how to bitcast them. So, we better don't do it,
207 /// and return types comparison result (so it determines the
208 /// relationship among constants we don't know how to bitcast).
209 ///
210 /// Just for clearance, let's see how the set of constants could look
211 /// on single dimension axis:
212 ///
213 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
214 /// Where: NFCT - Not a FirstClassType
215 /// FCT - FirstClassTyp:
216 ///
217 /// 2. Compare raw contents.
218 /// It ignores types on this stage and only compares bits from L and R.
219 /// Returns 0, if L and R has equivalent contents.
220 /// -1 or 1 if values are different.
221 /// Pretty trivial:
222 /// 2.1. If contents are numbers, compare numbers.
223 /// Ints with greater bitwidth are greater. Ints with same bitwidths
224 /// compared by their contents.
225 /// 2.2. "And so on". Just to avoid discrepancies with comments
226 /// perhaps it would be better to read the implementation itself.
227 /// 3. And again about overall picture. Let's look back at how the ordered set
228 /// of constants will look like:
229 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
230 ///
231 /// Now look, what could be inside [FCT, "others"], for example:
232 /// [FCT, "others"] =
233 /// [
234 /// [double 0.1], [double 1.23],
235 /// [i32 1], [i32 2],
236 /// { double 1.0 }, ; StructTyID, NumElements = 1
237 /// { i32 1 }, ; StructTyID, NumElements = 1
238 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
239 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
240 /// ]
241 ///
242 /// Let's explain the order. Float numbers will be less than integers, just
243 /// because of cmpType terms: FloatTyID < IntegerTyID.
244 /// Floats (with same fltSemantics) are sorted according to their value.
245 /// Then you can see integers, and they are, like a floats,
246 /// could be easy sorted among each others.
247 /// The structures. Structures are grouped at the tail, again because of their
248 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
249 /// Structures with greater number of elements are greater. Structures with
250 /// greater elements going first are greater.
251 /// The same logic with vectors, arrays and other possible complex types.
252 ///
253 /// Bitcastable constants.
254 /// Let's assume, that some constant, belongs to some group of
255 /// "so-called-equal" values with different types, and at the same time
256 /// belongs to another group of constants with equal types
257 /// and "really" equal values.
258 ///
259 /// Now, prove that this is impossible:
260 ///
261 /// If constant A with type TyA is bitcastable to B with type TyB, then:
262 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
263 /// those should be vectors (if TyA is vector), pointers
264 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
265 /// be equal to TyB.
266 /// 2. All constants with non-equal, but bitcastable types to TyA, are
267 /// bitcastable to B.
268 /// Once again, just because we allow it to vectors and pointers only.
269 /// This statement could be expanded as below:
270 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
271 /// vector B, and thus bitcastable to B as well.
272 /// 2.2. All pointers of the same address space, no matter what they point to,
273 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
274 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
275 /// QED.
276 ///
277 /// In another words, for pointers and vectors, we ignore top-level type and
278 /// look at their particular properties (bit-width for vectors, and
279 /// address space for pointers).
280 /// If these properties are equal - compare their contents.
281 int cmpConstants(const Constant *L, const Constant *R);
282
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000283 /// Assign or look up previously assigned numbers for the two values, and
284 /// return whether the numbers are equal. Numbers are assigned in the order
285 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000286 /// Comparison order:
287 /// Stage 0: Value that is function itself is always greater then others.
288 /// If left and right values are references to their functions, then
289 /// they are equal.
290 /// Stage 1: Constants are greater than non-constants.
291 /// If both left and right are constants, then the result of
292 /// cmpConstants is used as cmpValues result.
293 /// Stage 2: InlineAsm instances are greater than others. If both left and
294 /// right are InlineAsm instances, InlineAsm* pointers casted to
295 /// integers and compared as numbers.
296 /// Stage 3: For all other cases we compare order we meet these values in
297 /// their functions. If right value was met first during scanning,
298 /// then left value is greater.
299 /// In another words, we compare serial numbers, for more details
300 /// see comments for sn_mapL and sn_mapR.
301 int cmpValues(const Value *L, const Value *R);
302
303 bool enumerate(const Value *V1, const Value *V2) {
304 return cmpValues(V1, V2) == 0;
305 }
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000306
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000307 /// Compare two Instructions for equivalence, similar to
308 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000309 /// comparison.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000310 bool isEquivalentOperation(const Instruction *I1,
311 const Instruction *I2) const;
312
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000313 /// Compare two GEPs for equivalent pointer arithmetic.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000314 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
315 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000316 const GetElementPtrInst *GEP2) {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000317 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
318 }
319
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000320 /// cmpType - compares two types,
321 /// defines total ordering among the types set.
322 ///
323 /// Return values:
324 /// 0 if types are equal,
325 /// -1 if Left is less than Right,
326 /// +1 if Left is greater than Right.
327 ///
328 /// Description:
329 /// Comparison is broken onto stages. Like in lexicographical comparison
330 /// stage coming first has higher priority.
331 /// On each explanation stage keep in mind total ordering properties.
332 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000333 /// 0. Before comparison we coerce pointer types of 0 address space to
334 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000335 /// We also don't bother with same type at left and right, so
336 /// just return 0 in this case.
337 ///
338 /// 1. If types are of different kind (different type IDs).
339 /// Return result of type IDs comparison, treating them as numbers.
340 /// 2. If types are vectors or integers, compare Type* values as numbers.
341 /// 3. Types has same ID, so check whether they belongs to the next group:
342 /// * Void
343 /// * Float
344 /// * Double
345 /// * X86_FP80
346 /// * FP128
347 /// * PPC_FP128
348 /// * Label
349 /// * Metadata
350 /// If so - return 0, yes - we can treat these types as equal only because
351 /// their IDs are same.
352 /// 4. If Left and Right are pointers, return result of address space
353 /// comparison (numbers comparison). We can treat pointer types of same
354 /// address space as equal.
355 /// 5. If types are complex.
356 /// Then both Left and Right are to be expanded and their element types will
357 /// be checked with the same way. If we get Res != 0 on some stage, return it.
358 /// Otherwise return 0.
359 /// 6. For all other cases put llvm_unreachable.
360 int cmpType(Type *TyL, Type *TyR) const;
361
362 bool isEquivalentType(Type *Ty1, Type *Ty2) const {
363 return cmpType(Ty1, Ty2) == 0;
364 }
365
366 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000367
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000368 int cmpAPInt(const APInt &L, const APInt &R) const;
369 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000370 int cmpStrings(StringRef L, StringRef R) const;
371 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000372
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000373 // The two functions undergoing comparison.
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000374 const Function *F1, *F2;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000375
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000376 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000377
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000378 /// Assign serial numbers to values from left function, and values from
379 /// right function.
380 /// Explanation:
381 /// Being comparing functions we need to compare values we meet at left and
382 /// right sides.
383 /// Its easy to sort things out for external values. It just should be
384 /// the same value at left and right.
385 /// But for local values (those were introduced inside function body)
386 /// we have to ensure they were introduced at exactly the same place,
387 /// and plays the same role.
388 /// Let's assign serial number to each value when we meet it first time.
389 /// Values that were met at same place will be with same serial numbers.
390 /// In this case it would be good to explain few points about values assigned
391 /// to BBs and other ways of implementation (see below).
392 ///
393 /// 1. Safety of BB reordering.
394 /// It's safe to change the order of BasicBlocks in function.
395 /// Relationship with other functions and serial numbering will not be
396 /// changed in this case.
397 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
398 /// from the entry, and then take each terminator. So it doesn't matter how in
399 /// fact BBs are ordered in function. And since cmpValues are called during
400 /// this walk, the numbering depends only on how BBs located inside the CFG.
401 /// So the answer is - yes. We will get the same numbering.
402 ///
403 /// 2. Impossibility to use dominance properties of values.
404 /// If we compare two instruction operands: first is usage of local
405 /// variable AL from function FL, and second is usage of local variable AR
406 /// from FR, we could compare their origins and check whether they are
407 /// defined at the same place.
408 /// But, we are still not able to compare operands of PHI nodes, since those
409 /// could be operands from further BBs we didn't scan yet.
410 /// So it's impossible to use dominance properties in general.
411 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000412};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000413
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000414}
415
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000416int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
417 if (L < R) return -1;
418 if (L > R) return 1;
419 return 0;
420}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000421
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000422int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
423 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
424 return Res;
425 if (L.ugt(R)) return 1;
426 if (R.ugt(L)) return -1;
427 return 0;
428}
429
430int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
431 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
432 (uint64_t)&R.getSemantics()))
433 return Res;
434 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
435}
436
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000437int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
438 // Prevent heavy comparison, compare sizes first.
439 if (int Res = cmpNumbers(L.size(), R.size()))
440 return Res;
441
442 // Compare strings lexicographically only when it is necessary: only when
443 // strings are equal in size.
444 return L.compare(R);
445}
446
447int FunctionComparator::cmpAttrs(const AttributeSet L,
448 const AttributeSet R) const {
449 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
450 return Res;
451
452 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
453 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
454 RE = R.end(i);
455 for (; LI != LE && RI != RE; ++LI, ++RI) {
456 Attribute LA = *LI;
457 Attribute RA = *RI;
458 if (LA < RA)
459 return -1;
460 if (RA < LA)
461 return 1;
462 }
463 if (LI != LE)
464 return 1;
465 if (RI != RE)
466 return -1;
467 }
468 return 0;
469}
470
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000471/// Constants comparison:
472/// 1. Check whether type of L constant could be losslessly bitcasted to R
473/// type.
474/// 2. Compare constant contents.
475/// For more details see declaration comments.
476int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
477
478 Type *TyL = L->getType();
479 Type *TyR = R->getType();
480
481 // Check whether types are bitcastable. This part is just re-factored
482 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
483 // we also pack into result which type is "less" for us.
484 int TypesRes = cmpType(TyL, TyR);
485 if (TypesRes != 0) {
486 // Types are different, but check whether we can bitcast them.
487 if (!TyL->isFirstClassType()) {
488 if (TyR->isFirstClassType())
489 return -1;
490 // Neither TyL nor TyR are values of first class type. Return the result
491 // of comparing the types
492 return TypesRes;
493 }
494 if (!TyR->isFirstClassType()) {
495 if (TyL->isFirstClassType())
496 return 1;
497 return TypesRes;
498 }
499
500 // Vector -> Vector conversions are always lossless if the two vector types
501 // have the same size, otherwise not.
502 unsigned TyLWidth = 0;
503 unsigned TyRWidth = 0;
504
505 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
506 TyLWidth = VecTyL->getBitWidth();
507 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
508 TyRWidth = VecTyR->getBitWidth();
509
510 if (TyLWidth != TyRWidth)
511 return cmpNumbers(TyLWidth, TyRWidth);
512
513 // Zero bit-width means neither TyL nor TyR are vectors.
514 if (!TyLWidth) {
515 PointerType *PTyL = dyn_cast<PointerType>(TyL);
516 PointerType *PTyR = dyn_cast<PointerType>(TyR);
517 if (PTyL && PTyR) {
518 unsigned AddrSpaceL = PTyL->getAddressSpace();
519 unsigned AddrSpaceR = PTyR->getAddressSpace();
520 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
521 return Res;
522 }
523 if (PTyL)
524 return 1;
525 if (PTyR)
526 return -1;
527
528 // TyL and TyR aren't vectors, nor pointers. We don't know how to
529 // bitcast them.
530 return TypesRes;
531 }
532 }
533
534 // OK, types are bitcastable, now check constant contents.
535
536 if (L->isNullValue() && R->isNullValue())
537 return TypesRes;
538 if (L->isNullValue() && !R->isNullValue())
539 return 1;
540 if (!L->isNullValue() && R->isNullValue())
541 return -1;
542
543 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
544 return Res;
545
546 switch (L->getValueID()) {
547 case Value::UndefValueVal: return TypesRes;
548 case Value::ConstantIntVal: {
549 const APInt &LInt = cast<ConstantInt>(L)->getValue();
550 const APInt &RInt = cast<ConstantInt>(R)->getValue();
551 return cmpAPInt(LInt, RInt);
552 }
553 case Value::ConstantFPVal: {
554 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
555 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
556 return cmpAPFloat(LAPF, RAPF);
557 }
558 case Value::ConstantArrayVal: {
559 const ConstantArray *LA = cast<ConstantArray>(L);
560 const ConstantArray *RA = cast<ConstantArray>(R);
561 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
562 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
563 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
564 return Res;
565 for (uint64_t i = 0; i < NumElementsL; ++i) {
566 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
567 cast<Constant>(RA->getOperand(i))))
568 return Res;
569 }
570 return 0;
571 }
572 case Value::ConstantStructVal: {
573 const ConstantStruct *LS = cast<ConstantStruct>(L);
574 const ConstantStruct *RS = cast<ConstantStruct>(R);
575 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
576 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
577 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
578 return Res;
579 for (unsigned i = 0; i != NumElementsL; ++i) {
580 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
581 cast<Constant>(RS->getOperand(i))))
582 return Res;
583 }
584 return 0;
585 }
586 case Value::ConstantVectorVal: {
587 const ConstantVector *LV = cast<ConstantVector>(L);
588 const ConstantVector *RV = cast<ConstantVector>(R);
589 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
590 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
591 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
592 return Res;
593 for (uint64_t i = 0; i < NumElementsL; ++i) {
594 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
595 cast<Constant>(RV->getOperand(i))))
596 return Res;
597 }
598 return 0;
599 }
600 case Value::ConstantExprVal: {
601 const ConstantExpr *LE = cast<ConstantExpr>(L);
602 const ConstantExpr *RE = cast<ConstantExpr>(R);
603 unsigned NumOperandsL = LE->getNumOperands();
604 unsigned NumOperandsR = RE->getNumOperands();
605 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
606 return Res;
607 for (unsigned i = 0; i < NumOperandsL; ++i) {
608 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
609 cast<Constant>(RE->getOperand(i))))
610 return Res;
611 }
612 return 0;
613 }
614 case Value::FunctionVal:
615 case Value::GlobalVariableVal:
616 case Value::GlobalAliasVal:
617 default: // Unknown constant, cast L and R pointers to numbers and compare.
618 return cmpNumbers((uint64_t)L, (uint64_t)R);
619 }
620}
621
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000622/// cmpType - compares two types,
623/// defines total ordering among the types set.
624/// See method declaration comments for more details.
625int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
626
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000627 PointerType *PTyL = dyn_cast<PointerType>(TyL);
628 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000629
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000630 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000631 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
632 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000633 }
634
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000635 if (TyL == TyR)
636 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000637
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000638 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
639 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000640
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000641 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000642 default:
643 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000644 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000645 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000646 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000647 // TyL == TyR would have returned true earlier.
648 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000649
Nick Lewyckye04dc222009-06-12 08:04:51 +0000650 case Type::VoidTyID:
651 case Type::FloatTyID:
652 case Type::DoubleTyID:
653 case Type::X86_FP80TyID:
654 case Type::FP128TyID:
655 case Type::PPC_FP128TyID:
656 case Type::LabelTyID:
657 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000658 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000659
Nick Lewyckye04dc222009-06-12 08:04:51 +0000660 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000661 assert(PTyL && PTyR && "Both types must be pointers here.");
662 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000663 }
664
665 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000666 StructType *STyL = cast<StructType>(TyL);
667 StructType *STyR = cast<StructType>(TyR);
668 if (STyL->getNumElements() != STyR->getNumElements())
669 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000670
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000671 if (STyL->isPacked() != STyR->isPacked())
672 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000673
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000674 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
675 if (int Res = cmpType(STyL->getElementType(i),
676 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000677 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000678 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000679 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000680 }
681
682 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000683 FunctionType *FTyL = cast<FunctionType>(TyL);
684 FunctionType *FTyR = cast<FunctionType>(TyR);
685 if (FTyL->getNumParams() != FTyR->getNumParams())
686 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000687
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000688 if (FTyL->isVarArg() != FTyR->isVarArg())
689 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000690
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000691 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000692 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000693
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000694 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
695 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000696 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000697 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000698 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000699 }
700
Nick Lewycky375efe32010-07-16 06:31:12 +0000701 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000702 ArrayType *ATyL = cast<ArrayType>(TyL);
703 ArrayType *ATyR = cast<ArrayType>(TyR);
704 if (ATyL->getNumElements() != ATyR->getNumElements())
705 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
706 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000707 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000708 }
709}
710
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000711// Determine whether the two operations are the same except that pointer-to-A
712// and pointer-to-B are equivalent. This should be kept in sync with
713// Instruction::isSameOperationAs.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000714bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
715 const Instruction *I2) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000716 // Differences from Instruction::isSameOperationAs:
717 // * replace type comparison with calls to isEquivalentType.
718 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
719 // * because of the above, we don't test for the tail bit on calls later on
Nick Lewyckye04dc222009-06-12 08:04:51 +0000720 if (I1->getOpcode() != I2->getOpcode() ||
721 I1->getNumOperands() != I2->getNumOperands() ||
Dan Gohmanc8a27f22009-08-25 22:11:20 +0000722 !isEquivalentType(I1->getType(), I2->getType()) ||
723 !I1->hasSameSubclassOptionalData(I2))
Nick Lewyckye04dc222009-06-12 08:04:51 +0000724 return false;
725
726 // We have two instructions of identical opcode and #operands. Check to see
727 // if all operands are the same type
728 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
729 if (!isEquivalentType(I1->getOperand(i)->getType(),
730 I2->getOperand(i)->getType()))
731 return false;
732
733 // Check special state that is a part of some instructions.
734 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
735 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
Eli Friedman211e3482011-08-15 22:16:46 +0000736 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
737 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
738 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000739 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
740 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
Eli Friedman211e3482011-08-15 22:16:46 +0000741 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
742 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
743 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000744 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
745 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
746 if (const CallInst *CI = dyn_cast<CallInst>(I1))
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000747 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
Nick Lewycky91543442011-01-26 09:23:19 +0000748 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000749 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
750 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
Nick Lewycky91543442011-01-26 09:23:19 +0000751 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
Eli Friedmanadec5872011-07-29 03:05:32 +0000752 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
753 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
754 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
755 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
756 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
757 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
758 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
759 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
760 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
Tim Northovere94a5182014-03-11 10:48:52 +0000761 CXI->getSuccessOrdering() ==
762 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
763 CXI->getFailureOrdering() ==
764 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
Eli Friedmanadec5872011-07-29 03:05:32 +0000765 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
766 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
767 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
768 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
769 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
770 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000771
772 return true;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000773}
774
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000775// Determine whether two GEP operations perform the same underlying arithmetic.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000776bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
777 const GEPOperator *GEP2) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000778 unsigned AS = GEP1->getPointerAddressSpace();
779 if (AS != GEP2->getPointerAddressSpace())
780 return false;
781
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000782 if (DL) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000783 // When we have target data, we can reduce the GEP down to the value in bytes
784 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000785 unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000786 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000787 if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
788 GEP2->accumulateConstantOffset(*DL, Offset2)) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000789 return Offset1 == Offset2;
790 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000791 }
792
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000793 if (GEP1->getPointerOperand()->getType() !=
794 GEP2->getPointerOperand()->getType())
795 return false;
796
797 if (GEP1->getNumOperands() != GEP2->getNumOperands())
798 return false;
799
800 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000801 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000802 return false;
803 }
804
805 return true;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000806}
807
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000808/// Compare two values used by the two functions under pair-wise comparison. If
809/// this is the first time the values are seen, they're added to the mapping so
810/// that we will detect mismatches on next use.
811/// See comments in declaration for more details.
812int FunctionComparator::cmpValues(const Value *L, const Value *R) {
813 // Catch self-reference case.
814 if (L == F1) {
815 if (R == F2)
816 return 0;
817 return -1;
818 }
819 if (R == F2) {
820 if (L == F1)
821 return 0;
822 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000823 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000824
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000825 const Constant *ConstL = dyn_cast<Constant>(L);
826 const Constant *ConstR = dyn_cast<Constant>(R);
827 if (ConstL && ConstR) {
828 if (L == R)
829 return 0;
830 return cmpConstants(ConstL, ConstR);
831 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000832
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000833 if (ConstL)
834 return 1;
835 if (ConstR)
836 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000837
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000838 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
839 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
840
841 if (InlineAsmL && InlineAsmR)
842 return cmpNumbers((uint64_t)L, (uint64_t)R);
843 if (InlineAsmL)
844 return 1;
845 if (InlineAsmR)
846 return -1;
847
848 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
849 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
850
851 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000852}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000853// Test whether two basic blocks have equivalent behaviour.
854bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000855 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
856 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000857
858 do {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000859 if (!enumerate(F1I, F2I))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000860 return false;
861
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000862 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
863 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
864 if (!GEP2)
865 return false;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000866
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000867 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000868 return false;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000869
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000870 if (!isEquivalentGEP(GEP1, GEP2))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000871 return false;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000872 } else {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000873 if (!isEquivalentOperation(F1I, F2I))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000874 return false;
875
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000876 assert(F1I->getNumOperands() == F2I->getNumOperands());
877 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
878 Value *OpF1 = F1I->getOperand(i);
879 Value *OpF2 = F2I->getOperand(i);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000880
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000881 if (!enumerate(OpF1, OpF2))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000882 return false;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000883
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000884 if (OpF1->getValueID() != OpF2->getValueID() ||
885 !isEquivalentType(OpF1->getType(), OpF2->getType()))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000886 return false;
887 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000888 }
889
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000890 ++F1I, ++F2I;
891 } while (F1I != F1E && F2I != F2E);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000892
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000893 return F1I == F1E && F2I == F2E;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000894}
895
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000896// Test whether the two functions have equivalent behaviour.
897bool FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000898 // We need to recheck everything, but check the things that weren't included
899 // in the hash first.
900
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000901 sn_mapL.clear();
902 sn_mapR.clear();
903
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000904 if (F1->getAttributes() != F2->getAttributes())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000905 return false;
906
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000907 if (F1->hasGC() != F2->hasGC())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000908 return false;
909
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000910 if (F1->hasGC() && F1->getGC() != F2->getGC())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000911 return false;
912
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000913 if (F1->hasSection() != F2->hasSection())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000914 return false;
915
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000916 if (F1->hasSection() && F1->getSection() != F2->getSection())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000917 return false;
918
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000919 if (F1->isVarArg() != F2->isVarArg())
Nick Lewyckye04dc222009-06-12 08:04:51 +0000920 return false;
921
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000922 // TODO: if it's internal and only used in direct calls, we could handle this
923 // case too.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000924 if (F1->getCallingConv() != F2->getCallingConv())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000925 return false;
926
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000927 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000928 return false;
929
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000930 assert(F1->arg_size() == F2->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +0000931 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000932
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000933 // Visit the arguments so that they get enumerated in the order they're
934 // passed in.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000935 for (Function::const_arg_iterator f1i = F1->arg_begin(),
936 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000937 if (!enumerate(f1i, f2i))
Nick Lewycky71972d42010-09-07 01:42:10 +0000938 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000939 }
940
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000941 // We do a CFG-ordered walk since the actual ordering of the blocks in the
942 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000943 // functions, then takes each block from each terminator in order. As an
944 // artifact, this also means that unreachable blocks are ignored.
945 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
946 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000947
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000948 F1BBs.push_back(&F1->getEntryBlock());
949 F2BBs.push_back(&F2->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000950
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000951 VisitedBBs.insert(F1BBs[0]);
952 while (!F1BBs.empty()) {
953 const BasicBlock *F1BB = F1BBs.pop_back_val();
954 const BasicBlock *F2BB = F2BBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000955
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000956 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000957 return false;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000958
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000959 const TerminatorInst *F1TI = F1BB->getTerminator();
960 const TerminatorInst *F2TI = F2BB->getTerminator();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000961
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000962 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
963 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
964 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000965 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000966
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000967 F1BBs.push_back(F1TI->getSuccessor(i));
968 F2BBs.push_back(F2TI->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000969 }
970 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000971 return true;
972}
973
Nick Lewycky564fcca2011-01-28 07:36:21 +0000974namespace {
975
976/// MergeFunctions finds functions which will generate identical machine code,
977/// by considering all pointer types to be equivalent. Once identified,
978/// MergeFunctions will fold them by replacing a call to one to a call to a
979/// bitcast of the other.
980///
981class MergeFunctions : public ModulePass {
982public:
983 static char ID;
984 MergeFunctions()
985 : ModulePass(ID), HasGlobalAliases(false) {
986 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
987 }
988
Craig Topper3e4c6972014-03-05 09:10:37 +0000989 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000990
991private:
992 typedef DenseSet<ComparableFunction> FnSetType;
993
994 /// A work queue of functions that may have been modified and should be
995 /// analyzed again.
996 std::vector<WeakVH> Deferred;
997
998 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
999 /// equal to one that's already present.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001000 bool insert(ComparableFunction &NewF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001001
1002 /// Remove a Function from the FnSet and queue it up for a second sweep of
1003 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001004 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001005
1006 /// Find the functions that use this Value and remove them from FnSet and
1007 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001008 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001009
1010 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1011 /// necessary to make types match.
1012 void replaceDirectCallers(Function *Old, Function *New);
1013
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001014 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1015 /// be converted into a thunk. In either case, it should never be visited
1016 /// again.
1017 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001018
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001019 /// Replace G with a thunk or an alias to F. Deletes G.
1020 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001021
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001022 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1023 /// of G with bitcast(F). Deletes G.
1024 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001025
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001026 /// Replace G with an alias to F. Deletes G.
1027 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001028
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001029 /// The set of all distinct functions. Use the insert() and remove() methods
1030 /// to modify it.
Nick Lewycky564fcca2011-01-28 07:36:21 +00001031 FnSetType FnSet;
1032
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001033 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001034 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001035
1036 /// Whether or not the target supports global aliases.
1037 bool HasGlobalAliases;
1038};
1039
1040} // end anonymous namespace
1041
1042char MergeFunctions::ID = 0;
1043INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1044
1045ModulePass *llvm::createMergeFunctionsPass() {
1046 return new MergeFunctions();
1047}
1048
1049bool MergeFunctions::runOnModule(Module &M) {
1050 bool Changed = false;
Rafael Espindola93512512014-02-25 17:30:31 +00001051 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001052 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001053
1054 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1055 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1056 Deferred.push_back(WeakVH(I));
1057 }
1058 FnSet.resize(Deferred.size());
1059
1060 do {
1061 std::vector<WeakVH> Worklist;
1062 Deferred.swap(Worklist);
1063
1064 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1065 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1066
1067 // Insert only strong functions and merge them. Strong function merging
1068 // always deletes one of them.
1069 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1070 E = Worklist.end(); I != E; ++I) {
1071 if (!*I) continue;
1072 Function *F = cast<Function>(*I);
1073 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1074 !F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001075 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001076 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001077 }
1078 }
1079
1080 // Insert only weak functions and merge them. By doing these second we
1081 // create thunks to the strong function when possible. When two weak
1082 // functions are identical, we create a new strong function with two weak
1083 // weak thunks to it which are identical but not mergable.
1084 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1085 E = Worklist.end(); I != E; ++I) {
1086 if (!*I) continue;
1087 Function *F = cast<Function>(*I);
1088 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1089 F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001090 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001091 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001092 }
1093 }
1094 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1095 } while (!Deferred.empty());
1096
1097 FnSet.clear();
1098
1099 return Changed;
1100}
1101
1102bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1103 const ComparableFunction &RHS) {
1104 if (LHS.getFunc() == RHS.getFunc() &&
1105 LHS.getHash() == RHS.getHash())
1106 return true;
1107 if (!LHS.getFunc() || !RHS.getFunc())
1108 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001109
1110 // One of these is a special "underlying pointer comparison only" object.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001111 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1112 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky292e78c2011-02-09 06:32:02 +00001113 return false;
1114
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001115 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky564fcca2011-01-28 07:36:21 +00001116 "Comparing functions for different targets");
1117
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001118 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
Nick Lewyckya46c8982011-02-02 05:31:01 +00001119 RHS.getFunc()).compare();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001120}
1121
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001122// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001123void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1124 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001125 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1126 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001127 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001128 CallSite CS(U->getUser());
1129 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001130 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001131 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001132 }
1133 }
1134}
1135
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001136// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1137void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001138 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1139 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1140 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001141 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001142 return;
1143 }
1144 }
1145
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001146 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001147}
1148
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001149// Helper for writeThunk,
1150// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001151// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001152static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001153 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001154 if (SrcTy->isStructTy()) {
1155 assert(DestTy->isStructTy());
1156 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1157 Value *Result = UndefValue::get(DestTy);
1158 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1159 Value *Element = createCast(
1160 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1161 DestTy->getStructElementType(I));
1162
1163 Result =
1164 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1165 }
1166 return Result;
1167 }
1168 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001169 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1170 return Builder.CreateIntToPtr(V, DestTy);
1171 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1172 return Builder.CreatePtrToInt(V, DestTy);
1173 else
1174 return Builder.CreateBitCast(V, DestTy);
1175}
1176
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001177// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1178// of G with bitcast(F). Deletes G.
1179void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001180 if (!G->mayBeOverridden()) {
1181 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001182 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001183 }
1184
Nick Lewycky71972d42010-09-07 01:42:10 +00001185 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001186 // stop here and delete G. There's no need for a thunk.
1187 if (G->hasLocalLinkage() && G->use_empty()) {
1188 G->eraseFromParent();
1189 return;
1190 }
1191
Nick Lewycky25675ac2009-06-12 15:56:56 +00001192 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1193 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001194 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001195 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001196
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001197 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001198 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001199 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001200 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1201 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001202 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001203 ++i;
1204 }
1205
Jay Foad5bd375a2011-07-15 08:37:34 +00001206 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001207 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001208 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001209 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001210 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001211 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001212 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001213 }
1214
1215 NewG->copyAttributesFrom(G);
1216 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001217 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001218 G->replaceAllUsesWith(NewG);
1219 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001220
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001221 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001222 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001223}
1224
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001225// Replace G with an alias to F and delete G.
1226void MergeFunctions::writeAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001227 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
1228 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
1229 BitcastF, G->getParent());
1230 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1231 GA->takeName(G);
1232 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001233 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001234 G->replaceAllUsesWith(GA);
1235 G->eraseFromParent();
1236
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001237 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001238 ++NumAliasesWritten;
1239}
1240
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001241// Merge two equivalent functions. Upon completion, Function G is deleted.
1242void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001243 if (F->mayBeOverridden()) {
1244 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001245
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001246 if (HasGlobalAliases) {
1247 // Make them both thunks to the same internal function.
1248 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1249 F->getParent());
1250 H->copyAttributesFrom(F);
1251 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001252 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001253 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001254
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001255 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001256
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001257 writeAlias(F, G);
1258 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001259
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001260 F->setAlignment(MaxAlignment);
1261 F->setLinkage(GlobalValue::PrivateLinkage);
1262 } else {
1263 // We can't merge them. Instead, pick one and update all direct callers
1264 // to call it and hope that we improve the instruction cache hit rate.
1265 replaceDirectCallers(G, F);
1266 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001267
1268 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001269 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001270 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001271 }
1272
Nick Lewyckye04dc222009-06-12 08:04:51 +00001273 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001274}
1275
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001276// Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1277// that was already inserted.
1278bool MergeFunctions::insert(ComparableFunction &NewF) {
Nick Lewycky00959372010-09-05 08:22:49 +00001279 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
Nick Lewycky292e78c2011-02-09 06:32:02 +00001280 if (Result.second) {
1281 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001282 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001283 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001284
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001285 const ComparableFunction &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001286
Matt Arsenault517d84e2013-10-01 18:05:30 +00001287 // Don't merge tiny functions, since it can just end up making the function
1288 // larger.
1289 // FIXME: Should still merge them if they are unnamed_addr and produce an
1290 // alias.
1291 if (NewF.getFunc()->size() == 1) {
1292 if (NewF.getFunc()->front().size() <= 2) {
1293 DEBUG(dbgs() << NewF.getFunc()->getName()
1294 << " is to small to bother merging\n");
1295 return false;
1296 }
1297 }
1298
Nick Lewycky00959372010-09-05 08:22:49 +00001299 // Never thunk a strong function to a weak function.
Nick Lewycky71972d42010-09-07 01:42:10 +00001300 assert(!OldF.getFunc()->mayBeOverridden() ||
1301 NewF.getFunc()->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001302
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001303 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
1304 << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001305
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001306 Function *DeleteF = NewF.getFunc();
1307 NewF.release();
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001308 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001309 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001310}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001311
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001312// Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1313// so that we'll look at it in the next round.
1314void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001315 // We need to make sure we remove F, not a function "equal" to F per the
1316 // function equality comparator.
1317 //
1318 // The special "lookup only" ComparableFunction bypasses the expensive
1319 // function comparison in favour of a pointer comparison on the underlying
1320 // Function*'s.
1321 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
Nick Lewycky4e250c82011-01-02 02:46:33 +00001322 if (FnSet.erase(CF)) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001323 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001324 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001325 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001326}
Nick Lewycky00959372010-09-05 08:22:49 +00001327
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001328// For each instruction used by the value, remove() the function that contains
1329// the instruction. This should happen right before a call to RAUW.
1330void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001331 std::vector<Value *> Worklist;
1332 Worklist.push_back(V);
1333 while (!Worklist.empty()) {
1334 Value *V = Worklist.back();
1335 Worklist.pop_back();
1336
Chandler Carruthcdf47882014-03-09 03:16:01 +00001337 for (User *U : V->users()) {
1338 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001339 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001340 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001341 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001342 } else if (Constant *C = dyn_cast<Constant>(U)) {
1343 for (User *UU : C->users())
1344 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001345 }
Nick Lewycky00959372010-09-05 08:22:49 +00001346 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001347 }
Nick Lewycky00959372010-09-05 08:22:49 +00001348}