LLVM 19.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"
94#include "llvm/ADT/Statistic.h"
95#include "llvm/IR/Argument.h"
96#include "llvm/IR/BasicBlock.h"
97#include "llvm/IR/Constant.h"
98#include "llvm/IR/Constants.h"
100#include "llvm/IR/DebugLoc.h"
101#include "llvm/IR/DerivedTypes.h"
102#include "llvm/IR/Function.h"
103#include "llvm/IR/GlobalValue.h"
104#include "llvm/IR/IRBuilder.h"
105#include "llvm/IR/InstrTypes.h"
106#include "llvm/IR/Instruction.h"
107#include "llvm/IR/Instructions.h"
109#include "llvm/IR/Module.h"
111#include "llvm/IR/Type.h"
112#include "llvm/IR/Use.h"
113#include "llvm/IR/User.h"
114#include "llvm/IR/Value.h"
115#include "llvm/IR/ValueHandle.h"
116#include "llvm/Support/Casting.h"
118#include "llvm/Support/Debug.h"
120#include "llvm/Transforms/IPO.h"
123#include <algorithm>
124#include <cassert>
125#include <iterator>
126#include <set>
127#include <utility>
128#include <vector>
129
130using namespace llvm;
131
132#define DEBUG_TYPE "mergefunc"
133
134STATISTIC(NumFunctionsMerged, "Number of functions merged");
135STATISTIC(NumThunksWritten, "Number of thunks generated");
136STATISTIC(NumAliasesWritten, "Number of aliases generated");
137STATISTIC(NumDoubleWeak, "Number of new functions created");
138
140 "mergefunc-verify",
141 cl::desc("How many functions in a module could be used for "
142 "MergeFunctions to pass a basic correctness check. "
143 "'0' disables this check. Works only with '-debug' key."),
144 cl::init(0), cl::Hidden);
145
146// Under option -mergefunc-preserve-debug-info we:
147// - Do not create a new function for a thunk.
148// - Retain the debug info for a thunk's parameters (and associated
149// instructions for the debug info) from the entry block.
150// Note: -debug will display the algorithm at work.
151// - Create debug-info for the call (to the shared implementation) made by
152// a thunk and its return value.
153// - Erase the rest of the function, retaining the (minimally sized) entry
154// block to create a thunk.
155// - Preserve a thunk's call site to point to the thunk even when both occur
156// within the same translation unit, to aid debugability. Note that this
157// behaviour differs from the underlying -mergefunc implementation which
158// modifies the thunk's call site to point to the shared implementation
159// when both occur within the same translation unit.
160static cl::opt<bool>
161 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
162 cl::init(false),
163 cl::desc("Preserve debug info in thunk when mergefunc "
164 "transformations are made."));
165
166static cl::opt<bool>
167 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
168 cl::init(false),
169 cl::desc("Allow mergefunc to create aliases"));
170
171namespace {
172
173class FunctionNode {
174 mutable AssertingVH<Function> F;
175 IRHash Hash;
176
177public:
178 // Note the hash is recalculated potentially multiple times, but it is cheap.
179 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
180
181 Function *getFunc() const { return F; }
182 IRHash getHash() const { return Hash; }
183
184 /// Replace the reference to the function F by the function G, assuming their
185 /// implementations are equal.
186 void replaceBy(Function *G) const {
187 F = G;
188 }
189};
190
191/// MergeFunctions finds functions which will generate identical machine code,
192/// by considering all pointer types to be equivalent. Once identified,
193/// MergeFunctions will fold them by replacing a call to one to a call to a
194/// bitcast of the other.
195class MergeFunctions {
196public:
197 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
198 }
199
200 bool runOnModule(Module &M);
201
202private:
203 // The function comparison operator is provided here so that FunctionNodes do
204 // not need to become larger with another pointer.
205 class FunctionNodeCmp {
206 GlobalNumberState* GlobalNumbers;
207
208 public:
209 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
210
211 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
212 // Order first by hashes, then full function comparison.
213 if (LHS.getHash() != RHS.getHash())
214 return LHS.getHash() < RHS.getHash();
215 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
216 return FCmp.compare() < 0;
217 }
218 };
219 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
220
221 GlobalNumberState GlobalNumbers;
222
223 /// A work queue of functions that may have been modified and should be
224 /// analyzed again.
225 std::vector<WeakTrackingVH> Deferred;
226
227 /// Set of values marked as used in llvm.used and llvm.compiler.used.
229
230#ifndef NDEBUG
231 /// Checks the rules of order relation introduced among functions set.
232 /// Returns true, if check has been passed, and false if failed.
233 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
234#endif
235
236 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
237 /// equal to one that's already present.
238 bool insert(Function *NewFunction);
239
240 /// Remove a Function from the FnTree and queue it up for a second sweep of
241 /// analysis.
242 void remove(Function *F);
243
244 /// Find the functions that use this Value and remove them from FnTree and
245 /// queue the functions.
246 void removeUsers(Value *V);
247
248 /// Replace all direct calls of Old with calls of New. Will bitcast New if
249 /// necessary to make types match.
250 void replaceDirectCallers(Function *Old, Function *New);
251
252 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
253 /// be converted into a thunk. In either case, it should never be visited
254 /// again.
255 void mergeTwoFunctions(Function *F, Function *G);
256
257 /// Fill PDIUnrelatedWL with instructions from the entry block that are
258 /// unrelated to parameter related debug info.
259 /// \param PDPVUnrelatedWL The equivalent non-intrinsic debug records.
260 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
261 std::vector<Instruction *> &PDIUnrelatedWL,
262 std::vector<DPValue *> &PDPVUnrelatedWL);
263
264 /// Erase the rest of the CFG (i.e. barring the entry block).
265 void eraseTail(Function *G);
266
267 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
268 /// parameter debug info, from the entry block.
269 /// \param PDPVUnrelatedWL contains the equivalent set of non-instruction
270 /// debug-info records.
271 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
272 std::vector<DPValue *> &PDPVUnrelatedWL);
273
274 /// Replace G with a simple tail call to bitcast(F). Also (unless
275 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
276 /// delete G.
277 void writeThunk(Function *F, Function *G);
278
279 // Replace G with an alias to F (deleting function G)
280 void writeAlias(Function *F, Function *G);
281
282 // Replace G with an alias to F if possible, or a thunk to F if possible.
283 // Returns false if neither is the case.
284 bool writeThunkOrAlias(Function *F, Function *G);
285
286 /// Replace function F with function G in the function tree.
287 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
288
289 /// The set of all distinct functions. Use the insert() and remove() methods
290 /// to modify it. The map allows efficient lookup and deferring of Functions.
291 FnTreeType FnTree;
292
293 // Map functions to the iterators of the FunctionNode which contains them
294 // in the FnTree. This must be updated carefully whenever the FnTree is
295 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
296 // dangling iterators into FnTree. The invariant that preserves this is that
297 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
298 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
299};
300} // end anonymous namespace
301
304 MergeFunctions MF;
305 if (!MF.runOnModule(M))
306 return PreservedAnalyses::all();
308}
309
310#ifndef NDEBUG
311bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
312 if (const unsigned Max = NumFunctionsForVerificationCheck) {
313 unsigned TripleNumber = 0;
314 bool Valid = true;
315
316 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
317
318 unsigned i = 0;
319 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
320 E = Worklist.end();
321 I != E && i < Max; ++I, ++i) {
322 unsigned j = i;
323 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
324 ++J, ++j) {
325 Function *F1 = cast<Function>(*I);
326 Function *F2 = cast<Function>(*J);
327 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
328 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
329
330 // If F1 <= F2, then F2 >= F1, otherwise report failure.
331 if (Res1 != -Res2) {
332 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
333 << "\n";
334 dbgs() << *F1 << '\n' << *F2 << '\n';
335 Valid = false;
336 }
337
338 if (Res1 == 0)
339 continue;
340
341 unsigned k = j;
342 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
343 ++k, ++K, ++TripleNumber) {
344 if (K == J)
345 continue;
346
347 Function *F3 = cast<Function>(*K);
348 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
349 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
350
351 bool Transitive = true;
352
353 if (Res1 != 0 && Res1 == Res4) {
354 // F1 > F2, F2 > F3 => F1 > F3
355 Transitive = Res3 == Res1;
356 } else if (Res3 != 0 && Res3 == -Res4) {
357 // F1 > F3, F3 > F2 => F1 > F2
358 Transitive = Res3 == Res1;
359 } else if (Res4 != 0 && -Res3 == Res4) {
360 // F2 > F3, F3 > F1 => F2 > F1
361 Transitive = Res4 == -Res1;
362 }
363
364 if (!Transitive) {
365 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
366 << TripleNumber << "\n";
367 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
368 << Res4 << "\n";
369 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
370 Valid = false;
371 }
372 }
373 }
374 }
375
376 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
377 return Valid;
378 }
379 return true;
380}
381#endif
382
383/// Check whether \p F has an intrinsic which references
384/// distinct metadata as an operand. The most common
385/// instance of this would be CFI checks for function-local types.
387 for (const BasicBlock &BB : F) {
388 for (const Instruction &I : BB.instructionsWithoutDebug()) {
389 if (!isa<IntrinsicInst>(&I))
390 continue;
391
392 for (Value *Op : I.operands()) {
393 auto *MDL = dyn_cast<MetadataAsValue>(Op);
394 if (!MDL)
395 continue;
396 if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
397 if (N->isDistinct())
398 return true;
399 }
400 }
401 }
402 return false;
403}
404
405/// Check whether \p F is eligible for function merging.
407 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
409}
410
411bool MergeFunctions::runOnModule(Module &M) {
412 bool Changed = false;
413
415 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
416 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
417 Used.insert(UsedV.begin(), UsedV.end());
418
419 // All functions in the module, ordered by hash. Functions with a unique
420 // hash value are easily eliminated.
421 std::vector<std::pair<IRHash, Function *>> HashedFuncs;
422 for (Function &Func : M) {
423 if (isEligibleForMerging(Func)) {
424 HashedFuncs.push_back({StructuralHash(Func), &Func});
425 }
426 }
427
428 llvm::stable_sort(HashedFuncs, less_first());
429
430 auto S = HashedFuncs.begin();
431 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
432 // If the hash value matches the previous value or the next one, we must
433 // consider merging it. Otherwise it is dropped and never considered again.
434 if ((I != S && std::prev(I)->first == I->first) ||
435 (std::next(I) != IE && std::next(I)->first == I->first) ) {
436 Deferred.push_back(WeakTrackingVH(I->second));
437 }
438 }
439
440 do {
441 std::vector<WeakTrackingVH> Worklist;
442 Deferred.swap(Worklist);
443
444 LLVM_DEBUG(doFunctionalCheck(Worklist));
445
446 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
447 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
448
449 // Insert functions and merge them.
450 for (WeakTrackingVH &I : Worklist) {
451 if (!I)
452 continue;
453 Function *F = cast<Function>(I);
454 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
455 Changed |= insert(F);
456 }
457 }
458 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
459 } while (!Deferred.empty());
460
461 FnTree.clear();
462 FNodesInTree.clear();
463 GlobalNumbers.clear();
464 Used.clear();
465
466 return Changed;
467}
468
469// Replace direct callers of Old with New.
470void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
471 for (Use &U : llvm::make_early_inc_range(Old->uses())) {
472 CallBase *CB = dyn_cast<CallBase>(U.getUser());
473 if (CB && CB->isCallee(&U)) {
474 // Do not copy attributes from the called function to the call-site.
475 // Function comparison ensures that the attributes are the same up to
476 // type congruences in byval(), in which case we need to keep the byval
477 // type of the call-site, not the callee function.
478 remove(CB->getFunction());
479 U.set(New);
480 }
481 }
482}
483
484// Helper for writeThunk,
485// Selects proper bitcast operation,
486// but a bit simpler then CastInst::getCastOpcode.
487static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
488 Type *SrcTy = V->getType();
489 if (SrcTy->isStructTy()) {
490 assert(DestTy->isStructTy());
491 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
492 Value *Result = PoisonValue::get(DestTy);
493 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
494 Value *Element =
495 createCast(Builder, Builder.CreateExtractValue(V, ArrayRef(I)),
496 DestTy->getStructElementType(I));
497
498 Result = Builder.CreateInsertValue(Result, Element, ArrayRef(I));
499 }
500 return Result;
501 }
502 assert(!DestTy->isStructTy());
503 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504 return Builder.CreateIntToPtr(V, DestTy);
505 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506 return Builder.CreatePtrToInt(V, DestTy);
507 else
508 return Builder.CreateBitCast(V, DestTy);
509}
510
511// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
512// parameter debug info, from the entry block.
513void MergeFunctions::eraseInstsUnrelatedToPDI(
514 std::vector<Instruction *> &PDIUnrelatedWL,
515 std::vector<DPValue *> &PDPVUnrelatedWL) {
517 dbgs() << " Erasing instructions (in reverse order of appearance in "
518 "entry block) unrelated to parameter debug info from entry "
519 "block: {\n");
520 while (!PDIUnrelatedWL.empty()) {
521 Instruction *I = PDIUnrelatedWL.back();
522 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
523 LLVM_DEBUG(I->print(dbgs()));
524 LLVM_DEBUG(dbgs() << "\n");
525 I->eraseFromParent();
526 PDIUnrelatedWL.pop_back();
527 }
528
529 while (!PDPVUnrelatedWL.empty()) {
530 DPValue *DPV = PDPVUnrelatedWL.back();
531 LLVM_DEBUG(dbgs() << " Deleting DPValue ");
532 LLVM_DEBUG(DPV->print(dbgs()));
533 LLVM_DEBUG(dbgs() << "\n");
534 DPV->eraseFromParent();
535 PDPVUnrelatedWL.pop_back();
536 }
537
538 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
539 "debug info from entry block. \n");
540}
541
542// Reduce G to its entry block.
543void MergeFunctions::eraseTail(Function *G) {
544 std::vector<BasicBlock *> WorklistBB;
545 for (BasicBlock &BB : drop_begin(*G)) {
546 BB.dropAllReferences();
547 WorklistBB.push_back(&BB);
548 }
549 while (!WorklistBB.empty()) {
550 BasicBlock *BB = WorklistBB.back();
551 BB->eraseFromParent();
552 WorklistBB.pop_back();
553 }
554}
555
556// We are interested in the following instructions from the entry block as being
557// related to parameter debug info:
558// - @llvm.dbg.declare
559// - stores from the incoming parameters to locations on the stack-frame
560// - allocas that create these locations on the stack-frame
561// - @llvm.dbg.value
562// - the entry block's terminator
563// The rest are unrelated to debug info for the parameters; fill up
564// PDIUnrelatedWL with such instructions.
565void MergeFunctions::filterInstsUnrelatedToPDI(
566 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
567 std::vector<DPValue *> &PDPVUnrelatedWL) {
568 std::set<Instruction *> PDIRelated;
569 std::set<DPValue *> PDPVRelated;
570
571 // Work out whether a dbg.value intrinsic or an equivalent DPValue is a
572 // parameter to be preserved.
573 auto ExamineDbgValue = [](auto *DbgVal, auto &Container) {
574 LLVM_DEBUG(dbgs() << " Deciding: ");
575 LLVM_DEBUG(DbgVal->print(dbgs()));
576 LLVM_DEBUG(dbgs() << "\n");
577 DILocalVariable *DILocVar = DbgVal->getVariable();
578 if (DILocVar->isParameter()) {
579 LLVM_DEBUG(dbgs() << " Include (parameter): ");
580 LLVM_DEBUG(DbgVal->print(dbgs()));
581 LLVM_DEBUG(dbgs() << "\n");
582 Container.insert(DbgVal);
583 } else {
584 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
585 LLVM_DEBUG(DbgVal->print(dbgs()));
586 LLVM_DEBUG(dbgs() << "\n");
587 }
588 };
589
590 auto ExamineDbgDeclare = [&PDIRelated](auto *DbgDecl, auto &Container) {
591 LLVM_DEBUG(dbgs() << " Deciding: ");
592 LLVM_DEBUG(DbgDecl->print(dbgs()));
593 LLVM_DEBUG(dbgs() << "\n");
594 DILocalVariable *DILocVar = DbgDecl->getVariable();
595 if (DILocVar->isParameter()) {
596 LLVM_DEBUG(dbgs() << " Parameter: ");
597 LLVM_DEBUG(DILocVar->print(dbgs()));
598 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
599 if (AI) {
600 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
601 LLVM_DEBUG(dbgs() << "\n");
602 for (User *U : AI->users()) {
603 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
604 if (Value *Arg = SI->getValueOperand()) {
605 if (isa<Argument>(Arg)) {
606 LLVM_DEBUG(dbgs() << " Include: ");
607 LLVM_DEBUG(AI->print(dbgs()));
608 LLVM_DEBUG(dbgs() << "\n");
609 PDIRelated.insert(AI);
610 LLVM_DEBUG(dbgs() << " Include (parameter): ");
611 LLVM_DEBUG(SI->print(dbgs()));
612 LLVM_DEBUG(dbgs() << "\n");
613 PDIRelated.insert(SI);
614 LLVM_DEBUG(dbgs() << " Include: ");
615 LLVM_DEBUG(DbgDecl->print(dbgs()));
616 LLVM_DEBUG(dbgs() << "\n");
617 Container.insert(DbgDecl);
618 } else {
619 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
620 LLVM_DEBUG(SI->print(dbgs()));
621 LLVM_DEBUG(dbgs() << "\n");
622 }
623 }
624 } else {
625 LLVM_DEBUG(dbgs() << " Defer: ");
626 LLVM_DEBUG(U->print(dbgs()));
627 LLVM_DEBUG(dbgs() << "\n");
628 }
629 }
630 } else {
631 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
632 LLVM_DEBUG(DbgDecl->print(dbgs()));
633 LLVM_DEBUG(dbgs() << "\n");
634 }
635 } else {
636 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
637 LLVM_DEBUG(DbgDecl->print(dbgs()));
638 LLVM_DEBUG(dbgs() << "\n");
639 }
640 };
641
642 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
643 BI != BIE; ++BI) {
644 // Examine DPValues as they happen "before" the instruction. Are they
645 // connected to parameters?
646 for (DPValue &DPV : DPValue::filter(BI->getDbgValueRange())) {
647 if (DPV.isDbgValue() || DPV.isDbgAssign()) {
648 ExamineDbgValue(&DPV, PDPVRelated);
649 } else {
650 assert(DPV.isDbgDeclare());
651 ExamineDbgDeclare(&DPV, PDPVRelated);
652 }
653 }
654
655 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
656 ExamineDbgValue(DVI, PDIRelated);
657 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
658 ExamineDbgDeclare(DDI, PDIRelated);
659 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
660 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
661 LLVM_DEBUG(BI->print(dbgs()));
662 LLVM_DEBUG(dbgs() << "\n");
663 PDIRelated.insert(&*BI);
664 } else {
665 LLVM_DEBUG(dbgs() << " Defer: ");
666 LLVM_DEBUG(BI->print(dbgs()));
667 LLVM_DEBUG(dbgs() << "\n");
668 }
669 }
671 dbgs()
672 << " Report parameter debug info related/related instructions: {\n");
673
674 auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
675 if (Container.find(Rec) == Container.end()) {
676 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
677 LLVM_DEBUG(Rec->print(dbgs()));
678 LLVM_DEBUG(dbgs() << "\n");
679 UnrelatedCont.push_back(Rec);
680 } else {
681 LLVM_DEBUG(dbgs() << " PDIRelated: ");
682 LLVM_DEBUG(Rec->print(dbgs()));
683 LLVM_DEBUG(dbgs() << "\n");
684 }
685 };
686
687 // Collect the set of unrelated instructions and debug records.
688 for (Instruction &I : *GEntryBlock) {
689 for (DPValue &DPV : DPValue::filter(I.getDbgValueRange()))
690 IsPDIRelated(&DPV, PDPVRelated, PDPVUnrelatedWL);
691 IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
692 }
693 LLVM_DEBUG(dbgs() << " }\n");
694}
695
696/// Whether this function may be replaced by a forwarding thunk.
698 if (F->isVarArg())
699 return false;
700
701 // Don't merge tiny functions using a thunk, since it can just end up
702 // making the function larger.
703 if (F->size() == 1) {
704 if (F->front().sizeWithoutDebug() < 2) {
705 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
706 << " is too small to bother creating a thunk for\n");
707 return false;
708 }
709 }
710 return true;
711}
712
713/// Copy metadata from one function to another.
715 if (MDNode *MD = From->getMetadata(Key)) {
716 To->setMetadata(Key, MD);
717 }
718}
719
720// Replace G with a simple tail call to bitcast(F). Also (unless
721// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
722// delete G. Under MergeFunctionsPDI, we use G itself for creating
723// the thunk as we preserve the debug info (and associated instructions)
724// from G's entry block pertaining to G's incoming arguments which are
725// passed on as corresponding arguments in the call that G makes to F.
726// For better debugability, under MergeFunctionsPDI, we do not modify G's
727// call sites to point to F even when within the same translation unit.
728void MergeFunctions::writeThunk(Function *F, Function *G) {
729 BasicBlock *GEntryBlock = nullptr;
730 std::vector<Instruction *> PDIUnrelatedWL;
731 std::vector<DPValue *> PDPVUnrelatedWL;
732 BasicBlock *BB = nullptr;
733 Function *NewG = nullptr;
734 if (MergeFunctionsPDI) {
735 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
736 "function as thunk; retain original: "
737 << G->getName() << "()\n");
738 GEntryBlock = &G->getEntryBlock();
740 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
741 "debug info for "
742 << G->getName() << "() {\n");
743 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDPVUnrelatedWL);
744 GEntryBlock->getTerminator()->eraseFromParent();
745 BB = GEntryBlock;
746 } else {
747 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
748 G->getAddressSpace(), "", G->getParent());
749 NewG->setComdat(G->getComdat());
750 NewG->IsNewDbgInfoFormat = G->IsNewDbgInfoFormat;
751 BB = BasicBlock::Create(F->getContext(), "", NewG);
752 }
753
754 IRBuilder<> Builder(BB);
755 Function *H = MergeFunctionsPDI ? G : NewG;
757 unsigned i = 0;
758 FunctionType *FFTy = F->getFunctionType();
759 for (Argument &AI : H->args()) {
760 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
761 ++i;
762 }
763
764 CallInst *CI = Builder.CreateCall(F, Args);
765 ReturnInst *RI = nullptr;
766 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
767 G->getCallingConv() == CallingConv::SwiftTail;
770 CI->setCallingConv(F->getCallingConv());
771 CI->setAttributes(F->getAttributes());
772 if (H->getReturnType()->isVoidTy()) {
773 RI = Builder.CreateRetVoid();
774 } else {
775 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
776 }
777
778 if (MergeFunctionsPDI) {
779 DISubprogram *DIS = G->getSubprogram();
780 if (DIS) {
781 DebugLoc CIDbgLoc =
782 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
783 DebugLoc RIDbgLoc =
784 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
785 CI->setDebugLoc(CIDbgLoc);
786 RI->setDebugLoc(RIDbgLoc);
787 } else {
789 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
790 << G->getName() << "()\n");
791 }
792 eraseTail(G);
793 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDPVUnrelatedWL);
795 dbgs() << "} // End of parameter related debug info filtering for: "
796 << G->getName() << "()\n");
797 } else {
798 NewG->copyAttributesFrom(G);
799 NewG->takeName(G);
800 // Ensure CFI type metadata is propagated to the new function.
801 copyMetadataIfPresent(G, NewG, "type");
802 copyMetadataIfPresent(G, NewG, "kcfi_type");
803 removeUsers(G);
804 G->replaceAllUsesWith(NewG);
805 G->eraseFromParent();
806 }
807
808 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
809 ++NumThunksWritten;
810}
811
812// Whether this function may be replaced by an alias
814 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
815 return false;
816
817 // We should only see linkages supported by aliases here
818 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
819 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
820 return true;
821}
822
823// Replace G with an alias to F (deleting function G)
824void MergeFunctions::writeAlias(Function *F, Function *G) {
825 PointerType *PtrType = G->getType();
826 auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(),
827 G->getLinkage(), "", F, G->getParent());
828
829 const MaybeAlign FAlign = F->getAlign();
830 const MaybeAlign GAlign = G->getAlign();
831 if (FAlign || GAlign)
832 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
833 else
834 F->setAlignment(std::nullopt);
835 GA->takeName(G);
836 GA->setVisibility(G->getVisibility());
837 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
838
839 removeUsers(G);
840 G->replaceAllUsesWith(GA);
841 G->eraseFromParent();
842
843 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
844 ++NumAliasesWritten;
845}
846
847// Replace G with an alias to F if possible, or a thunk to F if
848// profitable. Returns false if neither is the case.
849bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
850 if (canCreateAliasFor(G)) {
851 writeAlias(F, G);
852 return true;
853 }
854 if (canCreateThunkFor(F)) {
855 writeThunk(F, G);
856 return true;
857 }
858 return false;
859}
860
861// Merge two equivalent functions. Upon completion, Function G is deleted.
862void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
863 if (F->isInterposable()) {
864 assert(G->isInterposable());
865
866 // Both writeThunkOrAlias() calls below must succeed, either because we can
867 // create aliases for G and NewF, or because a thunk for F is profitable.
868 // F here has the same signature as NewF below, so that's what we check.
869 if (!canCreateThunkFor(F) &&
871 return;
872
873 // Make them both thunks to the same internal function.
874 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
875 F->getAddressSpace(), "", F->getParent());
876 NewF->copyAttributesFrom(F);
877 NewF->takeName(F);
878 NewF->IsNewDbgInfoFormat = F->IsNewDbgInfoFormat;
879 // Ensure CFI type metadata is propagated to the new function.
880 copyMetadataIfPresent(F, NewF, "type");
881 copyMetadataIfPresent(F, NewF, "kcfi_type");
882 removeUsers(F);
883 F->replaceAllUsesWith(NewF);
884
885 // We collect alignment before writeThunkOrAlias that overwrites NewF and
886 // G's content.
887 const MaybeAlign NewFAlign = NewF->getAlign();
888 const MaybeAlign GAlign = G->getAlign();
889
890 writeThunkOrAlias(F, G);
891 writeThunkOrAlias(F, NewF);
892
893 if (NewFAlign || GAlign)
894 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
895 else
896 F->setAlignment(std::nullopt);
897 F->setLinkage(GlobalValue::PrivateLinkage);
898 ++NumDoubleWeak;
899 ++NumFunctionsMerged;
900 } else {
901 // For better debugability, under MergeFunctionsPDI, we do not modify G's
902 // call sites to point to F even when within the same translation unit.
903 if (!G->isInterposable() && !MergeFunctionsPDI) {
904 // Functions referred to by llvm.used/llvm.compiler.used are special:
905 // there are uses of the symbol name that are not visible to LLVM,
906 // usually from inline asm.
907 if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
908 // G might have been a key in our GlobalNumberState, and it's illegal
909 // to replace a key in ValueMap<GlobalValue *> with a non-global.
910 GlobalNumbers.erase(G);
911 // If G's address is not significant, replace it entirely.
912 removeUsers(G);
913 G->replaceAllUsesWith(F);
914 } else {
915 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
916 // above).
917 replaceDirectCallers(G, F);
918 }
919 }
920
921 // If G was internal then we may have replaced all uses of G with F. If so,
922 // stop here and delete G. There's no need for a thunk. (See note on
923 // MergeFunctionsPDI above).
924 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
925 G->eraseFromParent();
926 ++NumFunctionsMerged;
927 return;
928 }
929
930 if (writeThunkOrAlias(F, G)) {
931 ++NumFunctionsMerged;
932 }
933 }
934}
935
936/// Replace function F by function G.
937void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
938 Function *G) {
939 Function *F = FN.getFunc();
940 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
941 "The two functions must be equal");
942
943 auto I = FNodesInTree.find(F);
944 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
945 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
946
947 FnTreeType::iterator IterToFNInFnTree = I->second;
948 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
949 // Remove F -> FN and insert G -> FN
950 FNodesInTree.erase(I);
951 FNodesInTree.insert({G, IterToFNInFnTree});
952 // Replace F with G in FN, which is stored inside the FnTree.
953 FN.replaceBy(G);
954}
955
956// Ordering for functions that are equal under FunctionComparator
957static bool isFuncOrderCorrect(const Function *F, const Function *G) {
958 if (F->isInterposable() != G->isInterposable()) {
959 // Strong before weak, because the weak function may call the strong
960 // one, but not the other way around.
961 return !F->isInterposable();
962 }
963 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
964 // External before local, because we definitely have to keep the external
965 // function, but may be able to drop the local one.
966 return !F->hasLocalLinkage();
967 }
968 // Impose a total order (by name) on the replacement of functions. This is
969 // important when operating on more than one module independently to prevent
970 // cycles of thunks calling each other when the modules are linked together.
971 return F->getName() <= G->getName();
972}
973
974// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
975// that was already inserted.
976bool MergeFunctions::insert(Function *NewFunction) {
977 std::pair<FnTreeType::iterator, bool> Result =
978 FnTree.insert(FunctionNode(NewFunction));
979
980 if (Result.second) {
981 assert(FNodesInTree.count(NewFunction) == 0);
982 FNodesInTree.insert({NewFunction, Result.first});
983 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
984 << '\n');
985 return false;
986 }
987
988 const FunctionNode &OldF = *Result.first;
989
990 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
991 // Swap the two functions.
992 Function *F = OldF.getFunc();
993 replaceFunctionInTree(*Result.first, NewFunction);
994 NewFunction = F;
995 assert(OldF.getFunc() != F && "Must have swapped the functions.");
996 }
997
998 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
999 << " == " << NewFunction->getName() << '\n');
1000
1001 Function *DeleteF = NewFunction;
1002 mergeTwoFunctions(OldF.getFunc(), DeleteF);
1003 return true;
1004}
1005
1006// Remove a function from FnTree. If it was already in FnTree, add
1007// it to Deferred so that we'll look at it in the next round.
1008void MergeFunctions::remove(Function *F) {
1009 auto I = FNodesInTree.find(F);
1010 if (I != FNodesInTree.end()) {
1011 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1012 FnTree.erase(I->second);
1013 // I->second has been invalidated, remove it from the FNodesInTree map to
1014 // preserve the invariant.
1015 FNodesInTree.erase(I);
1016 Deferred.emplace_back(F);
1017 }
1018}
1019
1020// For each instruction used by the value, remove() the function that contains
1021// the instruction. This should happen right before a call to RAUW.
1022void MergeFunctions::removeUsers(Value *V) {
1023 for (User *U : V->users())
1024 if (auto *I = dyn_cast<Instruction>(U))
1025 remove(I->getFunction());
1026}
BlockVerifier::State From
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define H(x, y, z)
Definition: MD5.cpp:57
static bool canCreateAliasFor(Function *F)
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
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 void copyMetadataIfPresent(Function *From, Function *To, StringRef Key)
Copy metadata from one function to another.
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.
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
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)
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:167
This defines the Use class.
Value * RHS
Value * LHS
an instruction to allocate memory on the stack
Definition: Instructions.h:59
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:348
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Value handle that asserts if the Value is deleted.
Definition: ValueHandle.h:264
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator end()
Definition: BasicBlock.h:451
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:438
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:207
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:323
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:173
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:229
const Instruction & back() const
Definition: BasicBlock.h:463
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1259
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1543
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
Definition: InstrTypes.h:1492
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1562
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
Subprogram description.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void print(raw_ostream &O, bool IsForDebug=false) const
Definition: AsmWriter.cpp:4903
static auto filter(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DPValue types only and downcast.
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
int compare()
Test whether the two functions have equivalent behaviour.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:162
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
Definition: Function.h:106
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:781
static 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:518
GlobalNumberState assigns an integer to each global value in the program, which is used by the compar...
void erase(GlobalValue *Global)
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:80
void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1485
void setComdat(Comdat *C)
Definition: Globals.cpp:197
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2506
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2499
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2105
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2110
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2100
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2649
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:93
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:75
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:449
Metadata node.
Definition: Metadata.h:1067
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
LLVMContext & getContext() const
Definition: Metadata.h:1231
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
Definition: AsmWriter.cpp:5168
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:302
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Type * getStructElementType(unsigned N) const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
unsigned getStructNumElements() const
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:249
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4969
iterator_range< user_iterator > users()
Definition: Value.h:421
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
void pop_back()
Definition: ilist.h:255
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.
Definition: ScaledNumber.h:252
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
void stable_sort(R &&Range)
Definition: STLExtras.h:1975
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:665
IRHash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:821
#define N
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1459