LLVM 24.0.0git
MergeFunctions.cpp
Go to the documentation of this file.
1//===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass looks for equivalent functions that are mergable and folds them.
10//
11// Order relation is defined on set of functions. It was made through
12// special function comparison procedure that returns
13// 0 when functions are equal,
14// -1 when Left function is less than right function, and
15// 1 for opposite case. We need total-ordering, so we need to maintain
16// four properties on the functions set:
17// a <= a (reflexivity)
18// if a <= b and b <= a then a = b (antisymmetry)
19// if a <= b and b <= c then a <= c (transitivity).
20// for all a and b: a <= b or b <= a (totality).
21//
22// Comparison iterates through each instruction in each basic block.
23// Functions are kept on binary tree. For each new function F we perform
24// lookup in binary tree.
25// In practice it works the following way:
26// -- We define Function* container class with custom "operator<" (FunctionPtr).
27// -- "FunctionPtr" instances are stored in std::set collection, so every
28// std::set::insert operation will give you result in log(N) time.
29//
30// As an optimization, a hash of the function structure is calculated first, and
31// two functions are only compared if they have the same hash. This hash is
32// cheap to compute, and has the property that if function F == G according to
33// the comparison function, then hash(F) == hash(G). This consistency property
34// is critical to ensuring all possible merging opportunities are exploited.
35// Collisions in the hash affect the speed of the pass but not the correctness
36// or determinism of the resulting transformation.
37//
38// When a match is found the functions are folded. If both functions are
39// overridable, we move the functionality into a new internal function and
40// leave two overridable thunks to it.
41//
42//===----------------------------------------------------------------------===//
43//
44// Future work:
45//
46// * virtual functions.
47//
48// Many functions have their address taken by the virtual function table for
49// the object they belong to. However, as long as it's only used for a lookup
50// and call, this is irrelevant, and we'd like to fold such functions.
51//
52// * be smarter about bitcasts.
53//
54// In order to fold functions, we will sometimes add either bitcast instructions
55// or bitcast constant expressions. Unfortunately, this can confound further
56// analysis since the two functions differ where one has a bitcast and the
57// other doesn't. We should learn to look through bitcasts.
58//
59// * Compare complex types with pointer types inside.
60// * Compare cross-reference cases.
61// * Compare complex expressions.
62//
63// All the three issues above could be described as ability to prove that
64// fA == fB == fC == fE == fF == fG in example below:
65//
66// void fA() {
67// fB();
68// }
69// void fB() {
70// fA();
71// }
72//
73// void fE() {
74// fF();
75// }
76// void fF() {
77// fG();
78// }
79// void fG() {
80// fE();
81// }
82//
83// Simplest cross-reference case (fA <--> fB) was implemented in previous
84// versions of MergeFunctions, though it presented only in two function pairs
85// in test-suite (that counts >50k functions)
86// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
87// could cover much more cases.
88//
89//===----------------------------------------------------------------------===//
90
92#include "llvm/ADT/APInt.h"
93#include "llvm/ADT/ArrayRef.h"
94#include "llvm/ADT/DenseMap.h"
95#include "llvm/ADT/DenseSet.h"
97#include "llvm/ADT/STLExtras.h"
99#include "llvm/ADT/Statistic.h"
102#include "llvm/IR/Argument.h"
103#include "llvm/IR/BasicBlock.h"
105#include "llvm/IR/DebugLoc.h"
106#include "llvm/IR/DerivedTypes.h"
107#include "llvm/IR/Function.h"
108#include "llvm/IR/GlobalValue.h"
109#include "llvm/IR/IRBuilder.h"
110#include "llvm/IR/InstrTypes.h"
111#include "llvm/IR/Instruction.h"
112#include "llvm/IR/Instructions.h"
114#include "llvm/IR/Metadata.h"
115#include "llvm/IR/Module.h"
116#include "llvm/IR/PassManager.h"
119#include "llvm/IR/Type.h"
120#include "llvm/IR/Use.h"
121#include "llvm/IR/User.h"
122#include "llvm/IR/Value.h"
123#include "llvm/IR/ValueHandle.h"
125#include "llvm/Support/Casting.h"
127#include "llvm/Support/Debug.h"
131#include "llvm/Transforms/IPO.h"
134#include <algorithm>
135#include <cassert>
136#include <cstddef>
137#include <cstdint>
138#include <iterator>
139#include <memory>
140#include <optional>
141#include <set>
142#include <utility>
143#include <vector>
144
145using namespace llvm;
146
147#define DEBUG_TYPE "mergefunc"
148
149STATISTIC(NumFunctionsMerged, "Number of functions merged");
150STATISTIC(NumThunksWritten, "Number of thunks generated");
151STATISTIC(NumAliasesWritten, "Number of aliases generated");
152STATISTIC(NumDoubleWeak, "Number of new functions created");
153
155 "mergefunc-verify",
156 cl::desc("How many functions in a module could be used for "
157 "MergeFunctions to pass a basic correctness check. "
158 "'0' disables this check. Works only with '-debug' key."),
159 cl::init(0), cl::Hidden);
160
161// Under option -mergefunc-preserve-debug-info we:
162// - Do not create a new function for a thunk.
163// - Retain the debug info for a thunk's parameters (and associated
164// instructions for the debug info) from the entry block.
165// Note: -debug will display the algorithm at work.
166// - Create debug-info for the call (to the shared implementation) made by
167// a thunk and its return value.
168// - Erase the rest of the function, retaining the (minimally sized) entry
169// block to create a thunk.
170// - Preserve a thunk's call site to point to the thunk even when both occur
171// within the same translation unit, to aid debugability. Note that this
172// behaviour differs from the underlying -mergefunc implementation which
173// modifies the thunk's call site to point to the shared implementation
174// when both occur within the same translation unit.
175static cl::opt<bool>
176 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
177 cl::init(false),
178 cl::desc("Preserve debug info in thunk when mergefunc "
179 "transformations are made."));
180
181static cl::opt<bool>
182 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
183 cl::init(false),
184 cl::desc("Allow mergefunc to create aliases"));
185
186namespace {
187
188class FunctionNode {
189 mutable AssertingVH<Function> F;
190 stable_hash Hash;
191
192public:
193 // Note the hash is recalculated potentially multiple times, but it is cheap.
194 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
195
196 Function *getFunc() const { return F; }
197 stable_hash getHash() const { return Hash; }
198
199 /// Replace the reference to the function F by the function G, assuming their
200 /// implementations are equal.
201 void replaceBy(Function *G) const {
202 F = G;
203 }
204};
205
206/// MergeFunctions finds functions which will generate identical machine code,
207/// by considering all pointer types to be equivalent. Once identified,
208/// MergeFunctions will fold them by replacing a call to one to a call to a
209/// bitcast of the other.
210class MergeFunctions {
211public:
212 explicit MergeFunctions(FunctionAnalysisManager &FAM)
213 : FnTree(FunctionNodeCmp(&GlobalNumbers)), FAM(FAM) {}
214
215 template <typename FuncContainer> bool run(FuncContainer &Functions);
216 DenseMap<Function *, Function *> runOnFunctions(ArrayRef<Function *> Funcs);
217
218 SmallPtrSet<GlobalValue *, 4> &getUsed();
219
220private:
221 // The function comparison operator is provided here so that FunctionNodes do
222 // not need to become larger with another pointer.
223 class FunctionNodeCmp {
224 GlobalNumberState* GlobalNumbers;
225
226 public:
227 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
228
229 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
230 // Order first by hashes, then full function comparison.
231 if (LHS.getHash() != RHS.getHash())
232 return LHS.getHash() < RHS.getHash();
233 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
234 return FCmp.compare() < 0;
235 }
236 };
237 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
238
239 GlobalNumberState GlobalNumbers;
240
241 /// A work queue of functions that may have been modified and should be
242 /// analyzed again.
243 std::vector<WeakTrackingVH> Deferred;
244
245 /// Set of values marked as used in llvm.used and llvm.compiler.used.
246 SmallPtrSet<GlobalValue *, 4> Used;
247
248#ifndef NDEBUG
249 /// Checks the rules of order relation introduced among functions set.
250 /// Returns true, if check has been passed, and false if failed.
251 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
252#endif
253
254 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
255 /// equal to one that's already present.
256 bool insert(Function *NewFunction);
257
258 /// Remove a Function from the FnTree and queue it up for a second sweep of
259 /// analysis.
260 void remove(Function *F);
261
262 /// Find the functions that use this Value and remove them from FnTree and
263 /// queue the functions.
264 void removeUsers(Value *V);
265
266 /// Replace all direct calls of Old with calls of New. Will bitcast New if
267 /// necessary to make types match.
268 void replaceDirectCallers(Function *Old, Function *New);
269
270 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
271 /// be converted into a thunk. In either case, it should never be visited
272 /// again.
273 void mergeTwoFunctions(Function *F, Function *G);
274
275 void mergeInstrProfMetadataInto(Function *Dst, Function *Src);
276
277 /// Fill PDIUnrelatedWL with instructions from the entry block that are
278 /// unrelated to parameter related debug info.
279 /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
280 void
281 filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
282 std::vector<Instruction *> &PDIUnrelatedWL,
283 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
284
285 /// Erase the rest of the CFG (i.e. barring the entry block).
286 void eraseTail(Function *G);
287
288 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
289 /// parameter debug info, from the entry block.
290 /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
291 /// debug-info records.
292 void
293 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
294 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
295
296 /// Replace G with a simple tail call to bitcast(F). Also (unless
297 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
298 /// delete G.
299 void writeThunk(Function *F, Function *G);
300
301 // Replace G with an alias to F (deleting function G)
302 void writeAlias(Function *F, Function *G);
303
304 // If needed, replace G with an alias to F if possible, or a thunk to F if
305 // profitable. Returns false if neither is the case. If \p G is not needed
306 // (i.e. it is discardable and not used), \p G is removed directly.
307 // \p MergeProfile must be true when G's profile should be preserved, it is
308 // merged into F before G is erased or rewritten.
309 bool writeThunkOrAliasIfNeeded(Function *F, Function *G, bool MergeProfile);
310
311 /// Replace function F with function G in the function tree.
312 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
313
314 /// The set of all distinct functions. Use the insert() and remove() methods
315 /// to modify it. The map allows efficient lookup and deferring of Functions.
316 FnTreeType FnTree;
317
318 // Map functions to the iterators of the FunctionNode which contains them
319 // in the FnTree. This must be updated carefully whenever the FnTree is
320 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
321 // dangling iterators into FnTree. The invariant that preserves this is that
322 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
323 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
324
325 /// Deleted-New functions mapping
326 DenseMap<Function *, Function *> DelToNewMap;
327
329};
330} // end anonymous namespace
331
338
339SmallPtrSet<GlobalValue *, 4> &MergeFunctions::getUsed() { return Used; }
340
342 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
343 MergeFunctions MF(FAM);
345 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
346 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
347 MF.getUsed().insert_range(UsedV);
348 return MF.run(M);
349}
350
354 if (Funcs.empty())
356
357 Module &M = *Funcs.front()->getParent();
358 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
359 MergeFunctions MF(FAM);
360 return MF.runOnFunctions(Funcs);
361}
362
363#ifndef NDEBUG
364bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
365 if (const unsigned Max = NumFunctionsForVerificationCheck) {
366 unsigned TripleNumber = 0;
367 bool Valid = true;
368
369 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
370
371 unsigned i = 0;
372 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
373 E = Worklist.end();
374 I != E && i < Max; ++I, ++i) {
375 unsigned j = i;
376 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
377 ++J, ++j) {
378 Function *F1 = cast<Function>(*I);
379 Function *F2 = cast<Function>(*J);
380 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
381 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
382
383 // If F1 <= F2, then F2 >= F1, otherwise report failure.
384 if (Res1 != -Res2) {
385 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
386 << "\n";
387 dbgs() << *F1 << '\n' << *F2 << '\n';
388 Valid = false;
389 }
390
391 if (Res1 == 0)
392 continue;
393
394 unsigned k = j;
395 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
396 ++k, ++K, ++TripleNumber) {
397 if (K == J)
398 continue;
399
400 Function *F3 = cast<Function>(*K);
401 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
402 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
403
404 bool Transitive = true;
405
406 if (Res1 != 0 && Res1 == Res4) {
407 // F1 > F2, F2 > F3 => F1 > F3
408 Transitive = Res3 == Res1;
409 } else if (Res3 != 0 && Res3 == -Res4) {
410 // F1 > F3, F3 > F2 => F1 > F2
411 Transitive = Res3 == Res1;
412 } else if (Res4 != 0 && -Res3 == Res4) {
413 // F2 > F3, F3 > F1 => F2 > F1
414 Transitive = Res4 == -Res1;
415 }
416
417 if (!Transitive) {
418 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
419 << TripleNumber << "\n";
420 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
421 << Res4 << "\n";
422 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
423 Valid = false;
424 }
425 }
426 }
427 }
428
429 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
430 return Valid;
431 }
432 return true;
433}
434#endif
435
436/// Check whether \p F has an intrinsic which references
437/// distinct metadata as an operand. The most common
438/// instance of this would be CFI checks for function-local types.
440 for (const BasicBlock &BB : F) {
441 for (const Instruction &I : BB) {
442 if (!isa<IntrinsicInst>(&I))
443 continue;
444
445 for (Value *Op : I.operands()) {
446 auto *MDL = dyn_cast<MetadataAsValue>(Op);
447 if (!MDL)
448 continue;
449 if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
450 if (N->isDistinct())
451 return true;
452 }
453 }
454 }
455 return false;
456}
457
458/// Check whether \p F is eligible for function merging.
460 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
461 !F.hasFnAttribute(Attribute::NoIPA) &&
463}
464
465inline Function *asPtr(Function *Fn) { return Fn; }
466inline Function *asPtr(Function &Fn) { return &Fn; }
467
468template <typename FuncContainer> bool MergeFunctions::run(FuncContainer &M) {
469 bool Changed = false;
470
471 // All functions in the module, ordered by hash. Functions with a unique
472 // hash value are easily eliminated.
473 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
474 for (auto &Func : M) {
475 Function *FuncPtr = asPtr(Func);
476 if (isEligibleForMerging(*FuncPtr)) {
477 HashedFuncs.push_back({StructuralHash(*FuncPtr), FuncPtr});
478 }
479 }
480
481 llvm::stable_sort(HashedFuncs, less_first());
482
483 auto S = HashedFuncs.begin();
484 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
485 // If the hash value matches the previous value or the next one, we must
486 // consider merging it. Otherwise it is dropped and never considered again.
487 if ((I != S && std::prev(I)->first == I->first) ||
488 (std::next(I) != IE && std::next(I)->first == I->first)) {
489 Deferred.push_back(WeakTrackingVH(I->second));
490 }
491 }
492
493 do {
494 std::vector<WeakTrackingVH> Worklist;
495 Deferred.swap(Worklist);
496
497 LLVM_DEBUG(doFunctionalCheck(Worklist));
498
499 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
500 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
501
502 // Insert functions and merge them.
503 for (WeakTrackingVH &I : Worklist) {
504 if (!I)
505 continue;
507 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
508 !F->hasFnAttribute(Attribute::NoIPA)) {
509 Changed |= insert(F);
510 }
511 }
512 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
513 } while (!Deferred.empty());
514
515 FnTree.clear();
516 FNodesInTree.clear();
517 GlobalNumbers.clear();
518 Used.clear();
519
520 return Changed;
521}
522
524MergeFunctions::runOnFunctions(ArrayRef<Function *> Funcs) {
525 [[maybe_unused]] bool MergeResult = this->run(Funcs);
526 assert(MergeResult == !DelToNewMap.empty());
527 return this->DelToNewMap;
528}
529
530// Replace direct callers of Old with New.
531void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
532 for (Use &U : make_early_inc_range(Old->uses())) {
533 CallBase *CB = dyn_cast<CallBase>(U.getUser());
534 if (CB && CB->isCallee(&U)) {
535 // Do not copy attributes from the called function to the call-site.
536 // Function comparison ensures that the attributes are the same up to
537 // type congruences in byval(), in which case we need to keep the byval
538 // type of the call-site, not the callee function.
539 remove(CB->getFunction());
540 U.set(New);
541 }
542 }
543}
544
545// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
546// parameter debug info, from the entry block.
547void MergeFunctions::eraseInstsUnrelatedToPDI(
548 std::vector<Instruction *> &PDIUnrelatedWL,
549 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
551 dbgs() << " Erasing instructions (in reverse order of appearance in "
552 "entry block) unrelated to parameter debug info from entry "
553 "block: {\n");
554 while (!PDIUnrelatedWL.empty()) {
555 Instruction *I = PDIUnrelatedWL.back();
556 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
557 LLVM_DEBUG(I->print(dbgs()));
558 LLVM_DEBUG(dbgs() << "\n");
559 I->eraseFromParent();
560 PDIUnrelatedWL.pop_back();
561 }
562
563 while (!PDVRUnrelatedWL.empty()) {
564 DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
565 LLVM_DEBUG(dbgs() << " Deleting DbgVariableRecord ");
566 LLVM_DEBUG(DVR->print(dbgs()));
567 LLVM_DEBUG(dbgs() << "\n");
568 DVR->eraseFromParent();
569 PDVRUnrelatedWL.pop_back();
570 }
571
572 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
573 "debug info from entry block. \n");
574}
575
576// Reduce G to its entry block.
577void MergeFunctions::eraseTail(Function *G) {
578 std::vector<BasicBlock *> WorklistBB;
579 for (BasicBlock &BB : drop_begin(*G)) {
580 BB.dropAllReferences();
581 WorklistBB.push_back(&BB);
582 }
583 while (!WorklistBB.empty()) {
584 BasicBlock *BB = WorklistBB.back();
585 BB->eraseFromParent();
586 WorklistBB.pop_back();
587 }
588}
589
590// We are interested in the following instructions from the entry block as being
591// related to parameter debug info:
592// - @llvm.dbg.declare
593// - stores from the incoming parameters to locations on the stack-frame
594// - allocas that create these locations on the stack-frame
595// - @llvm.dbg.value
596// - the entry block's terminator
597// The rest are unrelated to debug info for the parameters; fill up
598// PDIUnrelatedWL with such instructions.
599void MergeFunctions::filterInstsUnrelatedToPDI(
600 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
601 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
602 std::set<Instruction *> PDIRelated;
603 std::set<DbgVariableRecord *> PDVRRelated;
604
605 // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
606 // is a parameter to be preserved.
607 auto ExamineDbgValue = [&PDVRRelated](DbgVariableRecord *DbgVal) {
608 LLVM_DEBUG(dbgs() << " Deciding: ");
609 LLVM_DEBUG(DbgVal->print(dbgs()));
610 LLVM_DEBUG(dbgs() << "\n");
611 DILocalVariable *DILocVar = DbgVal->getVariable();
612 if (DILocVar->isParameter()) {
613 LLVM_DEBUG(dbgs() << " Include (parameter): ");
614 LLVM_DEBUG(DbgVal->print(dbgs()));
615 LLVM_DEBUG(dbgs() << "\n");
616 PDVRRelated.insert(DbgVal);
617 } else {
618 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
619 LLVM_DEBUG(DbgVal->print(dbgs()));
620 LLVM_DEBUG(dbgs() << "\n");
621 }
622 };
623
624 auto ExamineDbgDeclare = [&PDIRelated,
625 &PDVRRelated](DbgVariableRecord *DbgDecl) {
626 LLVM_DEBUG(dbgs() << " Deciding: ");
627 LLVM_DEBUG(DbgDecl->print(dbgs()));
628 LLVM_DEBUG(dbgs() << "\n");
629 DILocalVariable *DILocVar = DbgDecl->getVariable();
630 if (DILocVar->isParameter()) {
631 LLVM_DEBUG(dbgs() << " Parameter: ");
632 LLVM_DEBUG(DILocVar->print(dbgs()));
633 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
634 if (AI) {
635 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
636 LLVM_DEBUG(dbgs() << "\n");
637 for (User *U : AI->users()) {
638 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
639 if (Value *Arg = SI->getValueOperand()) {
640 if (isa<Argument>(Arg)) {
641 LLVM_DEBUG(dbgs() << " Include: ");
642 LLVM_DEBUG(AI->print(dbgs()));
643 LLVM_DEBUG(dbgs() << "\n");
644 PDIRelated.insert(AI);
645 LLVM_DEBUG(dbgs() << " Include (parameter): ");
646 LLVM_DEBUG(SI->print(dbgs()));
647 LLVM_DEBUG(dbgs() << "\n");
648 PDIRelated.insert(SI);
649 LLVM_DEBUG(dbgs() << " Include: ");
650 LLVM_DEBUG(DbgDecl->print(dbgs()));
651 LLVM_DEBUG(dbgs() << "\n");
652 PDVRRelated.insert(DbgDecl);
653 } else {
654 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
655 LLVM_DEBUG(SI->print(dbgs()));
656 LLVM_DEBUG(dbgs() << "\n");
657 }
658 }
659 } else {
660 LLVM_DEBUG(dbgs() << " Defer: ");
661 LLVM_DEBUG(U->print(dbgs()));
662 LLVM_DEBUG(dbgs() << "\n");
663 }
664 }
665 } else {
666 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
667 LLVM_DEBUG(DbgDecl->print(dbgs()));
668 LLVM_DEBUG(dbgs() << "\n");
669 }
670 } else {
671 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
672 LLVM_DEBUG(DbgDecl->print(dbgs()));
673 LLVM_DEBUG(dbgs() << "\n");
674 }
675 };
676
677 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
678 BI != BIE; ++BI) {
679 // Examine DbgVariableRecords as they happen "before" the instruction. Are
680 // they connected to parameters?
681 for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
682 if (DVR.isDbgValue() || DVR.isDbgAssign()) {
683 ExamineDbgValue(&DVR);
684 } else {
685 assert(DVR.isDbgDeclare());
686 ExamineDbgDeclare(&DVR);
687 }
688 }
689
690 if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
691 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
692 LLVM_DEBUG(BI->print(dbgs()));
693 LLVM_DEBUG(dbgs() << "\n");
694 PDIRelated.insert(&*BI);
695 } else {
696 LLVM_DEBUG(dbgs() << " Defer: ");
697 LLVM_DEBUG(BI->print(dbgs()));
698 LLVM_DEBUG(dbgs() << "\n");
699 }
700 }
702 dbgs()
703 << " Report parameter debug info related/related instructions: {\n");
704
705 auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
706 if (Container.find(Rec) == Container.end()) {
707 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
708 LLVM_DEBUG(Rec->print(dbgs()));
709 LLVM_DEBUG(dbgs() << "\n");
710 UnrelatedCont.push_back(Rec);
711 } else {
712 LLVM_DEBUG(dbgs() << " PDIRelated: ");
713 LLVM_DEBUG(Rec->print(dbgs()));
714 LLVM_DEBUG(dbgs() << "\n");
715 }
716 };
717
718 // Collect the set of unrelated instructions and debug records.
719 for (Instruction &I : *GEntryBlock) {
720 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
721 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
722 IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
723 }
724 LLVM_DEBUG(dbgs() << " }\n");
725}
726
727/// Whether this function may be replaced by a forwarding thunk.
729 if (F->isVarArg())
730 return false;
731
732 if (F->hasKernelCallingConv())
733 return false;
734
735 // Don't merge tiny functions using a thunk, since it can just end up
736 // making the function larger.
737 if (F->size() == 1) {
738 if (F->front().size() < 2) {
739 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
740 << " is too small to bother creating a thunk for\n");
741 return false;
742 }
743 }
744 return true;
745}
746
747/// Copy all metadata of a specific kind from one function to another.
749 StringRef Kind) {
751 From->getMetadata(Kind, MDs);
752 for (MDNode *MD : MDs)
753 To->addMetadata(Kind, *MD);
754}
755
756// Replace G with a simple tail call to bitcast(F). Also (unless
757// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
758// delete G. Under MergeFunctionsPDI, we use G itself for creating
759// the thunk as we preserve the debug info (and associated instructions)
760// from G's entry block pertaining to G's incoming arguments which are
761// passed on as corresponding arguments in the call that G makes to F.
762// For better debugability, under MergeFunctionsPDI, we do not modify G's
763// call sites to point to F even when within the same translation unit.
764void MergeFunctions::writeThunk(Function *F, Function *G) {
765 std::optional<uint64_t> GEntryCount = G->getEntryCount();
766 BasicBlock *GEntryBlock = nullptr;
767 std::vector<Instruction *> PDIUnrelatedWL;
768 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
769 BasicBlock *BB = nullptr;
770 Function *NewG = nullptr;
771 if (MergeFunctionsPDI) {
772 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
773 "function as thunk; retain original: "
774 << G->getName() << "()\n");
775 GEntryBlock = &G->getEntryBlock();
777 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
778 "debug info for "
779 << G->getName() << "() {\n");
780 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
781 GEntryBlock->getTerminator()->eraseFromParent();
782 BB = GEntryBlock;
783 } else {
784 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
785 G->getAddressSpace(), "", G->getParent());
786 NewG->setComdat(G->getComdat());
787 BB = BasicBlock::Create(F->getContext(), "", NewG);
788 }
789
790 IRBuilder<> Builder(BB);
791 Function *H = MergeFunctionsPDI ? G : NewG;
793 unsigned i = 0;
794 FunctionType *FFTy = F->getFunctionType();
795 for (Argument &AI : H->args()) {
796 Args.push_back(Builder.CreateAggregateCast(&AI, FFTy->getParamType(i)));
797 ++i;
798 }
799
800 CallInst *CI = Builder.CreateCall(F, Args);
801 ReturnInst *RI = nullptr;
802 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
803 G->getCallingConv() == CallingConv::SwiftTail;
804 CI->setTailCallKind(isSwiftTailCall ? CallInst::TCK_MustTail
806 CI->setCallingConv(F->getCallingConv());
807 CI->setAttributes(F->getAttributes());
808 if (H->getReturnType()->isVoidTy()) {
809 RI = Builder.CreateRetVoid();
810 } else {
811 RI = Builder.CreateRet(Builder.CreateAggregateCast(CI, H->getReturnType()));
812 }
813
814 if (MergeFunctionsPDI) {
815 DISubprogram *DIS = G->getSubprogram();
816 if (DIS) {
817 DebugLoc CIDbgLoc =
818 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
819 DebugLoc RIDbgLoc =
820 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
821 CI->setDebugLoc(CIDbgLoc);
822 RI->setDebugLoc(RIDbgLoc);
823 } else {
825 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
826 << G->getName() << "()\n");
827 }
828 eraseTail(G);
829 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
831 dbgs() << "} // End of parameter related debug info filtering for: "
832 << G->getName() << "()\n");
833 } else {
834 NewG->copyAttributesFrom(G);
835 if (GEntryCount)
836 NewG->setEntryCount(*GEntryCount);
837 NewG->takeName(G);
838 // Ensure CFI type metadata is propagated to the new function.
839 copyMetadataIfPresent(G, NewG, "type");
840 copyMetadataIfPresent(G, NewG, "kcfi_type");
841 copyMetadataIfPresent(G, NewG, "callgraph");
842 removeUsers(G);
843 G->replaceAllUsesWith(NewG);
844 G->eraseFromParent();
845 }
846
847 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
848 ++NumThunksWritten;
849}
850
851// Whether this function may be replaced by an alias
853 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
854 return false;
855
856 // We should only see linkages supported by aliases here
857 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
858 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
859 return true;
860}
861
862// Replace G with an alias to F (deleting function G)
863void MergeFunctions::writeAlias(Function *F, Function *G) {
864 PointerType *PtrType = G->getType();
865 auto *GA =
866 GlobalAlias::create(G->getFunctionType(), PtrType->getAddressSpace(),
867 G->getLinkage(), "", F, G->getParent());
868
869 const MaybeAlign FAlign = F->getAlign();
870 const MaybeAlign GAlign = G->getAlign();
871 if (FAlign || GAlign)
872 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
873 else
874 F->setAlignment(std::nullopt);
875 GA->takeName(G);
876 GA->setVisibility(G->getVisibility());
877 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
878
879 removeUsers(G);
880 G->replaceAllUsesWith(GA);
881 G->eraseFromParent();
882
883 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
884 ++NumAliasesWritten;
885}
886
888 const Function &G) {
889 DenseSet<GlobalValue::GUID> AllImports = F.getImportGUIDs();
890 DenseSet<GlobalValue::GUID> GImports = G.getImportGUIDs();
891 AllImports.insert(GImports.begin(), GImports.end());
892 return AllImports;
893}
894
896 std::optional<uint64_t> FEntryCount = F.getEntryCount();
897 std::optional<uint64_t> GEntryCount = G.getEntryCount();
899 if (!FEntryCount && !GEntryCount && AllImports.empty())
900 return;
901
902 // -1 is a safe placeholder here, getEntryCount() already treats it as
903 // "unknown" (same sentinel SamplePGO uses for no-sample functions), so
904 // it won't look hot to anyone reading the count back.
905 uint64_t Sum = static_cast<uint64_t>(-1);
906 if (FEntryCount || GEntryCount)
907 Sum = SaturatingAdd(FEntryCount ? *FEntryCount : uint64_t{0},
908 GEntryCount ? *GEntryCount : uint64_t{0});
909 F.setEntryCount(Sum, AllImports.empty() ? nullptr : &AllImports);
910}
911
912// If needed, replace G with an alias to F if possible, or a thunk to F if
913// profitable. Returns false if neither is the case. If \p G is not needed (i.e.
914// it is discardable and unused), \p G is removed directly. If \p MergeProfile
915// is set, G's profile metadata is merged into F.
916bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G,
917 bool MergeProfile) {
918 bool ShouldErase =
919 G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI;
920 bool ShouldAlias = canCreateAliasFor(G);
921 bool ShouldThunk = canCreateThunkFor(F);
922
923 if (!ShouldErase && !ShouldAlias && !ShouldThunk)
924 return false;
925
926 if (MergeProfile) {
927 mergeInstrProfMetadataInto(F, G);
929 }
930
931 if (ShouldErase) {
932 G->eraseFromParent();
933 return true;
934 }
935
936 if (ShouldAlias) {
937 writeAlias(F, G);
938 return true;
939 }
940 if (ShouldThunk) {
941 writeThunk(F, G);
942 return true;
943 }
944
945 llvm_unreachable("Erase, alias or thunk must apply");
946}
947
948/// Returns true if \p F is either weak_odr or linkonce_odr.
949static bool isODR(const Function *F) {
950 return F->hasWeakODRLinkage() || F->hasLinkOnceODRLinkage();
951}
952
954 const BasicBlock *BB) {
955 if (auto Count = BFI.getBlockProfileCount(BB, /*AllowSynthetic=*/true))
956 return *Count;
957 return 1;
958}
959
960// The branch weights are relative within a function. Before merging we
961// normalize these to absolute counts.
962// (weight * BlockCount / TotalWeight)
963static uint64_t scaleToBlockCount(uint64_t Weight, uint64_t TotalWeight,
964 uint64_t BlockCount) {
965 if (Weight == 0 || TotalWeight == 0 || BlockCount == 0)
966 return 0;
967 APInt Num(128, BlockCount);
968 Num *= APInt(128, Weight);
969 APInt Den(128, TotalWeight);
970 Num = (Num + Den.lshr(1)).udiv(Den);
971 assert(Num.getActiveBits() <= 64 &&
972 "scaleToBlockCount: result exceeds uint64_t; Weight > TotalWeight?");
973 return Num.getLimitedValue();
974}
975
976// Combine the scaled branch_weights of corresponding instructions of F and G.
978 const Instruction *SrcI,
979 const BlockFrequencyInfo &DstBFI,
980 const BlockFrequencyInfo &SrcBFI) {
981 SmallVector<uint32_t, 8> DstWeights, SrcWeights;
982 bool HasDst = extractBranchWeights(*DstI, DstWeights);
983 bool HasSrc = extractBranchWeights(*SrcI, SrcWeights);
984 if (!HasDst && !HasSrc)
985 return;
986
987 uint64_t DstBlockCount = getBlockCountForMerging(DstBFI, DstI->getParent());
988 uint64_t SrcBlockCount = getBlockCountForMerging(SrcBFI, SrcI->getParent());
989
990 uint64_t DstTotal = 0, SrcTotal = 0;
991 if (HasDst)
992 extractProfTotalWeight(*DstI, DstTotal);
993 if (HasSrc)
994 extractProfTotalWeight(*SrcI, SrcTotal);
995
996 assert((!HasDst || !HasSrc || DstWeights.size() == SrcWeights.size()) &&
997 "equivalent branch/select instructions must have matching weight "
998 "arity");
999 size_t NumWeights = HasDst ? DstWeights.size() : SrcWeights.size();
1000 SmallVector<uint64_t, 8> MergedWeights;
1001 MergedWeights.reserve(NumWeights);
1002 for (size_t I = 0; I < NumWeights; ++I) {
1003 uint64_t DstW = HasDst ? DstWeights[I] : 0;
1004 uint64_t SrcW = HasSrc ? SrcWeights[I] : 0;
1005 uint64_t DstAbs = scaleToBlockCount(DstW, DstTotal, DstBlockCount);
1006 uint64_t SrcAbs = scaleToBlockCount(SrcW, SrcTotal, SrcBlockCount);
1007 MergedWeights.push_back(SaturatingAdd(DstAbs, SrcAbs));
1008 }
1009
1010 bool IsExpected =
1012 setFittedBranchWeights(*DstI, MergedWeights, IsExpected);
1013}
1014
1015// Accumulate value profile counts of Instruction I into Merged. Value profile
1016// counts are absolute, not relative branch-style weights.
1019 uint64_t Total = 0;
1021 getValueProfDataFromInst(I, Kind, /*MaxNumValueData=*/UINT32_MAX, Total);
1022 if (VDs.empty())
1023 return;
1024 for (const InstrProfValueData &VD : VDs)
1025 Merged[VD.Value] = SaturatingAdd(Merged[VD.Value], VD.Count);
1026}
1027
1028// Merge (union) value profiles of Dst and Src.
1030 const Instruction *SrcI) {
1031 MDNode *DstProf = DstI->getMetadata(LLVMContext::MD_prof);
1032 MDNode *SrcProf = SrcI->getMetadata(LLVMContext::MD_prof);
1033 bool HasDst = DstProf && isValueProfileMD(DstProf);
1034 bool HasSrc = SrcProf && isValueProfileMD(SrcProf);
1035 if (!HasDst && !HasSrc)
1036 return;
1037
1038 auto *DstKind =
1039 HasDst ? mdconst::dyn_extract<ConstantInt>(DstProf->getOperand(1))
1040 : nullptr;
1041 auto *SrcKind =
1042 HasSrc ? mdconst::dyn_extract<ConstantInt>(SrcProf->getOperand(1))
1043 : nullptr;
1044 if (HasDst && HasSrc && DstKind && SrcKind &&
1045 DstKind->getZExtValue() != SrcKind->getZExtValue()) {
1046 DstI->setMetadata(LLVMContext::MD_prof, nullptr);
1047 return;
1048 }
1049
1050 const ConstantInt *KindCI = DstKind ? DstKind : SrcKind;
1051 if (!KindCI) {
1052 DstI->setMetadata(LLVMContext::MD_prof, nullptr);
1053 return;
1054 }
1055
1056 InstrProfValueKind Kind =
1057 static_cast<InstrProfValueKind>(KindCI->getZExtValue());
1058
1060 if (HasDst)
1061 addValueProfile(*DstI, Kind, Merged);
1062 if (HasSrc)
1063 addValueProfile(*SrcI, Kind, Merged);
1064
1065 if (Merged.empty())
1066 return;
1067
1069 VDs.reserve(Merged.size());
1070 uint64_t Sum = 0;
1071 for (auto &[Value, Count] : Merged) {
1072 VDs.push_back({Value, Count});
1073 Sum = SaturatingAdd(Sum, Count);
1074 }
1075 llvm::sort(VDs, [](const InstrProfValueData &A, const InstrProfValueData &B) {
1076 return A.Count > B.Count;
1077 });
1078 annotateValueSite(*DstI->getFunction()->getParent(), *DstI, VDs, Sum, Kind,
1079 VDs.size());
1080}
1081
1082/// Merge \p Src's instruction-level branch weights and value profile
1083/// metadata into the corresponding instructions of \p Dst. \p Dst is the
1084/// surviving function; \p Src will be erased or rewritten after this call.
1085/// Both functions must be structurally identical.
1086void MergeFunctions::mergeInstrProfMetadataInto(Function *Dst, Function *Src) {
1087 const BlockFrequencyInfo &DstBFI =
1089 const BlockFrequencyInfo &SrcBFI =
1091
1092 // FunctionComparator guarantees identical CFG topology and instruction
1093 // ordering. Walk the CFGs in RPO rather than function block-list order, as
1094 // equivalent functions need not store their basic blocks in the same order.
1097 for (auto [DstBB, SrcBB] : llvm::zip_equal(DstRPOT, SrcRPOT)) {
1098 for (auto [DstI, SrcI] : llvm::zip_equal(*DstBB, *SrcBB)) {
1099 MDNode *DstProf = DstI.getMetadata(LLVMContext::MD_prof);
1100 MDNode *SrcProf = SrcI.getMetadata(LLVMContext::MD_prof);
1101 if ((DstProf && isValueProfileMD(DstProf)) ||
1102 (SrcProf && isValueProfileMD(SrcProf)))
1103 mergeValueProfileOnInstructions(&DstI, &SrcI);
1104
1105 // Handle branch weights on SelectInsts here. Terminators are handled
1106 // separately below, outside the instruction loop.
1107 if (isa<SelectInst>(DstI))
1108 mergeBranchWeightsOnInstructions(&DstI, &SrcI, DstBFI, SrcBFI);
1109 }
1110 Instruction *DstTerm = DstBB->getTerminator();
1111 const Instruction *SrcTerm = SrcBB->getTerminator();
1112 mergeBranchWeightsOnInstructions(DstTerm, SrcTerm, DstBFI, SrcBFI);
1113 }
1114
1118 FAM.invalidate(*Dst, PA);
1119}
1120
1121// Merge two equivalent functions. Upon completion, Function G is deleted.
1122void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1123
1124 std::optional<uint64_t> FEntryCount = F->getEntryCount();
1125
1126 // Create a new thunk that both F and G can call, if F cannot call G directly.
1127 // That is the case if F is either interposable or if G is either weak_odr or
1128 // linkonce_odr.
1129 if (F->isInterposable() || (isODR(F) && isODR(G))) {
1130 assert((!isODR(G) || isODR(F)) &&
1131 "if G is ODR, F must also be ODR due to ordering");
1132
1133 // Both writeThunkOrAliasIfNeeded() calls below must succeed, either because
1134 // we can create aliases for G and NewF, or because a thunk for F is
1135 // profitable. F here has the same signature as NewF below, so that's what
1136 // we check.
1137 if (!canCreateThunkFor(F) &&
1139 return;
1140
1141 // Make them both thunks to the same internal function.
1142 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
1143 F->getAddressSpace(), "", F->getParent());
1144 NewF->copyAttributesFrom(F);
1145 NewF->takeName(F);
1146 NewF->setComdat(F->getComdat());
1147 F->setComdat(nullptr);
1148 // Ensure CFI type metadata is propagated to the new function.
1149 copyMetadataIfPresent(F, NewF, "type");
1150 copyMetadataIfPresent(F, NewF, "kcfi_type");
1151 copyMetadataIfPresent(F, NewF, "callgraph");
1152 removeUsers(F);
1153 F->replaceAllUsesWith(NewF);
1154
1155 // If G or NewF are (weak|linkonce)_odr, update all callers to call the
1156 // thunk.
1157 if (isODR(G))
1158 replaceDirectCallers(G, F);
1159 if (isODR(F))
1160 replaceDirectCallers(NewF, F);
1161
1162 // We collect alignment before writeThunkOrAliasIfNeeded that overwrites
1163 // NewF and G's content.
1164 const MaybeAlign NewFAlign = NewF->getAlign();
1165 const MaybeAlign GAlign = G->getAlign();
1166
1167 // Merge !prof, while G still has its body.
1168 writeThunkOrAliasIfNeeded(F, G, /*MergeProfile*/ true);
1169 if (FEntryCount)
1170 NewF->setEntryCount(*FEntryCount);
1171 // NewF becomes thunk/alias to the shared body F, it has no profile to be
1172 // merged.
1173 writeThunkOrAliasIfNeeded(F, NewF, /*MergeProfile*/ false);
1174
1175 if (NewFAlign || GAlign)
1176 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
1177 else
1178 F->setAlignment(std::nullopt);
1179 F->setLinkage(GlobalValue::PrivateLinkage);
1180 ++NumDoubleWeak;
1181 ++NumFunctionsMerged;
1182 } else {
1183 // For better debugability, under MergeFunctionsPDI, we do not modify G's
1184 // call sites to point to F even when within the same translation unit.
1185 if (!G->isInterposable() && !MergeFunctionsPDI) {
1186 // Functions referred to by llvm.used/llvm.compiler.used are special:
1187 // there are uses of the symbol name that are not visible to LLVM,
1188 // usually from inline asm.
1189 if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
1190 // G might have been a key in our GlobalNumberState, and it's illegal
1191 // to replace a key in ValueMap<GlobalValue *> with a non-global.
1192 GlobalNumbers.erase(G);
1193 // If G's address is not significant, replace it entirely.
1194 removeUsers(G);
1195 G->replaceAllUsesWith(F);
1196 } else {
1197 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
1198 // above).
1199 replaceDirectCallers(G, F);
1200 }
1201 }
1202
1203 // If G was internal then we may have replaced all uses of G with F. If so,
1204 // stop here and delete G. There's no need for a thunk. (See note on
1205 // MergeFunctionsPDI above).
1206 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
1207 mergeInstrProfMetadataInto(F, G);
1209 G->eraseFromParent();
1210 ++NumFunctionsMerged;
1211 return;
1212 }
1213
1214 if (writeThunkOrAliasIfNeeded(F, G, /*MergeProfile*/ true))
1215 ++NumFunctionsMerged;
1216 }
1217}
1218
1219/// Replace function F by function G.
1220void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
1221 Function *G) {
1222 Function *F = FN.getFunc();
1223 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1224 "The two functions must be equal");
1225
1226 auto I = FNodesInTree.find(F);
1227 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1228 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1229
1230 FnTreeType::iterator IterToFNInFnTree = I->second;
1231 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1232 // Remove F -> FN and insert G -> FN
1233 FNodesInTree.erase(I);
1234 FNodesInTree.insert({G, IterToFNInFnTree});
1235 // Replace F with G in FN, which is stored inside the FnTree.
1236 FN.replaceBy(G);
1237}
1238
1239// Ordering for functions that are equal under FunctionComparator
1240static bool isFuncOrderCorrect(const Function *F, const Function *G) {
1241 if (isODR(F) != isODR(G)) {
1242 // ODR functions before non-ODR functions. A ODR function can call a non-ODR
1243 // function if it is not interposable, but not the other way around.
1244 return isODR(G);
1245 }
1246
1247 if (F->isInterposable() != G->isInterposable()) {
1248 // Strong before weak, because the weak function may call the strong
1249 // one, but not the other way around.
1250 return !F->isInterposable();
1251 }
1252
1253 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
1254 // External before local, because we definitely have to keep the external
1255 // function, but may be able to drop the local one.
1256 return !F->hasLocalLinkage();
1257 }
1258
1259 // Impose a total order (by name) on the replacement of functions. This is
1260 // important when operating on more than one module independently to prevent
1261 // cycles of thunks calling each other when the modules are linked together.
1262 return F->getName() <= G->getName();
1263}
1264
1265// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1266// that was already inserted.
1267bool MergeFunctions::insert(Function *NewFunction) {
1268 std::pair<FnTreeType::iterator, bool> Result =
1269 FnTree.insert(FunctionNode(NewFunction));
1270
1271 if (Result.second) {
1272 assert(FNodesInTree.count(NewFunction) == 0);
1273 FNodesInTree.insert({NewFunction, Result.first});
1274 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
1275 << '\n');
1276 return false;
1277 }
1278
1279 const FunctionNode &OldF = *Result.first;
1280
1281 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
1282 // Swap the two functions.
1283 Function *F = OldF.getFunc();
1284 replaceFunctionInTree(*Result.first, NewFunction);
1285 NewFunction = F;
1286 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1287 }
1288
1289 // Capture the Function pointer before mergeTwoFunctions, which may invalidate
1290 // OldF by erasing it from FnTree via removeUsers().
1291 Function *OldFunc = OldF.getFunc();
1292
1293 LLVM_DEBUG(dbgs() << " " << OldFunc->getName()
1294 << " == " << NewFunction->getName() << '\n');
1295
1296 Function *DeleteF = NewFunction;
1297 mergeTwoFunctions(OldFunc, DeleteF);
1298 this->DelToNewMap.insert({DeleteF, OldFunc});
1299 return true;
1300}
1301
1302// Remove a function from FnTree. If it was already in FnTree, add
1303// it to Deferred so that we'll look at it in the next round.
1304void MergeFunctions::remove(Function *F) {
1305 auto I = FNodesInTree.find(F);
1306 if (I != FNodesInTree.end()) {
1307 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1308 FnTree.erase(I->second);
1309 // I->second has been invalidated, remove it from the FNodesInTree map to
1310 // preserve the invariant.
1311 FNodesInTree.erase(I);
1312 Deferred.emplace_back(F);
1313 }
1314}
1315
1316// For each instruction used by the value, remove() the function that contains
1317// the instruction. This should happen right before a call to RAUW.
1318void MergeFunctions::removeUsers(Value *V) {
1319 for (User *U : V->users())
1320 if (auto *I = dyn_cast<Instruction>(U))
1321 remove(I->getFunction());
1322}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
static void mergeEntryCountsAndImportsInto(Function &F, Function &G)
static uint64_t getBlockCountForMerging(const BlockFrequencyInfo &BFI, const BasicBlock *BB)
static void mergeValueProfileOnInstructions(Instruction *DstI, const Instruction *SrcI)
static bool canCreateAliasFor(Function *F)
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
static bool isODR(const Function *F)
Returns true if F is either weak_odr or linkonce_odr.
static cl::opt< unsigned > NumFunctionsForVerificationCheck("mergefunc-verify", cl::desc("How many functions in a module could be used for " "MergeFunctions to pass a basic correctness check. " "'0' disables this check. Works only with '-debug' key."), cl::init(0), cl::Hidden)
static DenseSet< GlobalValue::GUID > unionImportGUIDs(const Function &F, const Function &G)
static bool canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
static cl::opt< bool > MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden, cl::init(false), cl::desc("Preserve debug info in thunk when mergefunc " "transformations are made."))
static uint64_t scaleToBlockCount(uint64_t Weight, uint64_t TotalWeight, uint64_t BlockCount)
static bool hasDistinctMetadataIntrinsic(const Function &F)
Check whether F has an intrinsic which references distinct metadata as an operand.
Function * asPtr(Function *Fn)
static void addValueProfile(const Instruction &I, InstrProfValueKind Kind, DenseMap< uint64_t, uint64_t > &Merged)
static void copyMetadataIfPresent(Function *From, Function *To, StringRef Kind)
Copy all metadata of a specific kind from one function to another.
static cl::opt< bool > MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, cl::init(false), cl::desc("Allow mergefunc to create aliases"))
static void mergeBranchWeightsOnInstructions(Instruction *DstI, const Instruction *SrcI, const BlockFrequencyInfo &DstBFI, const BlockFrequencyInfo &SrcBFI)
static bool isFuncOrderCorrect(const Function *F, const Function *G)
This file contains the declarations for metadata subclasses.
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1594
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
an instruction to allocate memory on the stack
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Value handle that asserts if the Value is deleted.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Subprogram description. Uses SubclassData1.
LLVM_ABI void eraseFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
A debug info location.
Definition DebugLoc.h:126
unsigned size() const
Definition DenseMap.h:172
bool empty() const
Definition DenseMap.h:171
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
LLVM_ABI int compare()
Test whether the two functions have equivalent behaviour.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
MaybeAlign getAlign() const
Returns the alignment of the given function.
Definition Function.h:1021
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:842
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
void erase(GlobalValue *Global)
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Module * getParent()
Get the module that this global value is contained inside of...
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
LLVMContext & getContext() const
Definition Metadata.h:1233
static LLVM_ABI bool runOnModule(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static LLVM_ABI DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > Funcs, ModuleAnalysisManager &AM)
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Class to represent pointers.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
iterator_range< user_iterator > users()
Definition Value.h:426
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Value handle that is nullable, but tries to track the Value.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
void stable_sort(R &&Range)
Definition STLExtras.h:2116
LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
uint64_t stable_hash
An opaque object representing a stable hash code.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
InstrProfValueKind
Definition InstrProf.h:323
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:610
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI stable_hash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:930
#define N
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439