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