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 enum EHSymbolFlags { EHGlobal = 1,
57 EHWeakDefinition = 1 << 1,
58 EHPrivateExtern = 1 << 2 };
59 DenseMap<const MCSymbol*, unsigned> FlagMap;
61 void EmitRegisterName(int64_t Register);
62 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
63 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
66 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
67 bool isVerboseAsm, bool useDwarfDirectory,
68 MCInstPrinter *printer, MCCodeEmitter *emitter,
69 MCAsmBackend *asmbackend, bool showInst)
70 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
71 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
72 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
73 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
74 if (InstPrinter && IsVerboseAsm)
75 InstPrinter->setCommentStream(CommentStream);
78 inline void EmitEOL() {
79 // If we don't have any comments, just emit a \n.
86 void EmitCommentsAndEOL();
88 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
90 bool isVerboseAsm() const override { return IsVerboseAsm; }
92 /// hasRawTextSupport - We support EmitRawText.
93 bool hasRawTextSupport() const override { return true; }
95 /// AddComment - Add a comment that can be emitted to the generated .s
96 /// file if applicable as a QoI issue to make the output of the compiler
97 /// more readable. This only affects the MCAsmStreamer, and only when
98 /// verbose assembly output is enabled.
99 void AddComment(const Twine &T) override;
101 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
102 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
104 /// GetCommentOS - Return a raw_ostream that comments can be written to.
105 /// Unlike AddComment, you are required to terminate comments with \n if you
107 raw_ostream &GetCommentOS() override {
109 return nulls(); // Discard comments unless in verbose asm mode.
110 return CommentStream;
113 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
115 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
116 void AddBlankLine() override {
120 /// @name MCStreamer Interface
123 void ChangeSection(const MCSection *Section,
124 const MCExpr *Subsection) override;
126 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
127 void EmitLabel(MCSymbol *Symbol) override;
128 void EmitDebugLabel(MCSymbol *Symbol) override;
130 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
131 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
132 void EmitDataRegion(MCDataRegionType Kind) override;
133 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
134 unsigned Update) override;
135 void EmitThumbFunc(MCSymbol *Func) override;
137 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
138 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
139 void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
140 const MCSymbol *Label,
141 unsigned PointerSize) override;
142 void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
143 const MCSymbol *Label) override;
145 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
147 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
148 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
149 void EmitCOFFSymbolStorageClass(int StorageClass) override;
150 void EmitCOFFSymbolType(int Type) override;
151 void EndCOFFSymbolDef() override;
152 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
153 void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
154 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
155 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
156 unsigned ByteAlignment) override;
158 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
160 /// @param Symbol - The common symbol to emit.
161 /// @param Size - The size of the common symbol.
162 /// @param ByteAlignment - The alignment of the common symbol in bytes.
163 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
164 unsigned ByteAlignment) override;
166 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = nullptr,
167 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
169 void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
170 uint64_t Size, unsigned ByteAlignment = 0) override;
172 void EmitBytes(StringRef Data) override;
174 void EmitValueImpl(const MCExpr *Value, unsigned Size,
175 const SMLoc &Loc = SMLoc()) override;
176 void EmitIntValue(uint64_t Value, unsigned Size) override;
178 void EmitULEB128Value(const MCExpr *Value) override;
180 void EmitSLEB128Value(const MCExpr *Value) override;
182 void EmitGPRel64Value(const MCExpr *Value) override;
184 void EmitGPRel32Value(const MCExpr *Value) override;
187 void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
189 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
190 unsigned ValueSize = 1,
191 unsigned MaxBytesToEmit = 0) override;
193 void EmitCodeAlignment(unsigned ByteAlignment,
194 unsigned MaxBytesToEmit = 0) override;
196 bool EmitValueToOffset(const MCExpr *Offset,
197 unsigned char Value = 0) override;
199 void EmitFileDirective(StringRef Filename) override;
200 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
202 unsigned CUID = 0) override;
203 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
204 unsigned Column, unsigned Flags,
205 unsigned Isa, unsigned Discriminator,
206 StringRef FileName) override;
207 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
209 void EmitIdent(StringRef IdentString) override;
210 void EmitCFISections(bool EH, bool Debug) override;
211 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
212 void EmitCFIDefCfaOffset(int64_t Offset) override;
213 void EmitCFIDefCfaRegister(int64_t Register) override;
214 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
215 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
216 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
217 void EmitCFIRememberState() override;
218 void EmitCFIRestoreState() override;
219 void EmitCFISameValue(int64_t Register) override;
220 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
221 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
222 void EmitCFISignalFrame() override;
223 void EmitCFIUndefined(int64_t Register) override;
224 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
225 void EmitCFIWindowSave() override;
227 void EmitWin64EHStartProc(const MCSymbol *Symbol) override;
228 void EmitWin64EHEndProc() override;
229 void EmitWin64EHStartChained() override;
230 void EmitWin64EHEndChained() override;
231 void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
232 bool Except) override;
233 void EmitWin64EHHandlerData() override;
234 void EmitWin64EHPushReg(unsigned Register) override;
235 void EmitWin64EHSetFrame(unsigned Register, unsigned Offset) override;
236 void EmitWin64EHAllocStack(unsigned Size) override;
237 void EmitWin64EHSaveReg(unsigned Register, unsigned Offset) override;
238 void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) override;
239 void EmitWin64EHPushFrame(bool Code) override;
240 void EmitWin64EHEndProlog() override;
242 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
244 void EmitBundleAlignMode(unsigned AlignPow2) override;
245 void EmitBundleLock(bool AlignToEnd) override;
246 void EmitBundleUnlock() override;
248 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
249 /// the specified string in the output .s file. This capability is
250 /// indicated by the hasRawTextSupport() predicate.
251 void EmitRawTextImpl(StringRef String) override;
253 void FinishImpl() override;
256 } // end anonymous namespace.
258 /// AddComment - Add a comment that can be emitted to the generated .s
259 /// file if applicable as a QoI issue to make the output of the compiler
260 /// more readable. This only affects the MCAsmStreamer, and only when
261 /// verbose assembly output is enabled.
262 void MCAsmStreamer::AddComment(const Twine &T) {
263 if (!IsVerboseAsm) return;
265 // Make sure that CommentStream is flushed.
266 CommentStream.flush();
268 T.toVector(CommentToEmit);
269 // Each comment goes on its own line.
270 CommentToEmit.push_back('\n');
272 // Tell the comment stream that the vector changed underneath it.
273 CommentStream.resync();
276 void MCAsmStreamer::EmitCommentsAndEOL() {
277 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
282 CommentStream.flush();
283 StringRef Comments = CommentToEmit.str();
285 assert(Comments.back() == '\n' &&
286 "Comment array not newline terminated");
288 // Emit a line of comments.
289 OS.PadToColumn(MAI->getCommentColumn());
290 size_t Position = Comments.find('\n');
291 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
293 Comments = Comments.substr(Position+1);
294 } while (!Comments.empty());
296 CommentToEmit.clear();
297 // Tell the comment stream that the vector changed underneath it.
298 CommentStream.resync();
301 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
302 assert(Bytes && "Invalid size!");
303 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
306 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
309 OS << MAI->getCommentString() << T;
313 void MCAsmStreamer::ChangeSection(const MCSection *Section,
314 const MCExpr *Subsection) {
315 assert(Section && "Cannot switch to a null section!");
316 Section->PrintSwitchToSection(*MAI, OS, Subsection);
319 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
320 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
321 MCStreamer::EmitLabel(Symbol);
323 OS << *Symbol << MAI->getLabelSuffix();
327 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
328 StringRef str = MCLOHIdToName(Kind);
331 int NbArgs = MCLOHIdToNbArgs(Kind);
332 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
333 assert(str != "" && "Invalid LOH name");
336 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
338 for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end();
348 void MCAsmStreamer::EmitDebugLabel(MCSymbol *Symbol) {
349 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
350 MCStreamer::EmitDebugLabel(Symbol);
352 OS << *Symbol << MAI->getDebugLabelSuffix();
356 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
358 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
359 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
360 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
361 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
362 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
367 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
368 assert(!Options.empty() && "At least one option is required!");
369 OS << "\t.linker_option \"" << Options[0] << '"';
370 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
371 ie = Options.end(); it != ie; ++it) {
372 OS << ", " << '"' << *it << '"';
377 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
378 if (!MAI->doesSupportDataRegionDirectives())
381 case MCDR_DataRegion: OS << "\t.data_region"; break;
382 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
383 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
384 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
385 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
390 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
391 unsigned Minor, unsigned Update) {
393 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
394 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
396 OS << " " << Major << ", " << Minor;
398 OS << ", " << Update;
402 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
403 // This needs to emit to a temporary string to get properly quoted
404 // MCSymbols when they have spaces in them.
405 OS << "\t.thumb_func";
406 // Only Mach-O hasSubsectionsViaSymbols()
407 if (MAI->hasSubsectionsViaSymbols())
412 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
413 OS << *Symbol << " = " << *Value;
416 MCStreamer::EmitAssignment(Symbol, Value);
419 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
420 OS << ".weakref " << *Alias << ", " << *Symbol;
424 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
425 const MCSymbol *LastLabel,
426 const MCSymbol *Label,
427 unsigned PointerSize) {
428 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
431 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
432 const MCSymbol *Label) {
433 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
434 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
435 AddrDelta = ForceExpAbs(AddrDelta);
436 EmitValue(AddrDelta, 4);
440 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
441 MCSymbolAttr Attribute) {
443 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
444 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
445 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
446 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
447 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
448 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
449 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
450 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
451 if (!MAI->hasDotTypeDotSizeDirective())
452 return false; // Symbol attribute not supported
453 OS << "\t.type\t" << *Symbol << ','
454 << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
456 default: return false;
457 case MCSA_ELF_TypeFunction: OS << "function"; break;
458 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
459 case MCSA_ELF_TypeObject: OS << "object"; break;
460 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
461 case MCSA_ELF_TypeCommon: OS << "common"; break;
462 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
463 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
467 case MCSA_Global: // .globl/.global
468 OS << MAI->getGlobalDirective();
469 FlagMap[Symbol] |= EHGlobal;
471 case MCSA_Hidden: OS << "\t.hidden\t"; break;
472 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
473 case MCSA_Internal: OS << "\t.internal\t"; break;
474 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
475 case MCSA_Local: OS << "\t.local\t"; break;
476 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
477 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
478 case MCSA_PrivateExtern:
479 OS << "\t.private_extern\t";
480 FlagMap[Symbol] |= EHPrivateExtern;
482 case MCSA_Protected: OS << "\t.protected\t"; break;
483 case MCSA_Reference: OS << "\t.reference\t"; break;
484 case MCSA_Weak: OS << "\t.weak\t"; break;
485 case MCSA_WeakDefinition:
486 OS << "\t.weak_definition\t";
487 FlagMap[Symbol] |= EHWeakDefinition;
490 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
491 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
500 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
501 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
505 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
506 OS << "\t.def\t " << *Symbol << ';';
510 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
511 OS << "\t.scl\t" << StorageClass << ';';
515 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
516 OS << "\t.type\t" << Type << ';';
520 void MCAsmStreamer::EndCOFFSymbolDef() {
525 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
526 OS << "\t.secidx\t" << *Symbol;
530 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
531 OS << "\t.secrel32\t" << *Symbol;
535 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
536 assert(MAI->hasDotTypeDotSizeDirective());
537 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
540 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
541 unsigned ByteAlignment) {
542 // Common symbols do not belong to any actual section.
543 AssignSection(Symbol, nullptr);
545 OS << "\t.comm\t" << *Symbol << ',' << Size;
546 if (ByteAlignment != 0) {
547 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
548 OS << ',' << ByteAlignment;
550 OS << ',' << Log2_32(ByteAlignment);
555 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
557 /// @param Symbol - The common symbol to emit.
558 /// @param Size - The size of the common symbol.
559 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
560 unsigned ByteAlign) {
561 // Common symbols do not belong to any actual section.
562 AssignSection(Symbol, nullptr);
564 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
566 switch (MAI->getLCOMMDirectiveAlignmentType()) {
567 case LCOMM::NoAlignment:
568 llvm_unreachable("alignment not supported on .lcomm!");
569 case LCOMM::ByteAlignment:
570 OS << ',' << ByteAlign;
572 case LCOMM::Log2Alignment:
573 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
574 OS << ',' << Log2_32(ByteAlign);
581 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
582 uint64_t Size, unsigned ByteAlignment) {
584 AssignSection(Symbol, Section);
586 // Note: a .zerofill directive does not switch sections.
589 // This is a mach-o specific directive.
590 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
591 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
594 OS << ',' << *Symbol << ',' << Size;
595 if (ByteAlignment != 0)
596 OS << ',' << Log2_32(ByteAlignment);
601 // .tbss sym, size, align
602 // This depends that the symbol has already been mangled from the original,
604 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
605 uint64_t Size, unsigned ByteAlignment) {
606 AssignSection(Symbol, Section);
608 assert(Symbol && "Symbol shouldn't be NULL!");
609 // Instead of using the Section we'll just use the shortcut.
610 // This is a mach-o specific directive and section.
611 OS << ".tbss " << *Symbol << ", " << Size;
613 // Output align if we have it. We default to 1 so don't bother printing
615 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
620 static inline char toOctal(int X) { return (X&7)+'0'; }
622 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
625 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
626 unsigned char C = Data[i];
627 if (C == '"' || C == '\\') {
628 OS << '\\' << (char)C;
632 if (isprint((unsigned char)C)) {
638 case '\b': OS << "\\b"; break;
639 case '\f': OS << "\\f"; break;
640 case '\n': OS << "\\n"; break;
641 case '\r': OS << "\\r"; break;
642 case '\t': OS << "\\t"; break;
645 OS << toOctal(C >> 6);
646 OS << toOctal(C >> 3);
647 OS << toOctal(C >> 0);
656 void MCAsmStreamer::EmitBytes(StringRef Data) {
657 assert(getCurrentSection().first &&
658 "Cannot emit contents before setting section!");
659 if (Data.empty()) return;
661 if (Data.size() == 1) {
662 OS << MAI->getData8bitsDirective();
663 OS << (unsigned)(unsigned char)Data[0];
668 // If the data ends with 0 and the target supports .asciz, use it, otherwise
670 if (MAI->getAscizDirective() && Data.back() == 0) {
671 OS << MAI->getAscizDirective();
672 Data = Data.substr(0, Data.size()-1);
674 OS << MAI->getAsciiDirective();
677 PrintQuotedString(Data, OS);
681 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
682 EmitValue(MCConstantExpr::Create(Value, getContext()), Size);
685 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
687 assert(Size <= 8 && "Invalid size");
688 assert(getCurrentSection().first &&
689 "Cannot emit contents before setting section!");
690 const char *Directive = nullptr;
693 case 1: Directive = MAI->getData8bitsDirective(); break;
694 case 2: Directive = MAI->getData16bitsDirective(); break;
695 case 4: Directive = MAI->getData32bitsDirective(); break;
696 case 8: Directive = MAI->getData64bitsDirective(); break;
701 if (!Value->EvaluateAsAbsolute(IntValue))
702 report_fatal_error("Don't know how to emit this value.");
704 // We couldn't handle the requested integer size so we fallback by breaking
705 // the request down into several, smaller, integers. Since sizes greater
706 // than eight are invalid and size equivalent to eight should have been
707 // handled earlier, we use four bytes as our largest piece of granularity.
708 bool IsLittleEndian = MAI->isLittleEndian();
709 for (unsigned Emitted = 0; Emitted != Size;) {
710 unsigned Remaining = Size - Emitted;
711 // The size of our partial emission must be a power of two less than
713 unsigned EmissionSize = PowerOf2Floor(Remaining);
714 if (EmissionSize > 4)
716 // Calculate the byte offset of our partial emission taking into account
717 // the endianness of the target.
718 unsigned ByteOffset =
719 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
720 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
721 // We truncate our partial emission to fit within the bounds of the
722 // emission domain. This produces nicer output and silences potential
723 // truncation warnings when round tripping through another assembler.
724 ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8);
725 EmitIntValue(ValueToEmit, EmissionSize);
726 Emitted += EmissionSize;
731 assert(Directive && "Invalid size for machine code value!");
732 OS << Directive << *Value;
736 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
738 if (Value->EvaluateAsAbsolute(IntValue)) {
739 EmitULEB128IntValue(IntValue);
742 assert(MAI->hasLEB128() && "Cannot print a .uleb");
743 OS << ".uleb128 " << *Value;
747 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
749 if (Value->EvaluateAsAbsolute(IntValue)) {
750 EmitSLEB128IntValue(IntValue);
753 assert(MAI->hasLEB128() && "Cannot print a .sleb");
754 OS << ".sleb128 " << *Value;
758 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
759 assert(MAI->getGPRel64Directive() != nullptr);
760 OS << MAI->getGPRel64Directive() << *Value;
764 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
765 assert(MAI->getGPRel32Directive() != nullptr);
766 OS << MAI->getGPRel32Directive() << *Value;
771 /// EmitFill - Emit NumBytes bytes worth of the value specified by
772 /// FillValue. This implements directives such as '.space'.
773 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
774 if (NumBytes == 0) return;
776 if (const char *ZeroDirective = MAI->getZeroDirective()) {
777 OS << ZeroDirective << NumBytes;
779 OS << ',' << (int)FillValue;
784 // Emit a byte at a time.
785 MCStreamer::EmitFill(NumBytes, FillValue);
788 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
790 unsigned MaxBytesToEmit) {
791 // Some assemblers don't support non-power of two alignments, so we always
792 // emit alignments as a power of two if possible.
793 if (isPowerOf2_32(ByteAlignment)) {
796 llvm_unreachable("Invalid size for machine code value!");
807 llvm_unreachable("Unsupported alignment size!");
810 if (MAI->getAlignmentIsInBytes())
813 OS << Log2_32(ByteAlignment);
815 if (Value || MaxBytesToEmit) {
817 OS.write_hex(truncateToSize(Value, ValueSize));
820 OS << ", " << MaxBytesToEmit;
826 // Non-power of two alignment. This is not widely supported by assemblers.
827 // FIXME: Parameterize this based on MAI.
829 default: llvm_unreachable("Invalid size for machine code value!");
830 case 1: OS << ".balign"; break;
831 case 2: OS << ".balignw"; break;
832 case 4: OS << ".balignl"; break;
833 case 8: llvm_unreachable("Unsupported alignment size!");
836 OS << ' ' << ByteAlignment;
837 OS << ", " << truncateToSize(Value, ValueSize);
839 OS << ", " << MaxBytesToEmit;
843 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
844 unsigned MaxBytesToEmit) {
845 // Emit with a text fill value.
846 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
850 bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
851 unsigned char Value) {
852 // FIXME: Verify that Offset is associated with the current section.
853 OS << ".org " << *Offset << ", " << (unsigned) Value;
859 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
860 assert(MAI->hasSingleParameterDotFile());
862 PrintQuotedString(Filename, OS);
866 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
872 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
873 unsigned NumFiles = Table.getMCDwarfFiles().size();
874 FileNo = Table.getFile(Directory, Filename, FileNo);
877 if (NumFiles == Table.getMCDwarfFiles().size())
880 SmallString<128> FullPathName;
882 if (!UseDwarfDirectory && !Directory.empty()) {
883 if (sys::path::is_absolute(Filename))
886 FullPathName = Directory;
887 sys::path::append(FullPathName, Filename);
889 Filename = FullPathName;
893 OS << "\t.file\t" << FileNo << ' ';
894 if (!Directory.empty()) {
895 PrintQuotedString(Directory, OS);
898 PrintQuotedString(Filename, OS);
904 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
905 unsigned Column, unsigned Flags,
907 unsigned Discriminator,
908 StringRef FileName) {
909 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
910 Isa, Discriminator, FileName);
911 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
912 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
913 OS << " basic_block";
914 if (Flags & DWARF2_FLAG_PROLOGUE_END)
915 OS << " prologue_end";
916 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
917 OS << " epilogue_begin";
919 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
920 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
923 if (Flags & DWARF2_FLAG_IS_STMT)
930 OS << " isa " << Isa;
932 OS << " discriminator " << Discriminator;
935 OS.PadToColumn(MAI->getCommentColumn());
936 OS << MAI->getCommentString() << ' ' << FileName << ':'
937 << Line << ':' << Column;
942 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
943 // Always use the zeroth line table, since asm syntax only supports one line
945 return MCStreamer::getDwarfLineTableSymbol(0);
948 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
949 assert(MAI->hasIdentDirective() && ".ident directive not supported");
951 PrintQuotedString(IdentString, OS);
955 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
956 MCStreamer::EmitCFISections(EH, Debug);
957 OS << "\t.cfi_sections ";
961 OS << ", .debug_frame";
963 OS << ".debug_frame";
969 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
970 OS << "\t.cfi_startproc";
976 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
977 // Put a dummy non-null value in Frame.End to mark that this frame has been
979 Frame.End = (MCSymbol *) 1;
981 OS << "\t.cfi_endproc";
985 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
986 if (InstPrinter && !MAI->useDwarfRegNumForCFI()) {
987 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
988 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
989 InstPrinter->printRegName(OS, LLVMRegister);
995 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
996 MCStreamer::EmitCFIDefCfa(Register, Offset);
997 OS << "\t.cfi_def_cfa ";
998 EmitRegisterName(Register);
999 OS << ", " << Offset;
1003 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1004 MCStreamer::EmitCFIDefCfaOffset(Offset);
1005 OS << "\t.cfi_def_cfa_offset " << Offset;
1009 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1010 MCStreamer::EmitCFIDefCfaRegister(Register);
1011 OS << "\t.cfi_def_cfa_register ";
1012 EmitRegisterName(Register);
1016 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1017 this->MCStreamer::EmitCFIOffset(Register, Offset);
1018 OS << "\t.cfi_offset ";
1019 EmitRegisterName(Register);
1020 OS << ", " << Offset;
1024 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1025 unsigned Encoding) {
1026 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1027 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
1031 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1032 MCStreamer::EmitCFILsda(Sym, Encoding);
1033 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
1037 void MCAsmStreamer::EmitCFIRememberState() {
1038 MCStreamer::EmitCFIRememberState();
1039 OS << "\t.cfi_remember_state";
1043 void MCAsmStreamer::EmitCFIRestoreState() {
1044 MCStreamer::EmitCFIRestoreState();
1045 OS << "\t.cfi_restore_state";
1049 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1050 MCStreamer::EmitCFISameValue(Register);
1051 OS << "\t.cfi_same_value ";
1052 EmitRegisterName(Register);
1056 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1057 MCStreamer::EmitCFIRelOffset(Register, Offset);
1058 OS << "\t.cfi_rel_offset ";
1059 EmitRegisterName(Register);
1060 OS << ", " << Offset;
1064 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1065 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1066 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1070 void MCAsmStreamer::EmitCFISignalFrame() {
1071 MCStreamer::EmitCFISignalFrame();
1072 OS << "\t.cfi_signal_frame";
1076 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1077 MCStreamer::EmitCFIUndefined(Register);
1078 OS << "\t.cfi_undefined " << Register;
1082 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1083 MCStreamer::EmitCFIRegister(Register1, Register2);
1084 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1088 void MCAsmStreamer::EmitCFIWindowSave() {
1089 MCStreamer::EmitCFIWindowSave();
1090 OS << "\t.cfi_window_save";
1094 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
1095 MCStreamer::EmitWin64EHStartProc(Symbol);
1097 OS << ".seh_proc " << *Symbol;
1101 void MCAsmStreamer::EmitWin64EHEndProc() {
1102 MCStreamer::EmitWin64EHEndProc();
1104 OS << "\t.seh_endproc";
1108 void MCAsmStreamer::EmitWin64EHStartChained() {
1109 MCStreamer::EmitWin64EHStartChained();
1111 OS << "\t.seh_startchained";
1115 void MCAsmStreamer::EmitWin64EHEndChained() {
1116 MCStreamer::EmitWin64EHEndChained();
1118 OS << "\t.seh_endchained";
1122 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
1124 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
1126 OS << "\t.seh_handler " << *Sym;
1134 static const MCSection *getWin64EHTableSection(StringRef suffix,
1135 MCContext &context) {
1136 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1137 /// this duplicate code in MCWin64EH.cpp.
1139 return context.getObjectFileInfo()->getXDataSection();
1140 return context.getCOFFSection((".xdata"+suffix).str(),
1141 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1142 COFF::IMAGE_SCN_MEM_READ |
1143 COFF::IMAGE_SCN_MEM_WRITE,
1144 SectionKind::getDataRel());
1147 void MCAsmStreamer::EmitWin64EHHandlerData() {
1148 MCStreamer::EmitWin64EHHandlerData();
1150 // Switch sections. Don't call SwitchSection directly, because that will
1151 // cause the section switch to be visible in the emitted assembly.
1152 // We only do this so the section switch that terminates the handler
1153 // data block is visible.
1154 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1155 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1156 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1158 SwitchSectionNoChange(xdataSect);
1160 OS << "\t.seh_handlerdata";
1164 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1165 MCStreamer::EmitWin64EHPushReg(Register);
1167 OS << "\t.seh_pushreg ";
1168 EmitRegisterName(Register);
1172 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1173 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1175 OS << "\t.seh_setframe ";
1176 EmitRegisterName(Register);
1177 OS << ", " << Offset;
1181 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1182 MCStreamer::EmitWin64EHAllocStack(Size);
1184 OS << "\t.seh_stackalloc " << Size;
1188 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1189 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1191 OS << "\t.seh_savereg ";
1192 EmitRegisterName(Register);
1193 OS << ", " << Offset;
1197 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1198 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1200 OS << "\t.seh_savexmm ";
1201 EmitRegisterName(Register);
1202 OS << ", " << Offset;
1206 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1207 MCStreamer::EmitWin64EHPushFrame(Code);
1209 OS << "\t.seh_pushframe";
1215 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1216 MCStreamer::EmitWin64EHEndProlog();
1218 OS << "\t.seh_endprologue";
1222 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1223 const MCSubtargetInfo &STI) {
1224 raw_ostream &OS = GetCommentOS();
1225 SmallString<256> Code;
1226 SmallVector<MCFixup, 4> Fixups;
1227 raw_svector_ostream VecOS(Code);
1228 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1231 // If we are showing fixups, create symbolic markers in the encoded
1232 // representation. We do this by making a per-bit map to the fixup item index,
1233 // then trying to display it as nicely as possible.
1234 SmallVector<uint8_t, 64> FixupMap;
1235 FixupMap.resize(Code.size() * 8);
1236 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1239 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1240 MCFixup &F = Fixups[i];
1241 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1242 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1243 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1244 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1245 FixupMap[Index] = 1 + i;
1249 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1250 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1251 OS << "encoding: [";
1252 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1256 // See if all bits are the same map entry.
1257 uint8_t MapEntry = FixupMap[i * 8 + 0];
1258 for (unsigned j = 1; j != 8; ++j) {
1259 if (FixupMap[i * 8 + j] == MapEntry)
1262 MapEntry = uint8_t(~0U);
1266 if (MapEntry != uint8_t(~0U)) {
1267 if (MapEntry == 0) {
1268 OS << format("0x%02x", uint8_t(Code[i]));
1271 // FIXME: Some of the 8 bits require fix up.
1272 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1273 << char('A' + MapEntry - 1) << '\'';
1275 OS << char('A' + MapEntry - 1);
1278 // Otherwise, write out in binary.
1280 for (unsigned j = 8; j--;) {
1281 unsigned Bit = (Code[i] >> j) & 1;
1284 if (MAI->isLittleEndian())
1285 FixupBit = i * 8 + j;
1287 FixupBit = i * 8 + (7-j);
1289 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1290 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1291 OS << char('A' + MapEntry - 1);
1299 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1300 MCFixup &F = Fixups[i];
1301 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1302 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1303 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1307 void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
1308 assert(getCurrentSection().first &&
1309 "Cannot emit contents before setting section!");
1311 // Show the encoding in a comment if we have a code emitter.
1313 AddEncodingComment(Inst, STI);
1315 // Show the MCInst if enabled.
1317 Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n ");
1318 GetCommentOS() << "\n";
1321 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1323 InstPrinter->printInst(&Inst, OS, "");
1325 Inst.print(OS, MAI);
1329 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1330 OS << "\t.bundle_align_mode " << AlignPow2;
1334 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1335 OS << "\t.bundle_lock";
1337 OS << " align_to_end";
1341 void MCAsmStreamer::EmitBundleUnlock() {
1342 OS << "\t.bundle_unlock";
1346 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1347 /// the specified string in the output .s file. This capability is
1348 /// indicated by the hasRawTextSupport() predicate.
1349 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1350 if (!String.empty() && String.back() == '\n')
1351 String = String.substr(0, String.size()-1);
1356 void MCAsmStreamer::FinishImpl() {
1357 // If we are generating dwarf for assembly source files dump out the sections.
1358 if (getContext().getGenDwarfForAssembly())
1359 MCGenDwarfInfo::Emit(this);
1361 // Emit the label for the line table, if requested - since the rest of the
1362 // line table will be defined by .loc/.file directives, and not emitted
1363 // directly, the label is the only work required here.
1364 auto &Tables = getContext().getMCDwarfLineTables();
1365 if (!Tables.empty()) {
1366 assert(Tables.size() == 1 && "asm output only supports one line table");
1367 if (auto *Label = Tables.begin()->second.getLabel()) {
1368 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1374 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1375 formatted_raw_ostream &OS,
1376 bool isVerboseAsm, bool useDwarfDirectory,
1377 MCInstPrinter *IP, MCCodeEmitter *CE,
1378 MCAsmBackend *MAB, bool ShowInst) {
1379 return new MCAsmStreamer(Context, OS, isVerboseAsm, useDwarfDirectory, IP, CE,