Add an assert.
[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/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCCodeEmitter.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCInstPrinter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/FormattedStream.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 using namespace llvm;
28
29 namespace {
30
31 class MCAsmStreamer : public MCStreamer {
32   formatted_raw_ostream &OS;
33   const MCAsmInfo &MAI;
34   OwningPtr<MCInstPrinter> InstPrinter;
35   OwningPtr<MCCodeEmitter> Emitter;
36
37   SmallString<128> CommentToEmit;
38   raw_svector_ostream CommentStream;
39
40   const TargetLoweringObjectFile *TLOF;
41   int PointerSize;
42
43   unsigned IsLittleEndian : 1;
44   unsigned IsVerboseAsm : 1;
45   unsigned ShowInst : 1;
46
47 public:
48   MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
49                 bool isLittleEndian, bool isVerboseAsm,
50                 const TargetLoweringObjectFile *tlof, int pointerSize,
51                 MCInstPrinter *printer, MCCodeEmitter *emitter, bool showInst)
52     : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
53       InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
54       TLOF(tlof), PointerSize(pointerSize),
55       IsLittleEndian(isLittleEndian), IsVerboseAsm(isVerboseAsm),
56       ShowInst(showInst) {
57     if (InstPrinter && IsVerboseAsm)
58       InstPrinter->setCommentStream(CommentStream);
59   }
60   ~MCAsmStreamer() {}
61
62   bool isLittleEndian() const { return IsLittleEndian; }
63
64   inline void EmitEOL() {
65     // If we don't have any comments, just emit a \n.
66     if (!IsVerboseAsm) {
67       OS << '\n';
68       return;
69     }
70     EmitCommentsAndEOL();
71   }
72   void EmitCommentsAndEOL();
73
74   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
75   /// all.
76   virtual bool isVerboseAsm() const { return IsVerboseAsm; }
77
78   /// hasRawTextSupport - We support EmitRawText.
79   virtual bool hasRawTextSupport() const { return true; }
80
81   /// AddComment - Add a comment that can be emitted to the generated .s
82   /// file if applicable as a QoI issue to make the output of the compiler
83   /// more readable.  This only affects the MCAsmStreamer, and only when
84   /// verbose assembly output is enabled.
85   virtual void AddComment(const Twine &T);
86
87   /// AddEncodingComment - Add a comment showing the encoding of an instruction.
88   virtual void AddEncodingComment(const MCInst &Inst);
89
90   /// GetCommentOS - Return a raw_ostream that comments can be written to.
91   /// Unlike AddComment, you are required to terminate comments with \n if you
92   /// use this method.
93   virtual raw_ostream &GetCommentOS() {
94     if (!IsVerboseAsm)
95       return nulls();  // Discard comments unless in verbose asm mode.
96     return CommentStream;
97   }
98
99   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
100   virtual void AddBlankLine() {
101     EmitEOL();
102   }
103
104   /// @name MCStreamer Interface
105   /// @{
106
107   virtual void SwitchSection(const MCSection *Section);
108
109   virtual void InitSections() {
110     // FIXME, this is MachO specific, but the testsuite
111     // expects this.
112     SwitchSection(getContext().getMachOSection("__TEXT", "__text",
113                          MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
114                          0, SectionKind::getText()));
115   }
116
117   virtual void EmitLabel(MCSymbol *Symbol);
118
119   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
120   virtual void EmitThumbFunc(MCSymbol *Func);
121
122   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
123   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
124
125   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
126
127   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
128   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
129   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
130   virtual void EmitCOFFSymbolType(int Type);
131   virtual void EndCOFFSymbolDef();
132   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
133   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
134                                 unsigned ByteAlignment);
135
136   /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
137   ///
138   /// @param Symbol - The common symbol to emit.
139   /// @param Size - The size of the common symbol.
140   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
141
142   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
143                             unsigned Size = 0, unsigned ByteAlignment = 0);
144
145   virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
146                                uint64_t Size, unsigned ByteAlignment = 0);
147
148   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
149
150   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
151
152   virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
153
154   virtual void EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
155
156   virtual void EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
157
158   virtual void EmitGPRel32Value(const MCExpr *Value);
159
160
161   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
162                         unsigned AddrSpace);
163
164   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
165                                     unsigned ValueSize = 1,
166                                     unsigned MaxBytesToEmit = 0);
167
168   virtual void EmitCodeAlignment(unsigned ByteAlignment,
169                                  unsigned MaxBytesToEmit = 0);
170
171   virtual void EmitValueToOffset(const MCExpr *Offset,
172                                  unsigned char Value = 0);
173
174   virtual void EmitFileDirective(StringRef Filename);
175   virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
176   virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
177                                      unsigned Column, unsigned Flags,
178                                      unsigned Isa, unsigned Discriminator);
179
180   virtual void EmitInstruction(const MCInst &Inst);
181
182   /// EmitRawText - If this file is backed by an assembly streamer, this dumps
183   /// the specified string in the output .s file.  This capability is
184   /// indicated by the hasRawTextSupport() predicate.
185   virtual void EmitRawText(StringRef String);
186
187   virtual void Finish();
188
189   /// @}
190 };
191
192 } // end anonymous namespace.
193
194 /// AddComment - Add a comment that can be emitted to the generated .s
195 /// file if applicable as a QoI issue to make the output of the compiler
196 /// more readable.  This only affects the MCAsmStreamer, and only when
197 /// verbose assembly output is enabled.
198 void MCAsmStreamer::AddComment(const Twine &T) {
199   if (!IsVerboseAsm) return;
200
201   // Make sure that CommentStream is flushed.
202   CommentStream.flush();
203
204   T.toVector(CommentToEmit);
205   // Each comment goes on its own line.
206   CommentToEmit.push_back('\n');
207
208   // Tell the comment stream that the vector changed underneath it.
209   CommentStream.resync();
210 }
211
212 void MCAsmStreamer::EmitCommentsAndEOL() {
213   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
214     OS << '\n';
215     return;
216   }
217
218   CommentStream.flush();
219   StringRef Comments = CommentToEmit.str();
220
221   assert(Comments.back() == '\n' &&
222          "Comment array not newline terminated");
223   do {
224     // Emit a line of comments.
225     OS.PadToColumn(MAI.getCommentColumn());
226     size_t Position = Comments.find('\n');
227     OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
228
229     Comments = Comments.substr(Position+1);
230   } while (!Comments.empty());
231
232   CommentToEmit.clear();
233   // Tell the comment stream that the vector changed underneath it.
234   CommentStream.resync();
235 }
236
237 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
238   assert(Bytes && "Invalid size!");
239   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
240 }
241
242 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
243   assert(Section && "Cannot switch to a null section!");
244   if (Section != CurSection) {
245     PrevSection = CurSection;
246     CurSection = Section;
247     Section->PrintSwitchToSection(MAI, OS);
248   }
249 }
250
251 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
252   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
253   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
254   assert(CurSection && "Cannot emit before setting section!");
255
256   OS << *Symbol << MAI.getLabelSuffix();
257   EmitEOL();
258   Symbol->setSection(*CurSection);
259 }
260
261 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
262   switch (Flag) {
263   default: assert(0 && "Invalid flag!");
264   case MCAF_SyntaxUnified:         OS << "\t.syntax unified"; break;
265   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
266   case MCAF_Code16:                OS << "\t.code\t16"; break;
267   case MCAF_Code32:                OS << "\t.code\t32"; break;
268   }
269   EmitEOL();
270 }
271
272 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
273   // This needs to emit to a temporary string to get properly quoted
274   // MCSymbols when they have spaces in them.
275   OS << "\t.thumb_func";
276   if (Func)
277     OS << '\t' << *Func;
278   EmitEOL();
279 }
280
281 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
282   OS << *Symbol << " = " << *Value;
283   EmitEOL();
284
285   // FIXME: Lift context changes into super class.
286   Symbol->setVariableValue(Value);
287 }
288
289 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
290   OS << ".weakref " << *Alias << ", " << *Symbol;
291   EmitEOL();
292 }
293
294 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
295                                         MCSymbolAttr Attribute) {
296   switch (Attribute) {
297   case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
298   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
299   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
300   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
301   case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
302   case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
303   case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
304   case MCSA_ELF_TypeGnuUniqueObject:  /// .type _foo, @gnu_unique_object
305     assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
306     OS << "\t.type\t" << *Symbol << ','
307        << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
308     switch (Attribute) {
309     default: assert(0 && "Unknown ELF .type");
310     case MCSA_ELF_TypeFunction:    OS << "function"; break;
311     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
312     case MCSA_ELF_TypeObject:      OS << "object"; break;
313     case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
314     case MCSA_ELF_TypeCommon:      OS << "common"; break;
315     case MCSA_ELF_TypeNoType:      OS << "no_type"; break;
316     case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
317     }
318     EmitEOL();
319     return;
320   case MCSA_Global: // .globl/.global
321     OS << MAI.getGlobalDirective();
322     break;
323   case MCSA_Hidden:         OS << "\t.hidden\t";          break;
324   case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
325   case MCSA_Internal:       OS << "\t.internal\t";        break;
326   case MCSA_LazyReference:  OS << "\t.lazy_reference\t";  break;
327   case MCSA_Local:          OS << "\t.local\t";           break;
328   case MCSA_NoDeadStrip:    OS << "\t.no_dead_strip\t";   break;
329   case MCSA_PrivateExtern:  OS << "\t.private_extern\t";  break;
330   case MCSA_Protected:      OS << "\t.protected\t";       break;
331   case MCSA_Reference:      OS << "\t.reference\t";       break;
332   case MCSA_Weak:           OS << "\t.weak\t";            break;
333   case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break;
334       // .weak_reference
335   case MCSA_WeakReference:  OS << MAI.getWeakRefDirective(); break;
336   case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
337   }
338
339   OS << *Symbol;
340   EmitEOL();
341 }
342
343 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
344   OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
345   EmitEOL();
346 }
347
348 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
349   OS << "\t.def\t " << *Symbol << ';';
350   EmitEOL();
351 }
352
353 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
354   OS << "\t.scl\t" << StorageClass << ';';
355   EmitEOL();
356 }
357
358 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
359   OS << "\t.type\t" << Type << ';';
360   EmitEOL();
361 }
362
363 void MCAsmStreamer::EndCOFFSymbolDef() {
364   OS << "\t.endef";
365   EmitEOL();
366 }
367
368 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
369   assert(MAI.hasDotTypeDotSizeDirective());
370   OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
371 }
372
373 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
374                                      unsigned ByteAlignment) {
375   OS << "\t.comm\t" << *Symbol << ',' << Size;
376   if (ByteAlignment != 0) {
377     if (MAI.getCOMMDirectiveAlignmentIsInBytes())
378       OS << ',' << ByteAlignment;
379     else
380       OS << ',' << Log2_32(ByteAlignment);
381   }
382   EmitEOL();
383 }
384
385 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
386 ///
387 /// @param Symbol - The common symbol to emit.
388 /// @param Size - The size of the common symbol.
389 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
390   assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
391   OS << "\t.lcomm\t" << *Symbol << ',' << Size;
392   EmitEOL();
393 }
394
395 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
396                                  unsigned Size, unsigned ByteAlignment) {
397   // Note: a .zerofill directive does not switch sections.
398   OS << ".zerofill ";
399
400   // This is a mach-o specific directive.
401   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
402   OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
403
404   if (Symbol != NULL) {
405     OS << ',' << *Symbol << ',' << Size;
406     if (ByteAlignment != 0)
407       OS << ',' << Log2_32(ByteAlignment);
408   }
409   EmitEOL();
410 }
411
412 // .tbss sym, size, align
413 // This depends that the symbol has already been mangled from the original,
414 // e.g. _a.
415 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
416                                    uint64_t Size, unsigned ByteAlignment) {
417   assert(Symbol != NULL && "Symbol shouldn't be NULL!");
418   // Instead of using the Section we'll just use the shortcut.
419   // This is a mach-o specific directive and section.
420   OS << ".tbss " << *Symbol << ", " << Size;
421
422   // Output align if we have it.  We default to 1 so don't bother printing
423   // that.
424   if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
425
426   EmitEOL();
427 }
428
429 static inline char toOctal(int X) { return (X&7)+'0'; }
430
431 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
432   OS << '"';
433
434   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
435     unsigned char C = Data[i];
436     if (C == '"' || C == '\\') {
437       OS << '\\' << (char)C;
438       continue;
439     }
440
441     if (isprint((unsigned char)C)) {
442       OS << (char)C;
443       continue;
444     }
445
446     switch (C) {
447       case '\b': OS << "\\b"; break;
448       case '\f': OS << "\\f"; break;
449       case '\n': OS << "\\n"; break;
450       case '\r': OS << "\\r"; break;
451       case '\t': OS << "\\t"; break;
452       default:
453         OS << '\\';
454         OS << toOctal(C >> 6);
455         OS << toOctal(C >> 3);
456         OS << toOctal(C >> 0);
457         break;
458     }
459   }
460
461   OS << '"';
462 }
463
464
465 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
466   assert(CurSection && "Cannot emit contents before setting section!");
467   if (Data.empty()) return;
468
469   if (Data.size() == 1) {
470     OS << MAI.getData8bitsDirective(AddrSpace);
471     OS << (unsigned)(unsigned char)Data[0];
472     EmitEOL();
473     return;
474   }
475
476   // If the data ends with 0 and the target supports .asciz, use it, otherwise
477   // use .ascii
478   if (MAI.getAscizDirective() && Data.back() == 0) {
479     OS << MAI.getAscizDirective();
480     Data = Data.substr(0, Data.size()-1);
481   } else {
482     OS << MAI.getAsciiDirective();
483   }
484
485   OS << ' ';
486   PrintQuotedString(Data, OS);
487   EmitEOL();
488 }
489
490 /// EmitIntValue - Special case of EmitValue that avoids the client having
491 /// to pass in a MCExpr for constant integers.
492 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
493                                  unsigned AddrSpace) {
494   assert(CurSection && "Cannot emit contents before setting section!");
495   const char *Directive = 0;
496   switch (Size) {
497   default: break;
498   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
499   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
500   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
501   case 8:
502     Directive = MAI.getData64bitsDirective(AddrSpace);
503     // If the target doesn't support 64-bit data, emit as two 32-bit halves.
504     if (Directive) break;
505     if (isLittleEndian()) {
506       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
507       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
508     } else {
509       EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
510       EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
511     }
512     return;
513   }
514
515   assert(Directive && "Invalid size for machine code value!");
516   OS << Directive << truncateToSize(Value, Size);
517   EmitEOL();
518 }
519
520 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
521                               unsigned AddrSpace) {
522   assert(CurSection && "Cannot emit contents before setting section!");
523   const char *Directive = 0;
524   switch (Size) {
525   default: break;
526   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
527   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
528   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
529   case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
530   }
531
532   assert(Directive && "Invalid size for machine code value!");
533   OS << Directive << *Value;
534   EmitEOL();
535 }
536
537 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace) {
538   int64_t IntValue;
539   if (Value->EvaluateAsAbsolute(IntValue)) {
540     SmallString<32> Tmp;
541     raw_svector_ostream OSE(Tmp);
542     MCObjectWriter::EncodeULEB128(IntValue, OSE);
543     EmitBytes(OSE.str(), AddrSpace);
544     return;
545   }
546   assert(MAI.hasLEB128() && "Cannot print a .uleb");
547   OS << ".uleb128 " << *Value;
548   EmitEOL();
549 }
550
551 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace) {
552   int64_t IntValue;
553   if (Value->EvaluateAsAbsolute(IntValue)) {
554     SmallString<32> Tmp;
555     raw_svector_ostream OSE(Tmp);
556     MCObjectWriter::EncodeSLEB128(IntValue, OSE);
557     EmitBytes(OSE.str(), AddrSpace);
558     return;
559   }
560   assert(MAI.hasLEB128() && "Cannot print a .sleb");
561   OS << ".sleb128 " << *Value;
562   EmitEOL();
563 }
564
565 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
566   assert(MAI.getGPRel32Directive() != 0);
567   OS << MAI.getGPRel32Directive() << *Value;
568   EmitEOL();
569 }
570
571
572 /// EmitFill - Emit NumBytes bytes worth of the value specified by
573 /// FillValue.  This implements directives such as '.space'.
574 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
575                              unsigned AddrSpace) {
576   if (NumBytes == 0) return;
577
578   if (AddrSpace == 0)
579     if (const char *ZeroDirective = MAI.getZeroDirective()) {
580       OS << ZeroDirective << NumBytes;
581       if (FillValue != 0)
582         OS << ',' << (int)FillValue;
583       EmitEOL();
584       return;
585     }
586
587   // Emit a byte at a time.
588   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
589 }
590
591 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
592                                          unsigned ValueSize,
593                                          unsigned MaxBytesToEmit) {
594   // Some assemblers don't support non-power of two alignments, so we always
595   // emit alignments as a power of two if possible.
596   if (isPowerOf2_32(ByteAlignment)) {
597     switch (ValueSize) {
598     default: llvm_unreachable("Invalid size for machine code value!");
599     case 1: OS << MAI.getAlignDirective(); break;
600     // FIXME: use MAI for this!
601     case 2: OS << ".p2alignw "; break;
602     case 4: OS << ".p2alignl "; break;
603     case 8: llvm_unreachable("Unsupported alignment size!");
604     }
605
606     if (MAI.getAlignmentIsInBytes())
607       OS << ByteAlignment;
608     else
609       OS << Log2_32(ByteAlignment);
610
611     if (Value || MaxBytesToEmit) {
612       OS << ", 0x";
613       OS.write_hex(truncateToSize(Value, ValueSize));
614
615       if (MaxBytesToEmit)
616         OS << ", " << MaxBytesToEmit;
617     }
618     EmitEOL();
619     return;
620   }
621
622   // Non-power of two alignment.  This is not widely supported by assemblers.
623   // FIXME: Parameterize this based on MAI.
624   switch (ValueSize) {
625   default: llvm_unreachable("Invalid size for machine code value!");
626   case 1: OS << ".balign";  break;
627   case 2: OS << ".balignw"; break;
628   case 4: OS << ".balignl"; break;
629   case 8: llvm_unreachable("Unsupported alignment size!");
630   }
631
632   OS << ' ' << ByteAlignment;
633   OS << ", " << truncateToSize(Value, ValueSize);
634   if (MaxBytesToEmit)
635     OS << ", " << MaxBytesToEmit;
636   EmitEOL();
637 }
638
639 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
640                                       unsigned MaxBytesToEmit) {
641   // Emit with a text fill value.
642   EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
643                        1, MaxBytesToEmit);
644 }
645
646 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
647                                       unsigned char Value) {
648   // FIXME: Verify that Offset is associated with the current section.
649   OS << ".org " << *Offset << ", " << (unsigned) Value;
650   EmitEOL();
651 }
652
653
654 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
655   assert(MAI.hasSingleParameterDotFile());
656   OS << "\t.file\t";
657   PrintQuotedString(Filename, OS);
658   EmitEOL();
659 }
660
661 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
662   if (!TLOF) {
663     OS << "\t.file\t" << FileNo << ' ';
664     PrintQuotedString(Filename, OS);
665     EmitEOL();
666   }
667   return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
668 }
669
670 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
671                                           unsigned Column, unsigned Flags,
672                                           unsigned Isa,
673                                           unsigned Discriminator) {
674   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
675                                           Isa, Discriminator);
676   if (TLOF)
677     return;
678
679   OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
680   if (Flags & DWARF2_FLAG_BASIC_BLOCK)
681     OS << " basic_block";
682   if (Flags & DWARF2_FLAG_PROLOGUE_END)
683     OS << " prologue_end";
684   if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
685     OS << " epilogue_begin";
686
687   unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
688   if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
689     OS << " is_stmt ";
690
691     if (Flags & DWARF2_FLAG_IS_STMT)
692       OS << "1";
693     else
694       OS << "0";
695   }
696
697   if (Isa)
698     OS << "isa " << Isa;
699   if (Discriminator)
700     OS << "discriminator " << Discriminator;
701   EmitEOL();
702 }
703
704 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
705   raw_ostream &OS = GetCommentOS();
706   SmallString<256> Code;
707   SmallVector<MCFixup, 4> Fixups;
708   raw_svector_ostream VecOS(Code);
709   Emitter->EncodeInstruction(Inst, VecOS, Fixups);
710   VecOS.flush();
711
712   // If we are showing fixups, create symbolic markers in the encoded
713   // representation. We do this by making a per-bit map to the fixup item index,
714   // then trying to display it as nicely as possible.
715   SmallVector<uint8_t, 64> FixupMap;
716   FixupMap.resize(Code.size() * 8);
717   for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
718     FixupMap[i] = 0;
719
720   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
721     MCFixup &F = Fixups[i];
722     const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
723     for (unsigned j = 0; j != Info.TargetSize; ++j) {
724       unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
725       assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
726       FixupMap[Index] = 1 + i;
727     }
728   }
729
730   OS << "encoding: [";
731   for (unsigned i = 0, e = Code.size(); i != e; ++i) {
732     if (i)
733       OS << ',';
734
735     // See if all bits are the same map entry.
736     uint8_t MapEntry = FixupMap[i * 8 + 0];
737     for (unsigned j = 1; j != 8; ++j) {
738       if (FixupMap[i * 8 + j] == MapEntry)
739         continue;
740
741       MapEntry = uint8_t(~0U);
742       break;
743     }
744
745     if (MapEntry != uint8_t(~0U)) {
746       if (MapEntry == 0) {
747         OS << format("0x%02x", uint8_t(Code[i]));
748       } else {
749         assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
750         OS << char('A' + MapEntry - 1);
751       }
752     } else {
753       // Otherwise, write out in binary.
754       OS << "0b";
755       for (unsigned j = 8; j--;) {
756         unsigned Bit = (Code[i] >> j) & 1;
757         
758         unsigned FixupBit;
759         if (IsLittleEndian)
760           FixupBit = i * 8 + j;
761         else
762           FixupBit = i * 8 + (7-j);
763         
764         if (uint8_t MapEntry = FixupMap[FixupBit]) {
765           assert(Bit == 0 && "Encoder wrote into fixed up bit!");
766           OS << char('A' + MapEntry - 1);
767         } else
768           OS << Bit;
769       }
770     }
771   }
772   OS << "]\n";
773
774   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
775     MCFixup &F = Fixups[i];
776     const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
777     OS << "  fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
778        << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
779   }
780 }
781
782 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
783   assert(CurSection && "Cannot emit contents before setting section!");
784
785   if (TLOF)
786     MCLineEntry::Make(this, getCurrentSection());
787
788   // Show the encoding in a comment if we have a code emitter.
789   if (Emitter)
790     AddEncodingComment(Inst);
791
792   // Show the MCInst if enabled.
793   if (ShowInst) {
794     Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
795     GetCommentOS() << "\n";
796   }
797
798   // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
799   if (InstPrinter)
800     InstPrinter->printInst(&Inst, OS);
801   else
802     Inst.print(OS, &MAI);
803   EmitEOL();
804 }
805
806 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
807 /// the specified string in the output .s file.  This capability is
808 /// indicated by the hasRawTextSupport() predicate.
809 void MCAsmStreamer::EmitRawText(StringRef String) {
810   if (!String.empty() && String.back() == '\n')
811     String = String.substr(0, String.size()-1);
812   OS << String;
813   EmitEOL();
814 }
815
816 void MCAsmStreamer::Finish() {
817   // Dump out the dwarf file & directory tables and line tables.
818   if (getContext().hasDwarfFiles() && TLOF) {
819     MCDwarfFileTable::Emit(this, TLOF->getDwarfLineSection(), NULL,
820                            PointerSize);
821   }
822 }
823
824 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
825                                     formatted_raw_ostream &OS,
826                                     bool isLittleEndian,
827                                     bool isVerboseAsm, MCInstPrinter *IP,
828                                     MCCodeEmitter *CE, bool ShowInst) {
829   return new MCAsmStreamer(Context, OS, isLittleEndian, isVerboseAsm,
830                            NULL, 0, IP, CE, ShowInst);
831 }
832
833
834 MCStreamer *llvm::createAsmStreamerNoLoc(MCContext &Context,
835                                          formatted_raw_ostream &OS,
836                                          bool isLittleEndian,
837                                          bool isVerboseAsm,
838                                          const TargetLoweringObjectFile *TLOF,
839                                          int PointerSize,
840                                          MCInstPrinter *IP,
841                                          MCCodeEmitter *CE, bool ShowInst) {
842   return new MCAsmStreamer(Context, OS, isLittleEndian, isVerboseAsm,
843                            TLOF, PointerSize, IP, CE, ShowInst);
844 }