Enable DebugInfo support for COFF object files.
[oota-llvm.git] / lib / Target / PTX / PTXMCAsmStreamer.cpp
1 //===- lib/Target/PTX/PTXMCAsmStreamer.cpp - PTX 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/ADT/OwningPtr.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCInstPrinter.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27
28 using namespace llvm;
29
30 namespace {
31 class PTXMCAsmStreamer : public MCStreamer {
32   formatted_raw_ostream &OS;
33   const MCAsmInfo &MAI;
34   OwningPtr<MCInstPrinter> InstPrinter;
35   OwningPtr<MCCodeEmitter> Emitter;
36
37   SmallString<128> CommentToEmit;
38   raw_svector_ostream CommentStream;
39
40   unsigned IsVerboseAsm : 1;
41   unsigned ShowInst : 1;
42
43 public:
44   PTXMCAsmStreamer(MCContext &Context,
45                    formatted_raw_ostream &os,
46                    bool isVerboseAsm, bool useLoc,
47                    MCInstPrinter *printer,
48                    MCCodeEmitter *emitter,
49                    bool showInst)
50     : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
51       InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
52       IsVerboseAsm(isVerboseAsm),
53       ShowInst(showInst) {
54     if (InstPrinter && IsVerboseAsm)
55       InstPrinter->setCommentStream(CommentStream);
56   }
57
58   ~PTXMCAsmStreamer() {}
59
60   inline void EmitEOL() {
61     // If we don't have any comments, just emit a \n.
62     if (!IsVerboseAsm) {
63       OS << '\n';
64       return;
65     }
66     EmitCommentsAndEOL();
67   }
68   void EmitCommentsAndEOL();
69
70   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
71   /// all.
72   virtual bool isVerboseAsm() const { return IsVerboseAsm; }
73
74   /// hasRawTextSupport - We support EmitRawText.
75   virtual bool hasRawTextSupport() const { return true; }
76
77   /// AddComment - Add a comment that can be emitted to the generated .s
78   /// file if applicable as a QoI issue to make the output of the compiler
79   /// more readable.  This only affects the MCAsmStreamer, and only when
80   /// verbose assembly output is enabled.
81   virtual void AddComment(const Twine &T);
82
83   /// AddEncodingComment - Add a comment showing the encoding of an instruction.
84   virtual void AddEncodingComment(const MCInst &Inst);
85
86   /// GetCommentOS - Return a raw_ostream that comments can be written to.
87   /// Unlike AddComment, you are required to terminate comments with \n if you
88   /// use this method.
89   virtual raw_ostream &GetCommentOS() {
90     if (!IsVerboseAsm)
91       return nulls();  // Discard comments unless in verbose asm mode.
92     return CommentStream;
93   }
94
95   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
96   virtual void AddBlankLine() {
97     EmitEOL();
98   }
99
100   /// @name MCStreamer Interface
101   /// @{
102
103   virtual void ChangeSection(const MCSection *Section);
104   virtual void InitSections() {}
105
106   virtual void EmitLabel(MCSymbol *Symbol);
107
108   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
109
110   virtual void EmitThumbFunc(MCSymbol *Func);
111
112   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
113
114   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
115
116   virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
117                                         const MCSymbol *LastLabel,
118                                         const MCSymbol *Label);
119
120   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
121
122   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
123   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
124   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
125   virtual void EmitCOFFSymbolType(int Type);
126   virtual void EndCOFFSymbolDef();
127   virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
128   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
129   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
130                                 unsigned ByteAlignment);
131
132   /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
133   ///
134   /// @param Symbol - The common symbol to emit.
135   /// @param Size - The size of the common symbol.
136   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
137
138   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
139                             unsigned Size = 0, unsigned ByteAlignment = 0);
140
141   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
142                               uint64_t Size, unsigned ByteAlignment = 0);
143
144   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
145
146   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
147                              bool isPCRel, unsigned AddrSpace);
148   virtual void EmitULEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
149   virtual void EmitSLEB128Value(const MCExpr *Value, unsigned AddrSpace = 0);
150   virtual void EmitGPRel32Value(const MCExpr *Value);
151
152
153   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
154                         unsigned AddrSpace);
155
156   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
157                                     unsigned ValueSize = 1,
158                                     unsigned MaxBytesToEmit = 0);
159
160   virtual void EmitCodeAlignment(unsigned ByteAlignment,
161                                  unsigned MaxBytesToEmit = 0);
162
163   virtual void EmitValueToOffset(const MCExpr *Offset,
164                                  unsigned char Value = 0);
165
166   virtual void EmitFileDirective(StringRef Filename);
167   virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
168
169   virtual void EmitInstruction(const MCInst &Inst);
170
171   /// EmitRawText - If this file is backed by an assembly streamer, this dumps
172   /// the specified string in the output .s file.  This capability is
173   /// indicated by the hasRawTextSupport() predicate.
174   virtual void EmitRawText(StringRef String);
175
176   virtual void Finish();
177
178   /// @}
179
180 }; // class PTXMCAsmStreamer
181
182 }
183
184 /// TODO: Add appropriate implementation of Emit*() methods when needed
185
186 void PTXMCAsmStreamer::AddComment(const Twine &T) {
187   if (!IsVerboseAsm) return;
188
189   // Make sure that CommentStream is flushed.
190   CommentStream.flush();
191
192   T.toVector(CommentToEmit);
193   // Each comment goes on its own line.
194   CommentToEmit.push_back('\n');
195
196   // Tell the comment stream that the vector changed underneath it.
197   CommentStream.resync();
198 }
199
200 void PTXMCAsmStreamer::EmitCommentsAndEOL() {
201   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
202     OS << '\n';
203     return;
204   }
205
206   CommentStream.flush();
207   StringRef Comments = CommentToEmit.str();
208
209   assert(Comments.back() == '\n' &&
210          "Comment array not newline terminated");
211   do {
212     // Emit a line of comments.
213     OS.PadToColumn(MAI.getCommentColumn());
214     size_t Position = Comments.find('\n');
215     OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
216
217     Comments = Comments.substr(Position+1);
218   } while (!Comments.empty());
219
220   CommentToEmit.clear();
221   // Tell the comment stream that the vector changed underneath it.
222   CommentStream.resync();
223 }
224
225 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
226   assert(Bytes && "Invalid size!");
227   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
228 }
229
230 void PTXMCAsmStreamer::ChangeSection(const MCSection *Section) {
231   assert(Section && "Cannot switch to a null section!");
232 }
233
234 void PTXMCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
235   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
236   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
237   assert(getCurrentSection() && "Cannot emit before setting section!");
238
239   OS << *Symbol << MAI.getLabelSuffix();
240   EmitEOL();
241   Symbol->setSection(*getCurrentSection());
242 }
243
244 void PTXMCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {}
245
246 void PTXMCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {}
247
248 void PTXMCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
249   OS << *Symbol << " = " << *Value;
250   EmitEOL();
251
252   // FIXME: Lift context changes into super class.
253   Symbol->setVariableValue(Value);
254 }
255
256 void PTXMCAsmStreamer::EmitWeakReference(MCSymbol *Alias,
257                                          const MCSymbol *Symbol) {
258   OS << ".weakref " << *Alias << ", " << *Symbol;
259   EmitEOL();
260 }
261
262 void PTXMCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
263                                                 const MCSymbol *LastLabel,
264                                                 const MCSymbol *Label) {
265   report_fatal_error("Unimplemented.");
266 }
267
268 void PTXMCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
269                                            MCSymbolAttr Attribute) {}
270
271 void PTXMCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
272
273 void PTXMCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
274
275 void PTXMCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {}
276
277 void PTXMCAsmStreamer::EmitCOFFSymbolType (int Type) {}
278
279 void PTXMCAsmStreamer::EndCOFFSymbolDef() {}
280
281 void PTXMCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {}
282
283 void PTXMCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
284
285 void PTXMCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
286                                         unsigned ByteAlignment) {}
287
288 void PTXMCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
289
290 void PTXMCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
291                                     unsigned Size, unsigned ByteAlignment) {}
292
293 void PTXMCAsmStreamer::EmitTBSSSymbol(const MCSection *Section,
294                                       MCSymbol *Symbol,
295                                       uint64_t Size, unsigned ByteAlignment) {}
296
297 static inline char toOctal(int X) { return (X&7)+'0'; }
298
299 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
300   OS << '"';
301
302   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
303     unsigned char C = Data[i];
304     if (C == '"' || C == '\\') {
305       OS << '\\' << (char)C;
306       continue;
307     }
308
309     if (isprint((unsigned char)C)) {
310       OS << (char)C;
311       continue;
312     }
313
314     switch (C) {
315       case '\b': OS << "\\b"; break;
316       case '\f': OS << "\\f"; break;
317       case '\n': OS << "\\n"; break;
318       case '\r': OS << "\\r"; break;
319       case '\t': OS << "\\t"; break;
320       default:
321         OS << '\\';
322         OS << toOctal(C >> 6);
323         OS << toOctal(C >> 3);
324         OS << toOctal(C >> 0);
325         break;
326     }
327   }
328
329   OS << '"';
330 }
331
332 void PTXMCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
333   assert(getCurrentSection() && "Cannot emit contents before setting section!");
334   if (Data.empty()) return;
335
336   if (Data.size() == 1) {
337     OS << MAI.getData8bitsDirective(AddrSpace);
338     OS << (unsigned)(unsigned char)Data[0];
339     EmitEOL();
340     return;
341   }
342
343   // If the data ends with 0 and the target supports .asciz, use it, otherwise
344   // use .ascii
345   if (MAI.getAscizDirective() && Data.back() == 0) {
346     OS << MAI.getAscizDirective();
347     Data = Data.substr(0, Data.size()-1);
348   } else {
349     OS << MAI.getAsciiDirective();
350   }
351
352   OS << ' ';
353   PrintQuotedString(Data, OS);
354   EmitEOL();
355 }
356
357 void PTXMCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
358                                      bool isPCRel, unsigned AddrSpace) {
359   assert(getCurrentSection() && "Cannot emit contents before setting section!");
360   assert(!isPCRel && "Cannot emit pc relative relocations!");
361   const char *Directive = 0;
362   switch (Size) {
363   default: break;
364   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
365   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
366   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
367   case 8:
368     Directive = MAI.getData64bitsDirective(AddrSpace);
369     // If the target doesn't support 64-bit data, emit as two 32-bit halves.
370     if (Directive) break;
371     int64_t IntValue;
372     if (!Value->EvaluateAsAbsolute(IntValue))
373       report_fatal_error("Don't know how to emit this value.");
374     if (getContext().getTargetAsmInfo().isLittleEndian()) {
375       EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
376       EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
377     } else {
378       EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
379       EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
380     }
381     return;
382   }
383
384   assert(Directive && "Invalid size for machine code value!");
385   OS << Directive << *Value;
386   EmitEOL();
387 }
388
389 void PTXMCAsmStreamer::EmitULEB128Value(const MCExpr *Value,
390                                         unsigned AddrSpace) {
391   assert(MAI.hasLEB128() && "Cannot print a .uleb");
392   OS << ".uleb128 " << *Value;
393   EmitEOL();
394 }
395
396 void PTXMCAsmStreamer::EmitSLEB128Value(const MCExpr *Value,
397                                         unsigned AddrSpace) {
398   assert(MAI.hasLEB128() && "Cannot print a .sleb");
399   OS << ".sleb128 " << *Value;
400   EmitEOL();
401 }
402
403 void PTXMCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
404   assert(MAI.getGPRel32Directive() != 0);
405   OS << MAI.getGPRel32Directive() << *Value;
406   EmitEOL();
407 }
408
409
410 /// EmitFill - Emit NumBytes bytes worth of the value specified by
411 /// FillValue.  This implements directives such as '.space'.
412 void PTXMCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
413                                 unsigned AddrSpace) {
414   if (NumBytes == 0) return;
415
416   if (AddrSpace == 0)
417     if (const char *ZeroDirective = MAI.getZeroDirective()) {
418       OS << ZeroDirective << NumBytes;
419       if (FillValue != 0)
420         OS << ',' << (int)FillValue;
421       EmitEOL();
422       return;
423     }
424
425   // Emit a byte at a time.
426   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
427 }
428
429 void PTXMCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
430                                             unsigned ValueSize,
431                                             unsigned MaxBytesToEmit) {
432   // Some assemblers don't support non-power of two alignments, so we always
433   // emit alignments as a power of two if possible.
434   if (isPowerOf2_32(ByteAlignment)) {
435     switch (ValueSize) {
436     default: llvm_unreachable("Invalid size for machine code value!");
437     case 1: OS << MAI.getAlignDirective(); break;
438     // FIXME: use MAI for this!
439     case 2: OS << ".p2alignw "; break;
440     case 4: OS << ".p2alignl "; break;
441     case 8: llvm_unreachable("Unsupported alignment size!");
442     }
443
444     if (MAI.getAlignmentIsInBytes())
445       OS << ByteAlignment;
446     else
447       OS << Log2_32(ByteAlignment);
448
449     if (Value || MaxBytesToEmit) {
450       OS << ", 0x";
451       OS.write_hex(truncateToSize(Value, ValueSize));
452
453       if (MaxBytesToEmit)
454         OS << ", " << MaxBytesToEmit;
455     }
456     EmitEOL();
457     return;
458   }
459
460   // Non-power of two alignment.  This is not widely supported by assemblers.
461   // FIXME: Parameterize this based on MAI.
462   switch (ValueSize) {
463   default: llvm_unreachable("Invalid size for machine code value!");
464   case 1: OS << ".balign";  break;
465   case 2: OS << ".balignw"; break;
466   case 4: OS << ".balignl"; break;
467   case 8: llvm_unreachable("Unsupported alignment size!");
468   }
469
470   OS << ' ' << ByteAlignment;
471   OS << ", " << truncateToSize(Value, ValueSize);
472   if (MaxBytesToEmit)
473     OS << ", " << MaxBytesToEmit;
474   EmitEOL();
475 }
476
477 void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
478                                          unsigned MaxBytesToEmit) {}
479
480 void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
481                                          unsigned char Value) {}
482
483
484 void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) {
485   assert(MAI.hasSingleParameterDotFile());
486   OS << "\t.file\t";
487   PrintQuotedString(Filename, OS);
488   EmitEOL();
489 }
490
491 // FIXME: should we inherit from MCAsmStreamer?
492 bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
493                                               StringRef Filename){
494   OS << "\t.file\t" << FileNo << ' ';
495   PrintQuotedString(Filename, OS);
496   EmitEOL();
497   return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
498 }
499
500 void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {}
501
502 void PTXMCAsmStreamer::EmitInstruction(const MCInst &Inst) {
503   assert(getCurrentSection() && "Cannot emit contents before setting section!");
504
505   // Show the encoding in a comment if we have a code emitter.
506   if (Emitter)
507     AddEncodingComment(Inst);
508
509   // Show the MCInst if enabled.
510   if (ShowInst) {
511     Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
512     GetCommentOS() << "\n";
513   }
514
515   // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
516   if (InstPrinter)
517     InstPrinter->printInst(&Inst, OS);
518   else
519     Inst.print(OS, &MAI);
520   EmitEOL();
521 }
522
523 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
524 /// the specified string in the output .s file.  This capability is
525 /// indicated by the hasRawTextSupport() predicate.
526 void PTXMCAsmStreamer::EmitRawText(StringRef String) {
527   if (!String.empty() && String.back() == '\n')
528     String = String.substr(0, String.size()-1);
529   OS << String;
530   EmitEOL();
531 }
532
533 void PTXMCAsmStreamer::Finish() {}
534
535 namespace llvm {
536   MCStreamer *createPTXAsmStreamer(MCContext &Context,
537                                    formatted_raw_ostream &OS,
538                                    bool isVerboseAsm, bool useLoc,
539                                    MCInstPrinter *IP,
540                                    MCCodeEmitter *CE, TargetAsmBackend *TAB,
541                                    bool ShowInst) {
542     return new PTXMCAsmStreamer(Context, OS, isVerboseAsm, useLoc,
543                                 IP, CE, ShowInst);
544   }
545 }