blob: 60ef2b6267337d0c6d6b27609e3093631035f396 [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.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000310 /// Stages are listed in "most significant stage first" order:
311 /// On each stage below, we do comparison between some left and right
312 /// operation parts. If parts are non-equal, we assign parts comparison
313 /// result to the operation comparison result and exit from method.
314 /// Otherwise we proceed to the next stage.
315 /// Stages:
316 /// 1. Operations opcodes. Compared as numbers.
317 /// 2. Number of operands.
318 /// 3. Operation types. Compared with cmpType method.
319 /// 4. Compare operation subclass optional data as stream of bytes:
320 /// just convert it to integers and call cmpNumbers.
321 /// 5. Compare in operation operand types with cmpType in
322 /// most significant operand first order.
323 /// 6. Last stage. Check operations for some specific attributes.
324 /// For example, for Load it would be:
325 /// 6.1.Load: volatile (as boolean flag)
326 /// 6.2.Load: alignment (as integer numbers)
327 /// 6.3.Load: synch-scope (as integer numbers)
328 /// On this stage its better to see the code, since its not more than 10-15
329 /// strings for particular instruction, and could change sometimes.
330 int cmpOperation(const Instruction *L, const Instruction *R) const;
331
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000332 bool isEquivalentOperation(const Instruction *I1,
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000333 const Instruction *I2) const {
334 return cmpOperation(I1, I2) == 0;
335 }
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000336
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000337 /// Compare two GEPs for equivalent pointer arithmetic.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000338 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
339 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000340 const GetElementPtrInst *GEP2) {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000341 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
342 }
343
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000344 /// cmpType - compares two types,
345 /// defines total ordering among the types set.
346 ///
347 /// Return values:
348 /// 0 if types are equal,
349 /// -1 if Left is less than Right,
350 /// +1 if Left is greater than Right.
351 ///
352 /// Description:
353 /// Comparison is broken onto stages. Like in lexicographical comparison
354 /// stage coming first has higher priority.
355 /// On each explanation stage keep in mind total ordering properties.
356 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000357 /// 0. Before comparison we coerce pointer types of 0 address space to
358 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000359 /// We also don't bother with same type at left and right, so
360 /// just return 0 in this case.
361 ///
362 /// 1. If types are of different kind (different type IDs).
363 /// Return result of type IDs comparison, treating them as numbers.
364 /// 2. If types are vectors or integers, compare Type* values as numbers.
365 /// 3. Types has same ID, so check whether they belongs to the next group:
366 /// * Void
367 /// * Float
368 /// * Double
369 /// * X86_FP80
370 /// * FP128
371 /// * PPC_FP128
372 /// * Label
373 /// * Metadata
374 /// If so - return 0, yes - we can treat these types as equal only because
375 /// their IDs are same.
376 /// 4. If Left and Right are pointers, return result of address space
377 /// comparison (numbers comparison). We can treat pointer types of same
378 /// address space as equal.
379 /// 5. If types are complex.
380 /// Then both Left and Right are to be expanded and their element types will
381 /// be checked with the same way. If we get Res != 0 on some stage, return it.
382 /// Otherwise return 0.
383 /// 6. For all other cases put llvm_unreachable.
384 int cmpType(Type *TyL, Type *TyR) const;
385
386 bool isEquivalentType(Type *Ty1, Type *Ty2) const {
387 return cmpType(Ty1, Ty2) == 0;
388 }
389
390 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000391
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000392 int cmpAPInt(const APInt &L, const APInt &R) const;
393 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000394 int cmpStrings(StringRef L, StringRef R) const;
395 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000396
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000397 // The two functions undergoing comparison.
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000398 const Function *F1, *F2;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000399
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000400 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000401
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000402 /// Assign serial numbers to values from left function, and values from
403 /// right function.
404 /// Explanation:
405 /// Being comparing functions we need to compare values we meet at left and
406 /// right sides.
407 /// Its easy to sort things out for external values. It just should be
408 /// the same value at left and right.
409 /// But for local values (those were introduced inside function body)
410 /// we have to ensure they were introduced at exactly the same place,
411 /// and plays the same role.
412 /// Let's assign serial number to each value when we meet it first time.
413 /// Values that were met at same place will be with same serial numbers.
414 /// In this case it would be good to explain few points about values assigned
415 /// to BBs and other ways of implementation (see below).
416 ///
417 /// 1. Safety of BB reordering.
418 /// It's safe to change the order of BasicBlocks in function.
419 /// Relationship with other functions and serial numbering will not be
420 /// changed in this case.
421 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
422 /// from the entry, and then take each terminator. So it doesn't matter how in
423 /// fact BBs are ordered in function. And since cmpValues are called during
424 /// this walk, the numbering depends only on how BBs located inside the CFG.
425 /// So the answer is - yes. We will get the same numbering.
426 ///
427 /// 2. Impossibility to use dominance properties of values.
428 /// If we compare two instruction operands: first is usage of local
429 /// variable AL from function FL, and second is usage of local variable AR
430 /// from FR, we could compare their origins and check whether they are
431 /// defined at the same place.
432 /// But, we are still not able to compare operands of PHI nodes, since those
433 /// could be operands from further BBs we didn't scan yet.
434 /// So it's impossible to use dominance properties in general.
435 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000436};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000437
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000438}
439
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000440int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
441 if (L < R) return -1;
442 if (L > R) return 1;
443 return 0;
444}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000445
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000446int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
447 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
448 return Res;
449 if (L.ugt(R)) return 1;
450 if (R.ugt(L)) return -1;
451 return 0;
452}
453
454int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
455 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
456 (uint64_t)&R.getSemantics()))
457 return Res;
458 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
459}
460
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000461int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
462 // Prevent heavy comparison, compare sizes first.
463 if (int Res = cmpNumbers(L.size(), R.size()))
464 return Res;
465
466 // Compare strings lexicographically only when it is necessary: only when
467 // strings are equal in size.
468 return L.compare(R);
469}
470
471int FunctionComparator::cmpAttrs(const AttributeSet L,
472 const AttributeSet R) const {
473 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
474 return Res;
475
476 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
477 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
478 RE = R.end(i);
479 for (; LI != LE && RI != RE; ++LI, ++RI) {
480 Attribute LA = *LI;
481 Attribute RA = *RI;
482 if (LA < RA)
483 return -1;
484 if (RA < LA)
485 return 1;
486 }
487 if (LI != LE)
488 return 1;
489 if (RI != RE)
490 return -1;
491 }
492 return 0;
493}
494
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000495/// Constants comparison:
496/// 1. Check whether type of L constant could be losslessly bitcasted to R
497/// type.
498/// 2. Compare constant contents.
499/// For more details see declaration comments.
500int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
501
502 Type *TyL = L->getType();
503 Type *TyR = R->getType();
504
505 // Check whether types are bitcastable. This part is just re-factored
506 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
507 // we also pack into result which type is "less" for us.
508 int TypesRes = cmpType(TyL, TyR);
509 if (TypesRes != 0) {
510 // Types are different, but check whether we can bitcast them.
511 if (!TyL->isFirstClassType()) {
512 if (TyR->isFirstClassType())
513 return -1;
514 // Neither TyL nor TyR are values of first class type. Return the result
515 // of comparing the types
516 return TypesRes;
517 }
518 if (!TyR->isFirstClassType()) {
519 if (TyL->isFirstClassType())
520 return 1;
521 return TypesRes;
522 }
523
524 // Vector -> Vector conversions are always lossless if the two vector types
525 // have the same size, otherwise not.
526 unsigned TyLWidth = 0;
527 unsigned TyRWidth = 0;
528
529 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
530 TyLWidth = VecTyL->getBitWidth();
531 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
532 TyRWidth = VecTyR->getBitWidth();
533
534 if (TyLWidth != TyRWidth)
535 return cmpNumbers(TyLWidth, TyRWidth);
536
537 // Zero bit-width means neither TyL nor TyR are vectors.
538 if (!TyLWidth) {
539 PointerType *PTyL = dyn_cast<PointerType>(TyL);
540 PointerType *PTyR = dyn_cast<PointerType>(TyR);
541 if (PTyL && PTyR) {
542 unsigned AddrSpaceL = PTyL->getAddressSpace();
543 unsigned AddrSpaceR = PTyR->getAddressSpace();
544 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
545 return Res;
546 }
547 if (PTyL)
548 return 1;
549 if (PTyR)
550 return -1;
551
552 // TyL and TyR aren't vectors, nor pointers. We don't know how to
553 // bitcast them.
554 return TypesRes;
555 }
556 }
557
558 // OK, types are bitcastable, now check constant contents.
559
560 if (L->isNullValue() && R->isNullValue())
561 return TypesRes;
562 if (L->isNullValue() && !R->isNullValue())
563 return 1;
564 if (!L->isNullValue() && R->isNullValue())
565 return -1;
566
567 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
568 return Res;
569
570 switch (L->getValueID()) {
571 case Value::UndefValueVal: return TypesRes;
572 case Value::ConstantIntVal: {
573 const APInt &LInt = cast<ConstantInt>(L)->getValue();
574 const APInt &RInt = cast<ConstantInt>(R)->getValue();
575 return cmpAPInt(LInt, RInt);
576 }
577 case Value::ConstantFPVal: {
578 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
579 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
580 return cmpAPFloat(LAPF, RAPF);
581 }
582 case Value::ConstantArrayVal: {
583 const ConstantArray *LA = cast<ConstantArray>(L);
584 const ConstantArray *RA = cast<ConstantArray>(R);
585 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
586 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
587 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
588 return Res;
589 for (uint64_t i = 0; i < NumElementsL; ++i) {
590 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
591 cast<Constant>(RA->getOperand(i))))
592 return Res;
593 }
594 return 0;
595 }
596 case Value::ConstantStructVal: {
597 const ConstantStruct *LS = cast<ConstantStruct>(L);
598 const ConstantStruct *RS = cast<ConstantStruct>(R);
599 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
600 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
601 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
602 return Res;
603 for (unsigned i = 0; i != NumElementsL; ++i) {
604 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
605 cast<Constant>(RS->getOperand(i))))
606 return Res;
607 }
608 return 0;
609 }
610 case Value::ConstantVectorVal: {
611 const ConstantVector *LV = cast<ConstantVector>(L);
612 const ConstantVector *RV = cast<ConstantVector>(R);
613 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
614 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
615 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
616 return Res;
617 for (uint64_t i = 0; i < NumElementsL; ++i) {
618 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
619 cast<Constant>(RV->getOperand(i))))
620 return Res;
621 }
622 return 0;
623 }
624 case Value::ConstantExprVal: {
625 const ConstantExpr *LE = cast<ConstantExpr>(L);
626 const ConstantExpr *RE = cast<ConstantExpr>(R);
627 unsigned NumOperandsL = LE->getNumOperands();
628 unsigned NumOperandsR = RE->getNumOperands();
629 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
630 return Res;
631 for (unsigned i = 0; i < NumOperandsL; ++i) {
632 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
633 cast<Constant>(RE->getOperand(i))))
634 return Res;
635 }
636 return 0;
637 }
638 case Value::FunctionVal:
639 case Value::GlobalVariableVal:
640 case Value::GlobalAliasVal:
641 default: // Unknown constant, cast L and R pointers to numbers and compare.
642 return cmpNumbers((uint64_t)L, (uint64_t)R);
643 }
644}
645
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000646/// cmpType - compares two types,
647/// defines total ordering among the types set.
648/// See method declaration comments for more details.
649int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
650
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000651 PointerType *PTyL = dyn_cast<PointerType>(TyL);
652 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000653
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000654 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000655 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
656 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000657 }
658
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000659 if (TyL == TyR)
660 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000661
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000662 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
663 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000664
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000665 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000666 default:
667 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000668 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000669 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000670 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000671 // TyL == TyR would have returned true earlier.
672 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000673
Nick Lewyckye04dc222009-06-12 08:04:51 +0000674 case Type::VoidTyID:
675 case Type::FloatTyID:
676 case Type::DoubleTyID:
677 case Type::X86_FP80TyID:
678 case Type::FP128TyID:
679 case Type::PPC_FP128TyID:
680 case Type::LabelTyID:
681 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000682 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000683
Nick Lewyckye04dc222009-06-12 08:04:51 +0000684 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000685 assert(PTyL && PTyR && "Both types must be pointers here.");
686 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000687 }
688
689 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000690 StructType *STyL = cast<StructType>(TyL);
691 StructType *STyR = cast<StructType>(TyR);
692 if (STyL->getNumElements() != STyR->getNumElements())
693 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000694
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000695 if (STyL->isPacked() != STyR->isPacked())
696 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000697
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000698 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
699 if (int Res = cmpType(STyL->getElementType(i),
700 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000701 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000702 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000703 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000704 }
705
706 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000707 FunctionType *FTyL = cast<FunctionType>(TyL);
708 FunctionType *FTyR = cast<FunctionType>(TyR);
709 if (FTyL->getNumParams() != FTyR->getNumParams())
710 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000711
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000712 if (FTyL->isVarArg() != FTyR->isVarArg())
713 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000714
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000715 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000716 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000717
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000718 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
719 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000720 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000721 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000722 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000723 }
724
Nick Lewycky375efe32010-07-16 06:31:12 +0000725 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000726 ArrayType *ATyL = cast<ArrayType>(TyL);
727 ArrayType *ATyR = cast<ArrayType>(TyR);
728 if (ATyL->getNumElements() != ATyR->getNumElements())
729 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
730 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000731 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000732 }
733}
734
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000735// Determine whether the two operations are the same except that pointer-to-A
736// and pointer-to-B are equivalent. This should be kept in sync with
737// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000738// Read method declaration comments for more details.
739int FunctionComparator::cmpOperation(const Instruction *L,
740 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000741 // Differences from Instruction::isSameOperationAs:
742 // * replace type comparison with calls to isEquivalentType.
743 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
744 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000745 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
746 return Res;
747
748 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
749 return Res;
750
751 if (int Res = cmpType(L->getType(), R->getType()))
752 return Res;
753
754 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
755 R->getRawSubclassOptionalData()))
756 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000757
758 // We have two instructions of identical opcode and #operands. Check to see
759 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000760 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
761 if (int Res =
762 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
763 return Res;
764 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000765
766 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000767 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
768 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
769 return Res;
770 if (int Res =
771 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
772 return Res;
773 if (int Res =
774 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
775 return Res;
776 return cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope());
777 }
778 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
779 if (int Res =
780 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
781 return Res;
782 if (int Res =
783 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
784 return Res;
785 if (int Res =
786 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
787 return Res;
788 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
789 }
790 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
791 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
792 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
793 if (int Res = cmpNumbers(CI->getCallingConv(),
794 cast<CallInst>(R)->getCallingConv()))
795 return Res;
796 return cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes());
797 }
798 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
799 if (int Res = cmpNumbers(CI->getCallingConv(),
800 cast<InvokeInst>(R)->getCallingConv()))
801 return Res;
802 return cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes());
803 }
804 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
805 ArrayRef<unsigned> LIndices = IVI->getIndices();
806 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
807 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
808 return Res;
809 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
810 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
811 return Res;
812 }
813 }
814 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
815 ArrayRef<unsigned> LIndices = EVI->getIndices();
816 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
817 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
818 return Res;
819 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
820 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
821 return Res;
822 }
823 }
824 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
825 if (int Res =
826 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
827 return Res;
828 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
829 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000830
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000831 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
832 if (int Res = cmpNumbers(CXI->isVolatile(),
833 cast<AtomicCmpXchgInst>(R)->isVolatile()))
834 return Res;
835 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
836 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
837 return Res;
838 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
839 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
840 return Res;
841 return cmpNumbers(CXI->getSynchScope(),
842 cast<AtomicCmpXchgInst>(R)->getSynchScope());
843 }
844 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
845 if (int Res = cmpNumbers(RMWI->getOperation(),
846 cast<AtomicRMWInst>(R)->getOperation()))
847 return Res;
848 if (int Res = cmpNumbers(RMWI->isVolatile(),
849 cast<AtomicRMWInst>(R)->isVolatile()))
850 return Res;
851 if (int Res = cmpNumbers(RMWI->getOrdering(),
852 cast<AtomicRMWInst>(R)->getOrdering()))
853 return Res;
854 return cmpNumbers(RMWI->getSynchScope(),
855 cast<AtomicRMWInst>(R)->getSynchScope());
856 }
857 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000858}
859
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000860// Determine whether two GEP operations perform the same underlying arithmetic.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000861bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
862 const GEPOperator *GEP2) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000863 unsigned AS = GEP1->getPointerAddressSpace();
864 if (AS != GEP2->getPointerAddressSpace())
865 return false;
866
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000867 if (DL) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000868 // When we have target data, we can reduce the GEP down to the value in bytes
869 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000870 unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000871 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000872 if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
873 GEP2->accumulateConstantOffset(*DL, Offset2)) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000874 return Offset1 == Offset2;
875 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000876 }
877
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000878 if (GEP1->getPointerOperand()->getType() !=
879 GEP2->getPointerOperand()->getType())
880 return false;
881
882 if (GEP1->getNumOperands() != GEP2->getNumOperands())
883 return false;
884
885 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000886 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000887 return false;
888 }
889
890 return true;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000891}
892
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000893/// Compare two values used by the two functions under pair-wise comparison. If
894/// this is the first time the values are seen, they're added to the mapping so
895/// that we will detect mismatches on next use.
896/// See comments in declaration for more details.
897int FunctionComparator::cmpValues(const Value *L, const Value *R) {
898 // Catch self-reference case.
899 if (L == F1) {
900 if (R == F2)
901 return 0;
902 return -1;
903 }
904 if (R == F2) {
905 if (L == F1)
906 return 0;
907 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000908 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000909
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000910 const Constant *ConstL = dyn_cast<Constant>(L);
911 const Constant *ConstR = dyn_cast<Constant>(R);
912 if (ConstL && ConstR) {
913 if (L == R)
914 return 0;
915 return cmpConstants(ConstL, ConstR);
916 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000917
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000918 if (ConstL)
919 return 1;
920 if (ConstR)
921 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000922
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000923 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
924 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
925
926 if (InlineAsmL && InlineAsmR)
927 return cmpNumbers((uint64_t)L, (uint64_t)R);
928 if (InlineAsmL)
929 return 1;
930 if (InlineAsmR)
931 return -1;
932
933 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
934 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
935
936 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000937}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000938// Test whether two basic blocks have equivalent behaviour.
939bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000940 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
941 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000942
943 do {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000944 if (!enumerate(F1I, F2I))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000945 return false;
946
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000947 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
948 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
949 if (!GEP2)
950 return false;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000951
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000952 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000953 return false;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000954
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000955 if (!isEquivalentGEP(GEP1, GEP2))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000956 return false;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000957 } else {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000958 if (!isEquivalentOperation(F1I, F2I))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000959 return false;
960
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000961 assert(F1I->getNumOperands() == F2I->getNumOperands());
962 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
963 Value *OpF1 = F1I->getOperand(i);
964 Value *OpF2 = F2I->getOperand(i);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000965
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000966 if (!enumerate(OpF1, OpF2))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +0000967 return false;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000968
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000969 if (OpF1->getValueID() != OpF2->getValueID() ||
970 !isEquivalentType(OpF1->getType(), OpF2->getType()))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000971 return false;
972 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000973 }
974
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000975 ++F1I, ++F2I;
976 } while (F1I != F1E && F2I != F2E);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000977
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000978 return F1I == F1E && F2I == F2E;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000979}
980
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000981// Test whether the two functions have equivalent behaviour.
982bool FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000983 // We need to recheck everything, but check the things that weren't included
984 // in the hash first.
985
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000986 sn_mapL.clear();
987 sn_mapR.clear();
988
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000989 if (F1->getAttributes() != F2->getAttributes())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000990 return false;
991
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000992 if (F1->hasGC() != F2->hasGC())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000993 return false;
994
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000995 if (F1->hasGC() && F1->getGC() != F2->getGC())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000996 return false;
997
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000998 if (F1->hasSection() != F2->hasSection())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000999 return false;
1000
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001001 if (F1->hasSection() && F1->getSection() != F2->getSection())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001002 return false;
1003
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001004 if (F1->isVarArg() != F2->isVarArg())
Nick Lewyckye04dc222009-06-12 08:04:51 +00001005 return false;
1006
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001007 // TODO: if it's internal and only used in direct calls, we could handle this
1008 // case too.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001009 if (F1->getCallingConv() != F2->getCallingConv())
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001010 return false;
1011
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001012 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001013 return false;
1014
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001015 assert(F1->arg_size() == F2->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001016 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001017
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001018 // Visit the arguments so that they get enumerated in the order they're
1019 // passed in.
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001020 for (Function::const_arg_iterator f1i = F1->arg_begin(),
1021 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001022 if (!enumerate(f1i, f2i))
Nick Lewycky71972d42010-09-07 01:42:10 +00001023 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001024 }
1025
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001026 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1027 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001028 // functions, then takes each block from each terminator in order. As an
1029 // artifact, this also means that unreachable blocks are ignored.
1030 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
1031 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001032
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001033 F1BBs.push_back(&F1->getEntryBlock());
1034 F2BBs.push_back(&F2->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001035
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001036 VisitedBBs.insert(F1BBs[0]);
1037 while (!F1BBs.empty()) {
1038 const BasicBlock *F1BB = F1BBs.pop_back_val();
1039 const BasicBlock *F2BB = F2BBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001040
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001041 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001042 return false;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001043
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001044 const TerminatorInst *F1TI = F1BB->getTerminator();
1045 const TerminatorInst *F2TI = F2BB->getTerminator();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001046
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001047 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
1048 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
1049 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001050 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001051
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001052 F1BBs.push_back(F1TI->getSuccessor(i));
1053 F2BBs.push_back(F2TI->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001054 }
1055 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001056 return true;
1057}
1058
Nick Lewycky564fcca2011-01-28 07:36:21 +00001059namespace {
1060
1061/// MergeFunctions finds functions which will generate identical machine code,
1062/// by considering all pointer types to be equivalent. Once identified,
1063/// MergeFunctions will fold them by replacing a call to one to a call to a
1064/// bitcast of the other.
1065///
1066class MergeFunctions : public ModulePass {
1067public:
1068 static char ID;
1069 MergeFunctions()
1070 : ModulePass(ID), HasGlobalAliases(false) {
1071 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1072 }
1073
Craig Topper3e4c6972014-03-05 09:10:37 +00001074 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001075
1076private:
1077 typedef DenseSet<ComparableFunction> FnSetType;
1078
1079 /// A work queue of functions that may have been modified and should be
1080 /// analyzed again.
1081 std::vector<WeakVH> Deferred;
1082
1083 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
1084 /// equal to one that's already present.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001085 bool insert(ComparableFunction &NewF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001086
1087 /// Remove a Function from the FnSet and queue it up for a second sweep of
1088 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001089 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001090
1091 /// Find the functions that use this Value and remove them from FnSet and
1092 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001093 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001094
1095 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1096 /// necessary to make types match.
1097 void replaceDirectCallers(Function *Old, Function *New);
1098
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001099 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1100 /// be converted into a thunk. In either case, it should never be visited
1101 /// again.
1102 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001103
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001104 /// Replace G with a thunk or an alias to F. Deletes G.
1105 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001106
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001107 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1108 /// of G with bitcast(F). Deletes G.
1109 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001110
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001111 /// Replace G with an alias to F. Deletes G.
1112 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001113
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001114 /// The set of all distinct functions. Use the insert() and remove() methods
1115 /// to modify it.
Nick Lewycky564fcca2011-01-28 07:36:21 +00001116 FnSetType FnSet;
1117
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001118 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001119 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001120
1121 /// Whether or not the target supports global aliases.
1122 bool HasGlobalAliases;
1123};
1124
1125} // end anonymous namespace
1126
1127char MergeFunctions::ID = 0;
1128INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1129
1130ModulePass *llvm::createMergeFunctionsPass() {
1131 return new MergeFunctions();
1132}
1133
1134bool MergeFunctions::runOnModule(Module &M) {
1135 bool Changed = false;
Rafael Espindola93512512014-02-25 17:30:31 +00001136 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001137 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001138
1139 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1140 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1141 Deferred.push_back(WeakVH(I));
1142 }
1143 FnSet.resize(Deferred.size());
1144
1145 do {
1146 std::vector<WeakVH> Worklist;
1147 Deferred.swap(Worklist);
1148
1149 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1150 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1151
1152 // Insert only strong functions and merge them. Strong function merging
1153 // always deletes one of them.
1154 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1155 E = Worklist.end(); I != E; ++I) {
1156 if (!*I) continue;
1157 Function *F = cast<Function>(*I);
1158 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1159 !F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001160 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001161 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001162 }
1163 }
1164
1165 // Insert only weak functions and merge them. By doing these second we
1166 // create thunks to the strong function when possible. When two weak
1167 // functions are identical, we create a new strong function with two weak
1168 // weak thunks to it which are identical but not mergable.
1169 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1170 E = Worklist.end(); I != E; ++I) {
1171 if (!*I) continue;
1172 Function *F = cast<Function>(*I);
1173 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1174 F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001175 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001176 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001177 }
1178 }
1179 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1180 } while (!Deferred.empty());
1181
1182 FnSet.clear();
1183
1184 return Changed;
1185}
1186
1187bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1188 const ComparableFunction &RHS) {
1189 if (LHS.getFunc() == RHS.getFunc() &&
1190 LHS.getHash() == RHS.getHash())
1191 return true;
1192 if (!LHS.getFunc() || !RHS.getFunc())
1193 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001194
1195 // One of these is a special "underlying pointer comparison only" object.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001196 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1197 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky292e78c2011-02-09 06:32:02 +00001198 return false;
1199
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001200 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky564fcca2011-01-28 07:36:21 +00001201 "Comparing functions for different targets");
1202
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001203 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
Nick Lewyckya46c8982011-02-02 05:31:01 +00001204 RHS.getFunc()).compare();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001205}
1206
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001207// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001208void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1209 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001210 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1211 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001212 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001213 CallSite CS(U->getUser());
1214 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001215 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001216 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001217 }
1218 }
1219}
1220
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001221// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1222void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001223 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1224 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1225 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001226 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001227 return;
1228 }
1229 }
1230
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001231 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001232}
1233
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001234// Helper for writeThunk,
1235// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001236// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001237static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001238 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001239 if (SrcTy->isStructTy()) {
1240 assert(DestTy->isStructTy());
1241 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1242 Value *Result = UndefValue::get(DestTy);
1243 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1244 Value *Element = createCast(
1245 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1246 DestTy->getStructElementType(I));
1247
1248 Result =
1249 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1250 }
1251 return Result;
1252 }
1253 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001254 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1255 return Builder.CreateIntToPtr(V, DestTy);
1256 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1257 return Builder.CreatePtrToInt(V, DestTy);
1258 else
1259 return Builder.CreateBitCast(V, DestTy);
1260}
1261
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001262// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1263// of G with bitcast(F). Deletes G.
1264void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001265 if (!G->mayBeOverridden()) {
1266 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001267 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001268 }
1269
Nick Lewycky71972d42010-09-07 01:42:10 +00001270 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001271 // stop here and delete G. There's no need for a thunk.
1272 if (G->hasLocalLinkage() && G->use_empty()) {
1273 G->eraseFromParent();
1274 return;
1275 }
1276
Nick Lewycky25675ac2009-06-12 15:56:56 +00001277 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1278 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001279 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001280 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001281
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001282 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001283 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001284 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001285 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1286 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001287 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001288 ++i;
1289 }
1290
Jay Foad5bd375a2011-07-15 08:37:34 +00001291 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001292 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001293 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001294 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001295 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001296 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001297 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001298 }
1299
1300 NewG->copyAttributesFrom(G);
1301 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001302 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001303 G->replaceAllUsesWith(NewG);
1304 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001305
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001306 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001307 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001308}
1309
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001310// Replace G with an alias to F and delete G.
1311void MergeFunctions::writeAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001312 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
1313 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
1314 BitcastF, G->getParent());
1315 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1316 GA->takeName(G);
1317 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001318 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001319 G->replaceAllUsesWith(GA);
1320 G->eraseFromParent();
1321
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001322 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001323 ++NumAliasesWritten;
1324}
1325
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001326// Merge two equivalent functions. Upon completion, Function G is deleted.
1327void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001328 if (F->mayBeOverridden()) {
1329 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001330
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001331 if (HasGlobalAliases) {
1332 // Make them both thunks to the same internal function.
1333 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1334 F->getParent());
1335 H->copyAttributesFrom(F);
1336 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001337 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001338 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001339
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001340 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001341
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001342 writeAlias(F, G);
1343 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001344
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001345 F->setAlignment(MaxAlignment);
1346 F->setLinkage(GlobalValue::PrivateLinkage);
1347 } else {
1348 // We can't merge them. Instead, pick one and update all direct callers
1349 // to call it and hope that we improve the instruction cache hit rate.
1350 replaceDirectCallers(G, F);
1351 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001352
1353 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001354 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001355 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001356 }
1357
Nick Lewyckye04dc222009-06-12 08:04:51 +00001358 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001359}
1360
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001361// Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1362// that was already inserted.
1363bool MergeFunctions::insert(ComparableFunction &NewF) {
Nick Lewycky00959372010-09-05 08:22:49 +00001364 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
Nick Lewycky292e78c2011-02-09 06:32:02 +00001365 if (Result.second) {
1366 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001367 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001368 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001369
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001370 const ComparableFunction &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001371
Matt Arsenault517d84e2013-10-01 18:05:30 +00001372 // Don't merge tiny functions, since it can just end up making the function
1373 // larger.
1374 // FIXME: Should still merge them if they are unnamed_addr and produce an
1375 // alias.
1376 if (NewF.getFunc()->size() == 1) {
1377 if (NewF.getFunc()->front().size() <= 2) {
1378 DEBUG(dbgs() << NewF.getFunc()->getName()
1379 << " is to small to bother merging\n");
1380 return false;
1381 }
1382 }
1383
Nick Lewycky00959372010-09-05 08:22:49 +00001384 // Never thunk a strong function to a weak function.
Nick Lewycky71972d42010-09-07 01:42:10 +00001385 assert(!OldF.getFunc()->mayBeOverridden() ||
1386 NewF.getFunc()->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001387
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001388 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
1389 << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001390
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001391 Function *DeleteF = NewF.getFunc();
1392 NewF.release();
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001393 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001394 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001395}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001396
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001397// Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1398// so that we'll look at it in the next round.
1399void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001400 // We need to make sure we remove F, not a function "equal" to F per the
1401 // function equality comparator.
1402 //
1403 // The special "lookup only" ComparableFunction bypasses the expensive
1404 // function comparison in favour of a pointer comparison on the underlying
1405 // Function*'s.
1406 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
Nick Lewycky4e250c82011-01-02 02:46:33 +00001407 if (FnSet.erase(CF)) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001408 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001409 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001410 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001411}
Nick Lewycky00959372010-09-05 08:22:49 +00001412
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001413// For each instruction used by the value, remove() the function that contains
1414// the instruction. This should happen right before a call to RAUW.
1415void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001416 std::vector<Value *> Worklist;
1417 Worklist.push_back(V);
1418 while (!Worklist.empty()) {
1419 Value *V = Worklist.back();
1420 Worklist.pop_back();
1421
Chandler Carruthcdf47882014-03-09 03:16:01 +00001422 for (User *U : V->users()) {
1423 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001424 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001425 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001426 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001427 } else if (Constant *C = dyn_cast<Constant>(U)) {
1428 for (User *UU : C->users())
1429 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001430 }
Nick Lewycky00959372010-09-05 08:22:49 +00001431 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001432 }
Nick Lewycky00959372010-09-05 08:22:49 +00001433}