1 //===- lib/Target/PTX/PTXMCAsmStreamer.cpp - PTX Text Assembly Output -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
31 class PTXMCAsmStreamer : public MCStreamer {
32 formatted_raw_ostream &OS;
34 OwningPtr<MCInstPrinter> InstPrinter;
35 OwningPtr<MCCodeEmitter> Emitter;
37 SmallString<128> CommentToEmit;
38 raw_svector_ostream CommentStream;
40 unsigned IsVerboseAsm : 1;
41 unsigned ShowInst : 1;
44 PTXMCAsmStreamer(MCContext &Context,
45 formatted_raw_ostream &os,
46 bool isVerboseAsm, bool useLoc,
47 MCInstPrinter *printer,
48 MCCodeEmitter *emitter,
50 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
51 InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
52 IsVerboseAsm(isVerboseAsm),
54 if (InstPrinter && IsVerboseAsm)
55 InstPrinter->setCommentStream(CommentStream);
58 ~PTXMCAsmStreamer() {}
60 inline void EmitEOL() {
61 // If we don't have any comments, just emit a \n.
68 void EmitCommentsAndEOL();
70 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
72 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
74 /// hasRawTextSupport - We support EmitRawText.
75 virtual bool hasRawTextSupport() const { return true; }
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);
83 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
84 virtual void AddEncodingComment(const MCInst &Inst);
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
89 virtual raw_ostream &GetCommentOS() {
91 return nulls(); // Discard comments unless in verbose asm mode.
95 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
96 virtual void AddBlankLine() {
100 /// @name MCStreamer Interface
103 virtual void ChangeSection(const MCSection *Section);
104 virtual void InitSections() {}
106 virtual void EmitLabel(MCSymbol *Symbol);
108 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
110 virtual void EmitThumbFunc(MCSymbol *Func);
112 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
114 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
116 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
117 const MCSymbol *LastLabel,
118 const MCSymbol *Label);
120 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
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 EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
128 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
129 unsigned ByteAlignment);
131 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
133 /// @param Symbol - The common symbol to emit.
134 /// @param Size - The size of the common symbol.
135 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
137 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
138 unsigned Size = 0, unsigned ByteAlignment = 0);
140 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
141 uint64_t Size, unsigned ByteAlignment = 0);
143 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
145 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
147 virtual void EmitULEB128Value(const MCExpr *Value);
148 virtual void EmitSLEB128Value(const MCExpr *Value);
149 virtual void EmitGPRel32Value(const MCExpr *Value);
152 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
155 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
156 unsigned ValueSize = 1,
157 unsigned MaxBytesToEmit = 0);
159 virtual void EmitCodeAlignment(unsigned ByteAlignment,
160 unsigned MaxBytesToEmit = 0);
162 virtual void EmitValueToOffset(const MCExpr *Offset,
163 unsigned char Value = 0);
165 virtual void EmitFileDirective(StringRef Filename);
166 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
168 virtual void EmitInstruction(const MCInst &Inst);
170 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
171 /// the specified string in the output .s file. This capability is
172 /// indicated by the hasRawTextSupport() predicate.
173 virtual void EmitRawText(StringRef String);
175 virtual void Finish();
179 }; // class PTXMCAsmStreamer
183 /// TODO: Add appropriate implementation of Emit*() methods when needed
185 void PTXMCAsmStreamer::AddComment(const Twine &T) {
186 if (!IsVerboseAsm) return;
188 // Make sure that CommentStream is flushed.
189 CommentStream.flush();
191 T.toVector(CommentToEmit);
192 // Each comment goes on its own line.
193 CommentToEmit.push_back('\n');
195 // Tell the comment stream that the vector changed underneath it.
196 CommentStream.resync();
199 void PTXMCAsmStreamer::EmitCommentsAndEOL() {
200 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
205 CommentStream.flush();
206 StringRef Comments = CommentToEmit.str();
208 assert(Comments.back() == '\n' &&
209 "Comment array not newline terminated");
211 // Emit a line of comments.
212 OS.PadToColumn(MAI.getCommentColumn());
213 size_t Position = Comments.find('\n');
214 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
216 Comments = Comments.substr(Position+1);
217 } while (!Comments.empty());
219 CommentToEmit.clear();
220 // Tell the comment stream that the vector changed underneath it.
221 CommentStream.resync();
224 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
225 assert(Bytes && "Invalid size!");
226 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
229 void PTXMCAsmStreamer::ChangeSection(const MCSection *Section) {
230 assert(Section && "Cannot switch to a null section!");
233 void PTXMCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
234 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
235 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
236 //assert(getCurrentSection() && "Cannot emit before setting section!");
238 OS << *Symbol << MAI.getLabelSuffix();
240 Symbol->setSection(*getCurrentSection());
243 void PTXMCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {}
245 void PTXMCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {}
247 void PTXMCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
248 OS << *Symbol << " = " << *Value;
251 // FIXME: Lift context changes into super class.
252 Symbol->setVariableValue(Value);
255 void PTXMCAsmStreamer::EmitWeakReference(MCSymbol *Alias,
256 const MCSymbol *Symbol) {
257 OS << ".weakref " << *Alias << ", " << *Symbol;
261 void PTXMCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
262 const MCSymbol *LastLabel,
263 const MCSymbol *Label) {
264 report_fatal_error("Unimplemented.");
267 void PTXMCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
268 MCSymbolAttr Attribute) {}
270 void PTXMCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
272 void PTXMCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
274 void PTXMCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {}
276 void PTXMCAsmStreamer::EmitCOFFSymbolType (int Type) {}
278 void PTXMCAsmStreamer::EndCOFFSymbolDef() {}
280 void PTXMCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
282 void PTXMCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
283 unsigned ByteAlignment) {}
285 void PTXMCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
287 void PTXMCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
288 unsigned Size, unsigned ByteAlignment) {}
290 void PTXMCAsmStreamer::EmitTBSSSymbol(const MCSection *Section,
292 uint64_t Size, unsigned ByteAlignment) {}
294 static inline char toOctal(int X) { return (X&7)+'0'; }
296 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
299 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
300 unsigned char C = Data[i];
301 if (C == '"' || C == '\\') {
302 OS << '\\' << (char)C;
306 if (isprint((unsigned char)C)) {
312 case '\b': OS << "\\b"; break;
313 case '\f': OS << "\\f"; break;
314 case '\n': OS << "\\n"; break;
315 case '\r': OS << "\\r"; break;
316 case '\t': OS << "\\t"; break;
319 OS << toOctal(C >> 6);
320 OS << toOctal(C >> 3);
321 OS << toOctal(C >> 0);
329 void PTXMCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
330 assert(getCurrentSection() && "Cannot emit contents before setting section!");
331 if (Data.empty()) return;
333 if (Data.size() == 1) {
334 OS << MAI.getData8bitsDirective(AddrSpace);
335 OS << (unsigned)(unsigned char)Data[0];
340 // If the data ends with 0 and the target supports .asciz, use it, otherwise
342 if (MAI.getAscizDirective() && Data.back() == 0) {
343 OS << MAI.getAscizDirective();
344 Data = Data.substr(0, Data.size()-1);
346 OS << MAI.getAsciiDirective();
350 PrintQuotedString(Data, OS);
354 void PTXMCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
355 unsigned AddrSpace) {
356 assert(getCurrentSection() && "Cannot emit contents before setting section!");
357 const char *Directive = 0;
360 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
361 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
362 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
364 Directive = MAI.getData64bitsDirective(AddrSpace);
365 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
366 if (Directive) break;
368 if (!Value->EvaluateAsAbsolute(IntValue))
369 report_fatal_error("Don't know how to emit this value.");
370 if (getContext().getTargetAsmInfo().isLittleEndian()) {
371 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
372 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
374 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
375 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
380 assert(Directive && "Invalid size for machine code value!");
381 OS << Directive << *Value;
385 void PTXMCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
386 assert(MAI.hasLEB128() && "Cannot print a .uleb");
387 OS << ".uleb128 " << *Value;
391 void PTXMCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
392 assert(MAI.hasLEB128() && "Cannot print a .sleb");
393 OS << ".sleb128 " << *Value;
397 void PTXMCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
398 assert(MAI.getGPRel32Directive() != 0);
399 OS << MAI.getGPRel32Directive() << *Value;
404 /// EmitFill - Emit NumBytes bytes worth of the value specified by
405 /// FillValue. This implements directives such as '.space'.
406 void PTXMCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
407 unsigned AddrSpace) {
408 if (NumBytes == 0) return;
411 if (const char *ZeroDirective = MAI.getZeroDirective()) {
412 OS << ZeroDirective << NumBytes;
414 OS << ',' << (int)FillValue;
419 // Emit a byte at a time.
420 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
423 void PTXMCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment,
426 unsigned MaxBytesToEmit) {
427 // Some assemblers don't support non-power of two alignments, so we always
428 // emit alignments as a power of two if possible.
429 if (isPowerOf2_32(ByteAlignment)) {
431 default: llvm_unreachable("Invalid size for machine code value!");
432 case 1: OS << MAI.getAlignDirective(); break;
433 // FIXME: use MAI for this!
434 case 2: OS << ".p2alignw "; break;
435 case 4: OS << ".p2alignl "; break;
436 case 8: llvm_unreachable("Unsupported alignment size!");
439 if (MAI.getAlignmentIsInBytes())
442 OS << Log2_32(ByteAlignment);
444 if (Value || MaxBytesToEmit) {
446 OS.write_hex(truncateToSize(Value, ValueSize));
449 OS << ", " << MaxBytesToEmit;
455 // Non-power of two alignment. This is not widely supported by assemblers.
456 // FIXME: Parameterize this based on MAI.
458 default: llvm_unreachable("Invalid size for machine code value!");
459 case 1: OS << ".balign"; break;
460 case 2: OS << ".balignw"; break;
461 case 4: OS << ".balignl"; break;
462 case 8: llvm_unreachable("Unsupported alignment size!");
465 OS << ' ' << ByteAlignment;
466 OS << ", " << truncateToSize(Value, ValueSize);
468 OS << ", " << MaxBytesToEmit;
472 void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
473 unsigned MaxBytesToEmit) {}
475 void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
476 unsigned char Value) {}
479 void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) {
480 assert(MAI.hasSingleParameterDotFile());
482 PrintQuotedString(Filename, OS);
486 // FIXME: should we inherit from MCAsmStreamer?
487 bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
489 OS << "\t.file\t" << FileNo << ' ';
490 PrintQuotedString(Filename, OS);
492 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
495 void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {}
497 void PTXMCAsmStreamer::EmitInstruction(const MCInst &Inst) {
498 assert(getCurrentSection() && "Cannot emit contents before setting section!");
500 // Show the encoding in a comment if we have a code emitter.
502 AddEncodingComment(Inst);
504 // Show the MCInst if enabled.
506 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
507 GetCommentOS() << "\n";
510 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
512 InstPrinter->printInst(&Inst, OS);
514 Inst.print(OS, &MAI);
518 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
519 /// the specified string in the output .s file. This capability is
520 /// indicated by the hasRawTextSupport() predicate.
521 void PTXMCAsmStreamer::EmitRawText(StringRef String) {
522 if (!String.empty() && String.back() == '\n')
523 String = String.substr(0, String.size()-1);
528 void PTXMCAsmStreamer::Finish() {}
531 MCStreamer *createPTXAsmStreamer(MCContext &Context,
532 formatted_raw_ostream &OS,
533 bool isVerboseAsm, bool useLoc, bool useCFI,
535 MCCodeEmitter *CE, TargetAsmBackend *TAB,
537 return new PTXMCAsmStreamer(Context, OS, isVerboseAsm, useLoc,