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