blob: 1c9d2170f92b41aae2e1e82f2b05de160bc4782c [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.
JF Bastien5e4303d2015-08-15 01:18:18 +000030//
31// As an optimization, a hash of the function structure is calculated first, and
32// two functions are only compared if they have the same hash. This hash is
33// cheap to compute, and has the property that if function F == G according to
34// the comparison function, then hash(F) == hash(G). This consistency property
35// is critical to ensuring all possible merging opportunities are exploited.
36// Collisions in the hash affect the speed of the pass but not the correctness
37// or determinism of the resulting transformation.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000038//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000039// When a match is found the functions are folded. If both functions are
40// overridable, we move the functionality into a new internal function and
41// leave two overridable thunks to it.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000042//
43//===----------------------------------------------------------------------===//
44//
45// Future work:
46//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000047// * virtual functions.
48//
49// Many functions have their address taken by the virtual function table for
50// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000051// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000052//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000053// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000054//
55// In order to fold functions, we will sometimes add either bitcast instructions
56// or bitcast constant expressions. Unfortunately, this can confound further
57// analysis since the two functions differ where one has a bitcast and the
Nick Lewyckyfbd27572010-08-08 05:04:23 +000058// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000059//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000060// * Compare complex types with pointer types inside.
61// * Compare cross-reference cases.
62// * Compare complex expressions.
63//
64// All the three issues above could be described as ability to prove that
65// fA == fB == fC == fE == fF == fG in example below:
66//
67// void fA() {
68// fB();
69// }
70// void fB() {
71// fA();
72// }
73//
74// void fE() {
75// fF();
76// }
77// void fF() {
78// fG();
79// }
80// void fG() {
81// fE();
82// }
83//
84// Simplest cross-reference case (fA <--> fB) was implemented in previous
85// versions of MergeFunctions, though it presented only in two function pairs
86// in test-suite (that counts >50k functions)
87// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88// could cover much more cases.
89//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000090//===----------------------------------------------------------------------===//
91
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000092#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000093#include "llvm/ADT/DenseSet.h"
94#include "llvm/ADT/FoldingSet.h"
95#include "llvm/ADT/STLExtras.h"
96#include "llvm/ADT/SmallSet.h"
97#include "llvm/ADT/Statistic.h"
JF Bastien5e4303d2015-08-15 01:18:18 +000098#include "llvm/ADT/Hashing.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000099#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000100#include "llvm/IR/Constants.h"
101#include "llvm/IR/DataLayout.h"
102#include "llvm/IR/IRBuilder.h"
103#include "llvm/IR/InlineAsm.h"
104#include "llvm/IR/Instructions.h"
105#include "llvm/IR/LLVMContext.h"
106#include "llvm/IR/Module.h"
107#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +0000108#include "llvm/IR/ValueHandle.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000109#include "llvm/Pass.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000110#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000111#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +0000112#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000113#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +0000114#include <vector>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000115using namespace llvm;
116
Chandler Carruth964daaa2014-04-22 02:55:47 +0000117#define DEBUG_TYPE "mergefunc"
118
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000119STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000120STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000121STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000122STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000123
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000124static cl::opt<unsigned> NumFunctionsForSanityCheck(
125 "mergefunc-sanity",
126 cl::desc("How many functions in module could be used for "
127 "MergeFunctions pass sanity check. "
128 "'0' disables this check. Works only with '-debug' key."),
129 cl::init(0), cl::Hidden);
130
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000131namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000132
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000133/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000134/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000135/// used if available. The comparator always fails conservatively (erring on the
136/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000137class FunctionComparator {
138public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000139 FunctionComparator(const Function *F1, const Function *F2)
140 : FnL(F1), FnR(F2) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000141
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000142 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000143 int compare();
JF Bastien5e4303d2015-08-15 01:18:18 +0000144 /// Hash a function. Equivalent functions will have the same hash, and unequal
145 /// functions will have different hashes with high probability.
146 typedef uint64_t FunctionHash;
147 static FunctionHash functionHash(Function &);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000148
149private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000150 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000151 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000152
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000153 /// Constants comparison.
154 /// Its analog to lexicographical comparison between hypothetical numbers
155 /// of next format:
156 /// <bitcastability-trait><raw-bit-contents>
157 ///
158 /// 1. Bitcastability.
159 /// Check whether L's type could be losslessly bitcasted to R's type.
160 /// On this stage method, in case when lossless bitcast is not possible
161 /// method returns -1 or 1, thus also defining which type is greater in
162 /// context of bitcastability.
163 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
164 /// to the contents comparison.
165 /// If types differ, remember types comparison result and check
166 /// whether we still can bitcast types.
167 /// Stage 1: Types that satisfies isFirstClassType conditions are always
168 /// greater then others.
169 /// Stage 2: Vector is greater then non-vector.
170 /// If both types are vectors, then vector with greater bitwidth is
171 /// greater.
172 /// If both types are vectors with the same bitwidth, then types
173 /// are bitcastable, and we can skip other stages, and go to contents
174 /// comparison.
175 /// Stage 3: Pointer types are greater than non-pointers. If both types are
176 /// pointers of the same address space - go to contents comparison.
177 /// Different address spaces: pointer with greater address space is
178 /// greater.
179 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
180 /// We don't know how to bitcast them. So, we better don't do it,
181 /// and return types comparison result (so it determines the
182 /// relationship among constants we don't know how to bitcast).
183 ///
184 /// Just for clearance, let's see how the set of constants could look
185 /// on single dimension axis:
186 ///
187 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
188 /// Where: NFCT - Not a FirstClassType
189 /// FCT - FirstClassTyp:
190 ///
191 /// 2. Compare raw contents.
192 /// It ignores types on this stage and only compares bits from L and R.
193 /// Returns 0, if L and R has equivalent contents.
194 /// -1 or 1 if values are different.
195 /// Pretty trivial:
196 /// 2.1. If contents are numbers, compare numbers.
197 /// Ints with greater bitwidth are greater. Ints with same bitwidths
198 /// compared by their contents.
199 /// 2.2. "And so on". Just to avoid discrepancies with comments
200 /// perhaps it would be better to read the implementation itself.
201 /// 3. And again about overall picture. Let's look back at how the ordered set
202 /// of constants will look like:
203 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
204 ///
205 /// Now look, what could be inside [FCT, "others"], for example:
206 /// [FCT, "others"] =
207 /// [
208 /// [double 0.1], [double 1.23],
209 /// [i32 1], [i32 2],
210 /// { double 1.0 }, ; StructTyID, NumElements = 1
211 /// { i32 1 }, ; StructTyID, NumElements = 1
212 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
213 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
214 /// ]
215 ///
216 /// Let's explain the order. Float numbers will be less than integers, just
217 /// because of cmpType terms: FloatTyID < IntegerTyID.
218 /// Floats (with same fltSemantics) are sorted according to their value.
219 /// Then you can see integers, and they are, like a floats,
220 /// could be easy sorted among each others.
221 /// The structures. Structures are grouped at the tail, again because of their
222 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
223 /// Structures with greater number of elements are greater. Structures with
224 /// greater elements going first are greater.
225 /// The same logic with vectors, arrays and other possible complex types.
226 ///
227 /// Bitcastable constants.
228 /// Let's assume, that some constant, belongs to some group of
229 /// "so-called-equal" values with different types, and at the same time
230 /// belongs to another group of constants with equal types
231 /// and "really" equal values.
232 ///
233 /// Now, prove that this is impossible:
234 ///
235 /// If constant A with type TyA is bitcastable to B with type TyB, then:
236 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
237 /// those should be vectors (if TyA is vector), pointers
238 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
239 /// be equal to TyB.
240 /// 2. All constants with non-equal, but bitcastable types to TyA, are
241 /// bitcastable to B.
242 /// Once again, just because we allow it to vectors and pointers only.
243 /// This statement could be expanded as below:
244 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
245 /// vector B, and thus bitcastable to B as well.
246 /// 2.2. All pointers of the same address space, no matter what they point to,
247 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
248 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
249 /// QED.
250 ///
251 /// In another words, for pointers and vectors, we ignore top-level type and
252 /// look at their particular properties (bit-width for vectors, and
253 /// address space for pointers).
254 /// If these properties are equal - compare their contents.
255 int cmpConstants(const Constant *L, const Constant *R);
256
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000257 /// Assign or look up previously assigned numbers for the two values, and
258 /// return whether the numbers are equal. Numbers are assigned in the order
259 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000260 /// Comparison order:
261 /// Stage 0: Value that is function itself is always greater then others.
262 /// If left and right values are references to their functions, then
263 /// they are equal.
264 /// Stage 1: Constants are greater than non-constants.
265 /// If both left and right are constants, then the result of
266 /// cmpConstants is used as cmpValues result.
267 /// Stage 2: InlineAsm instances are greater than others. If both left and
268 /// right are InlineAsm instances, InlineAsm* pointers casted to
269 /// integers and compared as numbers.
270 /// Stage 3: For all other cases we compare order we meet these values in
271 /// their functions. If right value was met first during scanning,
272 /// then left value is greater.
273 /// In another words, we compare serial numbers, for more details
274 /// see comments for sn_mapL and sn_mapR.
275 int cmpValues(const Value *L, const Value *R);
276
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000277 /// Compare two Instructions for equivalence, similar to
278 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000279 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000280 /// Stages are listed in "most significant stage first" order:
281 /// On each stage below, we do comparison between some left and right
282 /// operation parts. If parts are non-equal, we assign parts comparison
283 /// result to the operation comparison result and exit from method.
284 /// Otherwise we proceed to the next stage.
285 /// Stages:
286 /// 1. Operations opcodes. Compared as numbers.
287 /// 2. Number of operands.
288 /// 3. Operation types. Compared with cmpType method.
289 /// 4. Compare operation subclass optional data as stream of bytes:
290 /// just convert it to integers and call cmpNumbers.
291 /// 5. Compare in operation operand types with cmpType in
292 /// most significant operand first order.
293 /// 6. Last stage. Check operations for some specific attributes.
294 /// For example, for Load it would be:
295 /// 6.1.Load: volatile (as boolean flag)
296 /// 6.2.Load: alignment (as integer numbers)
297 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000298 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000299 /// On this stage its better to see the code, since its not more than 10-15
300 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000301 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000302
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000303 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000304 /// Parts to be compared for each comparison stage,
305 /// most significant stage first:
306 /// 1. Address space. As numbers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000308 /// 3. Pointer operand type (using cmpType method).
309 /// 4. Number of operands.
310 /// 5. Compare operands, using cmpValues method.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000311 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
312 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
313 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000314 }
315
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000316 /// cmpType - compares two types,
317 /// defines total ordering among the types set.
318 ///
319 /// Return values:
320 /// 0 if types are equal,
321 /// -1 if Left is less than Right,
322 /// +1 if Left is greater than Right.
323 ///
324 /// Description:
325 /// Comparison is broken onto stages. Like in lexicographical comparison
326 /// stage coming first has higher priority.
327 /// On each explanation stage keep in mind total ordering properties.
328 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000329 /// 0. Before comparison we coerce pointer types of 0 address space to
330 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000331 /// We also don't bother with same type at left and right, so
332 /// just return 0 in this case.
333 ///
334 /// 1. If types are of different kind (different type IDs).
335 /// Return result of type IDs comparison, treating them as numbers.
336 /// 2. If types are vectors or integers, compare Type* values as numbers.
337 /// 3. Types has same ID, so check whether they belongs to the next group:
338 /// * Void
339 /// * Float
340 /// * Double
341 /// * X86_FP80
342 /// * FP128
343 /// * PPC_FP128
344 /// * Label
345 /// * Metadata
346 /// If so - return 0, yes - we can treat these types as equal only because
347 /// their IDs are same.
348 /// 4. If Left and Right are pointers, return result of address space
349 /// comparison (numbers comparison). We can treat pointer types of same
350 /// address space as equal.
351 /// 5. If types are complex.
352 /// Then both Left and Right are to be expanded and their element types will
353 /// be checked with the same way. If we get Res != 0 on some stage, return it.
354 /// Otherwise return 0.
355 /// 6. For all other cases put llvm_unreachable.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000356 int cmpTypes(Type *TyL, Type *TyR) const;
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000357
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000358 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000359
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000360 int cmpAPInts(const APInt &L, const APInt &R) const;
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000361 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000362 int cmpStrings(StringRef L, StringRef R) const;
363 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000364
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000365 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000366 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000367
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000368 /// Assign serial numbers to values from left function, and values from
369 /// right function.
370 /// Explanation:
371 /// Being comparing functions we need to compare values we meet at left and
372 /// right sides.
373 /// Its easy to sort things out for external values. It just should be
374 /// the same value at left and right.
375 /// But for local values (those were introduced inside function body)
376 /// we have to ensure they were introduced at exactly the same place,
377 /// and plays the same role.
378 /// Let's assign serial number to each value when we meet it first time.
379 /// Values that were met at same place will be with same serial numbers.
380 /// In this case it would be good to explain few points about values assigned
381 /// to BBs and other ways of implementation (see below).
382 ///
383 /// 1. Safety of BB reordering.
384 /// It's safe to change the order of BasicBlocks in function.
385 /// Relationship with other functions and serial numbering will not be
386 /// changed in this case.
387 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
388 /// from the entry, and then take each terminator. So it doesn't matter how in
389 /// fact BBs are ordered in function. And since cmpValues are called during
390 /// this walk, the numbering depends only on how BBs located inside the CFG.
391 /// So the answer is - yes. We will get the same numbering.
392 ///
393 /// 2. Impossibility to use dominance properties of values.
394 /// If we compare two instruction operands: first is usage of local
395 /// variable AL from function FL, and second is usage of local variable AR
396 /// from FR, we could compare their origins and check whether they are
397 /// defined at the same place.
398 /// But, we are still not able to compare operands of PHI nodes, since those
399 /// could be operands from further BBs we didn't scan yet.
400 /// So it's impossible to use dominance properties in general.
401 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000402};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000403
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000404class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000405 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000406 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000407
408public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000409 // Note the hash is recalculated potentially multiple times, but it is cheap.
410 FunctionNode(Function *F) : F(F), Hash(FunctionComparator::functionHash(*F)){}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000411 Function *getFunc() const { return F; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000412
413 /// Replace the reference to the function F by the function G, assuming their
414 /// implementations are equal.
415 void replaceBy(Function *G) const {
416 assert(!(*this < FunctionNode(G)) && !(FunctionNode(G) < *this) &&
417 "The two functions must be equal");
418
419 F = G;
420 }
421
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000422 void release() { F = 0; }
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000423 bool operator<(const FunctionNode &RHS) const {
JF Bastien5e4303d2015-08-15 01:18:18 +0000424 // Order first by hashes, then full function comparison.
425 if (Hash != RHS.Hash)
426 return Hash < RHS.Hash;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 return (FunctionComparator(F, RHS.getFunc()).compare()) == -1;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000428 }
429};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000430}
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000431
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000432int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
433 if (L < R) return -1;
434 if (L > R) return 1;
435 return 0;
436}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000437
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000438int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000439 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
440 return Res;
441 if (L.ugt(R)) return 1;
442 if (R.ugt(L)) return -1;
443 return 0;
444}
445
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000446int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000447 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
448 (uint64_t)&R.getSemantics()))
449 return Res;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000450 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000451}
452
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000453int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
454 // Prevent heavy comparison, compare sizes first.
455 if (int Res = cmpNumbers(L.size(), R.size()))
456 return Res;
457
458 // Compare strings lexicographically only when it is necessary: only when
459 // strings are equal in size.
460 return L.compare(R);
461}
462
463int FunctionComparator::cmpAttrs(const AttributeSet L,
464 const AttributeSet R) const {
465 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
466 return Res;
467
468 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
469 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
470 RE = R.end(i);
471 for (; LI != LE && RI != RE; ++LI, ++RI) {
472 Attribute LA = *LI;
473 Attribute RA = *RI;
474 if (LA < RA)
475 return -1;
476 if (RA < LA)
477 return 1;
478 }
479 if (LI != LE)
480 return 1;
481 if (RI != RE)
482 return -1;
483 }
484 return 0;
485}
486
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000487/// Constants comparison:
488/// 1. Check whether type of L constant could be losslessly bitcasted to R
489/// type.
490/// 2. Compare constant contents.
491/// For more details see declaration comments.
492int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
493
494 Type *TyL = L->getType();
495 Type *TyR = R->getType();
496
497 // Check whether types are bitcastable. This part is just re-factored
498 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
499 // we also pack into result which type is "less" for us.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000500 int TypesRes = cmpTypes(TyL, TyR);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000501 if (TypesRes != 0) {
502 // Types are different, but check whether we can bitcast them.
503 if (!TyL->isFirstClassType()) {
504 if (TyR->isFirstClassType())
505 return -1;
506 // Neither TyL nor TyR are values of first class type. Return the result
507 // of comparing the types
508 return TypesRes;
509 }
510 if (!TyR->isFirstClassType()) {
511 if (TyL->isFirstClassType())
512 return 1;
513 return TypesRes;
514 }
515
516 // Vector -> Vector conversions are always lossless if the two vector types
517 // have the same size, otherwise not.
518 unsigned TyLWidth = 0;
519 unsigned TyRWidth = 0;
520
Craig Toppere3dcce92015-08-01 22:20:21 +0000521 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000522 TyLWidth = VecTyL->getBitWidth();
Craig Toppere3dcce92015-08-01 22:20:21 +0000523 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000524 TyRWidth = VecTyR->getBitWidth();
525
526 if (TyLWidth != TyRWidth)
527 return cmpNumbers(TyLWidth, TyRWidth);
528
529 // Zero bit-width means neither TyL nor TyR are vectors.
530 if (!TyLWidth) {
531 PointerType *PTyL = dyn_cast<PointerType>(TyL);
532 PointerType *PTyR = dyn_cast<PointerType>(TyR);
533 if (PTyL && PTyR) {
534 unsigned AddrSpaceL = PTyL->getAddressSpace();
535 unsigned AddrSpaceR = PTyR->getAddressSpace();
536 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
537 return Res;
538 }
539 if (PTyL)
540 return 1;
541 if (PTyR)
542 return -1;
543
544 // TyL and TyR aren't vectors, nor pointers. We don't know how to
545 // bitcast them.
546 return TypesRes;
547 }
548 }
549
550 // OK, types are bitcastable, now check constant contents.
551
552 if (L->isNullValue() && R->isNullValue())
553 return TypesRes;
554 if (L->isNullValue() && !R->isNullValue())
555 return 1;
556 if (!L->isNullValue() && R->isNullValue())
557 return -1;
558
559 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
560 return Res;
561
562 switch (L->getValueID()) {
563 case Value::UndefValueVal: return TypesRes;
564 case Value::ConstantIntVal: {
565 const APInt &LInt = cast<ConstantInt>(L)->getValue();
566 const APInt &RInt = cast<ConstantInt>(R)->getValue();
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000567 return cmpAPInts(LInt, RInt);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000568 }
569 case Value::ConstantFPVal: {
570 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
571 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000572 return cmpAPFloats(LAPF, RAPF);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000573 }
574 case Value::ConstantArrayVal: {
575 const ConstantArray *LA = cast<ConstantArray>(L);
576 const ConstantArray *RA = cast<ConstantArray>(R);
577 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
578 uint64_t NumElementsR = cast<ArrayType>(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>(LA->getOperand(i)),
583 cast<Constant>(RA->getOperand(i))))
584 return Res;
585 }
586 return 0;
587 }
588 case Value::ConstantStructVal: {
589 const ConstantStruct *LS = cast<ConstantStruct>(L);
590 const ConstantStruct *RS = cast<ConstantStruct>(R);
591 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
592 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
593 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
594 return Res;
595 for (unsigned i = 0; i != NumElementsL; ++i) {
596 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
597 cast<Constant>(RS->getOperand(i))))
598 return Res;
599 }
600 return 0;
601 }
602 case Value::ConstantVectorVal: {
603 const ConstantVector *LV = cast<ConstantVector>(L);
604 const ConstantVector *RV = cast<ConstantVector>(R);
605 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
606 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
607 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
608 return Res;
609 for (uint64_t i = 0; i < NumElementsL; ++i) {
610 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
611 cast<Constant>(RV->getOperand(i))))
612 return Res;
613 }
614 return 0;
615 }
616 case Value::ConstantExprVal: {
617 const ConstantExpr *LE = cast<ConstantExpr>(L);
618 const ConstantExpr *RE = cast<ConstantExpr>(R);
619 unsigned NumOperandsL = LE->getNumOperands();
620 unsigned NumOperandsR = RE->getNumOperands();
621 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
622 return Res;
623 for (unsigned i = 0; i < NumOperandsL; ++i) {
624 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
625 cast<Constant>(RE->getOperand(i))))
626 return Res;
627 }
628 return 0;
629 }
630 case Value::FunctionVal:
631 case Value::GlobalVariableVal:
632 case Value::GlobalAliasVal:
633 default: // Unknown constant, cast L and R pointers to numbers and compare.
634 return cmpNumbers((uint64_t)L, (uint64_t)R);
635 }
636}
637
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000638/// cmpType - compares two types,
639/// defines total ordering among the types set.
640/// See method declaration comments for more details.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000641int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000642
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000643 PointerType *PTyL = dyn_cast<PointerType>(TyL);
644 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000645
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000646 const DataLayout &DL = FnL->getParent()->getDataLayout();
647 if (PTyL && PTyL->getAddressSpace() == 0)
648 TyL = DL.getIntPtrType(TyL);
649 if (PTyR && PTyR->getAddressSpace() == 0)
650 TyR = DL.getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000651
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000652 if (TyL == TyR)
653 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000654
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000655 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
656 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000657
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000658 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000659 default:
660 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000661 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000662 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000663 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000664 // TyL == TyR would have returned true earlier.
665 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000666
Nick Lewyckye04dc222009-06-12 08:04:51 +0000667 case Type::VoidTyID:
668 case Type::FloatTyID:
669 case Type::DoubleTyID:
670 case Type::X86_FP80TyID:
671 case Type::FP128TyID:
672 case Type::PPC_FP128TyID:
673 case Type::LabelTyID:
674 case Type::MetadataTyID:
David Majnemerb611e3f2015-08-14 05:09:07 +0000675 case Type::TokenTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000676 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000677
Nick Lewyckye04dc222009-06-12 08:04:51 +0000678 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000679 assert(PTyL && PTyR && "Both types must be pointers here.");
680 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000681 }
682
683 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000684 StructType *STyL = cast<StructType>(TyL);
685 StructType *STyR = cast<StructType>(TyR);
686 if (STyL->getNumElements() != STyR->getNumElements())
687 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000688
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000689 if (STyL->isPacked() != STyR->isPacked())
690 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000691
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000692 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000693 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000694 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000695 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000696 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000697 }
698
699 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000700 FunctionType *FTyL = cast<FunctionType>(TyL);
701 FunctionType *FTyR = cast<FunctionType>(TyR);
702 if (FTyL->getNumParams() != FTyR->getNumParams())
703 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000704
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000705 if (FTyL->isVarArg() != FTyR->isVarArg())
706 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000707
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000708 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000709 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000710
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000711 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000712 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000713 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000714 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000715 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000716 }
717
Nick Lewycky375efe32010-07-16 06:31:12 +0000718 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000719 ArrayType *ATyL = cast<ArrayType>(TyL);
720 ArrayType *ATyR = cast<ArrayType>(TyR);
721 if (ATyL->getNumElements() != ATyR->getNumElements())
722 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000723 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000724 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000725 }
726}
727
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000728// Determine whether the two operations are the same except that pointer-to-A
729// and pointer-to-B are equivalent. This should be kept in sync with
730// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000731// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000732int FunctionComparator::cmpOperations(const Instruction *L,
733 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000734 // Differences from Instruction::isSameOperationAs:
735 // * replace type comparison with calls to isEquivalentType.
736 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
737 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000738 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
739 return Res;
740
741 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
742 return Res;
743
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000744 if (int Res = cmpTypes(L->getType(), R->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000745 return Res;
746
747 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
748 R->getRawSubclassOptionalData()))
749 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000750
Arnold Schwaighofer6a8c5f62015-05-12 21:42:22 +0000751 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
752 if (int Res = cmpTypes(AI->getAllocatedType(),
753 cast<AllocaInst>(R)->getAllocatedType()))
754 return Res;
755 if (int Res =
756 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
757 return Res;
758 }
759
Nick Lewyckye04dc222009-06-12 08:04:51 +0000760 // We have two instructions of identical opcode and #operands. Check to see
761 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000762 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
763 if (int Res =
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000764 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000765 return Res;
766 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000767
768 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000769 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
770 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
771 return Res;
772 if (int Res =
773 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
774 return Res;
775 if (int Res =
776 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
777 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000778 if (int Res =
779 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
780 return Res;
781 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
782 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000783 }
784 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
785 if (int Res =
786 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
787 return Res;
788 if (int Res =
789 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
790 return Res;
791 if (int Res =
792 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
793 return Res;
794 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
795 }
796 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
797 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
798 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
799 if (int Res = cmpNumbers(CI->getCallingConv(),
800 cast<CallInst>(R)->getCallingConv()))
801 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000802 if (int Res =
803 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
804 return Res;
805 return cmpNumbers(
806 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
807 (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000808 }
809 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
810 if (int Res = cmpNumbers(CI->getCallingConv(),
811 cast<InvokeInst>(R)->getCallingConv()))
812 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000813 if (int Res =
814 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
815 return Res;
816 return cmpNumbers(
817 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
818 (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000819 }
820 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
821 ArrayRef<unsigned> LIndices = IVI->getIndices();
822 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
823 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
824 return Res;
825 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
826 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
827 return Res;
828 }
829 }
830 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
831 ArrayRef<unsigned> LIndices = EVI->getIndices();
832 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
833 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
834 return Res;
835 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
836 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
837 return Res;
838 }
839 }
840 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
841 if (int Res =
842 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
843 return Res;
844 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
845 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000846
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000847 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
848 if (int Res = cmpNumbers(CXI->isVolatile(),
849 cast<AtomicCmpXchgInst>(R)->isVolatile()))
850 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000851 if (int Res = cmpNumbers(CXI->isWeak(),
852 cast<AtomicCmpXchgInst>(R)->isWeak()))
853 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000854 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
855 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
856 return Res;
857 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
858 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
859 return Res;
860 return cmpNumbers(CXI->getSynchScope(),
861 cast<AtomicCmpXchgInst>(R)->getSynchScope());
862 }
863 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
864 if (int Res = cmpNumbers(RMWI->getOperation(),
865 cast<AtomicRMWInst>(R)->getOperation()))
866 return Res;
867 if (int Res = cmpNumbers(RMWI->isVolatile(),
868 cast<AtomicRMWInst>(R)->isVolatile()))
869 return Res;
870 if (int Res = cmpNumbers(RMWI->getOrdering(),
871 cast<AtomicRMWInst>(R)->getOrdering()))
872 return Res;
873 return cmpNumbers(RMWI->getSynchScope(),
874 cast<AtomicRMWInst>(R)->getSynchScope());
875 }
876 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000877}
878
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000879// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000880// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000881int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000882 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000883
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000884 unsigned int ASL = GEPL->getPointerAddressSpace();
885 unsigned int ASR = GEPR->getPointerAddressSpace();
886
887 if (int Res = cmpNumbers(ASL, ASR))
888 return Res;
889
890 // When we have target data, we can reduce the GEP down to the value in bytes
891 // added to the address.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000892 const DataLayout &DL = FnL->getParent()->getDataLayout();
893 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
894 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
895 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
896 GEPR->accumulateConstantOffset(DL, OffsetR))
897 return cmpAPInts(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000898
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000899 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
900 (uint64_t)GEPR->getPointerOperand()->getType()))
901 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000902
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000903 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
904 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000905
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000906 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
907 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
908 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000909 }
910
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000911 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000912}
913
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000914/// Compare two values used by the two functions under pair-wise comparison. If
915/// this is the first time the values are seen, they're added to the mapping so
916/// that we will detect mismatches on next use.
917/// See comments in declaration for more details.
918int FunctionComparator::cmpValues(const Value *L, const Value *R) {
919 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000920 if (L == FnL) {
921 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000922 return 0;
923 return -1;
924 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000925 if (R == FnR) {
926 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000927 return 0;
928 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000929 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000930
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000931 const Constant *ConstL = dyn_cast<Constant>(L);
932 const Constant *ConstR = dyn_cast<Constant>(R);
933 if (ConstL && ConstR) {
934 if (L == R)
935 return 0;
936 return cmpConstants(ConstL, ConstR);
937 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000938
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000939 if (ConstL)
940 return 1;
941 if (ConstR)
942 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000943
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000944 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
945 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
946
947 if (InlineAsmL && InlineAsmR)
948 return cmpNumbers((uint64_t)L, (uint64_t)R);
949 if (InlineAsmL)
950 return 1;
951 if (InlineAsmR)
952 return -1;
953
954 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
955 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
956
957 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000958}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000959// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000960int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
961 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
962 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000963
964 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000965 if (int Res = cmpValues(InstL, InstR))
966 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000967
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000968 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
969 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +0000970
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000971 if (GEPL && !GEPR)
972 return 1;
973 if (GEPR && !GEPL)
974 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000975
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000976 if (GEPL && GEPR) {
977 if (int Res =
978 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
979 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000980 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000981 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000982 } else {
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000983 if (int Res = cmpOperations(InstL, InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000984 return Res;
985 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000986
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000987 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
988 Value *OpL = InstL->getOperand(i);
989 Value *OpR = InstR->getOperand(i);
990 if (int Res = cmpValues(OpL, OpR))
991 return Res;
992 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
993 return Res;
994 // TODO: Already checked in cmpOperation
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000995 if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000996 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000997 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000998 }
999
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001000 ++InstL, ++InstR;
1001 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001002
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001003 if (InstL != InstLE && InstR == InstRE)
1004 return 1;
1005 if (InstL == InstLE && InstR != InstRE)
1006 return -1;
1007 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001008}
1009
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001010// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001011int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001012
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001013 sn_mapL.clear();
1014 sn_mapR.clear();
1015
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001016 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1017 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001018
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001019 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1020 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001021
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001022 if (FnL->hasGC()) {
1023 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1024 return Res;
1025 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001026
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001027 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1028 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001029
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001030 if (FnL->hasSection()) {
1031 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1032 return Res;
1033 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001034
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001035 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1036 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001037
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001038 // TODO: if it's internal and only used in direct calls, we could handle this
1039 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001040 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1041 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001042
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001043 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001044 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001045
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001046 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001047 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001048
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001049 // Visit the arguments so that they get enumerated in the order they're
1050 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001051 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1052 ArgRI = FnR->arg_begin(),
1053 ArgLE = FnL->arg_end();
1054 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1055 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001056 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001057 }
1058
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001059 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1060 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001061 // functions, then takes each block from each terminator in order. As an
1062 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001063 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001064 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001065
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001066 FnLBBs.push_back(&FnL->getEntryBlock());
1067 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001068
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001069 VisitedBBs.insert(FnLBBs[0]);
1070 while (!FnLBBs.empty()) {
1071 const BasicBlock *BBL = FnLBBs.pop_back_val();
1072 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001073
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001074 if (int Res = cmpValues(BBL, BBR))
1075 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001076
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001077 if (int Res = compare(BBL, BBR))
1078 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001079
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001080 const TerminatorInst *TermL = BBL->getTerminator();
1081 const TerminatorInst *TermR = BBR->getTerminator();
1082
1083 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1084 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
David Blaikie70573dc2014-11-19 07:49:26 +00001085 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001086 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001087
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001088 FnLBBs.push_back(TermL->getSuccessor(i));
1089 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001090 }
1091 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001092 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001093}
1094
JF Bastien5e4303d2015-08-15 01:18:18 +00001095// Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1096// hash of a sequence of 64bit ints, but the entire input does not need to be
1097// available at once. This interface is necessary for functionHash because it
1098// needs to accumulate the hash as the structure of the function is traversed
1099// without saving these values to an intermediate buffer. This form of hashing
1100// is not often needed, as usually the object to hash is just read from a
1101// buffer.
1102class HashAccumulator64 {
1103 uint64_t Hash;
1104public:
1105 // Initialize to random constant, so the state isn't zero.
1106 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1107 void add(uint64_t V) {
1108 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1109 }
1110 // No finishing is required, because the entire hash value is used.
1111 uint64_t getHash() { return Hash; }
1112};
1113
1114// A function hash is calculated by considering only the number of arguments and
1115// whether a function is varargs, the order of basic blocks (given by the
1116// successors of each basic block in depth first order), and the order of
1117// opcodes of each instruction within each of these basic blocks. This mirrors
1118// the strategy compare() uses to compare functions by walking the BBs in depth
1119// first order and comparing each instruction in sequence. Because this hash
1120// does not look at the operands, it is insensitive to things such as the
1121// target of calls and the constants used in the function, which makes it useful
1122// when possibly merging functions which are the same modulo constants and call
1123// targets.
1124FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1125 HashAccumulator64 H;
1126 H.add(F.isVarArg());
1127 H.add(F.arg_size());
1128
1129 SmallVector<const BasicBlock *, 8> BBs;
1130 SmallSet<const BasicBlock *, 16> VisitedBBs;
1131
1132 // Walk the blocks in the same order as FunctionComparator::compare(),
1133 // accumulating the hash of the function "structure." (BB and opcode sequence)
1134 BBs.push_back(&F.getEntryBlock());
1135 VisitedBBs.insert(BBs[0]);
1136 while (!BBs.empty()) {
1137 const BasicBlock *BB = BBs.pop_back_val();
1138 // This random value acts as a block header, as otherwise the partition of
1139 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1140 H.add(45798);
1141 for (auto &Inst : *BB) {
1142 H.add(Inst.getOpcode());
1143 }
1144 const TerminatorInst *Term = BB->getTerminator();
1145 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1146 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1147 continue;
1148 BBs.push_back(Term->getSuccessor(i));
1149 }
1150 }
1151 return H.getHash();
1152}
1153
1154
Nick Lewycky564fcca2011-01-28 07:36:21 +00001155namespace {
1156
1157/// MergeFunctions finds functions which will generate identical machine code,
1158/// by considering all pointer types to be equivalent. Once identified,
1159/// MergeFunctions will fold them by replacing a call to one to a call to a
1160/// bitcast of the other.
1161///
1162class MergeFunctions : public ModulePass {
1163public:
1164 static char ID;
1165 MergeFunctions()
1166 : ModulePass(ID), HasGlobalAliases(false) {
1167 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1168 }
1169
Craig Topper3e4c6972014-03-05 09:10:37 +00001170 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001171
1172private:
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001173 typedef std::set<FunctionNode> FnTreeType;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001174
1175 /// A work queue of functions that may have been modified and should be
1176 /// analyzed again.
1177 std::vector<WeakVH> Deferred;
1178
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001179 /// Checks the rules of order relation introduced among functions set.
1180 /// Returns true, if sanity check has been passed, and false if failed.
1181 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1182
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001183 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001184 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001185 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001186
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001187 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001188 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001189 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001190
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001191 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001192 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001193 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001194
1195 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1196 /// necessary to make types match.
1197 void replaceDirectCallers(Function *Old, Function *New);
1198
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001199 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1200 /// be converted into a thunk. In either case, it should never be visited
1201 /// again.
1202 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001203
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001204 /// Replace G with a thunk or an alias to F. Deletes G.
1205 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001206
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001207 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1208 /// of G with bitcast(F). Deletes G.
1209 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001210
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001211 /// Replace G with an alias to F. Deletes G.
1212 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001213
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001214 /// Replace function F with function G in the function tree.
1215 void replaceFunctionInTree(FnTreeType::iterator &IterToF, Function *G);
1216
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001217 /// The set of all distinct functions. Use the insert() and remove() methods
1218 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001219 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001220
Nick Lewycky564fcca2011-01-28 07:36:21 +00001221 /// Whether or not the target supports global aliases.
1222 bool HasGlobalAliases;
1223};
1224
1225} // end anonymous namespace
1226
1227char MergeFunctions::ID = 0;
1228INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1229
1230ModulePass *llvm::createMergeFunctionsPass() {
1231 return new MergeFunctions();
1232}
1233
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001234bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1235 if (const unsigned Max = NumFunctionsForSanityCheck) {
1236 unsigned TripleNumber = 0;
1237 bool Valid = true;
1238
1239 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1240
1241 unsigned i = 0;
1242 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1243 I != E && i < Max; ++I, ++i) {
1244 unsigned j = i;
1245 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1246 Function *F1 = cast<Function>(*I);
1247 Function *F2 = cast<Function>(*J);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001248 int Res1 = FunctionComparator(F1, F2).compare();
1249 int Res2 = FunctionComparator(F2, F1).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001250
1251 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1252 if (Res1 != -Res2) {
1253 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1254 << "\n";
1255 F1->dump();
1256 F2->dump();
1257 Valid = false;
1258 }
1259
1260 if (Res1 == 0)
1261 continue;
1262
1263 unsigned k = j;
1264 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1265 ++k, ++K, ++TripleNumber) {
1266 if (K == J)
1267 continue;
1268
1269 Function *F3 = cast<Function>(*K);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001270 int Res3 = FunctionComparator(F1, F3).compare();
1271 int Res4 = FunctionComparator(F2, F3).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001272
1273 bool Transitive = true;
1274
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001275 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001276 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001277 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001278 } else if (Res3 != 0 && Res3 == -Res4) {
1279 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001280 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001281 } else if (Res4 != 0 && -Res3 == Res4) {
1282 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001283 Transitive = Res4 == -Res1;
1284 }
1285
1286 if (!Transitive) {
1287 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1288 << TripleNumber << "\n";
1289 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1290 << Res4 << "\n";
1291 F1->dump();
1292 F2->dump();
1293 F3->dump();
1294 Valid = false;
1295 }
1296 }
1297 }
1298 }
1299
1300 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1301 return Valid;
1302 }
1303 return true;
1304}
1305
Nick Lewycky564fcca2011-01-28 07:36:21 +00001306bool MergeFunctions::runOnModule(Module &M) {
1307 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001308
JF Bastien5e4303d2015-08-15 01:18:18 +00001309 // All functions in the module, ordered by hash. Functions with a unique
1310 // hash value are easily eliminated.
1311 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1312 HashedFuncs;
1313 for (Function &Func : M) {
1314 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1315 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1316 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001317 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001318
JF Bastien5e4303d2015-08-15 01:18:18 +00001319 std::sort(HashedFuncs.begin(), HashedFuncs.end());
1320
1321 auto S = HashedFuncs.begin();
1322 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1323 // If the hash value matches the previous value or the next one, we must
1324 // consider merging it. Otherwise it is dropped and never considered again.
1325 if ((I != S && std::prev(I)->first == I->first) ||
1326 (std::next(I) != IE && std::next(I)->first == I->first) ) {
1327 Deferred.push_back(WeakVH(I->second));
1328 }
1329 }
1330
Nick Lewycky564fcca2011-01-28 07:36:21 +00001331 do {
1332 std::vector<WeakVH> Worklist;
1333 Deferred.swap(Worklist);
1334
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001335 DEBUG(doSanityCheck(Worklist));
1336
Nick Lewycky564fcca2011-01-28 07:36:21 +00001337 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1338 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1339
1340 // Insert only strong functions and merge them. Strong function merging
1341 // always deletes one of them.
1342 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1343 E = Worklist.end(); I != E; ++I) {
1344 if (!*I) continue;
1345 Function *F = cast<Function>(*I);
1346 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1347 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001348 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001349 }
1350 }
1351
1352 // Insert only weak functions and merge them. By doing these second we
1353 // create thunks to the strong function when possible. When two weak
1354 // functions are identical, we create a new strong function with two weak
1355 // weak thunks to it which are identical but not mergable.
1356 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1357 E = Worklist.end(); I != E; ++I) {
1358 if (!*I) continue;
1359 Function *F = cast<Function>(*I);
1360 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1361 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001362 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001363 }
1364 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001365 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001366 } while (!Deferred.empty());
1367
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001368 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001369
1370 return Changed;
1371}
1372
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001373// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001374void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1375 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001376 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1377 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001378 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001379 CallSite CS(U->getUser());
1380 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001381 // Transfer the called function's attributes to the call site. Due to the
1382 // bitcast we will 'loose' ABI changing attributes because the 'called
1383 // function' is no longer a Function* but the bitcast. Code that looks up
1384 // the attributes from the called function will fail.
1385 auto &Context = New->getContext();
1386 auto NewFuncAttrs = New->getAttributes();
1387 auto CallSiteAttrs = CS.getAttributes();
1388
1389 CallSiteAttrs = CallSiteAttrs.addAttributes(
1390 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1391
1392 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1393 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1394 if (Attrs.getNumSlots())
1395 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1396 }
1397
1398 CS.setAttributes(CallSiteAttrs);
1399
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001400 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001401 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001402 }
1403 }
1404}
1405
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001406// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1407void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001408 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1409 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1410 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001411 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001412 return;
1413 }
1414 }
1415
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001416 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001417}
1418
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001419// Helper for writeThunk,
1420// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001421// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001422static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001423 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001424 if (SrcTy->isStructTy()) {
1425 assert(DestTy->isStructTy());
1426 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1427 Value *Result = UndefValue::get(DestTy);
1428 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1429 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +00001430 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +00001431 DestTy->getStructElementType(I));
1432
1433 Result =
Craig Toppere1d12942014-08-27 05:25:25 +00001434 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +00001435 }
1436 return Result;
1437 }
1438 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001439 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1440 return Builder.CreateIntToPtr(V, DestTy);
1441 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1442 return Builder.CreatePtrToInt(V, DestTy);
1443 else
1444 return Builder.CreateBitCast(V, DestTy);
1445}
1446
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001447// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1448// of G with bitcast(F). Deletes G.
1449void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001450 if (!G->mayBeOverridden()) {
1451 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001452 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001453 }
1454
Nick Lewycky71972d42010-09-07 01:42:10 +00001455 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001456 // stop here and delete G. There's no need for a thunk.
1457 if (G->hasLocalLinkage() && G->use_empty()) {
1458 G->eraseFromParent();
1459 return;
1460 }
1461
Nick Lewycky25675ac2009-06-12 15:56:56 +00001462 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1463 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001464 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001465 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001466
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001467 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001468 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001469 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001470 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1471 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001472 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001473 ++i;
1474 }
1475
Jay Foad5bd375a2011-07-15 08:37:34 +00001476 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001477 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001478 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001479 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001480 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001481 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001482 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001483 }
1484
1485 NewG->copyAttributesFrom(G);
1486 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001487 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001488 G->replaceAllUsesWith(NewG);
1489 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001490
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001491 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001492 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001493}
1494
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001495// Replace G with an alias to F and delete G.
1496void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001497 PointerType *PTy = G->getType();
David Blaikief64246b2015-04-29 21:22:39 +00001498 auto *GA = GlobalAlias::create(PTy, G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001499 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1500 GA->takeName(G);
1501 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001502 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001503 G->replaceAllUsesWith(GA);
1504 G->eraseFromParent();
1505
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001506 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001507 ++NumAliasesWritten;
1508}
1509
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001510// Merge two equivalent functions. Upon completion, Function G is deleted.
1511void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001512 if (F->mayBeOverridden()) {
1513 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001514
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001515 // Make them both thunks to the same internal function.
1516 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1517 F->getParent());
1518 H->copyAttributesFrom(F);
1519 H->takeName(F);
1520 removeUsers(F);
1521 F->replaceAllUsesWith(H);
1522
1523 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1524
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001525 if (HasGlobalAliases) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001526 writeAlias(F, G);
1527 writeAlias(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001528 } else {
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001529 writeThunk(F, G);
1530 writeThunk(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001531 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001532
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001533 F->setAlignment(MaxAlignment);
1534 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +00001535 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001536 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001537 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001538 }
1539
Nick Lewyckye04dc222009-06-12 08:04:51 +00001540 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001541}
1542
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001543/// Replace function F for function G in the map.
1544void MergeFunctions::replaceFunctionInTree(FnTreeType::iterator &IterToF,
1545 Function *G) {
1546 Function *F = IterToF->getFunc();
1547
1548 // A total order is already guaranteed otherwise because we process strong
1549 // functions before weak functions.
Denis Protivenskyc09e3762015-06-09 09:28:37 +00001550 assert(((F->mayBeOverridden() && G->mayBeOverridden()) ||
1551 (!F->mayBeOverridden() && !G->mayBeOverridden())) &&
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001552 "Only change functions if both are strong or both are weak");
Arnold Schwaighofer003c2e92015-06-09 00:17:40 +00001553 (void)F;
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001554
1555 IterToF->replaceBy(G);
1556}
1557
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001558// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001559// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001560bool MergeFunctions::insert(Function *NewFunction) {
1561 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001562 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001563
Nick Lewycky292e78c2011-02-09 06:32:02 +00001564 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001565 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001566 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001567 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001568
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001569 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001570
Matt Arsenault517d84e2013-10-01 18:05:30 +00001571 // Don't merge tiny functions, since it can just end up making the function
1572 // larger.
1573 // FIXME: Should still merge them if they are unnamed_addr and produce an
1574 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001575 if (NewFunction->size() == 1) {
1576 if (NewFunction->front().size() <= 2) {
1577 DEBUG(dbgs() << NewFunction->getName()
1578 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001579 return false;
1580 }
1581 }
1582
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001583 // Impose a total order (by name) on the replacement of functions. This is
1584 // important when operating on more than one module independently to prevent
1585 // cycles of thunks calling each other when the modules are linked together.
1586 //
1587 // When one function is weak and the other is strong there is an order imposed
1588 // already. We process strong functions before weak functions.
1589 if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
1590 (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
1591 if (OldF.getFunc()->getName() > NewFunction->getName()) {
1592 // Swap the two functions.
1593 Function *F = OldF.getFunc();
1594 replaceFunctionInTree(Result.first, NewFunction);
1595 NewFunction = F;
1596 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1597 }
1598
Nick Lewycky00959372010-09-05 08:22:49 +00001599 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001600 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001601
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001602 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1603 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001604
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001605 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001606 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001607 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001608}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001609
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001610// Remove a function from FnTree. If it was already in FnTree, add
1611// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001612void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001613 // We need to make sure we remove F, not a function "equal" to F per the
1614 // function equality comparator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001615 FnTreeType::iterator found = FnTree.find(FunctionNode(F));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001616 size_t Erased = 0;
1617 if (found != FnTree.end() && found->getFunc() == F) {
1618 Erased = 1;
1619 FnTree.erase(found);
1620 }
1621
1622 if (Erased) {
1623 DEBUG(dbgs() << "Removed " << F->getName()
1624 << " from set and deferred it.\n");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001625 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001626 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001627}
Nick Lewycky00959372010-09-05 08:22:49 +00001628
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001629// For each instruction used by the value, remove() the function that contains
1630// the instruction. This should happen right before a call to RAUW.
1631void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001632 std::vector<Value *> Worklist;
1633 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +00001634 SmallSet<Value*, 8> Visited;
1635 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +00001636 while (!Worklist.empty()) {
1637 Value *V = Worklist.back();
1638 Worklist.pop_back();
1639
Chandler Carruthcdf47882014-03-09 03:16:01 +00001640 for (User *U : V->users()) {
1641 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001642 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001643 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001644 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001645 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +00001646 for (User *UU : C->users()) {
1647 if (!Visited.insert(UU).second)
1648 Worklist.push_back(UU);
1649 }
Nick Lewycky5361b842011-01-02 19:16:44 +00001650 }
Nick Lewycky00959372010-09-05 08:22:49 +00001651 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001652 }
Nick Lewycky00959372010-09-05 08:22:49 +00001653}