blob: 27c1dd86590438974a107a04be14cfabd5b9ec66 [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:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000130 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000131 const Function *F2)
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000132 : FnL(F1), FnR(F2), DL(DL) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000133
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000134 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000135 int compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000136
137private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000138 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000139 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000140
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000141 /// Constants comparison.
142 /// Its analog to lexicographical comparison between hypothetical numbers
143 /// of next format:
144 /// <bitcastability-trait><raw-bit-contents>
145 ///
146 /// 1. Bitcastability.
147 /// Check whether L's type could be losslessly bitcasted to R's type.
148 /// On this stage method, in case when lossless bitcast is not possible
149 /// method returns -1 or 1, thus also defining which type is greater in
150 /// context of bitcastability.
151 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
152 /// to the contents comparison.
153 /// If types differ, remember types comparison result and check
154 /// whether we still can bitcast types.
155 /// Stage 1: Types that satisfies isFirstClassType conditions are always
156 /// greater then others.
157 /// Stage 2: Vector is greater then non-vector.
158 /// If both types are vectors, then vector with greater bitwidth is
159 /// greater.
160 /// If both types are vectors with the same bitwidth, then types
161 /// are bitcastable, and we can skip other stages, and go to contents
162 /// comparison.
163 /// Stage 3: Pointer types are greater than non-pointers. If both types are
164 /// pointers of the same address space - go to contents comparison.
165 /// Different address spaces: pointer with greater address space is
166 /// greater.
167 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
168 /// We don't know how to bitcast them. So, we better don't do it,
169 /// and return types comparison result (so it determines the
170 /// relationship among constants we don't know how to bitcast).
171 ///
172 /// Just for clearance, let's see how the set of constants could look
173 /// on single dimension axis:
174 ///
175 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
176 /// Where: NFCT - Not a FirstClassType
177 /// FCT - FirstClassTyp:
178 ///
179 /// 2. Compare raw contents.
180 /// It ignores types on this stage and only compares bits from L and R.
181 /// Returns 0, if L and R has equivalent contents.
182 /// -1 or 1 if values are different.
183 /// Pretty trivial:
184 /// 2.1. If contents are numbers, compare numbers.
185 /// Ints with greater bitwidth are greater. Ints with same bitwidths
186 /// compared by their contents.
187 /// 2.2. "And so on". Just to avoid discrepancies with comments
188 /// perhaps it would be better to read the implementation itself.
189 /// 3. And again about overall picture. Let's look back at how the ordered set
190 /// of constants will look like:
191 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
192 ///
193 /// Now look, what could be inside [FCT, "others"], for example:
194 /// [FCT, "others"] =
195 /// [
196 /// [double 0.1], [double 1.23],
197 /// [i32 1], [i32 2],
198 /// { double 1.0 }, ; StructTyID, NumElements = 1
199 /// { i32 1 }, ; StructTyID, NumElements = 1
200 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
201 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
202 /// ]
203 ///
204 /// Let's explain the order. Float numbers will be less than integers, just
205 /// because of cmpType terms: FloatTyID < IntegerTyID.
206 /// Floats (with same fltSemantics) are sorted according to their value.
207 /// Then you can see integers, and they are, like a floats,
208 /// could be easy sorted among each others.
209 /// The structures. Structures are grouped at the tail, again because of their
210 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
211 /// Structures with greater number of elements are greater. Structures with
212 /// greater elements going first are greater.
213 /// The same logic with vectors, arrays and other possible complex types.
214 ///
215 /// Bitcastable constants.
216 /// Let's assume, that some constant, belongs to some group of
217 /// "so-called-equal" values with different types, and at the same time
218 /// belongs to another group of constants with equal types
219 /// and "really" equal values.
220 ///
221 /// Now, prove that this is impossible:
222 ///
223 /// If constant A with type TyA is bitcastable to B with type TyB, then:
224 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
225 /// those should be vectors (if TyA is vector), pointers
226 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
227 /// be equal to TyB.
228 /// 2. All constants with non-equal, but bitcastable types to TyA, are
229 /// bitcastable to B.
230 /// Once again, just because we allow it to vectors and pointers only.
231 /// This statement could be expanded as below:
232 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
233 /// vector B, and thus bitcastable to B as well.
234 /// 2.2. All pointers of the same address space, no matter what they point to,
235 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
236 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
237 /// QED.
238 ///
239 /// In another words, for pointers and vectors, we ignore top-level type and
240 /// look at their particular properties (bit-width for vectors, and
241 /// address space for pointers).
242 /// If these properties are equal - compare their contents.
243 int cmpConstants(const Constant *L, const Constant *R);
244
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000245 /// Assign or look up previously assigned numbers for the two values, and
246 /// return whether the numbers are equal. Numbers are assigned in the order
247 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000248 /// Comparison order:
249 /// Stage 0: Value that is function itself is always greater then others.
250 /// If left and right values are references to their functions, then
251 /// they are equal.
252 /// Stage 1: Constants are greater than non-constants.
253 /// If both left and right are constants, then the result of
254 /// cmpConstants is used as cmpValues result.
255 /// Stage 2: InlineAsm instances are greater than others. If both left and
256 /// right are InlineAsm instances, InlineAsm* pointers casted to
257 /// integers and compared as numbers.
258 /// Stage 3: For all other cases we compare order we meet these values in
259 /// their functions. If right value was met first during scanning,
260 /// then left value is greater.
261 /// In another words, we compare serial numbers, for more details
262 /// see comments for sn_mapL and sn_mapR.
263 int cmpValues(const Value *L, const Value *R);
264
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000265 /// Compare two Instructions for equivalence, similar to
266 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000267 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000268 /// Stages are listed in "most significant stage first" order:
269 /// On each stage below, we do comparison between some left and right
270 /// operation parts. If parts are non-equal, we assign parts comparison
271 /// result to the operation comparison result and exit from method.
272 /// Otherwise we proceed to the next stage.
273 /// Stages:
274 /// 1. Operations opcodes. Compared as numbers.
275 /// 2. Number of operands.
276 /// 3. Operation types. Compared with cmpType method.
277 /// 4. Compare operation subclass optional data as stream of bytes:
278 /// just convert it to integers and call cmpNumbers.
279 /// 5. Compare in operation operand types with cmpType in
280 /// most significant operand first order.
281 /// 6. Last stage. Check operations for some specific attributes.
282 /// For example, for Load it would be:
283 /// 6.1.Load: volatile (as boolean flag)
284 /// 6.2.Load: alignment (as integer numbers)
285 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000286 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000287 /// On this stage its better to see the code, since its not more than 10-15
288 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000289 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000290
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000291 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000292 /// Parts to be compared for each comparison stage,
293 /// most significant stage first:
294 /// 1. Address space. As numbers.
295 /// 2. Constant offset, (if "DataLayout *DL" field is not NULL,
296 /// using GEPOperator::accumulateConstantOffset method).
297 /// 3. Pointer operand type (using cmpType method).
298 /// 4. Number of operands.
299 /// 5. Compare operands, using cmpValues method.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000300 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
301 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
302 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000303 }
304
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000305 /// cmpType - compares two types,
306 /// defines total ordering among the types set.
307 ///
308 /// Return values:
309 /// 0 if types are equal,
310 /// -1 if Left is less than Right,
311 /// +1 if Left is greater than Right.
312 ///
313 /// Description:
314 /// Comparison is broken onto stages. Like in lexicographical comparison
315 /// stage coming first has higher priority.
316 /// On each explanation stage keep in mind total ordering properties.
317 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000318 /// 0. Before comparison we coerce pointer types of 0 address space to
319 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000320 /// We also don't bother with same type at left and right, so
321 /// just return 0 in this case.
322 ///
323 /// 1. If types are of different kind (different type IDs).
324 /// Return result of type IDs comparison, treating them as numbers.
325 /// 2. If types are vectors or integers, compare Type* values as numbers.
326 /// 3. Types has same ID, so check whether they belongs to the next group:
327 /// * Void
328 /// * Float
329 /// * Double
330 /// * X86_FP80
331 /// * FP128
332 /// * PPC_FP128
333 /// * Label
334 /// * Metadata
335 /// If so - return 0, yes - we can treat these types as equal only because
336 /// their IDs are same.
337 /// 4. If Left and Right are pointers, return result of address space
338 /// comparison (numbers comparison). We can treat pointer types of same
339 /// address space as equal.
340 /// 5. If types are complex.
341 /// Then both Left and Right are to be expanded and their element types will
342 /// be checked with the same way. If we get Res != 0 on some stage, return it.
343 /// Otherwise return 0.
344 /// 6. For all other cases put llvm_unreachable.
345 int cmpType(Type *TyL, Type *TyR) const;
346
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000347 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000348
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000349 int cmpAPInt(const APInt &L, const APInt &R) const;
350 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000351 int cmpStrings(StringRef L, StringRef R) const;
352 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000353
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000354 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000355 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000356
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000357 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000358
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000359 /// Assign serial numbers to values from left function, and values from
360 /// right function.
361 /// Explanation:
362 /// Being comparing functions we need to compare values we meet at left and
363 /// right sides.
364 /// Its easy to sort things out for external values. It just should be
365 /// the same value at left and right.
366 /// But for local values (those were introduced inside function body)
367 /// we have to ensure they were introduced at exactly the same place,
368 /// and plays the same role.
369 /// Let's assign serial number to each value when we meet it first time.
370 /// Values that were met at same place will be with same serial numbers.
371 /// In this case it would be good to explain few points about values assigned
372 /// to BBs and other ways of implementation (see below).
373 ///
374 /// 1. Safety of BB reordering.
375 /// It's safe to change the order of BasicBlocks in function.
376 /// Relationship with other functions and serial numbering will not be
377 /// changed in this case.
378 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
379 /// from the entry, and then take each terminator. So it doesn't matter how in
380 /// fact BBs are ordered in function. And since cmpValues are called during
381 /// this walk, the numbering depends only on how BBs located inside the CFG.
382 /// So the answer is - yes. We will get the same numbering.
383 ///
384 /// 2. Impossibility to use dominance properties of values.
385 /// If we compare two instruction operands: first is usage of local
386 /// variable AL from function FL, and second is usage of local variable AR
387 /// from FR, we could compare their origins and check whether they are
388 /// defined at the same place.
389 /// But, we are still not able to compare operands of PHI nodes, since those
390 /// could be operands from further BBs we didn't scan yet.
391 /// So it's impossible to use dominance properties in general.
392 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000393};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000394
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000395class FunctionPtr {
396 AssertingVH<Function> F;
397 const DataLayout *DL;
398
399public:
400 FunctionPtr(Function *F, const DataLayout *DL) : F(F), DL(DL) {}
401 Function *getFunc() const { return F; }
402 void release() { F = 0; }
403 bool operator<(const FunctionPtr &RHS) const {
404 return (FunctionComparator(DL, F, RHS.getFunc()).compare()) == -1;
405 }
406};
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000407}
408
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000409int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
410 if (L < R) return -1;
411 if (L > R) return 1;
412 return 0;
413}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000414
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000415int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
416 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
417 return Res;
418 if (L.ugt(R)) return 1;
419 if (R.ugt(L)) return -1;
420 return 0;
421}
422
423int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
424 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
425 (uint64_t)&R.getSemantics()))
426 return Res;
427 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
428}
429
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000430int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
431 // Prevent heavy comparison, compare sizes first.
432 if (int Res = cmpNumbers(L.size(), R.size()))
433 return Res;
434
435 // Compare strings lexicographically only when it is necessary: only when
436 // strings are equal in size.
437 return L.compare(R);
438}
439
440int FunctionComparator::cmpAttrs(const AttributeSet L,
441 const AttributeSet R) const {
442 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
443 return Res;
444
445 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
446 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
447 RE = R.end(i);
448 for (; LI != LE && RI != RE; ++LI, ++RI) {
449 Attribute LA = *LI;
450 Attribute RA = *RI;
451 if (LA < RA)
452 return -1;
453 if (RA < LA)
454 return 1;
455 }
456 if (LI != LE)
457 return 1;
458 if (RI != RE)
459 return -1;
460 }
461 return 0;
462}
463
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000464/// Constants comparison:
465/// 1. Check whether type of L constant could be losslessly bitcasted to R
466/// type.
467/// 2. Compare constant contents.
468/// For more details see declaration comments.
469int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
470
471 Type *TyL = L->getType();
472 Type *TyR = R->getType();
473
474 // Check whether types are bitcastable. This part is just re-factored
475 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
476 // we also pack into result which type is "less" for us.
477 int TypesRes = cmpType(TyL, TyR);
478 if (TypesRes != 0) {
479 // Types are different, but check whether we can bitcast them.
480 if (!TyL->isFirstClassType()) {
481 if (TyR->isFirstClassType())
482 return -1;
483 // Neither TyL nor TyR are values of first class type. Return the result
484 // of comparing the types
485 return TypesRes;
486 }
487 if (!TyR->isFirstClassType()) {
488 if (TyL->isFirstClassType())
489 return 1;
490 return TypesRes;
491 }
492
493 // Vector -> Vector conversions are always lossless if the two vector types
494 // have the same size, otherwise not.
495 unsigned TyLWidth = 0;
496 unsigned TyRWidth = 0;
497
498 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
499 TyLWidth = VecTyL->getBitWidth();
500 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
501 TyRWidth = VecTyR->getBitWidth();
502
503 if (TyLWidth != TyRWidth)
504 return cmpNumbers(TyLWidth, TyRWidth);
505
506 // Zero bit-width means neither TyL nor TyR are vectors.
507 if (!TyLWidth) {
508 PointerType *PTyL = dyn_cast<PointerType>(TyL);
509 PointerType *PTyR = dyn_cast<PointerType>(TyR);
510 if (PTyL && PTyR) {
511 unsigned AddrSpaceL = PTyL->getAddressSpace();
512 unsigned AddrSpaceR = PTyR->getAddressSpace();
513 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
514 return Res;
515 }
516 if (PTyL)
517 return 1;
518 if (PTyR)
519 return -1;
520
521 // TyL and TyR aren't vectors, nor pointers. We don't know how to
522 // bitcast them.
523 return TypesRes;
524 }
525 }
526
527 // OK, types are bitcastable, now check constant contents.
528
529 if (L->isNullValue() && R->isNullValue())
530 return TypesRes;
531 if (L->isNullValue() && !R->isNullValue())
532 return 1;
533 if (!L->isNullValue() && R->isNullValue())
534 return -1;
535
536 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
537 return Res;
538
539 switch (L->getValueID()) {
540 case Value::UndefValueVal: return TypesRes;
541 case Value::ConstantIntVal: {
542 const APInt &LInt = cast<ConstantInt>(L)->getValue();
543 const APInt &RInt = cast<ConstantInt>(R)->getValue();
544 return cmpAPInt(LInt, RInt);
545 }
546 case Value::ConstantFPVal: {
547 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
548 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
549 return cmpAPFloat(LAPF, RAPF);
550 }
551 case Value::ConstantArrayVal: {
552 const ConstantArray *LA = cast<ConstantArray>(L);
553 const ConstantArray *RA = cast<ConstantArray>(R);
554 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
555 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
556 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
557 return Res;
558 for (uint64_t i = 0; i < NumElementsL; ++i) {
559 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
560 cast<Constant>(RA->getOperand(i))))
561 return Res;
562 }
563 return 0;
564 }
565 case Value::ConstantStructVal: {
566 const ConstantStruct *LS = cast<ConstantStruct>(L);
567 const ConstantStruct *RS = cast<ConstantStruct>(R);
568 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
569 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
570 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
571 return Res;
572 for (unsigned i = 0; i != NumElementsL; ++i) {
573 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
574 cast<Constant>(RS->getOperand(i))))
575 return Res;
576 }
577 return 0;
578 }
579 case Value::ConstantVectorVal: {
580 const ConstantVector *LV = cast<ConstantVector>(L);
581 const ConstantVector *RV = cast<ConstantVector>(R);
582 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
583 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
584 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
585 return Res;
586 for (uint64_t i = 0; i < NumElementsL; ++i) {
587 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
588 cast<Constant>(RV->getOperand(i))))
589 return Res;
590 }
591 return 0;
592 }
593 case Value::ConstantExprVal: {
594 const ConstantExpr *LE = cast<ConstantExpr>(L);
595 const ConstantExpr *RE = cast<ConstantExpr>(R);
596 unsigned NumOperandsL = LE->getNumOperands();
597 unsigned NumOperandsR = RE->getNumOperands();
598 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
599 return Res;
600 for (unsigned i = 0; i < NumOperandsL; ++i) {
601 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
602 cast<Constant>(RE->getOperand(i))))
603 return Res;
604 }
605 return 0;
606 }
607 case Value::FunctionVal:
608 case Value::GlobalVariableVal:
609 case Value::GlobalAliasVal:
610 default: // Unknown constant, cast L and R pointers to numbers and compare.
611 return cmpNumbers((uint64_t)L, (uint64_t)R);
612 }
613}
614
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000615/// cmpType - compares two types,
616/// defines total ordering among the types set.
617/// See method declaration comments for more details.
618int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
619
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000620 PointerType *PTyL = dyn_cast<PointerType>(TyL);
621 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000622
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000623 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000624 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
625 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000626 }
627
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000628 if (TyL == TyR)
629 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000630
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000631 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
632 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000633
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000634 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000635 default:
636 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000637 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000638 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000639 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000640 // TyL == TyR would have returned true earlier.
641 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000642
Nick Lewyckye04dc222009-06-12 08:04:51 +0000643 case Type::VoidTyID:
644 case Type::FloatTyID:
645 case Type::DoubleTyID:
646 case Type::X86_FP80TyID:
647 case Type::FP128TyID:
648 case Type::PPC_FP128TyID:
649 case Type::LabelTyID:
650 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000651 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000652
Nick Lewyckye04dc222009-06-12 08:04:51 +0000653 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000654 assert(PTyL && PTyR && "Both types must be pointers here.");
655 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000656 }
657
658 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000659 StructType *STyL = cast<StructType>(TyL);
660 StructType *STyR = cast<StructType>(TyR);
661 if (STyL->getNumElements() != STyR->getNumElements())
662 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000663
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000664 if (STyL->isPacked() != STyR->isPacked())
665 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000666
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000667 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
668 if (int Res = cmpType(STyL->getElementType(i),
669 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000670 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000671 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000672 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000673 }
674
675 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000676 FunctionType *FTyL = cast<FunctionType>(TyL);
677 FunctionType *FTyR = cast<FunctionType>(TyR);
678 if (FTyL->getNumParams() != FTyR->getNumParams())
679 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000680
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000681 if (FTyL->isVarArg() != FTyR->isVarArg())
682 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000683
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000684 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000685 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000686
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000687 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
688 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000689 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000690 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000691 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000692 }
693
Nick Lewycky375efe32010-07-16 06:31:12 +0000694 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000695 ArrayType *ATyL = cast<ArrayType>(TyL);
696 ArrayType *ATyR = cast<ArrayType>(TyR);
697 if (ATyL->getNumElements() != ATyR->getNumElements())
698 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
699 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000700 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000701 }
702}
703
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000704// Determine whether the two operations are the same except that pointer-to-A
705// and pointer-to-B are equivalent. This should be kept in sync with
706// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000707// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000708int FunctionComparator::cmpOperations(const Instruction *L,
709 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000710 // Differences from Instruction::isSameOperationAs:
711 // * replace type comparison with calls to isEquivalentType.
712 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
713 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000714 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
715 return Res;
716
717 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
718 return Res;
719
720 if (int Res = cmpType(L->getType(), R->getType()))
721 return Res;
722
723 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
724 R->getRawSubclassOptionalData()))
725 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000726
727 // We have two instructions of identical opcode and #operands. Check to see
728 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000729 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
730 if (int Res =
731 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
732 return Res;
733 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000734
735 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000736 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
737 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
738 return Res;
739 if (int Res =
740 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
741 return Res;
742 if (int Res =
743 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
744 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000745 if (int Res =
746 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
747 return Res;
748 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
749 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000750 }
751 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
752 if (int Res =
753 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
754 return Res;
755 if (int Res =
756 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
757 return Res;
758 if (int Res =
759 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
760 return Res;
761 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
762 }
763 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
764 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
765 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
766 if (int Res = cmpNumbers(CI->getCallingConv(),
767 cast<CallInst>(R)->getCallingConv()))
768 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000769 if (int Res =
770 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
771 return Res;
772 return cmpNumbers(
773 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
774 (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000775 }
776 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
777 if (int Res = cmpNumbers(CI->getCallingConv(),
778 cast<InvokeInst>(R)->getCallingConv()))
779 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000780 if (int Res =
781 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
782 return Res;
783 return cmpNumbers(
784 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
785 (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000786 }
787 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
788 ArrayRef<unsigned> LIndices = IVI->getIndices();
789 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
790 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
791 return Res;
792 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
793 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
794 return Res;
795 }
796 }
797 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
798 ArrayRef<unsigned> LIndices = EVI->getIndices();
799 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
800 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
801 return Res;
802 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
803 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
804 return Res;
805 }
806 }
807 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
808 if (int Res =
809 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
810 return Res;
811 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
812 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000813
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000814 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
815 if (int Res = cmpNumbers(CXI->isVolatile(),
816 cast<AtomicCmpXchgInst>(R)->isVolatile()))
817 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000818 if (int Res = cmpNumbers(CXI->isWeak(),
819 cast<AtomicCmpXchgInst>(R)->isWeak()))
820 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000821 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
822 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
823 return Res;
824 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
825 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
826 return Res;
827 return cmpNumbers(CXI->getSynchScope(),
828 cast<AtomicCmpXchgInst>(R)->getSynchScope());
829 }
830 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
831 if (int Res = cmpNumbers(RMWI->getOperation(),
832 cast<AtomicRMWInst>(R)->getOperation()))
833 return Res;
834 if (int Res = cmpNumbers(RMWI->isVolatile(),
835 cast<AtomicRMWInst>(R)->isVolatile()))
836 return Res;
837 if (int Res = cmpNumbers(RMWI->getOrdering(),
838 cast<AtomicRMWInst>(R)->getOrdering()))
839 return Res;
840 return cmpNumbers(RMWI->getSynchScope(),
841 cast<AtomicRMWInst>(R)->getSynchScope());
842 }
843 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000844}
845
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000846// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000847// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000848int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000849 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000850
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000851 unsigned int ASL = GEPL->getPointerAddressSpace();
852 unsigned int ASR = GEPR->getPointerAddressSpace();
853
854 if (int Res = cmpNumbers(ASL, ASR))
855 return Res;
856
857 // When we have target data, we can reduce the GEP down to the value in bytes
858 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000859 if (DL) {
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000860 unsigned BitWidth = DL->getPointerSizeInBits(ASL);
861 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
862 if (GEPL->accumulateConstantOffset(*DL, OffsetL) &&
863 GEPR->accumulateConstantOffset(*DL, OffsetR))
864 return cmpAPInt(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000865 }
866
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000867 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
868 (uint64_t)GEPR->getPointerOperand()->getType()))
869 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000870
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000871 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
872 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000873
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000874 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
875 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
876 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000877 }
878
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000879 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000880}
881
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000882/// Compare two values used by the two functions under pair-wise comparison. If
883/// this is the first time the values are seen, they're added to the mapping so
884/// that we will detect mismatches on next use.
885/// See comments in declaration for more details.
886int FunctionComparator::cmpValues(const Value *L, const Value *R) {
887 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000888 if (L == FnL) {
889 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000890 return 0;
891 return -1;
892 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000893 if (R == FnR) {
894 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000895 return 0;
896 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000897 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000898
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000899 const Constant *ConstL = dyn_cast<Constant>(L);
900 const Constant *ConstR = dyn_cast<Constant>(R);
901 if (ConstL && ConstR) {
902 if (L == R)
903 return 0;
904 return cmpConstants(ConstL, ConstR);
905 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000906
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000907 if (ConstL)
908 return 1;
909 if (ConstR)
910 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000911
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000912 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
913 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
914
915 if (InlineAsmL && InlineAsmR)
916 return cmpNumbers((uint64_t)L, (uint64_t)R);
917 if (InlineAsmL)
918 return 1;
919 if (InlineAsmR)
920 return -1;
921
922 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
923 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
924
925 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000926}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000927// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000928int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
929 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
930 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000931
932 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000933 if (int Res = cmpValues(InstL, InstR))
934 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000935
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000936 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
937 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +0000938
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000939 if (GEPL && !GEPR)
940 return 1;
941 if (GEPR && !GEPL)
942 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000943
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000944 if (GEPL && GEPR) {
945 if (int Res =
946 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
947 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000948 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000949 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000950 } else {
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000951 if (int Res = cmpOperations(InstL, InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000952 return Res;
953 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000954
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000955 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
956 Value *OpL = InstL->getOperand(i);
957 Value *OpR = InstR->getOperand(i);
958 if (int Res = cmpValues(OpL, OpR))
959 return Res;
960 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
961 return Res;
962 // TODO: Already checked in cmpOperation
963 if (int Res = cmpType(OpL->getType(), OpR->getType()))
964 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000965 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000966 }
967
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000968 ++InstL, ++InstR;
969 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000970
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000971 if (InstL != InstLE && InstR == InstRE)
972 return 1;
973 if (InstL == InstLE && InstR != InstRE)
974 return -1;
975 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000976}
977
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000978// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000979int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000980
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000981 sn_mapL.clear();
982 sn_mapR.clear();
983
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000984 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
985 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000986
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000987 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
988 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000989
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000990 if (FnL->hasGC()) {
991 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
992 return Res;
993 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000994
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000995 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
996 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000997
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000998 if (FnL->hasSection()) {
999 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1000 return Res;
1001 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001002
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001003 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1004 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001005
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001006 // TODO: if it's internal and only used in direct calls, we could handle this
1007 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001008 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1009 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001010
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001011 if (int Res = cmpType(FnL->getFunctionType(), FnR->getFunctionType()))
1012 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001013
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001014 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001015 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001016
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001017 // Visit the arguments so that they get enumerated in the order they're
1018 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001019 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1020 ArgRI = FnR->arg_begin(),
1021 ArgLE = FnL->arg_end();
1022 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1023 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001024 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001025 }
1026
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001027 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1028 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001029 // functions, then takes each block from each terminator in order. As an
1030 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001031 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001032 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001033
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001034 FnLBBs.push_back(&FnL->getEntryBlock());
1035 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001036
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001037 VisitedBBs.insert(FnLBBs[0]);
1038 while (!FnLBBs.empty()) {
1039 const BasicBlock *BBL = FnLBBs.pop_back_val();
1040 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001041
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001042 if (int Res = cmpValues(BBL, BBR))
1043 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001044
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001045 if (int Res = compare(BBL, BBR))
1046 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001047
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001048 const TerminatorInst *TermL = BBL->getTerminator();
1049 const TerminatorInst *TermR = BBR->getTerminator();
1050
1051 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1052 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1053 if (!VisitedBBs.insert(TermL->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001054 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001055
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001056 FnLBBs.push_back(TermL->getSuccessor(i));
1057 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001058 }
1059 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001060 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001061}
1062
Nick Lewycky564fcca2011-01-28 07:36:21 +00001063namespace {
1064
1065/// MergeFunctions finds functions which will generate identical machine code,
1066/// by considering all pointer types to be equivalent. Once identified,
1067/// MergeFunctions will fold them by replacing a call to one to a call to a
1068/// bitcast of the other.
1069///
1070class MergeFunctions : public ModulePass {
1071public:
1072 static char ID;
1073 MergeFunctions()
1074 : ModulePass(ID), HasGlobalAliases(false) {
1075 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1076 }
1077
Craig Topper3e4c6972014-03-05 09:10:37 +00001078 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001079
1080private:
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001081 typedef std::set<FunctionPtr> FnTreeType;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001082
1083 /// A work queue of functions that may have been modified and should be
1084 /// analyzed again.
1085 std::vector<WeakVH> Deferred;
1086
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001087 /// Checks the rules of order relation introduced among functions set.
1088 /// Returns true, if sanity check has been passed, and false if failed.
1089 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1090
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001091 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001092 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001093 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001094
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001095 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001096 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001097 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001098
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001099 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001100 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001101 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001102
1103 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1104 /// necessary to make types match.
1105 void replaceDirectCallers(Function *Old, Function *New);
1106
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001107 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1108 /// be converted into a thunk. In either case, it should never be visited
1109 /// again.
1110 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001111
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001112 /// Replace G with a thunk or an alias to F. Deletes G.
1113 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001114
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001115 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1116 /// of G with bitcast(F). Deletes G.
1117 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001118
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001119 /// Replace G with an alias to F. Deletes G.
1120 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001121
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001122 /// The set of all distinct functions. Use the insert() and remove() methods
1123 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001124 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001125
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001126 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001127 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001128
1129 /// 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);
1156 int Res1 = FunctionComparator(DL, F1, F2).compare();
1157 int Res2 = FunctionComparator(DL, F2, F1).compare();
1158
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);
1178 int Res3 = FunctionComparator(DL, F1, F3).compare();
1179 int Res4 = FunctionComparator(DL, F2, F3).compare();
1180
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;
Rafael Espindola93512512014-02-25 17:30:31 +00001216 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001217 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001218
1219 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1220 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1221 Deferred.push_back(WeakVH(I));
1222 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001223
1224 do {
1225 std::vector<WeakVH> Worklist;
1226 Deferred.swap(Worklist);
1227
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001228 DEBUG(doSanityCheck(Worklist));
1229
Nick Lewycky564fcca2011-01-28 07:36:21 +00001230 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1231 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1232
1233 // Insert only strong functions and merge them. Strong function merging
1234 // always deletes one of them.
1235 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1236 E = Worklist.end(); I != E; ++I) {
1237 if (!*I) continue;
1238 Function *F = cast<Function>(*I);
1239 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1240 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001241 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001242 }
1243 }
1244
1245 // Insert only weak functions and merge them. By doing these second we
1246 // create thunks to the strong function when possible. When two weak
1247 // functions are identical, we create a new strong function with two weak
1248 // weak thunks to it which are identical but not mergable.
1249 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1250 E = Worklist.end(); I != E; ++I) {
1251 if (!*I) continue;
1252 Function *F = cast<Function>(*I);
1253 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1254 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001255 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001256 }
1257 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001258 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001259 } while (!Deferred.empty());
1260
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001261 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001262
1263 return Changed;
1264}
1265
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001266// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001267void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1268 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001269 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1270 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001271 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001272 CallSite CS(U->getUser());
1273 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001274 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001275 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001276 }
1277 }
1278}
1279
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001280// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1281void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001282 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1283 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1284 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001285 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001286 return;
1287 }
1288 }
1289
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001290 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001291}
1292
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001293// Helper for writeThunk,
1294// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001295// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001296static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001297 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001298 if (SrcTy->isStructTy()) {
1299 assert(DestTy->isStructTy());
1300 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1301 Value *Result = UndefValue::get(DestTy);
1302 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1303 Value *Element = createCast(
1304 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1305 DestTy->getStructElementType(I));
1306
1307 Result =
1308 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1309 }
1310 return Result;
1311 }
1312 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001313 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1314 return Builder.CreateIntToPtr(V, DestTy);
1315 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1316 return Builder.CreatePtrToInt(V, DestTy);
1317 else
1318 return Builder.CreateBitCast(V, DestTy);
1319}
1320
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001321// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1322// of G with bitcast(F). Deletes G.
1323void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001324 if (!G->mayBeOverridden()) {
1325 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001326 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001327 }
1328
Nick Lewycky71972d42010-09-07 01:42:10 +00001329 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001330 // stop here and delete G. There's no need for a thunk.
1331 if (G->hasLocalLinkage() && G->use_empty()) {
1332 G->eraseFromParent();
1333 return;
1334 }
1335
Nick Lewycky25675ac2009-06-12 15:56:56 +00001336 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1337 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001338 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001339 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001340
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001341 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001342 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001343 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001344 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1345 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001346 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001347 ++i;
1348 }
1349
Jay Foad5bd375a2011-07-15 08:37:34 +00001350 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001351 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001352 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001353 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001354 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001355 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001356 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001357 }
1358
1359 NewG->copyAttributesFrom(G);
1360 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001361 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001362 G->replaceAllUsesWith(NewG);
1363 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001364
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001365 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001366 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001367}
1368
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001369// Replace G with an alias to F and delete G.
1370void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001371 PointerType *PTy = G->getType();
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001372 auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1373 G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001374 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1375 GA->takeName(G);
1376 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001377 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001378 G->replaceAllUsesWith(GA);
1379 G->eraseFromParent();
1380
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001381 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001382 ++NumAliasesWritten;
1383}
1384
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001385// Merge two equivalent functions. Upon completion, Function G is deleted.
1386void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001387 if (F->mayBeOverridden()) {
1388 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001389
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001390 if (HasGlobalAliases) {
1391 // Make them both thunks to the same internal function.
1392 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1393 F->getParent());
1394 H->copyAttributesFrom(F);
1395 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001396 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001397 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001398
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001399 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001400
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001401 writeAlias(F, G);
1402 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001403
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001404 F->setAlignment(MaxAlignment);
1405 F->setLinkage(GlobalValue::PrivateLinkage);
1406 } else {
1407 // We can't merge them. Instead, pick one and update all direct callers
1408 // to call it and hope that we improve the instruction cache hit rate.
1409 replaceDirectCallers(G, F);
1410 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001411
1412 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001413 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001414 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001415 }
1416
Nick Lewyckye04dc222009-06-12 08:04:51 +00001417 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001418}
1419
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001420// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001421// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001422bool MergeFunctions::insert(Function *NewFunction) {
1423 std::pair<FnTreeType::iterator, bool> Result =
1424 FnTree.insert(FunctionPtr(NewFunction, DL));
1425
Nick Lewycky292e78c2011-02-09 06:32:02 +00001426 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001427 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001428 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001429 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001430
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001431 const FunctionPtr &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001432
Matt Arsenault517d84e2013-10-01 18:05:30 +00001433 // Don't merge tiny functions, since it can just end up making the function
1434 // larger.
1435 // FIXME: Should still merge them if they are unnamed_addr and produce an
1436 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001437 if (NewFunction->size() == 1) {
1438 if (NewFunction->front().size() <= 2) {
1439 DEBUG(dbgs() << NewFunction->getName()
1440 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001441 return false;
1442 }
1443 }
1444
Nick Lewycky00959372010-09-05 08:22:49 +00001445 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001446 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001447
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001448 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1449 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001450
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001451 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001452 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001453 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001454}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001455
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001456// Remove a function from FnTree. If it was already in FnTree, add
1457// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001458void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001459 // We need to make sure we remove F, not a function "equal" to F per the
1460 // function equality comparator.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001461 FnTreeType::iterator found = FnTree.find(FunctionPtr(F, DL));
1462 size_t Erased = 0;
1463 if (found != FnTree.end() && found->getFunc() == F) {
1464 Erased = 1;
1465 FnTree.erase(found);
1466 }
1467
1468 if (Erased) {
1469 DEBUG(dbgs() << "Removed " << F->getName()
1470 << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001471 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001472 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001473}
Nick Lewycky00959372010-09-05 08:22:49 +00001474
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001475// For each instruction used by the value, remove() the function that contains
1476// the instruction. This should happen right before a call to RAUW.
1477void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001478 std::vector<Value *> Worklist;
1479 Worklist.push_back(V);
1480 while (!Worklist.empty()) {
1481 Value *V = Worklist.back();
1482 Worklist.pop_back();
1483
Chandler Carruthcdf47882014-03-09 03:16:01 +00001484 for (User *U : V->users()) {
1485 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001486 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001487 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001488 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001489 } else if (Constant *C = dyn_cast<Constant>(U)) {
1490 for (User *UU : C->users())
1491 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001492 }
Nick Lewycky00959372010-09-05 08:22:49 +00001493 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001494 }
Nick Lewycky00959372010-09-05 08:22:49 +00001495}