LLVM  9.0.0svn
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 
91 #include "llvm/ADT/ArrayRef.h"
92 #include "llvm/ADT/SmallPtrSet.h"
93 #include "llvm/ADT/SmallVector.h"
94 #include "llvm/ADT/Statistic.h"
95 #include "llvm/IR/Argument.h"
96 #include "llvm/IR/Attributes.h"
97 #include "llvm/IR/BasicBlock.h"
98 #include "llvm/IR/CallSite.h"
99 #include "llvm/IR/Constant.h"
100 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DebugLoc.h"
103 #include "llvm/IR/DerivedTypes.h"
104 #include "llvm/IR/Function.h"
105 #include "llvm/IR/GlobalValue.h"
106 #include "llvm/IR/IRBuilder.h"
107 #include "llvm/IR/InstrTypes.h"
108 #include "llvm/IR/Instruction.h"
109 #include "llvm/IR/Instructions.h"
110 #include "llvm/IR/IntrinsicInst.h"
111 #include "llvm/IR/Module.h"
112 #include "llvm/IR/Type.h"
113 #include "llvm/IR/Use.h"
114 #include "llvm/IR/User.h"
115 #include "llvm/IR/Value.h"
116 #include "llvm/IR/ValueHandle.h"
117 #include "llvm/IR/ValueMap.h"
118 #include "llvm/Pass.h"
119 #include "llvm/Support/Casting.h"
121 #include "llvm/Support/Debug.h"
123 #include "llvm/Transforms/IPO.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <iterator>
128 #include <set>
129 #include <utility>
130 #include <vector>
131 
132 using namespace llvm;
133 
134 #define DEBUG_TYPE "mergefunc"
135 
136 STATISTIC(NumFunctionsMerged, "Number of functions merged");
137 STATISTIC(NumThunksWritten, "Number of thunks generated");
138 STATISTIC(NumAliasesWritten, "Number of aliases generated");
139 STATISTIC(NumDoubleWeak, "Number of new functions created");
140 
142  "mergefunc-sanity",
143  cl::desc("How many functions in module could be used for "
144  "MergeFunctions pass sanity check. "
145  "'0' disables this check. Works only with '-debug' key."),
146  cl::init(0), cl::Hidden);
147 
148 // Under option -mergefunc-preserve-debug-info we:
149 // - Do not create a new function for a thunk.
150 // - Retain the debug info for a thunk's parameters (and associated
151 // instructions for the debug info) from the entry block.
152 // Note: -debug will display the algorithm at work.
153 // - Create debug-info for the call (to the shared implementation) made by
154 // a thunk and its return value.
155 // - Erase the rest of the function, retaining the (minimally sized) entry
156 // block to create a thunk.
157 // - Preserve a thunk's call site to point to the thunk even when both occur
158 // within the same translation unit, to aid debugability. Note that this
159 // behaviour differs from the underlying -mergefunc implementation which
160 // modifies the thunk's call site to point to the shared implementation
161 // when both occur within the same translation unit.
162 static cl::opt<bool>
163  MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
164  cl::init(false),
165  cl::desc("Preserve debug info in thunk when mergefunc "
166  "transformations are made."));
167 
168 static cl::opt<bool>
169  MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
170  cl::init(false),
171  cl::desc("Allow mergefunc to create aliases"));
172 
173 namespace {
174 
175 class FunctionNode {
176  mutable AssertingVH<Function> F;
178 
179 public:
180  // Note the hash is recalculated potentially multiple times, but it is cheap.
181  FunctionNode(Function *F)
182  : F(F), Hash(FunctionComparator::functionHash(*F)) {}
183 
184  Function *getFunc() const { return F; }
185  FunctionComparator::FunctionHash getHash() const { return Hash; }
186 
187  /// Replace the reference to the function F by the function G, assuming their
188  /// implementations are equal.
189  void replaceBy(Function *G) const {
190  F = G;
191  }
192 
193  void release() { F = nullptr; }
194 };
195 
196 /// MergeFunctions finds functions which will generate identical machine code,
197 /// by considering all pointer types to be equivalent. Once identified,
198 /// MergeFunctions will fold them by replacing a call to one to a call to a
199 /// bitcast of the other.
200 class MergeFunctions : public ModulePass {
201 public:
202  static char ID;
203 
204  MergeFunctions()
205  : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
207  }
208 
209  bool runOnModule(Module &M) override;
210 
211 private:
212  // The function comparison operator is provided here so that FunctionNodes do
213  // not need to become larger with another pointer.
214  class FunctionNodeCmp {
215  GlobalNumberState* GlobalNumbers;
216 
217  public:
218  FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
219 
220  bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
221  // Order first by hashes, then full function comparison.
222  if (LHS.getHash() != RHS.getHash())
223  return LHS.getHash() < RHS.getHash();
224  FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
225  return FCmp.compare() == -1;
226  }
227  };
228  using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
229 
230  GlobalNumberState GlobalNumbers;
231 
232  /// A work queue of functions that may have been modified and should be
233  /// analyzed again.
234  std::vector<WeakTrackingVH> Deferred;
235 
236 #ifndef NDEBUG
237  /// Checks the rules of order relation introduced among functions set.
238  /// Returns true, if sanity check has been passed, and false if failed.
239  bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
240 #endif
241 
242  /// Insert a ComparableFunction into the FnTree, or merge it away if it's
243  /// equal to one that's already present.
244  bool insert(Function *NewFunction);
245 
246  /// Remove a Function from the FnTree and queue it up for a second sweep of
247  /// analysis.
248  void remove(Function *F);
249 
250  /// Find the functions that use this Value and remove them from FnTree and
251  /// queue the functions.
252  void removeUsers(Value *V);
253 
254  /// Replace all direct calls of Old with calls of New. Will bitcast New if
255  /// necessary to make types match.
256  void replaceDirectCallers(Function *Old, Function *New);
257 
258  /// Merge two equivalent functions. Upon completion, G may be deleted, or may
259  /// be converted into a thunk. In either case, it should never be visited
260  /// again.
261  void mergeTwoFunctions(Function *F, Function *G);
262 
263  /// Fill PDIUnrelatedWL with instructions from the entry block that are
264  /// unrelated to parameter related debug info.
265  void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
266  std::vector<Instruction *> &PDIUnrelatedWL);
267 
268  /// Erase the rest of the CFG (i.e. barring the entry block).
269  void eraseTail(Function *G);
270 
271  /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
272  /// parameter debug info, from the entry block.
273  void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
274 
275  /// Replace G with a simple tail call to bitcast(F). Also (unless
276  /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
277  /// delete G.
278  void writeThunk(Function *F, Function *G);
279 
280  // Replace G with an alias to F (deleting function G)
281  void writeAlias(Function *F, Function *G);
282 
283  // Replace G with an alias to F if possible, or a thunk to F if possible.
284  // Returns false if neither is the case.
285  bool writeThunkOrAlias(Function *F, Function *G);
286 
287  /// Replace function F with function G in the function tree.
288  void replaceFunctionInTree(const FunctionNode &FN, Function *G);
289 
290  /// The set of all distinct functions. Use the insert() and remove() methods
291  /// to modify it. The map allows efficient lookup and deferring of Functions.
292  FnTreeType FnTree;
293 
294  // Map functions to the iterators of the FunctionNode which contains them
295  // in the FnTree. This must be updated carefully whenever the FnTree is
296  // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
297  // dangling iterators into FnTree. The invariant that preserves this is that
298  // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
299  DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
300 };
301 
302 } // end anonymous namespace
303 
304 char MergeFunctions::ID = 0;
305 
306 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
307 
309  return new MergeFunctions();
310 }
311 
312 #ifndef NDEBUG
313 bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
314  if (const unsigned Max = NumFunctionsForSanityCheck) {
315  unsigned TripleNumber = 0;
316  bool Valid = true;
317 
318  dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
319 
320  unsigned i = 0;
321  for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
322  E = Worklist.end();
323  I != E && i < Max; ++I, ++i) {
324  unsigned j = i;
325  for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
326  ++J, ++j) {
327  Function *F1 = cast<Function>(*I);
328  Function *F2 = cast<Function>(*J);
329  int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
330  int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
331 
332  // If F1 <= F2, then F2 >= F1, otherwise report failure.
333  if (Res1 != -Res2) {
334  dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
335  << "\n";
336  dbgs() << *F1 << '\n' << *F2 << '\n';
337  Valid = false;
338  }
339 
340  if (Res1 == 0)
341  continue;
342 
343  unsigned k = j;
344  for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
345  ++k, ++K, ++TripleNumber) {
346  if (K == J)
347  continue;
348 
349  Function *F3 = cast<Function>(*K);
350  int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
351  int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
352 
353  bool Transitive = true;
354 
355  if (Res1 != 0 && Res1 == Res4) {
356  // F1 > F2, F2 > F3 => F1 > F3
357  Transitive = Res3 == Res1;
358  } else if (Res3 != 0 && Res3 == -Res4) {
359  // F1 > F3, F3 > F2 => F1 > F2
360  Transitive = Res3 == Res1;
361  } else if (Res4 != 0 && -Res3 == Res4) {
362  // F2 > F3, F3 > F1 => F2 > F1
363  Transitive = Res4 == -Res1;
364  }
365 
366  if (!Transitive) {
367  dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
368  << TripleNumber << "\n";
369  dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
370  << Res4 << "\n";
371  dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
372  Valid = false;
373  }
374  }
375  }
376  }
377 
378  dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
379  return Valid;
380  }
381  return true;
382 }
383 #endif
384 
385 /// Check whether \p F is eligible for function merging.
387  return !F.isDeclaration() && !F.hasAvailableExternallyLinkage();
388 }
389 
390 bool MergeFunctions::runOnModule(Module &M) {
391  if (skipModule(M))
392  return false;
393 
394  bool Changed = false;
395 
396  // All functions in the module, ordered by hash. Functions with a unique
397  // hash value are easily eliminated.
398  std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
399  HashedFuncs;
400  for (Function &Func : M) {
401  if (isEligibleForMerging(Func)) {
402  HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
403  }
404  }
405 
406  std::stable_sort(
407  HashedFuncs.begin(), HashedFuncs.end(),
408  [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
409  const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
410  return a.first < b.first;
411  });
412 
413  auto S = HashedFuncs.begin();
414  for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
415  // If the hash value matches the previous value or the next one, we must
416  // consider merging it. Otherwise it is dropped and never considered again.
417  if ((I != S && std::prev(I)->first == I->first) ||
418  (std::next(I) != IE && std::next(I)->first == I->first) ) {
419  Deferred.push_back(WeakTrackingVH(I->second));
420  }
421  }
422 
423  do {
424  std::vector<WeakTrackingVH> Worklist;
425  Deferred.swap(Worklist);
426 
427  LLVM_DEBUG(doSanityCheck(Worklist));
428 
429  LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
430  LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
431 
432  // Insert functions and merge them.
433  for (WeakTrackingVH &I : Worklist) {
434  if (!I)
435  continue;
436  Function *F = cast<Function>(I);
437  if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
438  Changed |= insert(F);
439  }
440  }
441  LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
442  } while (!Deferred.empty());
443 
444  FnTree.clear();
445  FNodesInTree.clear();
446  GlobalNumbers.clear();
447 
448  return Changed;
449 }
450 
451 // Replace direct callers of Old with New.
452 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
453  Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
454  for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
455  Use *U = &*UI;
456  ++UI;
457  CallSite CS(U->getUser());
458  if (CS && CS.isCallee(U)) {
459  // Transfer the called function's attributes to the call site. Due to the
460  // bitcast we will 'lose' ABI changing attributes because the 'called
461  // function' is no longer a Function* but the bitcast. Code that looks up
462  // the attributes from the called function will fail.
463 
464  // FIXME: This is not actually true, at least not anymore. The callsite
465  // will always have the same ABI affecting attributes as the callee,
466  // because otherwise the original input has UB. Note that Old and New
467  // always have matching ABI, so no attributes need to be changed.
468  // Transferring other attributes may help other optimizations, but that
469  // should be done uniformly and not in this ad-hoc way.
470  auto &Context = New->getContext();
471  auto NewPAL = New->getAttributes();
472  SmallVector<AttributeSet, 4> NewArgAttrs;
473  for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
474  NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
475  // Don't transfer attributes from the function to the callee. Function
476  // attributes typically aren't relevant to the calling convention or ABI.
477  CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
478  NewPAL.getRetAttributes(),
479  NewArgAttrs));
480 
481  remove(CS.getInstruction()->getFunction());
482  U->set(BitcastNew);
483  }
484  }
485 }
486 
487 // Helper for writeThunk,
488 // Selects proper bitcast operation,
489 // but a bit simpler then CastInst::getCastOpcode.
490 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
491  Type *SrcTy = V->getType();
492  if (SrcTy->isStructTy()) {
493  assert(DestTy->isStructTy());
494  assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
495  Value *Result = UndefValue::get(DestTy);
496  for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
497  Value *Element = createCast(
498  Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
499  DestTy->getStructElementType(I));
500 
501  Result =
502  Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
503  }
504  return Result;
505  }
506  assert(!DestTy->isStructTy());
507  if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
508  return Builder.CreateIntToPtr(V, DestTy);
509  else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
510  return Builder.CreatePtrToInt(V, DestTy);
511  else
512  return Builder.CreateBitCast(V, DestTy);
513 }
514 
515 // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
516 // parameter debug info, from the entry block.
517 void MergeFunctions::eraseInstsUnrelatedToPDI(
518  std::vector<Instruction *> &PDIUnrelatedWL) {
519  LLVM_DEBUG(
520  dbgs() << " Erasing instructions (in reverse order of appearance in "
521  "entry block) unrelated to parameter debug info from entry "
522  "block: {\n");
523  while (!PDIUnrelatedWL.empty()) {
524  Instruction *I = PDIUnrelatedWL.back();
525  LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
526  LLVM_DEBUG(I->print(dbgs()));
527  LLVM_DEBUG(dbgs() << "\n");
528  I->eraseFromParent();
529  PDIUnrelatedWL.pop_back();
530  }
531  LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
532  "debug info from entry block. \n");
533 }
534 
535 // Reduce G to its entry block.
536 void MergeFunctions::eraseTail(Function *G) {
537  std::vector<BasicBlock *> WorklistBB;
538  for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
539  BBI != BBE; ++BBI) {
540  BBI->dropAllReferences();
541  WorklistBB.push_back(&*BBI);
542  }
543  while (!WorklistBB.empty()) {
544  BasicBlock *BB = WorklistBB.back();
545  BB->eraseFromParent();
546  WorklistBB.pop_back();
547  }
548 }
549 
550 // We are interested in the following instructions from the entry block as being
551 // related to parameter debug info:
552 // - @llvm.dbg.declare
553 // - stores from the incoming parameters to locations on the stack-frame
554 // - allocas that create these locations on the stack-frame
555 // - @llvm.dbg.value
556 // - the entry block's terminator
557 // The rest are unrelated to debug info for the parameters; fill up
558 // PDIUnrelatedWL with such instructions.
559 void MergeFunctions::filterInstsUnrelatedToPDI(
560  BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
561  std::set<Instruction *> PDIRelated;
562  for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
563  BI != BIE; ++BI) {
564  if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
565  LLVM_DEBUG(dbgs() << " Deciding: ");
566  LLVM_DEBUG(BI->print(dbgs()));
567  LLVM_DEBUG(dbgs() << "\n");
568  DILocalVariable *DILocVar = DVI->getVariable();
569  if (DILocVar->isParameter()) {
570  LLVM_DEBUG(dbgs() << " Include (parameter): ");
571  LLVM_DEBUG(BI->print(dbgs()));
572  LLVM_DEBUG(dbgs() << "\n");
573  PDIRelated.insert(&*BI);
574  } else {
575  LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
576  LLVM_DEBUG(BI->print(dbgs()));
577  LLVM_DEBUG(dbgs() << "\n");
578  }
579  } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
580  LLVM_DEBUG(dbgs() << " Deciding: ");
581  LLVM_DEBUG(BI->print(dbgs()));
582  LLVM_DEBUG(dbgs() << "\n");
583  DILocalVariable *DILocVar = DDI->getVariable();
584  if (DILocVar->isParameter()) {
585  LLVM_DEBUG(dbgs() << " Parameter: ");
586  LLVM_DEBUG(DILocVar->print(dbgs()));
587  AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
588  if (AI) {
589  LLVM_DEBUG(dbgs() << " Processing alloca users: ");
590  LLVM_DEBUG(dbgs() << "\n");
591  for (User *U : AI->users()) {
592  if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
593  if (Value *Arg = SI->getValueOperand()) {
594  if (dyn_cast<Argument>(Arg)) {
595  LLVM_DEBUG(dbgs() << " Include: ");
596  LLVM_DEBUG(AI->print(dbgs()));
597  LLVM_DEBUG(dbgs() << "\n");
598  PDIRelated.insert(AI);
599  LLVM_DEBUG(dbgs() << " Include (parameter): ");
600  LLVM_DEBUG(SI->print(dbgs()));
601  LLVM_DEBUG(dbgs() << "\n");
602  PDIRelated.insert(SI);
603  LLVM_DEBUG(dbgs() << " Include: ");
604  LLVM_DEBUG(BI->print(dbgs()));
605  LLVM_DEBUG(dbgs() << "\n");
606  PDIRelated.insert(&*BI);
607  } else {
608  LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
609  LLVM_DEBUG(SI->print(dbgs()));
610  LLVM_DEBUG(dbgs() << "\n");
611  }
612  }
613  } else {
614  LLVM_DEBUG(dbgs() << " Defer: ");
615  LLVM_DEBUG(U->print(dbgs()));
616  LLVM_DEBUG(dbgs() << "\n");
617  }
618  }
619  } else {
620  LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
621  LLVM_DEBUG(BI->print(dbgs()));
622  LLVM_DEBUG(dbgs() << "\n");
623  }
624  } else {
625  LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
626  LLVM_DEBUG(BI->print(dbgs()));
627  LLVM_DEBUG(dbgs() << "\n");
628  }
629  } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
630  LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
631  LLVM_DEBUG(BI->print(dbgs()));
632  LLVM_DEBUG(dbgs() << "\n");
633  PDIRelated.insert(&*BI);
634  } else {
635  LLVM_DEBUG(dbgs() << " Defer: ");
636  LLVM_DEBUG(BI->print(dbgs()));
637  LLVM_DEBUG(dbgs() << "\n");
638  }
639  }
640  LLVM_DEBUG(
641  dbgs()
642  << " Report parameter debug info related/related instructions: {\n");
643  for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
644  BI != BE; ++BI) {
645 
646  Instruction *I = &*BI;
647  if (PDIRelated.find(I) == PDIRelated.end()) {
648  LLVM_DEBUG(dbgs() << " !PDIRelated: ");
649  LLVM_DEBUG(I->print(dbgs()));
650  LLVM_DEBUG(dbgs() << "\n");
651  PDIUnrelatedWL.push_back(I);
652  } else {
653  LLVM_DEBUG(dbgs() << " PDIRelated: ");
654  LLVM_DEBUG(I->print(dbgs()));
655  LLVM_DEBUG(dbgs() << "\n");
656  }
657  }
658  LLVM_DEBUG(dbgs() << " }\n");
659 }
660 
661 /// Whether this function may be replaced by a forwarding thunk.
662 static bool canCreateThunkFor(Function *F) {
663  if (F->isVarArg())
664  return false;
665 
666  // Don't merge tiny functions using a thunk, since it can just end up
667  // making the function larger.
668  if (F->size() == 1) {
669  if (F->front().size() <= 2) {
670  LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
671  << " is too small to bother creating a thunk for\n");
672  return false;
673  }
674  }
675  return true;
676 }
677 
678 // Replace G with a simple tail call to bitcast(F). Also (unless
679 // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
680 // delete G. Under MergeFunctionsPDI, we use G itself for creating
681 // the thunk as we preserve the debug info (and associated instructions)
682 // from G's entry block pertaining to G's incoming arguments which are
683 // passed on as corresponding arguments in the call that G makes to F.
684 // For better debugability, under MergeFunctionsPDI, we do not modify G's
685 // call sites to point to F even when within the same translation unit.
686 void MergeFunctions::writeThunk(Function *F, Function *G) {
687  BasicBlock *GEntryBlock = nullptr;
688  std::vector<Instruction *> PDIUnrelatedWL;
689  BasicBlock *BB = nullptr;
690  Function *NewG = nullptr;
691  if (MergeFunctionsPDI) {
692  LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
693  "function as thunk; retain original: "
694  << G->getName() << "()\n");
695  GEntryBlock = &G->getEntryBlock();
696  LLVM_DEBUG(
697  dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
698  "debug info for "
699  << G->getName() << "() {\n");
700  filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
701  GEntryBlock->getTerminator()->eraseFromParent();
702  BB = GEntryBlock;
703  } else {
704  NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
705  G->getAddressSpace(), "", G->getParent());
706  BB = BasicBlock::Create(F->getContext(), "", NewG);
707  }
708 
709  IRBuilder<> Builder(BB);
710  Function *H = MergeFunctionsPDI ? G : NewG;
712  unsigned i = 0;
713  FunctionType *FFTy = F->getFunctionType();
714  for (Argument &AI : H->args()) {
715  Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
716  ++i;
717  }
718 
719  CallInst *CI = Builder.CreateCall(F, Args);
720  ReturnInst *RI = nullptr;
721  CI->setTailCall();
722  CI->setCallingConv(F->getCallingConv());
723  CI->setAttributes(F->getAttributes());
724  if (H->getReturnType()->isVoidTy()) {
725  RI = Builder.CreateRetVoid();
726  } else {
727  RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
728  }
729 
730  if (MergeFunctionsPDI) {
731  DISubprogram *DIS = G->getSubprogram();
732  if (DIS) {
733  DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
734  DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
735  CI->setDebugLoc(CIDbgLoc);
736  RI->setDebugLoc(RIDbgLoc);
737  } else {
738  LLVM_DEBUG(
739  dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
740  << G->getName() << "()\n");
741  }
742  eraseTail(G);
743  eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
744  LLVM_DEBUG(
745  dbgs() << "} // End of parameter related debug info filtering for: "
746  << G->getName() << "()\n");
747  } else {
748  NewG->copyAttributesFrom(G);
749  NewG->takeName(G);
750  removeUsers(G);
751  G->replaceAllUsesWith(NewG);
752  G->eraseFromParent();
753  }
754 
755  LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
756  ++NumThunksWritten;
757 }
758 
759 // Whether this function may be replaced by an alias
760 static bool canCreateAliasFor(Function *F) {
762  return false;
763 
764  // We should only see linkages supported by aliases here
766  || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
767  return true;
768 }
769 
770 // Replace G with an alias to F (deleting function G)
771 void MergeFunctions::writeAlias(Function *F, Function *G) {
772  Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
773  PointerType *PtrType = G->getType();
774  auto *GA = GlobalAlias::create(
775  PtrType->getElementType(), PtrType->getAddressSpace(),
776  G->getLinkage(), "", BitcastF, G->getParent());
777 
779  GA->takeName(G);
780  GA->setVisibility(G->getVisibility());
781  GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
782 
783  removeUsers(G);
784  G->replaceAllUsesWith(GA);
785  G->eraseFromParent();
786 
787  LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
788  ++NumAliasesWritten;
789 }
790 
791 // Replace G with an alias to F if possible, or a thunk to F if
792 // profitable. Returns false if neither is the case.
793 bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
794  if (canCreateAliasFor(G)) {
795  writeAlias(F, G);
796  return true;
797  }
798  if (canCreateThunkFor(F)) {
799  writeThunk(F, G);
800  return true;
801  }
802  return false;
803 }
804 
805 // Merge two equivalent functions. Upon completion, Function G is deleted.
806 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
807  if (F->isInterposable()) {
808  assert(G->isInterposable());
809 
810  // Both writeThunkOrAlias() calls below must succeed, either because we can
811  // create aliases for G and NewF, or because a thunk for F is profitable.
812  // F here has the same signature as NewF below, so that's what we check.
813  if (!canCreateThunkFor(F) &&
815  return;
816 
817  // Make them both thunks to the same internal function.
819  F->getAddressSpace(), "", F->getParent());
820  NewF->copyAttributesFrom(F);
821  NewF->takeName(F);
822  removeUsers(F);
823  F->replaceAllUsesWith(NewF);
824 
825  unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
826 
827  writeThunkOrAlias(F, G);
828  writeThunkOrAlias(F, NewF);
829 
830  F->setAlignment(MaxAlignment);
832  ++NumDoubleWeak;
833  ++NumFunctionsMerged;
834  } else {
835  // For better debugability, under MergeFunctionsPDI, we do not modify G's
836  // call sites to point to F even when within the same translation unit.
837  if (!G->isInterposable() && !MergeFunctionsPDI) {
838  if (G->hasGlobalUnnamedAddr()) {
839  // G might have been a key in our GlobalNumberState, and it's illegal
840  // to replace a key in ValueMap<GlobalValue *> with a non-global.
841  GlobalNumbers.erase(G);
842  // If G's address is not significant, replace it entirely.
843  Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
844  removeUsers(G);
845  G->replaceAllUsesWith(BitcastF);
846  } else {
847  // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
848  // above).
849  replaceDirectCallers(G, F);
850  }
851  }
852 
853  // If G was internal then we may have replaced all uses of G with F. If so,
854  // stop here and delete G. There's no need for a thunk. (See note on
855  // MergeFunctionsPDI above).
856  if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
857  G->eraseFromParent();
858  ++NumFunctionsMerged;
859  return;
860  }
861 
862  if (writeThunkOrAlias(F, G)) {
863  ++NumFunctionsMerged;
864  }
865  }
866 }
867 
868 /// Replace function F by function G.
869 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
870  Function *G) {
871  Function *F = FN.getFunc();
872  assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
873  "The two functions must be equal");
874 
875  auto I = FNodesInTree.find(F);
876  assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
877  assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
878 
879  FnTreeType::iterator IterToFNInFnTree = I->second;
880  assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
881  // Remove F -> FN and insert G -> FN
882  FNodesInTree.erase(I);
883  FNodesInTree.insert({G, IterToFNInFnTree});
884  // Replace F with G in FN, which is stored inside the FnTree.
885  FN.replaceBy(G);
886 }
887 
888 // Ordering for functions that are equal under FunctionComparator
889 static bool isFuncOrderCorrect(const Function *F, const Function *G) {
890  if (F->isInterposable() != G->isInterposable()) {
891  // Strong before weak, because the weak function may call the strong
892  // one, but not the other way around.
893  return !F->isInterposable();
894  }
895  if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
896  // External before local, because we definitely have to keep the external
897  // function, but may be able to drop the local one.
898  return !F->hasLocalLinkage();
899  }
900  // Impose a total order (by name) on the replacement of functions. This is
901  // important when operating on more than one module independently to prevent
902  // cycles of thunks calling each other when the modules are linked together.
903  return F->getName() <= G->getName();
904 }
905 
906 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
907 // that was already inserted.
908 bool MergeFunctions::insert(Function *NewFunction) {
909  std::pair<FnTreeType::iterator, bool> Result =
910  FnTree.insert(FunctionNode(NewFunction));
911 
912  if (Result.second) {
913  assert(FNodesInTree.count(NewFunction) == 0);
914  FNodesInTree.insert({NewFunction, Result.first});
915  LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
916  << '\n');
917  return false;
918  }
919 
920  const FunctionNode &OldF = *Result.first;
921 
922  if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
923  // Swap the two functions.
924  Function *F = OldF.getFunc();
925  replaceFunctionInTree(*Result.first, NewFunction);
926  NewFunction = F;
927  assert(OldF.getFunc() != F && "Must have swapped the functions.");
928  }
929 
930  LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
931  << " == " << NewFunction->getName() << '\n');
932 
933  Function *DeleteF = NewFunction;
934  mergeTwoFunctions(OldF.getFunc(), DeleteF);
935  return true;
936 }
937 
938 // Remove a function from FnTree. If it was already in FnTree, add
939 // it to Deferred so that we'll look at it in the next round.
941  auto I = FNodesInTree.find(F);
942  if (I != FNodesInTree.end()) {
943  LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
944  FnTree.erase(I->second);
945  // I->second has been invalidated, remove it from the FNodesInTree map to
946  // preserve the invariant.
947  FNodesInTree.erase(I);
948  Deferred.emplace_back(F);
949  }
950 }
951 
952 // For each instruction used by the value, remove() the function that contains
953 // the instruction. This should happen right before a call to RAUW.
954 void MergeFunctions::removeUsers(Value *V) {
955  std::vector<Value *> Worklist;
956  Worklist.push_back(V);
957  SmallPtrSet<Value*, 8> Visited;
958  Visited.insert(V);
959  while (!Worklist.empty()) {
960  Value *V = Worklist.back();
961  Worklist.pop_back();
962 
963  for (User *U : V->users()) {
964  if (Instruction *I = dyn_cast<Instruction>(U)) {
965  remove(I->getFunction());
966  } else if (isa<GlobalValue>(U)) {
967  // do nothing
968  } else if (Constant *C = dyn_cast<Constant>(U)) {
969  for (User *UU : C->users()) {
970  if (!Visited.insert(UU).second)
971  Worklist.push_back(UU);
972  }
973  }
974  }
975  }
976 }
size_t size() const
Definition: Function.h:660
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition: Function.h:176
uint64_t CallInst * C
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
unsigned getAlignment() const
Definition: GlobalObject.h:58
use_iterator use_end()
Definition: Value.h:346
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVMContext & Context
static Value * createCast(IRBuilder<> &Builder, Value *V, Type *DestTy)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:134
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
iterator end()
Definition: Function.h:657
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
ModulePass * createMergeFunctionsPass()
createMergeFunctionsPass - This pass discovers identical functions and collapses them.
static bool isFuncOrderCorrect(const Function *F, const Function *G)
This class represents a function call, abstracting a target machine&#39;s calling convention.
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:422
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:419
STATISTIC(NumFunctions, "Total number of functions")
A debug info location.
Definition: DebugLoc.h:33
F(f)
Type * getStructElementType(unsigned N) const
Definition: DerivedTypes.h:364
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.cpp:137
This defines the Use class.
void setAlignment(unsigned Align)
Definition: Globals.cpp:115
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
uint64_t FunctionHash
Hash a function.
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:450
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1762
bool hasExternalLinkage() const
Definition: GlobalValue.h:421
Subprogram description.
Class to represent function types.
Definition: DerivedTypes.h:102
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1767
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:181
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:223
An instruction for storing to memory.
Definition: Instructions.h:320
LinkageTypes getLinkage() const
Definition: GlobalValue.h:450
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:425
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
iterator begin()
Definition: Function.h:655
void initializeMergeFunctionsPass(PassRegistry &)
static bool canCreateAliasFor(Function *F)
void erase(GlobalValue *Global)
Class to represent pointers.
Definition: DerivedTypes.h:498
static cl::opt< unsigned > NumFunctionsForSanityCheck("mergefunc-sanity", cl::desc("How many functions in module could be used for " "MergeFunctions pass sanity check. " "'0' disables this check. Works only with '-debug' key."), cl::init(0), cl::Hidden)
static FunctionHash functionHash(Function &)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1782
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:140
const BasicBlock & getEntryBlock() const
Definition: Function.h:639
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:168
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:321
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:232
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1507
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:483
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
#define H(x, y, z)
Definition: MD5.cpp:57
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
size_t size() const
Definition: BasicBlock.h:278
const Instruction & back() const
Definition: BasicBlock.h:282
unsigned getAddressSpace() const
Definition: Globals.cpp:110
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4192
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1262
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
Definition: GlobalValue.h:360
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
unsigned getStructNumElements() const
Definition: DerivedTypes.h:360
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:192
void setTailCall(bool isTC=true)
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1424
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2119
unsigned first
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
bool hasWeakLinkage() const
Definition: GlobalValue.h:429
void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
Definition: AsmWriter.cpp:4321
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."))
Iterator for intrusive lists based on ilist_node.
static bool canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
iterator end()
Definition: BasicBlock.h:270
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
GlobalNumberState assigns an integer to each global value in the program, which is used by the compar...
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
Module.h This file contains the declarations for the Module class.
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:199
Value handle that asserts if the Value is deleted.
Definition: ValueHandle.h:237
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:444
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:163
int compare()
Test whether the two functions have equivalent behaviour.
iterator_range< user_iterator > users()
Definition: Value.h:399
static cl::opt< bool > MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, cl::init(false), cl::desc("Allow mergefunc to create aliases"))
use_iterator use_begin()
Definition: Value.h:338
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink &#39;this&#39; from the containing function and delete it.
Definition: BasicBlock.cpp:114
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1284
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Function.cpp:213
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1757
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:205
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
Definition: ScaledNumber.h:251
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:662
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:72
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2127
void pop_back()
Definition: ilist.h:316
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool use_empty() const
Definition: Value.h:322
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:422
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
Definition: Attributes.cpp:874
iterator_range< arg_iterator > args()
Definition: Function.h:688
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:217
an instruction to allocate memory on the stack
Definition: Instructions.h:59