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