blob: 1327645183ef25a853cc8b5f754b5b622a342ff7 [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
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000122namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000123
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000124/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000125/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000126/// used if available. The comparator always fails conservatively (erring on the
127/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000128class FunctionComparator {
129public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 FunctionComparator(const Function *F1, const Function *F2)
131 : FnL(F1), FnR(F2) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000132
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000133 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000134 int compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000135
136private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000137 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000138 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000139
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000140 /// Constants comparison.
141 /// Its analog to lexicographical comparison between hypothetical numbers
142 /// of next format:
143 /// <bitcastability-trait><raw-bit-contents>
144 ///
145 /// 1. Bitcastability.
146 /// Check whether L's type could be losslessly bitcasted to R's type.
147 /// On this stage method, in case when lossless bitcast is not possible
148 /// method returns -1 or 1, thus also defining which type is greater in
149 /// context of bitcastability.
150 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
151 /// to the contents comparison.
152 /// If types differ, remember types comparison result and check
153 /// whether we still can bitcast types.
154 /// Stage 1: Types that satisfies isFirstClassType conditions are always
155 /// greater then others.
156 /// Stage 2: Vector is greater then non-vector.
157 /// If both types are vectors, then vector with greater bitwidth is
158 /// greater.
159 /// If both types are vectors with the same bitwidth, then types
160 /// are bitcastable, and we can skip other stages, and go to contents
161 /// comparison.
162 /// Stage 3: Pointer types are greater than non-pointers. If both types are
163 /// pointers of the same address space - go to contents comparison.
164 /// Different address spaces: pointer with greater address space is
165 /// greater.
166 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
167 /// We don't know how to bitcast them. So, we better don't do it,
168 /// and return types comparison result (so it determines the
169 /// relationship among constants we don't know how to bitcast).
170 ///
171 /// Just for clearance, let's see how the set of constants could look
172 /// on single dimension axis:
173 ///
174 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
175 /// Where: NFCT - Not a FirstClassType
176 /// FCT - FirstClassTyp:
177 ///
178 /// 2. Compare raw contents.
179 /// It ignores types on this stage and only compares bits from L and R.
180 /// Returns 0, if L and R has equivalent contents.
181 /// -1 or 1 if values are different.
182 /// Pretty trivial:
183 /// 2.1. If contents are numbers, compare numbers.
184 /// Ints with greater bitwidth are greater. Ints with same bitwidths
185 /// compared by their contents.
186 /// 2.2. "And so on". Just to avoid discrepancies with comments
187 /// perhaps it would be better to read the implementation itself.
188 /// 3. And again about overall picture. Let's look back at how the ordered set
189 /// of constants will look like:
190 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
191 ///
192 /// Now look, what could be inside [FCT, "others"], for example:
193 /// [FCT, "others"] =
194 /// [
195 /// [double 0.1], [double 1.23],
196 /// [i32 1], [i32 2],
197 /// { double 1.0 }, ; StructTyID, NumElements = 1
198 /// { i32 1 }, ; StructTyID, NumElements = 1
199 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
200 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
201 /// ]
202 ///
203 /// Let's explain the order. Float numbers will be less than integers, just
204 /// because of cmpType terms: FloatTyID < IntegerTyID.
205 /// Floats (with same fltSemantics) are sorted according to their value.
206 /// Then you can see integers, and they are, like a floats,
207 /// could be easy sorted among each others.
208 /// The structures. Structures are grouped at the tail, again because of their
209 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
210 /// Structures with greater number of elements are greater. Structures with
211 /// greater elements going first are greater.
212 /// The same logic with vectors, arrays and other possible complex types.
213 ///
214 /// Bitcastable constants.
215 /// Let's assume, that some constant, belongs to some group of
216 /// "so-called-equal" values with different types, and at the same time
217 /// belongs to another group of constants with equal types
218 /// and "really" equal values.
219 ///
220 /// Now, prove that this is impossible:
221 ///
222 /// If constant A with type TyA is bitcastable to B with type TyB, then:
223 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
224 /// those should be vectors (if TyA is vector), pointers
225 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
226 /// be equal to TyB.
227 /// 2. All constants with non-equal, but bitcastable types to TyA, are
228 /// bitcastable to B.
229 /// Once again, just because we allow it to vectors and pointers only.
230 /// This statement could be expanded as below:
231 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
232 /// vector B, and thus bitcastable to B as well.
233 /// 2.2. All pointers of the same address space, no matter what they point to,
234 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
235 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
236 /// QED.
237 ///
238 /// In another words, for pointers and vectors, we ignore top-level type and
239 /// look at their particular properties (bit-width for vectors, and
240 /// address space for pointers).
241 /// If these properties are equal - compare their contents.
242 int cmpConstants(const Constant *L, const Constant *R);
243
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000244 /// Assign or look up previously assigned numbers for the two values, and
245 /// return whether the numbers are equal. Numbers are assigned in the order
246 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000247 /// Comparison order:
248 /// Stage 0: Value that is function itself is always greater then others.
249 /// If left and right values are references to their functions, then
250 /// they are equal.
251 /// Stage 1: Constants are greater than non-constants.
252 /// If both left and right are constants, then the result of
253 /// cmpConstants is used as cmpValues result.
254 /// Stage 2: InlineAsm instances are greater than others. If both left and
255 /// right are InlineAsm instances, InlineAsm* pointers casted to
256 /// integers and compared as numbers.
257 /// Stage 3: For all other cases we compare order we meet these values in
258 /// their functions. If right value was met first during scanning,
259 /// then left value is greater.
260 /// In another words, we compare serial numbers, for more details
261 /// see comments for sn_mapL and sn_mapR.
262 int cmpValues(const Value *L, const Value *R);
263
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000264 /// Compare two Instructions for equivalence, similar to
265 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000266 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000267 /// Stages are listed in "most significant stage first" order:
268 /// On each stage below, we do comparison between some left and right
269 /// operation parts. If parts are non-equal, we assign parts comparison
270 /// result to the operation comparison result and exit from method.
271 /// Otherwise we proceed to the next stage.
272 /// Stages:
273 /// 1. Operations opcodes. Compared as numbers.
274 /// 2. Number of operands.
275 /// 3. Operation types. Compared with cmpType method.
276 /// 4. Compare operation subclass optional data as stream of bytes:
277 /// just convert it to integers and call cmpNumbers.
278 /// 5. Compare in operation operand types with cmpType in
279 /// most significant operand first order.
280 /// 6. Last stage. Check operations for some specific attributes.
281 /// For example, for Load it would be:
282 /// 6.1.Load: volatile (as boolean flag)
283 /// 6.2.Load: alignment (as integer numbers)
284 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000285 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000286 /// On this stage its better to see the code, since its not more than 10-15
287 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000288 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000289
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000290 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000291 /// Parts to be compared for each comparison stage,
292 /// most significant stage first:
293 /// 1. Address space. As numbers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000295 /// 3. Pointer operand type (using cmpType method).
296 /// 4. Number of operands.
297 /// 5. Compare operands, using cmpValues method.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000298 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
299 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
300 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000301 }
302
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000303 /// cmpType - compares two types,
304 /// defines total ordering among the types set.
305 ///
306 /// Return values:
307 /// 0 if types are equal,
308 /// -1 if Left is less than Right,
309 /// +1 if Left is greater than Right.
310 ///
311 /// Description:
312 /// Comparison is broken onto stages. Like in lexicographical comparison
313 /// stage coming first has higher priority.
314 /// On each explanation stage keep in mind total ordering properties.
315 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000316 /// 0. Before comparison we coerce pointer types of 0 address space to
317 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000318 /// We also don't bother with same type at left and right, so
319 /// just return 0 in this case.
320 ///
321 /// 1. If types are of different kind (different type IDs).
322 /// Return result of type IDs comparison, treating them as numbers.
323 /// 2. If types are vectors or integers, compare Type* values as numbers.
324 /// 3. Types has same ID, so check whether they belongs to the next group:
325 /// * Void
326 /// * Float
327 /// * Double
328 /// * X86_FP80
329 /// * FP128
330 /// * PPC_FP128
331 /// * Label
332 /// * Metadata
333 /// If so - return 0, yes - we can treat these types as equal only because
334 /// their IDs are same.
335 /// 4. If Left and Right are pointers, return result of address space
336 /// comparison (numbers comparison). We can treat pointer types of same
337 /// address space as equal.
338 /// 5. If types are complex.
339 /// Then both Left and Right are to be expanded and their element types will
340 /// be checked with the same way. If we get Res != 0 on some stage, return it.
341 /// Otherwise return 0.
342 /// 6. For all other cases put llvm_unreachable.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000343 int cmpTypes(Type *TyL, Type *TyR) const;
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000344
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000345 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000346
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000347 int cmpAPInts(const APInt &L, const APInt &R) const;
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000348 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000349 int cmpStrings(StringRef L, StringRef R) const;
350 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000351
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000352 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000353 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000354
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000355 /// Assign serial numbers to values from left function, and values from
356 /// right function.
357 /// Explanation:
358 /// Being comparing functions we need to compare values we meet at left and
359 /// right sides.
360 /// Its easy to sort things out for external values. It just should be
361 /// the same value at left and right.
362 /// But for local values (those were introduced inside function body)
363 /// we have to ensure they were introduced at exactly the same place,
364 /// and plays the same role.
365 /// Let's assign serial number to each value when we meet it first time.
366 /// Values that were met at same place will be with same serial numbers.
367 /// In this case it would be good to explain few points about values assigned
368 /// to BBs and other ways of implementation (see below).
369 ///
370 /// 1. Safety of BB reordering.
371 /// It's safe to change the order of BasicBlocks in function.
372 /// Relationship with other functions and serial numbering will not be
373 /// changed in this case.
374 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
375 /// from the entry, and then take each terminator. So it doesn't matter how in
376 /// fact BBs are ordered in function. And since cmpValues are called during
377 /// this walk, the numbering depends only on how BBs located inside the CFG.
378 /// So the answer is - yes. We will get the same numbering.
379 ///
380 /// 2. Impossibility to use dominance properties of values.
381 /// If we compare two instruction operands: first is usage of local
382 /// variable AL from function FL, and second is usage of local variable AR
383 /// from FR, we could compare their origins and check whether they are
384 /// defined at the same place.
385 /// But, we are still not able to compare operands of PHI nodes, since those
386 /// could be operands from further BBs we didn't scan yet.
387 /// So it's impossible to use dominance properties in general.
388 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000389};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000390
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000391class FunctionNode {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000392 AssertingVH<Function> F;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000393
394public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 FunctionNode(Function *F) : F(F) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000396 Function *getFunc() const { return F; }
397 void release() { F = 0; }
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000398 bool operator<(const FunctionNode &RHS) const {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000399 return (FunctionComparator(F, RHS.getFunc()).compare()) == -1;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000400 }
401};
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000402}
403
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000404int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
405 if (L < R) return -1;
406 if (L > R) return 1;
407 return 0;
408}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000409
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000410int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000411 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
412 return Res;
413 if (L.ugt(R)) return 1;
414 if (R.ugt(L)) return -1;
415 return 0;
416}
417
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000418int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000419 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
420 (uint64_t)&R.getSemantics()))
421 return Res;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000422 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000423}
424
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000425int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
426 // Prevent heavy comparison, compare sizes first.
427 if (int Res = cmpNumbers(L.size(), R.size()))
428 return Res;
429
430 // Compare strings lexicographically only when it is necessary: only when
431 // strings are equal in size.
432 return L.compare(R);
433}
434
435int FunctionComparator::cmpAttrs(const AttributeSet L,
436 const AttributeSet R) const {
437 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
438 return Res;
439
440 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
441 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
442 RE = R.end(i);
443 for (; LI != LE && RI != RE; ++LI, ++RI) {
444 Attribute LA = *LI;
445 Attribute RA = *RI;
446 if (LA < RA)
447 return -1;
448 if (RA < LA)
449 return 1;
450 }
451 if (LI != LE)
452 return 1;
453 if (RI != RE)
454 return -1;
455 }
456 return 0;
457}
458
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000459/// Constants comparison:
460/// 1. Check whether type of L constant could be losslessly bitcasted to R
461/// type.
462/// 2. Compare constant contents.
463/// For more details see declaration comments.
464int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
465
466 Type *TyL = L->getType();
467 Type *TyR = R->getType();
468
469 // Check whether types are bitcastable. This part is just re-factored
470 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
471 // we also pack into result which type is "less" for us.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000472 int TypesRes = cmpTypes(TyL, TyR);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000473 if (TypesRes != 0) {
474 // Types are different, but check whether we can bitcast them.
475 if (!TyL->isFirstClassType()) {
476 if (TyR->isFirstClassType())
477 return -1;
478 // Neither TyL nor TyR are values of first class type. Return the result
479 // of comparing the types
480 return TypesRes;
481 }
482 if (!TyR->isFirstClassType()) {
483 if (TyL->isFirstClassType())
484 return 1;
485 return TypesRes;
486 }
487
488 // Vector -> Vector conversions are always lossless if the two vector types
489 // have the same size, otherwise not.
490 unsigned TyLWidth = 0;
491 unsigned TyRWidth = 0;
492
493 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
494 TyLWidth = VecTyL->getBitWidth();
495 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
496 TyRWidth = VecTyR->getBitWidth();
497
498 if (TyLWidth != TyRWidth)
499 return cmpNumbers(TyLWidth, TyRWidth);
500
501 // Zero bit-width means neither TyL nor TyR are vectors.
502 if (!TyLWidth) {
503 PointerType *PTyL = dyn_cast<PointerType>(TyL);
504 PointerType *PTyR = dyn_cast<PointerType>(TyR);
505 if (PTyL && PTyR) {
506 unsigned AddrSpaceL = PTyL->getAddressSpace();
507 unsigned AddrSpaceR = PTyR->getAddressSpace();
508 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
509 return Res;
510 }
511 if (PTyL)
512 return 1;
513 if (PTyR)
514 return -1;
515
516 // TyL and TyR aren't vectors, nor pointers. We don't know how to
517 // bitcast them.
518 return TypesRes;
519 }
520 }
521
522 // OK, types are bitcastable, now check constant contents.
523
524 if (L->isNullValue() && R->isNullValue())
525 return TypesRes;
526 if (L->isNullValue() && !R->isNullValue())
527 return 1;
528 if (!L->isNullValue() && R->isNullValue())
529 return -1;
530
531 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
532 return Res;
533
534 switch (L->getValueID()) {
535 case Value::UndefValueVal: return TypesRes;
536 case Value::ConstantIntVal: {
537 const APInt &LInt = cast<ConstantInt>(L)->getValue();
538 const APInt &RInt = cast<ConstantInt>(R)->getValue();
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000539 return cmpAPInts(LInt, RInt);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000540 }
541 case Value::ConstantFPVal: {
542 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
543 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000544 return cmpAPFloats(LAPF, RAPF);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000545 }
546 case Value::ConstantArrayVal: {
547 const ConstantArray *LA = cast<ConstantArray>(L);
548 const ConstantArray *RA = cast<ConstantArray>(R);
549 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
550 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
551 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
552 return Res;
553 for (uint64_t i = 0; i < NumElementsL; ++i) {
554 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
555 cast<Constant>(RA->getOperand(i))))
556 return Res;
557 }
558 return 0;
559 }
560 case Value::ConstantStructVal: {
561 const ConstantStruct *LS = cast<ConstantStruct>(L);
562 const ConstantStruct *RS = cast<ConstantStruct>(R);
563 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
564 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
565 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
566 return Res;
567 for (unsigned i = 0; i != NumElementsL; ++i) {
568 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
569 cast<Constant>(RS->getOperand(i))))
570 return Res;
571 }
572 return 0;
573 }
574 case Value::ConstantVectorVal: {
575 const ConstantVector *LV = cast<ConstantVector>(L);
576 const ConstantVector *RV = cast<ConstantVector>(R);
577 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
578 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
579 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
580 return Res;
581 for (uint64_t i = 0; i < NumElementsL; ++i) {
582 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
583 cast<Constant>(RV->getOperand(i))))
584 return Res;
585 }
586 return 0;
587 }
588 case Value::ConstantExprVal: {
589 const ConstantExpr *LE = cast<ConstantExpr>(L);
590 const ConstantExpr *RE = cast<ConstantExpr>(R);
591 unsigned NumOperandsL = LE->getNumOperands();
592 unsigned NumOperandsR = RE->getNumOperands();
593 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
594 return Res;
595 for (unsigned i = 0; i < NumOperandsL; ++i) {
596 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
597 cast<Constant>(RE->getOperand(i))))
598 return Res;
599 }
600 return 0;
601 }
602 case Value::FunctionVal:
603 case Value::GlobalVariableVal:
604 case Value::GlobalAliasVal:
605 default: // Unknown constant, cast L and R pointers to numbers and compare.
606 return cmpNumbers((uint64_t)L, (uint64_t)R);
607 }
608}
609
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000610/// cmpType - compares two types,
611/// defines total ordering among the types set.
612/// See method declaration comments for more details.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000613int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000614
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000615 PointerType *PTyL = dyn_cast<PointerType>(TyL);
616 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000617
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000618 const DataLayout &DL = FnL->getParent()->getDataLayout();
619 if (PTyL && PTyL->getAddressSpace() == 0)
620 TyL = DL.getIntPtrType(TyL);
621 if (PTyR && PTyR->getAddressSpace() == 0)
622 TyR = DL.getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000623
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000624 if (TyL == TyR)
625 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000626
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000627 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
628 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000629
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000630 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000631 default:
632 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000633 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000634 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000635 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000636 // TyL == TyR would have returned true earlier.
637 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000638
Nick Lewyckye04dc222009-06-12 08:04:51 +0000639 case Type::VoidTyID:
640 case Type::FloatTyID:
641 case Type::DoubleTyID:
642 case Type::X86_FP80TyID:
643 case Type::FP128TyID:
644 case Type::PPC_FP128TyID:
645 case Type::LabelTyID:
646 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000647 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000648
Nick Lewyckye04dc222009-06-12 08:04:51 +0000649 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000650 assert(PTyL && PTyR && "Both types must be pointers here.");
651 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000652 }
653
654 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000655 StructType *STyL = cast<StructType>(TyL);
656 StructType *STyR = cast<StructType>(TyR);
657 if (STyL->getNumElements() != STyR->getNumElements())
658 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000659
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000660 if (STyL->isPacked() != STyR->isPacked())
661 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000662
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000663 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000664 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000665 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000666 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000667 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000668 }
669
670 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000671 FunctionType *FTyL = cast<FunctionType>(TyL);
672 FunctionType *FTyR = cast<FunctionType>(TyR);
673 if (FTyL->getNumParams() != FTyR->getNumParams())
674 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000675
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000676 if (FTyL->isVarArg() != FTyR->isVarArg())
677 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000678
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000679 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000680 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000681
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000682 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000683 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000684 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000685 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000686 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000687 }
688
Nick Lewycky375efe32010-07-16 06:31:12 +0000689 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000690 ArrayType *ATyL = cast<ArrayType>(TyL);
691 ArrayType *ATyR = cast<ArrayType>(TyR);
692 if (ATyL->getNumElements() != ATyR->getNumElements())
693 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000694 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000695 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000696 }
697}
698
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000699// Determine whether the two operations are the same except that pointer-to-A
700// and pointer-to-B are equivalent. This should be kept in sync with
701// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000702// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000703int FunctionComparator::cmpOperations(const Instruction *L,
704 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000705 // Differences from Instruction::isSameOperationAs:
706 // * replace type comparison with calls to isEquivalentType.
707 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
708 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000709 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
710 return Res;
711
712 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
713 return Res;
714
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000715 if (int Res = cmpTypes(L->getType(), R->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000716 return Res;
717
718 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
719 R->getRawSubclassOptionalData()))
720 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000721
Arnold Schwaighofer6a8c5f62015-05-12 21:42:22 +0000722 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
723 if (int Res = cmpTypes(AI->getAllocatedType(),
724 cast<AllocaInst>(R)->getAllocatedType()))
725 return Res;
726 if (int Res =
727 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
728 return Res;
729 }
730
Nick Lewyckye04dc222009-06-12 08:04:51 +0000731 // We have two instructions of identical opcode and #operands. Check to see
732 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000733 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
734 if (int Res =
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000735 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000736 return Res;
737 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000738
739 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000740 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
741 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
742 return Res;
743 if (int Res =
744 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
745 return Res;
746 if (int Res =
747 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
748 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000749 if (int Res =
750 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
751 return Res;
752 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
753 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000754 }
755 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
756 if (int Res =
757 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
758 return Res;
759 if (int Res =
760 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
761 return Res;
762 if (int Res =
763 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
764 return Res;
765 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
766 }
767 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
768 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
769 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
770 if (int Res = cmpNumbers(CI->getCallingConv(),
771 cast<CallInst>(R)->getCallingConv()))
772 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000773 if (int Res =
774 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
775 return Res;
776 return cmpNumbers(
777 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
778 (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000779 }
780 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
781 if (int Res = cmpNumbers(CI->getCallingConv(),
782 cast<InvokeInst>(R)->getCallingConv()))
783 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000784 if (int Res =
785 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
786 return Res;
787 return cmpNumbers(
788 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
789 (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000790 }
791 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
792 ArrayRef<unsigned> LIndices = IVI->getIndices();
793 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
794 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
795 return Res;
796 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
797 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
798 return Res;
799 }
800 }
801 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
802 ArrayRef<unsigned> LIndices = EVI->getIndices();
803 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
804 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
805 return Res;
806 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
807 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
808 return Res;
809 }
810 }
811 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
812 if (int Res =
813 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
814 return Res;
815 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
816 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000817
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000818 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
819 if (int Res = cmpNumbers(CXI->isVolatile(),
820 cast<AtomicCmpXchgInst>(R)->isVolatile()))
821 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000822 if (int Res = cmpNumbers(CXI->isWeak(),
823 cast<AtomicCmpXchgInst>(R)->isWeak()))
824 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000825 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
826 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
827 return Res;
828 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
829 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
830 return Res;
831 return cmpNumbers(CXI->getSynchScope(),
832 cast<AtomicCmpXchgInst>(R)->getSynchScope());
833 }
834 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
835 if (int Res = cmpNumbers(RMWI->getOperation(),
836 cast<AtomicRMWInst>(R)->getOperation()))
837 return Res;
838 if (int Res = cmpNumbers(RMWI->isVolatile(),
839 cast<AtomicRMWInst>(R)->isVolatile()))
840 return Res;
841 if (int Res = cmpNumbers(RMWI->getOrdering(),
842 cast<AtomicRMWInst>(R)->getOrdering()))
843 return Res;
844 return cmpNumbers(RMWI->getSynchScope(),
845 cast<AtomicRMWInst>(R)->getSynchScope());
846 }
847 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000848}
849
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000850// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000851// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000852int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000853 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000854
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000855 unsigned int ASL = GEPL->getPointerAddressSpace();
856 unsigned int ASR = GEPR->getPointerAddressSpace();
857
858 if (int Res = cmpNumbers(ASL, ASR))
859 return Res;
860
861 // When we have target data, we can reduce the GEP down to the value in bytes
862 // added to the address.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000863 const DataLayout &DL = FnL->getParent()->getDataLayout();
864 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
865 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
866 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
867 GEPR->accumulateConstantOffset(DL, OffsetR))
868 return cmpAPInts(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000869
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000870 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
871 (uint64_t)GEPR->getPointerOperand()->getType()))
872 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000873
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000874 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
875 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000876
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000877 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
878 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
879 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000880 }
881
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000882 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000883}
884
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000885/// Compare two values used by the two functions under pair-wise comparison. If
886/// this is the first time the values are seen, they're added to the mapping so
887/// that we will detect mismatches on next use.
888/// See comments in declaration for more details.
889int FunctionComparator::cmpValues(const Value *L, const Value *R) {
890 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000891 if (L == FnL) {
892 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000893 return 0;
894 return -1;
895 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000896 if (R == FnR) {
897 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000898 return 0;
899 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000900 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000901
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000902 const Constant *ConstL = dyn_cast<Constant>(L);
903 const Constant *ConstR = dyn_cast<Constant>(R);
904 if (ConstL && ConstR) {
905 if (L == R)
906 return 0;
907 return cmpConstants(ConstL, ConstR);
908 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000909
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000910 if (ConstL)
911 return 1;
912 if (ConstR)
913 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000914
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000915 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
916 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
917
918 if (InlineAsmL && InlineAsmR)
919 return cmpNumbers((uint64_t)L, (uint64_t)R);
920 if (InlineAsmL)
921 return 1;
922 if (InlineAsmR)
923 return -1;
924
925 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
926 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
927
928 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000929}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000930// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000931int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
932 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
933 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000934
935 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000936 if (int Res = cmpValues(InstL, InstR))
937 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000938
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000939 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
940 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +0000941
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000942 if (GEPL && !GEPR)
943 return 1;
944 if (GEPR && !GEPL)
945 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000946
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000947 if (GEPL && GEPR) {
948 if (int Res =
949 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
950 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000951 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000952 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000953 } else {
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000954 if (int Res = cmpOperations(InstL, InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000955 return Res;
956 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000957
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000958 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
959 Value *OpL = InstL->getOperand(i);
960 Value *OpR = InstR->getOperand(i);
961 if (int Res = cmpValues(OpL, OpR))
962 return Res;
963 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
964 return Res;
965 // TODO: Already checked in cmpOperation
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000966 if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000967 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000968 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000969 }
970
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000971 ++InstL, ++InstR;
972 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000973
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000974 if (InstL != InstLE && InstR == InstRE)
975 return 1;
976 if (InstL == InstLE && InstR != InstRE)
977 return -1;
978 return 0;
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.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000982int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000983
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000984 sn_mapL.clear();
985 sn_mapR.clear();
986
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000987 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
988 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000989
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000990 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
991 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000992
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000993 if (FnL->hasGC()) {
994 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
995 return Res;
996 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000997
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000998 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
999 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001000
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001001 if (FnL->hasSection()) {
1002 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1003 return Res;
1004 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001005
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001006 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1007 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001008
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001009 // TODO: if it's internal and only used in direct calls, we could handle this
1010 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001011 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1012 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001013
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001014 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001015 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001016
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001017 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001018 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001019
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001020 // Visit the arguments so that they get enumerated in the order they're
1021 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001022 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1023 ArgRI = FnR->arg_begin(),
1024 ArgLE = FnL->arg_end();
1025 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1026 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001027 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001028 }
1029
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001030 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1031 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001032 // functions, then takes each block from each terminator in order. As an
1033 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001034 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001035 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001036
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001037 FnLBBs.push_back(&FnL->getEntryBlock());
1038 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001039
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001040 VisitedBBs.insert(FnLBBs[0]);
1041 while (!FnLBBs.empty()) {
1042 const BasicBlock *BBL = FnLBBs.pop_back_val();
1043 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001044
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001045 if (int Res = cmpValues(BBL, BBR))
1046 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001047
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001048 if (int Res = compare(BBL, BBR))
1049 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001050
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001051 const TerminatorInst *TermL = BBL->getTerminator();
1052 const TerminatorInst *TermR = BBR->getTerminator();
1053
1054 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1055 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
David Blaikie70573dc2014-11-19 07:49:26 +00001056 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001057 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001058
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001059 FnLBBs.push_back(TermL->getSuccessor(i));
1060 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001061 }
1062 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001063 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001064}
1065
Nick Lewycky564fcca2011-01-28 07:36:21 +00001066namespace {
1067
1068/// MergeFunctions finds functions which will generate identical machine code,
1069/// by considering all pointer types to be equivalent. Once identified,
1070/// MergeFunctions will fold them by replacing a call to one to a call to a
1071/// bitcast of the other.
1072///
1073class MergeFunctions : public ModulePass {
1074public:
1075 static char ID;
1076 MergeFunctions()
1077 : ModulePass(ID), HasGlobalAliases(false) {
1078 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1079 }
1080
Craig Topper3e4c6972014-03-05 09:10:37 +00001081 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001082
1083private:
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001084 typedef std::set<FunctionNode> FnTreeType;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001085
1086 /// A work queue of functions that may have been modified and should be
1087 /// analyzed again.
1088 std::vector<WeakVH> Deferred;
1089
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001090 /// Checks the rules of order relation introduced among functions set.
1091 /// Returns true, if sanity check has been passed, and false if failed.
1092 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1093
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001094 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001095 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001096 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001097
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001098 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001099 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001100 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001101
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001102 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001103 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001104 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001105
1106 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1107 /// necessary to make types match.
1108 void replaceDirectCallers(Function *Old, Function *New);
1109
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001110 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1111 /// be converted into a thunk. In either case, it should never be visited
1112 /// again.
1113 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001114
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001115 /// Replace G with a thunk or an alias to F. Deletes G.
1116 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001117
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001118 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1119 /// of G with bitcast(F). Deletes G.
1120 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001121
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001122 /// Replace G with an alias to F. Deletes G.
1123 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001124
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001125 /// The set of all distinct functions. Use the insert() and remove() methods
1126 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001127 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001128
Nick Lewycky564fcca2011-01-28 07:36:21 +00001129 /// Whether or not the target supports global aliases.
1130 bool HasGlobalAliases;
1131};
1132
1133} // end anonymous namespace
1134
1135char MergeFunctions::ID = 0;
1136INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1137
1138ModulePass *llvm::createMergeFunctionsPass() {
1139 return new MergeFunctions();
1140}
1141
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001142bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1143 if (const unsigned Max = NumFunctionsForSanityCheck) {
1144 unsigned TripleNumber = 0;
1145 bool Valid = true;
1146
1147 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1148
1149 unsigned i = 0;
1150 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1151 I != E && i < Max; ++I, ++i) {
1152 unsigned j = i;
1153 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1154 Function *F1 = cast<Function>(*I);
1155 Function *F2 = cast<Function>(*J);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 int Res1 = FunctionComparator(F1, F2).compare();
1157 int Res2 = FunctionComparator(F2, F1).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001158
1159 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1160 if (Res1 != -Res2) {
1161 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1162 << "\n";
1163 F1->dump();
1164 F2->dump();
1165 Valid = false;
1166 }
1167
1168 if (Res1 == 0)
1169 continue;
1170
1171 unsigned k = j;
1172 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1173 ++k, ++K, ++TripleNumber) {
1174 if (K == J)
1175 continue;
1176
1177 Function *F3 = cast<Function>(*K);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001178 int Res3 = FunctionComparator(F1, F3).compare();
1179 int Res4 = FunctionComparator(F2, F3).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001180
1181 bool Transitive = true;
1182
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001183 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001184 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001185 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001186 } else if (Res3 != 0 && Res3 == -Res4) {
1187 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001188 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001189 } else if (Res4 != 0 && -Res3 == Res4) {
1190 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001191 Transitive = Res4 == -Res1;
1192 }
1193
1194 if (!Transitive) {
1195 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1196 << TripleNumber << "\n";
1197 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1198 << Res4 << "\n";
1199 F1->dump();
1200 F2->dump();
1201 F3->dump();
1202 Valid = false;
1203 }
1204 }
1205 }
1206 }
1207
1208 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1209 return Valid;
1210 }
1211 return true;
1212}
1213
Nick Lewycky564fcca2011-01-28 07:36:21 +00001214bool MergeFunctions::runOnModule(Module &M) {
1215 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001216
1217 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1218 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1219 Deferred.push_back(WeakVH(I));
1220 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001221
1222 do {
1223 std::vector<WeakVH> Worklist;
1224 Deferred.swap(Worklist);
1225
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001226 DEBUG(doSanityCheck(Worklist));
1227
Nick Lewycky564fcca2011-01-28 07:36:21 +00001228 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1229 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1230
1231 // Insert only strong functions and merge them. Strong function merging
1232 // always deletes one of them.
1233 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1234 E = Worklist.end(); I != E; ++I) {
1235 if (!*I) continue;
1236 Function *F = cast<Function>(*I);
1237 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1238 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001239 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001240 }
1241 }
1242
1243 // Insert only weak functions and merge them. By doing these second we
1244 // create thunks to the strong function when possible. When two weak
1245 // functions are identical, we create a new strong function with two weak
1246 // weak thunks to it which are identical but not mergable.
1247 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1248 E = Worklist.end(); I != E; ++I) {
1249 if (!*I) continue;
1250 Function *F = cast<Function>(*I);
1251 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1252 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001253 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001254 }
1255 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001256 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001257 } while (!Deferred.empty());
1258
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001259 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001260
1261 return Changed;
1262}
1263
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001264// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001265void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1266 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001267 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1268 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001269 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001270 CallSite CS(U->getUser());
1271 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001272 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001274 }
1275 }
1276}
1277
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001278// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1279void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001280 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1281 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1282 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001283 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001284 return;
1285 }
1286 }
1287
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001288 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001289}
1290
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001291// Helper for writeThunk,
1292// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001293// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001294static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001295 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001296 if (SrcTy->isStructTy()) {
1297 assert(DestTy->isStructTy());
1298 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1299 Value *Result = UndefValue::get(DestTy);
1300 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1301 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +00001302 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +00001303 DestTy->getStructElementType(I));
1304
1305 Result =
Craig Toppere1d12942014-08-27 05:25:25 +00001306 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +00001307 }
1308 return Result;
1309 }
1310 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001311 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1312 return Builder.CreateIntToPtr(V, DestTy);
1313 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1314 return Builder.CreatePtrToInt(V, DestTy);
1315 else
1316 return Builder.CreateBitCast(V, DestTy);
1317}
1318
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001319// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1320// of G with bitcast(F). Deletes G.
1321void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001322 if (!G->mayBeOverridden()) {
1323 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001324 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001325 }
1326
Nick Lewycky71972d42010-09-07 01:42:10 +00001327 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001328 // stop here and delete G. There's no need for a thunk.
1329 if (G->hasLocalLinkage() && G->use_empty()) {
1330 G->eraseFromParent();
1331 return;
1332 }
1333
Nick Lewycky25675ac2009-06-12 15:56:56 +00001334 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1335 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001336 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001337 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001338
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001339 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001340 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001341 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001342 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1343 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001344 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001345 ++i;
1346 }
1347
Jay Foad5bd375a2011-07-15 08:37:34 +00001348 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001349 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001350 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001351 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001352 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001353 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001354 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001355 }
1356
1357 NewG->copyAttributesFrom(G);
1358 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001359 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001360 G->replaceAllUsesWith(NewG);
1361 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001362
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001363 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001364 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001365}
1366
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001367// Replace G with an alias to F and delete G.
1368void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001369 PointerType *PTy = G->getType();
David Blaikief64246b2015-04-29 21:22:39 +00001370 auto *GA = GlobalAlias::create(PTy, G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001371 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1372 GA->takeName(G);
1373 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001374 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001375 G->replaceAllUsesWith(GA);
1376 G->eraseFromParent();
1377
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001378 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001379 ++NumAliasesWritten;
1380}
1381
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001382// Merge two equivalent functions. Upon completion, Function G is deleted.
1383void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001384 if (F->mayBeOverridden()) {
1385 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001386
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001387 if (HasGlobalAliases) {
1388 // Make them both thunks to the same internal function.
1389 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1390 F->getParent());
1391 H->copyAttributesFrom(F);
1392 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001393 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001394 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001395
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001396 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001397
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001398 writeAlias(F, G);
1399 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001400
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001401 F->setAlignment(MaxAlignment);
1402 F->setLinkage(GlobalValue::PrivateLinkage);
1403 } else {
1404 // We can't merge them. Instead, pick one and update all direct callers
1405 // to call it and hope that we improve the instruction cache hit rate.
1406 replaceDirectCallers(G, F);
1407 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001408
1409 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001410 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001411 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001412 }
1413
Nick Lewyckye04dc222009-06-12 08:04:51 +00001414 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001415}
1416
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001417// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001418// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001419bool MergeFunctions::insert(Function *NewFunction) {
1420 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001421 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001422
Nick Lewycky292e78c2011-02-09 06:32:02 +00001423 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001424 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001425 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001426 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001427
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001428 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001429
Matt Arsenault517d84e2013-10-01 18:05:30 +00001430 // Don't merge tiny functions, since it can just end up making the function
1431 // larger.
1432 // FIXME: Should still merge them if they are unnamed_addr and produce an
1433 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001434 if (NewFunction->size() == 1) {
1435 if (NewFunction->front().size() <= 2) {
1436 DEBUG(dbgs() << NewFunction->getName()
1437 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001438 return false;
1439 }
1440 }
1441
Nick Lewycky00959372010-09-05 08:22:49 +00001442 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001443 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001444
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001445 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1446 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001447
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001448 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001449 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001450 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001451}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001452
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001453// Remove a function from FnTree. If it was already in FnTree, add
1454// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001455void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001456 // We need to make sure we remove F, not a function "equal" to F per the
1457 // function equality comparator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001458 FnTreeType::iterator found = FnTree.find(FunctionNode(F));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001459 size_t Erased = 0;
1460 if (found != FnTree.end() && found->getFunc() == F) {
1461 Erased = 1;
1462 FnTree.erase(found);
1463 }
1464
1465 if (Erased) {
1466 DEBUG(dbgs() << "Removed " << F->getName()
1467 << " from set and deferred it.\n");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001468 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001469 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001470}
Nick Lewycky00959372010-09-05 08:22:49 +00001471
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001472// For each instruction used by the value, remove() the function that contains
1473// the instruction. This should happen right before a call to RAUW.
1474void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001475 std::vector<Value *> Worklist;
1476 Worklist.push_back(V);
1477 while (!Worklist.empty()) {
1478 Value *V = Worklist.back();
1479 Worklist.pop_back();
1480
Chandler Carruthcdf47882014-03-09 03:16:01 +00001481 for (User *U : V->users()) {
1482 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001483 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001484 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001485 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001486 } else if (Constant *C = dyn_cast<Constant>(U)) {
1487 for (User *UU : C->users())
1488 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001489 }
Nick Lewycky00959372010-09-05 08:22:49 +00001490 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001491 }
Nick Lewycky00959372010-09-05 08:22:49 +00001492}