blob: 11efe95b10d4e0c9c85defe0dbe33d5246edd92b [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.
Fangrui Songf78650a2018-07-30 19:41:25 +000030//
JF Bastien5e4303d2015-08-15 01:18:18 +000031// 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
Eugene Zelenkof27d1612017-10-19 21:21:30 +000092#include "llvm/ADT/ArrayRef.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000093#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000094#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000095#include "llvm/ADT/Statistic.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000096#include "llvm/IR/Argument.h"
97#include "llvm/IR/Attributes.h"
98#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000099#include "llvm/IR/CallSite.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000100#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000101#include "llvm/IR/Constants.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000102#include "llvm/IR/DebugInfoMetadata.h"
103#include "llvm/IR/DebugLoc.h"
104#include "llvm/IR/DerivedTypes.h"
105#include "llvm/IR/Function.h"
106#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000107#include "llvm/IR/IRBuilder.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000108#include "llvm/IR/InstrTypes.h"
109#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000110#include "llvm/IR/Instructions.h"
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000111#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000112#include "llvm/IR/Module.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000113#include "llvm/IR/Type.h"
114#include "llvm/IR/Use.h"
115#include "llvm/IR/User.h"
116#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +0000117#include "llvm/IR/ValueHandle.h"
JF Bastien057292a2015-08-21 23:27:24 +0000118#include "llvm/IR/ValueMap.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000119#include "llvm/Pass.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000120#include "llvm/Support/Casting.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000121#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000122#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000123#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +0000124#include "llvm/Transforms/IPO.h"
Erik Eckstein4d6fb722016-11-11 21:15:13 +0000125#include "llvm/Transforms/Utils/FunctionComparator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000126#include <algorithm>
127#include <cassert>
128#include <iterator>
129#include <set>
130#include <utility>
Nick Lewycky68984ed2010-08-31 08:29:37 +0000131#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000132
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000133using namespace llvm;
134
Chandler Carruth964daaa2014-04-22 02:55:47 +0000135#define DEBUG_TYPE "mergefunc"
136
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000137STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000138STATISTIC(NumThunksWritten, "Number of thunks generated");
Nikita Popov6f54fb02018-11-21 19:37:19 +0000139STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000140STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000141
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000142static cl::opt<unsigned> NumFunctionsForSanityCheck(
143 "mergefunc-sanity",
144 cl::desc("How many functions in module could be used for "
145 "MergeFunctions pass sanity check. "
146 "'0' disables this check. Works only with '-debug' key."),
147 cl::init(0), cl::Hidden);
148
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000149// Under option -mergefunc-preserve-debug-info we:
150// - Do not create a new function for a thunk.
151// - Retain the debug info for a thunk's parameters (and associated
152// instructions for the debug info) from the entry block.
153// Note: -debug will display the algorithm at work.
154// - Create debug-info for the call (to the shared implementation) made by
155// a thunk and its return value.
156// - Erase the rest of the function, retaining the (minimally sized) entry
157// block to create a thunk.
158// - Preserve a thunk's call site to point to the thunk even when both occur
159// within the same translation unit, to aid debugability. Note that this
160// behaviour differs from the underlying -mergefunc implementation which
161// modifies the thunk's call site to point to the shared implementation
162// when both occur within the same translation unit.
163static cl::opt<bool>
164 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
165 cl::init(false),
166 cl::desc("Preserve debug info in thunk when mergefunc "
167 "transformations are made."));
168
Nikita Popov6f54fb02018-11-21 19:37:19 +0000169static cl::opt<bool>
170 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
171 cl::init(false),
172 cl::desc("Allow mergefunc to create aliases"));
173
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000174namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000175
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000176class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000177 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000178 FunctionComparator::FunctionHash Hash;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000179
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000180public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000181 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000182 FunctionNode(Function *F)
183 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000184
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000185 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000186 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000187
188 /// Replace the reference to the function F by the function G, assuming their
189 /// implementations are equal.
190 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000191 F = G;
192 }
193
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000194 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000195};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000196
197/// MergeFunctions finds functions which will generate identical machine code,
198/// by considering all pointer types to be equivalent. Once identified,
199/// MergeFunctions will fold them by replacing a call to one to a call to a
200/// bitcast of the other.
Nick Lewycky564fcca2011-01-28 07:36:21 +0000201class MergeFunctions : public ModulePass {
202public:
203 static char ID;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000204
Nick Lewycky564fcca2011-01-28 07:36:21 +0000205 MergeFunctions()
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000206 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
Nick Lewycky564fcca2011-01-28 07:36:21 +0000207 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
208 }
209
Craig Topper3e4c6972014-03-05 09:10:37 +0000210 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000211
212private:
JF Bastien057292a2015-08-21 23:27:24 +0000213 // The function comparison operator is provided here so that FunctionNodes do
214 // not need to become larger with another pointer.
215 class FunctionNodeCmp {
216 GlobalNumberState* GlobalNumbers;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000217
JF Bastien057292a2015-08-21 23:27:24 +0000218 public:
219 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000220
JF Bastien057292a2015-08-21 23:27:24 +0000221 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
222 // Order first by hashes, then full function comparison.
223 if (LHS.getHash() != RHS.getHash())
224 return LHS.getHash() < RHS.getHash();
225 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
226 return FCmp.compare() == -1;
227 }
228 };
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000229 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
JF Bastien057292a2015-08-21 23:27:24 +0000230
231 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000232
233 /// A work queue of functions that may have been modified and should be
234 /// analyzed again.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000235 std::vector<WeakTrackingVH> Deferred;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000236
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000237#ifndef NDEBUG
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000238 /// Checks the rules of order relation introduced among functions set.
239 /// Returns true, if sanity check has been passed, and false if failed.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000240 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
Davide Italianob6681e22017-04-28 19:39:45 +0000241#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000242
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000243 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +0000244 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000245 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000246
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000247 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +0000248 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000249 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000250
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000251 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +0000252 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000253 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000254
255 /// Replace all direct calls of Old with calls of New. Will bitcast New if
256 /// necessary to make types match.
257 void replaceDirectCallers(Function *Old, Function *New);
258
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000259 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
260 /// be converted into a thunk. In either case, it should never be visited
261 /// again.
262 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000263
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000264 /// Fill PDIUnrelatedWL with instructions from the entry block that are
265 /// unrelated to parameter related debug info.
266 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
267 std::vector<Instruction *> &PDIUnrelatedWL);
268
269 /// Erase the rest of the CFG (i.e. barring the entry block).
270 void eraseTail(Function *G);
271
272 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
273 /// parameter debug info, from the entry block.
274 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
275
276 /// Replace G with a simple tail call to bitcast(F). Also (unless
277 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
278 /// delete G.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000279 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000280
Nikita Popov6f54fb02018-11-21 19:37:19 +0000281 // Replace G with an alias to F (deleting function G)
282 void writeAlias(Function *F, Function *G);
283
284 // Replace G with an alias to F if possible, or a thunk to F if
285 // profitable. Returns false if neither is the case.
286 bool writeThunkOrAlias(Function *F, Function *G);
287
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000288 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +0000289 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000290
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000291 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +0000292 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000293 FnTreeType FnTree;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000294
JF Bastien3a4ad612015-09-02 23:55:23 +0000295 // Map functions to the iterators of the FunctionNode which contains them
296 // in the FnTree. This must be updated carefully whenever the FnTree is
297 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
298 // dangling iterators into FnTree. The invariant that preserves this is that
299 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
whitequark73cb9782018-11-08 03:58:01 +0000300 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000301};
302
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000303} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +0000304
305char MergeFunctions::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000306
Nick Lewycky564fcca2011-01-28 07:36:21 +0000307INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
308
309ModulePass *llvm::createMergeFunctionsPass() {
310 return new MergeFunctions();
311}
312
Davide Italianob6681e22017-04-28 19:39:45 +0000313#ifndef NDEBUG
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000314bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000315 if (const unsigned Max = NumFunctionsForSanityCheck) {
316 unsigned TripleNumber = 0;
317 bool Valid = true;
318
319 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
320
321 unsigned i = 0;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000322 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
323 E = Worklist.end();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000324 I != E && i < Max; ++I, ++i) {
325 unsigned j = i;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000326 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
327 ++J, ++j) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000328 Function *F1 = cast<Function>(*I);
329 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +0000330 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
331 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000332
333 // If F1 <= F2, then F2 >= F1, otherwise report failure.
334 if (Res1 != -Res2) {
335 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
336 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000337 dbgs() << *F1 << '\n' << *F2 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000338 Valid = false;
339 }
340
341 if (Res1 == 0)
342 continue;
343
344 unsigned k = j;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000345 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000346 ++k, ++K, ++TripleNumber) {
347 if (K == J)
348 continue;
349
350 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +0000351 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
352 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000353
354 bool Transitive = true;
355
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000356 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000357 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000358 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000359 } else if (Res3 != 0 && Res3 == -Res4) {
360 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000361 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000362 } else if (Res4 != 0 && -Res3 == Res4) {
363 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000364 Transitive = Res4 == -Res1;
365 }
366
367 if (!Transitive) {
368 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
369 << TripleNumber << "\n";
370 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
371 << Res4 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000372 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000373 Valid = false;
374 }
375 }
376 }
377 }
378
379 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
380 return Valid;
381 }
382 return true;
383}
Davide Italianob6681e22017-04-28 19:39:45 +0000384#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000385
Nick Lewycky564fcca2011-01-28 07:36:21 +0000386bool MergeFunctions::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000387 if (skipModule(M))
388 return false;
389
Nick Lewycky564fcca2011-01-28 07:36:21 +0000390 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000391
JF Bastien5e4303d2015-08-15 01:18:18 +0000392 // All functions in the module, ordered by hash. Functions with a unique
393 // hash value are easily eliminated.
394 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
395 HashedFuncs;
396 for (Function &Func : M) {
397 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
398 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
Fangrui Songf78650a2018-07-30 19:41:25 +0000399 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000400 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000401
NAKAMURA Takumi51962752015-08-16 02:41:23 +0000402 std::stable_sort(
403 HashedFuncs.begin(), HashedFuncs.end(),
404 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
405 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
406 return a.first < b.first;
407 });
JF Bastien5e4303d2015-08-15 01:18:18 +0000408
409 auto S = HashedFuncs.begin();
410 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
411 // If the hash value matches the previous value or the next one, we must
412 // consider merging it. Otherwise it is dropped and never considered again.
413 if ((I != S && std::prev(I)->first == I->first) ||
414 (std::next(I) != IE && std::next(I)->first == I->first) ) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000415 Deferred.push_back(WeakTrackingVH(I->second));
JF Bastien5e4303d2015-08-15 01:18:18 +0000416 }
417 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000418
Nick Lewycky564fcca2011-01-28 07:36:21 +0000419 do {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000420 std::vector<WeakTrackingVH> Worklist;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000421 Deferred.swap(Worklist);
422
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000423 LLVM_DEBUG(doSanityCheck(Worklist));
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000424
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000425 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
426 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000427
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000428 // Insert functions and merge them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000429 for (WeakTrackingVH &I : Worklist) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000430 if (!I)
431 continue;
432 Function *F = cast<Function>(I);
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000433 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000434 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000435 }
436 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000437 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000438 } while (!Deferred.empty());
439
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000440 FnTree.clear();
whitequark73cb9782018-11-08 03:58:01 +0000441 FNodesInTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000442 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +0000443
444 return Changed;
445}
446
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000447// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000448void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
449 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000450 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
451 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000452 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 CallSite CS(U->getUser());
454 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000455 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +0000456 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000457 // function' is no longer a Function* but the bitcast. Code that looks up
458 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +0000459
460 // FIXME: This is not actually true, at least not anymore. The callsite
461 // will always have the same ABI affecting attributes as the callee,
462 // because otherwise the original input has UB. Note that Old and New
463 // always have matching ABI, so no attributes need to be changed.
464 // Transferring other attributes may help other optimizations, but that
465 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000466 auto &Context = New->getContext();
Reid Klecknerf021fab2017-04-13 23:12:13 +0000467 auto NewPAL = New->getAttributes();
468 SmallVector<AttributeSet, 4> NewArgAttrs;
469 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
470 NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
471 // Don't transfer attributes from the function to the callee. Function
472 // attributes typically aren't relevant to the calling convention or ABI.
473 CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
474 NewPAL.getRetAttributes(),
475 NewArgAttrs));
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000476
Vedant Kumar08fe7e02019-01-11 17:56:21 +0000477 remove(CS.getInstruction()->getFunction());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000478 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000479 }
480 }
481}
482
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000483// Helper for writeThunk,
484// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +0000485// but a bit simpler then CastInst::getCastOpcode.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000486static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000487 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +0000488 if (SrcTy->isStructTy()) {
489 assert(DestTy->isStructTy());
490 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
491 Value *Result = UndefValue::get(DestTy);
492 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
493 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +0000494 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +0000495 DestTy->getStructElementType(I));
496
497 Result =
Craig Toppere1d12942014-08-27 05:25:25 +0000498 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +0000499 }
500 return Result;
501 }
502 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000503 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504 return Builder.CreateIntToPtr(V, DestTy);
505 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506 return Builder.CreatePtrToInt(V, DestTy);
507 else
508 return Builder.CreateBitCast(V, DestTy);
509}
510
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000511// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
512// parameter debug info, from the entry block.
513void MergeFunctions::eraseInstsUnrelatedToPDI(
514 std::vector<Instruction *> &PDIUnrelatedWL) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(
516 dbgs() << " Erasing instructions (in reverse order of appearance in "
517 "entry block) unrelated to parameter debug info from entry "
518 "block: {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000519 while (!PDIUnrelatedWL.empty()) {
520 Instruction *I = PDIUnrelatedWL.back();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000521 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
522 LLVM_DEBUG(I->print(dbgs()));
523 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000524 I->eraseFromParent();
525 PDIUnrelatedWL.pop_back();
526 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000527 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
528 "debug info from entry block. \n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000529}
530
531// Reduce G to its entry block.
532void MergeFunctions::eraseTail(Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000533 std::vector<BasicBlock *> WorklistBB;
534 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
535 BBI != BBE; ++BBI) {
536 BBI->dropAllReferences();
537 WorklistBB.push_back(&*BBI);
538 }
539 while (!WorklistBB.empty()) {
540 BasicBlock *BB = WorklistBB.back();
541 BB->eraseFromParent();
542 WorklistBB.pop_back();
543 }
544}
545
546// We are interested in the following instructions from the entry block as being
547// related to parameter debug info:
548// - @llvm.dbg.declare
549// - stores from the incoming parameters to locations on the stack-frame
550// - allocas that create these locations on the stack-frame
551// - @llvm.dbg.value
552// - the entry block's terminator
553// The rest are unrelated to debug info for the parameters; fill up
554// PDIUnrelatedWL with such instructions.
555void MergeFunctions::filterInstsUnrelatedToPDI(
556 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000557 std::set<Instruction *> PDIRelated;
558 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
559 BI != BIE; ++BI) {
560 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << " Deciding: ");
562 LLVM_DEBUG(BI->print(dbgs()));
563 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000564 DILocalVariable *DILocVar = DVI->getVariable();
565 if (DILocVar->isParameter()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000566 LLVM_DEBUG(dbgs() << " Include (parameter): ");
567 LLVM_DEBUG(BI->print(dbgs()));
568 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000569 PDIRelated.insert(&*BI);
570 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
572 LLVM_DEBUG(BI->print(dbgs()));
573 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000574 }
575 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << " Deciding: ");
577 LLVM_DEBUG(BI->print(dbgs()));
578 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000579 DILocalVariable *DILocVar = DDI->getVariable();
580 if (DILocVar->isParameter()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << " Parameter: ");
582 LLVM_DEBUG(DILocVar->print(dbgs()));
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000583 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
584 if (AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000585 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
586 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000587 for (User *U : AI->users()) {
588 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
589 if (Value *Arg = SI->getValueOperand()) {
590 if (dyn_cast<Argument>(Arg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << " Include: ");
592 LLVM_DEBUG(AI->print(dbgs()));
593 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000594 PDIRelated.insert(AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000595 LLVM_DEBUG(dbgs() << " Include (parameter): ");
596 LLVM_DEBUG(SI->print(dbgs()));
597 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000598 PDIRelated.insert(SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000599 LLVM_DEBUG(dbgs() << " Include: ");
600 LLVM_DEBUG(BI->print(dbgs()));
601 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000602 PDIRelated.insert(&*BI);
603 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000604 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
605 LLVM_DEBUG(SI->print(dbgs()));
606 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000607 }
608 }
609 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000610 LLVM_DEBUG(dbgs() << " Defer: ");
611 LLVM_DEBUG(U->print(dbgs()));
612 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000613 }
614 }
615 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
617 LLVM_DEBUG(BI->print(dbgs()));
618 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000619 }
620 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000621 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
622 LLVM_DEBUG(BI->print(dbgs()));
623 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000624 }
Chandler Carruth93cf2ea2018-10-18 00:37:37 +0000625 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000626 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
627 LLVM_DEBUG(BI->print(dbgs()));
628 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000629 PDIRelated.insert(&*BI);
630 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000631 LLVM_DEBUG(dbgs() << " Defer: ");
632 LLVM_DEBUG(BI->print(dbgs()));
633 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000634 }
635 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000636 LLVM_DEBUG(
637 dbgs()
638 << " Report parameter debug info related/related instructions: {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000639 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
640 BI != BE; ++BI) {
641
642 Instruction *I = &*BI;
643 if (PDIRelated.find(I) == PDIRelated.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000644 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
645 LLVM_DEBUG(I->print(dbgs()));
646 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000647 PDIUnrelatedWL.push_back(I);
648 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000649 LLVM_DEBUG(dbgs() << " PDIRelated: ");
650 LLVM_DEBUG(I->print(dbgs()));
651 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000652 }
653 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000654 LLVM_DEBUG(dbgs() << " }\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000655}
656
whitequark8f0ab252018-05-15 11:31:07 +0000657// Don't merge tiny functions using a thunk, since it can just end up
658// making the function larger.
659static bool isThunkProfitable(Function * F) {
660 if (F->size() == 1) {
661 if (F->front().size() <= 2) {
Nicola Zaghen03d0b912018-05-23 15:09:29 +0000662 LLVM_DEBUG(dbgs() << "isThunkProfitable: " << F->getName()
663 << " is too small to bother creating a thunk for\n");
whitequark8f0ab252018-05-15 11:31:07 +0000664 return false;
665 }
666 }
667 return true;
668}
669
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000670// Replace G with a simple tail call to bitcast(F). Also (unless
671// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
672// delete G. Under MergeFunctionsPDI, we use G itself for creating
673// the thunk as we preserve the debug info (and associated instructions)
674// from G's entry block pertaining to G's incoming arguments which are
675// passed on as corresponding arguments in the call that G makes to F.
676// For better debugability, under MergeFunctionsPDI, we do not modify G's
677// call sites to point to F even when within the same translation unit.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000678void MergeFunctions::writeThunk(Function *F, Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000679 BasicBlock *GEntryBlock = nullptr;
680 std::vector<Instruction *> PDIUnrelatedWL;
681 BasicBlock *BB = nullptr;
682 Function *NewG = nullptr;
683 if (MergeFunctionsPDI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000684 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
685 "function as thunk; retain original: "
686 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000687 GEntryBlock = &G->getEntryBlock();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000688 LLVM_DEBUG(
689 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
690 "debug info for "
691 << G->getName() << "() {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000692 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
693 GEntryBlock->getTerminator()->eraseFromParent();
694 BB = GEntryBlock;
695 } else {
Dylan McKayf920da02018-12-18 09:52:52 +0000696 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
697 G->getAddressSpace(), "", G->getParent());
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000698 BB = BasicBlock::Create(F->getContext(), "", NewG);
699 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000700
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000701 IRBuilder<> Builder(BB);
702 Function *H = MergeFunctionsPDI ? G : NewG;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000703 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000704 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000705 FunctionType *FFTy = F->getFunctionType();
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000706 for (Argument &AI : H->args()) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000707 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000708 ++i;
709 }
710
Jay Foad5bd375a2011-07-15 08:37:34 +0000711 CallInst *CI = Builder.CreateCall(F, Args);
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000712 ReturnInst *RI = nullptr;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000713 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +0000714 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +0000715 CI->setAttributes(F->getAttributes());
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000716 if (H->getReturnType()->isVoidTy()) {
717 RI = Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000718 } else {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000719 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000720 }
721
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000722 if (MergeFunctionsPDI) {
723 DISubprogram *DIS = G->getSubprogram();
724 if (DIS) {
725 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
726 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
727 CI->setDebugLoc(CIDbgLoc);
728 RI->setDebugLoc(RIDbgLoc);
729 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000730 LLVM_DEBUG(
731 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
732 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000733 }
734 eraseTail(G);
735 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000736 LLVM_DEBUG(
737 dbgs() << "} // End of parameter related debug info filtering for: "
738 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000739 } else {
740 NewG->copyAttributesFrom(G);
741 NewG->takeName(G);
742 removeUsers(G);
743 G->replaceAllUsesWith(NewG);
744 G->eraseFromParent();
745 }
Nick Lewycky71972d42010-09-07 01:42:10 +0000746
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000747 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +0000748 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000749}
750
Nikita Popov6f54fb02018-11-21 19:37:19 +0000751// Whether this function may be replaced by an alias
752static bool canCreateAliasFor(Function *F) {
753 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
754 return false;
755
756 // We should only see linkages supported by aliases here
757 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
758 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
759 return true;
760}
761
762// Replace G with an alias to F (deleting function G)
763void MergeFunctions::writeAlias(Function *F, Function *G) {
764 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
765 PointerType *PtrType = G->getType();
766 auto *GA = GlobalAlias::create(
767 PtrType->getElementType(), PtrType->getAddressSpace(),
768 G->getLinkage(), "", BitcastF, G->getParent());
769
770 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
771 GA->takeName(G);
772 GA->setVisibility(G->getVisibility());
773 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
774
775 removeUsers(G);
776 G->replaceAllUsesWith(GA);
777 G->eraseFromParent();
778
779 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
780 ++NumAliasesWritten;
781}
782
783// Replace G with an alias to F if possible, or a thunk to F if
784// profitable. Returns false if neither is the case.
785bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
786 if (canCreateAliasFor(G)) {
787 writeAlias(F, G);
788 return true;
789 }
790 if (isThunkProfitable(F)) {
791 writeThunk(F, G);
792 return true;
793 }
794 return false;
795}
796
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000797// Merge two equivalent functions. Upon completion, Function G is deleted.
798void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000799 if (F->isInterposable()) {
800 assert(G->isInterposable());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000801
Nikita Popov6f54fb02018-11-21 19:37:19 +0000802 // Both writeThunkOrAlias() calls below must succeed, either because we can
803 // create aliases for G and NewF, or because a thunk for F is profitable.
804 // F here has the same signature as NewF below, so that's what we check.
805 if (!isThunkProfitable(F) && (!canCreateAliasFor(F) || !canCreateAliasFor(G))) {
whitequark8f0ab252018-05-15 11:31:07 +0000806 return;
807 }
808
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000809 // Make them both thunks to the same internal function.
Dylan McKayf920da02018-12-18 09:52:52 +0000810 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
811 F->getAddressSpace(), "", F->getParent());
Nikita Popov6f54fb02018-11-21 19:37:19 +0000812 NewF->copyAttributesFrom(F);
813 NewF->takeName(F);
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000814 removeUsers(F);
Nikita Popov6f54fb02018-11-21 19:37:19 +0000815 F->replaceAllUsesWith(NewF);
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000816
Nikita Popov6f54fb02018-11-21 19:37:19 +0000817 unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000818
Nikita Popov6f54fb02018-11-21 19:37:19 +0000819 writeThunkOrAlias(F, G);
820 writeThunkOrAlias(F, NewF);
Nick Lewycky71972d42010-09-07 01:42:10 +0000821
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000822 F->setAlignment(MaxAlignment);
823 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +0000824 ++NumDoubleWeak;
whitequark8f0ab252018-05-15 11:31:07 +0000825 ++NumFunctionsMerged;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000826 } else {
whitequark8f0ab252018-05-15 11:31:07 +0000827 // For better debugability, under MergeFunctionsPDI, we do not modify G's
828 // call sites to point to F even when within the same translation unit.
829 if (!G->isInterposable() && !MergeFunctionsPDI) {
830 if (G->hasGlobalUnnamedAddr()) {
831 // G might have been a key in our GlobalNumberState, and it's illegal
832 // to replace a key in ValueMap<GlobalValue *> with a non-global.
833 GlobalNumbers.erase(G);
834 // If G's address is not significant, replace it entirely.
835 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
whitequark3580ac62018-11-08 03:57:55 +0000836 removeUsers(G);
whitequark8f0ab252018-05-15 11:31:07 +0000837 G->replaceAllUsesWith(BitcastF);
838 } else {
839 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
840 // above).
841 replaceDirectCallers(G, F);
842 }
843 }
Nick Lewycky3c6d34a2008-11-02 16:46:26 +0000844
whitequark8f0ab252018-05-15 11:31:07 +0000845 // If G was internal then we may have replaced all uses of G with F. If so,
846 // stop here and delete G. There's no need for a thunk. (See note on
847 // MergeFunctionsPDI above).
Vedant Kumaree10ef72019-01-11 17:56:35 +0000848 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
whitequark8f0ab252018-05-15 11:31:07 +0000849 G->eraseFromParent();
850 ++NumFunctionsMerged;
851 return;
852 }
853
Nikita Popov6f54fb02018-11-21 19:37:19 +0000854 if (writeThunkOrAlias(F, G)) {
855 ++NumFunctionsMerged;
whitequark8f0ab252018-05-15 11:31:07 +0000856 }
whitequark8f0ab252018-05-15 11:31:07 +0000857 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000858}
859
JF Bastien3a4ad612015-09-02 23:55:23 +0000860/// Replace function F by function G.
861void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000862 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000863 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +0000864 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
865 "The two functions must be equal");
Fangrui Songf78650a2018-07-30 19:41:25 +0000866
JF Bastien3a4ad612015-09-02 23:55:23 +0000867 auto I = FNodesInTree.find(F);
868 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
869 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
Fangrui Songf78650a2018-07-30 19:41:25 +0000870
JF Bastien3a4ad612015-09-02 23:55:23 +0000871 FnTreeType::iterator IterToFNInFnTree = I->second;
872 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
873 // Remove F -> FN and insert G -> FN
874 FNodesInTree.erase(I);
875 FNodesInTree.insert({G, IterToFNInFnTree});
876 // Replace F with G in FN, which is stored inside the FnTree.
877 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000878}
879
whitequark73cb9782018-11-08 03:58:01 +0000880// Ordering for functions that are equal under FunctionComparator
881static bool isFuncOrderCorrect(const Function *F, const Function *G) {
882 if (F->isInterposable() != G->isInterposable()) {
883 // Strong before weak, because the weak function may call the strong
884 // one, but not the other way around.
885 return !F->isInterposable();
886 }
887 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
888 // External before local, because we definitely have to keep the external
889 // function, but may be able to drop the local one.
890 return !F->hasLocalLinkage();
891 }
892 // Impose a total order (by name) on the replacement of functions. This is
893 // important when operating on more than one module independently to prevent
894 // cycles of thunks calling each other when the modules are linked together.
895 return F->getName() <= G->getName();
896}
897
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000898// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000899// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000900bool MergeFunctions::insert(Function *NewFunction) {
901 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000902 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000903
Nick Lewycky292e78c2011-02-09 06:32:02 +0000904 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000905 assert(FNodesInTree.count(NewFunction) == 0);
906 FNodesInTree.insert({NewFunction, Result.first});
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000907 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
908 << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000909 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +0000910 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000911
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000912 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +0000913
whitequark73cb9782018-11-08 03:58:01 +0000914 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000915 // Swap the two functions.
916 Function *F = OldF.getFunc();
917 replaceFunctionInTree(*Result.first, NewFunction);
918 NewFunction = F;
919 assert(OldF.getFunc() != F && "Must have swapped the functions.");
920 }
Nick Lewycky00959372010-09-05 08:22:49 +0000921
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000922 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
923 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000924
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000925 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000926 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +0000927 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000928}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000929
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000930// Remove a function from FnTree. If it was already in FnTree, add
931// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000932void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000933 auto I = FNodesInTree.find(F);
934 if (I != FNodesInTree.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000935 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
JF Bastien3a4ad612015-09-02 23:55:23 +0000936 FnTree.erase(I->second);
937 // I->second has been invalidated, remove it from the FNodesInTree map to
938 // preserve the invariant.
939 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000940 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000941 }
Nick Lewycky4e250c82011-01-02 02:46:33 +0000942}
Nick Lewycky00959372010-09-05 08:22:49 +0000943
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000944// For each instruction used by the value, remove() the function that contains
945// the instruction. This should happen right before a call to RAUW.
946void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +0000947 std::vector<Value *> Worklist;
948 Worklist.push_back(V);
Florian Hahna1cc8482018-06-12 11:16:56 +0000949 SmallPtrSet<Value*, 8> Visited;
JF Bastien7289f732015-07-15 21:51:33 +0000950 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +0000951 while (!Worklist.empty()) {
952 Value *V = Worklist.back();
953 Worklist.pop_back();
954
Chandler Carruthcdf47882014-03-09 03:16:01 +0000955 for (User *U : V->users()) {
956 if (Instruction *I = dyn_cast<Instruction>(U)) {
Vedant Kumar08fe7e02019-01-11 17:56:21 +0000957 remove(I->getFunction());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000958 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +0000959 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +0000960 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +0000961 for (User *UU : C->users()) {
962 if (!Visited.insert(UU).second)
963 Worklist.push_back(UU);
964 }
Nick Lewycky5361b842011-01-02 19:16:44 +0000965 }
Nick Lewycky00959372010-09-05 08:22:49 +0000966 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000967 }
Nick Lewycky00959372010-09-05 08:22:49 +0000968}