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