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