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