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