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