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