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"
30 class PTXMCAsmStreamer : public MCStreamer {
31 formatted_raw_ostream &OS;
33 OwningPtr<MCInstPrinter> InstPrinter;
34 OwningPtr<MCCodeEmitter> Emitter;
36 SmallString<128> CommentToEmit;
37 raw_svector_ostream CommentStream;
39 unsigned IsVerboseAsm : 1;
40 unsigned ShowInst : 1;
43 PTXMCAsmStreamer(MCContext &Context,
44 formatted_raw_ostream &os,
45 bool isVerboseAsm, bool useLoc,
46 MCInstPrinter *printer,
47 MCCodeEmitter *emitter,
49 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
50 InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
51 IsVerboseAsm(isVerboseAsm),
53 if (InstPrinter && IsVerboseAsm)
54 InstPrinter->setCommentStream(CommentStream);
57 ~PTXMCAsmStreamer() {}
59 inline void EmitEOL() {
60 // If we don't have any comments, just emit a \n.
67 void EmitCommentsAndEOL();
69 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
71 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
73 /// hasRawTextSupport - We support EmitRawText.
74 virtual bool hasRawTextSupport() const { return true; }
76 /// AddComment - Add a comment that can be emitted to the generated .s
77 /// file if applicable as a QoI issue to make the output of the compiler
78 /// more readable. This only affects the MCAsmStreamer, and only when
79 /// verbose assembly output is enabled.
80 virtual void AddComment(const Twine &T);
82 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
83 virtual void AddEncodingComment(const MCInst &Inst);
85 /// GetCommentOS - Return a raw_ostream that comments can be written to.
86 /// Unlike AddComment, you are required to terminate comments with \n if you
88 virtual raw_ostream &GetCommentOS() {
90 return nulls(); // Discard comments unless in verbose asm mode.
94 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
95 virtual void AddBlankLine() {
99 /// @name MCStreamer Interface
102 virtual void ChangeSection(const MCSection *Section);
103 virtual void InitSections() {}
105 virtual void EmitLabel(MCSymbol *Symbol);
107 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
109 virtual void EmitThumbFunc(MCSymbol *Func);
111 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
113 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
115 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
116 const MCSymbol *LastLabel,
117 const MCSymbol *Label,
118 unsigned PointerSize);
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 /// @param ByteAlignment - The alignment of the common symbol in bytes.
136 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
137 unsigned ByteAlignment);
139 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
140 unsigned Size = 0, unsigned ByteAlignment = 0);
142 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
143 uint64_t Size, unsigned ByteAlignment = 0);
145 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
147 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
149 virtual void EmitULEB128Value(const MCExpr *Value);
150 virtual void EmitSLEB128Value(const MCExpr *Value);
151 virtual void EmitGPRel32Value(const MCExpr *Value);
154 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
157 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
158 unsigned ValueSize = 1,
159 unsigned MaxBytesToEmit = 0);
161 virtual void EmitCodeAlignment(unsigned ByteAlignment,
162 unsigned MaxBytesToEmit = 0);
164 virtual void EmitValueToOffset(const MCExpr *Offset,
165 unsigned char Value = 0);
167 virtual void EmitFileDirective(StringRef Filename);
168 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
170 virtual void EmitInstruction(const MCInst &Inst);
172 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
173 /// the specified string in the output .s file. This capability is
174 /// indicated by the hasRawTextSupport() predicate.
175 virtual void EmitRawText(StringRef String);
177 virtual void Finish();
181 }; // class PTXMCAsmStreamer
185 /// TODO: Add appropriate implementation of Emit*() methods when needed
187 void PTXMCAsmStreamer::AddComment(const Twine &T) {
188 if (!IsVerboseAsm) return;
190 // Make sure that CommentStream is flushed.
191 CommentStream.flush();
193 T.toVector(CommentToEmit);
194 // Each comment goes on its own line.
195 CommentToEmit.push_back('\n');
197 // Tell the comment stream that the vector changed underneath it.
198 CommentStream.resync();
201 void PTXMCAsmStreamer::EmitCommentsAndEOL() {
202 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
207 CommentStream.flush();
208 StringRef Comments = CommentToEmit.str();
210 assert(Comments.back() == '\n' &&
211 "Comment array not newline terminated");
213 // Emit a line of comments.
214 OS.PadToColumn(MAI.getCommentColumn());
215 size_t Position = Comments.find('\n');
216 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
218 Comments = Comments.substr(Position+1);
219 } while (!Comments.empty());
221 CommentToEmit.clear();
222 // Tell the comment stream that the vector changed underneath it.
223 CommentStream.resync();
226 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
227 assert(Bytes && "Invalid size!");
228 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
231 void PTXMCAsmStreamer::ChangeSection(const MCSection *Section) {
232 assert(Section && "Cannot switch to a null section!");
235 void PTXMCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
236 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
237 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
238 //assert(getCurrentSection() && "Cannot emit before setting section!");
240 OS << *Symbol << MAI.getLabelSuffix();
242 Symbol->setSection(*getCurrentSection());
245 void PTXMCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {}
247 void PTXMCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {}
249 void PTXMCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
250 OS << *Symbol << " = " << *Value;
253 // FIXME: Lift context changes into super class.
254 Symbol->setVariableValue(Value);
257 void PTXMCAsmStreamer::EmitWeakReference(MCSymbol *Alias,
258 const MCSymbol *Symbol) {
259 OS << ".weakref " << *Alias << ", " << *Symbol;
263 void PTXMCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
264 const MCSymbol *LastLabel,
265 const MCSymbol *Label,
266 unsigned PointerSize) {
267 report_fatal_error("Unimplemented.");
270 void PTXMCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
271 MCSymbolAttr Attribute) {}
273 void PTXMCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
275 void PTXMCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
277 void PTXMCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {}
279 void PTXMCAsmStreamer::EmitCOFFSymbolType (int Type) {}
281 void PTXMCAsmStreamer::EndCOFFSymbolDef() {}
283 void PTXMCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
285 void PTXMCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
286 unsigned ByteAlignment) {}
288 void PTXMCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
289 unsigned ByteAlignment) {}
291 void PTXMCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
292 unsigned Size, unsigned ByteAlignment) {}
294 void PTXMCAsmStreamer::EmitTBSSSymbol(const MCSection *Section,
296 uint64_t Size, unsigned ByteAlignment) {}
298 static inline char toOctal(int X) { return (X&7)+'0'; }
300 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
303 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
304 unsigned char C = Data[i];
305 if (C == '"' || C == '\\') {
306 OS << '\\' << (char)C;
310 if (isprint((unsigned char)C)) {
316 case '\b': OS << "\\b"; break;
317 case '\f': OS << "\\f"; break;
318 case '\n': OS << "\\n"; break;
319 case '\r': OS << "\\r"; break;
320 case '\t': OS << "\\t"; break;
323 OS << toOctal(C >> 6);
324 OS << toOctal(C >> 3);
325 OS << toOctal(C >> 0);
333 void PTXMCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
334 assert(getCurrentSection() && "Cannot emit contents before setting section!");
335 if (Data.empty()) return;
337 if (Data.size() == 1) {
338 OS << MAI.getData8bitsDirective(AddrSpace);
339 OS << (unsigned)(unsigned char)Data[0];
344 // If the data ends with 0 and the target supports .asciz, use it, otherwise
346 if (MAI.getAscizDirective() && Data.back() == 0) {
347 OS << MAI.getAscizDirective();
348 Data = Data.substr(0, Data.size()-1);
350 OS << MAI.getAsciiDirective();
354 PrintQuotedString(Data, OS);
358 void PTXMCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
359 unsigned AddrSpace) {
360 assert(getCurrentSection() && "Cannot emit contents before setting section!");
361 const char *Directive = 0;
364 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
365 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
366 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
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;
372 if (!Value->EvaluateAsAbsolute(IntValue))
373 report_fatal_error("Don't know how to emit this value.");
374 if (getContext().getAsmInfo().isLittleEndian()) {
375 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
376 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
378 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
379 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
384 assert(Directive && "Invalid size for machine code value!");
385 OS << Directive << *Value;
389 void PTXMCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
390 assert(MAI.hasLEB128() && "Cannot print a .uleb");
391 OS << ".uleb128 " << *Value;
395 void PTXMCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
396 assert(MAI.hasLEB128() && "Cannot print a .sleb");
397 OS << ".sleb128 " << *Value;
401 void PTXMCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
402 assert(MAI.getGPRel32Directive() != 0);
403 OS << MAI.getGPRel32Directive() << *Value;
408 /// EmitFill - Emit NumBytes bytes worth of the value specified by
409 /// FillValue. This implements directives such as '.space'.
410 void PTXMCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
411 unsigned AddrSpace) {
412 if (NumBytes == 0) return;
415 if (const char *ZeroDirective = MAI.getZeroDirective()) {
416 OS << ZeroDirective << NumBytes;
418 OS << ',' << (int)FillValue;
423 // Emit a byte at a time.
424 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
427 void PTXMCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment,
430 unsigned MaxBytesToEmit) {
431 // Some assemblers don't support non-power of two alignments, so we always
432 // emit alignments as a power of two if possible.
433 if (isPowerOf2_32(ByteAlignment)) {
435 default: llvm_unreachable("Invalid size for machine code value!");
436 case 1: OS << MAI.getAlignDirective(); break;
437 // FIXME: use MAI for this!
438 case 2: OS << ".p2alignw "; break;
439 case 4: OS << ".p2alignl "; break;
440 case 8: llvm_unreachable("Unsupported alignment size!");
443 if (MAI.getAlignmentIsInBytes())
446 OS << Log2_32(ByteAlignment);
448 if (Value || MaxBytesToEmit) {
450 OS.write_hex(truncateToSize(Value, ValueSize));
453 OS << ", " << MaxBytesToEmit;
459 // Non-power of two alignment. This is not widely supported by assemblers.
460 // FIXME: Parameterize this based on MAI.
462 default: llvm_unreachable("Invalid size for machine code value!");
463 case 1: OS << ".balign"; break;
464 case 2: OS << ".balignw"; break;
465 case 4: OS << ".balignl"; break;
466 case 8: llvm_unreachable("Unsupported alignment size!");
469 OS << ' ' << ByteAlignment;
470 OS << ", " << truncateToSize(Value, ValueSize);
472 OS << ", " << MaxBytesToEmit;
476 void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
477 unsigned MaxBytesToEmit) {}
479 void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
480 unsigned char Value) {}
483 void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) {
484 assert(MAI.hasSingleParameterDotFile());
486 PrintQuotedString(Filename, OS);
490 // FIXME: should we inherit from MCAsmStreamer?
491 bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
493 OS << "\t.file\t" << FileNo << ' ';
494 PrintQuotedString(Filename, OS);
496 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
499 void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {}
501 void PTXMCAsmStreamer::EmitInstruction(const MCInst &Inst) {
502 assert(getCurrentSection() && "Cannot emit contents before setting section!");
504 // Show the encoding in a comment if we have a code emitter.
506 AddEncodingComment(Inst);
508 // Show the MCInst if enabled.
510 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
511 GetCommentOS() << "\n";
514 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
516 InstPrinter->printInst(&Inst, OS);
518 Inst.print(OS, &MAI);
522 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
523 /// the specified string in the output .s file. This capability is
524 /// indicated by the hasRawTextSupport() predicate.
525 void PTXMCAsmStreamer::EmitRawText(StringRef String) {
526 if (!String.empty() && String.back() == '\n')
527 String = String.substr(0, String.size()-1);
532 void PTXMCAsmStreamer::Finish() {}
535 MCStreamer *createPTXAsmStreamer(MCContext &Context,
536 formatted_raw_ostream &OS,
537 bool isVerboseAsm, bool useLoc, bool useCFI,
539 MCCodeEmitter *CE, MCAsmBackend *MAB,
541 return new PTXMCAsmStreamer(Context, OS, isVerboseAsm, useLoc,