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/ArrayRef.h"
93#include "llvm/ADT/DenseSet.h"
95#include "llvm/ADT/Statistic.h"
96#include "llvm/IR/Argument.h"
97#include "llvm/IR/BasicBlock.h"
99#include "llvm/IR/DebugLoc.h"
100#include "llvm/IR/DerivedTypes.h"
101#include "llvm/IR/Function.h"
102#include "llvm/IR/GlobalValue.h"
103#include "llvm/IR/IRBuilder.h"
104#include "llvm/IR/InstrTypes.h"
105#include "llvm/IR/Instruction.h"
106#include "llvm/IR/Instructions.h"
108#include "llvm/IR/Module.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
114#include "llvm/IR/ValueHandle.h"
115#include "llvm/Support/Casting.h"
117#include "llvm/Support/Debug.h"
120#include "llvm/Transforms/IPO.h"
123#include <algorithm>
124#include <cassert>
125#include <iterator>
126#include <optional>
127#include <set>
128#include <utility>
129#include <vector>
130
131using namespace llvm;
132
133#define DEBUG_TYPE "mergefunc"
134
135STATISTIC(NumFunctionsMerged, "Number of functions merged");
136STATISTIC(NumThunksWritten, "Number of thunks generated");
137STATISTIC(NumAliasesWritten, "Number of aliases generated");
138STATISTIC(NumDoubleWeak, "Number of new functions created");
139
141 "mergefunc-verify",
142 cl::desc("How many functions in a module could be used for "
143 "MergeFunctions to pass a basic correctness check. "
144 "'0' disables this check. Works only with '-debug' key."),
145 cl::init(0), cl::Hidden);
146
147// Under option -mergefunc-preserve-debug-info we:
148// - Do not create a new function for a thunk.
149// - Retain the debug info for a thunk's parameters (and associated
150// instructions for the debug info) from the entry block.
151// Note: -debug will display the algorithm at work.
152// - Create debug-info for the call (to the shared implementation) made by
153// a thunk and its return value.
154// - Erase the rest of the function, retaining the (minimally sized) entry
155// block to create a thunk.
156// - Preserve a thunk's call site to point to the thunk even when both occur
157// within the same translation unit, to aid debugability. Note that this
158// behaviour differs from the underlying -mergefunc implementation which
159// modifies the thunk's call site to point to the shared implementation
160// when both occur within the same translation unit.
161static cl::opt<bool>
162 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
163 cl::init(false),
164 cl::desc("Preserve debug info in thunk when mergefunc "
165 "transformations are made."));
166
167static cl::opt<bool>
168 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
169 cl::init(false),
170 cl::desc("Allow mergefunc to create aliases"));
171
172namespace {
173
174class FunctionNode {
175 mutable AssertingVH<Function> F;
176 stable_hash Hash;
177
178public:
179 // Note the hash is recalculated potentially multiple times, but it is cheap.
180 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
181
182 Function *getFunc() const { return F; }
183 stable_hash getHash() const { return Hash; }
184
185 /// Replace the reference to the function F by the function G, assuming their
186 /// implementations are equal.
187 void replaceBy(Function *G) const {
188 F = G;
189 }
190};
191
192/// MergeFunctions finds functions which will generate identical machine code,
193/// by considering all pointer types to be equivalent. Once identified,
194/// MergeFunctions will fold them by replacing a call to one to a call to a
195/// bitcast of the other.
196class MergeFunctions {
197public:
198 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
199 }
200
201 template <typename FuncContainer> bool run(FuncContainer &Functions);
202 DenseMap<Function *, Function *> runOnFunctions(ArrayRef<Function *> F);
203
204 SmallPtrSet<GlobalValue *, 4> &getUsed();
205
206private:
207 // The function comparison operator is provided here so that FunctionNodes do
208 // not need to become larger with another pointer.
209 class FunctionNodeCmp {
210 GlobalNumberState* GlobalNumbers;
211
212 public:
213 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
214
215 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
216 // Order first by hashes, then full function comparison.
217 if (LHS.getHash() != RHS.getHash())
218 return LHS.getHash() < RHS.getHash();
219 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
220 return FCmp.compare() < 0;
221 }
222 };
223 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
224
225 GlobalNumberState GlobalNumbers;
226
227 /// A work queue of functions that may have been modified and should be
228 /// analyzed again.
229 std::vector<WeakTrackingVH> Deferred;
230
231 /// Set of values marked as used in llvm.used and llvm.compiler.used.
232 SmallPtrSet<GlobalValue *, 4> Used;
233
234#ifndef NDEBUG
235 /// Checks the rules of order relation introduced among functions set.
236 /// Returns true, if check has been passed, and false if failed.
237 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
238#endif
239
240 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
241 /// equal to one that's already present.
242 bool insert(Function *NewFunction);
243
244 /// Remove a Function from the FnTree and queue it up for a second sweep of
245 /// analysis.
246 void remove(Function *F);
247
248 /// Find the functions that use this Value and remove them from FnTree and
249 /// queue the functions.
250 void removeUsers(Value *V);
251
252 /// Replace all direct calls of Old with calls of New. Will bitcast New if
253 /// necessary to make types match.
254 void replaceDirectCallers(Function *Old, Function *New);
255
256 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
257 /// be converted into a thunk. In either case, it should never be visited
258 /// again.
259 void mergeTwoFunctions(Function *F, Function *G);
260
261 /// Fill PDIUnrelatedWL with instructions from the entry block that are
262 /// unrelated to parameter related debug info.
263 /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
264 void
265 filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
266 std::vector<Instruction *> &PDIUnrelatedWL,
267 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
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 /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
275 /// debug-info records.
276 void
277 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
278 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
279
280 /// Replace G with a simple tail call to bitcast(F). Also (unless
281 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
282 /// delete G.
283 void writeThunk(Function *F, Function *G);
284
285 // Replace G with an alias to F (deleting function G)
286 void writeAlias(Function *F, Function *G);
287
288 // If needed, replace G with an alias to F if possible, or a thunk to F if
289 // profitable. Returns false if neither is the case. If \p G is not needed
290 // (i.e. it is discardable and not used), \p G is removed directly.
291 // \p MergeProfile must be true when G's profile should be preserved, it is
292 // merged into F before G is erased or rewritten.
293 bool writeThunkOrAliasIfNeeded(Function *F, Function *G, bool MergeProfile);
294
295 /// Replace function F with function G in the function tree.
296 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
297
298 /// The set of all distinct functions. Use the insert() and remove() methods
299 /// to modify it. The map allows efficient lookup and deferring of Functions.
300 FnTreeType FnTree;
301
302 // Map functions to the iterators of the FunctionNode which contains them
303 // in the FnTree. This must be updated carefully whenever the FnTree is
304 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
305 // dangling iterators into FnTree. The invariant that preserves this is that
306 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
307 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
308
309 /// Deleted-New functions mapping
310 DenseMap<Function *, Function *> DelToNewMap;
311};
312} // end anonymous namespace
313
320
321SmallPtrSet<GlobalValue *, 4> &MergeFunctions::getUsed() { return Used; }
322
324 MergeFunctions MF;
326 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
327 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
328 MF.getUsed().insert_range(UsedV);
329 return MF.run(M);
330}
331
334 MergeFunctions MF;
335 return MF.runOnFunctions(F);
336}
337
338#ifndef NDEBUG
339bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
340 if (const unsigned Max = NumFunctionsForVerificationCheck) {
341 unsigned TripleNumber = 0;
342 bool Valid = true;
343
344 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
345
346 unsigned i = 0;
347 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
348 E = Worklist.end();
349 I != E && i < Max; ++I, ++i) {
350 unsigned j = i;
351 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
352 ++J, ++j) {
353 Function *F1 = cast<Function>(*I);
354 Function *F2 = cast<Function>(*J);
355 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
356 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
357
358 // If F1 <= F2, then F2 >= F1, otherwise report failure.
359 if (Res1 != -Res2) {
360 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
361 << "\n";
362 dbgs() << *F1 << '\n' << *F2 << '\n';
363 Valid = false;
364 }
365
366 if (Res1 == 0)
367 continue;
368
369 unsigned k = j;
370 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
371 ++k, ++K, ++TripleNumber) {
372 if (K == J)
373 continue;
374
375 Function *F3 = cast<Function>(*K);
376 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
377 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
378
379 bool Transitive = true;
380
381 if (Res1 != 0 && Res1 == Res4) {
382 // F1 > F2, F2 > F3 => F1 > F3
383 Transitive = Res3 == Res1;
384 } else if (Res3 != 0 && Res3 == -Res4) {
385 // F1 > F3, F3 > F2 => F1 > F2
386 Transitive = Res3 == Res1;
387 } else if (Res4 != 0 && -Res3 == Res4) {
388 // F2 > F3, F3 > F1 => F2 > F1
389 Transitive = Res4 == -Res1;
390 }
391
392 if (!Transitive) {
393 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
394 << TripleNumber << "\n";
395 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
396 << Res4 << "\n";
397 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
398 Valid = false;
399 }
400 }
401 }
402 }
403
404 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
405 return Valid;
406 }
407 return true;
408}
409#endif
410
411/// Check whether \p F has an intrinsic which references
412/// distinct metadata as an operand. The most common
413/// instance of this would be CFI checks for function-local types.
415 for (const BasicBlock &BB : F) {
416 for (const Instruction &I : BB) {
417 if (!isa<IntrinsicInst>(&I))
418 continue;
419
420 for (Value *Op : I.operands()) {
421 auto *MDL = dyn_cast<MetadataAsValue>(Op);
422 if (!MDL)
423 continue;
424 if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
425 if (N->isDistinct())
426 return true;
427 }
428 }
429 }
430 return false;
431}
432
433/// Check whether \p F is eligible for function merging.
435 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
436 !F.hasFnAttribute(Attribute::NoIPA) &&
438}
439
440inline Function *asPtr(Function *Fn) { return Fn; }
441inline Function *asPtr(Function &Fn) { return &Fn; }
442
443template <typename FuncContainer> bool MergeFunctions::run(FuncContainer &M) {
444 bool Changed = false;
445
446 // All functions in the module, ordered by hash. Functions with a unique
447 // hash value are easily eliminated.
448 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
449 for (auto &Func : M) {
450 Function *FuncPtr = asPtr(Func);
451 if (isEligibleForMerging(*FuncPtr)) {
452 HashedFuncs.push_back({StructuralHash(*FuncPtr), FuncPtr});
453 }
454 }
455
456 llvm::stable_sort(HashedFuncs, less_first());
457
458 auto S = HashedFuncs.begin();
459 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
460 // If the hash value matches the previous value or the next one, we must
461 // consider merging it. Otherwise it is dropped and never considered again.
462 if ((I != S && std::prev(I)->first == I->first) ||
463 (std::next(I) != IE && std::next(I)->first == I->first)) {
464 Deferred.push_back(WeakTrackingVH(I->second));
465 }
466 }
467
468 do {
469 std::vector<WeakTrackingVH> Worklist;
470 Deferred.swap(Worklist);
471
472 LLVM_DEBUG(doFunctionalCheck(Worklist));
473
474 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
475 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
476
477 // Insert functions and merge them.
478 for (WeakTrackingVH &I : Worklist) {
479 if (!I)
480 continue;
482 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
483 !F->hasFnAttribute(Attribute::NoIPA)) {
484 Changed |= insert(F);
485 }
486 }
487 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
488 } while (!Deferred.empty());
489
490 FnTree.clear();
491 FNodesInTree.clear();
492 GlobalNumbers.clear();
493 Used.clear();
494
495 return Changed;
496}
497
499MergeFunctions::runOnFunctions(ArrayRef<Function *> F) {
500 [[maybe_unused]] bool MergeResult = this->run(F);
501 assert(MergeResult == !DelToNewMap.empty());
502 return this->DelToNewMap;
503}
504
505// Replace direct callers of Old with New.
506void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
507 for (Use &U : make_early_inc_range(Old->uses())) {
508 CallBase *CB = dyn_cast<CallBase>(U.getUser());
509 if (CB && CB->isCallee(&U)) {
510 // Do not copy attributes from the called function to the call-site.
511 // Function comparison ensures that the attributes are the same up to
512 // type congruences in byval(), in which case we need to keep the byval
513 // type of the call-site, not the callee function.
514 remove(CB->getFunction());
515 U.set(New);
516 }
517 }
518}
519
520// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
521// parameter debug info, from the entry block.
522void MergeFunctions::eraseInstsUnrelatedToPDI(
523 std::vector<Instruction *> &PDIUnrelatedWL,
524 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
526 dbgs() << " Erasing instructions (in reverse order of appearance in "
527 "entry block) unrelated to parameter debug info from entry "
528 "block: {\n");
529 while (!PDIUnrelatedWL.empty()) {
530 Instruction *I = PDIUnrelatedWL.back();
531 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
532 LLVM_DEBUG(I->print(dbgs()));
533 LLVM_DEBUG(dbgs() << "\n");
534 I->eraseFromParent();
535 PDIUnrelatedWL.pop_back();
536 }
537
538 while (!PDVRUnrelatedWL.empty()) {
539 DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
540 LLVM_DEBUG(dbgs() << " Deleting DbgVariableRecord ");
541 LLVM_DEBUG(DVR->print(dbgs()));
542 LLVM_DEBUG(dbgs() << "\n");
543 DVR->eraseFromParent();
544 PDVRUnrelatedWL.pop_back();
545 }
546
547 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
548 "debug info from entry block. \n");
549}
550
551// Reduce G to its entry block.
552void MergeFunctions::eraseTail(Function *G) {
553 std::vector<BasicBlock *> WorklistBB;
554 for (BasicBlock &BB : drop_begin(*G)) {
555 BB.dropAllReferences();
556 WorklistBB.push_back(&BB);
557 }
558 while (!WorklistBB.empty()) {
559 BasicBlock *BB = WorklistBB.back();
560 BB->eraseFromParent();
561 WorklistBB.pop_back();
562 }
563}
564
565// We are interested in the following instructions from the entry block as being
566// related to parameter debug info:
567// - @llvm.dbg.declare
568// - stores from the incoming parameters to locations on the stack-frame
569// - allocas that create these locations on the stack-frame
570// - @llvm.dbg.value
571// - the entry block's terminator
572// The rest are unrelated to debug info for the parameters; fill up
573// PDIUnrelatedWL with such instructions.
574void MergeFunctions::filterInstsUnrelatedToPDI(
575 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
576 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
577 std::set<Instruction *> PDIRelated;
578 std::set<DbgVariableRecord *> PDVRRelated;
579
580 // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
581 // is a parameter to be preserved.
582 auto ExamineDbgValue = [&PDVRRelated](DbgVariableRecord *DbgVal) {
583 LLVM_DEBUG(dbgs() << " Deciding: ");
584 LLVM_DEBUG(DbgVal->print(dbgs()));
585 LLVM_DEBUG(dbgs() << "\n");
586 DILocalVariable *DILocVar = DbgVal->getVariable();
587 if (DILocVar->isParameter()) {
588 LLVM_DEBUG(dbgs() << " Include (parameter): ");
589 LLVM_DEBUG(DbgVal->print(dbgs()));
590 LLVM_DEBUG(dbgs() << "\n");
591 PDVRRelated.insert(DbgVal);
592 } else {
593 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
594 LLVM_DEBUG(DbgVal->print(dbgs()));
595 LLVM_DEBUG(dbgs() << "\n");
596 }
597 };
598
599 auto ExamineDbgDeclare = [&PDIRelated,
600 &PDVRRelated](DbgVariableRecord *DbgDecl) {
601 LLVM_DEBUG(dbgs() << " Deciding: ");
602 LLVM_DEBUG(DbgDecl->print(dbgs()));
603 LLVM_DEBUG(dbgs() << "\n");
604 DILocalVariable *DILocVar = DbgDecl->getVariable();
605 if (DILocVar->isParameter()) {
606 LLVM_DEBUG(dbgs() << " Parameter: ");
607 LLVM_DEBUG(DILocVar->print(dbgs()));
608 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
609 if (AI) {
610 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
611 LLVM_DEBUG(dbgs() << "\n");
612 for (User *U : AI->users()) {
613 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
614 if (Value *Arg = SI->getValueOperand()) {
615 if (isa<Argument>(Arg)) {
616 LLVM_DEBUG(dbgs() << " Include: ");
617 LLVM_DEBUG(AI->print(dbgs()));
618 LLVM_DEBUG(dbgs() << "\n");
619 PDIRelated.insert(AI);
620 LLVM_DEBUG(dbgs() << " Include (parameter): ");
621 LLVM_DEBUG(SI->print(dbgs()));
622 LLVM_DEBUG(dbgs() << "\n");
623 PDIRelated.insert(SI);
624 LLVM_DEBUG(dbgs() << " Include: ");
625 LLVM_DEBUG(DbgDecl->print(dbgs()));
626 LLVM_DEBUG(dbgs() << "\n");
627 PDVRRelated.insert(DbgDecl);
628 } else {
629 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
630 LLVM_DEBUG(SI->print(dbgs()));
631 LLVM_DEBUG(dbgs() << "\n");
632 }
633 }
634 } else {
635 LLVM_DEBUG(dbgs() << " Defer: ");
636 LLVM_DEBUG(U->print(dbgs()));
637 LLVM_DEBUG(dbgs() << "\n");
638 }
639 }
640 } else {
641 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
642 LLVM_DEBUG(DbgDecl->print(dbgs()));
643 LLVM_DEBUG(dbgs() << "\n");
644 }
645 } else {
646 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
647 LLVM_DEBUG(DbgDecl->print(dbgs()));
648 LLVM_DEBUG(dbgs() << "\n");
649 }
650 };
651
652 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
653 BI != BIE; ++BI) {
654 // Examine DbgVariableRecords as they happen "before" the instruction. Are
655 // they connected to parameters?
656 for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
657 if (DVR.isDbgValue() || DVR.isDbgAssign()) {
658 ExamineDbgValue(&DVR);
659 } else {
660 assert(DVR.isDbgDeclare());
661 ExamineDbgDeclare(&DVR);
662 }
663 }
664
665 if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
666 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
667 LLVM_DEBUG(BI->print(dbgs()));
668 LLVM_DEBUG(dbgs() << "\n");
669 PDIRelated.insert(&*BI);
670 } else {
671 LLVM_DEBUG(dbgs() << " Defer: ");
672 LLVM_DEBUG(BI->print(dbgs()));
673 LLVM_DEBUG(dbgs() << "\n");
674 }
675 }
677 dbgs()
678 << " Report parameter debug info related/related instructions: {\n");
679
680 auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
681 if (Container.find(Rec) == Container.end()) {
682 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
683 LLVM_DEBUG(Rec->print(dbgs()));
684 LLVM_DEBUG(dbgs() << "\n");
685 UnrelatedCont.push_back(Rec);
686 } else {
687 LLVM_DEBUG(dbgs() << " PDIRelated: ");
688 LLVM_DEBUG(Rec->print(dbgs()));
689 LLVM_DEBUG(dbgs() << "\n");
690 }
691 };
692
693 // Collect the set of unrelated instructions and debug records.
694 for (Instruction &I : *GEntryBlock) {
695 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
696 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
697 IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
698 }
699 LLVM_DEBUG(dbgs() << " }\n");
700}
701
702/// Whether this function may be replaced by a forwarding thunk.
704 if (F->isVarArg())
705 return false;
706
707 if (F->hasKernelCallingConv())
708 return false;
709
710 // Don't merge tiny functions using a thunk, since it can just end up
711 // making the function larger.
712 if (F->size() == 1) {
713 if (F->front().size() < 2) {
714 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
715 << " is too small to bother creating a thunk for\n");
716 return false;
717 }
718 }
719 return true;
720}
721
722/// Copy all metadata of a specific kind from one function to another.
724 StringRef Kind) {
726 From->getMetadata(Kind, MDs);
727 for (MDNode *MD : MDs)
728 To->addMetadata(Kind, *MD);
729}
730
731// Replace G with a simple tail call to bitcast(F). Also (unless
732// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
733// delete G. Under MergeFunctionsPDI, we use G itself for creating
734// the thunk as we preserve the debug info (and associated instructions)
735// from G's entry block pertaining to G's incoming arguments which are
736// passed on as corresponding arguments in the call that G makes to F.
737// For better debugability, under MergeFunctionsPDI, we do not modify G's
738// call sites to point to F even when within the same translation unit.
739void MergeFunctions::writeThunk(Function *F, Function *G) {
740 std::optional<uint64_t> GEC = G->getEntryCount();
741 BasicBlock *GEntryBlock = nullptr;
742 std::vector<Instruction *> PDIUnrelatedWL;
743 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
744 BasicBlock *BB = nullptr;
745 Function *NewG = nullptr;
746 if (MergeFunctionsPDI) {
747 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
748 "function as thunk; retain original: "
749 << G->getName() << "()\n");
750 GEntryBlock = &G->getEntryBlock();
752 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
753 "debug info for "
754 << G->getName() << "() {\n");
755 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
756 GEntryBlock->getTerminator()->eraseFromParent();
757 BB = GEntryBlock;
758 } else {
759 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
760 G->getAddressSpace(), "", G->getParent());
761 NewG->setComdat(G->getComdat());
762 BB = BasicBlock::Create(F->getContext(), "", NewG);
763 }
764
765 IRBuilder<> Builder(BB);
766 Function *H = MergeFunctionsPDI ? G : NewG;
768 unsigned i = 0;
769 FunctionType *FFTy = F->getFunctionType();
770 for (Argument &AI : H->args()) {
771 Args.push_back(Builder.CreateAggregateCast(&AI, FFTy->getParamType(i)));
772 ++i;
773 }
774
775 CallInst *CI = Builder.CreateCall(F, Args);
776 ReturnInst *RI = nullptr;
777 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
778 G->getCallingConv() == CallingConv::SwiftTail;
779 CI->setTailCallKind(isSwiftTailCall ? CallInst::TCK_MustTail
781 CI->setCallingConv(F->getCallingConv());
782 CI->setAttributes(F->getAttributes());
783 if (H->getReturnType()->isVoidTy()) {
784 RI = Builder.CreateRetVoid();
785 } else {
786 RI = Builder.CreateRet(Builder.CreateAggregateCast(CI, H->getReturnType()));
787 }
788
789 if (MergeFunctionsPDI) {
790 DISubprogram *DIS = G->getSubprogram();
791 if (DIS) {
792 DebugLoc CIDbgLoc =
793 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
794 DebugLoc RIDbgLoc =
795 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
796 CI->setDebugLoc(CIDbgLoc);
797 RI->setDebugLoc(RIDbgLoc);
798 } else {
800 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
801 << G->getName() << "()\n");
802 }
803 eraseTail(G);
804 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
806 dbgs() << "} // End of parameter related debug info filtering for: "
807 << G->getName() << "()\n");
808 } else {
809 NewG->copyAttributesFrom(G);
810 if (GEC)
811 NewG->setEntryCount(*GEC);
812 NewG->takeName(G);
813 // Ensure CFI type metadata is propagated to the new function.
814 copyMetadataIfPresent(G, NewG, "type");
815 copyMetadataIfPresent(G, NewG, "kcfi_type");
816 copyMetadataIfPresent(G, NewG, "callgraph");
817 removeUsers(G);
818 G->replaceAllUsesWith(NewG);
819 G->eraseFromParent();
820 }
821
822 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
823 ++NumThunksWritten;
824}
825
826// Whether this function may be replaced by an alias
828 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
829 return false;
830
831 // We should only see linkages supported by aliases here
832 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
833 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
834 return true;
835}
836
837// Replace G with an alias to F (deleting function G)
838void MergeFunctions::writeAlias(Function *F, Function *G) {
839 PointerType *PtrType = G->getType();
840 auto *GA =
841 GlobalAlias::create(G->getFunctionType(), PtrType->getAddressSpace(),
842 G->getLinkage(), "", F, G->getParent());
843
844 const MaybeAlign FAlign = F->getAlign();
845 const MaybeAlign GAlign = G->getAlign();
846 if (FAlign || GAlign)
847 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
848 else
849 F->setAlignment(std::nullopt);
850 GA->takeName(G);
851 GA->setVisibility(G->getVisibility());
852 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
853
854 removeUsers(G);
855 G->replaceAllUsesWith(GA);
856 G->eraseFromParent();
857
858 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
859 ++NumAliasesWritten;
860}
861
863 const Function &G) {
864 DenseSet<GlobalValue::GUID> AllImports = F.getImportGUIDs();
865 DenseSet<GlobalValue::GUID> GImports = G.getImportGUIDs();
866 AllImports.insert(GImports.begin(), GImports.end());
867 return AllImports;
868}
869
871 std::optional<uint64_t> FEntryCount = F.getEntryCount();
872 std::optional<uint64_t> GEntryCount = G.getEntryCount();
874 if (!FEntryCount && !GEntryCount && AllImports.empty())
875 return;
876
877 // -1 is a safe placeholder here, getEntryCount() already treats it as
878 // "unknown" (same sentinel SamplePGO uses for no-sample functions), so
879 // it won't look hot to anyone reading the count back.
880 uint64_t Sum = static_cast<uint64_t>(-1);
881 if (FEntryCount || GEntryCount)
882 Sum = SaturatingAdd(FEntryCount ? *FEntryCount : uint64_t{0},
883 GEntryCount ? *GEntryCount : uint64_t{0});
884 F.setEntryCount(Sum, AllImports.empty() ? nullptr : &AllImports);
885}
886
887// If needed, replace G with an alias to F if possible, or a thunk to F if
888// profitable. Returns false if neither is the case. If \p G is not needed (i.e.
889// it is discardable and unused), \p G is removed directly. If \p MergeProfile
890// is set, G's profile metadata is merged into F.
891bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G,
892 bool MergeProfile) {
893 bool ShouldErase =
894 G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI;
895 bool ShouldAlias = canCreateAliasFor(G);
896 bool ShouldThunk = canCreateThunkFor(F);
897
898 if (!ShouldErase && !ShouldAlias && !ShouldThunk)
899 return false;
900
901 if (MergeProfile)
903
904 if (ShouldErase) {
905 G->eraseFromParent();
906 return true;
907 }
908
909 if (ShouldAlias) {
910 writeAlias(F, G);
911 return true;
912 }
913 if (ShouldThunk) {
914 writeThunk(F, G);
915 return true;
916 }
917
918 llvm_unreachable("Erase, alias or thunk must apply");
919}
920
921/// Returns true if \p F is either weak_odr or linkonce_odr.
922static bool isODR(const Function *F) {
923 return F->hasWeakODRLinkage() || F->hasLinkOnceODRLinkage();
924}
925
926// Merge two equivalent functions. Upon completion, Function G is deleted.
927void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
928
929 std::optional<uint64_t> FEntryCount = F->getEntryCount();
930
931 // Create a new thunk that both F and G can call, if F cannot call G directly.
932 // That is the case if F is either interposable or if G is either weak_odr or
933 // linkonce_odr.
934 if (F->isInterposable() || (isODR(F) && isODR(G))) {
935 assert((!isODR(G) || isODR(F)) &&
936 "if G is ODR, F must also be ODR due to ordering");
937
938 // Both writeThunkOrAliasIfNeeded() calls below must succeed, either because
939 // we can create aliases for G and NewF, or because a thunk for F is
940 // profitable. F here has the same signature as NewF below, so that's what
941 // we check.
942 if (!canCreateThunkFor(F) &&
944 return;
945
946 // Make them both thunks to the same internal function.
947 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
948 F->getAddressSpace(), "", F->getParent());
949 NewF->copyAttributesFrom(F);
950 NewF->takeName(F);
951 NewF->setComdat(F->getComdat());
952 F->setComdat(nullptr);
953 // Ensure CFI type metadata is propagated to the new function.
954 copyMetadataIfPresent(F, NewF, "type");
955 copyMetadataIfPresent(F, NewF, "kcfi_type");
956 copyMetadataIfPresent(F, NewF, "callgraph");
957 removeUsers(F);
958 F->replaceAllUsesWith(NewF);
959
960 // If G or NewF are (weak|linkonce)_odr, update all callers to call the
961 // thunk.
962 if (isODR(G))
963 replaceDirectCallers(G, F);
964 if (isODR(F))
965 replaceDirectCallers(NewF, F);
966
967 // We collect alignment before writeThunkOrAliasIfNeeded that overwrites
968 // NewF and G's content.
969 const MaybeAlign NewFAlign = NewF->getAlign();
970 const MaybeAlign GAlign = G->getAlign();
971
972 // Merge !prof, while G still has its body.
973 writeThunkOrAliasIfNeeded(F, G, /*MergeProfile*/ true);
974 if (FEntryCount)
975 NewF->setEntryCount(*FEntryCount);
976 // NewF becomes thunk/alias to the shared body F, it has no profile to be
977 // merged.
978 writeThunkOrAliasIfNeeded(F, NewF, /*MergeProfile*/ false);
979
980 if (NewFAlign || GAlign)
981 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
982 else
983 F->setAlignment(std::nullopt);
984 F->setLinkage(GlobalValue::PrivateLinkage);
985 ++NumDoubleWeak;
986 ++NumFunctionsMerged;
987 } else {
988 // For better debugability, under MergeFunctionsPDI, we do not modify G's
989 // call sites to point to F even when within the same translation unit.
990 if (!G->isInterposable() && !MergeFunctionsPDI) {
991 // Functions referred to by llvm.used/llvm.compiler.used are special:
992 // there are uses of the symbol name that are not visible to LLVM,
993 // usually from inline asm.
994 if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
995 // G might have been a key in our GlobalNumberState, and it's illegal
996 // to replace a key in ValueMap<GlobalValue *> with a non-global.
997 GlobalNumbers.erase(G);
998 // If G's address is not significant, replace it entirely.
999 removeUsers(G);
1000 G->replaceAllUsesWith(F);
1001 } else {
1002 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
1003 // above).
1004 replaceDirectCallers(G, F);
1005 }
1006 }
1007
1008 // If G was internal then we may have replaced all uses of G with F. If so,
1009 // stop here and delete G. There's no need for a thunk. (See note on
1010 // MergeFunctionsPDI above).
1011 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
1013 G->eraseFromParent();
1014 ++NumFunctionsMerged;
1015 return;
1016 }
1017
1018 if (writeThunkOrAliasIfNeeded(F, G, /*MergeProfile*/ true))
1019 ++NumFunctionsMerged;
1020 }
1021}
1022
1023/// Replace function F by function G.
1024void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
1025 Function *G) {
1026 Function *F = FN.getFunc();
1027 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1028 "The two functions must be equal");
1029
1030 auto I = FNodesInTree.find(F);
1031 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1032 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1033
1034 FnTreeType::iterator IterToFNInFnTree = I->second;
1035 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1036 // Remove F -> FN and insert G -> FN
1037 FNodesInTree.erase(I);
1038 FNodesInTree.insert({G, IterToFNInFnTree});
1039 // Replace F with G in FN, which is stored inside the FnTree.
1040 FN.replaceBy(G);
1041}
1042
1043// Ordering for functions that are equal under FunctionComparator
1044static bool isFuncOrderCorrect(const Function *F, const Function *G) {
1045 if (isODR(F) != isODR(G)) {
1046 // ODR functions before non-ODR functions. A ODR function can call a non-ODR
1047 // function if it is not interposable, but not the other way around.
1048 return isODR(G);
1049 }
1050
1051 if (F->isInterposable() != G->isInterposable()) {
1052 // Strong before weak, because the weak function may call the strong
1053 // one, but not the other way around.
1054 return !F->isInterposable();
1055 }
1056
1057 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
1058 // External before local, because we definitely have to keep the external
1059 // function, but may be able to drop the local one.
1060 return !F->hasLocalLinkage();
1061 }
1062
1063 // Impose a total order (by name) on the replacement of functions. This is
1064 // important when operating on more than one module independently to prevent
1065 // cycles of thunks calling each other when the modules are linked together.
1066 return F->getName() <= G->getName();
1067}
1068
1069// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1070// that was already inserted.
1071bool MergeFunctions::insert(Function *NewFunction) {
1072 std::pair<FnTreeType::iterator, bool> Result =
1073 FnTree.insert(FunctionNode(NewFunction));
1074
1075 if (Result.second) {
1076 assert(FNodesInTree.count(NewFunction) == 0);
1077 FNodesInTree.insert({NewFunction, Result.first});
1078 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
1079 << '\n');
1080 return false;
1081 }
1082
1083 const FunctionNode &OldF = *Result.first;
1084
1085 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
1086 // Swap the two functions.
1087 Function *F = OldF.getFunc();
1088 replaceFunctionInTree(*Result.first, NewFunction);
1089 NewFunction = F;
1090 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1091 }
1092
1093 // Capture the Function pointer before mergeTwoFunctions, which may invalidate
1094 // OldF by erasing it from FnTree via removeUsers().
1095 Function *OldFunc = OldF.getFunc();
1096
1097 LLVM_DEBUG(dbgs() << " " << OldFunc->getName()
1098 << " == " << NewFunction->getName() << '\n');
1099
1100 Function *DeleteF = NewFunction;
1101 mergeTwoFunctions(OldFunc, DeleteF);
1102 this->DelToNewMap.insert({DeleteF, OldFunc});
1103 return true;
1104}
1105
1106// Remove a function from FnTree. If it was already in FnTree, add
1107// it to Deferred so that we'll look at it in the next round.
1108void MergeFunctions::remove(Function *F) {
1109 auto I = FNodesInTree.find(F);
1110 if (I != FNodesInTree.end()) {
1111 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1112 FnTree.erase(I->second);
1113 // I->second has been invalidated, remove it from the FNodesInTree map to
1114 // preserve the invariant.
1115 FNodesInTree.erase(I);
1116 Deferred.emplace_back(F);
1117 }
1118}
1119
1120// For each instruction used by the value, remove() the function that contains
1121// the instruction. This should happen right before a call to RAUW.
1122void MergeFunctions::removeUsers(Value *V) {
1123 for (User *U : V->users())
1124 if (auto *I = dyn_cast<Instruction>(U))
1125 remove(I->getFunction());
1126}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
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 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 bool hasDistinctMetadataIntrinsic(const Function &F)
Check whether F has an intrinsic which references distinct metadata as an operand.
Function * asPtr(Function *Fn)
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 bool isFuncOrderCorrect(const Function *F, const Function *G)
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
an instruction to allocate memory on the stack
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
Value handle that asserts if the Value is deleted.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
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
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)
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
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:1014
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.
@ 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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
LLVMContext & getContext() const
Definition Metadata.h:1233
static LLVM_ABI DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > F)
static LLVM_ABI bool runOnModule(Module &M)
LLVM_ABI PreservedAnalyses run(Module &M, 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
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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
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)
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
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:914
#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