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/SmallString.h"
12 #include "llvm/ADT/STLExtras.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/MCSymbol.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"
35 #include <unordered_map>
40 class MCAsmStreamer : public MCStreamer {
42 formatted_raw_ostream &OS;
45 std::unique_ptr<MCInstPrinter> InstPrinter;
46 std::unique_ptr<MCCodeEmitter> Emitter;
47 std::unique_ptr<MCAsmBackend> AsmBackend;
49 SmallString<128> CommentToEmit;
50 raw_svector_ostream CommentStream;
52 unsigned IsVerboseAsm : 1;
53 unsigned ShowInst : 1;
54 unsigned UseDwarfDirectory : 1;
56 void EmitRegisterName(int64_t Register);
57 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
58 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
61 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
62 bool isVerboseAsm, bool useDwarfDirectory,
63 MCInstPrinter *printer, MCCodeEmitter *emitter,
64 MCAsmBackend *asmbackend, bool showInst)
65 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
66 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
67 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
68 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
69 if (InstPrinter && IsVerboseAsm)
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(const MCSection *Section,
119 const MCExpr *Subsection) override;
121 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
122 void EmitLabel(MCSymbol *Symbol) override;
123 void EmitDebugLabel(MCSymbol *Symbol) override;
125 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
126 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
127 void EmitDataRegion(MCDataRegionType Kind) override;
128 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
129 unsigned Update) override;
130 void EmitThumbFunc(MCSymbol *Func) override;
132 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
133 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
134 void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
135 const MCSymbol *Label,
136 unsigned PointerSize) override;
137 void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
138 const MCSymbol *Label) override;
140 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
142 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
143 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
144 void EmitCOFFSymbolStorageClass(int StorageClass) override;
145 void EmitCOFFSymbolType(int Type) override;
146 void EndCOFFSymbolDef() override;
147 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
148 void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
149 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
150 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
151 unsigned ByteAlignment) override;
153 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
155 /// @param Symbol - The common symbol to emit.
156 /// @param Size - The size of the common symbol.
157 /// @param ByteAlignment - The alignment of the common symbol in bytes.
158 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
159 unsigned ByteAlignment) override;
161 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = nullptr,
162 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
164 void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
165 uint64_t Size, unsigned ByteAlignment = 0) override;
167 void EmitBytes(StringRef Data) override;
169 void EmitValueImpl(const MCExpr *Value, unsigned Size,
170 const SMLoc &Loc = SMLoc()) override;
171 void EmitIntValue(uint64_t Value, unsigned Size) override;
173 void EmitULEB128Value(const MCExpr *Value) override;
175 void EmitSLEB128Value(const MCExpr *Value) override;
177 void EmitGPRel64Value(const MCExpr *Value) override;
179 void EmitGPRel32Value(const MCExpr *Value) override;
182 void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
184 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
185 unsigned ValueSize = 1,
186 unsigned MaxBytesToEmit = 0) override;
188 void EmitCodeAlignment(unsigned ByteAlignment,
189 unsigned MaxBytesToEmit = 0) override;
191 bool EmitValueToOffset(const MCExpr *Offset,
192 unsigned char Value = 0) override;
194 void EmitFileDirective(StringRef Filename) override;
195 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
197 unsigned CUID = 0) override;
198 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
199 unsigned Column, unsigned Flags,
200 unsigned Isa, unsigned Discriminator,
201 StringRef FileName) override;
202 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
204 void EmitIdent(StringRef IdentString) override;
205 void EmitCFISections(bool EH, bool Debug) override;
206 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
207 void EmitCFIDefCfaOffset(int64_t Offset) override;
208 void EmitCFIDefCfaRegister(int64_t Register) override;
209 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
210 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
211 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
212 void EmitCFIRememberState() override;
213 void EmitCFIRestoreState() override;
214 void EmitCFISameValue(int64_t Register) override;
215 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
216 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
217 void EmitCFISignalFrame() override;
218 void EmitCFIUndefined(int64_t Register) override;
219 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
220 void EmitCFIWindowSave() override;
222 void EmitWin64EHStartProc(const MCSymbol *Symbol) override;
223 void EmitWin64EHEndProc() override;
224 void EmitWin64EHStartChained() override;
225 void EmitWin64EHEndChained() override;
226 void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
227 bool Except) override;
228 void EmitWin64EHHandlerData() override;
229 void EmitWin64EHPushReg(unsigned Register) override;
230 void EmitWin64EHSetFrame(unsigned Register, unsigned Offset) override;
231 void EmitWin64EHAllocStack(unsigned Size) override;
232 void EmitWin64EHSaveReg(unsigned Register, unsigned Offset) override;
233 void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) override;
234 void EmitWin64EHPushFrame(bool Code) override;
235 void EmitWin64EHEndProlog() override;
237 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
239 void EmitBundleAlignMode(unsigned AlignPow2) override;
240 void EmitBundleLock(bool AlignToEnd) override;
241 void EmitBundleUnlock() override;
243 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
244 /// the specified string in the output .s file. This capability is
245 /// indicated by the hasRawTextSupport() predicate.
246 void EmitRawTextImpl(StringRef String) override;
248 void FinishImpl() override;
251 } // end anonymous namespace.
253 /// AddComment - Add a comment that can be emitted to the generated .s
254 /// file if applicable as a QoI issue to make the output of the compiler
255 /// more readable. This only affects the MCAsmStreamer, and only when
256 /// verbose assembly output is enabled.
257 void MCAsmStreamer::AddComment(const Twine &T) {
258 if (!IsVerboseAsm) return;
260 // Make sure that CommentStream is flushed.
261 CommentStream.flush();
263 T.toVector(CommentToEmit);
264 // Each comment goes on its own line.
265 CommentToEmit.push_back('\n');
267 // Tell the comment stream that the vector changed underneath it.
268 CommentStream.resync();
271 void MCAsmStreamer::EmitCommentsAndEOL() {
272 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
277 CommentStream.flush();
278 StringRef Comments = CommentToEmit.str();
280 assert(Comments.back() == '\n' &&
281 "Comment array not newline terminated");
283 // Emit a line of comments.
284 OS.PadToColumn(MAI->getCommentColumn());
285 size_t Position = Comments.find('\n');
286 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
288 Comments = Comments.substr(Position+1);
289 } while (!Comments.empty());
291 CommentToEmit.clear();
292 // Tell the comment stream that the vector changed underneath it.
293 CommentStream.resync();
296 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
297 assert(Bytes && "Invalid size!");
298 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
301 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
304 OS << MAI->getCommentString() << T;
308 void MCAsmStreamer::ChangeSection(const MCSection *Section,
309 const MCExpr *Subsection) {
310 assert(Section && "Cannot switch to a null section!");
311 Section->PrintSwitchToSection(*MAI, OS, Subsection);
314 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
315 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
316 MCStreamer::EmitLabel(Symbol);
318 OS << *Symbol << MAI->getLabelSuffix();
322 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
323 StringRef str = MCLOHIdToName(Kind);
326 int NbArgs = MCLOHIdToNbArgs(Kind);
327 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
328 assert(str != "" && "Invalid LOH name");
331 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
333 for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
343 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
344 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
345 MCStreamer::EmitDebugLabel(Symbol);
347 OS << *Symbol << MAI->getDebugLabelSuffix();
351 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
353 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
354 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
355 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
356 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
357 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
362 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
363 assert(!Options.empty() && "At least one option is required!");
364 OS << "\t.linker_option \"" << Options[0] << '"';
365 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
366 ie = Options.end(); it != ie; ++it) {
367 OS << ", " << '"' << *it << '"';
372 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
373 if (!MAI->doesSupportDataRegionDirectives())
376 case MCDR_DataRegion: OS << "\t.data_region"; break;
377 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
378 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
379 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
380 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
385 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
386 unsigned Minor, unsigned Update) {
388 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
389 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
391 OS << " " << Major << ", " << Minor;
393 OS << ", " << Update;
397 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
398 // This needs to emit to a temporary string to get properly quoted
399 // MCSymbols when they have spaces in them.
400 OS << "\t.thumb_func";
401 // Only Mach-O hasSubsectionsViaSymbols()
402 if (MAI->hasSubsectionsViaSymbols())
407 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
408 OS << *Symbol << " = " << *Value;
411 MCStreamer::EmitAssignment(Symbol, Value);
414 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
415 OS << ".weakref " << *Alias << ", " << *Symbol;
419 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
420 const MCSymbol *LastLabel,
421 const MCSymbol *Label,
422 unsigned PointerSize) {
423 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
426 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
427 const MCSymbol *Label) {
428 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
429 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
430 AddrDelta = ForceExpAbs(AddrDelta);
431 EmitValue(AddrDelta, 4);
435 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
436 MCSymbolAttr Attribute) {
438 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
439 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
440 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
441 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
442 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
443 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
444 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
445 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
446 if (!MAI->hasDotTypeDotSizeDirective())
447 return false; // Symbol attribute not supported
448 OS << "\t.type\t" << *Symbol << ','
449 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
451 default: return false;
452 case MCSA_ELF_TypeFunction: OS << "function"; break;
453 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
454 case MCSA_ELF_TypeObject: OS << "object"; break;
455 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
456 case MCSA_ELF_TypeCommon: OS << "common"; break;
457 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
458 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
462 case MCSA_Global: // .globl/.global
463 OS << MAI->getGlobalDirective();
465 case MCSA_Hidden: OS << "\t.hidden\t"; break;
466 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
467 case MCSA_Internal: OS << "\t.internal\t"; break;
468 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
469 case MCSA_Local: OS << "\t.local\t"; break;
470 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
471 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
472 case MCSA_PrivateExtern:
473 OS << "\t.private_extern\t";
475 case MCSA_Protected: OS << "\t.protected\t"; break;
476 case MCSA_Reference: OS << "\t.reference\t"; break;
477 case MCSA_Weak: OS << "\t.weak\t"; break;
478 case MCSA_WeakDefinition:
479 OS << "\t.weak_definition\t";
482 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
483 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
492 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
493 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
497 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
498 OS << "\t.def\t " << *Symbol << ';';
502 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
503 OS << "\t.scl\t" << StorageClass << ';';
507 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
508 OS << "\t.type\t" << Type << ';';
512 void MCAsmStreamer::EndCOFFSymbolDef() {
517 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
518 OS << "\t.secidx\t" << *Symbol;
522 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
523 OS << "\t.secrel32\t" << *Symbol;
527 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
528 assert(MAI->hasDotTypeDotSizeDirective());
529 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
532 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
533 unsigned ByteAlignment) {
534 // Common symbols do not belong to any actual section.
535 AssignSection(Symbol, nullptr);
537 OS << "\t.comm\t" << *Symbol << ',' << Size;
538 if (ByteAlignment != 0) {
539 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
540 OS << ',' << ByteAlignment;
542 OS << ',' << Log2_32(ByteAlignment);
547 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
549 /// @param Symbol - The common symbol to emit.
550 /// @param Size - The size of the common symbol.
551 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
552 unsigned ByteAlign) {
553 // Common symbols do not belong to any actual section.
554 AssignSection(Symbol, nullptr);
556 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
558 switch (MAI->getLCOMMDirectiveAlignmentType()) {
559 case LCOMM::NoAlignment:
560 llvm_unreachable("alignment not supported on .lcomm!");
561 case LCOMM::ByteAlignment:
562 OS << ',' << ByteAlign;
564 case LCOMM::Log2Alignment:
565 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
566 OS << ',' << Log2_32(ByteAlign);
573 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
574 uint64_t Size, unsigned ByteAlignment) {
576 AssignSection(Symbol, Section);
578 // Note: a .zerofill directive does not switch sections.
581 // This is a mach-o specific directive.
582 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
583 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
586 OS << ',' << *Symbol << ',' << Size;
587 if (ByteAlignment != 0)
588 OS << ',' << Log2_32(ByteAlignment);
593 // .tbss sym, size, align
594 // This depends that the symbol has already been mangled from the original,
596 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
597 uint64_t Size, unsigned ByteAlignment) {
598 AssignSection(Symbol, Section);
600 assert(Symbol && "Symbol shouldn't be NULL!");
601 // Instead of using the Section we'll just use the shortcut.
602 // This is a mach-o specific directive and section.
603 OS << ".tbss " << *Symbol << ", " << Size;
605 // Output align if we have it. We default to 1 so don't bother printing
607 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
612 static inline char toOctal(int X) { return (X&7)+'0'; }
614 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
617 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
618 unsigned char C = Data[i];
619 if (C == '"' || C == '\\') {
620 OS << '\\' << (char)C;
624 if (isprint((unsigned char)C)) {
630 case '\b': OS << "\\b"; break;
631 case '\f': OS << "\\f"; break;
632 case '\n': OS << "\\n"; break;
633 case '\r': OS << "\\r"; break;
634 case '\t': OS << "\\t"; break;
637 OS << toOctal(C >> 6);
638 OS << toOctal(C >> 3);
639 OS << toOctal(C >> 0);
648 void MCAsmStreamer::EmitBytes(StringRef Data) {
649 assert(getCurrentSection().first &&
650 "Cannot emit contents before setting section!");
651 if (Data.empty()) return;
653 if (Data.size() == 1) {
654 OS << MAI->getData8bitsDirective();
655 OS << (unsigned)(unsigned char)Data[0];
660 // If the data ends with 0 and the target supports .asciz, use it, otherwise
662 if (MAI->getAscizDirective() && Data.back() == 0) {
663 OS << MAI->getAscizDirective();
664 Data = Data.substr(0, Data.size()-1);
666 OS << MAI->getAsciiDirective();
669 PrintQuotedString(Data, OS);
673 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
674 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
677 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
679 assert(Size <= 8 && "Invalid size");
680 assert(getCurrentSection().first &&
681 "Cannot emit contents before setting section!");
682 const char *Directive = nullptr;
685 case 1: Directive = MAI->getData8bitsDirective(); break;
686 case 2: Directive = MAI->getData16bitsDirective(); break;
687 case 4: Directive = MAI->getData32bitsDirective(); break;
688 case 8: Directive = MAI->getData64bitsDirective(); break;
693 if (!Value->EvaluateAsAbsolute(IntValue))
694 report_fatal_error("Don't know how to emit this value.");
696 // We couldn't handle the requested integer size so we fallback by breaking
697 // the request down into several, smaller, integers. Since sizes greater
698 // than eight are invalid and size equivalent to eight should have been
699 // handled earlier, we use four bytes as our largest piece of granularity.
700 bool IsLittleEndian = MAI->isLittleEndian();
701 for (unsigned Emitted = 0; Emitted != Size;) {
702 unsigned Remaining = Size - Emitted;
703 // The size of our partial emission must be a power of two less than
705 unsigned EmissionSize = PowerOf2Floor(Remaining);
706 if (EmissionSize > 4)
708 // Calculate the byte offset of our partial emission taking into account
709 // the endianness of the target.
710 unsigned ByteOffset =
711 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
712 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
713 // We truncate our partial emission to fit within the bounds of the
714 // emission domain. This produces nicer output and silences potential
715 // truncation warnings when round tripping through another assembler.
716 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
717 EmitIntValue(ValueToEmit, EmissionSize);
718 Emitted += EmissionSize;
723 assert(Directive && "Invalid size for machine code value!");
724 OS << Directive << *Value;
728 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
730 if (Value->EvaluateAsAbsolute(IntValue)) {
731 EmitULEB128IntValue(IntValue);
734 assert(MAI->hasLEB128() && "Cannot print a .uleb");
735 OS << ".uleb128 " << *Value;
739 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
741 if (Value->EvaluateAsAbsolute(IntValue)) {
742 EmitSLEB128IntValue(IntValue);
745 assert(MAI->hasLEB128() && "Cannot print a .sleb");
746 OS << ".sleb128 " << *Value;
750 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
751 assert(MAI->getGPRel64Directive() != nullptr);
752 OS << MAI->getGPRel64Directive() << *Value;
756 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
757 assert(MAI->getGPRel32Directive() != nullptr);
758 OS << MAI->getGPRel32Directive() << *Value;
763 /// EmitFill - Emit NumBytes bytes worth of the value specified by
764 /// FillValue. This implements directives such as '.space'.
765 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
766 if (NumBytes == 0) return;
768 if (const char *ZeroDirective = MAI->getZeroDirective()) {
769 OS << ZeroDirective << NumBytes;
771 OS << ',' << (int)FillValue;
776 // Emit a byte at a time.
777 MCStreamer::EmitFill(NumBytes, FillValue);
780 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
782 unsigned MaxBytesToEmit) {
783 // Some assemblers don't support non-power of two alignments, so we always
784 // emit alignments as a power of two if possible.
785 if (isPowerOf2_32(ByteAlignment)) {
788 llvm_unreachable("Invalid size for machine code value!");
799 llvm_unreachable("Unsupported alignment size!");
802 if (MAI->getAlignmentIsInBytes())
805 OS << Log2_32(ByteAlignment);
807 if (Value || MaxBytesToEmit) {
809 OS.write_hex(truncateToSize(Value, ValueSize));
812 OS << ", " << MaxBytesToEmit;
818 // Non-power of two alignment. This is not widely supported by assemblers.
819 // FIXME: Parameterize this based on MAI.
821 default: llvm_unreachable("Invalid size for machine code value!");
822 case 1: OS << ".balign"; break;
823 case 2: OS << ".balignw"; break;
824 case 4: OS << ".balignl"; break;
825 case 8: llvm_unreachable("Unsupported alignment size!");
828 OS << ' ' << ByteAlignment;
829 OS << ", " << truncateToSize(Value, ValueSize);
831 OS << ", " << MaxBytesToEmit;
835 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
836 unsigned MaxBytesToEmit) {
837 // Emit with a text fill value.
838 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
842 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
843 unsigned char Value) {
844 // FIXME: Verify that Offset is associated with the current section.
845 OS << ".org " << *Offset << ", " << (unsigned) Value;
851 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
852 assert(MAI->hasSingleParameterDotFile());
854 PrintQuotedString(Filename, OS);
858 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
864 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
865 unsigned NumFiles = Table.getMCDwarfFiles().size();
866 FileNo = Table.getFile(Directory, Filename, FileNo);
869 if (NumFiles == Table.getMCDwarfFiles().size())
872 SmallString<128> FullPathName;
874 if (!UseDwarfDirectory && !Directory.empty()) {
875 if (sys::path::is_absolute(Filename))
878 FullPathName = Directory;
879 sys::path::append(FullPathName, Filename);
881 Filename = FullPathName;
885 OS << "\t.file\t" << FileNo << ' ';
886 if (!Directory.empty()) {
887 PrintQuotedString(Directory, OS);
890 PrintQuotedString(Filename, OS);
896 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
897 unsigned Column, unsigned Flags,
899 unsigned Discriminator,
900 StringRef FileName) {
901 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
902 Isa, Discriminator, FileName);
903 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
904 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
905 OS << " basic_block";
906 if (Flags & DWARF2_FLAG_PROLOGUE_END)
907 OS << " prologue_end";
908 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
909 OS << " epilogue_begin";
911 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
912 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
915 if (Flags & DWARF2_FLAG_IS_STMT)
922 OS << " isa " << Isa;
924 OS << " discriminator " << Discriminator;
927 OS.PadToColumn(MAI->getCommentColumn());
928 OS << MAI->getCommentString() << ' ' << FileName << ':'
929 << Line << ':' << Column;
934 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
935 // Always use the zeroth line table, since asm syntax only supports one line
937 return MCStreamer::getDwarfLineTableSymbol(0);
940 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
941 assert(MAI->hasIdentDirective() && ".ident directive not supported");
943 PrintQuotedString(IdentString, OS);
947 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
948 MCStreamer::EmitCFISections(EH, Debug);
949 OS << "\t.cfi_sections ";
953 OS << ", .debug_frame";
955 OS << ".debug_frame";
961 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
962 OS << "\t.cfi_startproc";
968 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
969 // Put a dummy non-null value in Frame.End to mark that this frame has been
971 Frame.End = (MCSymbol *) 1;
973 OS << "\t.cfi_endproc";
977 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
978 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
979 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
980 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
981 InstPrinter->printRegName(OS, LLVMRegister);
987 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
988 MCStreamer::EmitCFIDefCfa(Register, Offset);
989 OS << "\t.cfi_def_cfa ";
990 EmitRegisterName(Register);
991 OS << ", " << Offset;
995 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
996 MCStreamer::EmitCFIDefCfaOffset(Offset);
997 OS << "\t.cfi_def_cfa_offset " << Offset;
1001 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1002 MCStreamer::EmitCFIDefCfaRegister(Register);
1003 OS << "\t.cfi_def_cfa_register ";
1004 EmitRegisterName(Register);
1008 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1009 this->MCStreamer::EmitCFIOffset(Register, Offset);
1010 OS << "\t.cfi_offset ";
1011 EmitRegisterName(Register);
1012 OS << ", " << Offset;
1016 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1017 unsigned Encoding) {
1018 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1019 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1023 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1024 MCStreamer::EmitCFILsda(Sym, Encoding);
1025 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1029 void MCAsmStreamer::EmitCFIRememberState() {
1030 MCStreamer::EmitCFIRememberState();
1031 OS << "\t.cfi_remember_state";
1035 void MCAsmStreamer::EmitCFIRestoreState() {
1036 MCStreamer::EmitCFIRestoreState();
1037 OS << "\t.cfi_restore_state";
1041 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1042 MCStreamer::EmitCFISameValue(Register);
1043 OS << "\t.cfi_same_value ";
1044 EmitRegisterName(Register);
1048 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1049 MCStreamer::EmitCFIRelOffset(Register, Offset);
1050 OS << "\t.cfi_rel_offset ";
1051 EmitRegisterName(Register);
1052 OS << ", " << Offset;
1056 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1057 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1058 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1062 void MCAsmStreamer::EmitCFISignalFrame() {
1063 MCStreamer::EmitCFISignalFrame();
1064 OS << "\t.cfi_signal_frame";
1068 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1069 MCStreamer::EmitCFIUndefined(Register);
1070 OS << "\t.cfi_undefined " << Register;
1074 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1075 MCStreamer::EmitCFIRegister(Register1, Register2);
1076 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1080 void MCAsmStreamer::EmitCFIWindowSave() {
1081 MCStreamer::EmitCFIWindowSave();
1082 OS << "\t.cfi_window_save";
1086 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1087 MCStreamer::EmitWin64EHStartProc(Symbol);
1089 OS << ".seh_proc " << *Symbol;
1093 void MCAsmStreamer::EmitWin64EHEndProc() {
1094 MCStreamer::EmitWin64EHEndProc();
1096 OS << "\t.seh_endproc";
1100 void MCAsmStreamer::EmitWin64EHStartChained() {
1101 MCStreamer::EmitWin64EHStartChained();
1103 OS << "\t.seh_startchained";
1107 void MCAsmStreamer::EmitWin64EHEndChained() {
1108 MCStreamer::EmitWin64EHEndChained();
1110 OS << "\t.seh_endchained";
1114 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1116 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1118 OS << "\t.seh_handler " << *Sym;
1126 static const MCSection *getWin64EHTableSection(StringRef suffix,
1127 MCContext &context) {
1128 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1129 /// this duplicate code in MCWin64EH.cpp.
1131 return context.getObjectFileInfo()->getXDataSection();
1132 return context.getCOFFSection((".xdata"+suffix).str(),
1133 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1134 COFF::IMAGE_SCN_MEM_READ |
1135 COFF::IMAGE_SCN_MEM_WRITE,
1136 SectionKind::getDataRel());
1139 void MCAsmStreamer::EmitWin64EHHandlerData() {
1140 MCStreamer::EmitWin64EHHandlerData();
1142 // Switch sections. Don't call SwitchSection directly, because that will
1143 // cause the section switch to be visible in the emitted assembly.
1144 // We only do this so the section switch that terminates the handler
1145 // data block is visible.
1146 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1147 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1148 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1150 SwitchSectionNoChange(xdataSect);
1152 OS << "\t.seh_handlerdata";
1156 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1157 MCStreamer::EmitWin64EHPushReg(Register);
1159 OS << "\t.seh_pushreg ";
1160 EmitRegisterName(Register);
1164 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1165 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1167 OS << "\t.seh_setframe ";
1168 EmitRegisterName(Register);
1169 OS << ", " << Offset;
1173 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1174 MCStreamer::EmitWin64EHAllocStack(Size);
1176 OS << "\t.seh_stackalloc " << Size;
1180 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1181 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1183 OS << "\t.seh_savereg ";
1184 EmitRegisterName(Register);
1185 OS << ", " << Offset;
1189 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1190 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1192 OS << "\t.seh_savexmm ";
1193 EmitRegisterName(Register);
1194 OS << ", " << Offset;
1198 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1199 MCStreamer::EmitWin64EHPushFrame(Code);
1201 OS << "\t.seh_pushframe";
1207 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1208 MCStreamer::EmitWin64EHEndProlog();
1210 OS << "\t.seh_endprologue";
1214 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1215 const MCSubtargetInfo &STI) {
1216 raw_ostream &OS = GetCommentOS();
1217 SmallString<256> Code;
1218 SmallVector<MCFixup, 4> Fixups;
1219 raw_svector_ostream VecOS(Code);
1220 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1223 // If we are showing fixups, create symbolic markers in the encoded
1224 // representation. We do this by making a per-bit map to the fixup item index,
1225 // then trying to display it as nicely as possible.
1226 SmallVector<uint8_t, 64> FixupMap;
1227 FixupMap.resize(Code.size() * 8);
1228 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1231 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1232 MCFixup &F = Fixups[i];
1233 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1234 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1235 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1236 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1237 FixupMap[Index] = 1 + i;
1241 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1242 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1243 OS << "encoding: [";
1244 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1248 // See if all bits are the same map entry.
1249 uint8_t MapEntry = FixupMap[i * 8 + 0];
1250 for (unsigned j = 1; j != 8; ++j) {
1251 if (FixupMap[i * 8 + j] == MapEntry)
1254 MapEntry = uint8_t(~0U);
1258 if (MapEntry != uint8_t(~0U)) {
1259 if (MapEntry == 0) {
1260 OS << format("0x%02x", uint8_t(Code[i]));
1263 // FIXME: Some of the 8 bits require fix up.
1264 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1265 << char('A' + MapEntry - 1) << '\'';
1267 OS << char('A' + MapEntry - 1);
1270 // Otherwise, write out in binary.
1272 for (unsigned j = 8; j--;) {
1273 unsigned Bit = (Code[i] >> j) & 1;
1276 if (MAI->isLittleEndian())
1277 FixupBit = i * 8 + j;
1279 FixupBit = i * 8 + (7-j);
1281 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1282 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1283 OS << char('A' + MapEntry - 1);
1291 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1292 MCFixup &F = Fixups[i];
1293 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1294 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1295 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1299 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1300 assert(getCurrentSection().first &&
1301 "Cannot emit contents before setting section!");
1303 // Show the encoding in a comment if we have a code emitter.
1305 AddEncodingComment(Inst, STI);
1307 // Show the MCInst if enabled.
1309 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1310 GetCommentOS() << "\n";
1313 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1315 InstPrinter->printInst(&Inst, OS, "");
1317 Inst.print(OS, MAI);
1321 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1322 OS << "\t.bundle_align_mode " << AlignPow2;
1326 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1327 OS << "\t.bundle_lock";
1329 OS << " align_to_end";
1333 void MCAsmStreamer::EmitBundleUnlock() {
1334 OS << "\t.bundle_unlock";
1338 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1339 /// the specified string in the output .s file. This capability is
1340 /// indicated by the hasRawTextSupport() predicate.
1341 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1342 if (!String.empty() && String.back() == '\n')
1343 String = String.substr(0, String.size()-1);
1348 void MCAsmStreamer::FinishImpl() {
1349 // If we are generating dwarf for assembly source files dump out the sections.
1350 if (getContext().getGenDwarfForAssembly())
1351 MCGenDwarfInfo::Emit(this);
1353 // Emit the label for the line table, if requested - since the rest of the
1354 // line table will be defined by .loc/.file directives, and not emitted
1355 // directly, the label is the only work required here.
1356 auto &Tables = getContext().getMCDwarfLineTables();
1357 if (!Tables.empty()) {
1358 assert(Tables.size() == 1 && "asm output only supports one line table");
1359 if (auto *Label = Tables.begin()->second.getLabel()) {
1360 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1366 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1367 formatted_raw_ostream &OS,
1368 bool isVerboseAsm, bool useDwarfDirectory,
1369 MCInstPrinter *IP, MCCodeEmitter *CE,
1370 MCAsmBackend *MAB, bool ShowInst) {
1371 return new MCAsmStreamer(Context, OS, isVerboseAsm, useDwarfDirectory, IP, CE,