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