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 27using namespace llvm; 28 29namespace { 30class PTXMCAsmStreamer : public MCStreamer { 31 formatted_raw_ostream &OS; 32 const MCAsmInfo &MAI; 33 OwningPtr<MCInstPrinter> InstPrinter; 34 OwningPtr<MCCodeEmitter> Emitter; 35 36 SmallString<128> CommentToEmit; 37 raw_svector_ostream CommentStream; 38 39 unsigned IsVerboseAsm : 1; 40 unsigned ShowInst : 1; 41 42public: 43 PTXMCAsmStreamer(MCContext &Context, 44 formatted_raw_ostream &os, 45 bool isVerboseAsm, bool useLoc, 46 MCInstPrinter *printer, 47 MCCodeEmitter *emitter, 48 bool showInst) 49 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()), 50 InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit), 51 IsVerboseAsm(isVerboseAsm), 52 ShowInst(showInst) { 53 if (InstPrinter && IsVerboseAsm) 54 InstPrinter->setCommentStream(CommentStream); 55 } 56 57 ~PTXMCAsmStreamer() {} 58 59 inline void EmitEOL() { 60 // If we don't have any comments, just emit a \n. 61 if (!IsVerboseAsm) { 62 OS << '\n'; 63 return; 64 } 65 EmitCommentsAndEOL(); 66 } 67 void EmitCommentsAndEOL(); 68 69 /// isVerboseAsm - Return true if this streamer supports verbose assembly at 70 /// all. 71 virtual bool isVerboseAsm() const { return IsVerboseAsm; } 72 73 /// hasRawTextSupport - We support EmitRawText. 74 virtual bool hasRawTextSupport() const { return true; } 75 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); 81 82 /// AddEncodingComment - Add a comment showing the encoding of an instruction. 83 virtual void AddEncodingComment(const MCInst &Inst); 84 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 87 /// use this method. 88 virtual raw_ostream &GetCommentOS() { 89 if (!IsVerboseAsm) 90 return nulls(); // Discard comments unless in verbose asm mode. 91 return CommentStream; 92 } 93 94 /// AddBlankLine - Emit a blank line to a .s file to pretty it up. 95 virtual void AddBlankLine() { 96 EmitEOL(); 97 } 98 99 /// @name MCStreamer Interface 100 /// @{ 101 102 virtual void ChangeSection(const MCSection *Section); 103 virtual void InitSections() { /* PTX does not use sections */ } 104 105 virtual void EmitLabel(MCSymbol *Symbol); 106 107 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag); 108 109 virtual void EmitThumbFunc(MCSymbol *Func); 110 111 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value); 112 113 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol); 114 115 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta, 116 const MCSymbol *LastLabel, 117 const MCSymbol *Label, 118 unsigned PointerSize); 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 EmitELFSize(MCSymbol *Symbol, const MCExpr *Value); 128 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, 129 unsigned ByteAlignment); 130 131 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol. 132 /// 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); 138 139 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0, 140 unsigned Size = 0, unsigned ByteAlignment = 0); 141 142 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, 143 uint64_t Size, unsigned ByteAlignment = 0); 144 145 virtual void EmitBytes(StringRef Data, unsigned AddrSpace); 146 147 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size, 148 unsigned AddrSpace); 149 virtual void EmitULEB128Value(const MCExpr *Value); 150 virtual void EmitSLEB128Value(const MCExpr *Value); 151 virtual void EmitGPRel32Value(const MCExpr *Value); 152 153 154 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue, 155 unsigned AddrSpace); 156 157 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, 158 unsigned ValueSize = 1, 159 unsigned MaxBytesToEmit = 0); 160 161 virtual void EmitCodeAlignment(unsigned ByteAlignment, 162 unsigned MaxBytesToEmit = 0); 163 164 virtual void EmitValueToOffset(const MCExpr *Offset, 165 unsigned char Value = 0); 166 167 virtual void EmitFileDirective(StringRef Filename); 168 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename); 169 170 virtual void EmitInstruction(const MCInst &Inst); 171 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); 176 177 virtual void Finish(); 178 179 /// @} 180 181}; // class PTXMCAsmStreamer 182 183} 184 185/// TODO: Add appropriate implementation of Emit*() methods when needed 186 187void PTXMCAsmStreamer::AddComment(const Twine &T) { 188 if (!IsVerboseAsm) return; 189 190 // Make sure that CommentStream is flushed. 191 CommentStream.flush(); 192 193 T.toVector(CommentToEmit); 194 // Each comment goes on its own line. 195 CommentToEmit.push_back('\n'); 196 197 // Tell the comment stream that the vector changed underneath it. 198 CommentStream.resync(); 199} 200 201void PTXMCAsmStreamer::EmitCommentsAndEOL() { 202 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) { 203 OS << '\n'; 204 return; 205 } 206 207 CommentStream.flush(); 208 StringRef Comments = CommentToEmit.str(); 209 210 assert(Comments.back() == '\n' && 211 "Comment array not newline terminated"); 212 do { 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'; 217 218 Comments = Comments.substr(Position+1); 219 } while (!Comments.empty()); 220 221 CommentToEmit.clear(); 222 // Tell the comment stream that the vector changed underneath it. 223 CommentStream.resync(); 224} 225 226static 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)); 229} 230 231void PTXMCAsmStreamer::ChangeSection(const MCSection *Section) { 232 assert(Section && "Cannot switch to a null section!"); 233} 234 235void 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!"); 239 240 OS << *Symbol << MAI.getLabelSuffix(); 241 EmitEOL(); 242 Symbol->setSection(*getCurrentSection()); 243} 244 245void PTXMCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {} 246 247void PTXMCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {} 248 249void PTXMCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { 250 OS << *Symbol << " = " << *Value; 251 EmitEOL(); 252 253 // FIXME: Lift context changes into super class. 254 Symbol->setVariableValue(Value); 255} 256 257void PTXMCAsmStreamer::EmitWeakReference(MCSymbol *Alias, 258 const MCSymbol *Symbol) { 259 OS << ".weakref " << *Alias << ", " << *Symbol; 260 EmitEOL(); 261} 262 263void PTXMCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta, 264 const MCSymbol *LastLabel, 265 const MCSymbol *Label, 266 unsigned PointerSize) { 267 report_fatal_error("Unimplemented."); 268} 269 270void PTXMCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol, 271 MCSymbolAttr Attribute) {} 272 273void PTXMCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {} 274 275void PTXMCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {} 276 277void PTXMCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {} 278 279void PTXMCAsmStreamer::EmitCOFFSymbolType (int Type) {} 280 281void PTXMCAsmStreamer::EndCOFFSymbolDef() {} 282 283void PTXMCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {} 284 285void PTXMCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, 286 unsigned ByteAlignment) {} 287 288void PTXMCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, 289 unsigned ByteAlignment) {} 290 291void PTXMCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol, 292 unsigned Size, unsigned ByteAlignment) {} 293 294void PTXMCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, 295 MCSymbol *Symbol, 296 uint64_t Size, unsigned ByteAlignment) {} 297 298static inline char toOctal(int X) { return (X&7)+'0'; } 299 300static void PrintQuotedString(StringRef Data, raw_ostream &OS) { 301 OS << '"'; 302 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; 307 continue; 308 } 309 310 if (isprint((unsigned char)C)) { 311 OS << (char)C; 312 continue; 313 } 314 315 switch (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; 321 default: 322 OS << '\\'; 323 OS << toOctal(C >> 6); 324 OS << toOctal(C >> 3); 325 OS << toOctal(C >> 0); 326 break; 327 } 328 } 329 330 OS << '"'; 331} 332 333void PTXMCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) { 334 assert(getCurrentSection() && "Cannot emit contents before setting section!"); 335 if (Data.empty()) return; 336 337 if (Data.size() == 1) { 338 OS << MAI.getData8bitsDirective(AddrSpace); 339 OS << (unsigned)(unsigned char)Data[0]; 340 EmitEOL(); 341 return; 342 } 343 344 // If the data ends with 0 and the target supports .asciz, use it, otherwise 345 // use .ascii 346 if (MAI.getAscizDirective() && Data.back() == 0) { 347 OS << MAI.getAscizDirective(); 348 Data = Data.substr(0, Data.size()-1); 349 } else { 350 OS << MAI.getAsciiDirective(); 351 } 352 353 OS << ' '; 354 PrintQuotedString(Data, OS); 355 EmitEOL(); 356} 357 358void PTXMCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, 359 unsigned AddrSpace) { 360 assert(getCurrentSection() && "Cannot emit contents before setting section!"); 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().getAsmInfo().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 389void PTXMCAsmStreamer::EmitULEB128Value(const MCExpr *Value) { 390 assert(MAI.hasLEB128() && "Cannot print a .uleb"); 391 OS << ".uleb128 " << *Value; 392 EmitEOL(); 393} 394 395void PTXMCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) { 396 assert(MAI.hasLEB128() && "Cannot print a .sleb"); 397 OS << ".sleb128 " << *Value; 398 EmitEOL(); 399} 400 401void PTXMCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) { 402 assert(MAI.getGPRel32Directive() != 0); 403 OS << MAI.getGPRel32Directive() << *Value; 404 EmitEOL(); 405} 406 407 408/// EmitFill - Emit NumBytes bytes worth of the value specified by 409/// FillValue. This implements directives such as '.space'. 410void PTXMCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue, 411 unsigned AddrSpace) { 412 if (NumBytes == 0) return; 413 414 if (AddrSpace == 0) 415 if (const char *ZeroDirective = MAI.getZeroDirective()) { 416 OS << ZeroDirective << NumBytes; 417 if (FillValue != 0) 418 OS << ',' << (int)FillValue; 419 EmitEOL(); 420 return; 421 } 422 423 // Emit a byte at a time. 424 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace); 425} 426 427void PTXMCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, 428 int64_t Value, 429 unsigned ValueSize, 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)) { 434 switch (ValueSize) { 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!"); 441 } 442 443 if (MAI.getAlignmentIsInBytes()) 444 OS << ByteAlignment; 445 else 446 OS << Log2_32(ByteAlignment); 447 448 if (Value || MaxBytesToEmit) { 449 OS << ", 0x"; 450 OS.write_hex(truncateToSize(Value, ValueSize)); 451 452 if (MaxBytesToEmit) 453 OS << ", " << MaxBytesToEmit; 454 } 455 EmitEOL(); 456 return; 457 } 458 459 // Non-power of two alignment. This is not widely supported by assemblers. 460 // FIXME: Parameterize this based on MAI. 461 switch (ValueSize) { 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!"); 467 } 468 469 OS << ' ' << ByteAlignment; 470 OS << ", " << truncateToSize(Value, ValueSize); 471 if (MaxBytesToEmit) 472 OS << ", " << MaxBytesToEmit; 473 EmitEOL(); 474} 475 476void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment, 477 unsigned MaxBytesToEmit) {} 478 479void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset, 480 unsigned char Value) {} 481 482 483void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) { 484 assert(MAI.hasSingleParameterDotFile()); 485 OS << "\t.file\t"; 486 PrintQuotedString(Filename, OS); 487 EmitEOL(); 488} 489 490// FIXME: should we inherit from MCAsmStreamer? 491bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, 492 StringRef Filename){ 493 OS << "\t.file\t" << FileNo << ' '; 494 PrintQuotedString(Filename, OS); 495 EmitEOL(); 496 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename); 497} 498 499void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {} 500 501void PTXMCAsmStreamer::EmitInstruction(const MCInst &Inst) { 502 assert(getCurrentSection() && "Cannot emit contents before setting section!"); 503 504 // Show the encoding in a comment if we have a code emitter. 505 if (Emitter) 506 AddEncodingComment(Inst); 507 508 // Show the MCInst if enabled. 509 if (ShowInst) { 510 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n "); 511 GetCommentOS() << "\n"; 512 } 513 514 // If we have an AsmPrinter, use that to print, otherwise print the MCInst. 515 if (InstPrinter) 516 InstPrinter->printInst(&Inst, OS, ""); 517 else 518 Inst.print(OS, &MAI); 519 EmitEOL(); 520} 521 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. 525void PTXMCAsmStreamer::EmitRawText(StringRef String) { 526 if (!String.empty() && String.back() == '\n') 527 String = String.substr(0, String.size()-1); 528 OS << String; 529 EmitEOL(); 530} 531 532void PTXMCAsmStreamer::Finish() {} 533 534namespace llvm { 535 MCStreamer *createPTXAsmStreamer(MCContext &Context, 536 formatted_raw_ostream &OS, 537 bool isVerboseAsm, bool useLoc, bool useCFI, 538 MCInstPrinter *IP, 539 MCCodeEmitter *CE, MCAsmBackend *MAB, 540 bool ShowInst) { 541 return new PTXMCAsmStreamer(Context, OS, isVerboseAsm, useLoc, 542 IP, CE, ShowInst); 543 } 544} 545