1 //===- lib/MC/MCAsmStreamer.cpp - 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/MC/MCStreamer.h"
11 #include "llvm/ADT/STLExtras.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/MCSymbolELF.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"
39 class MCAsmStreamer final : public MCStreamer {
40 std::unique_ptr<formatted_raw_ostream> OSOwner;
41 formatted_raw_ostream &OS;
43 std::unique_ptr<MCInstPrinter> InstPrinter;
44 std::unique_ptr<MCCodeEmitter> Emitter;
45 std::unique_ptr<MCAsmBackend> AsmBackend;
47 SmallString<128> CommentToEmit;
48 raw_svector_ostream CommentStream;
50 unsigned IsVerboseAsm : 1;
51 unsigned ShowInst : 1;
52 unsigned UseDwarfDirectory : 1;
54 void EmitRegisterName(int64_t Register);
55 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
56 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
59 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
60 bool isVerboseAsm, bool useDwarfDirectory,
61 MCInstPrinter *printer, MCCodeEmitter *emitter,
62 MCAsmBackend *asmbackend, bool showInst)
63 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
64 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
65 AsmBackend(asmbackend), CommentStream(CommentToEmit),
66 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
67 UseDwarfDirectory(useDwarfDirectory) {
70 InstPrinter->setCommentStream(CommentStream);
73 inline void EmitEOL() {
74 // If we don't have any comments, just emit a \n.
81 void EmitCommentsAndEOL();
83 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
85 bool isVerboseAsm() const override { return IsVerboseAsm; }
87 /// hasRawTextSupport - We support EmitRawText.
88 bool hasRawTextSupport() const override { return true; }
90 /// AddComment - Add a comment that can be emitted to the generated .s
91 /// file if applicable as a QoI issue to make the output of the compiler
92 /// more readable. This only affects the MCAsmStreamer, and only when
93 /// verbose assembly output is enabled.
94 void AddComment(const Twine &T) override;
96 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
97 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
99 /// GetCommentOS - Return a raw_ostream that comments can be written to.
100 /// Unlike AddComment, you are required to terminate comments with \n if you
102 raw_ostream &GetCommentOS() override {
104 return nulls(); // Discard comments unless in verbose asm mode.
105 return CommentStream;
108 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
110 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
111 void AddBlankLine() override {
115 /// @name MCStreamer Interface
118 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
120 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
121 void EmitLabel(MCSymbol *Symbol) override;
123 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
124 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
125 void EmitDataRegion(MCDataRegionType Kind) override;
126 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
127 unsigned Update) override;
128 void EmitThumbFunc(MCSymbol *Func) override;
130 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
131 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
132 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
134 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
135 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
136 void EmitCOFFSymbolStorageClass(int StorageClass) override;
137 void EmitCOFFSymbolType(int Type) override;
138 void EndCOFFSymbolDef() override;
139 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
140 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
141 void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
142 void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
143 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
144 unsigned ByteAlignment) override;
146 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
148 /// @param Symbol - The common symbol to emit.
149 /// @param Size - The size of the common symbol.
150 /// @param ByteAlignment - The alignment of the common symbol in bytes.
151 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
152 unsigned ByteAlignment) override;
154 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
155 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
157 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
158 unsigned ByteAlignment = 0) override;
160 void EmitBytes(StringRef Data) override;
162 void EmitValueImpl(const MCExpr *Value, unsigned Size,
163 const SMLoc &Loc = SMLoc()) override;
164 void EmitIntValue(uint64_t Value, unsigned Size) override;
166 void EmitULEB128Value(const MCExpr *Value) override;
168 void EmitSLEB128Value(const MCExpr *Value) override;
170 void EmitGPRel64Value(const MCExpr *Value) override;
172 void EmitGPRel32Value(const MCExpr *Value) override;
175 void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
177 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
178 unsigned ValueSize = 1,
179 unsigned MaxBytesToEmit = 0) override;
181 void EmitCodeAlignment(unsigned ByteAlignment,
182 unsigned MaxBytesToEmit = 0) override;
184 bool EmitValueToOffset(const MCExpr *Offset,
185 unsigned char Value = 0) override;
187 void EmitFileDirective(StringRef Filename) override;
188 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
190 unsigned CUID = 0) override;
191 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
192 unsigned Column, unsigned Flags,
193 unsigned Isa, unsigned Discriminator,
194 StringRef FileName) override;
195 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
197 void EmitIdent(StringRef IdentString) override;
198 void EmitCFISections(bool EH, bool Debug) override;
199 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
200 void EmitCFIDefCfaOffset(int64_t Offset) override;
201 void EmitCFIDefCfaRegister(int64_t Register) override;
202 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
203 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
204 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
205 void EmitCFIRememberState() override;
206 void EmitCFIRestoreState() override;
207 void EmitCFISameValue(int64_t Register) override;
208 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
209 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
210 void EmitCFISignalFrame() override;
211 void EmitCFIUndefined(int64_t Register) override;
212 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
213 void EmitCFIWindowSave() override;
215 void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
216 void EmitWinCFIEndProc() override;
217 void EmitWinCFIStartChained() override;
218 void EmitWinCFIEndChained() override;
219 void EmitWinCFIPushReg(unsigned Register) override;
220 void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
221 void EmitWinCFIAllocStack(unsigned Size) override;
222 void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
223 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
224 void EmitWinCFIPushFrame(bool Code) override;
225 void EmitWinCFIEndProlog() override;
227 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
228 void EmitWinEHHandlerData() override;
230 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
232 void EmitBundleAlignMode(unsigned AlignPow2) override;
233 void EmitBundleLock(bool AlignToEnd) override;
234 void EmitBundleUnlock() override;
236 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
237 /// the specified string in the output .s file. This capability is
238 /// indicated by the hasRawTextSupport() predicate.
239 void EmitRawTextImpl(StringRef String) override;
241 void FinishImpl() override;
244 } // end anonymous namespace.
246 /// AddComment - Add a comment that can be emitted to the generated .s
247 /// file if applicable as a QoI issue to make the output of the compiler
248 /// more readable. This only affects the MCAsmStreamer, and only when
249 /// verbose assembly output is enabled.
250 void MCAsmStreamer::AddComment(const Twine &T) {
251 if (!IsVerboseAsm) return;
253 // Make sure that CommentStream is flushed.
254 CommentStream.flush();
256 T.toVector(CommentToEmit);
257 // Each comment goes on its own line.
258 CommentToEmit.push_back('\n');
260 // Tell the comment stream that the vector changed underneath it.
261 CommentStream.resync();
264 void MCAsmStreamer::EmitCommentsAndEOL() {
265 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
270 CommentStream.flush();
271 StringRef Comments = CommentToEmit;
273 assert(Comments.back() == '\n' &&
274 "Comment array not newline terminated");
276 // Emit a line of comments.
277 OS.PadToColumn(MAI->getCommentColumn());
278 size_t Position = Comments.find('\n');
279 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
281 Comments = Comments.substr(Position+1);
282 } while (!Comments.empty());
284 CommentToEmit.clear();
285 // Tell the comment stream that the vector changed underneath it.
286 CommentStream.resync();
289 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
290 assert(Bytes && "Invalid size!");
291 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
294 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
297 OS << MAI->getCommentString() << T;
301 void MCAsmStreamer::ChangeSection(MCSection *Section,
302 const MCExpr *Subsection) {
303 assert(Section && "Cannot switch to a null section!");
304 Section->PrintSwitchToSection(*MAI, OS, Subsection);
307 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
308 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
309 MCStreamer::EmitLabel(Symbol);
311 OS << *Symbol << MAI->getLabelSuffix();
315 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
316 StringRef str = MCLOHIdToName(Kind);
319 int NbArgs = MCLOHIdToNbArgs(Kind);
320 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
321 assert(str != "" && "Invalid LOH name");
324 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
326 for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
336 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
338 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
339 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
340 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
341 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
342 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
347 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
348 assert(!Options.empty() && "At least one option is required!");
349 OS << "\t.linker_option \"" << Options[0] << '"';
350 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
351 ie = Options.end(); it != ie; ++it) {
352 OS << ", " << '"' << *it << '"';
357 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
358 if (!MAI->doesSupportDataRegionDirectives())
361 case MCDR_DataRegion: OS << "\t.data_region"; break;
362 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
363 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
364 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
365 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
370 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
371 unsigned Minor, unsigned Update) {
373 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
374 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
376 OS << " " << Major << ", " << Minor;
378 OS << ", " << Update;
382 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
383 // This needs to emit to a temporary string to get properly quoted
384 // MCSymbols when they have spaces in them.
385 OS << "\t.thumb_func";
386 // Only Mach-O hasSubsectionsViaSymbols()
387 if (MAI->hasSubsectionsViaSymbols())
392 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
393 OS << *Symbol << " = " << *Value;
396 MCStreamer::EmitAssignment(Symbol, Value);
399 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
400 OS << ".weakref " << *Alias << ", " << *Symbol;
404 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
405 MCSymbolAttr Attribute) {
407 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
408 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
409 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
410 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
411 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
412 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
413 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
414 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
415 if (!MAI->hasDotTypeDotSizeDirective())
416 return false; // Symbol attribute not supported
417 OS << "\t.type\t" << *Symbol << ','
418 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
420 default: return false;
421 case MCSA_ELF_TypeFunction: OS << "function"; break;
422 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
423 case MCSA_ELF_TypeObject: OS << "object"; break;
424 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
425 case MCSA_ELF_TypeCommon: OS << "common"; break;
426 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
427 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
431 case MCSA_Global: // .globl/.global
432 OS << MAI->getGlobalDirective();
434 case MCSA_Hidden: OS << "\t.hidden\t"; break;
435 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
436 case MCSA_Internal: OS << "\t.internal\t"; break;
437 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
438 case MCSA_Local: OS << "\t.local\t"; break;
439 case MCSA_NoDeadStrip:
440 if (!MAI->hasNoDeadStrip())
442 OS << "\t.no_dead_strip\t";
444 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
445 case MCSA_PrivateExtern:
446 OS << "\t.private_extern\t";
448 case MCSA_Protected: OS << "\t.protected\t"; break;
449 case MCSA_Reference: OS << "\t.reference\t"; break;
450 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
451 case MCSA_WeakDefinition:
452 OS << "\t.weak_definition\t";
455 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
456 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
465 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
466 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
470 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
471 OS << "\t.def\t " << *Symbol << ';';
475 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
476 OS << "\t.scl\t" << StorageClass << ';';
480 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
481 OS << "\t.type\t" << Type << ';';
485 void MCAsmStreamer::EndCOFFSymbolDef() {
490 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
491 OS << "\t.safeseh\t" << *Symbol;
495 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
496 OS << "\t.secidx\t" << *Symbol;
500 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
501 OS << "\t.secrel32\t" << *Symbol;
505 void MCAsmStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {
506 assert(MAI->hasDotTypeDotSizeDirective());
507 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
510 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
511 unsigned ByteAlignment) {
512 // Common symbols do not belong to any actual section.
513 AssignSection(Symbol, nullptr);
515 OS << "\t.comm\t" << *Symbol << ',' << Size;
516 if (ByteAlignment != 0) {
517 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
518 OS << ',' << ByteAlignment;
520 OS << ',' << Log2_32(ByteAlignment);
525 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
527 /// @param Symbol - The common symbol to emit.
528 /// @param Size - The size of the common symbol.
529 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
530 unsigned ByteAlign) {
531 // Common symbols do not belong to any actual section.
532 AssignSection(Symbol, nullptr);
534 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
536 switch (MAI->getLCOMMDirectiveAlignmentType()) {
537 case LCOMM::NoAlignment:
538 llvm_unreachable("alignment not supported on .lcomm!");
539 case LCOMM::ByteAlignment:
540 OS << ',' << ByteAlign;
542 case LCOMM::Log2Alignment:
543 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
544 OS << ',' << Log2_32(ByteAlign);
551 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
552 uint64_t Size, unsigned ByteAlignment) {
554 AssignSection(Symbol, Section);
556 // Note: a .zerofill directive does not switch sections.
559 // This is a mach-o specific directive.
560 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
561 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
564 OS << ',' << *Symbol << ',' << Size;
565 if (ByteAlignment != 0)
566 OS << ',' << Log2_32(ByteAlignment);
571 // .tbss sym, size, align
572 // This depends that the symbol has already been mangled from the original,
574 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
575 uint64_t Size, unsigned ByteAlignment) {
576 AssignSection(Symbol, Section);
578 assert(Symbol && "Symbol shouldn't be NULL!");
579 // Instead of using the Section we'll just use the shortcut.
580 // This is a mach-o specific directive and section.
581 OS << ".tbss " << *Symbol << ", " << Size;
583 // Output align if we have it. We default to 1 so don't bother printing
585 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
590 static inline char toOctal(int X) { return (X&7)+'0'; }
592 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
595 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
596 unsigned char C = Data[i];
597 if (C == '"' || C == '\\') {
598 OS << '\\' << (char)C;
602 if (isprint((unsigned char)C)) {
608 case '\b': OS << "\\b"; break;
609 case '\f': OS << "\\f"; break;
610 case '\n': OS << "\\n"; break;
611 case '\r': OS << "\\r"; break;
612 case '\t': OS << "\\t"; break;
615 OS << toOctal(C >> 6);
616 OS << toOctal(C >> 3);
617 OS << toOctal(C >> 0);
626 void MCAsmStreamer::EmitBytes(StringRef Data) {
627 assert(getCurrentSection().first &&
628 "Cannot emit contents before setting section!");
629 if (Data.empty()) return;
631 if (Data.size() == 1) {
632 OS << MAI->getData8bitsDirective();
633 OS << (unsigned)(unsigned char)Data[0];
638 // If the data ends with 0 and the target supports .asciz, use it, otherwise
640 if (MAI->getAscizDirective() && Data.back() == 0) {
641 OS << MAI->getAscizDirective();
642 Data = Data.substr(0, Data.size()-1);
644 OS << MAI->getAsciiDirective();
647 PrintQuotedString(Data, OS);
651 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
652 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
655 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
657 assert(Size <= 8 && "Invalid size");
658 assert(getCurrentSection().first &&
659 "Cannot emit contents before setting section!");
660 const char *Directive = nullptr;
663 case 1: Directive = MAI->getData8bitsDirective(); break;
664 case 2: Directive = MAI->getData16bitsDirective(); break;
665 case 4: Directive = MAI->getData32bitsDirective(); break;
666 case 8: Directive = MAI->getData64bitsDirective(); break;
671 if (!Value->evaluateAsAbsolute(IntValue))
672 report_fatal_error("Don't know how to emit this value.");
674 // We couldn't handle the requested integer size so we fallback by breaking
675 // the request down into several, smaller, integers. Since sizes greater
676 // than eight are invalid and size equivalent to eight should have been
677 // handled earlier, we use four bytes as our largest piece of granularity.
678 bool IsLittleEndian = MAI->isLittleEndian();
679 for (unsigned Emitted = 0; Emitted != Size;) {
680 unsigned Remaining = Size - Emitted;
681 // The size of our partial emission must be a power of two less than
683 unsigned EmissionSize = PowerOf2Floor(Remaining);
684 if (EmissionSize > 4)
686 // Calculate the byte offset of our partial emission taking into account
687 // the endianness of the target.
688 unsigned ByteOffset =
689 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
690 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
691 // We truncate our partial emission to fit within the bounds of the
692 // emission domain. This produces nicer output and silences potential
693 // truncation warnings when round tripping through another assembler.
694 uint64_t Shift = 64 - EmissionSize * 8;
695 assert(Shift < static_cast<uint64_t>(
696 std::numeric_limits<unsigned long long>::digits) &&
697 "undefined behavior");
698 ValueToEmit &= ~0ULL >> Shift;
699 EmitIntValue(ValueToEmit, EmissionSize);
700 Emitted += EmissionSize;
705 assert(Directive && "Invalid size for machine code value!");
706 OS << Directive << *Value;
710 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
712 if (Value->evaluateAsAbsolute(IntValue)) {
713 EmitULEB128IntValue(IntValue);
716 OS << ".uleb128 " << *Value;
720 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
722 if (Value->evaluateAsAbsolute(IntValue)) {
723 EmitSLEB128IntValue(IntValue);
726 OS << ".sleb128 " << *Value;
730 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
731 assert(MAI->getGPRel64Directive() != nullptr);
732 OS << MAI->getGPRel64Directive() << *Value;
736 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
737 assert(MAI->getGPRel32Directive() != nullptr);
738 OS << MAI->getGPRel32Directive() << *Value;
743 /// EmitFill - Emit NumBytes bytes worth of the value specified by
744 /// FillValue. This implements directives such as '.space'.
745 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
746 if (NumBytes == 0) return;
748 if (const char *ZeroDirective = MAI->getZeroDirective()) {
749 OS << ZeroDirective << NumBytes;
751 OS << ',' << (int)FillValue;
756 // Emit a byte at a time.
757 MCStreamer::EmitFill(NumBytes, FillValue);
760 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
762 unsigned MaxBytesToEmit) {
763 // Some assemblers don't support non-power of two alignments, so we always
764 // emit alignments as a power of two if possible.
765 if (isPowerOf2_32(ByteAlignment)) {
768 llvm_unreachable("Invalid size for machine code value!");
779 llvm_unreachable("Unsupported alignment size!");
782 if (MAI->getAlignmentIsInBytes())
785 OS << Log2_32(ByteAlignment);
787 if (Value || MaxBytesToEmit) {
789 OS.write_hex(truncateToSize(Value, ValueSize));
792 OS << ", " << MaxBytesToEmit;
798 // Non-power of two alignment. This is not widely supported by assemblers.
799 // FIXME: Parameterize this based on MAI.
801 default: llvm_unreachable("Invalid size for machine code value!");
802 case 1: OS << ".balign"; break;
803 case 2: OS << ".balignw"; break;
804 case 4: OS << ".balignl"; break;
805 case 8: llvm_unreachable("Unsupported alignment size!");
808 OS << ' ' << ByteAlignment;
809 OS << ", " << truncateToSize(Value, ValueSize);
811 OS << ", " << MaxBytesToEmit;
815 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
816 unsigned MaxBytesToEmit) {
817 // Emit with a text fill value.
818 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
822 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
823 unsigned char Value) {
824 // FIXME: Verify that Offset is associated with the current section.
825 OS << ".org " << *Offset << ", " << (unsigned) Value;
831 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
832 assert(MAI->hasSingleParameterDotFile());
834 PrintQuotedString(Filename, OS);
838 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
844 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
845 unsigned NumFiles = Table.getMCDwarfFiles().size();
846 FileNo = Table.getFile(Directory, Filename, FileNo);
849 if (NumFiles == Table.getMCDwarfFiles().size())
852 SmallString<128> FullPathName;
854 if (!UseDwarfDirectory && !Directory.empty()) {
855 if (sys::path::is_absolute(Filename))
858 FullPathName = Directory;
859 sys::path::append(FullPathName, Filename);
861 Filename = FullPathName;
865 OS << "\t.file\t" << FileNo << ' ';
866 if (!Directory.empty()) {
867 PrintQuotedString(Directory, OS);
870 PrintQuotedString(Filename, OS);
876 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
877 unsigned Column, unsigned Flags,
879 unsigned Discriminator,
880 StringRef FileName) {
881 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
882 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
883 OS << " basic_block";
884 if (Flags & DWARF2_FLAG_PROLOGUE_END)
885 OS << " prologue_end";
886 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
887 OS << " epilogue_begin";
889 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
890 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
893 if (Flags & DWARF2_FLAG_IS_STMT)
900 OS << " isa " << Isa;
902 OS << " discriminator " << Discriminator;
905 OS.PadToColumn(MAI->getCommentColumn());
906 OS << MAI->getCommentString() << ' ' << FileName << ':'
907 << Line << ':' << Column;
910 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
911 Isa, Discriminator, FileName);
914 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
915 // Always use the zeroth line table, since asm syntax only supports one line
917 return MCStreamer::getDwarfLineTableSymbol(0);
920 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
921 assert(MAI->hasIdentDirective() && ".ident directive not supported");
923 PrintQuotedString(IdentString, OS);
927 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
928 MCStreamer::EmitCFISections(EH, Debug);
929 OS << "\t.cfi_sections ";
933 OS << ", .debug_frame";
935 OS << ".debug_frame";
941 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
942 OS << "\t.cfi_startproc";
948 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
949 MCStreamer::EmitCFIEndProcImpl(Frame);
950 OS << "\t.cfi_endproc";
954 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
955 if (!MAI->useDwarfRegNumForCFI()) {
956 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
957 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
958 InstPrinter->printRegName(OS, LLVMRegister);
964 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
965 MCStreamer::EmitCFIDefCfa(Register, Offset);
966 OS << "\t.cfi_def_cfa ";
967 EmitRegisterName(Register);
968 OS << ", " << Offset;
972 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
973 MCStreamer::EmitCFIDefCfaOffset(Offset);
974 OS << "\t.cfi_def_cfa_offset " << Offset;
978 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
979 MCStreamer::EmitCFIDefCfaRegister(Register);
980 OS << "\t.cfi_def_cfa_register ";
981 EmitRegisterName(Register);
985 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
986 this->MCStreamer::EmitCFIOffset(Register, Offset);
987 OS << "\t.cfi_offset ";
988 EmitRegisterName(Register);
989 OS << ", " << Offset;
993 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
995 MCStreamer::EmitCFIPersonality(Sym, Encoding);
996 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1000 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1001 MCStreamer::EmitCFILsda(Sym, Encoding);
1002 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1006 void MCAsmStreamer::EmitCFIRememberState() {
1007 MCStreamer::EmitCFIRememberState();
1008 OS << "\t.cfi_remember_state";
1012 void MCAsmStreamer::EmitCFIRestoreState() {
1013 MCStreamer::EmitCFIRestoreState();
1014 OS << "\t.cfi_restore_state";
1018 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1019 MCStreamer::EmitCFISameValue(Register);
1020 OS << "\t.cfi_same_value ";
1021 EmitRegisterName(Register);
1025 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1026 MCStreamer::EmitCFIRelOffset(Register, Offset);
1027 OS << "\t.cfi_rel_offset ";
1028 EmitRegisterName(Register);
1029 OS << ", " << Offset;
1033 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1034 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1035 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1039 void MCAsmStreamer::EmitCFISignalFrame() {
1040 MCStreamer::EmitCFISignalFrame();
1041 OS << "\t.cfi_signal_frame";
1045 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1046 MCStreamer::EmitCFIUndefined(Register);
1047 OS << "\t.cfi_undefined " << Register;
1051 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1052 MCStreamer::EmitCFIRegister(Register1, Register2);
1053 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1057 void MCAsmStreamer::EmitCFIWindowSave() {
1058 MCStreamer::EmitCFIWindowSave();
1059 OS << "\t.cfi_window_save";
1063 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1064 MCStreamer::EmitWinCFIStartProc(Symbol);
1066 OS << ".seh_proc " << *Symbol;
1070 void MCAsmStreamer::EmitWinCFIEndProc() {
1071 MCStreamer::EmitWinCFIEndProc();
1073 OS << "\t.seh_endproc";
1077 void MCAsmStreamer::EmitWinCFIStartChained() {
1078 MCStreamer::EmitWinCFIStartChained();
1080 OS << "\t.seh_startchained";
1084 void MCAsmStreamer::EmitWinCFIEndChained() {
1085 MCStreamer::EmitWinCFIEndChained();
1087 OS << "\t.seh_endchained";
1091 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1093 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1095 OS << "\t.seh_handler " << *Sym;
1103 void MCAsmStreamer::EmitWinEHHandlerData() {
1104 MCStreamer::EmitWinEHHandlerData();
1106 // Switch sections. Don't call SwitchSection directly, because that will
1107 // cause the section switch to be visible in the emitted assembly.
1108 // We only do this so the section switch that terminates the handler
1109 // data block is visible.
1110 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1112 WinEH::UnwindEmitter::getXDataSection(CurFrame->Function, getContext());
1113 SwitchSectionNoChange(XData);
1115 OS << "\t.seh_handlerdata";
1119 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1120 MCStreamer::EmitWinCFIPushReg(Register);
1122 OS << "\t.seh_pushreg " << Register;
1126 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1127 MCStreamer::EmitWinCFISetFrame(Register, Offset);
1129 OS << "\t.seh_setframe " << Register << ", " << Offset;
1133 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1134 MCStreamer::EmitWinCFIAllocStack(Size);
1136 OS << "\t.seh_stackalloc " << Size;
1140 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1141 MCStreamer::EmitWinCFISaveReg(Register, Offset);
1143 OS << "\t.seh_savereg " << Register << ", " << Offset;
1147 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1148 MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1150 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1154 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1155 MCStreamer::EmitWinCFIPushFrame(Code);
1157 OS << "\t.seh_pushframe";
1163 void MCAsmStreamer::EmitWinCFIEndProlog(void) {
1164 MCStreamer::EmitWinCFIEndProlog();
1166 OS << "\t.seh_endprologue";
1170 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1171 const MCSubtargetInfo &STI) {
1172 raw_ostream &OS = GetCommentOS();
1173 SmallString<256> Code;
1174 SmallVector<MCFixup, 4> Fixups;
1175 raw_svector_ostream VecOS(Code);
1176 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1179 // If we are showing fixups, create symbolic markers in the encoded
1180 // representation. We do this by making a per-bit map to the fixup item index,
1181 // then trying to display it as nicely as possible.
1182 SmallVector<uint8_t, 64> FixupMap;
1183 FixupMap.resize(Code.size() * 8);
1184 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1187 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1188 MCFixup &F = Fixups[i];
1189 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1190 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1191 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1192 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1193 FixupMap[Index] = 1 + i;
1197 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1198 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1199 OS << "encoding: [";
1200 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1204 // See if all bits are the same map entry.
1205 uint8_t MapEntry = FixupMap[i * 8 + 0];
1206 for (unsigned j = 1; j != 8; ++j) {
1207 if (FixupMap[i * 8 + j] == MapEntry)
1210 MapEntry = uint8_t(~0U);
1214 if (MapEntry != uint8_t(~0U)) {
1215 if (MapEntry == 0) {
1216 OS << format("0x%02x", uint8_t(Code[i]));
1219 // FIXME: Some of the 8 bits require fix up.
1220 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1221 << char('A' + MapEntry - 1) << '\'';
1223 OS << char('A' + MapEntry - 1);
1226 // Otherwise, write out in binary.
1228 for (unsigned j = 8; j--;) {
1229 unsigned Bit = (Code[i] >> j) & 1;
1232 if (MAI->isLittleEndian())
1233 FixupBit = i * 8 + j;
1235 FixupBit = i * 8 + (7-j);
1237 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1238 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1239 OS << char('A' + MapEntry - 1);
1247 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1248 MCFixup &F = Fixups[i];
1249 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1250 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1251 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1255 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1256 assert(getCurrentSection().first &&
1257 "Cannot emit contents before setting section!");
1259 // Show the encoding in a comment if we have a code emitter.
1261 AddEncodingComment(Inst, STI);
1263 // Show the MCInst if enabled.
1265 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1266 GetCommentOS() << "\n";
1269 InstPrinter->printInst(&Inst, OS, "", STI);
1274 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1275 OS << "\t.bundle_align_mode " << AlignPow2;
1279 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1280 OS << "\t.bundle_lock";
1282 OS << " align_to_end";
1286 void MCAsmStreamer::EmitBundleUnlock() {
1287 OS << "\t.bundle_unlock";
1291 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1292 /// the specified string in the output .s file. This capability is
1293 /// indicated by the hasRawTextSupport() predicate.
1294 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1295 if (!String.empty() && String.back() == '\n')
1296 String = String.substr(0, String.size()-1);
1301 void MCAsmStreamer::FinishImpl() {
1302 // If we are generating dwarf for assembly source files dump out the sections.
1303 if (getContext().getGenDwarfForAssembly())
1304 MCGenDwarfInfo::Emit(this);
1306 // Emit the label for the line table, if requested - since the rest of the
1307 // line table will be defined by .loc/.file directives, and not emitted
1308 // directly, the label is the only work required here.
1309 auto &Tables = getContext().getMCDwarfLineTables();
1310 if (!Tables.empty()) {
1311 assert(Tables.size() == 1 && "asm output only supports one line table");
1312 if (auto *Label = Tables.begin()->second.getLabel()) {
1313 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1319 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1320 std::unique_ptr<formatted_raw_ostream> OS,
1321 bool isVerboseAsm, bool useDwarfDirectory,
1322 MCInstPrinter *IP, MCCodeEmitter *CE,
1323 MCAsmBackend *MAB, bool ShowInst) {
1324 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1325 useDwarfDirectory, IP, CE, MAB, ShowInst);