LLVM  8.0.0svn
AsmWriter.cpp
Go to the documentation of this file.
1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements `print` family of functions in classes like
11 // Module, Function, Value, etc. In-memory representation of those classes is
12 // converted to IR strings.
13 //
14 // Note that these routines must be extremely tolerant of various errors in the
15 // LLVM code, because it can be used for debugging transformations.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/Comdat.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalAlias.h"
48 #include "llvm/IR/GlobalIFunc.h"
50 #include "llvm/IR/GlobalObject.h"
51 #include "llvm/IR/GlobalValue.h"
52 #include "llvm/IR/GlobalVariable.h"
54 #include "llvm/IR/InlineAsm.h"
55 #include "llvm/IR/InstrTypes.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Metadata.h"
60 #include "llvm/IR/Module.h"
63 #include "llvm/IR/Operator.h"
64 #include "llvm/IR/Statepoint.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/TypeFinder.h"
67 #include "llvm/IR/Use.h"
68 #include "llvm/IR/UseListOrder.h"
69 #include "llvm/IR/User.h"
70 #include "llvm/IR/Value.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/Format.h"
79 #include <algorithm>
80 #include <cassert>
81 #include <cctype>
82 #include <cstddef>
83 #include <cstdint>
84 #include <iterator>
85 #include <memory>
86 #include <string>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 
93 // Make virtual table appear in this compilation unit.
95 
96 //===----------------------------------------------------------------------===//
97 // Helper Functions
98 //===----------------------------------------------------------------------===//
99 
100 namespace {
101 
102 struct OrderMap {
104 
105  unsigned size() const { return IDs.size(); }
106  std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
107 
108  std::pair<unsigned, bool> lookup(const Value *V) const {
109  return IDs.lookup(V);
110  }
111 
112  void index(const Value *V) {
113  // Explicitly sequence get-size and insert-value operations to avoid UB.
114  unsigned ID = IDs.size() + 1;
115  IDs[V].first = ID;
116  }
117 };
118 
119 } // end anonymous namespace
120 
121 static void orderValue(const Value *V, OrderMap &OM) {
122  if (OM.lookup(V).first)
123  return;
124 
125  if (const Constant *C = dyn_cast<Constant>(V))
126  if (C->getNumOperands() && !isa<GlobalValue>(C))
127  for (const Value *Op : C->operands())
128  if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
129  orderValue(Op, OM);
130 
131  // Note: we cannot cache this lookup above, since inserting into the map
132  // changes the map's size, and thus affects the other IDs.
133  OM.index(V);
134 }
135 
136 static OrderMap orderModule(const Module *M) {
137  // This needs to match the order used by ValueEnumerator::ValueEnumerator()
138  // and ValueEnumerator::incorporateFunction().
139  OrderMap OM;
140 
141  for (const GlobalVariable &G : M->globals()) {
142  if (G.hasInitializer())
143  if (!isa<GlobalValue>(G.getInitializer()))
144  orderValue(G.getInitializer(), OM);
145  orderValue(&G, OM);
146  }
147  for (const GlobalAlias &A : M->aliases()) {
148  if (!isa<GlobalValue>(A.getAliasee()))
149  orderValue(A.getAliasee(), OM);
150  orderValue(&A, OM);
151  }
152  for (const GlobalIFunc &I : M->ifuncs()) {
153  if (!isa<GlobalValue>(I.getResolver()))
154  orderValue(I.getResolver(), OM);
155  orderValue(&I, OM);
156  }
157  for (const Function &F : *M) {
158  for (const Use &U : F.operands())
159  if (!isa<GlobalValue>(U.get()))
160  orderValue(U.get(), OM);
161 
162  orderValue(&F, OM);
163 
164  if (F.isDeclaration())
165  continue;
166 
167  for (const Argument &A : F.args())
168  orderValue(&A, OM);
169  for (const BasicBlock &BB : F) {
170  orderValue(&BB, OM);
171  for (const Instruction &I : BB) {
172  for (const Value *Op : I.operands())
173  if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
174  isa<InlineAsm>(*Op))
175  orderValue(Op, OM);
176  orderValue(&I, OM);
177  }
178  }
179  }
180  return OM;
181 }
182 
183 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
184  unsigned ID, const OrderMap &OM,
185  UseListOrderStack &Stack) {
186  // Predict use-list order for this one.
187  using Entry = std::pair<const Use *, unsigned>;
189  for (const Use &U : V->uses())
190  // Check if this user will be serialized.
191  if (OM.lookup(U.getUser()).first)
192  List.push_back(std::make_pair(&U, List.size()));
193 
194  if (List.size() < 2)
195  // We may have lost some users.
196  return;
197 
198  bool GetsReversed =
199  !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
200  if (auto *BA = dyn_cast<BlockAddress>(V))
201  ID = OM.lookup(BA->getBasicBlock()).first;
202  llvm::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
203  const Use *LU = L.first;
204  const Use *RU = R.first;
205  if (LU == RU)
206  return false;
207 
208  auto LID = OM.lookup(LU->getUser()).first;
209  auto RID = OM.lookup(RU->getUser()).first;
210 
211  // If ID is 4, then expect: 7 6 5 1 2 3.
212  if (LID < RID) {
213  if (GetsReversed)
214  if (RID <= ID)
215  return true;
216  return false;
217  }
218  if (RID < LID) {
219  if (GetsReversed)
220  if (LID <= ID)
221  return false;
222  return true;
223  }
224 
225  // LID and RID are equal, so we have different operands of the same user.
226  // Assume operands are added in order for all instructions.
227  if (GetsReversed)
228  if (LID <= ID)
229  return LU->getOperandNo() < RU->getOperandNo();
230  return LU->getOperandNo() > RU->getOperandNo();
231  });
232 
233  if (std::is_sorted(
234  List.begin(), List.end(),
235  [](const Entry &L, const Entry &R) { return L.second < R.second; }))
236  // Order is already correct.
237  return;
238 
239  // Store the shuffle.
240  Stack.emplace_back(V, F, List.size());
241  assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
242  for (size_t I = 0, E = List.size(); I != E; ++I)
243  Stack.back().Shuffle[I] = List[I].second;
244 }
245 
246 static void predictValueUseListOrder(const Value *V, const Function *F,
247  OrderMap &OM, UseListOrderStack &Stack) {
248  auto &IDPair = OM[V];
249  assert(IDPair.first && "Unmapped value");
250  if (IDPair.second)
251  // Already predicted.
252  return;
253 
254  // Do the actual prediction.
255  IDPair.second = true;
256  if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
257  predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
258 
259  // Recursive descent into constants.
260  if (const Constant *C = dyn_cast<Constant>(V))
261  if (C->getNumOperands()) // Visit GlobalValues.
262  for (const Value *Op : C->operands())
263  if (isa<Constant>(Op)) // Visit GlobalValues.
264  predictValueUseListOrder(Op, F, OM, Stack);
265 }
266 
268  OrderMap OM = orderModule(M);
269 
270  // Use-list orders need to be serialized after all the users have been added
271  // to a value, or else the shuffles will be incomplete. Store them per
272  // function in a stack.
273  //
274  // Aside from function order, the order of values doesn't matter much here.
275  UseListOrderStack Stack;
276 
277  // We want to visit the functions backward now so we can list function-local
278  // constants in the last Function they're used in. Module-level constants
279  // have already been visited above.
280  for (const Function &F : make_range(M->rbegin(), M->rend())) {
281  if (F.isDeclaration())
282  continue;
283  for (const BasicBlock &BB : F)
284  predictValueUseListOrder(&BB, &F, OM, Stack);
285  for (const Argument &A : F.args())
286  predictValueUseListOrder(&A, &F, OM, Stack);
287  for (const BasicBlock &BB : F)
288  for (const Instruction &I : BB)
289  for (const Value *Op : I.operands())
290  if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
291  predictValueUseListOrder(Op, &F, OM, Stack);
292  for (const BasicBlock &BB : F)
293  for (const Instruction &I : BB)
294  predictValueUseListOrder(&I, &F, OM, Stack);
295  }
296 
297  // Visit globals last.
298  for (const GlobalVariable &G : M->globals())
299  predictValueUseListOrder(&G, nullptr, OM, Stack);
300  for (const Function &F : *M)
301  predictValueUseListOrder(&F, nullptr, OM, Stack);
302  for (const GlobalAlias &A : M->aliases())
303  predictValueUseListOrder(&A, nullptr, OM, Stack);
304  for (const GlobalIFunc &I : M->ifuncs())
305  predictValueUseListOrder(&I, nullptr, OM, Stack);
306  for (const GlobalVariable &G : M->globals())
307  if (G.hasInitializer())
308  predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
309  for (const GlobalAlias &A : M->aliases())
310  predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
311  for (const GlobalIFunc &I : M->ifuncs())
312  predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
313  for (const Function &F : *M)
314  for (const Use &U : F.operands())
315  predictValueUseListOrder(U.get(), nullptr, OM, Stack);
316 
317  return Stack;
318 }
319 
320 static const Module *getModuleFromVal(const Value *V) {
321  if (const Argument *MA = dyn_cast<Argument>(V))
322  return MA->getParent() ? MA->getParent()->getParent() : nullptr;
323 
324  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
325  return BB->getParent() ? BB->getParent()->getParent() : nullptr;
326 
327  if (const Instruction *I = dyn_cast<Instruction>(V)) {
328  const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
329  return M ? M->getParent() : nullptr;
330  }
331 
332  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
333  return GV->getParent();
334 
335  if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
336  for (const User *U : MAV->users())
337  if (isa<Instruction>(U))
338  if (const Module *M = getModuleFromVal(U))
339  return M;
340  return nullptr;
341  }
342 
343  return nullptr;
344 }
345 
346 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
347  switch (cc) {
348  default: Out << "cc" << cc; break;
349  case CallingConv::Fast: Out << "fastcc"; break;
350  case CallingConv::Cold: Out << "coldcc"; break;
351  case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
352  case CallingConv::AnyReg: Out << "anyregcc"; break;
353  case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
354  case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
355  case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
356  case CallingConv::GHC: Out << "ghccc"; break;
357  case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
358  case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
359  case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
360  case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
361  case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
362  case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
363  case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
364  case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
365  case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
366  case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
367  case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
368  case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
369  case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
370  case CallingConv::PTX_Device: Out << "ptx_device"; break;
371  case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
372  case CallingConv::Win64: Out << "win64cc"; break;
373  case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
374  case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
375  case CallingConv::Swift: Out << "swiftcc"; break;
376  case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
377  case CallingConv::HHVM: Out << "hhvmcc"; break;
378  case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
379  case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
380  case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
381  case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
382  case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
383  case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
384  case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
385  case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
386  case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
387  }
388 }
389 
396 };
397 
399  assert(!Name.empty() && "Cannot get empty name!");
400 
401  // Scan the name to see if it needs quotes first.
402  bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
403  if (!NeedsQuotes) {
404  for (unsigned i = 0, e = Name.size(); i != e; ++i) {
405  // By making this unsigned, the value passed in to isalnum will always be
406  // in the range 0-255. This is important when building with MSVC because
407  // its implementation will assert. This situation can arise when dealing
408  // with UTF-8 multibyte characters.
409  unsigned char C = Name[i];
410  if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
411  C != '_') {
412  NeedsQuotes = true;
413  break;
414  }
415  }
416  }
417 
418  // If we didn't need any quotes, just write out the name in one blast.
419  if (!NeedsQuotes) {
420  OS << Name;
421  return;
422  }
423 
424  // Okay, we need quotes. Output the quotes and escape any scary characters as
425  // needed.
426  OS << '"';
427  printEscapedString(Name, OS);
428  OS << '"';
429 }
430 
431 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
432 /// (if the string only contains simple characters) or is surrounded with ""'s
433 /// (if it has special chars in it). Print it out.
435  switch (Prefix) {
436  case NoPrefix:
437  break;
438  case GlobalPrefix:
439  OS << '@';
440  break;
441  case ComdatPrefix:
442  OS << '$';
443  break;
444  case LabelPrefix:
445  break;
446  case LocalPrefix:
447  OS << '%';
448  break;
449  }
450  printLLVMNameWithoutPrefix(OS, Name);
451 }
452 
453 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
454 /// (if the string only contains simple characters) or is surrounded with ""'s
455 /// (if it has special chars in it). Print it out.
456 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
457  PrintLLVMName(OS, V->getName(),
458  isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
459 }
460 
461 namespace {
462 
463 class TypePrinting {
464 public:
465  TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
466 
467  TypePrinting(const TypePrinting &) = delete;
468  TypePrinting &operator=(const TypePrinting &) = delete;
469 
470  /// The named types that are used by the current module.
471  TypeFinder &getNamedTypes();
472 
473  /// The numbered types, number to type mapping.
474  std::vector<StructType *> &getNumberedTypes();
475 
476  bool empty();
477 
478  void print(Type *Ty, raw_ostream &OS);
479 
480  void printStructBody(StructType *Ty, raw_ostream &OS);
481 
482 private:
483  void incorporateTypes();
484 
485  /// A module to process lazily when needed. Set to nullptr as soon as used.
486  const Module *DeferredM;
487 
488  TypeFinder NamedTypes;
489 
490  // The numbered types, along with their value.
492 
493  std::vector<StructType *> NumberedTypes;
494 };
495 
496 } // end anonymous namespace
497 
498 TypeFinder &TypePrinting::getNamedTypes() {
499  incorporateTypes();
500  return NamedTypes;
501 }
502 
503 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
504  incorporateTypes();
505 
506  // We know all the numbers that each type is used and we know that it is a
507  // dense assignment. Convert the map to an index table, if it's not done
508  // already (judging from the sizes):
509  if (NumberedTypes.size() == Type2Number.size())
510  return NumberedTypes;
511 
512  NumberedTypes.resize(Type2Number.size());
513  for (const auto &P : Type2Number) {
514  assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
515  assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
516  NumberedTypes[P.second] = P.first;
517  }
518  return NumberedTypes;
519 }
520 
521 bool TypePrinting::empty() {
522  incorporateTypes();
523  return NamedTypes.empty() && Type2Number.empty();
524 }
525 
526 void TypePrinting::incorporateTypes() {
527  if (!DeferredM)
528  return;
529 
530  NamedTypes.run(*DeferredM, false);
531  DeferredM = nullptr;
532 
533  // The list of struct types we got back includes all the struct types, split
534  // the unnamed ones out to a numbering and remove the anonymous structs.
535  unsigned NextNumber = 0;
536 
537  std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
538  for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
539  StructType *STy = *I;
540 
541  // Ignore anonymous types.
542  if (STy->isLiteral())
543  continue;
544 
545  if (STy->getName().empty())
546  Type2Number[STy] = NextNumber++;
547  else
548  *NextToUse++ = STy;
549  }
550 
551  NamedTypes.erase(NextToUse, NamedTypes.end());
552 }
553 
554 /// Write the specified type to the specified raw_ostream, making use of type
555 /// names or up references to shorten the type name where possible.
556 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
557  switch (Ty->getTypeID()) {
558  case Type::VoidTyID: OS << "void"; return;
559  case Type::HalfTyID: OS << "half"; return;
560  case Type::FloatTyID: OS << "float"; return;
561  case Type::DoubleTyID: OS << "double"; return;
562  case Type::X86_FP80TyID: OS << "x86_fp80"; return;
563  case Type::FP128TyID: OS << "fp128"; return;
564  case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
565  case Type::LabelTyID: OS << "label"; return;
566  case Type::MetadataTyID: OS << "metadata"; return;
567  case Type::X86_MMXTyID: OS << "x86_mmx"; return;
568  case Type::TokenTyID: OS << "token"; return;
569  case Type::IntegerTyID:
570  OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
571  return;
572 
573  case Type::FunctionTyID: {
574  FunctionType *FTy = cast<FunctionType>(Ty);
575  print(FTy->getReturnType(), OS);
576  OS << " (";
578  E = FTy->param_end(); I != E; ++I) {
579  if (I != FTy->param_begin())
580  OS << ", ";
581  print(*I, OS);
582  }
583  if (FTy->isVarArg()) {
584  if (FTy->getNumParams()) OS << ", ";
585  OS << "...";
586  }
587  OS << ')';
588  return;
589  }
590  case Type::StructTyID: {
591  StructType *STy = cast<StructType>(Ty);
592 
593  if (STy->isLiteral())
594  return printStructBody(STy, OS);
595 
596  if (!STy->getName().empty())
597  return PrintLLVMName(OS, STy->getName(), LocalPrefix);
598 
599  incorporateTypes();
600  const auto I = Type2Number.find(STy);
601  if (I != Type2Number.end())
602  OS << '%' << I->second;
603  else // Not enumerated, print the hex address.
604  OS << "%\"type " << STy << '\"';
605  return;
606  }
607  case Type::PointerTyID: {
608  PointerType *PTy = cast<PointerType>(Ty);
609  print(PTy->getElementType(), OS);
610  if (unsigned AddressSpace = PTy->getAddressSpace())
611  OS << " addrspace(" << AddressSpace << ')';
612  OS << '*';
613  return;
614  }
615  case Type::ArrayTyID: {
616  ArrayType *ATy = cast<ArrayType>(Ty);
617  OS << '[' << ATy->getNumElements() << " x ";
618  print(ATy->getElementType(), OS);
619  OS << ']';
620  return;
621  }
622  case Type::VectorTyID: {
623  VectorType *PTy = cast<VectorType>(Ty);
624  OS << "<" << PTy->getNumElements() << " x ";
625  print(PTy->getElementType(), OS);
626  OS << '>';
627  return;
628  }
629  }
630  llvm_unreachable("Invalid TypeID");
631 }
632 
633 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
634  if (STy->isOpaque()) {
635  OS << "opaque";
636  return;
637  }
638 
639  if (STy->isPacked())
640  OS << '<';
641 
642  if (STy->getNumElements() == 0) {
643  OS << "{}";
644  } else {
645  StructType::element_iterator I = STy->element_begin();
646  OS << "{ ";
647  print(*I++, OS);
648  for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
649  OS << ", ";
650  print(*I, OS);
651  }
652 
653  OS << " }";
654  }
655  if (STy->isPacked())
656  OS << '>';
657 }
658 
659 namespace llvm {
660 
661 //===----------------------------------------------------------------------===//
662 // SlotTracker Class: Enumerate slot numbers for unnamed values
663 //===----------------------------------------------------------------------===//
664 /// This class provides computation of slot numbers for LLVM Assembly writing.
665 ///
666 class SlotTracker {
667 public:
668  /// ValueMap - A mapping of Values to slot numbers.
669  using ValueMap = DenseMap<const Value *, unsigned>;
670 
671 private:
672  /// TheModule - The module for which we are holding slot numbers.
673  const Module* TheModule;
674 
675  /// TheFunction - The function for which we are holding slot numbers.
676  const Function* TheFunction = nullptr;
677  bool FunctionProcessed = false;
678  bool ShouldInitializeAllMetadata;
679 
680  /// The summary index for which we are holding slot numbers.
681  const ModuleSummaryIndex *TheIndex = nullptr;
682 
683  /// mMap - The slot map for the module level data.
684  ValueMap mMap;
685  unsigned mNext = 0;
686 
687  /// fMap - The slot map for the function level data.
688  ValueMap fMap;
689  unsigned fNext = 0;
690 
691  /// mdnMap - Map for MDNodes.
692  DenseMap<const MDNode*, unsigned> mdnMap;
693  unsigned mdnNext = 0;
694 
695  /// asMap - The slot map for attribute sets.
696  DenseMap<AttributeSet, unsigned> asMap;
697  unsigned asNext = 0;
698 
699  /// ModulePathMap - The slot map for Module paths used in the summary index.
700  StringMap<unsigned> ModulePathMap;
701  unsigned ModulePathNext = 0;
702 
703  /// GUIDMap - The slot map for GUIDs used in the summary index.
704  DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
705  unsigned GUIDNext = 0;
706 
707 public:
708  /// Construct from a module.
709  ///
710  /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
711  /// functions, giving correct numbering for metadata referenced only from
712  /// within a function (even if no functions have been initialized).
713  explicit SlotTracker(const Module *M,
714  bool ShouldInitializeAllMetadata = false);
715 
716  /// Construct from a function, starting out in incorp state.
717  ///
718  /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
719  /// functions, giving correct numbering for metadata referenced only from
720  /// within a function (even if no functions have been initialized).
721  explicit SlotTracker(const Function *F,
722  bool ShouldInitializeAllMetadata = false);
723 
724  /// Construct from a module summary index.
725  explicit SlotTracker(const ModuleSummaryIndex *Index);
726 
727  SlotTracker(const SlotTracker &) = delete;
728  SlotTracker &operator=(const SlotTracker &) = delete;
729 
730  /// Return the slot number of the specified value in it's type
731  /// plane. If something is not in the SlotTracker, return -1.
732  int getLocalSlot(const Value *V);
733  int getGlobalSlot(const GlobalValue *V);
734  int getMetadataSlot(const MDNode *N);
735  int getAttributeGroupSlot(AttributeSet AS);
736  int getModulePathSlot(StringRef Path);
737  int getGUIDSlot(GlobalValue::GUID GUID);
738 
739  /// If you'd like to deal with a function instead of just a module, use
740  /// this method to get its data into the SlotTracker.
741  void incorporateFunction(const Function *F) {
742  TheFunction = F;
743  FunctionProcessed = false;
744  }
745 
746  const Function *getFunction() const { return TheFunction; }
747 
748  /// After calling incorporateFunction, use this method to remove the
749  /// most recently incorporated function from the SlotTracker. This
750  /// will reset the state of the machine back to just the module contents.
751  void purgeFunction();
752 
753  /// MDNode map iterators.
754  using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
755 
756  mdn_iterator mdn_begin() { return mdnMap.begin(); }
757  mdn_iterator mdn_end() { return mdnMap.end(); }
758  unsigned mdn_size() const { return mdnMap.size(); }
759  bool mdn_empty() const { return mdnMap.empty(); }
760 
761  /// AttributeSet map iterators.
762  using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
763 
764  as_iterator as_begin() { return asMap.begin(); }
765  as_iterator as_end() { return asMap.end(); }
766  unsigned as_size() const { return asMap.size(); }
767  bool as_empty() const { return asMap.empty(); }
768 
769  /// GUID map iterators.
770  using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
771 
772  /// These functions do the actual initialization.
773  inline void initializeIfNeeded();
774  void initializeIndexIfNeeded();
775 
776  // Implementation Details
777 private:
778  /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
779  void CreateModuleSlot(const GlobalValue *V);
780 
781  /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
782  void CreateMetadataSlot(const MDNode *N);
783 
784  /// CreateFunctionSlot - Insert the specified Value* into the slot table.
785  void CreateFunctionSlot(const Value *V);
786 
787  /// Insert the specified AttributeSet into the slot table.
788  void CreateAttributeSetSlot(AttributeSet AS);
789 
790  inline void CreateModulePathSlot(StringRef Path);
791  void CreateGUIDSlot(GlobalValue::GUID GUID);
792 
793  /// Add all of the module level global variables (and their initializers)
794  /// and function declarations, but not the contents of those functions.
795  void processModule();
796  void processIndex();
797 
798  /// Add all of the functions arguments, basic blocks, and instructions.
799  void processFunction();
800 
801  /// Add the metadata directly attached to a GlobalObject.
802  void processGlobalObjectMetadata(const GlobalObject &GO);
803 
804  /// Add all of the metadata from a function.
805  void processFunctionMetadata(const Function &F);
806 
807  /// Add all of the metadata from an instruction.
808  void processInstructionMetadata(const Instruction &I);
809 };
810 
811 } // end namespace llvm
812 
813 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
814  const Function *F)
815  : M(M), F(F), Machine(&Machine) {}
816 
817 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
818  bool ShouldInitializeAllMetadata)
819  : ShouldCreateStorage(M),
820  ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
821 
822 ModuleSlotTracker::~ModuleSlotTracker() = default;
823 
824 SlotTracker *ModuleSlotTracker::getMachine() {
825  if (!ShouldCreateStorage)
826  return Machine;
827 
828  ShouldCreateStorage = false;
829  MachineStorage =
830  llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
831  Machine = MachineStorage.get();
832  return Machine;
833 }
834 
835 void ModuleSlotTracker::incorporateFunction(const Function &F) {
836  // Using getMachine() may lazily create the slot tracker.
837  if (!getMachine())
838  return;
839 
840  // Nothing to do if this is the right function already.
841  if (this->F == &F)
842  return;
843  if (this->F)
844  Machine->purgeFunction();
845  Machine->incorporateFunction(&F);
846  this->F = &F;
847 }
848 
849 int ModuleSlotTracker::getLocalSlot(const Value *V) {
850  assert(F && "No function incorporated");
851  return Machine->getLocalSlot(V);
852 }
853 
854 static SlotTracker *createSlotTracker(const Value *V) {
855  if (const Argument *FA = dyn_cast<Argument>(V))
856  return new SlotTracker(FA->getParent());
857 
858  if (const Instruction *I = dyn_cast<Instruction>(V))
859  if (I->getParent())
860  return new SlotTracker(I->getParent()->getParent());
861 
862  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
863  return new SlotTracker(BB->getParent());
864 
865  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
866  return new SlotTracker(GV->getParent());
867 
868  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
869  return new SlotTracker(GA->getParent());
870 
871  if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
872  return new SlotTracker(GIF->getParent());
873 
874  if (const Function *Func = dyn_cast<Function>(V))
875  return new SlotTracker(Func);
876 
877  return nullptr;
878 }
879 
880 #if 0
881 #define ST_DEBUG(X) dbgs() << X
882 #else
883 #define ST_DEBUG(X)
884 #endif
885 
886 // Module level constructor. Causes the contents of the Module (sans functions)
887 // to be added to the slot table.
888 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
889  : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
890 
891 // Function level constructor. Causes the contents of the Module and the one
892 // function provided to be added to the slot table.
893 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
894  : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
895  ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
896 
897 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
898  : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
899 
900 inline void SlotTracker::initializeIfNeeded() {
901  if (TheModule) {
902  processModule();
903  TheModule = nullptr; ///< Prevent re-processing next time we're called.
904  }
905 
906  if (TheFunction && !FunctionProcessed)
907  processFunction();
908 }
909 
911  if (!TheIndex)
912  return;
913  processIndex();
914  TheIndex = nullptr; ///< Prevent re-processing next time we're called.
915 }
916 
917 // Iterate through all the global variables, functions, and global
918 // variable initializers and create slots for them.
919 void SlotTracker::processModule() {
920  ST_DEBUG("begin processModule!\n");
921 
922  // Add all of the unnamed global variables to the value table.
923  for (const GlobalVariable &Var : TheModule->globals()) {
924  if (!Var.hasName())
925  CreateModuleSlot(&Var);
926  processGlobalObjectMetadata(Var);
927  auto Attrs = Var.getAttributes();
928  if (Attrs.hasAttributes())
929  CreateAttributeSetSlot(Attrs);
930  }
931 
932  for (const GlobalAlias &A : TheModule->aliases()) {
933  if (!A.hasName())
934  CreateModuleSlot(&A);
935  }
936 
937  for (const GlobalIFunc &I : TheModule->ifuncs()) {
938  if (!I.hasName())
939  CreateModuleSlot(&I);
940  }
941 
942  // Add metadata used by named metadata.
943  for (const NamedMDNode &NMD : TheModule->named_metadata()) {
944  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
945  CreateMetadataSlot(NMD.getOperand(i));
946  }
947 
948  for (const Function &F : *TheModule) {
949  if (!F.hasName())
950  // Add all the unnamed functions to the table.
951  CreateModuleSlot(&F);
952 
953  if (ShouldInitializeAllMetadata)
954  processFunctionMetadata(F);
955 
956  // Add all the function attributes to the table.
957  // FIXME: Add attributes of other objects?
958  AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
959  if (FnAttrs.hasAttributes())
960  CreateAttributeSetSlot(FnAttrs);
961  }
962 
963  ST_DEBUG("end processModule!\n");
964 }
965 
966 // Process the arguments, basic blocks, and instructions of a function.
967 void SlotTracker::processFunction() {
968  ST_DEBUG("begin processFunction!\n");
969  fNext = 0;
970 
971  // Process function metadata if it wasn't hit at the module-level.
972  if (!ShouldInitializeAllMetadata)
973  processFunctionMetadata(*TheFunction);
974 
975  // Add all the function arguments with no names.
976  for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
977  AE = TheFunction->arg_end(); AI != AE; ++AI)
978  if (!AI->hasName())
979  CreateFunctionSlot(&*AI);
980 
981  ST_DEBUG("Inserting Instructions:\n");
982 
983  // Add all of the basic blocks and instructions with no names.
984  for (auto &BB : *TheFunction) {
985  if (!BB.hasName())
986  CreateFunctionSlot(&BB);
987 
988  for (auto &I : BB) {
989  if (!I.getType()->isVoidTy() && !I.hasName())
990  CreateFunctionSlot(&I);
991 
992  // We allow direct calls to any llvm.foo function here, because the
993  // target may not be linked into the optimizer.
994  if (auto CS = ImmutableCallSite(&I)) {
995  // Add all the call attributes to the table.
996  AttributeSet Attrs = CS.getAttributes().getFnAttributes();
997  if (Attrs.hasAttributes())
998  CreateAttributeSetSlot(Attrs);
999  }
1000  }
1001  }
1002 
1003  FunctionProcessed = true;
1004 
1005  ST_DEBUG("end processFunction!\n");
1006 }
1007 
1008 // Iterate through all the GUID in the index and create slots for them.
1009 void SlotTracker::processIndex() {
1010  ST_DEBUG("begin processIndex!\n");
1011  assert(TheIndex);
1012 
1013  // The first block of slots are just the module ids, which start at 0 and are
1014  // assigned consecutively. Since the StringMap iteration order isn't
1015  // guaranteed, use a std::map to order by module ID before assigning slots.
1016  std::map<uint64_t, StringRef> ModuleIdToPathMap;
1017  for (auto &ModPath : TheIndex->modulePaths())
1018  ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1019  for (auto &ModPair : ModuleIdToPathMap)
1020  CreateModulePathSlot(ModPair.second);
1021 
1022  // Start numbering the GUIDs after the module ids.
1023  GUIDNext = ModulePathNext;
1024 
1025  for (auto &GlobalList : *TheIndex)
1026  CreateGUIDSlot(GlobalList.first);
1027 
1028  for (auto &TId : TheIndex->typeIds())
1029  CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1030 
1031  ST_DEBUG("end processIndex!\n");
1032 }
1033 
1034 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1036  GO.getAllMetadata(MDs);
1037  for (auto &MD : MDs)
1038  CreateMetadataSlot(MD.second);
1039 }
1040 
1041 void SlotTracker::processFunctionMetadata(const Function &F) {
1042  processGlobalObjectMetadata(F);
1043  for (auto &BB : F) {
1044  for (auto &I : BB)
1045  processInstructionMetadata(I);
1046  }
1047 }
1048 
1049 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1050  // Process metadata used directly by intrinsics.
1051  if (const CallInst *CI = dyn_cast<CallInst>(&I))
1052  if (Function *F = CI->getCalledFunction())
1053  if (F->isIntrinsic())
1054  for (auto &Op : I.operands())
1055  if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1056  if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1057  CreateMetadataSlot(N);
1058 
1059  // Process metadata attached to this instruction.
1061  I.getAllMetadata(MDs);
1062  for (auto &MD : MDs)
1063  CreateMetadataSlot(MD.second);
1064 }
1065 
1066 /// Clean up after incorporating a function. This is the only way to get out of
1067 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1068 /// incorporation state is indicated by TheFunction != 0.
1070  ST_DEBUG("begin purgeFunction!\n");
1071  fMap.clear(); // Simply discard the function level map
1072  TheFunction = nullptr;
1073  FunctionProcessed = false;
1074  ST_DEBUG("end purgeFunction!\n");
1075 }
1076 
1077 /// getGlobalSlot - Get the slot number of a global value.
1079  // Check for uninitialized state and do lazy initialization.
1080  initializeIfNeeded();
1081 
1082  // Find the value in the module map
1083  ValueMap::iterator MI = mMap.find(V);
1084  return MI == mMap.end() ? -1 : (int)MI->second;
1085 }
1086 
1087 /// getMetadataSlot - Get the slot number of a MDNode.
1089  // Check for uninitialized state and do lazy initialization.
1090  initializeIfNeeded();
1091 
1092  // Find the MDNode in the module map
1093  mdn_iterator MI = mdnMap.find(N);
1094  return MI == mdnMap.end() ? -1 : (int)MI->second;
1095 }
1096 
1097 /// getLocalSlot - Get the slot number for a value that is local to a function.
1099  assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1100 
1101  // Check for uninitialized state and do lazy initialization.
1102  initializeIfNeeded();
1103 
1104  ValueMap::iterator FI = fMap.find(V);
1105  return FI == fMap.end() ? -1 : (int)FI->second;
1106 }
1107 
1109  // Check for uninitialized state and do lazy initialization.
1110  initializeIfNeeded();
1111 
1112  // Find the AttributeSet in the module map.
1113  as_iterator AI = asMap.find(AS);
1114  return AI == asMap.end() ? -1 : (int)AI->second;
1115 }
1116 
1118  // Check for uninitialized state and do lazy initialization.
1119  initializeIndexIfNeeded();
1120 
1121  // Find the Module path in the map
1122  auto I = ModulePathMap.find(Path);
1123  return I == ModulePathMap.end() ? -1 : (int)I->second;
1124 }
1125 
1127  // Check for uninitialized state and do lazy initialization.
1128  initializeIndexIfNeeded();
1129 
1130  // Find the GUID in the map
1131  guid_iterator I = GUIDMap.find(GUID);
1132  return I == GUIDMap.end() ? -1 : (int)I->second;
1133 }
1134 
1135 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1136 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1137  assert(V && "Can't insert a null Value into SlotTracker!");
1138  assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1139  assert(!V->hasName() && "Doesn't need a slot!");
1140 
1141  unsigned DestSlot = mNext++;
1142  mMap[V] = DestSlot;
1143 
1144  ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1145  DestSlot << " [");
1146  // G = Global, F = Function, A = Alias, I = IFunc, o = other
1147  ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1148  (isa<Function>(V) ? 'F' :
1149  (isa<GlobalAlias>(V) ? 'A' :
1150  (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1151 }
1152 
1153 /// CreateSlot - Create a new slot for the specified value if it has no name.
1154 void SlotTracker::CreateFunctionSlot(const Value *V) {
1155  assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1156 
1157  unsigned DestSlot = fNext++;
1158  fMap[V] = DestSlot;
1159 
1160  // G = Global, F = Function, o = other
1161  ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1162  DestSlot << " [o]\n");
1163 }
1164 
1165 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1166 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1167  assert(N && "Can't insert a null Value into SlotTracker!");
1168 
1169  // Don't make slots for DIExpressions. We just print them inline everywhere.
1170  if (isa<DIExpression>(N))
1171  return;
1172 
1173  unsigned DestSlot = mdnNext;
1174  if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1175  return;
1176  ++mdnNext;
1177 
1178  // Recursively add any MDNodes referenced by operands.
1179  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180  if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1181  CreateMetadataSlot(Op);
1182 }
1183 
1184 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1185  assert(AS.hasAttributes() && "Doesn't need a slot!");
1186 
1187  as_iterator I = asMap.find(AS);
1188  if (I != asMap.end())
1189  return;
1190 
1191  unsigned DestSlot = asNext++;
1192  asMap[AS] = DestSlot;
1193 }
1194 
1195 /// Create a new slot for the specified Module
1196 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1197  ModulePathMap[Path] = ModulePathNext++;
1198 }
1199 
1200 /// Create a new slot for the specified GUID
1201 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1202  GUIDMap[GUID] = GUIDNext++;
1203 }
1204 
1205 //===----------------------------------------------------------------------===//
1206 // AsmWriter Implementation
1207 //===----------------------------------------------------------------------===//
1208 
1209 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1210  TypePrinting *TypePrinter,
1212  const Module *Context);
1213 
1214 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1215  TypePrinting *TypePrinter,
1216  SlotTracker *Machine, const Module *Context,
1217  bool FromValue = false);
1218 
1221  switch (Op) {
1222  default: Out << " <unknown operation " << Op << ">"; break;
1223  case AtomicRMWInst::Xchg: Out << " xchg"; break;
1224  case AtomicRMWInst::Add: Out << " add"; break;
1225  case AtomicRMWInst::Sub: Out << " sub"; break;
1226  case AtomicRMWInst::And: Out << " and"; break;
1227  case AtomicRMWInst::Nand: Out << " nand"; break;
1228  case AtomicRMWInst::Or: Out << " or"; break;
1229  case AtomicRMWInst::Xor: Out << " xor"; break;
1230  case AtomicRMWInst::Max: Out << " max"; break;
1231  case AtomicRMWInst::Min: Out << " min"; break;
1232  case AtomicRMWInst::UMax: Out << " umax"; break;
1233  case AtomicRMWInst::UMin: Out << " umin"; break;
1234  }
1235 }
1236 
1237 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1238  if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1239  // 'Fast' is an abbreviation for all fast-math-flags.
1240  if (FPO->isFast())
1241  Out << " fast";
1242  else {
1243  if (FPO->hasAllowReassoc())
1244  Out << " reassoc";
1245  if (FPO->hasNoNaNs())
1246  Out << " nnan";
1247  if (FPO->hasNoInfs())
1248  Out << " ninf";
1249  if (FPO->hasNoSignedZeros())
1250  Out << " nsz";
1251  if (FPO->hasAllowReciprocal())
1252  Out << " arcp";
1253  if (FPO->hasAllowContract())
1254  Out << " contract";
1255  if (FPO->hasApproxFunc())
1256  Out << " afn";
1257  }
1258  }
1259 
1260  if (const OverflowingBinaryOperator *OBO =
1261  dyn_cast<OverflowingBinaryOperator>(U)) {
1262  if (OBO->hasNoUnsignedWrap())
1263  Out << " nuw";
1264  if (OBO->hasNoSignedWrap())
1265  Out << " nsw";
1266  } else if (const PossiblyExactOperator *Div =
1267  dyn_cast<PossiblyExactOperator>(U)) {
1268  if (Div->isExact())
1269  Out << " exact";
1270  } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1271  if (GEP->isInBounds())
1272  Out << " inbounds";
1273  }
1274 }
1275 
1276 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1277  TypePrinting &TypePrinter,
1279  const Module *Context) {
1280  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1281  if (CI->getType()->isIntegerTy(1)) {
1282  Out << (CI->getZExtValue() ? "true" : "false");
1283  return;
1284  }
1285  Out << CI->getValue();
1286  return;
1287  }
1288 
1289  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1290  const APFloat &APF = CFP->getValueAPF();
1291  if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1292  &APF.getSemantics() == &APFloat::IEEEdouble()) {
1293  // We would like to output the FP constant value in exponential notation,
1294  // but we cannot do this if doing so will lose precision. Check here to
1295  // make sure that we only output it in exponential format if we can parse
1296  // the value back and get the same value.
1297  //
1298  bool ignored;
1299  bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1300  bool isInf = APF.isInfinity();
1301  bool isNaN = APF.isNaN();
1302  if (!isInf && !isNaN) {
1303  double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1305  APF.toString(StrVal, 6, 0, false);
1306  // Check to make sure that the stringized number is not some string like
1307  // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1308  // that the string matches the "[-+]?[0-9]" regex.
1309  //
1310  assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1311  ((StrVal[0] == '-' || StrVal[0] == '+') &&
1312  (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1313  "[-+]?[0-9] regex does not match!");
1314  // Reparse stringized version!
1315  if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1316  Out << StrVal;
1317  return;
1318  }
1319  }
1320  // Otherwise we could not reparse it to exactly the same value, so we must
1321  // output the string in hexadecimal format! Note that loading and storing
1322  // floating point types changes the bits of NaNs on some hosts, notably
1323  // x86, so we must not use these types.
1324  static_assert(sizeof(double) == sizeof(uint64_t),
1325  "assuming that double is 64 bits!");
1326  APFloat apf = APF;
1327  // Floats are represented in ASCII IR as double, convert.
1328  if (!isDouble)
1330  &ignored);
1331  Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1332  return;
1333  }
1334 
1335  // Either half, or some form of long double.
1336  // These appear as a magic letter identifying the type, then a
1337  // fixed number of hex digits.
1338  Out << "0x";
1339  APInt API = APF.bitcastToAPInt();
1340  if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1341  Out << 'K';
1342  Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1343  /*Upper=*/true);
1344  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1345  /*Upper=*/true);
1346  return;
1347  } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1348  Out << 'L';
1349  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1350  /*Upper=*/true);
1351  Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1352  /*Upper=*/true);
1353  } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1354  Out << 'M';
1355  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1356  /*Upper=*/true);
1357  Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1358  /*Upper=*/true);
1359  } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1360  Out << 'H';
1361  Out << format_hex_no_prefix(API.getZExtValue(), 4,
1362  /*Upper=*/true);
1363  } else
1364  llvm_unreachable("Unsupported floating point type");
1365  return;
1366  }
1367 
1368  if (isa<ConstantAggregateZero>(CV)) {
1369  Out << "zeroinitializer";
1370  return;
1371  }
1372 
1373  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1374  Out << "blockaddress(";
1375  WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1376  Context);
1377  Out << ", ";
1378  WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1379  Context);
1380  Out << ")";
1381  return;
1382  }
1383 
1384  if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1385  Type *ETy = CA->getType()->getElementType();
1386  Out << '[';
1387  TypePrinter.print(ETy, Out);
1388  Out << ' ';
1389  WriteAsOperandInternal(Out, CA->getOperand(0),
1390  &TypePrinter, Machine,
1391  Context);
1392  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1393  Out << ", ";
1394  TypePrinter.print(ETy, Out);
1395  Out << ' ';
1396  WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1397  Context);
1398  }
1399  Out << ']';
1400  return;
1401  }
1402 
1403  if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1404  // As a special case, print the array as a string if it is an array of
1405  // i8 with ConstantInt values.
1406  if (CA->isString()) {
1407  Out << "c\"";
1408  printEscapedString(CA->getAsString(), Out);
1409  Out << '"';
1410  return;
1411  }
1412 
1413  Type *ETy = CA->getType()->getElementType();
1414  Out << '[';
1415  TypePrinter.print(ETy, Out);
1416  Out << ' ';
1417  WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1418  &TypePrinter, Machine,
1419  Context);
1420  for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1421  Out << ", ";
1422  TypePrinter.print(ETy, Out);
1423  Out << ' ';
1424  WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1425  Machine, Context);
1426  }
1427  Out << ']';
1428  return;
1429  }
1430 
1431  if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1432  if (CS->getType()->isPacked())
1433  Out << '<';
1434  Out << '{';
1435  unsigned N = CS->getNumOperands();
1436  if (N) {
1437  Out << ' ';
1438  TypePrinter.print(CS->getOperand(0)->getType(), Out);
1439  Out << ' ';
1440 
1441  WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1442  Context);
1443 
1444  for (unsigned i = 1; i < N; i++) {
1445  Out << ", ";
1446  TypePrinter.print(CS->getOperand(i)->getType(), Out);
1447  Out << ' ';
1448 
1449  WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1450  Context);
1451  }
1452  Out << ' ';
1453  }
1454 
1455  Out << '}';
1456  if (CS->getType()->isPacked())
1457  Out << '>';
1458  return;
1459  }
1460 
1461  if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1462  Type *ETy = CV->getType()->getVectorElementType();
1463  Out << '<';
1464  TypePrinter.print(ETy, Out);
1465  Out << ' ';
1466  WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1467  Machine, Context);
1468  for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1469  Out << ", ";
1470  TypePrinter.print(ETy, Out);
1471  Out << ' ';
1472  WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1473  Machine, Context);
1474  }
1475  Out << '>';
1476  return;
1477  }
1478 
1479  if (isa<ConstantPointerNull>(CV)) {
1480  Out << "null";
1481  return;
1482  }
1483 
1484  if (isa<ConstantTokenNone>(CV)) {
1485  Out << "none";
1486  return;
1487  }
1488 
1489  if (isa<UndefValue>(CV)) {
1490  Out << "undef";
1491  return;
1492  }
1493 
1494  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1495  Out << CE->getOpcodeName();
1496  WriteOptimizationInfo(Out, CE);
1497  if (CE->isCompare())
1498  Out << ' ' << CmpInst::getPredicateName(
1499  static_cast<CmpInst::Predicate>(CE->getPredicate()));
1500  Out << " (";
1501 
1502  Optional<unsigned> InRangeOp;
1503  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1504  TypePrinter.print(GEP->getSourceElementType(), Out);
1505  Out << ", ";
1506  InRangeOp = GEP->getInRangeIndex();
1507  if (InRangeOp)
1508  ++*InRangeOp;
1509  }
1510 
1511  for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1512  if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1513  Out << "inrange ";
1514  TypePrinter.print((*OI)->getType(), Out);
1515  Out << ' ';
1516  WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1517  if (OI+1 != CE->op_end())
1518  Out << ", ";
1519  }
1520 
1521  if (CE->hasIndices()) {
1522  ArrayRef<unsigned> Indices = CE->getIndices();
1523  for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1524  Out << ", " << Indices[i];
1525  }
1526 
1527  if (CE->isCast()) {
1528  Out << " to ";
1529  TypePrinter.print(CE->getType(), Out);
1530  }
1531 
1532  Out << ')';
1533  return;
1534  }
1535 
1536  Out << "<placeholder or erroneous Constant>";
1537 }
1538 
1539 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1540  TypePrinting *TypePrinter, SlotTracker *Machine,
1541  const Module *Context) {
1542  Out << "!{";
1543  for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1544  const Metadata *MD = Node->getOperand(mi);
1545  if (!MD)
1546  Out << "null";
1547  else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1548  Value *V = MDV->getValue();
1549  TypePrinter->print(V->getType(), Out);
1550  Out << ' ';
1551  WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1552  } else {
1553  WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1554  }
1555  if (mi + 1 != me)
1556  Out << ", ";
1557  }
1558 
1559  Out << "}";
1560 }
1561 
1562 namespace {
1563 
1564 struct FieldSeparator {
1565  bool Skip = true;
1566  const char *Sep;
1567 
1568  FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1569 };
1570 
1571 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1572  if (FS.Skip) {
1573  FS.Skip = false;
1574  return OS;
1575  }
1576  return OS << FS.Sep;
1577 }
1578 
1579 struct MDFieldPrinter {
1580  raw_ostream &Out;
1581  FieldSeparator FS;
1582  TypePrinting *TypePrinter = nullptr;
1583  SlotTracker *Machine = nullptr;
1584  const Module *Context = nullptr;
1585 
1586  explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1587  MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1588  SlotTracker *Machine, const Module *Context)
1589  : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1590  }
1591 
1592  void printTag(const DINode *N);
1593  void printMacinfoType(const DIMacroNode *N);
1594  void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1595  void printString(StringRef Name, StringRef Value,
1596  bool ShouldSkipEmpty = true);
1597  void printMetadata(StringRef Name, const Metadata *MD,
1598  bool ShouldSkipNull = true);
1599  template <class IntTy>
1600  void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1601  void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1602  void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1603  template <class IntTy, class Stringifier>
1604  void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1605  bool ShouldSkipZero = true);
1606  void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1607  void printNameTableKind(StringRef Name,
1608  DICompileUnit::DebugNameTableKind NTK);
1609 };
1610 
1611 } // end anonymous namespace
1612 
1613 void MDFieldPrinter::printTag(const DINode *N) {
1614  Out << FS << "tag: ";
1615  auto Tag = dwarf::TagString(N->getTag());
1616  if (!Tag.empty())
1617  Out << Tag;
1618  else
1619  Out << N->getTag();
1620 }
1621 
1622 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1623  Out << FS << "type: ";
1624  auto Type = dwarf::MacinfoString(N->getMacinfoType());
1625  if (!Type.empty())
1626  Out << Type;
1627  else
1628  Out << N->getMacinfoType();
1629 }
1630 
1631 void MDFieldPrinter::printChecksum(
1632  const DIFile::ChecksumInfo<StringRef> &Checksum) {
1633  Out << FS << "checksumkind: " << Checksum.getKindAsString();
1634  printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1635 }
1636 
1637 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1638  bool ShouldSkipEmpty) {
1639  if (ShouldSkipEmpty && Value.empty())
1640  return;
1641 
1642  Out << FS << Name << ": \"";
1643  printEscapedString(Value, Out);
1644  Out << "\"";
1645 }
1646 
1647 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1648  TypePrinting *TypePrinter,
1649  SlotTracker *Machine,
1650  const Module *Context) {
1651  if (!MD) {
1652  Out << "null";
1653  return;
1654  }
1655  WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1656 }
1657 
1658 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1659  bool ShouldSkipNull) {
1660  if (ShouldSkipNull && !MD)
1661  return;
1662 
1663  Out << FS << Name << ": ";
1664  writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1665 }
1666 
1667 template <class IntTy>
1668 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1669  if (ShouldSkipZero && !Int)
1670  return;
1671 
1672  Out << FS << Name << ": " << Int;
1673 }
1674 
1675 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1676  Optional<bool> Default) {
1677  if (Default && Value == *Default)
1678  return;
1679  Out << FS << Name << ": " << (Value ? "true" : "false");
1680 }
1681 
1682 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1683  if (!Flags)
1684  return;
1685 
1686  Out << FS << Name << ": ";
1687 
1688  SmallVector<DINode::DIFlags, 8> SplitFlags;
1689  auto Extra = DINode::splitFlags(Flags, SplitFlags);
1690 
1691  FieldSeparator FlagsFS(" | ");
1692  for (auto F : SplitFlags) {
1693  auto StringF = DINode::getFlagString(F);
1694  assert(!StringF.empty() && "Expected valid flag");
1695  Out << FlagsFS << StringF;
1696  }
1697  if (Extra || SplitFlags.empty())
1698  Out << FlagsFS << Extra;
1699 }
1700 
1701 void MDFieldPrinter::printEmissionKind(StringRef Name,
1702  DICompileUnit::DebugEmissionKind EK) {
1703  Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1704 }
1705 
1706 void MDFieldPrinter::printNameTableKind(StringRef Name,
1707  DICompileUnit::DebugNameTableKind NTK) {
1708  if (NTK == DICompileUnit::DebugNameTableKind::Default)
1709  return;
1710  Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1711 }
1712 
1713 template <class IntTy, class Stringifier>
1714 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1715  Stringifier toString, bool ShouldSkipZero) {
1716  if (!Value)
1717  return;
1718 
1719  Out << FS << Name << ": ";
1720  auto S = toString(Value);
1721  if (!S.empty())
1722  Out << S;
1723  else
1724  Out << Value;
1725 }
1726 
1727 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1728  TypePrinting *TypePrinter, SlotTracker *Machine,
1729  const Module *Context) {
1730  Out << "!GenericDINode(";
1731  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1732  Printer.printTag(N);
1733  Printer.printString("header", N->getHeader());
1734  if (N->getNumDwarfOperands()) {
1735  Out << Printer.FS << "operands: {";
1736  FieldSeparator IFS;
1737  for (auto &I : N->dwarf_operands()) {
1738  Out << IFS;
1739  writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1740  }
1741  Out << "}";
1742  }
1743  Out << ")";
1744 }
1745 
1746 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1747  TypePrinting *TypePrinter, SlotTracker *Machine,
1748  const Module *Context) {
1749  Out << "!DILocation(";
1750  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1751  // Always output the line, since 0 is a relevant and important value for it.
1752  Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1753  Printer.printInt("column", DL->getColumn());
1754  Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1755  Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1756  Out << ")";
1757 }
1758 
1759 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1760  TypePrinting *TypePrinter, SlotTracker *Machine,
1761  const Module *Context) {
1762  Out << "!DISubrange(";
1763  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1764  if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1765  Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1766  else
1767  Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
1768  /*ShouldSkipNull */ false);
1769  Printer.printInt("lowerBound", N->getLowerBound());
1770  Out << ")";
1771 }
1772 
1773 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1774  TypePrinting *, SlotTracker *, const Module *) {
1775  Out << "!DIEnumerator(";
1776  MDFieldPrinter Printer(Out);
1777  Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1778  if (N->isUnsigned()) {
1779  auto Value = static_cast<uint64_t>(N->getValue());
1780  Printer.printInt("value", Value, /* ShouldSkipZero */ false);
1781  Printer.printBool("isUnsigned", true);
1782  } else {
1783  Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1784  }
1785  Out << ")";
1786 }
1787 
1788 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1789  TypePrinting *, SlotTracker *, const Module *) {
1790  Out << "!DIBasicType(";
1791  MDFieldPrinter Printer(Out);
1792  if (N->getTag() != dwarf::DW_TAG_base_type)
1793  Printer.printTag(N);
1794  Printer.printString("name", N->getName());
1795  Printer.printInt("size", N->getSizeInBits());
1796  Printer.printInt("align", N->getAlignInBits());
1797  Printer.printDwarfEnum("encoding", N->getEncoding(),
1798  dwarf::AttributeEncodingString);
1799  Printer.printDIFlags("flags", N->getFlags());
1800  Out << ")";
1801 }
1802 
1803 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1804  TypePrinting *TypePrinter, SlotTracker *Machine,
1805  const Module *Context) {
1806  Out << "!DIDerivedType(";
1807  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1808  Printer.printTag(N);
1809  Printer.printString("name", N->getName());
1810  Printer.printMetadata("scope", N->getRawScope());
1811  Printer.printMetadata("file", N->getRawFile());
1812  Printer.printInt("line", N->getLine());
1813  Printer.printMetadata("baseType", N->getRawBaseType(),
1814  /* ShouldSkipNull */ false);
1815  Printer.printInt("size", N->getSizeInBits());
1816  Printer.printInt("align", N->getAlignInBits());
1817  Printer.printInt("offset", N->getOffsetInBits());
1818  Printer.printDIFlags("flags", N->getFlags());
1819  Printer.printMetadata("extraData", N->getRawExtraData());
1820  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1821  Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1822  /* ShouldSkipZero */ false);
1823  Out << ")";
1824 }
1825 
1826 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1827  TypePrinting *TypePrinter,
1828  SlotTracker *Machine, const Module *Context) {
1829  Out << "!DICompositeType(";
1830  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1831  Printer.printTag(N);
1832  Printer.printString("name", N->getName());
1833  Printer.printMetadata("scope", N->getRawScope());
1834  Printer.printMetadata("file", N->getRawFile());
1835  Printer.printInt("line", N->getLine());
1836  Printer.printMetadata("baseType", N->getRawBaseType());
1837  Printer.printInt("size", N->getSizeInBits());
1838  Printer.printInt("align", N->getAlignInBits());
1839  Printer.printInt("offset", N->getOffsetInBits());
1840  Printer.printDIFlags("flags", N->getFlags());
1841  Printer.printMetadata("elements", N->getRawElements());
1842  Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1843  dwarf::LanguageString);
1844  Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1845  Printer.printMetadata("templateParams", N->getRawTemplateParams());
1846  Printer.printString("identifier", N->getIdentifier());
1847  Printer.printMetadata("discriminator", N->getRawDiscriminator());
1848  Out << ")";
1849 }
1850 
1851 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1852  TypePrinting *TypePrinter,
1853  SlotTracker *Machine, const Module *Context) {
1854  Out << "!DISubroutineType(";
1855  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1856  Printer.printDIFlags("flags", N->getFlags());
1857  Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1858  Printer.printMetadata("types", N->getRawTypeArray(),
1859  /* ShouldSkipNull */ false);
1860  Out << ")";
1861 }
1862 
1863 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1864  SlotTracker *, const Module *) {
1865  Out << "!DIFile(";
1866  MDFieldPrinter Printer(Out);
1867  Printer.printString("filename", N->getFilename(),
1868  /* ShouldSkipEmpty */ false);
1869  Printer.printString("directory", N->getDirectory(),
1870  /* ShouldSkipEmpty */ false);
1871  // Print all values for checksum together, or not at all.
1872  if (N->getChecksum())
1873  Printer.printChecksum(*N->getChecksum());
1874  Printer.printString("source", N->getSource().getValueOr(StringRef()),
1875  /* ShouldSkipEmpty */ true);
1876  Out << ")";
1877 }
1878 
1879 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1880  TypePrinting *TypePrinter, SlotTracker *Machine,
1881  const Module *Context) {
1882  Out << "!DICompileUnit(";
1883  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1884  Printer.printDwarfEnum("language", N->getSourceLanguage(),
1885  dwarf::LanguageString, /* ShouldSkipZero */ false);
1886  Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1887  Printer.printString("producer", N->getProducer());
1888  Printer.printBool("isOptimized", N->isOptimized());
1889  Printer.printString("flags", N->getFlags());
1890  Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1891  /* ShouldSkipZero */ false);
1892  Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1893  Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1894  Printer.printMetadata("enums", N->getRawEnumTypes());
1895  Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1896  Printer.printMetadata("globals", N->getRawGlobalVariables());
1897  Printer.printMetadata("imports", N->getRawImportedEntities());
1898  Printer.printMetadata("macros", N->getRawMacros());
1899  Printer.printInt("dwoId", N->getDWOId());
1900  Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1901  Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1902  false);
1903  Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
1904  Out << ")";
1905 }
1906 
1907 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1908  TypePrinting *TypePrinter, SlotTracker *Machine,
1909  const Module *Context) {
1910  Out << "!DISubprogram(";
1911  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1912  Printer.printString("name", N->getName());
1913  Printer.printString("linkageName", N->getLinkageName());
1914  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1915  Printer.printMetadata("file", N->getRawFile());
1916  Printer.printInt("line", N->getLine());
1917  Printer.printMetadata("type", N->getRawType());
1918  Printer.printBool("isLocal", N->isLocalToUnit());
1919  Printer.printBool("isDefinition", N->isDefinition());
1920  Printer.printInt("scopeLine", N->getScopeLine());
1921  Printer.printMetadata("containingType", N->getRawContainingType());
1922  Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1923  dwarf::VirtualityString);
1924  if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1925  N->getVirtualIndex() != 0)
1926  Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1927  Printer.printInt("thisAdjustment", N->getThisAdjustment());
1928  Printer.printDIFlags("flags", N->getFlags());
1929  Printer.printBool("isOptimized", N->isOptimized());
1930  Printer.printMetadata("unit", N->getRawUnit());
1931  Printer.printMetadata("templateParams", N->getRawTemplateParams());
1932  Printer.printMetadata("declaration", N->getRawDeclaration());
1933  Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
1934  Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1935  Out << ")";
1936 }
1937 
1938 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1939  TypePrinting *TypePrinter, SlotTracker *Machine,
1940  const Module *Context) {
1941  Out << "!DILexicalBlock(";
1942  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1943  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1944  Printer.printMetadata("file", N->getRawFile());
1945  Printer.printInt("line", N->getLine());
1946  Printer.printInt("column", N->getColumn());
1947  Out << ")";
1948 }
1949 
1950 static void writeDILexicalBlockFile(raw_ostream &Out,
1951  const DILexicalBlockFile *N,
1952  TypePrinting *TypePrinter,
1953  SlotTracker *Machine,
1954  const Module *Context) {
1955  Out << "!DILexicalBlockFile(";
1956  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1957  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1958  Printer.printMetadata("file", N->getRawFile());
1959  Printer.printInt("discriminator", N->getDiscriminator(),
1960  /* ShouldSkipZero */ false);
1961  Out << ")";
1962 }
1963 
1964 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1965  TypePrinting *TypePrinter, SlotTracker *Machine,
1966  const Module *Context) {
1967  Out << "!DINamespace(";
1968  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1969  Printer.printString("name", N->getName());
1970  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1971  Printer.printBool("exportSymbols", N->getExportSymbols(), false);
1972  Out << ")";
1973 }
1974 
1975 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1976  TypePrinting *TypePrinter, SlotTracker *Machine,
1977  const Module *Context) {
1978  Out << "!DIMacro(";
1979  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1980  Printer.printMacinfoType(N);
1981  Printer.printInt("line", N->getLine());
1982  Printer.printString("name", N->getName());
1983  Printer.printString("value", N->getValue());
1984  Out << ")";
1985 }
1986 
1987 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1988  TypePrinting *TypePrinter, SlotTracker *Machine,
1989  const Module *Context) {
1990  Out << "!DIMacroFile(";
1991  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1992  Printer.printInt("line", N->getLine());
1993  Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1994  Printer.printMetadata("nodes", N->getRawElements());
1995  Out << ")";
1996 }
1997 
1998 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1999  TypePrinting *TypePrinter, SlotTracker *Machine,
2000  const Module *Context) {
2001  Out << "!DIModule(";
2002  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2003  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2004  Printer.printString("name", N->getName());
2005  Printer.printString("configMacros", N->getConfigurationMacros());
2006  Printer.printString("includePath", N->getIncludePath());
2007  Printer.printString("isysroot", N->getISysRoot());
2008  Out << ")";
2009 }
2010 
2011 
2012 static void writeDITemplateTypeParameter(raw_ostream &Out,
2013  const DITemplateTypeParameter *N,
2014  TypePrinting *TypePrinter,
2015  SlotTracker *Machine,
2016  const Module *Context) {
2017  Out << "!DITemplateTypeParameter(";
2018  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2019  Printer.printString("name", N->getName());
2020  Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2021  Out << ")";
2022 }
2023 
2024 static void writeDITemplateValueParameter(raw_ostream &Out,
2025  const DITemplateValueParameter *N,
2026  TypePrinting *TypePrinter,
2027  SlotTracker *Machine,
2028  const Module *Context) {
2029  Out << "!DITemplateValueParameter(";
2030  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2031  if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2032  Printer.printTag(N);
2033  Printer.printString("name", N->getName());
2034  Printer.printMetadata("type", N->getRawType());
2035  Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2036  Out << ")";
2037 }
2038 
2039 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2040  TypePrinting *TypePrinter,
2041  SlotTracker *Machine, const Module *Context) {
2042  Out << "!DIGlobalVariable(";
2043  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2044  Printer.printString("name", N->getName());
2045  Printer.printString("linkageName", N->getLinkageName());
2046  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2047  Printer.printMetadata("file", N->getRawFile());
2048  Printer.printInt("line", N->getLine());
2049  Printer.printMetadata("type", N->getRawType());
2050  Printer.printBool("isLocal", N->isLocalToUnit());
2051  Printer.printBool("isDefinition", N->isDefinition());
2052  Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2053  Printer.printInt("align", N->getAlignInBits());
2054  Out << ")";
2055 }
2056 
2057 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2058  TypePrinting *TypePrinter,
2059  SlotTracker *Machine, const Module *Context) {
2060  Out << "!DILocalVariable(";
2061  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2062  Printer.printString("name", N->getName());
2063  Printer.printInt("arg", N->getArg());
2064  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2065  Printer.printMetadata("file", N->getRawFile());
2066  Printer.printInt("line", N->getLine());
2067  Printer.printMetadata("type", N->getRawType());
2068  Printer.printDIFlags("flags", N->getFlags());
2069  Printer.printInt("align", N->getAlignInBits());
2070  Out << ")";
2071 }
2072 
2073 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2074  TypePrinting *TypePrinter,
2075  SlotTracker *Machine, const Module *Context) {
2076  Out << "!DILabel(";
2077  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2078  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2079  Printer.printString("name", N->getName());
2080  Printer.printMetadata("file", N->getRawFile());
2081  Printer.printInt("line", N->getLine());
2082  Out << ")";
2083 }
2084 
2085 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2086  TypePrinting *TypePrinter, SlotTracker *Machine,
2087  const Module *Context) {
2088  Out << "!DIExpression(";
2089  FieldSeparator FS;
2090  if (N->isValid()) {
2091  for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
2092  auto OpStr = dwarf::OperationEncodingString(I->getOp());
2093  assert(!OpStr.empty() && "Expected valid opcode");
2094 
2095  Out << FS << OpStr;
2096  for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2097  Out << FS << I->getArg(A);
2098  }
2099  } else {
2100  for (const auto &I : N->getElements())
2101  Out << FS << I;
2102  }
2103  Out << ")";
2104 }
2105 
2106 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2107  const DIGlobalVariableExpression *N,
2108  TypePrinting *TypePrinter,
2109  SlotTracker *Machine,
2110  const Module *Context) {
2111  Out << "!DIGlobalVariableExpression(";
2112  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2113  Printer.printMetadata("var", N->getVariable());
2114  Printer.printMetadata("expr", N->getExpression());
2115  Out << ")";
2116 }
2117 
2118 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2119  TypePrinting *TypePrinter, SlotTracker *Machine,
2120  const Module *Context) {
2121  Out << "!DIObjCProperty(";
2122  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2123  Printer.printString("name", N->getName());
2124  Printer.printMetadata("file", N->getRawFile());
2125  Printer.printInt("line", N->getLine());
2126  Printer.printString("setter", N->getSetterName());
2127  Printer.printString("getter", N->getGetterName());
2128  Printer.printInt("attributes", N->getAttributes());
2129  Printer.printMetadata("type", N->getRawType());
2130  Out << ")";
2131 }
2132 
2133 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2134  TypePrinting *TypePrinter,
2135  SlotTracker *Machine, const Module *Context) {
2136  Out << "!DIImportedEntity(";
2137  MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2138  Printer.printTag(N);
2139  Printer.printString("name", N->getName());
2140  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2141  Printer.printMetadata("entity", N->getRawEntity());
2142  Printer.printMetadata("file", N->getRawFile());
2143  Printer.printInt("line", N->getLine());
2144  Out << ")";
2145 }
2146 
2147 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2148  TypePrinting *TypePrinter,
2149  SlotTracker *Machine,
2150  const Module *Context) {
2151  if (Node->isDistinct())
2152  Out << "distinct ";
2153  else if (Node->isTemporary())
2154  Out << "<temporary!> "; // Handle broken code.
2155 
2156  switch (Node->getMetadataID()) {
2157  default:
2158  llvm_unreachable("Expected uniquable MDNode");
2159 #define HANDLE_MDNODE_LEAF(CLASS) \
2160  case Metadata::CLASS##Kind: \
2161  write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
2162  break;
2163 #include "llvm/IR/Metadata.def"
2164  }
2165 }
2166 
2167 // Full implementation of printing a Value as an operand with support for
2168 // TypePrinting, etc.
2169 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2170  TypePrinting *TypePrinter,
2171  SlotTracker *Machine,
2172  const Module *Context) {
2173  if (V->hasName()) {
2174  PrintLLVMName(Out, V);
2175  return;
2176  }
2177 
2178  const Constant *CV = dyn_cast<Constant>(V);
2179  if (CV && !isa<GlobalValue>(CV)) {
2180  assert(TypePrinter && "Constants require TypePrinting!");
2181  WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2182  return;
2183  }
2184 
2185  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2186  Out << "asm ";
2187  if (IA->hasSideEffects())
2188  Out << "sideeffect ";
2189  if (IA->isAlignStack())
2190  Out << "alignstack ";
2191  // We don't emit the AD_ATT dialect as it's the assumed default.
2192  if (IA->getDialect() == InlineAsm::AD_Intel)
2193  Out << "inteldialect ";
2194  Out << '"';
2195  printEscapedString(IA->getAsmString(), Out);
2196  Out << "\", \"";
2197  printEscapedString(IA->getConstraintString(), Out);
2198  Out << '"';
2199  return;
2200  }
2201 
2202  if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2203  WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2204  Context, /* FromValue */ true);
2205  return;
2206  }
2207 
2208  char Prefix = '%';
2209  int Slot;
2210  // If we have a SlotTracker, use it.
2211  if (Machine) {
2212  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2213  Slot = Machine->getGlobalSlot(GV);
2214  Prefix = '@';
2215  } else {
2216  Slot = Machine->getLocalSlot(V);
2217 
2218  // If the local value didn't succeed, then we may be referring to a value
2219  // from a different function. Translate it, as this can happen when using
2220  // address of blocks.
2221  if (Slot == -1)
2222  if ((Machine = createSlotTracker(V))) {
2223  Slot = Machine->getLocalSlot(V);
2224  delete Machine;
2225  }
2226  }
2227  } else if ((Machine = createSlotTracker(V))) {
2228  // Otherwise, create one to get the # and then destroy it.
2229  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2230  Slot = Machine->getGlobalSlot(GV);
2231  Prefix = '@';
2232  } else {
2233  Slot = Machine->getLocalSlot(V);
2234  }
2235  delete Machine;
2236  Machine = nullptr;
2237  } else {
2238  Slot = -1;
2239  }
2240 
2241  if (Slot != -1)
2242  Out << Prefix << Slot;
2243  else
2244  Out << "<badref>";
2245 }
2246 
2247 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2248  TypePrinting *TypePrinter,
2249  SlotTracker *Machine, const Module *Context,
2250  bool FromValue) {
2251  // Write DIExpressions inline when used as a value. Improves readability of
2252  // debug info intrinsics.
2253  if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2254  writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2255  return;
2256  }
2257 
2258  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2259  std::unique_ptr<SlotTracker> MachineStorage;
2260  if (!Machine) {
2261  MachineStorage = make_unique<SlotTracker>(Context);
2262  Machine = MachineStorage.get();
2263  }
2264  int Slot = Machine->getMetadataSlot(N);
2265  if (Slot == -1)
2266  // Give the pointer value instead of "badref", since this comes up all
2267  // the time when debugging.
2268  Out << "<" << N << ">";
2269  else
2270  Out << '!' << Slot;
2271  return;
2272  }
2273 
2274  if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2275  Out << "!\"";
2276  printEscapedString(MDS->getString(), Out);
2277  Out << '"';
2278  return;
2279  }
2280 
2281  auto *V = cast<ValueAsMetadata>(MD);
2282  assert(TypePrinter && "TypePrinter required for metadata values");
2283  assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2284  "Unexpected function-local metadata outside of value argument");
2285 
2286  TypePrinter->print(V->getValue()->getType(), Out);
2287  Out << ' ';
2288  WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2289 }
2290 
2291 namespace {
2292 
2293 class AssemblyWriter {
2294  formatted_raw_ostream &Out;
2295  const Module *TheModule = nullptr;
2296  const ModuleSummaryIndex *TheIndex = nullptr;
2297  std::unique_ptr<SlotTracker> SlotTrackerStorage;
2299  TypePrinting TypePrinter;
2300  AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2301  SetVector<const Comdat *> Comdats;
2302  bool IsForDebug;
2303  bool ShouldPreserveUseListOrder;
2304  UseListOrderStack UseListOrders;
2305  SmallVector<StringRef, 8> MDNames;
2306  /// Synchronization scope names registered with LLVMContext.
2309 
2310 public:
2311  /// Construct an AssemblyWriter with an external SlotTracker
2312  AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2313  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2314  bool ShouldPreserveUseListOrder = false);
2315 
2316  AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2317  const ModuleSummaryIndex *Index, bool IsForDebug);
2318 
2319  void printMDNodeBody(const MDNode *MD);
2320  void printNamedMDNode(const NamedMDNode *NMD);
2321 
2322  void printModule(const Module *M);
2323 
2324  void writeOperand(const Value *Op, bool PrintType);
2325  void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2326  void writeOperandBundles(ImmutableCallSite CS);
2327  void writeSyncScope(const LLVMContext &Context,
2328  SyncScope::ID SSID);
2329  void writeAtomic(const LLVMContext &Context,
2330  AtomicOrdering Ordering,
2331  SyncScope::ID SSID);
2332  void writeAtomicCmpXchg(const LLVMContext &Context,
2333  AtomicOrdering SuccessOrdering,
2334  AtomicOrdering FailureOrdering,
2335  SyncScope::ID SSID);
2336 
2337  void writeAllMDNodes();
2338  void writeMDNode(unsigned Slot, const MDNode *Node);
2339  void writeAllAttributeGroups();
2340 
2341  void printTypeIdentities();
2342  void printGlobal(const GlobalVariable *GV);
2343  void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2344  void printComdat(const Comdat *C);
2345  void printFunction(const Function *F);
2346  void printArgument(const Argument *FA, AttributeSet Attrs);
2347  void printBasicBlock(const BasicBlock *BB);
2348  void printInstructionLine(const Instruction &I);
2349  void printInstruction(const Instruction &I);
2350 
2351  void printUseListOrder(const UseListOrder &Order);
2352  void printUseLists(const Function *F);
2353 
2354  void printModuleSummaryIndex();
2355  void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2356  void printSummary(const GlobalValueSummary &Summary);
2357  void printAliasSummary(const AliasSummary *AS);
2358  void printGlobalVarSummary(const GlobalVarSummary *GS);
2359  void printFunctionSummary(const FunctionSummary *FS);
2360  void printTypeIdSummary(const TypeIdSummary &TIS);
2361  void printTypeTestResolution(const TypeTestResolution &TTRes);
2362  void printArgs(const std::vector<uint64_t> &Args);
2363  void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2364  void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2365  void printVFuncId(const FunctionSummary::VFuncId VFId);
2366  void
2367  printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2368  const char *Tag);
2369  void
2370  printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2371  const char *Tag);
2372 
2373 private:
2374  /// Print out metadata attachments.
2375  void printMetadataAttachments(
2376  const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2377  StringRef Separator);
2378 
2379  // printInfoComment - Print a little comment after the instruction indicating
2380  // which slot it occupies.
2381  void printInfoComment(const Value &V);
2382 
2383  // printGCRelocateComment - print comment after call to the gc.relocate
2384  // intrinsic indicating base and derived pointer names.
2385  void printGCRelocateComment(const GCRelocateInst &Relocate);
2386 };
2387 
2388 } // end anonymous namespace
2389 
2390 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2391  const Module *M, AssemblyAnnotationWriter *AAW,
2392  bool IsForDebug, bool ShouldPreserveUseListOrder)
2393  : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2394  IsForDebug(IsForDebug),
2395  ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2396  if (!TheModule)
2397  return;
2398  for (const GlobalObject &GO : TheModule->global_objects())
2399  if (const Comdat *C = GO.getComdat())
2400  Comdats.insert(C);
2401 }
2402 
2403 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2404  const ModuleSummaryIndex *Index, bool IsForDebug)
2405  : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2406  IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2407 
2408 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2409  if (!Operand) {
2410  Out << "<null operand!>";
2411  return;
2412  }
2413  if (PrintType) {
2414  TypePrinter.print(Operand->getType(), Out);
2415  Out << ' ';
2416  }
2417  WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2418 }
2419 
2420 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2421  SyncScope::ID SSID) {
2422  switch (SSID) {
2423  case SyncScope::System: {
2424  break;
2425  }
2426  default: {
2427  if (SSNs.empty())
2428  Context.getSyncScopeNames(SSNs);
2429 
2430  Out << " syncscope(\"";
2431  printEscapedString(SSNs[SSID], Out);
2432  Out << "\")";
2433  break;
2434  }
2435  }
2436 }
2437 
2438 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2439  AtomicOrdering Ordering,
2440  SyncScope::ID SSID) {
2441  if (Ordering == AtomicOrdering::NotAtomic)
2442  return;
2443 
2444  writeSyncScope(Context, SSID);
2445  Out << " " << toIRString(Ordering);
2446 }
2447 
2448 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2449  AtomicOrdering SuccessOrdering,
2450  AtomicOrdering FailureOrdering,
2451  SyncScope::ID SSID) {
2452  assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2453  FailureOrdering != AtomicOrdering::NotAtomic);
2454 
2455  writeSyncScope(Context, SSID);
2456  Out << " " << toIRString(SuccessOrdering);
2457  Out << " " << toIRString(FailureOrdering);
2458 }
2459 
2460 void AssemblyWriter::writeParamOperand(const Value *Operand,
2461  AttributeSet Attrs) {
2462  if (!Operand) {
2463  Out << "<null operand!>";
2464  return;
2465  }
2466 
2467  // Print the type
2468  TypePrinter.print(Operand->getType(), Out);
2469  // Print parameter attributes list
2470  if (Attrs.hasAttributes())
2471  Out << ' ' << Attrs.getAsString();
2472  Out << ' ';
2473  // Print the operand
2474  WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2475 }
2476 
2477 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2478  if (!CS.hasOperandBundles())
2479  return;
2480 
2481  Out << " [ ";
2482 
2483  bool FirstBundle = true;
2484  for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2486 
2487  if (!FirstBundle)
2488  Out << ", ";
2489  FirstBundle = false;
2490 
2491  Out << '"';
2492  printEscapedString(BU.getTagName(), Out);
2493  Out << '"';
2494 
2495  Out << '(';
2496 
2497  bool FirstInput = true;
2498  for (const auto &Input : BU.Inputs) {
2499  if (!FirstInput)
2500  Out << ", ";
2501  FirstInput = false;
2502 
2503  TypePrinter.print(Input->getType(), Out);
2504  Out << " ";
2505  WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2506  }
2507 
2508  Out << ')';
2509  }
2510 
2511  Out << " ]";
2512 }
2513 
2514 void AssemblyWriter::printModule(const Module *M) {
2515  Machine.initializeIfNeeded();
2516 
2517  if (ShouldPreserveUseListOrder)
2518  UseListOrders = predictUseListOrder(M);
2519 
2520  if (!M->getModuleIdentifier().empty() &&
2521  // Don't print the ID if it will start a new line (which would
2522  // require a comment char before it).
2523  M->getModuleIdentifier().find('\n') == std::string::npos)
2524  Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2525 
2526  if (!M->getSourceFileName().empty()) {
2527  Out << "source_filename = \"";
2529  Out << "\"\n";
2530  }
2531 
2532  const std::string &DL = M->getDataLayoutStr();
2533  if (!DL.empty())
2534  Out << "target datalayout = \"" << DL << "\"\n";
2535  if (!M->getTargetTriple().empty())
2536  Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2537 
2538  if (!M->getModuleInlineAsm().empty()) {
2539  Out << '\n';
2540 
2541  // Split the string into lines, to make it easier to read the .ll file.
2543  do {
2544  StringRef Front;
2545  std::tie(Front, Asm) = Asm.split('\n');
2546 
2547  // We found a newline, print the portion of the asm string from the
2548  // last newline up to this newline.
2549  Out << "module asm \"";
2550  printEscapedString(Front, Out);
2551  Out << "\"\n";
2552  } while (!Asm.empty());
2553  }
2554 
2555  printTypeIdentities();
2556 
2557  // Output all comdats.
2558  if (!Comdats.empty())
2559  Out << '\n';
2560  for (const Comdat *C : Comdats) {
2561  printComdat(C);
2562  if (C != Comdats.back())
2563  Out << '\n';
2564  }
2565 
2566  // Output all globals.
2567  if (!M->global_empty()) Out << '\n';
2568  for (const GlobalVariable &GV : M->globals()) {
2569  printGlobal(&GV); Out << '\n';
2570  }
2571 
2572  // Output all aliases.
2573  if (!M->alias_empty()) Out << "\n";
2574  for (const GlobalAlias &GA : M->aliases())
2575  printIndirectSymbol(&GA);
2576 
2577  // Output all ifuncs.
2578  if (!M->ifunc_empty()) Out << "\n";
2579  for (const GlobalIFunc &GI : M->ifuncs())
2580  printIndirectSymbol(&GI);
2581 
2582  // Output global use-lists.
2583  printUseLists(nullptr);
2584 
2585  // Output all of the functions.
2586  for (const Function &F : *M)
2587  printFunction(&F);
2588  assert(UseListOrders.empty() && "All use-lists should have been consumed");
2589 
2590  // Output all attribute groups.
2591  if (!Machine.as_empty()) {
2592  Out << '\n';
2593  writeAllAttributeGroups();
2594  }
2595 
2596  // Output named metadata.
2597  if (!M->named_metadata_empty()) Out << '\n';
2598 
2599  for (const NamedMDNode &Node : M->named_metadata())
2600  printNamedMDNode(&Node);
2601 
2602  // Output metadata.
2603  if (!Machine.mdn_empty()) {
2604  Out << '\n';
2605  writeAllMDNodes();
2606  }
2607 }
2608 
2609 void AssemblyWriter::printModuleSummaryIndex() {
2610  assert(TheIndex);
2611  Machine.initializeIndexIfNeeded();
2612 
2613  Out << "\n";
2614 
2615  // Print module path entries. To print in order, add paths to a vector
2616  // indexed by module slot.
2617  std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2618  std::string RegularLTOModuleName = "[Regular LTO]";
2619  moduleVec.resize(TheIndex->modulePaths().size());
2620  for (auto &ModPath : TheIndex->modulePaths())
2621  moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2622  // A module id of -1 is a special entry for a regular LTO module created
2623  // during the thin link.
2624  ModPath.second.first == -1u ? RegularLTOModuleName
2625  : (std::string)ModPath.first(),
2626  ModPath.second.second);
2627 
2628  unsigned i = 0;
2629  for (auto &ModPair : moduleVec) {
2630  Out << "^" << i++ << " = module: (";
2631  Out << "path: \"";
2632  printEscapedString(ModPair.first, Out);
2633  Out << "\", hash: (";
2634  FieldSeparator FS;
2635  for (auto Hash : ModPair.second)
2636  Out << FS << Hash;
2637  Out << "))\n";
2638  }
2639 
2640  // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2641  // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2642  for (auto &GlobalList : *TheIndex) {
2643  auto GUID = GlobalList.first;
2644  for (auto &Summary : GlobalList.second.SummaryList)
2645  SummaryToGUIDMap[Summary.get()] = GUID;
2646  }
2647 
2648  // Print the global value summary entries.
2649  for (auto &GlobalList : *TheIndex) {
2650  auto GUID = GlobalList.first;
2651  auto VI = TheIndex->getValueInfo(GlobalList);
2652  printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2653  }
2654 
2655  // Print the TypeIdMap entries.
2656  for (auto &TId : TheIndex->typeIds()) {
2657  auto GUID = GlobalValue::getGUID(TId.first);
2658  Out << "^" << Machine.getGUIDSlot(GUID) << " = typeid: (name: \""
2659  << TId.first << "\"";
2660  printTypeIdSummary(TId.second);
2661  Out << ") ; guid = " << GUID << "\n";
2662  }
2663 }
2664 
2665 static const char *
2667  switch (K) {
2669  return "indir";
2671  return "singleImpl";
2673  return "branchFunnel";
2674  }
2675  llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2676 }
2677 
2680  switch (K) {
2682  return "indir";
2684  return "uniformRetVal";
2686  return "uniqueRetVal";
2688  return "virtualConstProp";
2689  }
2690  llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2691 }
2692 
2694  switch (K) {
2696  return "unsat";
2698  return "byteArray";
2700  return "inline";
2702  return "single";
2704  return "allOnes";
2705  }
2706  llvm_unreachable("invalid TypeTestResolution kind");
2707 }
2708 
2709 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2710  Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2711  << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2712 
2713  // The following fields are only used if the target does not support the use
2714  // of absolute symbols to store constants. Print only if non-zero.
2715  if (TTRes.AlignLog2)
2716  Out << ", alignLog2: " << TTRes.AlignLog2;
2717  if (TTRes.SizeM1)
2718  Out << ", sizeM1: " << TTRes.SizeM1;
2719  if (TTRes.BitMask)
2720  // BitMask is uint8_t which causes it to print the corresponding char.
2721  Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2722  if (TTRes.InlineBits)
2723  Out << ", inlineBits: " << TTRes.InlineBits;
2724 
2725  Out << ")";
2726 }
2727 
2728 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2729  Out << ", summary: (";
2730  printTypeTestResolution(TIS.TTRes);
2731  if (!TIS.WPDRes.empty()) {
2732  Out << ", wpdResolutions: (";
2733  FieldSeparator FS;
2734  for (auto &WPDRes : TIS.WPDRes) {
2735  Out << FS;
2736  Out << "(offset: " << WPDRes.first << ", ";
2737  printWPDRes(WPDRes.second);
2738  Out << ")";
2739  }
2740  Out << ")";
2741  }
2742  Out << ")";
2743 }
2744 
2745 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2746  Out << "args: (";
2747  FieldSeparator FS;
2748  for (auto arg : Args) {
2749  Out << FS;
2750  Out << arg;
2751  }
2752  Out << ")";
2753 }
2754 
2755 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2756  Out << "wpdRes: (kind: ";
2757  Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2758 
2760  Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2761 
2762  if (!WPDRes.ResByArg.empty()) {
2763  Out << ", resByArg: (";
2764  FieldSeparator FS;
2765  for (auto &ResByArg : WPDRes.ResByArg) {
2766  Out << FS;
2767  printArgs(ResByArg.first);
2768  Out << ", byArg: (kind: ";
2769  Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2770  if (ResByArg.second.TheKind ==
2772  ResByArg.second.TheKind ==
2774  Out << ", info: " << ResByArg.second.Info;
2775 
2776  // The following fields are only used if the target does not support the
2777  // use of absolute symbols to store constants. Print only if non-zero.
2778  if (ResByArg.second.Byte || ResByArg.second.Bit)
2779  Out << ", byte: " << ResByArg.second.Byte
2780  << ", bit: " << ResByArg.second.Bit;
2781 
2782  Out << ")";
2783  }
2784  Out << ")";
2785  }
2786  Out << ")";
2787 }
2788 
2790  switch (SK) {
2792  return "alias";
2794  return "function";
2796  return "variable";
2797  }
2798  llvm_unreachable("invalid summary kind");
2799 }
2800 
2801 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2802  Out << ", aliasee: ";
2803  // The indexes emitted for distributed backends may not include the
2804  // aliasee summary (only if it is being imported directly). Handle
2805  // that case by just emitting "null" as the aliasee.
2806  if (AS->hasAliasee())
2807  Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2808  else
2809  Out << "null";
2810 }
2811 
2812 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2813  // Nothing for now
2814 }
2815 
2817  switch (LT) {
2819  return "external";
2821  return "private";
2823  return "internal";
2825  return "linkonce";
2827  return "linkonce_odr";
2829  return "weak";
2831  return "weak_odr";
2833  return "common";
2835  return "appending";
2837  return "extern_weak";
2839  return "available_externally";
2840  }
2841  llvm_unreachable("invalid linkage");
2842 }
2843 
2844 // When printing the linkage types in IR where the ExternalLinkage is
2845 // not printed, and other linkage types are expected to be printed with
2846 // a space after the name.
2848  if (LT == GlobalValue::ExternalLinkage)
2849  return "";
2850  return getLinkageName(LT) + " ";
2851 }
2852 
2853 static const char *getHotnessName(CalleeInfo::HotnessType HT) {
2854  switch (HT) {
2856  return "unknown";
2858  return "cold";
2860  return "none";
2862  return "hot";
2864  return "critical";
2865  }
2866  llvm_unreachable("invalid hotness");
2867 }
2868 
2869 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2870  Out << ", insts: " << FS->instCount();
2871 
2872  FunctionSummary::FFlags FFlags = FS->fflags();
2873  if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2874  FFlags.ReturnDoesNotAlias) {
2875  Out << ", funcFlags: (";
2876  Out << "readNone: " << FFlags.ReadNone;
2877  Out << ", readOnly: " << FFlags.ReadOnly;
2878  Out << ", noRecurse: " << FFlags.NoRecurse;
2879  Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2880  Out << ")";
2881  }
2882  if (!FS->calls().empty()) {
2883  Out << ", calls: (";
2884  FieldSeparator IFS;
2885  for (auto &Call : FS->calls()) {
2886  Out << IFS;
2887  Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2888  if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2889  Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2890  else if (Call.second.RelBlockFreq)
2891  Out << ", relbf: " << Call.second.RelBlockFreq;
2892  Out << ")";
2893  }
2894  Out << ")";
2895  }
2896 
2897  if (const auto *TIdInfo = FS->getTypeIdInfo())
2898  printTypeIdInfo(*TIdInfo);
2899 }
2900 
2901 void AssemblyWriter::printTypeIdInfo(
2902  const FunctionSummary::TypeIdInfo &TIDInfo) {
2903  Out << ", typeIdInfo: (";
2904  FieldSeparator TIDFS;
2905  if (!TIDInfo.TypeTests.empty()) {
2906  Out << TIDFS;
2907  Out << "typeTests: (";
2908  FieldSeparator FS;
2909  for (auto &GUID : TIDInfo.TypeTests) {
2910  Out << FS;
2911  auto Slot = Machine.getGUIDSlot(GUID);
2912  if (Slot != -1)
2913  Out << "^" << Slot;
2914  else
2915  Out << GUID;
2916  }
2917  Out << ")";
2918  }
2919  if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2920  Out << TIDFS;
2921  printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2922  }
2923  if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2924  Out << TIDFS;
2925  printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2926  }
2927  if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2928  Out << TIDFS;
2929  printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2930  "typeTestAssumeConstVCalls");
2931  }
2932  if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2933  Out << TIDFS;
2934  printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2935  "typeCheckedLoadConstVCalls");
2936  }
2937  Out << ")";
2938 }
2939 
2940 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
2941  Out << "vFuncId: (";
2942  auto Slot = Machine.getGUIDSlot(VFId.GUID);
2943  if (Slot != -1)
2944  Out << "^" << Slot;
2945  else
2946  Out << "guid: " << VFId.GUID;
2947  Out << ", offset: " << VFId.Offset;
2948  Out << ")";
2949 }
2950 
2951 void AssemblyWriter::printNonConstVCalls(
2952  const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
2953  Out << Tag << ": (";
2954  FieldSeparator FS;
2955  for (auto &VFuncId : VCallList) {
2956  Out << FS;
2957  printVFuncId(VFuncId);
2958  }
2959  Out << ")";
2960 }
2961 
2962 void AssemblyWriter::printConstVCalls(
2963  const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
2964  Out << Tag << ": (";
2965  FieldSeparator FS;
2966  for (auto &ConstVCall : VCallList) {
2967  Out << FS;
2968  Out << "(";
2969  printVFuncId(ConstVCall.VFunc);
2970  if (!ConstVCall.Args.empty()) {
2971  Out << ", ";
2972  printArgs(ConstVCall.Args);
2973  }
2974  Out << ")";
2975  }
2976  Out << ")";
2977 }
2978 
2979 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
2980  GlobalValueSummary::GVFlags GVFlags = Summary.flags();
2982  Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
2983  Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
2984  << ", flags: (";
2985  Out << "linkage: " << getLinkageName(LT);
2986  Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
2987  Out << ", live: " << GVFlags.Live;
2988  Out << ", dsoLocal: " << GVFlags.DSOLocal;
2989  Out << ")";
2990 
2992  printAliasSummary(cast<AliasSummary>(&Summary));
2993  else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
2994  printFunctionSummary(cast<FunctionSummary>(&Summary));
2995  else
2996  printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
2997 
2998  auto RefList = Summary.refs();
2999  if (!RefList.empty()) {
3000  Out << ", refs: (";
3001  FieldSeparator FS;
3002  for (auto &Ref : RefList) {
3003  Out << FS;
3004  Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3005  }
3006  Out << ")";
3007  }
3008 
3009  Out << ")";
3010 }
3011 
3012 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3013  Out << "^" << Slot << " = gv: (";
3014  if (!VI.name().empty())
3015  Out << "name: \"" << VI.name() << "\"";
3016  else
3017  Out << "guid: " << VI.getGUID();
3018  if (!VI.getSummaryList().empty()) {
3019  Out << ", summaries: (";
3020  FieldSeparator FS;
3021  for (auto &Summary : VI.getSummaryList()) {
3022  Out << FS;
3023  printSummary(*Summary);
3024  }
3025  Out << ")";
3026  }
3027  Out << ")";
3028  if (!VI.name().empty())
3029  Out << " ; guid = " << VI.getGUID();
3030  Out << "\n";
3031 }
3032 
3034  formatted_raw_ostream &Out) {
3035  if (Name.empty()) {
3036  Out << "<empty name> ";
3037  } else {
3038  if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3039  Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3040  Out << Name[0];
3041  else
3042  Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3043  for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3044  unsigned char C = Name[i];
3045  if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3046  C == '.' || C == '_')
3047  Out << C;
3048  else
3049  Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3050  }
3051  }
3052 }
3053 
3054 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3055  Out << '!';
3056  printMetadataIdentifier(NMD->getName(), Out);
3057  Out << " = !{";
3058  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3059  if (i)
3060  Out << ", ";
3061 
3062  // Write DIExpressions inline.
3063  // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3064  MDNode *Op = NMD->getOperand(i);
3065  if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3066  writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3067  continue;
3068  }
3069 
3070  int Slot = Machine.getMetadataSlot(Op);
3071  if (Slot == -1)
3072  Out << "<badref>";
3073  else
3074  Out << '!' << Slot;
3075  }
3076  Out << "}\n";
3077 }
3078 
3080  formatted_raw_ostream &Out) {
3081  switch (Vis) {
3082  case GlobalValue::DefaultVisibility: break;
3083  case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3084  case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3085  }
3086 }
3087 
3088 static void PrintDSOLocation(const GlobalValue &GV,
3089  formatted_raw_ostream &Out) {
3090  // GVs with local linkage or non default visibility are implicitly dso_local,
3091  // so we don't print it.
3092  bool Implicit = GV.hasLocalLinkage() ||
3094  if (GV.isDSOLocal() && !Implicit)
3095  Out << "dso_local ";
3096 }
3097 
3099  formatted_raw_ostream &Out) {
3100  switch (SCT) {
3102  case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3103  case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3104  }
3105 }
3106 
3108  formatted_raw_ostream &Out) {
3109  switch (TLM) {
3111  break;
3113  Out << "thread_local ";
3114  break;
3116  Out << "thread_local(localdynamic) ";
3117  break;
3119  Out << "thread_local(initialexec) ";
3120  break;
3122  Out << "thread_local(localexec) ";
3123  break;
3124  }
3125 }
3126 
3128  switch (UA) {
3130  return "";
3132  return "local_unnamed_addr";
3134  return "unnamed_addr";
3135  }
3136  llvm_unreachable("Unknown UnnamedAddr");
3137 }
3138 
3140  const GlobalObject &GO) {
3141  const Comdat *C = GO.getComdat();
3142  if (!C)
3143  return;
3144 
3145  if (isa<GlobalVariable>(GO))
3146  Out << ',';
3147  Out << " comdat";
3148 
3149  if (GO.getName() == C->getName())
3150  return;
3151 
3152  Out << '(';
3153  PrintLLVMName(Out, C->getName(), ComdatPrefix);
3154  Out << ')';
3155 }
3156 
3157 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3158  if (GV->isMaterializable())
3159  Out << "; Materializable\n";
3160 
3161  WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3162  Out << " = ";
3163 
3164  if (!GV->hasInitializer() && GV->hasExternalLinkage())
3165  Out << "external ";
3166 
3167  Out << getLinkageNameWithSpace(GV->getLinkage());
3168  PrintDSOLocation(*GV, Out);
3169  PrintVisibility(GV->getVisibility(), Out);
3173  if (!UA.empty())
3174  Out << UA << ' ';
3175 
3176  if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3177  Out << "addrspace(" << AddressSpace << ") ";
3178  if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3179  Out << (GV->isConstant() ? "constant " : "global ");
3180  TypePrinter.print(GV->getValueType(), Out);
3181 
3182  if (GV->hasInitializer()) {
3183  Out << ' ';
3184  writeOperand(GV->getInitializer(), false);
3185  }
3186 
3187  if (GV->hasSection()) {
3188  Out << ", section \"";
3189  printEscapedString(GV->getSection(), Out);
3190  Out << '"';
3191  }
3192  maybePrintComdat(Out, *GV);
3193  if (GV->getAlignment())
3194  Out << ", align " << GV->getAlignment();
3195 
3197  GV->getAllMetadata(MDs);
3198  printMetadataAttachments(MDs, ", ");
3199 
3200  auto Attrs = GV->getAttributes();
3201  if (Attrs.hasAttributes())
3202  Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3203 
3204  printInfoComment(*GV);
3205 }
3206 
3207 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3208  if (GIS->isMaterializable())
3209  Out << "; Materializable\n";
3210 
3211  WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3212  Out << " = ";
3213 
3214  Out << getLinkageNameWithSpace(GIS->getLinkage());
3215  PrintDSOLocation(*GIS, Out);
3216  PrintVisibility(GIS->getVisibility(), Out);
3220  if (!UA.empty())
3221  Out << UA << ' ';
3222 
3223  if (isa<GlobalAlias>(GIS))
3224  Out << "alias ";
3225  else if (isa<GlobalIFunc>(GIS))
3226  Out << "ifunc ";
3227  else
3228  llvm_unreachable("Not an alias or ifunc!");
3229 
3230  TypePrinter.print(GIS->getValueType(), Out);
3231 
3232  Out << ", ";
3233 
3234  const Constant *IS = GIS->getIndirectSymbol();
3235 
3236  if (!IS) {
3237  TypePrinter.print(GIS->getType(), Out);
3238  Out << " <<NULL ALIASEE>>";
3239  } else {
3240  writeOperand(IS, !isa<ConstantExpr>(IS));
3241  }
3242 
3243  printInfoComment(*GIS);
3244  Out << '\n';
3245 }
3246 
3247 void AssemblyWriter::printComdat(const Comdat *C) {
3248  C->print(Out);
3249 }
3250 
3251 void AssemblyWriter::printTypeIdentities() {
3252  if (TypePrinter.empty())
3253  return;
3254 
3255  Out << '\n';
3256 
3257  // Emit all numbered types.
3258  auto &NumberedTypes = TypePrinter.getNumberedTypes();
3259  for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3260  Out << '%' << I << " = type ";
3261 
3262  // Make sure we print out at least one level of the type structure, so
3263  // that we do not get %2 = type %2
3264  TypePrinter.printStructBody(NumberedTypes[I], Out);
3265  Out << '\n';
3266  }
3267 
3268  auto &NamedTypes = TypePrinter.getNamedTypes();
3269  for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3270  PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3271  Out << " = type ";
3272 
3273  // Make sure we print out at least one level of the type structure, so
3274  // that we do not get %FILE = type %FILE
3275  TypePrinter.printStructBody(NamedTypes[I], Out);
3276  Out << '\n';
3277  }
3278 }
3279 
3280 /// printFunction - Print all aspects of a function.
3281 void AssemblyWriter::printFunction(const Function *F) {
3282  // Print out the return type and name.
3283  Out << '\n';
3284 
3285  if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3286 
3287  if (F->isMaterializable())
3288  Out << "; Materializable\n";
3289 
3290  const AttributeList &Attrs = F->getAttributes();
3292  AttributeSet AS = Attrs.getFnAttributes();
3293  std::string AttrStr;
3294 
3295  for (const Attribute &Attr : AS) {
3296  if (!Attr.isStringAttribute()) {
3297  if (!AttrStr.empty()) AttrStr += ' ';
3298  AttrStr += Attr.getAsString();
3299  }
3300  }
3301 
3302  if (!AttrStr.empty())
3303  Out << "; Function Attrs: " << AttrStr << '\n';
3304  }
3305 
3306  Machine.incorporateFunction(F);
3307 
3308  if (F->isDeclaration()) {
3309  Out << "declare";
3311  F->getAllMetadata(MDs);
3312  printMetadataAttachments(MDs, " ");
3313  Out << ' ';
3314  } else
3315  Out << "define ";
3316 
3317  Out << getLinkageNameWithSpace(F->getLinkage());
3318  PrintDSOLocation(*F, Out);
3319  PrintVisibility(F->getVisibility(), Out);
3321 
3322  // Print the calling convention.
3323  if (F->getCallingConv() != CallingConv::C) {
3324  PrintCallingConv(F->getCallingConv(), Out);
3325  Out << " ";
3326  }
3327 
3328  FunctionType *FT = F->getFunctionType();
3330  Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3331  TypePrinter.print(F->getReturnType(), Out);
3332  Out << ' ';
3333  WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3334  Out << '(';
3335 
3336  // Loop over the arguments, printing them...
3337  if (F->isDeclaration() && !IsForDebug) {
3338  // We're only interested in the type here - don't print argument names.
3339  for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3340  // Insert commas as we go... the first arg doesn't get a comma
3341  if (I)
3342  Out << ", ";
3343  // Output type...
3344  TypePrinter.print(FT->getParamType(I), Out);
3345 
3346  AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3347  if (ArgAttrs.hasAttributes())
3348  Out << ' ' << ArgAttrs.getAsString();
3349  }
3350  } else {
3351  // The arguments are meaningful here, print them in detail.
3352  for (const Argument &Arg : F->args()) {
3353  // Insert commas as we go... the first arg doesn't get a comma
3354  if (Arg.getArgNo() != 0)
3355  Out << ", ";
3356  printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3357  }
3358  }
3359 
3360  // Finish printing arguments...
3361  if (FT->isVarArg()) {
3362  if (FT->getNumParams()) Out << ", ";
3363  Out << "..."; // Output varargs portion of signature!
3364  }
3365  Out << ')';
3367  if (!UA.empty())
3368  Out << ' ' << UA;
3370  Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3371  if (F->hasSection()) {
3372  Out << " section \"";
3373  printEscapedString(F->getSection(), Out);
3374  Out << '"';
3375  }
3376  maybePrintComdat(Out, *F);
3377  if (F->getAlignment())
3378  Out << " align " << F->getAlignment();
3379  if (F->hasGC())
3380  Out << " gc \"" << F->getGC() << '"';
3381  if (F->hasPrefixData()) {
3382  Out << " prefix ";
3383  writeOperand(F->getPrefixData(), true);
3384  }
3385  if (F->hasPrologueData()) {
3386  Out << " prologue ";
3387  writeOperand(F->getPrologueData(), true);
3388  }
3389  if (F->hasPersonalityFn()) {
3390  Out << " personality ";
3391  writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3392  }
3393 
3394  if (F->isDeclaration()) {
3395  Out << '\n';
3396  } else {
3398  F->getAllMetadata(MDs);
3399  printMetadataAttachments(MDs, " ");
3400 
3401  Out << " {";
3402  // Output all of the function's basic blocks.
3403  for (const BasicBlock &BB : *F)
3404  printBasicBlock(&BB);
3405 
3406  // Output the function's use-lists.
3407  printUseLists(F);
3408 
3409  Out << "}\n";
3410  }
3411 
3412  Machine.purgeFunction();
3413 }
3414 
3415 /// printArgument - This member is called for every argument that is passed into
3416 /// the function. Simply print it out
3417 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3418  // Output type...
3419  TypePrinter.print(Arg->getType(), Out);
3420 
3421  // Output parameter attributes list
3422  if (Attrs.hasAttributes())
3423  Out << ' ' << Attrs.getAsString();
3424 
3425  // Output name, if available...
3426  if (Arg->hasName()) {
3427  Out << ' ';
3428  PrintLLVMName(Out, Arg);
3429  }
3430 }
3431 
3432 /// printBasicBlock - This member is called for each basic block in a method.
3433 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3434  if (BB->hasName()) { // Print out the label if it exists...
3435  Out << "\n";
3436  PrintLLVMName(Out, BB->getName(), LabelPrefix);
3437  Out << ':';
3438  } else if (!BB->use_empty()) { // Don't print block # of no uses...
3439  Out << "\n; <label>:";
3440  int Slot = Machine.getLocalSlot(BB);
3441  if (Slot != -1)
3442  Out << Slot << ":";
3443  else
3444  Out << "<badref>";
3445  }
3446 
3447  if (!BB->getParent()) {
3448  Out.PadToColumn(50);
3449  Out << "; Error: Block without parent!";
3450  } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
3451  // Output predecessors for the block.
3452  Out.PadToColumn(50);
3453  Out << ";";
3454  const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3455 
3456  if (PI == PE) {
3457  Out << " No predecessors!";
3458  } else {
3459  Out << " preds = ";
3460  writeOperand(*PI, false);
3461  for (++PI; PI != PE; ++PI) {
3462  Out << ", ";
3463  writeOperand(*PI, false);
3464  }
3465  }
3466  }
3467 
3468  Out << "\n";
3469 
3470  if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3471 
3472  // Output all of the instructions in the basic block...
3473  for (const Instruction &I : *BB) {
3474  printInstructionLine(I);
3475  }
3476 
3477  if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3478 }
3479 
3480 /// printInstructionLine - Print an instruction and a newline character.
3481 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3482  printInstruction(I);
3483  Out << '\n';
3484 }
3485 
3486 /// printGCRelocateComment - print comment after call to the gc.relocate
3487 /// intrinsic indicating base and derived pointer names.
3488 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3489  Out << " ; (";
3490  writeOperand(Relocate.getBasePtr(), false);
3491  Out << ", ";
3492  writeOperand(Relocate.getDerivedPtr(), false);
3493  Out << ")";
3494 }
3495 
3496 /// printInfoComment - Print a little comment after the instruction indicating
3497 /// which slot it occupies.
3498 void AssemblyWriter::printInfoComment(const Value &V) {
3499  if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3500  printGCRelocateComment(*Relocate);
3501 
3502  if (AnnotationWriter)
3503  AnnotationWriter->printInfoComment(V, Out);
3504 }
3505 
3506 // This member is called for each Instruction in a function..
3507 void AssemblyWriter::printInstruction(const Instruction &I) {
3508  if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3509 
3510  // Print out indentation for an instruction.
3511  Out << " ";
3512 
3513  // Print out name if it exists...
3514  if (I.hasName()) {
3515  PrintLLVMName(Out, &I);
3516  Out << " = ";
3517  } else if (!I.getType()->isVoidTy()) {
3518  // Print out the def slot taken.
3519  int SlotNum = Machine.getLocalSlot(&I);
3520  if (SlotNum == -1)
3521  Out << "<badref> = ";
3522  else
3523  Out << '%' << SlotNum << " = ";
3524  }
3525 
3526  if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3527  if (CI->isMustTailCall())
3528  Out << "musttail ";
3529  else if (CI->isTailCall())
3530  Out << "tail ";
3531  else if (CI->isNoTailCall())
3532  Out << "notail ";
3533  }
3534 
3535  // Print out the opcode...
3536  Out << I.getOpcodeName();
3537 
3538  // If this is an atomic load or store, print out the atomic marker.
3539  if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
3540  (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3541  Out << " atomic";
3542 
3543  if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3544  Out << " weak";
3545 
3546  // If this is a volatile operation, print out the volatile marker.
3547  if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
3548  (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3549  (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3550  (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3551  Out << " volatile";
3552 
3553  // Print out optimization information.
3554  WriteOptimizationInfo(Out, &I);
3555 
3556  // Print out the compare instruction predicates
3557  if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3558  Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3559 
3560  // Print out the atomicrmw operation
3561  if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3562  writeAtomicRMWOperation(Out, RMWI->getOperation());
3563 
3564  // Print out the type of the operands...
3565  const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3566 
3567  // Special case conditional branches to swizzle the condition out to the front
3568  if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3569  const BranchInst &BI(cast<BranchInst>(I));
3570  Out << ' ';
3571  writeOperand(BI.getCondition(), true);
3572  Out << ", ";
3573  writeOperand(BI.getSuccessor(0), true);
3574  Out << ", ";
3575  writeOperand(BI.getSuccessor(1), true);
3576 
3577  } else if (isa<SwitchInst>(I)) {
3578  const SwitchInst& SI(cast<SwitchInst>(I));
3579  // Special case switch instruction to get formatting nice and correct.
3580  Out << ' ';
3581  writeOperand(SI.getCondition(), true);
3582  Out << ", ";
3583  writeOperand(SI.getDefaultDest(), true);
3584  Out << " [";
3585  for (auto Case : SI.cases()) {
3586  Out << "\n ";
3587  writeOperand(Case.getCaseValue(), true);
3588  Out << ", ";
3589  writeOperand(Case.getCaseSuccessor(), true);
3590  }
3591  Out << "\n ]";
3592  } else if (isa<IndirectBrInst>(I)) {
3593  // Special case indirectbr instruction to get formatting nice and correct.
3594  Out << ' ';
3595  writeOperand(Operand, true);
3596  Out << ", [";
3597 
3598  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3599  if (i != 1)
3600  Out << ", ";
3601  writeOperand(I.getOperand(i), true);
3602  }
3603  Out << ']';
3604  } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3605  Out << ' ';
3606  TypePrinter.print(I.getType(), Out);
3607  Out << ' ';
3608 
3609  for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3610  if (op) Out << ", ";
3611  Out << "[ ";
3612  writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3613  writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3614  }
3615  } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3616  Out << ' ';
3617  writeOperand(I.getOperand(0), true);
3618  for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3619  Out << ", " << *i;
3620  } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3621  Out << ' ';
3622  writeOperand(I.getOperand(0), true); Out << ", ";
3623  writeOperand(I.getOperand(1), true);
3624  for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3625  Out << ", " << *i;
3626  } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3627  Out << ' ';
3628  TypePrinter.print(I.getType(), Out);
3629  if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3630  Out << '\n';
3631 
3632  if (LPI->isCleanup())
3633  Out << " cleanup";
3634 
3635  for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3636  if (i != 0 || LPI->isCleanup()) Out << "\n";
3637  if (LPI->isCatch(i))
3638  Out << " catch ";
3639  else
3640  Out << " filter ";
3641 
3642  writeOperand(LPI->getClause(i), true);
3643  }
3644  } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3645  Out << " within ";
3646  writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3647  Out << " [";
3648  unsigned Op = 0;
3649  for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3650  if (Op > 0)
3651  Out << ", ";
3652  writeOperand(PadBB, /*PrintType=*/true);
3653  ++Op;
3654  }
3655  Out << "] unwind ";
3656  if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3657  writeOperand(UnwindDest, /*PrintType=*/true);
3658  else
3659  Out << "to caller";
3660  } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3661  Out << " within ";
3662  writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3663  Out << " [";
3664  for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3665  ++Op) {
3666  if (Op > 0)
3667  Out << ", ";
3668  writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3669  }
3670  Out << ']';
3671  } else if (isa<ReturnInst>(I) && !Operand) {
3672  Out << " void";
3673  } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3674  Out << " from ";
3675  writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3676 
3677  Out << " to ";
3678  writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3679  } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3680  Out << " from ";
3681  writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3682 
3683  Out << " unwind ";
3684  if (CRI->hasUnwindDest())
3685  writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3686  else
3687  Out << "to caller";
3688  } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3689  // Print the calling convention being used.
3690  if (CI->getCallingConv() != CallingConv::C) {
3691  Out << " ";
3692  PrintCallingConv(CI->getCallingConv(), Out);
3693  }
3694 
3695  Operand = CI->getCalledValue();
3696  FunctionType *FTy = CI->getFunctionType();
3697  Type *RetTy = FTy->getReturnType();
3698  const AttributeList &PAL = CI->getAttributes();
3699 
3701  Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3702 
3703  // If possible, print out the short form of the call instruction. We can
3704  // only do this if the first argument is a pointer to a nonvararg function,
3705  // and if the return type is not a pointer to a function.
3706  //
3707  Out << ' ';
3708  TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3709  Out << ' ';
3710  writeOperand(Operand, false);
3711  Out << '(';
3712  for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3713  if (op > 0)
3714  Out << ", ";
3715  writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3716  }
3717 
3718  // Emit an ellipsis if this is a musttail call in a vararg function. This
3719  // is only to aid readability, musttail calls forward varargs by default.
3720  if (CI->isMustTailCall() && CI->getParent() &&
3721  CI->getParent()->getParent() &&
3722  CI->getParent()->getParent()->isVarArg())
3723  Out << ", ...";
3724 
3725  Out << ')';
3727  Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3728 
3729  writeOperandBundles(CI);
3730  } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3731  Operand = II->getCalledValue();
3732  FunctionType *FTy = II->getFunctionType();
3733  Type *RetTy = FTy->getReturnType();
3734  const AttributeList &PAL = II->getAttributes();
3735 
3736  // Print the calling convention being used.
3737  if (II->getCallingConv() != CallingConv::C) {
3738  Out << " ";
3739  PrintCallingConv(II->getCallingConv(), Out);
3740  }
3741 
3743  Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3744 
3745  // If possible, print out the short form of the invoke instruction. We can
3746  // only do this if the first argument is a pointer to a nonvararg function,
3747  // and if the return type is not a pointer to a function.
3748  //
3749  Out << ' ';
3750  TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3751  Out << ' ';
3752  writeOperand(Operand, false);
3753  Out << '(';
3754  for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3755  if (op)
3756  Out << ", ";
3757  writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3758  }
3759 
3760  Out << ')';
3762  Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3763 
3764  writeOperandBundles(II);
3765 
3766  Out << "\n to ";
3767  writeOperand(II->getNormalDest(), true);
3768  Out << " unwind ";
3769  writeOperand(II->getUnwindDest(), true);
3770  } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3771  Out << ' ';
3772  if (AI->isUsedWithInAlloca())
3773  Out << "inalloca ";
3774  if (AI->isSwiftError())
3775  Out << "swifterror ";
3776  TypePrinter.print(AI->getAllocatedType(), Out);
3777 
3778  // Explicitly write the array size if the code is broken, if it's an array
3779  // allocation, or if the type is not canonical for scalar allocations. The
3780  // latter case prevents the type from mutating when round-tripping through
3781  // assembly.
3782  if (!AI->getArraySize() || AI->isArrayAllocation() ||
3783  !AI->getArraySize()->getType()->isIntegerTy(32)) {
3784  Out << ", ";
3785  writeOperand(AI->getArraySize(), true);
3786  }
3787  if (AI->getAlignment()) {
3788  Out << ", align " << AI->getAlignment();
3789  }
3790 
3791  unsigned AddrSpace = AI->getType()->getAddressSpace();
3792  if (AddrSpace != 0) {
3793  Out << ", addrspace(" << AddrSpace << ')';
3794  }
3795  } else if (isa<CastInst>(I)) {
3796  if (Operand) {
3797  Out << ' ';
3798  writeOperand(Operand, true); // Work with broken code
3799  }
3800  Out << " to ";
3801  TypePrinter.print(I.getType(), Out);
3802  } else if (isa<VAArgInst>(I)) {
3803  if (Operand) {
3804  Out << ' ';
3805  writeOperand(Operand, true); // Work with broken code
3806  }
3807  Out << ", ";
3808  TypePrinter.print(I.getType(), Out);
3809  } else if (Operand) { // Print the normal way.
3810  if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3811  Out << ' ';
3812  TypePrinter.print(GEP->getSourceElementType(), Out);
3813  Out << ',';
3814  } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3815  Out << ' ';
3816  TypePrinter.print(LI->getType(), Out);
3817  Out << ',';
3818  }
3819 
3820  // PrintAllTypes - Instructions who have operands of all the same type
3821  // omit the type from all but the first operand. If the instruction has
3822  // different type operands (for example br), then they are all printed.
3823  bool PrintAllTypes = false;
3824  Type *TheType = Operand->getType();
3825 
3826  // Select, Store and ShuffleVector always print all types.
3827  if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3828  || isa<ReturnInst>(I)) {
3829  PrintAllTypes = true;
3830  } else {
3831  for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3832  Operand = I.getOperand(i);
3833  // note that Operand shouldn't be null, but the test helps make dump()
3834  // more tolerant of malformed IR
3835  if (Operand && Operand->getType() != TheType) {
3836  PrintAllTypes = true; // We have differing types! Print them all!
3837  break;
3838  }
3839  }
3840  }
3841 
3842  if (!PrintAllTypes) {
3843  Out << ' ';
3844  TypePrinter.print(TheType, Out);
3845  }
3846 
3847  Out << ' ';
3848  for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3849  if (i) Out << ", ";
3850  writeOperand(I.getOperand(i), PrintAllTypes);
3851  }
3852  }
3853 
3854  // Print atomic ordering/alignment for memory operations
3855  if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3856  if (LI->isAtomic())
3857  writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
3858  if (LI->getAlignment())
3859  Out << ", align " << LI->getAlignment();
3860  } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3861  if (SI->isAtomic())
3862  writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
3863  if (SI->getAlignment())
3864  Out << ", align " << SI->getAlignment();
3865  } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3866  writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3867  CXI->getFailureOrdering(), CXI->getSyncScopeID());
3868  } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3869  writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3870  RMWI->getSyncScopeID());
3871  } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3872  writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
3873  }
3874 
3875  // Print Metadata info.
3877  I.getAllMetadata(InstMD);
3878  printMetadataAttachments(InstMD, ", ");
3879 
3880  // Print a nice comment.
3881  printInfoComment(I);
3882 }
3883 
3884 void AssemblyWriter::printMetadataAttachments(
3885  const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3886  StringRef Separator) {
3887  if (MDs.empty())
3888  return;
3889 
3890  if (MDNames.empty())
3891  MDs[0].second->getContext().getMDKindNames(MDNames);
3892 
3893  for (const auto &I : MDs) {
3894  unsigned Kind = I.first;
3895  Out << Separator;
3896  if (Kind < MDNames.size()) {
3897  Out << "!";
3898  printMetadataIdentifier(MDNames[Kind], Out);
3899  } else
3900  Out << "!<unknown kind #" << Kind << ">";
3901  Out << ' ';
3902  WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3903  }
3904 }
3905 
3906 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3907  Out << '!' << Slot << " = ";
3908  printMDNodeBody(Node);
3909  Out << "\n";
3910 }
3911 
3912 void AssemblyWriter::writeAllMDNodes() {
3914  Nodes.resize(Machine.mdn_size());
3915  for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3916  I != E; ++I)
3917  Nodes[I->second] = cast<MDNode>(I->first);
3918 
3919  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3920  writeMDNode(i, Nodes[i]);
3921  }
3922 }
3923 
3924 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3925  WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3926 }
3927 
3928 void AssemblyWriter::writeAllAttributeGroups() {
3929  std::vector<std::pair<AttributeSet, unsigned>> asVec;
3930  asVec.resize(Machine.as_size());
3931 
3932  for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3933  I != E; ++I)
3934  asVec[I->second] = *I;
3935 
3936  for (const auto &I : asVec)
3937  Out << "attributes #" << I.second << " = { "
3938  << I.first.getAsString(true) << " }\n";
3939 }
3940 
3941 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3942  bool IsInFunction = Machine.getFunction();
3943  if (IsInFunction)
3944  Out << " ";
3945 
3946  Out << "uselistorder";
3947  if (const BasicBlock *BB =
3948  IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3949  Out << "_bb ";
3950  writeOperand(BB->getParent(), false);
3951  Out << ", ";
3952  writeOperand(BB, false);
3953  } else {
3954  Out << " ";
3955  writeOperand(Order.V, true);
3956  }
3957  Out << ", { ";
3958 
3959  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3960  Out << Order.Shuffle[0];
3961  for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3962  Out << ", " << Order.Shuffle[I];
3963  Out << " }\n";
3964 }
3965 
3966 void AssemblyWriter::printUseLists(const Function *F) {
3967  auto hasMore =
3968  [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3969  if (!hasMore())
3970  // Nothing to do.
3971  return;
3972 
3973  Out << "\n; uselistorder directives\n";
3974  while (hasMore()) {
3975  printUseListOrder(UseListOrders.back());
3976  UseListOrders.pop_back();
3977  }
3978 }
3979 
3980 //===----------------------------------------------------------------------===//
3981 // External Interface declarations
3982 //===----------------------------------------------------------------------===//
3983 
3985  bool ShouldPreserveUseListOrder,
3986  bool IsForDebug) const {
3987  SlotTracker SlotTable(this->getParent());
3988  formatted_raw_ostream OS(ROS);
3989  AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
3990  IsForDebug,
3991  ShouldPreserveUseListOrder);
3992  W.printFunction(this);
3993 }
3994 
3996  bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3997  SlotTracker SlotTable(this);
3998  formatted_raw_ostream OS(ROS);
3999  AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4000  ShouldPreserveUseListOrder);
4001  W.printModule(this);
4002 }
4003 
4004 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4005  SlotTracker SlotTable(getParent());
4006  formatted_raw_ostream OS(ROS);
4007  AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4008  W.printNamedMDNode(this);
4009 }
4010 
4012  bool IsForDebug) const {
4013  Optional<SlotTracker> LocalST;
4014  SlotTracker *SlotTable;
4015  if (auto *ST = MST.getMachine())
4016  SlotTable = ST;
4017  else {
4018  LocalST.emplace(getParent());
4019  SlotTable = &*LocalST;
4020  }
4021 
4022  formatted_raw_ostream OS(ROS);
4023  AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4024  W.printNamedMDNode(this);
4025 }
4026 
4027 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4029  ROS << " = comdat ";
4030 
4031  switch (getSelectionKind()) {
4032  case Comdat::Any:
4033  ROS << "any";
4034  break;
4035  case Comdat::ExactMatch:
4036  ROS << "exactmatch";
4037  break;
4038  case Comdat::Largest:
4039  ROS << "largest";
4040  break;
4041  case Comdat::NoDuplicates:
4042  ROS << "noduplicates";
4043  break;
4044  case Comdat::SameSize:
4045  ROS << "samesize";
4046  break;
4047  }
4048 
4049  ROS << '\n';
4050 }
4051 
4052 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4053  TypePrinting TP;
4054  TP.print(const_cast<Type*>(this), OS);
4055 
4056  if (NoDetails)
4057  return;
4058 
4059  // If the type is a named struct type, print the body as well.
4060  if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4061  if (!STy->isLiteral()) {
4062  OS << " = type ";
4063  TP.printStructBody(STy, OS);
4064  }
4065 }
4066 
4067 static bool isReferencingMDNode(const Instruction &I) {
4068  if (const auto *CI = dyn_cast<CallInst>(&I))
4069  if (Function *F = CI->getCalledFunction())
4070  if (F->isIntrinsic())
4071  for (auto &Op : I.operands())
4072  if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4073  if (isa<MDNode>(V->getMetadata()))
4074  return true;
4075  return false;
4076 }
4077 
4078 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4079  bool ShouldInitializeAllMetadata = false;
4080  if (auto *I = dyn_cast<Instruction>(this))
4081  ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4082  else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4083  ShouldInitializeAllMetadata = true;
4084 
4085  ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4086  print(ROS, MST, IsForDebug);
4087 }
4088 
4090  bool IsForDebug) const {
4091  formatted_raw_ostream OS(ROS);
4092  SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4093  SlotTracker &SlotTable =
4094  MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4095  auto incorporateFunction = [&](const Function *F) {
4096  if (F)
4097  MST.incorporateFunction(*F);
4098  };
4099 
4100  if (const Instruction *I = dyn_cast<Instruction>(this)) {
4101  incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4102  AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4103  W.printInstruction(*I);
4104  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4105  incorporateFunction(BB->getParent());
4106  AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4107  W.printBasicBlock(BB);
4108  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4109  AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4110  if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4111  W.printGlobal(V);
4112  else if (const Function *F = dyn_cast<Function>(GV))
4113  W.printFunction(F);
4114  else
4115  W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4116  } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4117  V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4118  } else if (const Constant *C = dyn_cast<Constant>(this)) {
4119  TypePrinting TypePrinter;
4120  TypePrinter.print(C->getType(), OS);
4121  OS << ' ';
4122  WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4123  } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4124  this->printAsOperand(OS, /* PrintType */ true, MST);
4125  } else {
4126  llvm_unreachable("Unknown value to print out!");
4127  }
4128 }
4129 
4130 /// Print without a type, skipping the TypePrinting object.
4131 ///
4132 /// \return \c true iff printing was successful.
4133 static bool printWithoutType(const Value &V, raw_ostream &O,
4134  SlotTracker *Machine, const Module *M) {
4135  if (V.hasName() || isa<GlobalValue>(V) ||
4136  (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4137  WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4138  return true;
4139  }
4140  return false;
4141 }
4142 
4143 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4144  ModuleSlotTracker &MST) {
4145  TypePrinting TypePrinter(MST.getModule());
4146  if (PrintType) {
4147  TypePrinter.print(V.getType(), O);
4148  O << ' ';
4149  }
4150 
4151  WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4152  MST.getModule());
4153 }
4154 
4155 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4156  const Module *M) const {
4157  if (!M)
4158  M = getModuleFromVal(this);
4159 
4160  if (!PrintType)
4161  if (printWithoutType(*this, O, nullptr, M))
4162  return;
4163 
4165  M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4166  ModuleSlotTracker MST(Machine, M);
4167  printAsOperandImpl(*this, O, PrintType, MST);
4168 }
4169 
4170 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4171  ModuleSlotTracker &MST) const {
4172  if (!PrintType)
4173  if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4174  return;
4175 
4176  printAsOperandImpl(*this, O, PrintType, MST);
4177 }
4178 
4179 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4180  ModuleSlotTracker &MST, const Module *M,
4181  bool OnlyAsOperand) {
4182  formatted_raw_ostream OS(ROS);
4183 
4184  TypePrinting TypePrinter(M);
4185 
4186  WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4187  /* FromValue */ true);
4188 
4189  auto *N = dyn_cast<MDNode>(&MD);
4190  if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4191  return;
4192 
4193  OS << " = ";
4194  WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4195 }
4196 
4197 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4198  ModuleSlotTracker MST(M, isa<MDNode>(this));
4199  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4200 }
4201 
4203  const Module *M) const {
4204  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4205 }
4206 
4208  bool /*IsForDebug*/) const {
4209  ModuleSlotTracker MST(M, isa<MDNode>(this));
4210  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4211 }
4212 
4214  const Module *M, bool /*IsForDebug*/) const {
4215  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4216 }
4217 
4218 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4219  SlotTracker SlotTable(this);
4220  formatted_raw_ostream OS(ROS);
4221  AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4222  W.printModuleSummaryIndex();
4223 }
4224 
4225 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4226 // Value::dump - allow easy printing of Values from the debugger.
4228 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4229 
4230 // Type::dump - allow easy printing of Types from the debugger.
4232 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4233 
4234 // Module::dump() - Allow printing of Modules from the debugger.
4236 void Module::dump() const {
4237  print(dbgs(), nullptr,
4238  /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4239 }
4240 
4241 // Allow printing of Comdats from the debugger.
4243 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4244 
4245 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4247 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4248 
4250 void Metadata::dump() const { dump(nullptr); }
4251 
4253 void Metadata::dump(const Module *M) const {
4254  print(dbgs(), M, /*IsForDebug=*/true);
4255  dbgs() << '\n';
4256 }
4257 
4258 // Allow printing of ModuleSummaryIndex from the debugger.
4260 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4261 #endif
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Type * getVectorElementType() const
Definition: Type.h:371
AttributeSet getAttributes() const
Return the attribute set for this global.
uint64_t CallInst * C
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:126
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:90
static SlotTracker * createSlotTracker(const Value *V)
Definition: AsmWriter.cpp:854
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:185
unsigned getAlignment() const
Definition: GlobalObject.h:59
use_iterator use_end()
Definition: Value.h:347
7: Labels
Definition: Type.h:64
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:238
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:254
static void WriteOptimizationInfo(raw_ostream &Out, const User *U)
Definition: AsmWriter.cpp:1237
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:875
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
iterator_range< use_iterator > uses()
Definition: Value.h:355
static std::string getLinkageName(GlobalValue::LinkageTypes LT)
Definition: AsmWriter.cpp:2816
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
This instruction extracts a struct member or array element value from an aggregate value...
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:55
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1557
*p = old <signed v ? old : v
Definition: Instructions.h:711
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
void purgeFunction()
After calling incorporateFunction, use this method to remove the most recently incorporated function ...
Definition: AsmWriter.cpp:1069
LLVMContext & Context
static bool printWithoutType(const Value &V, raw_ostream &O, SlotTracker *Machine, const Module *M)
Print without a type, skipping the TypePrinting object.
Definition: AsmWriter.cpp:4133
Atomic ordering constants.
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1081
DenseMap< GlobalValue::GUID, unsigned >::iterator guid_iterator
GUID map iterators.
Definition: AsmWriter.cpp:770
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:492
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
unsigned Linkage
The linkage type of the associated global value.
const GlobalValueSummary & getAliasee() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
2: 32-bit floating point type
Definition: Type.h:59
An instruction for ordering other memory operations.
Definition: Instructions.h:444
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA)
Definition: AsmWriter.cpp:3127
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:518
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:186
Global variable summary information to aid decisions and implementation of importing.
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
Unsatisfiable type (i.e. no global has this type metadata)
bool isMaterializable() const
If this function&#39;s Module is being lazily streamed in functions from disk or some other source...
Definition: Globals.cpp:45
Available for inspection, not emission.
Definition: GlobalValue.h:50
static void writeAtomicRMWOperation(raw_ostream &Out, AtomicRMWInst::BinOp Op)
Definition: AsmWriter.cpp:1219
PrefixType
Definition: AsmWriter.cpp:390
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
This class represents a function call, abstracting a target machine&#39;s calling convention.
SPIR_KERNEL - Calling convention for SPIR kernel functions.
Definition: CallingConv.h:137
This file contains the declarations for metadata subclasses.
void emplace(ArgTypes &&... Args)
Create a new object by constructing it in place with the given arguments.
Definition: Optional.h:153
Value * getCondition() const
*p = old <unsigned v ? old : v
Definition: Instructions.h:715
float convertToFloat() const
Definition: APFloat.h:1098
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:201
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3098
bool global_empty() const
Definition: Module.h:571
*p = old >unsigned v ? old : v
Definition: Instructions.h:713
Externally visible function.
Definition: GlobalValue.h:49
void printEscapedString(StringRef Name, raw_ostream &Out)
Print each character of the specified string, escaping it if it is not printable or if it is an escap...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do not have all constant integer arguments.
bool hasPrologueData() const
Check whether this function has prologue data.
Definition: Function.h:706
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:39
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:229
unsigned second
BasicBlock * getSuccessor(unsigned i) const
13: Structures
Definition: Type.h:73
Metadata node.
Definition: Metadata.h:862
int getGlobalSlot(const GlobalValue *V)
getGlobalSlot - Get the slot number of a global value.
Definition: AsmWriter.cpp:1078
F(f)
4: 80-bit floating point type (X87)
Definition: Type.h:61
const fltSemantics & getSemantics() const
Definition: APFloat.h:1155
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
param_iterator param_end() const
Definition: DerivedTypes.h:129
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:452
An instruction for reading from memory.
Definition: Instructions.h:168
Manage lifetime of a slot tracker for printing IR.
1: 16-bit floating point type
Definition: Type.h:58
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:436
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:681
Hexagon Common GEP
Value * getCondition() const
Kind
Specifies which kind of type check we should emit for this byte array.
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:59
#define op(i)
15: Pointers
Definition: Type.h:75
This defines the Use class.
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1417
Calling convention used for AMDPAL shader stage before geometry shader if geometry is in use...
Definition: CallingConv.h:221
12: Functions
Definition: Type.h:72
*p = old >signed v ? old : v
Definition: Instructions.h:709
int getMetadataSlot(const MDNode *N)
getMetadataSlot - Get the slot number of a MDNode.
Definition: AsmWriter.cpp:1088
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair...
static void PrintCallingConv(unsigned cc, raw_ostream &Out)
Definition: AsmWriter.cpp:346
Tentative definitions.
Definition: GlobalValue.h:59
void dump() const
Dump to stderr (for debugging).
Definition: AsmWriter.cpp:4260
static void PrintDSOLocation(const GlobalValue &GV, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3088
SPIR_FUNC - Calling convention for SPIR non-kernel device functions.
Definition: CallingConv.h:129
Constant * getPrologueData() const
Get the prologue data associated with this function.
Definition: Function.cpp:1308
TypeTestResolution TTRes
SlotTracker * getMachine()
Lazily creates a slot tracker.
Definition: AsmWriter.cpp:824
static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack)
Definition: AsmWriter.cpp:246
const TypeIdInfo * getTypeIdInfo() const
ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:103
void print(raw_ostream &OS, bool IsForDebug=false) const
Print to an output stream.
Definition: AsmWriter.cpp:4218
static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT)
Definition: AsmWriter.cpp:2847
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4228
The address of a basic block.
Definition: Constants.h:836
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
GlobalValue::GUID getGUID() const
A tuple of MDNodes.
Definition: Metadata.h:1323
bool hasPrefixData() const
Check whether this function has prefix data.
Definition: Function.h:697
APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition: APInt.cpp:515
std::vector< unsigned > Shuffle
Definition: UseListOrder.h:30
static OrderMap orderModule(const Module *M)
Definition: AsmWriter.cpp:136
static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, ModuleSlotTracker &MST, const Module *M, bool OnlyAsOperand)
Definition: AsmWriter.cpp:4179
const Value * V
Definition: UseListOrder.h:28
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:138
bool isDSOLocal() const
Definition: GlobalValue.h:279
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module...
Class to represent struct types.
Definition: DerivedTypes.h:201
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Value * getDerivedPtr() const
Definition: Statepoint.h:402
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
const Module * getModule() const
UnnamedAddr getUnnamedAddr() const
Definition: GlobalValue.h:212
The access may reference the value stored in memory.
static StringRef getName(Value *V)
This file contains the simple types necessary to represent the attributes associated with functions a...
Just do a regular virtual call.
The linker may choose any COMDAT.
Definition: Comdat.h:35
unsigned getNumOperands() const
Definition: Metadata.cpp:1077
bool hasAttributes(unsigned Index) const
Return true if attribute exists at the given index.
APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition: APInt.cpp:510
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
static void printMetadataIdentifier(StringRef Name, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3033
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
This file implements a class to represent arbitrary precision integral constant values and operations...
Constant * getPrefixData() const
Get the prefix data associated with this function.
Definition: Function.cpp:1298
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
void dump() const
Definition: AsmWriter.cpp:4243
bool hasExternalLinkage() const
Definition: GlobalValue.h:421
Class to represent function types.
Definition: DerivedTypes.h:103
MSP430_INTR - Calling convention used for MSP430 interrupt routines.
Definition: CallingConv.h:106
bool isInfinity() const
Definition: APFloat.h:1144
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
reverse_iterator rend()
Definition: Module.h:590
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4444
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:158
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition: APFloat.h:1167
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:693
ARM_AAPCS - ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:100
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the function to an output stream with an optional AssemblyAnnotationWriter. ...
Definition: AsmWriter.cpp:3984
Class to represent array types.
Definition: DerivedTypes.h:369
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:63
int getModulePathSlot(StringRef Path)
Definition: AsmWriter.cpp:1117
bool isVarArg() const
Definition: DerivedTypes.h:123
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:208
const std::string & getGC() const
Definition: Function.cpp:452
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:210
An instruction for storing to memory.
Definition: Instructions.h:310
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:688
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:363
LinkageTypes getLinkage() const
Definition: GlobalValue.h:450
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:123
char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16)...
Definition: StringExtras.h:37
static void PrintVisibility(GlobalValue::VisibilityTypes Vis, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3079
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Structure to hold a use-list order.
Definition: UseListOrder.h:27
Calling convention used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:195
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:144
Value * getOperand(unsigned i) const
Definition: User.h:170
int getLocalSlot(const Value *V)
Return the slot number of the specified value in it&#39;s type plane.
Definition: AsmWriter.cpp:1098
Class to represent pointers.
Definition: DerivedTypes.h:467
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:219
X86_FastCall - &#39;fast&#39; analog of X86_StdCall.
Definition: CallingConv.h:92
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:338
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
11: Arbitrary bit width integers
Definition: Type.h:71
bool alias_empty() const
Definition: Module.h:611
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
ExternalWeak linkage description.
Definition: GlobalValue.h:58
const BasicBlock & getEntryBlock() const
Definition: Function.h:626
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:666
0: type with no size
Definition: Type.h:57
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:155
unsigned getNumOperands() const
No other Module may specify this COMDAT.
Definition: Comdat.h:38
StringRef getName() const
Definition: Comdat.cpp:27
const char * toIRString(AtomicOrdering ao)
String used by LLVM IR to represent atomic ordering.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Calling convention used for AVR signal routines.
Definition: CallingConv.h:180
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void print(raw_ostream &OS, bool IsForDebug=false) const
Definition: AsmWriter.cpp:4027
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:258
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:232
Calling convention used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:216
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:686
static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack)
Definition: AsmWriter.cpp:183
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Conditional or Unconditional Branch instruction.
const char * getOpcodeName() const
Definition: Instruction.h:128
bool isNaN() const
Definition: APFloat.h:1145
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:87
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
SummaryKind getSummaryKind() const
Which kind of summary subclass this is.
ArrayRef< Use > Inputs
Definition: InstrTypes.h:1223
void dump() const
Dump the module to stderr (for debugging).
Definition: AsmWriter.cpp:4236
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
static StringRef getPredicateName(Predicate P)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
unsigned instCount() const
Get the instruction count recorded for this function.
10: Tokens
Definition: Type.h:67
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
void print(raw_ostream &ROS, bool IsForDebug=false) const
Definition: AsmWriter.cpp:4004
std::vector< UseListOrder > UseListOrderStack
Definition: UseListOrder.h:40
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
double convertToDouble() const
Definition: APFloat.h:1097
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
BasicBlock * getDefaultDest() const
Calling convention used by HipHop Virtual Machine (HHVM) to perform calls to and from translation cac...
Definition: CallingConv.h:164
A udiv or sdiv instruction, which can be marked as "exact", indicating that no bits are destroyed...
Definition: Operator.h:120
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:2169
param_iterator param_begin() const
Definition: DerivedTypes.h:128
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool hasOperandBundles() const
Definition: CallSite.h:535
Single element (last example in "Short Inline Bit Vectors")
StringRef name() const
static const char * getHotnessName(CalleeInfo::HotnessType HT)
Definition: AsmWriter.cpp:2853
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
Definition: Operator.h:67
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:4078
StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:487
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:70
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:63
static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, ModuleSlotTracker &MST)
Definition: AsmWriter.cpp:4143
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
op_range operands()
Definition: User.h:238
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:129
bool isMaterializable() const
Definition: Function.h:165
static const Module * getModuleFromVal(const Value *V)
Definition: AsmWriter.cpp:320
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:36
Used for AVR interrupt routines.
Definition: CallingConv.h:177
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:172
All type identifier related information.
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:60
std::string getAsString(unsigned Index, bool InAttrGrp=false) const
Return the attributes at the index as a string.
Function and variable summary information to aid decisions and implementation of importing.
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:835
const AMDGPUAS & AS
static bool isAtomic(Instruction *I)
size_t size() const
Definition: SmallVector.h:53
static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3107
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4155
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned first
An "identifier" for a virtual function.
void dump() const
Definition: AsmWriter.cpp:4232
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:969
Struct that holds a reference to a particular GUID in a global value summary.
static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix)
Turn the specified name into an &#39;LLVM name&#39;, which is either prefixed with % (if the string only cont...
Definition: AsmWriter.cpp:434
reverse_iterator rbegin()
Definition: Module.h:588
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:3995
X86_ThisCall - Similar to X86_StdCall.
Definition: CallingConv.h:111
14: Arrays
Definition: Type.h:74
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
PTX_Device - Call to a PTX device function.
Definition: CallingConv.h:119
void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
Definition: AsmWriter.cpp:4207
std::vector< VFuncId > TypeCheckedLoadVCalls
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:120
unsigned getNumOperands() const
Definition: User.h:192
std::string getAsString(bool InAttrGrp=false) const
Definition: Attributes.cpp:613
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1142
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:117
OperandBundleUse getOperandBundleAt(unsigned Index) const
Definition: CallSite.h:551
16: SIMD &#39;packed&#39; format, or other vector type
Definition: Type.h:76
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:199
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:82
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition: Operator.h:240
Module.h This file contains the declarations for the Module class.
static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, TypePrinting &TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:1276
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:727
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:126
AddressSpace
Definition: NVPTXBaseInfo.h:22
Single implementation devirtualization.
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
Type * getReturnType() const
Definition: DerivedTypes.h:124
void printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name)
Print out a name of an LLVM value without any prefixes.
Definition: AsmWriter.cpp:398
Alias summary information.
The linker will choose the largest COMDAT.
Definition: Comdat.h:37
static bool isReferencingMDNode(const Instruction &I)
Definition: AsmWriter.cpp:4067
DWARF expression.
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Get all metadata attached to this Instruction.
Definition: Instruction.h:216
enum llvm::TypeTestResolution::Kind TheKind
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
8: Metadata
Definition: Type.h:65
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:150
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition...
Definition: DerivedTypes.h:265
Class to represent vector types.
Definition: DerivedTypes.h:393
This file contains constants used for implementing Dwarf debug support.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:410
Class for arbitrary precision integers.
Definition: APInt.h:70
static bool isWeak(const MCSymbolELF &Sym)
Register calling convention used for parameters transfer optimization.
Definition: CallingConv.h:204
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
StringRef getName() const
Definition: Metadata.cpp:1098
A lightweight accessor for an operand bundle meant to be passed around by value.
Definition: InstrTypes.h:1222
iterator_range< user_iterator > users()
Definition: Value.h:400
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:500
SummaryKind
Sububclass discriminator (for dyn_cast<> et al.)
static const char * getWholeProgDevirtResByArgKindName(WholeProgramDevirtResolution::ByArg::Kind K)
Definition: AsmWriter.cpp:2678
amdgpu Simplify well known AMD library false Value Value * Arg
void initializeIndexIfNeeded()
Definition: AsmWriter.cpp:910
FFlags fflags() const
Get function attribute flags.
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
Definition: CallingConv.h:189
const Comdat * getComdat() const
Definition: GlobalObject.h:101
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:135
use_iterator use_begin()
Definition: Value.h:339
#define ST_DEBUG(X)
Definition: AsmWriter.cpp:883
Test a byte array (first example)
Function to be accessible from DLL.
Definition: GlobalValue.h:73
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition: Function.h:335
unsigned getNumOperandBundles() const
Definition: CallSite.h:531
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument, "this"), where the key is the argument vector.
static const char * getTTResKindName(TypeTestResolution::Kind K)
Definition: AsmWriter.cpp:2693
bool ifunc_empty() const
Definition: Module.h:629
StringRef modulePath() const
Get the path to the module containing this function.
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4052
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:2085
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit...
static void orderValue(const Value *V, OrderMap &OM)
Definition: AsmWriter.cpp:121
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
Establish a view to a call site for examination.
Definition: CallSite.h:714
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:199
const NodeList & List
Definition: RDFGraph.cpp:210
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
void dump() const
User-friendly dump.
Definition: AsmWriter.cpp:4250
StringRef getTagName() const
Return the tag of this operand bundle as a string.
Definition: InstrTypes.h:1241
static void maybePrintComdat(formatted_raw_ostream &Out, const GlobalObject &GO)
Definition: AsmWriter.cpp:3139
static const char * getSummaryKindName(GlobalValueSummary::SummaryKind SK)
Definition: AsmWriter.cpp:2789
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
Type * getValueType() const
Definition: GlobalValue.h:275
int getGUIDSlot(GlobalValue::GUID GUID)
Definition: AsmWriter.cpp:1126
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, TypePrinting *TypePrinter, SlotTracker *Machine, const Module *Context)
Definition: AsmWriter.cpp:2147
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
const Constant * getIndirectSymbol() const
Function attribute flags.
iterator_range< ifunc_iterator > ifuncs()
Definition: Module.h:631
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
Function summary information to aid decisions and implementation of importing.
Function to be imported from DLL.
Definition: GlobalValue.h:72
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:181
PTX_Kernel - Call to a PTX kernel.
Definition: CallingConv.h:115
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:246
This file defines passes to print out IR in various granularities.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
const unsigned Kind
3: 64-bit floating point type
Definition: Type.h:60
Multiway switch.
void printAsOperand(raw_ostream &OS, const Module *M=nullptr) const
Print as operand.
Definition: AsmWriter.cpp:4197
Calling convention used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:192
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete, but still used on some target...
Definition: CallingConv.h:96
Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins.
Definition: CallingConv.h:140
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:261
Represents calls to the gc.relocate intrinsic.
Definition: Statepoint.h:374
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1288
A vector that has set insertion semantics.
Definition: SetVector.h:41
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
X86_INTR - x86 hardware interrupt context.
Definition: CallingConv.h:174
static const Function * getParent(const Value *V)
AttributeSet getFnAttributes() const
The function attributes are returned.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
Invoke instruction.
bool hasDefaultVisibility() const
Definition: GlobalValue.h:233
Type * getElementType() const
Definition: DerivedTypes.h:360
iterator_range< global_iterator > globals()
Definition: Module.h:573
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
The C convention as implemented on Windows/x86-64 and AArch64.
Definition: CallingConv.h:154
void dump() const
Definition: AsmWriter.cpp:4247
APInt bitcastToAPInt() const
Definition: APFloat.h:1094
Value * getBasePtr() const
Definition: Statepoint.h:397
static bool isVolatile(Instruction *Inst)
9: MMX vectors (64 bits, X86 specific)
Definition: Type.h:66
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
static const char * getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)
Definition: AsmWriter.cpp:2666
TypeFinder - Walk over a module, identifying all of the types that are used by the module...
Definition: TypeFinder.h:31
Root of the metadata hierarchy.
Definition: Metadata.h:58
Calling convention used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:198
bool isExternallyInitialized() const
static UseListOrderStack predictUseListOrder(const Module *M)
Definition: AsmWriter.cpp:267
bool use_empty() const
Definition: Value.h:323
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
Definition: DerivedTypes.h:486
TLM
Definition: LLParser.cpp:1491
int getAttributeGroupSlot(AttributeSet AS)
Definition: AsmWriter.cpp:1108
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
HHVM calling convention for invoking C/C++ helpers.
Definition: CallingConv.h:167
iterator_range< arg_iterator > args()
Definition: Function.h:675
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
const BasicBlock * getParent() const
Definition: Instruction.h:67
an instruction to allocate memory on the stack
Definition: Instructions.h:60
This instruction inserts a struct field of array element value into an aggregate value.
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:62
iterator_range< alias_iterator > aliases()
Definition: Module.h:613
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with all constant integer arguments.
void resize(size_type N)
Definition: SmallVector.h:351