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