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