LLVM  3.7.0
MCAsmStreamer.cpp
Go to the documentation of this file.
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
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 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCSymbolELF.h"
30 #include "llvm/Support/Format.h"
33 #include "llvm/Support/Path.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 namespace {
38 
39 class MCAsmStreamer final : public MCStreamer {
40  std::unique_ptr<formatted_raw_ostream> OSOwner;
42  const MCAsmInfo *MAI;
43  std::unique_ptr<MCInstPrinter> InstPrinter;
44  std::unique_ptr<MCCodeEmitter> Emitter;
45  std::unique_ptr<MCAsmBackend> AsmBackend;
46 
47  SmallString<128> CommentToEmit;
48  raw_svector_ostream CommentStream;
49 
50  unsigned IsVerboseAsm : 1;
51  unsigned ShowInst : 1;
52  unsigned UseDwarfDirectory : 1;
53 
54  void EmitRegisterName(int64_t Register);
55  void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
56  void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
57 
58 public:
59  MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
60  bool isVerboseAsm, bool useDwarfDirectory,
61  MCInstPrinter *printer, MCCodeEmitter *emitter,
62  MCAsmBackend *asmbackend, bool showInst)
63  : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
64  MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
65  AsmBackend(asmbackend), CommentStream(CommentToEmit),
66  IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
67  UseDwarfDirectory(useDwarfDirectory) {
68  assert(InstPrinter);
69  if (IsVerboseAsm)
70  InstPrinter->setCommentStream(CommentStream);
71  }
72 
73  inline void EmitEOL() {
74  // If we don't have any comments, just emit a \n.
75  if (!IsVerboseAsm) {
76  OS << '\n';
77  return;
78  }
79  EmitCommentsAndEOL();
80  }
81  void EmitCommentsAndEOL();
82 
83  /// isVerboseAsm - Return true if this streamer supports verbose assembly at
84  /// all.
85  bool isVerboseAsm() const override { return IsVerboseAsm; }
86 
87  /// hasRawTextSupport - We support EmitRawText.
88  bool hasRawTextSupport() const override { return true; }
89 
90  /// AddComment - Add a comment that can be emitted to the generated .s
91  /// file if applicable as a QoI issue to make the output of the compiler
92  /// more readable. This only affects the MCAsmStreamer, and only when
93  /// verbose assembly output is enabled.
94  void AddComment(const Twine &T) override;
95 
96  /// AddEncodingComment - Add a comment showing the encoding of an instruction.
97  void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
98 
99  /// GetCommentOS - Return a raw_ostream that comments can be written to.
100  /// Unlike AddComment, you are required to terminate comments with \n if you
101  /// use this method.
102  raw_ostream &GetCommentOS() override {
103  if (!IsVerboseAsm)
104  return nulls(); // Discard comments unless in verbose asm mode.
105  return CommentStream;
106  }
107 
108  void emitRawComment(const Twine &T, bool TabPrefix = true) override;
109 
110  /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
111  void AddBlankLine() override {
112  EmitEOL();
113  }
114 
115  /// @name MCStreamer Interface
116  /// @{
117 
118  void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
119 
120  void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
121  void EmitLabel(MCSymbol *Symbol) override;
122 
123  void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
124  void EmitLinkerOptions(ArrayRef<std::string> Options) override;
125  void EmitDataRegion(MCDataRegionType Kind) override;
126  void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
127  unsigned Update) override;
128  void EmitThumbFunc(MCSymbol *Func) override;
129 
130  void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
131  void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
132  bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
133 
134  void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
135  void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
136  void EmitCOFFSymbolStorageClass(int StorageClass) override;
137  void EmitCOFFSymbolType(int Type) override;
138  void EndCOFFSymbolDef() override;
139  void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
140  void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
141  void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
142  void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
143  void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
144  unsigned ByteAlignment) override;
145 
146  /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
147  ///
148  /// @param Symbol - The common symbol to emit.
149  /// @param Size - The size of the common symbol.
150  /// @param ByteAlignment - The alignment of the common symbol in bytes.
151  void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
152  unsigned ByteAlignment) override;
153 
154  void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
155  uint64_t Size = 0, unsigned ByteAlignment = 0) override;
156 
157  void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
158  unsigned ByteAlignment = 0) override;
159 
160  void EmitBytes(StringRef Data) override;
161 
162  void EmitValueImpl(const MCExpr *Value, unsigned Size,
163  const SMLoc &Loc = SMLoc()) override;
164  void EmitIntValue(uint64_t Value, unsigned Size) override;
165 
166  void EmitULEB128Value(const MCExpr *Value) override;
167 
168  void EmitSLEB128Value(const MCExpr *Value) override;
169 
170  void EmitGPRel64Value(const MCExpr *Value) override;
171 
172  void EmitGPRel32Value(const MCExpr *Value) override;
173 
174 
175  void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
176 
177  void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
178  unsigned ValueSize = 1,
179  unsigned MaxBytesToEmit = 0) override;
180 
181  void EmitCodeAlignment(unsigned ByteAlignment,
182  unsigned MaxBytesToEmit = 0) override;
183 
184  bool EmitValueToOffset(const MCExpr *Offset,
185  unsigned char Value = 0) override;
186 
187  void EmitFileDirective(StringRef Filename) override;
188  unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
189  StringRef Filename,
190  unsigned CUID = 0) override;
191  void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
192  unsigned Column, unsigned Flags,
193  unsigned Isa, unsigned Discriminator,
194  StringRef FileName) override;
195  MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
196 
197  void EmitIdent(StringRef IdentString) override;
198  void EmitCFISections(bool EH, bool Debug) override;
199  void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
200  void EmitCFIDefCfaOffset(int64_t Offset) override;
201  void EmitCFIDefCfaRegister(int64_t Register) override;
202  void EmitCFIOffset(int64_t Register, int64_t Offset) override;
203  void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
204  void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
205  void EmitCFIRememberState() override;
206  void EmitCFIRestoreState() override;
207  void EmitCFISameValue(int64_t Register) override;
208  void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
209  void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
210  void EmitCFISignalFrame() override;
211  void EmitCFIUndefined(int64_t Register) override;
212  void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
213  void EmitCFIWindowSave() override;
214 
215  void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
216  void EmitWinCFIEndProc() override;
217  void EmitWinCFIStartChained() override;
218  void EmitWinCFIEndChained() override;
219  void EmitWinCFIPushReg(unsigned Register) override;
220  void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
221  void EmitWinCFIAllocStack(unsigned Size) override;
222  void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
223  void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
224  void EmitWinCFIPushFrame(bool Code) override;
225  void EmitWinCFIEndProlog() override;
226 
227  void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
228  void EmitWinEHHandlerData() override;
229 
230  void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
231 
232  void EmitBundleAlignMode(unsigned AlignPow2) override;
233  void EmitBundleLock(bool AlignToEnd) override;
234  void EmitBundleUnlock() override;
235 
236  /// EmitRawText - If this file is backed by an assembly streamer, this dumps
237  /// the specified string in the output .s file. This capability is
238  /// indicated by the hasRawTextSupport() predicate.
239  void EmitRawTextImpl(StringRef String) override;
240 
241  void FinishImpl() override;
242 };
243 
244 } // end anonymous namespace.
245 
246 /// AddComment - Add a comment that can be emitted to the generated .s
247 /// file if applicable as a QoI issue to make the output of the compiler
248 /// more readable. This only affects the MCAsmStreamer, and only when
249 /// verbose assembly output is enabled.
250 void MCAsmStreamer::AddComment(const Twine &T) {
251  if (!IsVerboseAsm) return;
252 
253  // Make sure that CommentStream is flushed.
254  CommentStream.flush();
255 
256  T.toVector(CommentToEmit);
257  // Each comment goes on its own line.
258  CommentToEmit.push_back('\n');
259 
260  // Tell the comment stream that the vector changed underneath it.
261  CommentStream.resync();
262 }
263 
264 void MCAsmStreamer::EmitCommentsAndEOL() {
265  if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
266  OS << '\n';
267  return;
268  }
269 
270  CommentStream.flush();
271  StringRef Comments = CommentToEmit;
272 
273  assert(Comments.back() == '\n' &&
274  "Comment array not newline terminated");
275  do {
276  // Emit a line of comments.
277  OS.PadToColumn(MAI->getCommentColumn());
278  size_t Position = Comments.find('\n');
279  OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
280 
281  Comments = Comments.substr(Position+1);
282  } while (!Comments.empty());
283 
284  CommentToEmit.clear();
285  // Tell the comment stream that the vector changed underneath it.
286  CommentStream.resync();
287 }
288 
289 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
290  assert(Bytes && "Invalid size!");
291  return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
292 }
293 
294 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
295  if (TabPrefix)
296  OS << '\t';
297  OS << MAI->getCommentString() << T;
298  EmitEOL();
299 }
300 
301 void MCAsmStreamer::ChangeSection(MCSection *Section,
302  const MCExpr *Subsection) {
303  assert(Section && "Cannot switch to a null section!");
304  Section->PrintSwitchToSection(*MAI, OS, Subsection);
305 }
306 
307 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
308  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
309  MCStreamer::EmitLabel(Symbol);
310 
311  Symbol->print(OS, MAI);
312  OS << MAI->getLabelSuffix();
313 
314  EmitEOL();
315 }
316 
317 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
318  StringRef str = MCLOHIdToName(Kind);
319 
320 #ifndef NDEBUG
321  int NbArgs = MCLOHIdToNbArgs(Kind);
322  assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
323  assert(str != "" && "Invalid LOH name");
324 #endif
325 
326  OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
327  bool IsFirst = true;
328  for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
329  It != EndIt; ++It) {
330  if (!IsFirst)
331  OS << ", ";
332  IsFirst = false;
333  (*It)->print(OS, MAI);
334  }
335  EmitEOL();
336 }
337 
338 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
339  switch (Flag) {
340  case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
341  case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
342  case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
343  case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
344  case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
345  }
346  EmitEOL();
347 }
348 
349 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
350  assert(!Options.empty() && "At least one option is required!");
351  OS << "\t.linker_option \"" << Options[0] << '"';
352  for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
353  ie = Options.end(); it != ie; ++it) {
354  OS << ", " << '"' << *it << '"';
355  }
356  OS << "\n";
357 }
358 
359 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
360  if (!MAI->doesSupportDataRegionDirectives())
361  return;
362  switch (Kind) {
363  case MCDR_DataRegion: OS << "\t.data_region"; break;
364  case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
365  case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
366  case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
367  case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
368  }
369  EmitEOL();
370 }
371 
372 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
373  unsigned Minor, unsigned Update) {
374  switch (Kind) {
375  case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
376  case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
377  }
378  OS << " " << Major << ", " << Minor;
379  if (Update)
380  OS << ", " << Update;
381  EmitEOL();
382 }
383 
384 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
385  // This needs to emit to a temporary string to get properly quoted
386  // MCSymbols when they have spaces in them.
387  OS << "\t.thumb_func";
388  // Only Mach-O hasSubsectionsViaSymbols()
389  if (MAI->hasSubsectionsViaSymbols()) {
390  OS << '\t';
391  Func->print(OS, MAI);
392  }
393  EmitEOL();
394 }
395 
396 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
397  Symbol->print(OS, MAI);
398  OS << " = ";
399  Value->print(OS, MAI);
400 
401  EmitEOL();
402 
403  MCStreamer::EmitAssignment(Symbol, Value);
404 }
405 
406 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
407  OS << ".weakref ";
408  Alias->print(OS, MAI);
409  OS << ", ";
410  Symbol->print(OS, MAI);
411  EmitEOL();
412 }
413 
414 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
416  switch (Attribute) {
417  case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
418  case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
419  case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
420  case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
421  case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
422  case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
423  case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
424  case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
425  if (!MAI->hasDotTypeDotSizeDirective())
426  return false; // Symbol attribute not supported
427  OS << "\t.type\t";
428  Symbol->print(OS, MAI);
429  OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
430  switch (Attribute) {
431  default: return false;
432  case MCSA_ELF_TypeFunction: OS << "function"; break;
433  case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
434  case MCSA_ELF_TypeObject: OS << "object"; break;
435  case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
436  case MCSA_ELF_TypeCommon: OS << "common"; break;
437  case MCSA_ELF_TypeNoType: OS << "no_type"; break;
438  case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
439  }
440  EmitEOL();
441  return true;
442  case MCSA_Global: // .globl/.global
443  OS << MAI->getGlobalDirective();
444  break;
445  case MCSA_Hidden: OS << "\t.hidden\t"; break;
446  case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
447  case MCSA_Internal: OS << "\t.internal\t"; break;
448  case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
449  case MCSA_Local: OS << "\t.local\t"; break;
450  case MCSA_NoDeadStrip:
451  if (!MAI->hasNoDeadStrip())
452  return false;
453  OS << "\t.no_dead_strip\t";
454  break;
455  case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
456  case MCSA_PrivateExtern:
457  OS << "\t.private_extern\t";
458  break;
459  case MCSA_Protected: OS << "\t.protected\t"; break;
460  case MCSA_Reference: OS << "\t.reference\t"; break;
461  case MCSA_Weak: OS << MAI->getWeakDirective(); break;
462  case MCSA_WeakDefinition:
463  OS << "\t.weak_definition\t";
464  break;
465  // .weak_reference
466  case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
467  case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
468  }
469 
470  Symbol->print(OS, MAI);
471  EmitEOL();
472 
473  return true;
474 }
475 
476 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
477  OS << ".desc" << ' ';
478  Symbol->print(OS, MAI);
479  OS << ',' << DescValue;
480  EmitEOL();
481 }
482 
483 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
484  OS << "\t.def\t ";
485  Symbol->print(OS, MAI);
486  OS << ';';
487  EmitEOL();
488 }
489 
490 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
491  OS << "\t.scl\t" << StorageClass << ';';
492  EmitEOL();
493 }
494 
495 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
496  OS << "\t.type\t" << Type << ';';
497  EmitEOL();
498 }
499 
500 void MCAsmStreamer::EndCOFFSymbolDef() {
501  OS << "\t.endef";
502  EmitEOL();
503 }
504 
505 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
506  OS << "\t.safeseh\t";
507  Symbol->print(OS, MAI);
508  EmitEOL();
509 }
510 
511 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
512  OS << "\t.secidx\t";
513  Symbol->print(OS, MAI);
514  EmitEOL();
515 }
516 
517 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
518  OS << "\t.secrel32\t";
519  Symbol->print(OS, MAI);
520  EmitEOL();
521 }
522 
523 void MCAsmStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {
524  assert(MAI->hasDotTypeDotSizeDirective());
525  OS << "\t.size\t";
526  Symbol->print(OS, MAI);
527  OS << ", ";
528  Value->print(OS, MAI);
529  OS << '\n';
530 }
531 
532 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
533  unsigned ByteAlignment) {
534  // Common symbols do not belong to any actual section.
535  AssignSection(Symbol, nullptr);
536 
537  OS << "\t.comm\t";
538  Symbol->print(OS, MAI);
539  OS << ',' << Size;
540 
541  if (ByteAlignment != 0) {
542  if (MAI->getCOMMDirectiveAlignmentIsInBytes())
543  OS << ',' << ByteAlignment;
544  else
545  OS << ',' << Log2_32(ByteAlignment);
546  }
547  EmitEOL();
548 }
549 
550 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
551 ///
552 /// @param Symbol - The common symbol to emit.
553 /// @param Size - The size of the common symbol.
554 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
555  unsigned ByteAlign) {
556  // Common symbols do not belong to any actual section.
557  AssignSection(Symbol, nullptr);
558 
559  OS << "\t.lcomm\t";
560  Symbol->print(OS, MAI);
561  OS << ',' << Size;
562 
563  if (ByteAlign > 1) {
564  switch (MAI->getLCOMMDirectiveAlignmentType()) {
565  case LCOMM::NoAlignment:
566  llvm_unreachable("alignment not supported on .lcomm!");
568  OS << ',' << ByteAlign;
569  break;
571  assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
572  OS << ',' << Log2_32(ByteAlign);
573  break;
574  }
575  }
576  EmitEOL();
577 }
578 
579 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
580  uint64_t Size, unsigned ByteAlignment) {
581  if (Symbol)
582  AssignSection(Symbol, Section);
583 
584  // Note: a .zerofill directive does not switch sections.
585  OS << ".zerofill ";
586 
587  // This is a mach-o specific directive.
588  const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
589  OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
590 
591  if (Symbol) {
592  OS << ',';
593  Symbol->print(OS, MAI);
594  OS << ',' << Size;
595  if (ByteAlignment != 0)
596  OS << ',' << Log2_32(ByteAlignment);
597  }
598  EmitEOL();
599 }
600 
601 // .tbss sym, size, align
602 // This depends that the symbol has already been mangled from the original,
603 // e.g. _a.
604 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
605  uint64_t Size, unsigned ByteAlignment) {
606  AssignSection(Symbol, Section);
607 
608  assert(Symbol && "Symbol shouldn't be NULL!");
609  // Instead of using the Section we'll just use the shortcut.
610  // This is a mach-o specific directive and section.
611  OS << ".tbss ";
612  Symbol->print(OS, MAI);
613  OS << ", " << Size;
614 
615  // Output align if we have it. We default to 1 so don't bother printing
616  // that.
617  if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
618 
619  EmitEOL();
620 }
621 
622 static inline char toOctal(int X) { return (X&7)+'0'; }
623 
624 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
625  OS << '"';
626 
627  for (unsigned i = 0, e = Data.size(); i != e; ++i) {
628  unsigned char C = Data[i];
629  if (C == '"' || C == '\\') {
630  OS << '\\' << (char)C;
631  continue;
632  }
633 
634  if (isprint((unsigned char)C)) {
635  OS << (char)C;
636  continue;
637  }
638 
639  switch (C) {
640  case '\b': OS << "\\b"; break;
641  case '\f': OS << "\\f"; break;
642  case '\n': OS << "\\n"; break;
643  case '\r': OS << "\\r"; break;
644  case '\t': OS << "\\t"; break;
645  default:
646  OS << '\\';
647  OS << toOctal(C >> 6);
648  OS << toOctal(C >> 3);
649  OS << toOctal(C >> 0);
650  break;
651  }
652  }
653 
654  OS << '"';
655 }
656 
657 
658 void MCAsmStreamer::EmitBytes(StringRef Data) {
659  assert(getCurrentSection().first &&
660  "Cannot emit contents before setting section!");
661  if (Data.empty()) return;
662 
663  if (Data.size() == 1) {
664  OS << MAI->getData8bitsDirective();
665  OS << (unsigned)(unsigned char)Data[0];
666  EmitEOL();
667  return;
668  }
669 
670  // If the data ends with 0 and the target supports .asciz, use it, otherwise
671  // use .ascii
672  if (MAI->getAscizDirective() && Data.back() == 0) {
673  OS << MAI->getAscizDirective();
674  Data = Data.substr(0, Data.size()-1);
675  } else {
676  OS << MAI->getAsciiDirective();
677  }
678 
679  PrintQuotedString(Data, OS);
680  EmitEOL();
681 }
682 
683 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
684  EmitValue(MCConstantExpr::create(Value, getContext()), Size);
685 }
686 
687 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
688  const SMLoc &Loc) {
689  assert(Size <= 8 && "Invalid size");
690  assert(getCurrentSection().first &&
691  "Cannot emit contents before setting section!");
692  const char *Directive = nullptr;
693  switch (Size) {
694  default: break;
695  case 1: Directive = MAI->getData8bitsDirective(); break;
696  case 2: Directive = MAI->getData16bitsDirective(); break;
697  case 4: Directive = MAI->getData32bitsDirective(); break;
698  case 8: Directive = MAI->getData64bitsDirective(); break;
699  }
700 
701  if (!Directive) {
702  int64_t IntValue;
703  if (!Value->evaluateAsAbsolute(IntValue))
704  report_fatal_error("Don't know how to emit this value.");
705 
706  // We couldn't handle the requested integer size so we fallback by breaking
707  // the request down into several, smaller, integers. Since sizes greater
708  // than eight are invalid and size equivalent to eight should have been
709  // handled earlier, we use four bytes as our largest piece of granularity.
710  bool IsLittleEndian = MAI->isLittleEndian();
711  for (unsigned Emitted = 0; Emitted != Size;) {
712  unsigned Remaining = Size - Emitted;
713  // The size of our partial emission must be a power of two less than
714  // eight.
715  unsigned EmissionSize = PowerOf2Floor(Remaining);
716  if (EmissionSize > 4)
717  EmissionSize = 4;
718  // Calculate the byte offset of our partial emission taking into account
719  // the endianness of the target.
720  unsigned ByteOffset =
721  IsLittleEndian ? Emitted : (Remaining - EmissionSize);
722  uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
723  // We truncate our partial emission to fit within the bounds of the
724  // emission domain. This produces nicer output and silences potential
725  // truncation warnings when round tripping through another assembler.
726  uint64_t Shift = 64 - EmissionSize * 8;
727  assert(Shift < static_cast<uint64_t>(
728  std::numeric_limits<unsigned long long>::digits) &&
729  "undefined behavior");
730  ValueToEmit &= ~0ULL >> Shift;
731  EmitIntValue(ValueToEmit, EmissionSize);
732  Emitted += EmissionSize;
733  }
734  return;
735  }
736 
737  assert(Directive && "Invalid size for machine code value!");
738  OS << Directive;
739  Value->print(OS, MAI);
740  EmitEOL();
741 }
742 
743 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
744  int64_t IntValue;
745  if (Value->evaluateAsAbsolute(IntValue)) {
746  EmitULEB128IntValue(IntValue);
747  return;
748  }
749  OS << ".uleb128 ";
750  Value->print(OS, MAI);
751  EmitEOL();
752 }
753 
754 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
755  int64_t IntValue;
756  if (Value->evaluateAsAbsolute(IntValue)) {
757  EmitSLEB128IntValue(IntValue);
758  return;
759  }
760  OS << ".sleb128 ";
761  Value->print(OS, MAI);
762  EmitEOL();
763 }
764 
765 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
766  assert(MAI->getGPRel64Directive() != nullptr);
767  OS << MAI->getGPRel64Directive();
768  Value->print(OS, MAI);
769  EmitEOL();
770 }
771 
772 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
773  assert(MAI->getGPRel32Directive() != nullptr);
774  OS << MAI->getGPRel32Directive();
775  Value->print(OS, MAI);
776  EmitEOL();
777 }
778 
779 
780 /// EmitFill - Emit NumBytes bytes worth of the value specified by
781 /// FillValue. This implements directives such as '.space'.
782 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
783  if (NumBytes == 0) return;
784 
785  if (const char *ZeroDirective = MAI->getZeroDirective()) {
786  OS << ZeroDirective << NumBytes;
787  if (FillValue != 0)
788  OS << ',' << (int)FillValue;
789  EmitEOL();
790  return;
791  }
792 
793  // Emit a byte at a time.
794  MCStreamer::EmitFill(NumBytes, FillValue);
795 }
796 
797 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
798  unsigned ValueSize,
799  unsigned MaxBytesToEmit) {
800  // Some assemblers don't support non-power of two alignments, so we always
801  // emit alignments as a power of two if possible.
802  if (isPowerOf2_32(ByteAlignment)) {
803  switch (ValueSize) {
804  default:
805  llvm_unreachable("Invalid size for machine code value!");
806  case 1:
807  OS << "\t.align\t";
808  break;
809  case 2:
810  OS << ".p2alignw ";
811  break;
812  case 4:
813  OS << ".p2alignl ";
814  break;
815  case 8:
816  llvm_unreachable("Unsupported alignment size!");
817  }
818 
819  if (MAI->getAlignmentIsInBytes())
820  OS << ByteAlignment;
821  else
822  OS << Log2_32(ByteAlignment);
823 
824  if (Value || MaxBytesToEmit) {
825  OS << ", 0x";
826  OS.write_hex(truncateToSize(Value, ValueSize));
827 
828  if (MaxBytesToEmit)
829  OS << ", " << MaxBytesToEmit;
830  }
831  EmitEOL();
832  return;
833  }
834 
835  // Non-power of two alignment. This is not widely supported by assemblers.
836  // FIXME: Parameterize this based on MAI.
837  switch (ValueSize) {
838  default: llvm_unreachable("Invalid size for machine code value!");
839  case 1: OS << ".balign"; break;
840  case 2: OS << ".balignw"; break;
841  case 4: OS << ".balignl"; break;
842  case 8: llvm_unreachable("Unsupported alignment size!");
843  }
844 
845  OS << ' ' << ByteAlignment;
846  OS << ", " << truncateToSize(Value, ValueSize);
847  if (MaxBytesToEmit)
848  OS << ", " << MaxBytesToEmit;
849  EmitEOL();
850 }
851 
852 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
853  unsigned MaxBytesToEmit) {
854  // Emit with a text fill value.
855  EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
856  1, MaxBytesToEmit);
857 }
858 
859 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
860  unsigned char Value) {
861  // FIXME: Verify that Offset is associated with the current section.
862  OS << ".org ";
863  Offset->print(OS, MAI);
864  OS << ", " << (unsigned)Value;
865  EmitEOL();
866  return false;
867 }
868 
869 
870 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
871  assert(MAI->hasSingleParameterDotFile());
872  OS << "\t.file\t";
873  PrintQuotedString(Filename, OS);
874  EmitEOL();
875 }
876 
877 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
878  StringRef Directory,
879  StringRef Filename,
880  unsigned CUID) {
881  assert(CUID == 0);
882 
883  MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
884  unsigned NumFiles = Table.getMCDwarfFiles().size();
885  FileNo = Table.getFile(Directory, Filename, FileNo);
886  if (FileNo == 0)
887  return 0;
888  if (NumFiles == Table.getMCDwarfFiles().size())
889  return FileNo;
890 
891  SmallString<128> FullPathName;
892 
893  if (!UseDwarfDirectory && !Directory.empty()) {
894  if (sys::path::is_absolute(Filename))
895  Directory = "";
896  else {
897  FullPathName = Directory;
898  sys::path::append(FullPathName, Filename);
899  Directory = "";
900  Filename = FullPathName;
901  }
902  }
903 
904  OS << "\t.file\t" << FileNo << ' ';
905  if (!Directory.empty()) {
906  PrintQuotedString(Directory, OS);
907  OS << ' ';
908  }
909  PrintQuotedString(Filename, OS);
910  EmitEOL();
911 
912  return FileNo;
913 }
914 
915 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
916  unsigned Column, unsigned Flags,
917  unsigned Isa,
918  unsigned Discriminator,
919  StringRef FileName) {
920  OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
921  if (Flags & DWARF2_FLAG_BASIC_BLOCK)
922  OS << " basic_block";
923  if (Flags & DWARF2_FLAG_PROLOGUE_END)
924  OS << " prologue_end";
925  if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
926  OS << " epilogue_begin";
927 
928  unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
929  if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
930  OS << " is_stmt ";
931 
932  if (Flags & DWARF2_FLAG_IS_STMT)
933  OS << "1";
934  else
935  OS << "0";
936  }
937 
938  if (Isa)
939  OS << " isa " << Isa;
940  if (Discriminator)
941  OS << " discriminator " << Discriminator;
942 
943  if (IsVerboseAsm) {
944  OS.PadToColumn(MAI->getCommentColumn());
945  OS << MAI->getCommentString() << ' ' << FileName << ':'
946  << Line << ':' << Column;
947  }
948  EmitEOL();
949  this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
950  Isa, Discriminator, FileName);
951 }
952 
953 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
954  // Always use the zeroth line table, since asm syntax only supports one line
955  // table for now.
957 }
958 
959 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
960  assert(MAI->hasIdentDirective() && ".ident directive not supported");
961  OS << "\t.ident\t";
962  PrintQuotedString(IdentString, OS);
963  EmitEOL();
964 }
965 
966 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
967  MCStreamer::EmitCFISections(EH, Debug);
968  OS << "\t.cfi_sections ";
969  if (EH) {
970  OS << ".eh_frame";
971  if (Debug)
972  OS << ", .debug_frame";
973  } else if (Debug) {
974  OS << ".debug_frame";
975  }
976 
977  EmitEOL();
978 }
979 
980 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
981  OS << "\t.cfi_startproc";
982  if (Frame.IsSimple)
983  OS << " simple";
984  EmitEOL();
985 }
986 
987 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
989  OS << "\t.cfi_endproc";
990  EmitEOL();
991 }
992 
993 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
994  if (!MAI->useDwarfRegNumForCFI()) {
995  const MCRegisterInfo *MRI = getContext().getRegisterInfo();
996  unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
997  InstPrinter->printRegName(OS, LLVMRegister);
998  } else {
999  OS << Register;
1000  }
1001 }
1002 
1003 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1004  MCStreamer::EmitCFIDefCfa(Register, Offset);
1005  OS << "\t.cfi_def_cfa ";
1006  EmitRegisterName(Register);
1007  OS << ", " << Offset;
1008  EmitEOL();
1009 }
1010 
1011 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1013  OS << "\t.cfi_def_cfa_offset " << Offset;
1014  EmitEOL();
1015 }
1016 
1017 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1019  OS << "\t.cfi_def_cfa_register ";
1020  EmitRegisterName(Register);
1021  EmitEOL();
1022 }
1023 
1024 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1025  this->MCStreamer::EmitCFIOffset(Register, Offset);
1026  OS << "\t.cfi_offset ";
1027  EmitRegisterName(Register);
1028  OS << ", " << Offset;
1029  EmitEOL();
1030 }
1031 
1032 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1033  unsigned Encoding) {
1034  MCStreamer::EmitCFIPersonality(Sym, Encoding);
1035  OS << "\t.cfi_personality " << Encoding << ", ";
1036  Sym->print(OS, MAI);
1037  EmitEOL();
1038 }
1039 
1040 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1041  MCStreamer::EmitCFILsda(Sym, Encoding);
1042  OS << "\t.cfi_lsda " << Encoding << ", ";
1043  Sym->print(OS, MAI);
1044  EmitEOL();
1045 }
1046 
1047 void MCAsmStreamer::EmitCFIRememberState() {
1049  OS << "\t.cfi_remember_state";
1050  EmitEOL();
1051 }
1052 
1053 void MCAsmStreamer::EmitCFIRestoreState() {
1055  OS << "\t.cfi_restore_state";
1056  EmitEOL();
1057 }
1058 
1059 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1060  MCStreamer::EmitCFISameValue(Register);
1061  OS << "\t.cfi_same_value ";
1062  EmitRegisterName(Register);
1063  EmitEOL();
1064 }
1065 
1066 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1067  MCStreamer::EmitCFIRelOffset(Register, Offset);
1068  OS << "\t.cfi_rel_offset ";
1069  EmitRegisterName(Register);
1070  OS << ", " << Offset;
1071  EmitEOL();
1072 }
1073 
1074 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1076  OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1077  EmitEOL();
1078 }
1079 
1080 void MCAsmStreamer::EmitCFISignalFrame() {
1082  OS << "\t.cfi_signal_frame";
1083  EmitEOL();
1084 }
1085 
1086 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1087  MCStreamer::EmitCFIUndefined(Register);
1088  OS << "\t.cfi_undefined " << Register;
1089  EmitEOL();
1090 }
1091 
1092 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1093  MCStreamer::EmitCFIRegister(Register1, Register2);
1094  OS << "\t.cfi_register " << Register1 << ", " << Register2;
1095  EmitEOL();
1096 }
1097 
1098 void MCAsmStreamer::EmitCFIWindowSave() {
1100  OS << "\t.cfi_window_save";
1101  EmitEOL();
1102 }
1103 
1104 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1106 
1107  OS << ".seh_proc ";
1108  Symbol->print(OS, MAI);
1109  EmitEOL();
1110 }
1111 
1112 void MCAsmStreamer::EmitWinCFIEndProc() {
1114 
1115  OS << "\t.seh_endproc";
1116  EmitEOL();
1117 }
1118 
1119 void MCAsmStreamer::EmitWinCFIStartChained() {
1121 
1122  OS << "\t.seh_startchained";
1123  EmitEOL();
1124 }
1125 
1126 void MCAsmStreamer::EmitWinCFIEndChained() {
1128 
1129  OS << "\t.seh_endchained";
1130  EmitEOL();
1131 }
1132 
1133 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1134  bool Except) {
1135  MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1136 
1137  OS << "\t.seh_handler ";
1138  Sym->print(OS, MAI);
1139  if (Unwind)
1140  OS << ", @unwind";
1141  if (Except)
1142  OS << ", @except";
1143  EmitEOL();
1144 }
1145 
1146 void MCAsmStreamer::EmitWinEHHandlerData() {
1148 
1149  // Switch sections. Don't call SwitchSection directly, because that will
1150  // cause the section switch to be visible in the emitted assembly.
1151  // We only do this so the section switch that terminates the handler
1152  // data block is visible.
1153  WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1154  MCSection *XData =
1155  WinEH::UnwindEmitter::getXDataSection(CurFrame->Function, getContext());
1156  SwitchSectionNoChange(XData);
1157 
1158  OS << "\t.seh_handlerdata";
1159  EmitEOL();
1160 }
1161 
1162 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1164 
1165  OS << "\t.seh_pushreg " << Register;
1166  EmitEOL();
1167 }
1168 
1169 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1170  MCStreamer::EmitWinCFISetFrame(Register, Offset);
1171 
1172  OS << "\t.seh_setframe " << Register << ", " << Offset;
1173  EmitEOL();
1174 }
1175 
1176 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1178 
1179  OS << "\t.seh_stackalloc " << Size;
1180  EmitEOL();
1181 }
1182 
1183 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1184  MCStreamer::EmitWinCFISaveReg(Register, Offset);
1185 
1186  OS << "\t.seh_savereg " << Register << ", " << Offset;
1187  EmitEOL();
1188 }
1189 
1190 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1191  MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1192 
1193  OS << "\t.seh_savexmm " << Register << ", " << Offset;
1194  EmitEOL();
1195 }
1196 
1197 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1199 
1200  OS << "\t.seh_pushframe";
1201  if (Code)
1202  OS << " @code";
1203  EmitEOL();
1204 }
1205 
1206 void MCAsmStreamer::EmitWinCFIEndProlog(void) {
1208 
1209  OS << "\t.seh_endprologue";
1210  EmitEOL();
1211 }
1212 
1213 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1214  const MCSubtargetInfo &STI) {
1215  raw_ostream &OS = GetCommentOS();
1216  SmallString<256> Code;
1218  raw_svector_ostream VecOS(Code);
1219  Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1220  VecOS.flush();
1221 
1222  // If we are showing fixups, create symbolic markers in the encoded
1223  // representation. We do this by making a per-bit map to the fixup item index,
1224  // then trying to display it as nicely as possible.
1225  SmallVector<uint8_t, 64> FixupMap;
1226  FixupMap.resize(Code.size() * 8);
1227  for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1228  FixupMap[i] = 0;
1229 
1230  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1231  MCFixup &F = Fixups[i];
1232  const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1233  for (unsigned j = 0; j != Info.TargetSize; ++j) {
1234  unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1235  assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1236  FixupMap[Index] = 1 + i;
1237  }
1238  }
1239 
1240  // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1241  // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1242  OS << "encoding: [";
1243  for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1244  if (i)
1245  OS << ',';
1246 
1247  // See if all bits are the same map entry.
1248  uint8_t MapEntry = FixupMap[i * 8 + 0];
1249  for (unsigned j = 1; j != 8; ++j) {
1250  if (FixupMap[i * 8 + j] == MapEntry)
1251  continue;
1252 
1253  MapEntry = uint8_t(~0U);
1254  break;
1255  }
1256 
1257  if (MapEntry != uint8_t(~0U)) {
1258  if (MapEntry == 0) {
1259  OS << format("0x%02x", uint8_t(Code[i]));
1260  } else {
1261  if (Code[i]) {
1262  // FIXME: Some of the 8 bits require fix up.
1263  OS << format("0x%02x", uint8_t(Code[i])) << '\''
1264  << char('A' + MapEntry - 1) << '\'';
1265  } else
1266  OS << char('A' + MapEntry - 1);
1267  }
1268  } else {
1269  // Otherwise, write out in binary.
1270  OS << "0b";
1271  for (unsigned j = 8; j--;) {
1272  unsigned Bit = (Code[i] >> j) & 1;
1273 
1274  unsigned FixupBit;
1275  if (MAI->isLittleEndian())
1276  FixupBit = i * 8 + j;
1277  else
1278  FixupBit = i * 8 + (7-j);
1279 
1280  if (uint8_t MapEntry = FixupMap[FixupBit]) {
1281  assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1282  OS << char('A' + MapEntry - 1);
1283  } else
1284  OS << Bit;
1285  }
1286  }
1287  }
1288  OS << "]\n";
1289 
1290  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1291  MCFixup &F = Fixups[i];
1292  const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1293  OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1294  << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1295  }
1296 }
1297 
1298 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1299  assert(getCurrentSection().first &&
1300  "Cannot emit contents before setting section!");
1301 
1302  // Show the encoding in a comment if we have a code emitter.
1303  if (Emitter)
1304  AddEncodingComment(Inst, STI);
1305 
1306  // Show the MCInst if enabled.
1307  if (ShowInst) {
1308  Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1309  GetCommentOS() << "\n";
1310  }
1311 
1312  if(getTargetStreamer())
1313  getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1314  else
1315  InstPrinter->printInst(&Inst, OS, "", STI);
1316 
1317  EmitEOL();
1318 }
1319 
1320 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1321  OS << "\t.bundle_align_mode " << AlignPow2;
1322  EmitEOL();
1323 }
1324 
1325 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1326  OS << "\t.bundle_lock";
1327  if (AlignToEnd)
1328  OS << " align_to_end";
1329  EmitEOL();
1330 }
1331 
1332 void MCAsmStreamer::EmitBundleUnlock() {
1333  OS << "\t.bundle_unlock";
1334  EmitEOL();
1335 }
1336 
1337 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1338 /// the specified string in the output .s file. This capability is
1339 /// indicated by the hasRawTextSupport() predicate.
1340 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1341  if (!String.empty() && String.back() == '\n')
1342  String = String.substr(0, String.size()-1);
1343  OS << String;
1344  EmitEOL();
1345 }
1346 
1347 void MCAsmStreamer::FinishImpl() {
1348  // If we are generating dwarf for assembly source files dump out the sections.
1349  if (getContext().getGenDwarfForAssembly())
1350  MCGenDwarfInfo::Emit(this);
1351 
1352  // Emit the label for the line table, if requested - since the rest of the
1353  // line table will be defined by .loc/.file directives, and not emitted
1354  // directly, the label is the only work required here.
1355  auto &Tables = getContext().getMCDwarfLineTables();
1356  if (!Tables.empty()) {
1357  assert(Tables.size() == 1 && "asm output only supports one line table");
1358  if (auto *Label = Tables.begin()->second.getLabel()) {
1359  SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1360  EmitLabel(Label);
1361  }
1362  }
1363 }
1364 
1366  std::unique_ptr<formatted_raw_ostream> OS,
1367  bool isVerboseAsm, bool useDwarfDirectory,
1368  MCInstPrinter *IP, MCCodeEmitter *CE,
1369  MCAsmBackend *MAB, bool ShowInst) {
1370  return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1371  useDwarfDirectory, IP, CE, MAB, ShowInst);
1372 }
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:26
virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName)
This implements the DWARF2 '.loc fileno lineno ...' assembler directive.
Definition: MCStreamer.cpp:153
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:48
virtual void EmitCFISameValue(int64_t Register)
Definition: MCStreamer.cpp:341
virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding)
Definition: MCStreamer.cpp:311
MCSectionMachO - This represents a section on a Mach-O system (used by Mac OS X). ...
#define DWARF2_FLAG_PROLOGUE_END
Definition: MCDwarf.h:70
virtual void EmitWinCFIEndProlog()
Definition: MCStreamer.cpp:550
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:51
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
Not a valid directive.
Definition: MCDirectives.h:20
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:240
.ios_version_min
Definition: MCDirectives.h:64
StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:405
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:488
virtual void EmitCFIRegister(int64_t Register1, int64_t Register2)
Definition: MCStreamer.cpp:378
F(f)
.macosx_version_min
Definition: MCDirectives.h:65
MCDataRegionType
Definition: MCDirectives.h:55
virtual void EmitCFIDefCfaOffset(int64_t Offset)
Definition: MCStreamer.cpp:270
.type _foo, STT_NOTYPE # aka
Definition: MCDirectives.h:28
virtual MCSymbol * getDwarfLineTableSymbol(unsigned CUID)
Definition: MCStreamer.cpp:162
COFF::SymbolStorageClass StorageClass
Definition: COFFYAML.cpp:294
void dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer=nullptr, StringRef Separator=" ") const
Dump the MCInst as prettily as possible using the additional MC structures, if given.
Definition: MCInst.cpp:51
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
unsigned TargetOffset
The bit offset to write the relocation into.
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:62
virtual void EmitCFISections(bool EH, bool Debug)
Definition: MCStreamer.cpp:213
static int64_t truncateToSize(int64_t Value, unsigned Bytes)
virtual void EmitWinEHHandlerData()
Definition: MCStreamer.cpp:464
virtual void EmitCFIRememberState()
Definition: MCStreamer.cpp:326
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:443
virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding)
Definition: MCStreamer.cpp:319
#define DWARF2_FLAG_IS_STMT
Definition: MCDwarf.h:68
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:33
const char * Name
A target specific name for the fixup kind.
.data_region jt16
Definition: MCDirectives.h:58
bool is_absolute(const Twine &path)
Is path absolute?
Definition: Path.cpp:650
.local (ELF)
Definition: MCDirectives.h:35
.no_dead_strip (MachO)
Definition: MCDirectives.h:36
virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value)
Emit an assignment of Value to Symbol.
Definition: MCStreamer.cpp:596
Context object for machine code objects.
Definition: MCContext.h:48
const SmallVectorImpl< MCDwarfFile > & getMCDwarfFiles() const
Definition: MCDwarf.h:246
.code16 (X86) / .code 16 (ARM)
Definition: MCDirectives.h:50
#define T
virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame)
Definition: MCStreamer.cpp:248
StringRef getSectionName() const
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
.protected (ELF)
Definition: MCDirectives.h:39
.lazy_reference (MachO)
Definition: MCDirectives.h:34
virtual void EmitCFIRestoreState()
Definition: MCStreamer.cpp:333
uint32_t getOffset() const
Definition: MCFixup.h:91
.reference (MachO)
Definition: MCDirectives.h:40
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:150
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:97
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:111
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:58
.hidden (ELF)
Definition: MCDirectives.h:31
.data_region jt32
Definition: MCDirectives.h:59
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
Definition: MCExpr.cpp:33
Streaming machine code generation interface.
Definition: MCStreamer.h:157
const MCExpr * getValue() const
Definition: MCFixup.h:94
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:44
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static char toOctal(int X)
virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue)
Emit NumBytes bytes worth of the value specified by FillValue.
Definition: MCStreamer.cpp:136
#define DWARF2_FLAG_EPILOGUE_BEGIN
Definition: MCDwarf.h:71
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst)
Create a machine code streamer which will print out assembly for the native target, suitable for compiling with a native assembler.
virtual void EmitWinCFIPushReg(unsigned Register)
Definition: MCStreamer.cpp:470
char back() const
back - Get the last character in the string.
Definition: StringRef.h:122
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:23
virtual void EmitCFIDefCfaRegister(int64_t Register)
Definition: MCStreamer.cpp:286
MCLOHType
Linker Optimization Hint Type.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
.subsections_via_symbols (MachO)
Definition: MCDirectives.h:49
#define DWARF2_FLAG_BASIC_BLOCK
Definition: MCDwarf.h:69
virtual void EmitWinCFIEndChained()
Definition: MCStreamer.cpp:437
virtual void EmitWinCFIEndProc()
Definition: MCStreamer.cpp:416
virtual void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS, const MCExpr *Subsection) const =0
virtual void EmitCFIUndefined(int64_t Register)
Definition: MCStreamer.cpp:370
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:129
.weak_reference (MachO)
Definition: MCDirectives.h:43
int getLLVMRegNum(unsigned RegNum, bool isEH) const
Map a dwarf register back to a target register.
MCFixupKind getKind() const
Definition: MCFixup.h:89
virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except)
Definition: MCStreamer.cpp:450
virtual void EmitWinCFIStartChained()
Definition: MCStreamer.cpp:426
virtual void EmitLabel(MCSymbol *Symbol)
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:203
virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset)
Definition: MCStreamer.cpp:525
virtual void EmitCFIOffset(int64_t Register, int64_t Offset)
Definition: MCStreamer.cpp:295
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
.indirect_symbol (MachO)
Definition: MCDirectives.h:32
.type _foo, STT_TLS # aka
Definition: MCDirectives.h:26
Promote Memory to Register
Definition: Mem2Reg.cpp:58
unsigned TargetSize
The number of bits written by this fixup.
virtual void EmitWinCFIAllocStack(unsigned Size)
Definition: MCStreamer.cpp:498
MCSymbolAttr
Definition: MCDirectives.h:19
static StringRef MCLOHDirectiveName()
unsigned Log2_32(uint32_t Value)
Log2_32 - This function returns the floor log base 2 of the specified value, -1 if the value is zero...
Definition: MathExtras.h:468
const MCSymbol * Function
Definition: MCWinEH.h:37
.syntax (ARM/ELF)
Definition: MCDirectives.h:48
.internal (ELF)
Definition: MCDirectives.h:33
static void Emit(MCStreamer *MCOS)
Definition: MCDwarf.cpp:836
StringRef getSegmentName() const
.code32 (X86) / .code 32 (ARM)
Definition: MCDirectives.h:51
.type _foo, STT_COMMON # aka
Definition: MCDirectives.h:27
.code64 (X86)
Definition: MCDirectives.h:52
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:38
.symbol_resolver (MachO)
Definition: MCDirectives.h:37
.type _foo,
Definition: MCDirectives.h:30
virtual void EmitCFISignalFrame()
Definition: MCStreamer.cpp:364
virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset)
Definition: MCStreamer.cpp:303
MCAssemblerFlag
Definition: MCDirectives.h:47
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
MCSubtargetInfo - Generic base class for all target subtargets.
.weak_definition (MachO)
Definition: MCDirectives.h:42
virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset)
Definition: MCStreamer.cpp:261
static MCSection * getXDataSection(const MCSymbol *Function, MCContext &Context)
Definition: MCWinEH.cpp:70
Target independent information on a fixup kind.
.private_extern (MachO)
Definition: MCDirectives.h:38
const ARM::ArchExtKind Kind
.data_region jt8
Definition: MCDirectives.h:57
static int MCLOHIdToNbArgs(MCLOHType Kind)
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Definition: MathExtras.h:594
MCVersionMinType
Definition: MCDirectives.h:63
LLVM Value Representation.
Definition: Value.h:69
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:34
static cl::opt< bool, true > Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag))
virtual void EmitWinCFIStartProc(const MCSymbol *Symbol)
Definition: MCStreamer.cpp:402
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
static StringRef MCLOHIdToName(MCLOHType Kind)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset)
Definition: MCStreamer.cpp:512
virtual void EmitWinCFIPushFrame(bool Code)
Definition: MCStreamer.cpp:538
bool isPowerOf2_32(uint32_t Value)
isPowerOf2_32 - This function returns true if the argument is a power of two > 0. ...
Definition: MathExtras.h:354
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
bool isUndefined() const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:258
static void PrintQuotedString(StringRef Data, raw_ostream &OS)
Represents a location in source code.
Definition: SMLoc.h:23
unsigned getFile(StringRef &Directory, StringRef &FileName, unsigned FileNumber=0)
Definition: MCDwarf.cpp:344
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:150
virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment)
Definition: MCStreamer.cpp:278
.end_data_region
Definition: MCDirectives.h:60
virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset)
Definition: MCStreamer.cpp:480
virtual void EmitCFIWindowSave()
Definition: MCStreamer.cpp:386
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110
void resize(size_type N)
Definition: SmallVector.h:376