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