blob: ee6b11b45a79fb7856b9885e067c6eb6c927314d [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//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000012// Order relation is defined on set of functions. It was made through
13// special function comparison procedure that returns
14// 0 when functions are equal,
15// -1 when Left function is less than right function, and
16// 1 for opposite case. We need total-ordering, so we need to maintain
17// four properties on the functions set:
18// a <= a (reflexivity)
19// if a <= b and b <= a then a = b (antisymmetry)
20// if a <= b and b <= c then a <= c (transitivity).
21// for all a and b: a <= b or b <= a (totality).
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000022//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000023// Comparison iterates through each instruction in each basic block.
24// Functions are kept on binary tree. For each new function F we perform
25// lookup in binary tree.
26// In practice it works the following way:
27// -- We define Function* container class with custom "operator<" (FunctionPtr).
28// -- "FunctionPtr" instances are stored in std::set collection, so every
29// std::set::insert operation will give you result in log(N) time.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000030//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000031// When a match is found the functions are folded. If both functions are
32// overridable, we move the functionality into a new internal function and
33// leave two overridable thunks to it.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000034//
35//===----------------------------------------------------------------------===//
36//
37// Future work:
38//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000039// * virtual functions.
40//
41// Many functions have their address taken by the virtual function table for
42// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000043// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000044//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000045// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000046//
47// In order to fold functions, we will sometimes add either bitcast instructions
48// or bitcast constant expressions. Unfortunately, this can confound further
49// analysis since the two functions differ where one has a bitcast and the
Nick Lewyckyfbd27572010-08-08 05:04:23 +000050// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000051//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000052// * Compare complex types with pointer types inside.
53// * Compare cross-reference cases.
54// * Compare complex expressions.
55//
56// All the three issues above could be described as ability to prove that
57// fA == fB == fC == fE == fF == fG in example below:
58//
59// void fA() {
60// fB();
61// }
62// void fB() {
63// fA();
64// }
65//
66// void fE() {
67// fF();
68// }
69// void fF() {
70// fG();
71// }
72// void fG() {
73// fE();
74// }
75//
76// Simplest cross-reference case (fA <--> fB) was implemented in previous
77// versions of MergeFunctions, though it presented only in two function pairs
78// in test-suite (that counts >50k functions)
79// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
80// could cover much more cases.
81//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000082//===----------------------------------------------------------------------===//
83
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000084#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include "llvm/ADT/DenseSet.h"
86#include "llvm/ADT/FoldingSet.h"
87#include "llvm/ADT/STLExtras.h"
88#include "llvm/ADT/SmallSet.h"
89#include "llvm/ADT/Statistic.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000090#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000091#include "llvm/IR/Constants.h"
92#include "llvm/IR/DataLayout.h"
93#include "llvm/IR/IRBuilder.h"
94#include "llvm/IR/InlineAsm.h"
95#include "llvm/IR/Instructions.h"
96#include "llvm/IR/LLVMContext.h"
97#include "llvm/IR/Module.h"
98#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000099#include "llvm/IR/ValueHandle.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000100#include "llvm/Pass.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000101#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000102#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +0000103#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000104#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +0000105#include <vector>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000106using namespace llvm;
107
Chandler Carruth964daaa2014-04-22 02:55:47 +0000108#define DEBUG_TYPE "mergefunc"
109
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000110STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000111STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000112STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000113STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000114
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000115static cl::opt<unsigned> NumFunctionsForSanityCheck(
116 "mergefunc-sanity",
117 cl::desc("How many functions in module could be used for "
118 "MergeFunctions pass sanity check. "
119 "'0' disables this check. Works only with '-debug' key."),
120 cl::init(0), cl::Hidden);
121
Benjamin Kramer630e6e12013-04-19 23:06:44 +0000122/// Returns the type id for a type to be hashed. We turn pointer types into
123/// integers here because the actual compare logic below considers pointers and
124/// integers of the same size as equal.
125static Type::TypeID getTypeIDForHash(Type *Ty) {
126 if (Ty->isPointerTy())
127 return Type::IntegerTyID;
128 return Ty->getTypeID();
129}
130
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000131/// Creates a hash-code for the function which is the same for any two
132/// functions that will compare equal, without looking at the instructions
133/// inside the function.
134static unsigned profileFunction(const Function *F) {
Chris Lattner229907c2011-07-18 04:54:35 +0000135 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000136
Nick Lewycky00959372010-09-05 08:22:49 +0000137 FoldingSetNodeID ID;
138 ID.AddInteger(F->size());
139 ID.AddInteger(F->getCallingConv());
140 ID.AddBoolean(F->hasGC());
141 ID.AddBoolean(FTy->isVarArg());
Benjamin Kramer630e6e12013-04-19 23:06:44 +0000142 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
Nick Lewycky00959372010-09-05 08:22:49 +0000143 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramer630e6e12013-04-19 23:06:44 +0000144 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
Nick Lewycky00959372010-09-05 08:22:49 +0000145 return ID.ComputeHash();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000146}
147
Nick Lewycky71972d42010-09-07 01:42:10 +0000148namespace {
149
Nick Lewyckyaaf40122011-01-28 08:19:00 +0000150/// ComparableFunction - A struct that pairs together functions with a
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000151/// DataLayout so that we can keep them together as elements in the DenseSet.
Nick Lewycky00959372010-09-05 08:22:49 +0000152class ComparableFunction {
153public:
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000154 static const ComparableFunction EmptyKey;
155 static const ComparableFunction TombstoneKey;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000156 static DataLayout * const LookupOnly;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000157
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000158 ComparableFunction(Function *Func, const DataLayout *DL)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000159 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
Nick Lewycky00959372010-09-05 08:22:49 +0000160
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000161 Function *getFunc() const { return Func; }
162 unsigned getHash() const { return Hash; }
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000163 const DataLayout *getDataLayout() const { return DL; }
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000164
165 // Drops AssertingVH reference to the function. Outside of debug mode, this
166 // does nothing.
167 void release() {
168 assert(Func &&
169 "Attempted to release function twice, or release empty/tombstone!");
Craig Topperf40110f2014-04-25 05:29:35 +0000170 Func = nullptr;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000171 }
172
173private:
174 explicit ComparableFunction(unsigned Hash)
Craig Topperf40110f2014-04-25 05:29:35 +0000175 : Func(nullptr), Hash(Hash), DL(nullptr) {}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000176
177 AssertingVH<Function> Func;
178 unsigned Hash;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000179 const DataLayout *DL;
Nick Lewycky00959372010-09-05 08:22:49 +0000180};
181
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000182const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
183const ComparableFunction ComparableFunction::TombstoneKey =
184 ComparableFunction(1);
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000185DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000186
Nick Lewycky71972d42010-09-07 01:42:10 +0000187}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000188
189namespace llvm {
190 template <>
191 struct DenseMapInfo<ComparableFunction> {
192 static ComparableFunction getEmptyKey() {
193 return ComparableFunction::EmptyKey;
194 }
195 static ComparableFunction getTombstoneKey() {
196 return ComparableFunction::TombstoneKey;
197 }
198 static unsigned getHashValue(const ComparableFunction &CF) {
199 return CF.getHash();
200 }
201 static bool isEqual(const ComparableFunction &LHS,
202 const ComparableFunction &RHS);
203 };
204}
205
206namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000207
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000208/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000209/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000210/// used if available. The comparator always fails conservatively (erring on the
211/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000212class FunctionComparator {
213public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000214 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000215 const Function *F2)
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000216 : FnL(F1), FnR(F2), DL(DL) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000217
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000218 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000219 int compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000220
221private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000222 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000223 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000224
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000225 /// Constants comparison.
226 /// Its analog to lexicographical comparison between hypothetical numbers
227 /// of next format:
228 /// <bitcastability-trait><raw-bit-contents>
229 ///
230 /// 1. Bitcastability.
231 /// Check whether L's type could be losslessly bitcasted to R's type.
232 /// On this stage method, in case when lossless bitcast is not possible
233 /// method returns -1 or 1, thus also defining which type is greater in
234 /// context of bitcastability.
235 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
236 /// to the contents comparison.
237 /// If types differ, remember types comparison result and check
238 /// whether we still can bitcast types.
239 /// Stage 1: Types that satisfies isFirstClassType conditions are always
240 /// greater then others.
241 /// Stage 2: Vector is greater then non-vector.
242 /// If both types are vectors, then vector with greater bitwidth is
243 /// greater.
244 /// If both types are vectors with the same bitwidth, then types
245 /// are bitcastable, and we can skip other stages, and go to contents
246 /// comparison.
247 /// Stage 3: Pointer types are greater than non-pointers. If both types are
248 /// pointers of the same address space - go to contents comparison.
249 /// Different address spaces: pointer with greater address space is
250 /// greater.
251 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
252 /// We don't know how to bitcast them. So, we better don't do it,
253 /// and return types comparison result (so it determines the
254 /// relationship among constants we don't know how to bitcast).
255 ///
256 /// Just for clearance, let's see how the set of constants could look
257 /// on single dimension axis:
258 ///
259 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
260 /// Where: NFCT - Not a FirstClassType
261 /// FCT - FirstClassTyp:
262 ///
263 /// 2. Compare raw contents.
264 /// It ignores types on this stage and only compares bits from L and R.
265 /// Returns 0, if L and R has equivalent contents.
266 /// -1 or 1 if values are different.
267 /// Pretty trivial:
268 /// 2.1. If contents are numbers, compare numbers.
269 /// Ints with greater bitwidth are greater. Ints with same bitwidths
270 /// compared by their contents.
271 /// 2.2. "And so on". Just to avoid discrepancies with comments
272 /// perhaps it would be better to read the implementation itself.
273 /// 3. And again about overall picture. Let's look back at how the ordered set
274 /// of constants will look like:
275 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
276 ///
277 /// Now look, what could be inside [FCT, "others"], for example:
278 /// [FCT, "others"] =
279 /// [
280 /// [double 0.1], [double 1.23],
281 /// [i32 1], [i32 2],
282 /// { double 1.0 }, ; StructTyID, NumElements = 1
283 /// { i32 1 }, ; StructTyID, NumElements = 1
284 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
285 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
286 /// ]
287 ///
288 /// Let's explain the order. Float numbers will be less than integers, just
289 /// because of cmpType terms: FloatTyID < IntegerTyID.
290 /// Floats (with same fltSemantics) are sorted according to their value.
291 /// Then you can see integers, and they are, like a floats,
292 /// could be easy sorted among each others.
293 /// The structures. Structures are grouped at the tail, again because of their
294 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
295 /// Structures with greater number of elements are greater. Structures with
296 /// greater elements going first are greater.
297 /// The same logic with vectors, arrays and other possible complex types.
298 ///
299 /// Bitcastable constants.
300 /// Let's assume, that some constant, belongs to some group of
301 /// "so-called-equal" values with different types, and at the same time
302 /// belongs to another group of constants with equal types
303 /// and "really" equal values.
304 ///
305 /// Now, prove that this is impossible:
306 ///
307 /// If constant A with type TyA is bitcastable to B with type TyB, then:
308 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
309 /// those should be vectors (if TyA is vector), pointers
310 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
311 /// be equal to TyB.
312 /// 2. All constants with non-equal, but bitcastable types to TyA, are
313 /// bitcastable to B.
314 /// Once again, just because we allow it to vectors and pointers only.
315 /// This statement could be expanded as below:
316 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
317 /// vector B, and thus bitcastable to B as well.
318 /// 2.2. All pointers of the same address space, no matter what they point to,
319 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
320 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
321 /// QED.
322 ///
323 /// In another words, for pointers and vectors, we ignore top-level type and
324 /// look at their particular properties (bit-width for vectors, and
325 /// address space for pointers).
326 /// If these properties are equal - compare their contents.
327 int cmpConstants(const Constant *L, const Constant *R);
328
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000329 /// Assign or look up previously assigned numbers for the two values, and
330 /// return whether the numbers are equal. Numbers are assigned in the order
331 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000332 /// Comparison order:
333 /// Stage 0: Value that is function itself is always greater then others.
334 /// If left and right values are references to their functions, then
335 /// they are equal.
336 /// Stage 1: Constants are greater than non-constants.
337 /// If both left and right are constants, then the result of
338 /// cmpConstants is used as cmpValues result.
339 /// Stage 2: InlineAsm instances are greater than others. If both left and
340 /// right are InlineAsm instances, InlineAsm* pointers casted to
341 /// integers and compared as numbers.
342 /// Stage 3: For all other cases we compare order we meet these values in
343 /// their functions. If right value was met first during scanning,
344 /// then left value is greater.
345 /// In another words, we compare serial numbers, for more details
346 /// see comments for sn_mapL and sn_mapR.
347 int cmpValues(const Value *L, const Value *R);
348
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000349 /// Compare two Instructions for equivalence, similar to
350 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000351 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000352 /// Stages are listed in "most significant stage first" order:
353 /// On each stage below, we do comparison between some left and right
354 /// operation parts. If parts are non-equal, we assign parts comparison
355 /// result to the operation comparison result and exit from method.
356 /// Otherwise we proceed to the next stage.
357 /// Stages:
358 /// 1. Operations opcodes. Compared as numbers.
359 /// 2. Number of operands.
360 /// 3. Operation types. Compared with cmpType method.
361 /// 4. Compare operation subclass optional data as stream of bytes:
362 /// just convert it to integers and call cmpNumbers.
363 /// 5. Compare in operation operand types with cmpType in
364 /// most significant operand first order.
365 /// 6. Last stage. Check operations for some specific attributes.
366 /// For example, for Load it would be:
367 /// 6.1.Load: volatile (as boolean flag)
368 /// 6.2.Load: alignment (as integer numbers)
369 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000370 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000371 /// On this stage its better to see the code, since its not more than 10-15
372 /// strings for particular instruction, and could change sometimes.
373 int cmpOperation(const Instruction *L, const Instruction *R) const;
374
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000375 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000376 /// Parts to be compared for each comparison stage,
377 /// most significant stage first:
378 /// 1. Address space. As numbers.
379 /// 2. Constant offset, (if "DataLayout *DL" field is not NULL,
380 /// using GEPOperator::accumulateConstantOffset method).
381 /// 3. Pointer operand type (using cmpType method).
382 /// 4. Number of operands.
383 /// 5. Compare operands, using cmpValues method.
384 int cmpGEP(const GEPOperator *GEPL, const GEPOperator *GEPR);
385 int cmpGEP(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
386 return cmpGEP(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
387 }
388
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000389 /// cmpType - compares two types,
390 /// defines total ordering among the types set.
391 ///
392 /// Return values:
393 /// 0 if types are equal,
394 /// -1 if Left is less than Right,
395 /// +1 if Left is greater than Right.
396 ///
397 /// Description:
398 /// Comparison is broken onto stages. Like in lexicographical comparison
399 /// stage coming first has higher priority.
400 /// On each explanation stage keep in mind total ordering properties.
401 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000402 /// 0. Before comparison we coerce pointer types of 0 address space to
403 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000404 /// We also don't bother with same type at left and right, so
405 /// just return 0 in this case.
406 ///
407 /// 1. If types are of different kind (different type IDs).
408 /// Return result of type IDs comparison, treating them as numbers.
409 /// 2. If types are vectors or integers, compare Type* values as numbers.
410 /// 3. Types has same ID, so check whether they belongs to the next group:
411 /// * Void
412 /// * Float
413 /// * Double
414 /// * X86_FP80
415 /// * FP128
416 /// * PPC_FP128
417 /// * Label
418 /// * Metadata
419 /// If so - return 0, yes - we can treat these types as equal only because
420 /// their IDs are same.
421 /// 4. If Left and Right are pointers, return result of address space
422 /// comparison (numbers comparison). We can treat pointer types of same
423 /// address space as equal.
424 /// 5. If types are complex.
425 /// Then both Left and Right are to be expanded and their element types will
426 /// be checked with the same way. If we get Res != 0 on some stage, return it.
427 /// Otherwise return 0.
428 /// 6. For all other cases put llvm_unreachable.
429 int cmpType(Type *TyL, Type *TyR) const;
430
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000431 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000432
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000433 int cmpAPInt(const APInt &L, const APInt &R) const;
434 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000435 int cmpStrings(StringRef L, StringRef R) const;
436 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000437
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000438 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000439 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000440
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000441 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000442
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000443 /// Assign serial numbers to values from left function, and values from
444 /// right function.
445 /// Explanation:
446 /// Being comparing functions we need to compare values we meet at left and
447 /// right sides.
448 /// Its easy to sort things out for external values. It just should be
449 /// the same value at left and right.
450 /// But for local values (those were introduced inside function body)
451 /// we have to ensure they were introduced at exactly the same place,
452 /// and plays the same role.
453 /// Let's assign serial number to each value when we meet it first time.
454 /// Values that were met at same place will be with same serial numbers.
455 /// In this case it would be good to explain few points about values assigned
456 /// to BBs and other ways of implementation (see below).
457 ///
458 /// 1. Safety of BB reordering.
459 /// It's safe to change the order of BasicBlocks in function.
460 /// Relationship with other functions and serial numbering will not be
461 /// changed in this case.
462 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
463 /// from the entry, and then take each terminator. So it doesn't matter how in
464 /// fact BBs are ordered in function. And since cmpValues are called during
465 /// this walk, the numbering depends only on how BBs located inside the CFG.
466 /// So the answer is - yes. We will get the same numbering.
467 ///
468 /// 2. Impossibility to use dominance properties of values.
469 /// If we compare two instruction operands: first is usage of local
470 /// variable AL from function FL, and second is usage of local variable AR
471 /// from FR, we could compare their origins and check whether they are
472 /// defined at the same place.
473 /// But, we are still not able to compare operands of PHI nodes, since those
474 /// could be operands from further BBs we didn't scan yet.
475 /// So it's impossible to use dominance properties in general.
476 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000477};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000478
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000479class FunctionPtr {
480 AssertingVH<Function> F;
481 const DataLayout *DL;
482
483public:
484 FunctionPtr(Function *F, const DataLayout *DL) : F(F), DL(DL) {}
485 Function *getFunc() const { return F; }
486 void release() { F = 0; }
487 bool operator<(const FunctionPtr &RHS) const {
488 return (FunctionComparator(DL, F, RHS.getFunc()).compare()) == -1;
489 }
490};
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000491}
492
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000493int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
494 if (L < R) return -1;
495 if (L > R) return 1;
496 return 0;
497}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000498
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000499int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
500 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
501 return Res;
502 if (L.ugt(R)) return 1;
503 if (R.ugt(L)) return -1;
504 return 0;
505}
506
507int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
508 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
509 (uint64_t)&R.getSemantics()))
510 return Res;
511 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
512}
513
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000514int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
515 // Prevent heavy comparison, compare sizes first.
516 if (int Res = cmpNumbers(L.size(), R.size()))
517 return Res;
518
519 // Compare strings lexicographically only when it is necessary: only when
520 // strings are equal in size.
521 return L.compare(R);
522}
523
524int FunctionComparator::cmpAttrs(const AttributeSet L,
525 const AttributeSet R) const {
526 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
527 return Res;
528
529 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
530 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
531 RE = R.end(i);
532 for (; LI != LE && RI != RE; ++LI, ++RI) {
533 Attribute LA = *LI;
534 Attribute RA = *RI;
535 if (LA < RA)
536 return -1;
537 if (RA < LA)
538 return 1;
539 }
540 if (LI != LE)
541 return 1;
542 if (RI != RE)
543 return -1;
544 }
545 return 0;
546}
547
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000548/// Constants comparison:
549/// 1. Check whether type of L constant could be losslessly bitcasted to R
550/// type.
551/// 2. Compare constant contents.
552/// For more details see declaration comments.
553int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
554
555 Type *TyL = L->getType();
556 Type *TyR = R->getType();
557
558 // Check whether types are bitcastable. This part is just re-factored
559 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
560 // we also pack into result which type is "less" for us.
561 int TypesRes = cmpType(TyL, TyR);
562 if (TypesRes != 0) {
563 // Types are different, but check whether we can bitcast them.
564 if (!TyL->isFirstClassType()) {
565 if (TyR->isFirstClassType())
566 return -1;
567 // Neither TyL nor TyR are values of first class type. Return the result
568 // of comparing the types
569 return TypesRes;
570 }
571 if (!TyR->isFirstClassType()) {
572 if (TyL->isFirstClassType())
573 return 1;
574 return TypesRes;
575 }
576
577 // Vector -> Vector conversions are always lossless if the two vector types
578 // have the same size, otherwise not.
579 unsigned TyLWidth = 0;
580 unsigned TyRWidth = 0;
581
582 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
583 TyLWidth = VecTyL->getBitWidth();
584 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
585 TyRWidth = VecTyR->getBitWidth();
586
587 if (TyLWidth != TyRWidth)
588 return cmpNumbers(TyLWidth, TyRWidth);
589
590 // Zero bit-width means neither TyL nor TyR are vectors.
591 if (!TyLWidth) {
592 PointerType *PTyL = dyn_cast<PointerType>(TyL);
593 PointerType *PTyR = dyn_cast<PointerType>(TyR);
594 if (PTyL && PTyR) {
595 unsigned AddrSpaceL = PTyL->getAddressSpace();
596 unsigned AddrSpaceR = PTyR->getAddressSpace();
597 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
598 return Res;
599 }
600 if (PTyL)
601 return 1;
602 if (PTyR)
603 return -1;
604
605 // TyL and TyR aren't vectors, nor pointers. We don't know how to
606 // bitcast them.
607 return TypesRes;
608 }
609 }
610
611 // OK, types are bitcastable, now check constant contents.
612
613 if (L->isNullValue() && R->isNullValue())
614 return TypesRes;
615 if (L->isNullValue() && !R->isNullValue())
616 return 1;
617 if (!L->isNullValue() && R->isNullValue())
618 return -1;
619
620 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
621 return Res;
622
623 switch (L->getValueID()) {
624 case Value::UndefValueVal: return TypesRes;
625 case Value::ConstantIntVal: {
626 const APInt &LInt = cast<ConstantInt>(L)->getValue();
627 const APInt &RInt = cast<ConstantInt>(R)->getValue();
628 return cmpAPInt(LInt, RInt);
629 }
630 case Value::ConstantFPVal: {
631 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
632 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
633 return cmpAPFloat(LAPF, RAPF);
634 }
635 case Value::ConstantArrayVal: {
636 const ConstantArray *LA = cast<ConstantArray>(L);
637 const ConstantArray *RA = cast<ConstantArray>(R);
638 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
639 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
640 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
641 return Res;
642 for (uint64_t i = 0; i < NumElementsL; ++i) {
643 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
644 cast<Constant>(RA->getOperand(i))))
645 return Res;
646 }
647 return 0;
648 }
649 case Value::ConstantStructVal: {
650 const ConstantStruct *LS = cast<ConstantStruct>(L);
651 const ConstantStruct *RS = cast<ConstantStruct>(R);
652 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
653 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
654 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
655 return Res;
656 for (unsigned i = 0; i != NumElementsL; ++i) {
657 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
658 cast<Constant>(RS->getOperand(i))))
659 return Res;
660 }
661 return 0;
662 }
663 case Value::ConstantVectorVal: {
664 const ConstantVector *LV = cast<ConstantVector>(L);
665 const ConstantVector *RV = cast<ConstantVector>(R);
666 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
667 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
668 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
669 return Res;
670 for (uint64_t i = 0; i < NumElementsL; ++i) {
671 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
672 cast<Constant>(RV->getOperand(i))))
673 return Res;
674 }
675 return 0;
676 }
677 case Value::ConstantExprVal: {
678 const ConstantExpr *LE = cast<ConstantExpr>(L);
679 const ConstantExpr *RE = cast<ConstantExpr>(R);
680 unsigned NumOperandsL = LE->getNumOperands();
681 unsigned NumOperandsR = RE->getNumOperands();
682 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
683 return Res;
684 for (unsigned i = 0; i < NumOperandsL; ++i) {
685 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
686 cast<Constant>(RE->getOperand(i))))
687 return Res;
688 }
689 return 0;
690 }
691 case Value::FunctionVal:
692 case Value::GlobalVariableVal:
693 case Value::GlobalAliasVal:
694 default: // Unknown constant, cast L and R pointers to numbers and compare.
695 return cmpNumbers((uint64_t)L, (uint64_t)R);
696 }
697}
698
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000699/// cmpType - compares two types,
700/// defines total ordering among the types set.
701/// See method declaration comments for more details.
702int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
703
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000704 PointerType *PTyL = dyn_cast<PointerType>(TyL);
705 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000706
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000707 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000708 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
709 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000710 }
711
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000712 if (TyL == TyR)
713 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000714
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000715 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
716 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000717
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000718 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000719 default:
720 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000721 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000722 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000723 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000724 // TyL == TyR would have returned true earlier.
725 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000726
Nick Lewyckye04dc222009-06-12 08:04:51 +0000727 case Type::VoidTyID:
728 case Type::FloatTyID:
729 case Type::DoubleTyID:
730 case Type::X86_FP80TyID:
731 case Type::FP128TyID:
732 case Type::PPC_FP128TyID:
733 case Type::LabelTyID:
734 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000735 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000736
Nick Lewyckye04dc222009-06-12 08:04:51 +0000737 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000738 assert(PTyL && PTyR && "Both types must be pointers here.");
739 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000740 }
741
742 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000743 StructType *STyL = cast<StructType>(TyL);
744 StructType *STyR = cast<StructType>(TyR);
745 if (STyL->getNumElements() != STyR->getNumElements())
746 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000747
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000748 if (STyL->isPacked() != STyR->isPacked())
749 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000750
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000751 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
752 if (int Res = cmpType(STyL->getElementType(i),
753 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000754 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000755 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000756 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000757 }
758
759 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000760 FunctionType *FTyL = cast<FunctionType>(TyL);
761 FunctionType *FTyR = cast<FunctionType>(TyR);
762 if (FTyL->getNumParams() != FTyR->getNumParams())
763 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000764
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000765 if (FTyL->isVarArg() != FTyR->isVarArg())
766 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000767
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000768 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000769 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000770
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000771 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
772 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000773 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000774 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000775 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000776 }
777
Nick Lewycky375efe32010-07-16 06:31:12 +0000778 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000779 ArrayType *ATyL = cast<ArrayType>(TyL);
780 ArrayType *ATyR = cast<ArrayType>(TyR);
781 if (ATyL->getNumElements() != ATyR->getNumElements())
782 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
783 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000784 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000785 }
786}
787
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000788// Determine whether the two operations are the same except that pointer-to-A
789// and pointer-to-B are equivalent. This should be kept in sync with
790// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000791// Read method declaration comments for more details.
792int FunctionComparator::cmpOperation(const Instruction *L,
793 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000794 // Differences from Instruction::isSameOperationAs:
795 // * replace type comparison with calls to isEquivalentType.
796 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
797 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000798 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
799 return Res;
800
801 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
802 return Res;
803
804 if (int Res = cmpType(L->getType(), R->getType()))
805 return Res;
806
807 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
808 R->getRawSubclassOptionalData()))
809 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000810
811 // We have two instructions of identical opcode and #operands. Check to see
812 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000813 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
814 if (int Res =
815 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
816 return Res;
817 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000818
819 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000820 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
821 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
822 return Res;
823 if (int Res =
824 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
825 return Res;
826 if (int Res =
827 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
828 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000829 if (int Res =
830 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
831 return Res;
832 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
833 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000834 }
835 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
836 if (int Res =
837 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
838 return Res;
839 if (int Res =
840 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
841 return Res;
842 if (int Res =
843 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
844 return Res;
845 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
846 }
847 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
848 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
849 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
850 if (int Res = cmpNumbers(CI->getCallingConv(),
851 cast<CallInst>(R)->getCallingConv()))
852 return Res;
853 return cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes());
854 }
855 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
856 if (int Res = cmpNumbers(CI->getCallingConv(),
857 cast<InvokeInst>(R)->getCallingConv()))
858 return Res;
859 return cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes());
860 }
861 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
862 ArrayRef<unsigned> LIndices = IVI->getIndices();
863 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
864 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
865 return Res;
866 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
867 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
868 return Res;
869 }
870 }
871 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
872 ArrayRef<unsigned> LIndices = EVI->getIndices();
873 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
874 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
875 return Res;
876 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
877 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
878 return Res;
879 }
880 }
881 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
882 if (int Res =
883 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
884 return Res;
885 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
886 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000887
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000888 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
889 if (int Res = cmpNumbers(CXI->isVolatile(),
890 cast<AtomicCmpXchgInst>(R)->isVolatile()))
891 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000892 if (int Res = cmpNumbers(CXI->isWeak(),
893 cast<AtomicCmpXchgInst>(R)->isWeak()))
894 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000895 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
896 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
897 return Res;
898 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
899 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
900 return Res;
901 return cmpNumbers(CXI->getSynchScope(),
902 cast<AtomicCmpXchgInst>(R)->getSynchScope());
903 }
904 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
905 if (int Res = cmpNumbers(RMWI->getOperation(),
906 cast<AtomicRMWInst>(R)->getOperation()))
907 return Res;
908 if (int Res = cmpNumbers(RMWI->isVolatile(),
909 cast<AtomicRMWInst>(R)->isVolatile()))
910 return Res;
911 if (int Res = cmpNumbers(RMWI->getOrdering(),
912 cast<AtomicRMWInst>(R)->getOrdering()))
913 return Res;
914 return cmpNumbers(RMWI->getSynchScope(),
915 cast<AtomicRMWInst>(R)->getSynchScope());
916 }
917 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000918}
919
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000920// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000921// Read method declaration comments for more details.
922int FunctionComparator::cmpGEP(const GEPOperator *GEPL,
923 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000924
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000925 unsigned int ASL = GEPL->getPointerAddressSpace();
926 unsigned int ASR = GEPR->getPointerAddressSpace();
927
928 if (int Res = cmpNumbers(ASL, ASR))
929 return Res;
930
931 // When we have target data, we can reduce the GEP down to the value in bytes
932 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000933 if (DL) {
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000934 unsigned BitWidth = DL->getPointerSizeInBits(ASL);
935 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
936 if (GEPL->accumulateConstantOffset(*DL, OffsetL) &&
937 GEPR->accumulateConstantOffset(*DL, OffsetR))
938 return cmpAPInt(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000939 }
940
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000941 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
942 (uint64_t)GEPR->getPointerOperand()->getType()))
943 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000944
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000945 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
946 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000947
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000948 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
949 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
950 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000951 }
952
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000953 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000954}
955
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000956/// Compare two values used by the two functions under pair-wise comparison. If
957/// this is the first time the values are seen, they're added to the mapping so
958/// that we will detect mismatches on next use.
959/// See comments in declaration for more details.
960int FunctionComparator::cmpValues(const Value *L, const Value *R) {
961 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000962 if (L == FnL) {
963 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000964 return 0;
965 return -1;
966 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000967 if (R == FnR) {
968 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000969 return 0;
970 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000971 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000972
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000973 const Constant *ConstL = dyn_cast<Constant>(L);
974 const Constant *ConstR = dyn_cast<Constant>(R);
975 if (ConstL && ConstR) {
976 if (L == R)
977 return 0;
978 return cmpConstants(ConstL, ConstR);
979 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000980
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000981 if (ConstL)
982 return 1;
983 if (ConstR)
984 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000985
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000986 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
987 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
988
989 if (InlineAsmL && InlineAsmR)
990 return cmpNumbers((uint64_t)L, (uint64_t)R);
991 if (InlineAsmL)
992 return 1;
993 if (InlineAsmR)
994 return -1;
995
996 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
997 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
998
999 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001000}
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001001// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001002int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
1003 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
1004 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001005
1006 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001007 if (int Res = cmpValues(InstL, InstR))
1008 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001009
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001010 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
1011 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +00001012
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001013 if (GEPL && !GEPR)
1014 return 1;
1015 if (GEPR && !GEPL)
1016 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +00001017
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001018 if (GEPL && GEPR) {
1019 if (int Res =
1020 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
1021 return Res;
1022 if (int Res = cmpGEP(GEPL, GEPR))
1023 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001024 } else {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001025 if (int Res = cmpOperation(InstL, InstR))
1026 return Res;
1027 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001028
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001029 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
1030 Value *OpL = InstL->getOperand(i);
1031 Value *OpR = InstR->getOperand(i);
1032 if (int Res = cmpValues(OpL, OpR))
1033 return Res;
1034 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
1035 return Res;
1036 // TODO: Already checked in cmpOperation
1037 if (int Res = cmpType(OpL->getType(), OpR->getType()))
1038 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001039 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001040 }
1041
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001042 ++InstL, ++InstR;
1043 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001044
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001045 if (InstL != InstLE && InstR == InstRE)
1046 return 1;
1047 if (InstL == InstLE && InstR != InstRE)
1048 return -1;
1049 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001050}
1051
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001052// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001053int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001054
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001055 sn_mapL.clear();
1056 sn_mapR.clear();
1057
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001058 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1059 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001060
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001061 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1062 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001063
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001064 if (FnL->hasGC()) {
1065 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1066 return Res;
1067 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001068
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001069 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1070 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001071
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001072 if (FnL->hasSection()) {
1073 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1074 return Res;
1075 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001076
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001077 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1078 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001079
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001080 // TODO: if it's internal and only used in direct calls, we could handle this
1081 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001082 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1083 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001084
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001085 if (int Res = cmpType(FnL->getFunctionType(), FnR->getFunctionType()))
1086 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001087
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001088 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001089 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001090
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001091 // Visit the arguments so that they get enumerated in the order they're
1092 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001093 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1094 ArgRI = FnR->arg_begin(),
1095 ArgLE = FnL->arg_end();
1096 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1097 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001098 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001099 }
1100
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001101 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1102 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001103 // functions, then takes each block from each terminator in order. As an
1104 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001105 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001106 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001107
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001108 FnLBBs.push_back(&FnL->getEntryBlock());
1109 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001110
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001111 VisitedBBs.insert(FnLBBs[0]);
1112 while (!FnLBBs.empty()) {
1113 const BasicBlock *BBL = FnLBBs.pop_back_val();
1114 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001115
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001116 if (int Res = cmpValues(BBL, BBR))
1117 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001118
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001119 if (int Res = compare(BBL, BBR))
1120 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001121
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001122 const TerminatorInst *TermL = BBL->getTerminator();
1123 const TerminatorInst *TermR = BBR->getTerminator();
1124
1125 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1126 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1127 if (!VisitedBBs.insert(TermL->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001128 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001129
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001130 FnLBBs.push_back(TermL->getSuccessor(i));
1131 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001132 }
1133 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001134 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001135}
1136
Nick Lewycky564fcca2011-01-28 07:36:21 +00001137namespace {
1138
1139/// MergeFunctions finds functions which will generate identical machine code,
1140/// by considering all pointer types to be equivalent. Once identified,
1141/// MergeFunctions will fold them by replacing a call to one to a call to a
1142/// bitcast of the other.
1143///
1144class MergeFunctions : public ModulePass {
1145public:
1146 static char ID;
1147 MergeFunctions()
1148 : ModulePass(ID), HasGlobalAliases(false) {
1149 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1150 }
1151
Craig Topper3e4c6972014-03-05 09:10:37 +00001152 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001153
1154private:
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001155 typedef std::set<FunctionPtr> FnTreeType;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001156
1157 /// A work queue of functions that may have been modified and should be
1158 /// analyzed again.
1159 std::vector<WeakVH> Deferred;
1160
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001161 /// Checks the rules of order relation introduced among functions set.
1162 /// Returns true, if sanity check has been passed, and false if failed.
1163 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1164
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001165 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001166 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001167 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001168
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001169 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001170 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001171 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001172
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001173 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001174 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001175 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001176
1177 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1178 /// necessary to make types match.
1179 void replaceDirectCallers(Function *Old, Function *New);
1180
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001181 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1182 /// be converted into a thunk. In either case, it should never be visited
1183 /// again.
1184 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001185
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001186 /// Replace G with a thunk or an alias to F. Deletes G.
1187 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001188
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001189 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1190 /// of G with bitcast(F). Deletes G.
1191 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001192
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001193 /// Replace G with an alias to F. Deletes G.
1194 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001195
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001196 /// The set of all distinct functions. Use the insert() and remove() methods
1197 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001198 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001199
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001200 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001201 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001202
1203 /// Whether or not the target supports global aliases.
1204 bool HasGlobalAliases;
1205};
1206
1207} // end anonymous namespace
1208
1209char MergeFunctions::ID = 0;
1210INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1211
1212ModulePass *llvm::createMergeFunctionsPass() {
1213 return new MergeFunctions();
1214}
1215
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001216bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1217 if (const unsigned Max = NumFunctionsForSanityCheck) {
1218 unsigned TripleNumber = 0;
1219 bool Valid = true;
1220
1221 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1222
1223 unsigned i = 0;
1224 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1225 I != E && i < Max; ++I, ++i) {
1226 unsigned j = i;
1227 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1228 Function *F1 = cast<Function>(*I);
1229 Function *F2 = cast<Function>(*J);
1230 int Res1 = FunctionComparator(DL, F1, F2).compare();
1231 int Res2 = FunctionComparator(DL, F2, F1).compare();
1232
1233 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1234 if (Res1 != -Res2) {
1235 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1236 << "\n";
1237 F1->dump();
1238 F2->dump();
1239 Valid = false;
1240 }
1241
1242 if (Res1 == 0)
1243 continue;
1244
1245 unsigned k = j;
1246 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1247 ++k, ++K, ++TripleNumber) {
1248 if (K == J)
1249 continue;
1250
1251 Function *F3 = cast<Function>(*K);
1252 int Res3 = FunctionComparator(DL, F1, F3).compare();
1253 int Res4 = FunctionComparator(DL, F2, F3).compare();
1254
1255 bool Transitive = true;
1256
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001257 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001258 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001259 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001260 } else if (Res3 != 0 && Res3 == -Res4) {
1261 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001262 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001263 } else if (Res4 != 0 && -Res3 == Res4) {
1264 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001265 Transitive = Res4 == -Res1;
1266 }
1267
1268 if (!Transitive) {
1269 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1270 << TripleNumber << "\n";
1271 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1272 << Res4 << "\n";
1273 F1->dump();
1274 F2->dump();
1275 F3->dump();
1276 Valid = false;
1277 }
1278 }
1279 }
1280 }
1281
1282 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1283 return Valid;
1284 }
1285 return true;
1286}
1287
Nick Lewycky564fcca2011-01-28 07:36:21 +00001288bool MergeFunctions::runOnModule(Module &M) {
1289 bool Changed = false;
Rafael Espindola93512512014-02-25 17:30:31 +00001290 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001291 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001292
1293 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1294 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1295 Deferred.push_back(WeakVH(I));
1296 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001297
1298 do {
1299 std::vector<WeakVH> Worklist;
1300 Deferred.swap(Worklist);
1301
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001302 DEBUG(doSanityCheck(Worklist));
1303
Nick Lewycky564fcca2011-01-28 07:36:21 +00001304 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1305 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1306
1307 // Insert only strong functions and merge them. Strong function merging
1308 // always deletes one of them.
1309 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1310 E = Worklist.end(); I != E; ++I) {
1311 if (!*I) continue;
1312 Function *F = cast<Function>(*I);
1313 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1314 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001315 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001316 }
1317 }
1318
1319 // Insert only weak functions and merge them. By doing these second we
1320 // create thunks to the strong function when possible. When two weak
1321 // functions are identical, we create a new strong function with two weak
1322 // weak thunks to it which are identical but not mergable.
1323 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1324 E = Worklist.end(); I != E; ++I) {
1325 if (!*I) continue;
1326 Function *F = cast<Function>(*I);
1327 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1328 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001329 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001330 }
1331 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001332 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001333 } while (!Deferred.empty());
1334
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001335 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001336
1337 return Changed;
1338}
1339
1340bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1341 const ComparableFunction &RHS) {
1342 if (LHS.getFunc() == RHS.getFunc() &&
1343 LHS.getHash() == RHS.getHash())
1344 return true;
1345 if (!LHS.getFunc() || !RHS.getFunc())
1346 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001347
1348 // One of these is a special "underlying pointer comparison only" object.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001349 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1350 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky292e78c2011-02-09 06:32:02 +00001351 return false;
1352
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001353 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky564fcca2011-01-28 07:36:21 +00001354 "Comparing functions for different targets");
1355
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001356 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(), RHS.getFunc())
1357 .compare() == 0;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001358}
1359
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001360// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001361void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1362 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001363 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1364 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001365 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001366 CallSite CS(U->getUser());
1367 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001368 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001369 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001370 }
1371 }
1372}
1373
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001374// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1375void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001376 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1377 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1378 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001379 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001380 return;
1381 }
1382 }
1383
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001384 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001385}
1386
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001387// Helper for writeThunk,
1388// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001389// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001390static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001391 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001392 if (SrcTy->isStructTy()) {
1393 assert(DestTy->isStructTy());
1394 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1395 Value *Result = UndefValue::get(DestTy);
1396 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1397 Value *Element = createCast(
1398 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1399 DestTy->getStructElementType(I));
1400
1401 Result =
1402 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1403 }
1404 return Result;
1405 }
1406 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001407 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1408 return Builder.CreateIntToPtr(V, DestTy);
1409 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1410 return Builder.CreatePtrToInt(V, DestTy);
1411 else
1412 return Builder.CreateBitCast(V, DestTy);
1413}
1414
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001415// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1416// of G with bitcast(F). Deletes G.
1417void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001418 if (!G->mayBeOverridden()) {
1419 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001420 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001421 }
1422
Nick Lewycky71972d42010-09-07 01:42:10 +00001423 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001424 // stop here and delete G. There's no need for a thunk.
1425 if (G->hasLocalLinkage() && G->use_empty()) {
1426 G->eraseFromParent();
1427 return;
1428 }
1429
Nick Lewycky25675ac2009-06-12 15:56:56 +00001430 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1431 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001432 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001433 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001434
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001435 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001436 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001437 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001438 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1439 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001440 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001441 ++i;
1442 }
1443
Jay Foad5bd375a2011-07-15 08:37:34 +00001444 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001445 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001446 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001447 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001448 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001449 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001450 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001451 }
1452
1453 NewG->copyAttributesFrom(G);
1454 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001455 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001456 G->replaceAllUsesWith(NewG);
1457 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001458
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001459 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001460 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001461}
1462
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001463// Replace G with an alias to F and delete G.
1464void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001465 PointerType *PTy = G->getType();
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001466 auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1467 G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001468 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1469 GA->takeName(G);
1470 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001471 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001472 G->replaceAllUsesWith(GA);
1473 G->eraseFromParent();
1474
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001475 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001476 ++NumAliasesWritten;
1477}
1478
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001479// Merge two equivalent functions. Upon completion, Function G is deleted.
1480void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001481 if (F->mayBeOverridden()) {
1482 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001483
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001484 if (HasGlobalAliases) {
1485 // Make them both thunks to the same internal function.
1486 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1487 F->getParent());
1488 H->copyAttributesFrom(F);
1489 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001490 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001491 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001492
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001493 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001494
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001495 writeAlias(F, G);
1496 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001497
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001498 F->setAlignment(MaxAlignment);
1499 F->setLinkage(GlobalValue::PrivateLinkage);
1500 } else {
1501 // We can't merge them. Instead, pick one and update all direct callers
1502 // to call it and hope that we improve the instruction cache hit rate.
1503 replaceDirectCallers(G, F);
1504 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001505
1506 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001507 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001508 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001509 }
1510
Nick Lewyckye04dc222009-06-12 08:04:51 +00001511 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001512}
1513
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001514// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001515// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001516bool MergeFunctions::insert(Function *NewFunction) {
1517 std::pair<FnTreeType::iterator, bool> Result =
1518 FnTree.insert(FunctionPtr(NewFunction, DL));
1519
Nick Lewycky292e78c2011-02-09 06:32:02 +00001520 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001521 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001522 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001523 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001524
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001525 const FunctionPtr &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001526
Matt Arsenault517d84e2013-10-01 18:05:30 +00001527 // Don't merge tiny functions, since it can just end up making the function
1528 // larger.
1529 // FIXME: Should still merge them if they are unnamed_addr and produce an
1530 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001531 if (NewFunction->size() == 1) {
1532 if (NewFunction->front().size() <= 2) {
1533 DEBUG(dbgs() << NewFunction->getName()
1534 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001535 return false;
1536 }
1537 }
1538
Nick Lewycky00959372010-09-05 08:22:49 +00001539 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001540 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001541
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001542 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1543 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001544
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001545 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001546 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001547 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001548}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001549
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001550// Remove a function from FnTree. If it was already in FnTree, add
1551// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001552void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001553 // We need to make sure we remove F, not a function "equal" to F per the
1554 // function equality comparator.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001555 FnTreeType::iterator found = FnTree.find(FunctionPtr(F, DL));
1556 size_t Erased = 0;
1557 if (found != FnTree.end() && found->getFunc() == F) {
1558 Erased = 1;
1559 FnTree.erase(found);
1560 }
1561
1562 if (Erased) {
1563 DEBUG(dbgs() << "Removed " << F->getName()
1564 << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001565 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001566 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001567}
Nick Lewycky00959372010-09-05 08:22:49 +00001568
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001569// For each instruction used by the value, remove() the function that contains
1570// the instruction. This should happen right before a call to RAUW.
1571void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001572 std::vector<Value *> Worklist;
1573 Worklist.push_back(V);
1574 while (!Worklist.empty()) {
1575 Value *V = Worklist.back();
1576 Worklist.pop_back();
1577
Chandler Carruthcdf47882014-03-09 03:16:01 +00001578 for (User *U : V->users()) {
1579 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001580 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001581 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001582 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001583 } else if (Constant *C = dyn_cast<Constant>(U)) {
1584 for (User *UU : C->users())
1585 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001586 }
Nick Lewycky00959372010-09-05 08:22:49 +00001587 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001588 }
Nick Lewycky00959372010-09-05 08:22:49 +00001589}