blob: 5cf6c5ae8326d7d588ac705af97244275c56786d [file] [log] [blame]
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001//===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass looks for equivalent functions that are mergable and folds them.
11//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000012// A hash is computed from the function, based on its type and number of
13// basic blocks.
14//
15// Once all hashes are computed, we perform an expensive equality comparison
16// on each function pair. This takes n^2/2 comparisons per bucket, so it's
17// important that the hash function be high quality. The equality comparison
18// iterates through each instruction in each basic block.
19//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000020// When a match is found the functions are folded. If both functions are
21// overridable, we move the functionality into a new internal function and
22// leave two overridable thunks to it.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000023//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000028// * virtual functions.
29//
30// Many functions have their address taken by the virtual function table for
31// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000032// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000033//
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +000034// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000036//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000037// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000038//
39// In order to fold functions, we will sometimes add either bitcast instructions
40// or bitcast constant expressions. Unfortunately, this can confound further
41// analysis since the two functions differ where one has a bitcast and the
Nick Lewyckyfbd27572010-08-08 05:04:23 +000042// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000043//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000044//===----------------------------------------------------------------------===//
45
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000046#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/ADT/DenseSet.h"
48#include "llvm/ADT/FoldingSet.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/SmallSet.h"
51#include "llvm/ADT/Statistic.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000052#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000061#include "llvm/IR/ValueHandle.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000062#include "llvm/Pass.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +000063#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000064#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000065#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000066#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +000067#include <vector>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000068using namespace llvm;
69
Chandler Carruth964daaa2014-04-22 02:55:47 +000070#define DEBUG_TYPE "mergefunc"
71
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000072STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +000073STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +000074STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +000075STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000076
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +000077static cl::opt<unsigned> NumFunctionsForSanityCheck(
78 "mergefunc-sanity",
79 cl::desc("How many functions in module could be used for "
80 "MergeFunctions pass sanity check. "
81 "'0' disables this check. Works only with '-debug' key."),
82 cl::init(0), cl::Hidden);
83
Benjamin Kramer630e6e12013-04-19 23:06:44 +000084/// Returns the type id for a type to be hashed. We turn pointer types into
85/// integers here because the actual compare logic below considers pointers and
86/// integers of the same size as equal.
87static Type::TypeID getTypeIDForHash(Type *Ty) {
88 if (Ty->isPointerTy())
89 return Type::IntegerTyID;
90 return Ty->getTypeID();
91}
92
Nick Lewyckycfb284c2011-01-28 08:43:14 +000093/// Creates a hash-code for the function which is the same for any two
94/// functions that will compare equal, without looking at the instructions
95/// inside the function.
96static unsigned profileFunction(const Function *F) {
Chris Lattner229907c2011-07-18 04:54:35 +000097 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyfbd27572010-08-08 05:04:23 +000098
Nick Lewycky00959372010-09-05 08:22:49 +000099 FoldingSetNodeID ID;
100 ID.AddInteger(F->size());
101 ID.AddInteger(F->getCallingConv());
102 ID.AddBoolean(F->hasGC());
103 ID.AddBoolean(FTy->isVarArg());
Benjamin Kramer630e6e12013-04-19 23:06:44 +0000104 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
Nick Lewycky00959372010-09-05 08:22:49 +0000105 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramer630e6e12013-04-19 23:06:44 +0000106 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
Nick Lewycky00959372010-09-05 08:22:49 +0000107 return ID.ComputeHash();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000108}
109
Nick Lewycky71972d42010-09-07 01:42:10 +0000110namespace {
111
Nick Lewyckyaaf40122011-01-28 08:19:00 +0000112/// ComparableFunction - A struct that pairs together functions with a
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000113/// DataLayout so that we can keep them together as elements in the DenseSet.
Nick Lewycky00959372010-09-05 08:22:49 +0000114class ComparableFunction {
115public:
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000116 static const ComparableFunction EmptyKey;
117 static const ComparableFunction TombstoneKey;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000118 static DataLayout * const LookupOnly;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000119
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000120 ComparableFunction(Function *Func, const DataLayout *DL)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000121 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
Nick Lewycky00959372010-09-05 08:22:49 +0000122
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000123 Function *getFunc() const { return Func; }
124 unsigned getHash() const { return Hash; }
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000125 const DataLayout *getDataLayout() const { return DL; }
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000126
127 // Drops AssertingVH reference to the function. Outside of debug mode, this
128 // does nothing.
129 void release() {
130 assert(Func &&
131 "Attempted to release function twice, or release empty/tombstone!");
Craig Topperf40110f2014-04-25 05:29:35 +0000132 Func = nullptr;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000133 }
134
135private:
136 explicit ComparableFunction(unsigned Hash)
Craig Topperf40110f2014-04-25 05:29:35 +0000137 : Func(nullptr), Hash(Hash), DL(nullptr) {}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000138
139 AssertingVH<Function> Func;
140 unsigned Hash;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000141 const DataLayout *DL;
Nick Lewycky00959372010-09-05 08:22:49 +0000142};
143
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000144const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
145const ComparableFunction ComparableFunction::TombstoneKey =
146 ComparableFunction(1);
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000147DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000148
Nick Lewycky71972d42010-09-07 01:42:10 +0000149}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000150
151namespace llvm {
152 template <>
153 struct DenseMapInfo<ComparableFunction> {
154 static ComparableFunction getEmptyKey() {
155 return ComparableFunction::EmptyKey;
156 }
157 static ComparableFunction getTombstoneKey() {
158 return ComparableFunction::TombstoneKey;
159 }
160 static unsigned getHashValue(const ComparableFunction &CF) {
161 return CF.getHash();
162 }
163 static bool isEqual(const ComparableFunction &LHS,
164 const ComparableFunction &RHS);
165 };
166}
167
168namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000169
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000170/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000171/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000172/// used if available. The comparator always fails conservatively (erring on the
173/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000174class FunctionComparator {
175public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000176 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000177 const Function *F2)
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000178 : FnL(F1), FnR(F2), DL(DL) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000179
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000180 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000181 int compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000182
183private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000184 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000185 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000186
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000187 /// Constants comparison.
188 /// Its analog to lexicographical comparison between hypothetical numbers
189 /// of next format:
190 /// <bitcastability-trait><raw-bit-contents>
191 ///
192 /// 1. Bitcastability.
193 /// Check whether L's type could be losslessly bitcasted to R's type.
194 /// On this stage method, in case when lossless bitcast is not possible
195 /// method returns -1 or 1, thus also defining which type is greater in
196 /// context of bitcastability.
197 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
198 /// to the contents comparison.
199 /// If types differ, remember types comparison result and check
200 /// whether we still can bitcast types.
201 /// Stage 1: Types that satisfies isFirstClassType conditions are always
202 /// greater then others.
203 /// Stage 2: Vector is greater then non-vector.
204 /// If both types are vectors, then vector with greater bitwidth is
205 /// greater.
206 /// If both types are vectors with the same bitwidth, then types
207 /// are bitcastable, and we can skip other stages, and go to contents
208 /// comparison.
209 /// Stage 3: Pointer types are greater than non-pointers. If both types are
210 /// pointers of the same address space - go to contents comparison.
211 /// Different address spaces: pointer with greater address space is
212 /// greater.
213 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
214 /// We don't know how to bitcast them. So, we better don't do it,
215 /// and return types comparison result (so it determines the
216 /// relationship among constants we don't know how to bitcast).
217 ///
218 /// Just for clearance, let's see how the set of constants could look
219 /// on single dimension axis:
220 ///
221 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
222 /// Where: NFCT - Not a FirstClassType
223 /// FCT - FirstClassTyp:
224 ///
225 /// 2. Compare raw contents.
226 /// It ignores types on this stage and only compares bits from L and R.
227 /// Returns 0, if L and R has equivalent contents.
228 /// -1 or 1 if values are different.
229 /// Pretty trivial:
230 /// 2.1. If contents are numbers, compare numbers.
231 /// Ints with greater bitwidth are greater. Ints with same bitwidths
232 /// compared by their contents.
233 /// 2.2. "And so on". Just to avoid discrepancies with comments
234 /// perhaps it would be better to read the implementation itself.
235 /// 3. And again about overall picture. Let's look back at how the ordered set
236 /// of constants will look like:
237 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
238 ///
239 /// Now look, what could be inside [FCT, "others"], for example:
240 /// [FCT, "others"] =
241 /// [
242 /// [double 0.1], [double 1.23],
243 /// [i32 1], [i32 2],
244 /// { double 1.0 }, ; StructTyID, NumElements = 1
245 /// { i32 1 }, ; StructTyID, NumElements = 1
246 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
247 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
248 /// ]
249 ///
250 /// Let's explain the order. Float numbers will be less than integers, just
251 /// because of cmpType terms: FloatTyID < IntegerTyID.
252 /// Floats (with same fltSemantics) are sorted according to their value.
253 /// Then you can see integers, and they are, like a floats,
254 /// could be easy sorted among each others.
255 /// The structures. Structures are grouped at the tail, again because of their
256 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
257 /// Structures with greater number of elements are greater. Structures with
258 /// greater elements going first are greater.
259 /// The same logic with vectors, arrays and other possible complex types.
260 ///
261 /// Bitcastable constants.
262 /// Let's assume, that some constant, belongs to some group of
263 /// "so-called-equal" values with different types, and at the same time
264 /// belongs to another group of constants with equal types
265 /// and "really" equal values.
266 ///
267 /// Now, prove that this is impossible:
268 ///
269 /// If constant A with type TyA is bitcastable to B with type TyB, then:
270 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
271 /// those should be vectors (if TyA is vector), pointers
272 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
273 /// be equal to TyB.
274 /// 2. All constants with non-equal, but bitcastable types to TyA, are
275 /// bitcastable to B.
276 /// Once again, just because we allow it to vectors and pointers only.
277 /// This statement could be expanded as below:
278 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
279 /// vector B, and thus bitcastable to B as well.
280 /// 2.2. All pointers of the same address space, no matter what they point to,
281 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
282 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
283 /// QED.
284 ///
285 /// In another words, for pointers and vectors, we ignore top-level type and
286 /// look at their particular properties (bit-width for vectors, and
287 /// address space for pointers).
288 /// If these properties are equal - compare their contents.
289 int cmpConstants(const Constant *L, const Constant *R);
290
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000291 /// Assign or look up previously assigned numbers for the two values, and
292 /// return whether the numbers are equal. Numbers are assigned in the order
293 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000294 /// Comparison order:
295 /// Stage 0: Value that is function itself is always greater then others.
296 /// If left and right values are references to their functions, then
297 /// they are equal.
298 /// Stage 1: Constants are greater than non-constants.
299 /// If both left and right are constants, then the result of
300 /// cmpConstants is used as cmpValues result.
301 /// Stage 2: InlineAsm instances are greater than others. If both left and
302 /// right are InlineAsm instances, InlineAsm* pointers casted to
303 /// integers and compared as numbers.
304 /// Stage 3: For all other cases we compare order we meet these values in
305 /// their functions. If right value was met first during scanning,
306 /// then left value is greater.
307 /// In another words, we compare serial numbers, for more details
308 /// see comments for sn_mapL and sn_mapR.
309 int cmpValues(const Value *L, const Value *R);
310
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000311 /// Compare two Instructions for equivalence, similar to
312 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000313 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000314 /// Stages are listed in "most significant stage first" order:
315 /// On each stage below, we do comparison between some left and right
316 /// operation parts. If parts are non-equal, we assign parts comparison
317 /// result to the operation comparison result and exit from method.
318 /// Otherwise we proceed to the next stage.
319 /// Stages:
320 /// 1. Operations opcodes. Compared as numbers.
321 /// 2. Number of operands.
322 /// 3. Operation types. Compared with cmpType method.
323 /// 4. Compare operation subclass optional data as stream of bytes:
324 /// just convert it to integers and call cmpNumbers.
325 /// 5. Compare in operation operand types with cmpType in
326 /// most significant operand first order.
327 /// 6. Last stage. Check operations for some specific attributes.
328 /// For example, for Load it would be:
329 /// 6.1.Load: volatile (as boolean flag)
330 /// 6.2.Load: alignment (as integer numbers)
331 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000332 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000333 /// On this stage its better to see the code, since its not more than 10-15
334 /// strings for particular instruction, and could change sometimes.
335 int cmpOperation(const Instruction *L, const Instruction *R) const;
336
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000337 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000338 /// Parts to be compared for each comparison stage,
339 /// most significant stage first:
340 /// 1. Address space. As numbers.
341 /// 2. Constant offset, (if "DataLayout *DL" field is not NULL,
342 /// using GEPOperator::accumulateConstantOffset method).
343 /// 3. Pointer operand type (using cmpType method).
344 /// 4. Number of operands.
345 /// 5. Compare operands, using cmpValues method.
346 int cmpGEP(const GEPOperator *GEPL, const GEPOperator *GEPR);
347 int cmpGEP(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
348 return cmpGEP(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
349 }
350
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000351 /// cmpType - compares two types,
352 /// defines total ordering among the types set.
353 ///
354 /// Return values:
355 /// 0 if types are equal,
356 /// -1 if Left is less than Right,
357 /// +1 if Left is greater than Right.
358 ///
359 /// Description:
360 /// Comparison is broken onto stages. Like in lexicographical comparison
361 /// stage coming first has higher priority.
362 /// On each explanation stage keep in mind total ordering properties.
363 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000364 /// 0. Before comparison we coerce pointer types of 0 address space to
365 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000366 /// We also don't bother with same type at left and right, so
367 /// just return 0 in this case.
368 ///
369 /// 1. If types are of different kind (different type IDs).
370 /// Return result of type IDs comparison, treating them as numbers.
371 /// 2. If types are vectors or integers, compare Type* values as numbers.
372 /// 3. Types has same ID, so check whether they belongs to the next group:
373 /// * Void
374 /// * Float
375 /// * Double
376 /// * X86_FP80
377 /// * FP128
378 /// * PPC_FP128
379 /// * Label
380 /// * Metadata
381 /// If so - return 0, yes - we can treat these types as equal only because
382 /// their IDs are same.
383 /// 4. If Left and Right are pointers, return result of address space
384 /// comparison (numbers comparison). We can treat pointer types of same
385 /// address space as equal.
386 /// 5. If types are complex.
387 /// Then both Left and Right are to be expanded and their element types will
388 /// be checked with the same way. If we get Res != 0 on some stage, return it.
389 /// Otherwise return 0.
390 /// 6. For all other cases put llvm_unreachable.
391 int cmpType(Type *TyL, Type *TyR) const;
392
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000393 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000394
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000395 int cmpAPInt(const APInt &L, const APInt &R) const;
396 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000397 int cmpStrings(StringRef L, StringRef R) const;
398 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000399
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000400 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000401 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000402
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000403 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000404
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000405 /// Assign serial numbers to values from left function, and values from
406 /// right function.
407 /// Explanation:
408 /// Being comparing functions we need to compare values we meet at left and
409 /// right sides.
410 /// Its easy to sort things out for external values. It just should be
411 /// the same value at left and right.
412 /// But for local values (those were introduced inside function body)
413 /// we have to ensure they were introduced at exactly the same place,
414 /// and plays the same role.
415 /// Let's assign serial number to each value when we meet it first time.
416 /// Values that were met at same place will be with same serial numbers.
417 /// In this case it would be good to explain few points about values assigned
418 /// to BBs and other ways of implementation (see below).
419 ///
420 /// 1. Safety of BB reordering.
421 /// It's safe to change the order of BasicBlocks in function.
422 /// Relationship with other functions and serial numbering will not be
423 /// changed in this case.
424 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
425 /// from the entry, and then take each terminator. So it doesn't matter how in
426 /// fact BBs are ordered in function. And since cmpValues are called during
427 /// this walk, the numbering depends only on how BBs located inside the CFG.
428 /// So the answer is - yes. We will get the same numbering.
429 ///
430 /// 2. Impossibility to use dominance properties of values.
431 /// If we compare two instruction operands: first is usage of local
432 /// variable AL from function FL, and second is usage of local variable AR
433 /// from FR, we could compare their origins and check whether they are
434 /// defined at the same place.
435 /// But, we are still not able to compare operands of PHI nodes, since those
436 /// could be operands from further BBs we didn't scan yet.
437 /// So it's impossible to use dominance properties in general.
438 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000439};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000440
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000441class FunctionPtr {
442 AssertingVH<Function> F;
443 const DataLayout *DL;
444
445public:
446 FunctionPtr(Function *F, const DataLayout *DL) : F(F), DL(DL) {}
447 Function *getFunc() const { return F; }
448 void release() { F = 0; }
449 bool operator<(const FunctionPtr &RHS) const {
450 return (FunctionComparator(DL, F, RHS.getFunc()).compare()) == -1;
451 }
452};
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000453}
454
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000455int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
456 if (L < R) return -1;
457 if (L > R) return 1;
458 return 0;
459}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000460
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000461int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
462 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
463 return Res;
464 if (L.ugt(R)) return 1;
465 if (R.ugt(L)) return -1;
466 return 0;
467}
468
469int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
470 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
471 (uint64_t)&R.getSemantics()))
472 return Res;
473 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
474}
475
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000476int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
477 // Prevent heavy comparison, compare sizes first.
478 if (int Res = cmpNumbers(L.size(), R.size()))
479 return Res;
480
481 // Compare strings lexicographically only when it is necessary: only when
482 // strings are equal in size.
483 return L.compare(R);
484}
485
486int FunctionComparator::cmpAttrs(const AttributeSet L,
487 const AttributeSet R) const {
488 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
489 return Res;
490
491 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
492 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
493 RE = R.end(i);
494 for (; LI != LE && RI != RE; ++LI, ++RI) {
495 Attribute LA = *LI;
496 Attribute RA = *RI;
497 if (LA < RA)
498 return -1;
499 if (RA < LA)
500 return 1;
501 }
502 if (LI != LE)
503 return 1;
504 if (RI != RE)
505 return -1;
506 }
507 return 0;
508}
509
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000510/// Constants comparison:
511/// 1. Check whether type of L constant could be losslessly bitcasted to R
512/// type.
513/// 2. Compare constant contents.
514/// For more details see declaration comments.
515int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
516
517 Type *TyL = L->getType();
518 Type *TyR = R->getType();
519
520 // Check whether types are bitcastable. This part is just re-factored
521 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
522 // we also pack into result which type is "less" for us.
523 int TypesRes = cmpType(TyL, TyR);
524 if (TypesRes != 0) {
525 // Types are different, but check whether we can bitcast them.
526 if (!TyL->isFirstClassType()) {
527 if (TyR->isFirstClassType())
528 return -1;
529 // Neither TyL nor TyR are values of first class type. Return the result
530 // of comparing the types
531 return TypesRes;
532 }
533 if (!TyR->isFirstClassType()) {
534 if (TyL->isFirstClassType())
535 return 1;
536 return TypesRes;
537 }
538
539 // Vector -> Vector conversions are always lossless if the two vector types
540 // have the same size, otherwise not.
541 unsigned TyLWidth = 0;
542 unsigned TyRWidth = 0;
543
544 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
545 TyLWidth = VecTyL->getBitWidth();
546 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
547 TyRWidth = VecTyR->getBitWidth();
548
549 if (TyLWidth != TyRWidth)
550 return cmpNumbers(TyLWidth, TyRWidth);
551
552 // Zero bit-width means neither TyL nor TyR are vectors.
553 if (!TyLWidth) {
554 PointerType *PTyL = dyn_cast<PointerType>(TyL);
555 PointerType *PTyR = dyn_cast<PointerType>(TyR);
556 if (PTyL && PTyR) {
557 unsigned AddrSpaceL = PTyL->getAddressSpace();
558 unsigned AddrSpaceR = PTyR->getAddressSpace();
559 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
560 return Res;
561 }
562 if (PTyL)
563 return 1;
564 if (PTyR)
565 return -1;
566
567 // TyL and TyR aren't vectors, nor pointers. We don't know how to
568 // bitcast them.
569 return TypesRes;
570 }
571 }
572
573 // OK, types are bitcastable, now check constant contents.
574
575 if (L->isNullValue() && R->isNullValue())
576 return TypesRes;
577 if (L->isNullValue() && !R->isNullValue())
578 return 1;
579 if (!L->isNullValue() && R->isNullValue())
580 return -1;
581
582 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
583 return Res;
584
585 switch (L->getValueID()) {
586 case Value::UndefValueVal: return TypesRes;
587 case Value::ConstantIntVal: {
588 const APInt &LInt = cast<ConstantInt>(L)->getValue();
589 const APInt &RInt = cast<ConstantInt>(R)->getValue();
590 return cmpAPInt(LInt, RInt);
591 }
592 case Value::ConstantFPVal: {
593 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
594 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
595 return cmpAPFloat(LAPF, RAPF);
596 }
597 case Value::ConstantArrayVal: {
598 const ConstantArray *LA = cast<ConstantArray>(L);
599 const ConstantArray *RA = cast<ConstantArray>(R);
600 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
601 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
602 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
603 return Res;
604 for (uint64_t i = 0; i < NumElementsL; ++i) {
605 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
606 cast<Constant>(RA->getOperand(i))))
607 return Res;
608 }
609 return 0;
610 }
611 case Value::ConstantStructVal: {
612 const ConstantStruct *LS = cast<ConstantStruct>(L);
613 const ConstantStruct *RS = cast<ConstantStruct>(R);
614 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
615 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
616 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
617 return Res;
618 for (unsigned i = 0; i != NumElementsL; ++i) {
619 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
620 cast<Constant>(RS->getOperand(i))))
621 return Res;
622 }
623 return 0;
624 }
625 case Value::ConstantVectorVal: {
626 const ConstantVector *LV = cast<ConstantVector>(L);
627 const ConstantVector *RV = cast<ConstantVector>(R);
628 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
629 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
630 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
631 return Res;
632 for (uint64_t i = 0; i < NumElementsL; ++i) {
633 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
634 cast<Constant>(RV->getOperand(i))))
635 return Res;
636 }
637 return 0;
638 }
639 case Value::ConstantExprVal: {
640 const ConstantExpr *LE = cast<ConstantExpr>(L);
641 const ConstantExpr *RE = cast<ConstantExpr>(R);
642 unsigned NumOperandsL = LE->getNumOperands();
643 unsigned NumOperandsR = RE->getNumOperands();
644 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
645 return Res;
646 for (unsigned i = 0; i < NumOperandsL; ++i) {
647 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
648 cast<Constant>(RE->getOperand(i))))
649 return Res;
650 }
651 return 0;
652 }
653 case Value::FunctionVal:
654 case Value::GlobalVariableVal:
655 case Value::GlobalAliasVal:
656 default: // Unknown constant, cast L and R pointers to numbers and compare.
657 return cmpNumbers((uint64_t)L, (uint64_t)R);
658 }
659}
660
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000661/// cmpType - compares two types,
662/// defines total ordering among the types set.
663/// See method declaration comments for more details.
664int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
665
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000666 PointerType *PTyL = dyn_cast<PointerType>(TyL);
667 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000668
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000669 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000670 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
671 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000672 }
673
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000674 if (TyL == TyR)
675 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000676
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000677 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
678 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000679
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000680 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000681 default:
682 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000683 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000684 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000685 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000686 // TyL == TyR would have returned true earlier.
687 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000688
Nick Lewyckye04dc222009-06-12 08:04:51 +0000689 case Type::VoidTyID:
690 case Type::FloatTyID:
691 case Type::DoubleTyID:
692 case Type::X86_FP80TyID:
693 case Type::FP128TyID:
694 case Type::PPC_FP128TyID:
695 case Type::LabelTyID:
696 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000697 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000698
Nick Lewyckye04dc222009-06-12 08:04:51 +0000699 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000700 assert(PTyL && PTyR && "Both types must be pointers here.");
701 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000702 }
703
704 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000705 StructType *STyL = cast<StructType>(TyL);
706 StructType *STyR = cast<StructType>(TyR);
707 if (STyL->getNumElements() != STyR->getNumElements())
708 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000709
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000710 if (STyL->isPacked() != STyR->isPacked())
711 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000712
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000713 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
714 if (int Res = cmpType(STyL->getElementType(i),
715 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000716 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000717 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000718 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000719 }
720
721 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000722 FunctionType *FTyL = cast<FunctionType>(TyL);
723 FunctionType *FTyR = cast<FunctionType>(TyR);
724 if (FTyL->getNumParams() != FTyR->getNumParams())
725 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000726
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000727 if (FTyL->isVarArg() != FTyR->isVarArg())
728 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000729
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000730 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000731 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000732
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000733 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
734 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000735 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000736 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000737 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000738 }
739
Nick Lewycky375efe32010-07-16 06:31:12 +0000740 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000741 ArrayType *ATyL = cast<ArrayType>(TyL);
742 ArrayType *ATyR = cast<ArrayType>(TyR);
743 if (ATyL->getNumElements() != ATyR->getNumElements())
744 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
745 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000746 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000747 }
748}
749
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000750// Determine whether the two operations are the same except that pointer-to-A
751// and pointer-to-B are equivalent. This should be kept in sync with
752// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000753// Read method declaration comments for more details.
754int FunctionComparator::cmpOperation(const Instruction *L,
755 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000756 // Differences from Instruction::isSameOperationAs:
757 // * replace type comparison with calls to isEquivalentType.
758 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
759 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000760 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
761 return Res;
762
763 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
764 return Res;
765
766 if (int Res = cmpType(L->getType(), R->getType()))
767 return Res;
768
769 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
770 R->getRawSubclassOptionalData()))
771 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000772
773 // We have two instructions of identical opcode and #operands. Check to see
774 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000775 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
776 if (int Res =
777 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
778 return Res;
779 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000780
781 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000782 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
783 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
784 return Res;
785 if (int Res =
786 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
787 return Res;
788 if (int Res =
789 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
790 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000791 if (int Res =
792 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
793 return Res;
794 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
795 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000796 }
797 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
798 if (int Res =
799 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
800 return Res;
801 if (int Res =
802 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
803 return Res;
804 if (int Res =
805 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
806 return Res;
807 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
808 }
809 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
810 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
811 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
812 if (int Res = cmpNumbers(CI->getCallingConv(),
813 cast<CallInst>(R)->getCallingConv()))
814 return Res;
815 return cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes());
816 }
817 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
818 if (int Res = cmpNumbers(CI->getCallingConv(),
819 cast<InvokeInst>(R)->getCallingConv()))
820 return Res;
821 return cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes());
822 }
823 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
824 ArrayRef<unsigned> LIndices = IVI->getIndices();
825 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
826 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
827 return Res;
828 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
829 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
830 return Res;
831 }
832 }
833 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
834 ArrayRef<unsigned> LIndices = EVI->getIndices();
835 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
836 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
837 return Res;
838 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
839 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
840 return Res;
841 }
842 }
843 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
844 if (int Res =
845 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
846 return Res;
847 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
848 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000849
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000850 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
851 if (int Res = cmpNumbers(CXI->isVolatile(),
852 cast<AtomicCmpXchgInst>(R)->isVolatile()))
853 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000854 if (int Res = cmpNumbers(CXI->isWeak(),
855 cast<AtomicCmpXchgInst>(R)->isWeak()))
856 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000857 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
858 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
859 return Res;
860 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
861 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
862 return Res;
863 return cmpNumbers(CXI->getSynchScope(),
864 cast<AtomicCmpXchgInst>(R)->getSynchScope());
865 }
866 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
867 if (int Res = cmpNumbers(RMWI->getOperation(),
868 cast<AtomicRMWInst>(R)->getOperation()))
869 return Res;
870 if (int Res = cmpNumbers(RMWI->isVolatile(),
871 cast<AtomicRMWInst>(R)->isVolatile()))
872 return Res;
873 if (int Res = cmpNumbers(RMWI->getOrdering(),
874 cast<AtomicRMWInst>(R)->getOrdering()))
875 return Res;
876 return cmpNumbers(RMWI->getSynchScope(),
877 cast<AtomicRMWInst>(R)->getSynchScope());
878 }
879 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000880}
881
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000882// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000883// Read method declaration comments for more details.
884int FunctionComparator::cmpGEP(const GEPOperator *GEPL,
885 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000886
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000887 unsigned int ASL = GEPL->getPointerAddressSpace();
888 unsigned int ASR = GEPR->getPointerAddressSpace();
889
890 if (int Res = cmpNumbers(ASL, ASR))
891 return Res;
892
893 // When we have target data, we can reduce the GEP down to the value in bytes
894 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000895 if (DL) {
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000896 unsigned BitWidth = DL->getPointerSizeInBits(ASL);
897 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
898 if (GEPL->accumulateConstantOffset(*DL, OffsetL) &&
899 GEPR->accumulateConstantOffset(*DL, OffsetR))
900 return cmpAPInt(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000901 }
902
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000903 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
904 (uint64_t)GEPR->getPointerOperand()->getType()))
905 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000906
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000907 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
908 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000909
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000910 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
911 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
912 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000913 }
914
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000915 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000916}
917
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000918/// Compare two values used by the two functions under pair-wise comparison. If
919/// this is the first time the values are seen, they're added to the mapping so
920/// that we will detect mismatches on next use.
921/// See comments in declaration for more details.
922int FunctionComparator::cmpValues(const Value *L, const Value *R) {
923 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000924 if (L == FnL) {
925 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000926 return 0;
927 return -1;
928 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000929 if (R == FnR) {
930 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000931 return 0;
932 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000933 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000934
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000935 const Constant *ConstL = dyn_cast<Constant>(L);
936 const Constant *ConstR = dyn_cast<Constant>(R);
937 if (ConstL && ConstR) {
938 if (L == R)
939 return 0;
940 return cmpConstants(ConstL, ConstR);
941 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000942
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000943 if (ConstL)
944 return 1;
945 if (ConstR)
946 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000947
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000948 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
949 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
950
951 if (InlineAsmL && InlineAsmR)
952 return cmpNumbers((uint64_t)L, (uint64_t)R);
953 if (InlineAsmL)
954 return 1;
955 if (InlineAsmR)
956 return -1;
957
958 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
959 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
960
961 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000962}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000963// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000964int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
965 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
966 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000967
968 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000969 if (int Res = cmpValues(InstL, InstR))
970 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000971
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000972 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
973 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +0000974
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000975 if (GEPL && !GEPR)
976 return 1;
977 if (GEPR && !GEPL)
978 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000979
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000980 if (GEPL && GEPR) {
981 if (int Res =
982 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
983 return Res;
984 if (int Res = cmpGEP(GEPL, GEPR))
985 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000986 } else {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000987 if (int Res = cmpOperation(InstL, InstR))
988 return Res;
989 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000990
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000991 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
992 Value *OpL = InstL->getOperand(i);
993 Value *OpR = InstR->getOperand(i);
994 if (int Res = cmpValues(OpL, OpR))
995 return Res;
996 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
997 return Res;
998 // TODO: Already checked in cmpOperation
999 if (int Res = cmpType(OpL->getType(), OpR->getType()))
1000 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001001 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001002 }
1003
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001004 ++InstL, ++InstR;
1005 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001006
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001007 if (InstL != InstLE && InstR == InstRE)
1008 return 1;
1009 if (InstL == InstLE && InstR != InstRE)
1010 return -1;
1011 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001012}
1013
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001014// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001015int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001016
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001017 sn_mapL.clear();
1018 sn_mapR.clear();
1019
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001020 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1021 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001022
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001023 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1024 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001025
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001026 if (FnL->hasGC()) {
1027 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1028 return Res;
1029 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001030
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001031 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1032 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001033
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001034 if (FnL->hasSection()) {
1035 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1036 return Res;
1037 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001038
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001039 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1040 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001041
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001042 // TODO: if it's internal and only used in direct calls, we could handle this
1043 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001044 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1045 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001046
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001047 if (int Res = cmpType(FnL->getFunctionType(), FnR->getFunctionType()))
1048 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001049
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001050 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001051 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001052
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001053 // Visit the arguments so that they get enumerated in the order they're
1054 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001055 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1056 ArgRI = FnR->arg_begin(),
1057 ArgLE = FnL->arg_end();
1058 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1059 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001060 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001061 }
1062
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001063 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1064 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001065 // functions, then takes each block from each terminator in order. As an
1066 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001067 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001068 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001069
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001070 FnLBBs.push_back(&FnL->getEntryBlock());
1071 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001072
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001073 VisitedBBs.insert(FnLBBs[0]);
1074 while (!FnLBBs.empty()) {
1075 const BasicBlock *BBL = FnLBBs.pop_back_val();
1076 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001077
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001078 if (int Res = cmpValues(BBL, BBR))
1079 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001080
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001081 if (int Res = compare(BBL, BBR))
1082 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001083
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001084 const TerminatorInst *TermL = BBL->getTerminator();
1085 const TerminatorInst *TermR = BBR->getTerminator();
1086
1087 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1088 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1089 if (!VisitedBBs.insert(TermL->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001090 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001091
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001092 FnLBBs.push_back(TermL->getSuccessor(i));
1093 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001094 }
1095 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001096 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001097}
1098
Nick Lewycky564fcca2011-01-28 07:36:21 +00001099namespace {
1100
1101/// MergeFunctions finds functions which will generate identical machine code,
1102/// by considering all pointer types to be equivalent. Once identified,
1103/// MergeFunctions will fold them by replacing a call to one to a call to a
1104/// bitcast of the other.
1105///
1106class MergeFunctions : public ModulePass {
1107public:
1108 static char ID;
1109 MergeFunctions()
1110 : ModulePass(ID), HasGlobalAliases(false) {
1111 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1112 }
1113
Craig Topper3e4c6972014-03-05 09:10:37 +00001114 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001115
1116private:
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001117 typedef std::set<FunctionPtr> FnTreeType;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001118
1119 /// A work queue of functions that may have been modified and should be
1120 /// analyzed again.
1121 std::vector<WeakVH> Deferred;
1122
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001123 /// Checks the rules of order relation introduced among functions set.
1124 /// Returns true, if sanity check has been passed, and false if failed.
1125 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1126
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001127 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001128 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001129 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001130
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001131 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001132 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001133 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001134
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001135 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001136 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001137 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001138
1139 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1140 /// necessary to make types match.
1141 void replaceDirectCallers(Function *Old, Function *New);
1142
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001143 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1144 /// be converted into a thunk. In either case, it should never be visited
1145 /// again.
1146 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001147
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001148 /// Replace G with a thunk or an alias to F. Deletes G.
1149 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001150
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001151 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1152 /// of G with bitcast(F). Deletes G.
1153 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001154
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001155 /// Replace G with an alias to F. Deletes G.
1156 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001157
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001158 /// The set of all distinct functions. Use the insert() and remove() methods
1159 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001160 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001161
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001162 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001163 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001164
1165 /// Whether or not the target supports global aliases.
1166 bool HasGlobalAliases;
1167};
1168
1169} // end anonymous namespace
1170
1171char MergeFunctions::ID = 0;
1172INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1173
1174ModulePass *llvm::createMergeFunctionsPass() {
1175 return new MergeFunctions();
1176}
1177
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001178bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1179 if (const unsigned Max = NumFunctionsForSanityCheck) {
1180 unsigned TripleNumber = 0;
1181 bool Valid = true;
1182
1183 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1184
1185 unsigned i = 0;
1186 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1187 I != E && i < Max; ++I, ++i) {
1188 unsigned j = i;
1189 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1190 Function *F1 = cast<Function>(*I);
1191 Function *F2 = cast<Function>(*J);
1192 int Res1 = FunctionComparator(DL, F1, F2).compare();
1193 int Res2 = FunctionComparator(DL, F2, F1).compare();
1194
1195 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1196 if (Res1 != -Res2) {
1197 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1198 << "\n";
1199 F1->dump();
1200 F2->dump();
1201 Valid = false;
1202 }
1203
1204 if (Res1 == 0)
1205 continue;
1206
1207 unsigned k = j;
1208 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1209 ++k, ++K, ++TripleNumber) {
1210 if (K == J)
1211 continue;
1212
1213 Function *F3 = cast<Function>(*K);
1214 int Res3 = FunctionComparator(DL, F1, F3).compare();
1215 int Res4 = FunctionComparator(DL, F2, F3).compare();
1216
1217 bool Transitive = true;
1218
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001219 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001220 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001221 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001222 } else if (Res3 != 0 && Res3 == -Res4) {
1223 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001224 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001225 } else if (Res4 != 0 && -Res3 == Res4) {
1226 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001227 Transitive = Res4 == -Res1;
1228 }
1229
1230 if (!Transitive) {
1231 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1232 << TripleNumber << "\n";
1233 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1234 << Res4 << "\n";
1235 F1->dump();
1236 F2->dump();
1237 F3->dump();
1238 Valid = false;
1239 }
1240 }
1241 }
1242 }
1243
1244 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1245 return Valid;
1246 }
1247 return true;
1248}
1249
Nick Lewycky564fcca2011-01-28 07:36:21 +00001250bool MergeFunctions::runOnModule(Module &M) {
1251 bool Changed = false;
Rafael Espindola93512512014-02-25 17:30:31 +00001252 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001253 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001254
1255 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1256 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1257 Deferred.push_back(WeakVH(I));
1258 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001259
1260 do {
1261 std::vector<WeakVH> Worklist;
1262 Deferred.swap(Worklist);
1263
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001264 DEBUG(doSanityCheck(Worklist));
1265
Nick Lewycky564fcca2011-01-28 07:36:21 +00001266 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1267 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1268
1269 // Insert only strong functions and merge them. Strong function merging
1270 // always deletes one of them.
1271 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1272 E = Worklist.end(); I != E; ++I) {
1273 if (!*I) continue;
1274 Function *F = cast<Function>(*I);
1275 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1276 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001277 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001278 }
1279 }
1280
1281 // Insert only weak functions and merge them. By doing these second we
1282 // create thunks to the strong function when possible. When two weak
1283 // functions are identical, we create a new strong function with two weak
1284 // weak thunks to it which are identical but not mergable.
1285 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1286 E = Worklist.end(); I != E; ++I) {
1287 if (!*I) continue;
1288 Function *F = cast<Function>(*I);
1289 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1290 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001291 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001292 }
1293 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001294 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001295 } while (!Deferred.empty());
1296
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001297 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001298
1299 return Changed;
1300}
1301
1302bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1303 const ComparableFunction &RHS) {
1304 if (LHS.getFunc() == RHS.getFunc() &&
1305 LHS.getHash() == RHS.getHash())
1306 return true;
1307 if (!LHS.getFunc() || !RHS.getFunc())
1308 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001309
1310 // One of these is a special "underlying pointer comparison only" object.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001311 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1312 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky292e78c2011-02-09 06:32:02 +00001313 return false;
1314
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001315 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky564fcca2011-01-28 07:36:21 +00001316 "Comparing functions for different targets");
1317
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001318 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(), RHS.getFunc())
1319 .compare() == 0;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001320}
1321
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001322// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001323void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1324 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001325 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1326 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001327 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001328 CallSite CS(U->getUser());
1329 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001330 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001331 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001332 }
1333 }
1334}
1335
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001336// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1337void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001338 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1339 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1340 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001341 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001342 return;
1343 }
1344 }
1345
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001346 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001347}
1348
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001349// Helper for writeThunk,
1350// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001351// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001352static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001353 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001354 if (SrcTy->isStructTy()) {
1355 assert(DestTy->isStructTy());
1356 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1357 Value *Result = UndefValue::get(DestTy);
1358 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1359 Value *Element = createCast(
1360 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1361 DestTy->getStructElementType(I));
1362
1363 Result =
1364 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1365 }
1366 return Result;
1367 }
1368 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001369 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1370 return Builder.CreateIntToPtr(V, DestTy);
1371 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1372 return Builder.CreatePtrToInt(V, DestTy);
1373 else
1374 return Builder.CreateBitCast(V, DestTy);
1375}
1376
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001377// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1378// of G with bitcast(F). Deletes G.
1379void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001380 if (!G->mayBeOverridden()) {
1381 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001382 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001383 }
1384
Nick Lewycky71972d42010-09-07 01:42:10 +00001385 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001386 // stop here and delete G. There's no need for a thunk.
1387 if (G->hasLocalLinkage() && G->use_empty()) {
1388 G->eraseFromParent();
1389 return;
1390 }
1391
Nick Lewycky25675ac2009-06-12 15:56:56 +00001392 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1393 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001394 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001395 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001396
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001397 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001398 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001399 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001400 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1401 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001402 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001403 ++i;
1404 }
1405
Jay Foad5bd375a2011-07-15 08:37:34 +00001406 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001407 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001408 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001409 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001410 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001411 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001412 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001413 }
1414
1415 NewG->copyAttributesFrom(G);
1416 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001417 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001418 G->replaceAllUsesWith(NewG);
1419 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001420
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001421 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001422 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001423}
1424
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001425// Replace G with an alias to F and delete G.
1426void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001427 PointerType *PTy = G->getType();
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001428 auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1429 G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001430 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1431 GA->takeName(G);
1432 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001433 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001434 G->replaceAllUsesWith(GA);
1435 G->eraseFromParent();
1436
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001437 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001438 ++NumAliasesWritten;
1439}
1440
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001441// Merge two equivalent functions. Upon completion, Function G is deleted.
1442void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001443 if (F->mayBeOverridden()) {
1444 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001445
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001446 if (HasGlobalAliases) {
1447 // Make them both thunks to the same internal function.
1448 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1449 F->getParent());
1450 H->copyAttributesFrom(F);
1451 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001452 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001453 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001454
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001455 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001456
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001457 writeAlias(F, G);
1458 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001459
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001460 F->setAlignment(MaxAlignment);
1461 F->setLinkage(GlobalValue::PrivateLinkage);
1462 } else {
1463 // We can't merge them. Instead, pick one and update all direct callers
1464 // to call it and hope that we improve the instruction cache hit rate.
1465 replaceDirectCallers(G, F);
1466 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001467
1468 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001469 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001470 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001471 }
1472
Nick Lewyckye04dc222009-06-12 08:04:51 +00001473 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001474}
1475
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001476// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001477// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001478bool MergeFunctions::insert(Function *NewFunction) {
1479 std::pair<FnTreeType::iterator, bool> Result =
1480 FnTree.insert(FunctionPtr(NewFunction, DL));
1481
Nick Lewycky292e78c2011-02-09 06:32:02 +00001482 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001483 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001484 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001485 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001486
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001487 const FunctionPtr &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001488
Matt Arsenault517d84e2013-10-01 18:05:30 +00001489 // Don't merge tiny functions, since it can just end up making the function
1490 // larger.
1491 // FIXME: Should still merge them if they are unnamed_addr and produce an
1492 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001493 if (NewFunction->size() == 1) {
1494 if (NewFunction->front().size() <= 2) {
1495 DEBUG(dbgs() << NewFunction->getName()
1496 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001497 return false;
1498 }
1499 }
1500
Nick Lewycky00959372010-09-05 08:22:49 +00001501 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001502 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001503
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001504 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1505 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001506
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001507 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001508 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001509 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001510}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001511
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001512// Remove a function from FnTree. If it was already in FnTree, add
1513// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001514void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001515 // We need to make sure we remove F, not a function "equal" to F per the
1516 // function equality comparator.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001517 FnTreeType::iterator found = FnTree.find(FunctionPtr(F, DL));
1518 size_t Erased = 0;
1519 if (found != FnTree.end() && found->getFunc() == F) {
1520 Erased = 1;
1521 FnTree.erase(found);
1522 }
1523
1524 if (Erased) {
1525 DEBUG(dbgs() << "Removed " << F->getName()
1526 << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001527 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001528 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001529}
Nick Lewycky00959372010-09-05 08:22:49 +00001530
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001531// For each instruction used by the value, remove() the function that contains
1532// the instruction. This should happen right before a call to RAUW.
1533void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001534 std::vector<Value *> Worklist;
1535 Worklist.push_back(V);
1536 while (!Worklist.empty()) {
1537 Value *V = Worklist.back();
1538 Worklist.pop_back();
1539
Chandler Carruthcdf47882014-03-09 03:16:01 +00001540 for (User *U : V->users()) {
1541 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001542 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001543 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001544 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001545 } else if (Constant *C = dyn_cast<Constant>(U)) {
1546 for (User *UU : C->users())
1547 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001548 }
Nick Lewycky00959372010-09-05 08:22:49 +00001549 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001550 }
Nick Lewycky00959372010-09-05 08:22:49 +00001551}