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