1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCCodeView.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/MCStreamer.h"
28 #include "llvm/MC/MCSymbolELF.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
42 class MCAsmStreamer final : public MCStreamer {
43 std::unique_ptr<formatted_raw_ostream> OSOwner;
44 formatted_raw_ostream &OS;
46 std::unique_ptr<MCInstPrinter> InstPrinter;
47 std::unique_ptr<MCCodeEmitter> Emitter;
48 std::unique_ptr<MCAsmBackend> AsmBackend;
50 SmallString<128> ExplicitCommentToEmit;
51 SmallString<128> CommentToEmit;
52 raw_svector_ostream CommentStream;
54 unsigned IsVerboseAsm : 1;
55 unsigned ShowInst : 1;
56 unsigned UseDwarfDirectory : 1;
58 void EmitRegisterName(int64_t Register);
59 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
60 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
63 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
64 bool isVerboseAsm, bool useDwarfDirectory,
65 MCInstPrinter *printer, MCCodeEmitter *emitter,
66 MCAsmBackend *asmbackend, bool showInst)
67 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
68 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
69 AsmBackend(asmbackend), CommentStream(CommentToEmit),
70 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
71 UseDwarfDirectory(useDwarfDirectory) {
74 InstPrinter->setCommentStream(CommentStream);
77 inline void EmitEOL() {
78 // Dump Explicit Comments here.
79 emitExplicitComments();
80 // If we don't have any comments, just emit a \n.
88 void EmitSyntaxDirective() override;
90 void EmitCommentsAndEOL();
92 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
94 bool isVerboseAsm() const override { return IsVerboseAsm; }
96 /// hasRawTextSupport - We support EmitRawText.
97 bool hasRawTextSupport() const override { return true; }
99 /// AddComment - Add a comment that can be emitted to the generated .s
100 /// file if applicable as a QoI issue to make the output of the compiler
101 /// more readable. This only affects the MCAsmStreamer, and only when
102 /// verbose assembly output is enabled.
103 void AddComment(const Twine &T, bool EOL = true) override;
105 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
106 /// If PrintSchedInfo - is true then the comment sched:[x:y] should
107 // be added to output if it's being supported by target
108 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &,
109 bool PrintSchedInfo);
111 /// GetCommentOS - Return a raw_ostream that comments can be written to.
112 /// Unlike AddComment, you are required to terminate comments with \n if you
114 raw_ostream &GetCommentOS() override {
116 return nulls(); // Discard comments unless in verbose asm mode.
117 return CommentStream;
120 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
122 void addExplicitComment(const Twine &T) override;
123 void emitExplicitComments() override;
125 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
126 void AddBlankLine() override {
130 /// @name MCStreamer Interface
133 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
135 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
136 void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
138 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
139 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
140 void EmitDataRegion(MCDataRegionType Kind) override;
141 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
142 unsigned Update) override;
143 void EmitThumbFunc(MCSymbol *Func) override;
145 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
146 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
147 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
149 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
150 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
151 void EmitCOFFSymbolStorageClass(int StorageClass) override;
152 void EmitCOFFSymbolType(int Type) override;
153 void EndCOFFSymbolDef() override;
154 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
155 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
156 void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
157 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
158 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
159 unsigned ByteAlignment) override;
161 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
163 /// @param Symbol - The common symbol to emit.
164 /// @param Size - The size of the common symbol.
165 /// @param ByteAlignment - The alignment of the common symbol in bytes.
166 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
167 unsigned ByteAlignment) override;
169 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
170 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
172 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
173 unsigned ByteAlignment = 0) override;
175 void EmitBinaryData(StringRef Data) override;
177 void EmitBytes(StringRef Data) override;
179 void EmitValueImpl(const MCExpr *Value, unsigned Size,
180 SMLoc Loc = SMLoc()) override;
181 void EmitIntValue(uint64_t Value, unsigned Size) override;
183 void EmitULEB128Value(const MCExpr *Value) override;
185 void EmitSLEB128Value(const MCExpr *Value) override;
187 void EmitDTPRel32Value(const MCExpr *Value) override;
188 void EmitDTPRel64Value(const MCExpr *Value) override;
189 void EmitTPRel32Value(const MCExpr *Value) override;
190 void EmitTPRel64Value(const MCExpr *Value) override;
192 void EmitGPRel64Value(const MCExpr *Value) override;
194 void EmitGPRel32Value(const MCExpr *Value) override;
197 void emitFill(uint64_t NumBytes, uint8_t FillValue) override;
199 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
200 SMLoc Loc = SMLoc()) override;
202 void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override;
204 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
205 SMLoc Loc = SMLoc()) override;
207 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
208 unsigned ValueSize = 1,
209 unsigned MaxBytesToEmit = 0) override;
211 void EmitCodeAlignment(unsigned ByteAlignment,
212 unsigned MaxBytesToEmit = 0) override;
214 void emitValueToOffset(const MCExpr *Offset,
218 void EmitFileDirective(StringRef Filename) override;
219 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
221 unsigned CUID = 0) override;
222 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
223 unsigned Column, unsigned Flags,
224 unsigned Isa, unsigned Discriminator,
225 StringRef FileName) override;
226 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
228 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename) override;
229 bool EmitCVFuncIdDirective(unsigned FuncId) override;
230 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
231 unsigned IAFile, unsigned IALine,
232 unsigned IACol, SMLoc Loc) override;
233 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
234 unsigned Column, bool PrologueEnd, bool IsStmt,
235 StringRef FileName, SMLoc Loc) override;
236 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
237 const MCSymbol *FnEnd) override;
238 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
239 unsigned SourceFileId,
240 unsigned SourceLineNum,
241 const MCSymbol *FnStartSym,
242 const MCSymbol *FnEndSym) override;
243 void EmitCVDefRangeDirective(
244 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
245 StringRef FixedSizePortion) override;
246 void EmitCVStringTableDirective() override;
247 void EmitCVFileChecksumsDirective() override;
249 void EmitIdent(StringRef IdentString) override;
250 void EmitCFISections(bool EH, bool Debug) override;
251 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
252 void EmitCFIDefCfaOffset(int64_t Offset) override;
253 void EmitCFIDefCfaRegister(int64_t Register) override;
254 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
255 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
256 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
257 void EmitCFIRememberState() override;
258 void EmitCFIRestoreState() override;
259 void EmitCFISameValue(int64_t Register) override;
260 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
261 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
262 void EmitCFIEscape(StringRef Values) override;
263 void EmitCFIGnuArgsSize(int64_t Size) override;
264 void EmitCFISignalFrame() override;
265 void EmitCFIUndefined(int64_t Register) override;
266 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
267 void EmitCFIWindowSave() override;
269 void EmitWinCFIStartProc(const MCSymbol *Symbol) override;
270 void EmitWinCFIEndProc() override;
271 void EmitWinCFIStartChained() override;
272 void EmitWinCFIEndChained() override;
273 void EmitWinCFIPushReg(unsigned Register) override;
274 void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override;
275 void EmitWinCFIAllocStack(unsigned Size) override;
276 void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override;
277 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override;
278 void EmitWinCFIPushFrame(bool Code) override;
279 void EmitWinCFIEndProlog() override;
281 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override;
282 void EmitWinEHHandlerData() override;
284 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
285 bool PrintSchedInfo) override;
287 void EmitBundleAlignMode(unsigned AlignPow2) override;
288 void EmitBundleLock(bool AlignToEnd) override;
289 void EmitBundleUnlock() override;
291 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
292 const MCExpr *Expr, SMLoc Loc) override;
294 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
295 /// the specified string in the output .s file. This capability is
296 /// indicated by the hasRawTextSupport() predicate.
297 void EmitRawTextImpl(StringRef String) override;
299 void FinishImpl() override;
302 } // end anonymous namespace.
304 /// AddComment - Add a comment that can be emitted to the generated .s
305 /// file if applicable as a QoI issue to make the output of the compiler
306 /// more readable. This only affects the MCAsmStreamer, and only when
307 /// verbose assembly output is enabled.
308 /// By deafult EOL is set to true so that each comment goes on its own line.
309 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
310 if (!IsVerboseAsm) return;
312 T.toVector(CommentToEmit);
315 CommentToEmit.push_back('\n'); // Place comment in a new line.
318 void MCAsmStreamer::EmitCommentsAndEOL() {
319 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
324 StringRef Comments = CommentToEmit;
326 assert(Comments.back() == '\n' &&
327 "Comment array not newline terminated");
329 // Emit a line of comments.
330 OS.PadToColumn(MAI->getCommentColumn());
331 size_t Position = Comments.find('\n');
332 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
334 Comments = Comments.substr(Position+1);
335 } while (!Comments.empty());
337 CommentToEmit.clear();
340 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
341 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
342 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
345 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
348 OS << MAI->getCommentString() << T;
352 void MCAsmStreamer::addExplicitComment(const Twine &T) {
353 StringRef c = T.getSingleStringRef();
354 if (c.equals(StringRef(MAI->getSeparatorString())))
356 if (c.startswith(StringRef("//"))) {
357 ExplicitCommentToEmit.append("\t");
358 ExplicitCommentToEmit.append(MAI->getCommentString());
360 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
361 } else if (c.startswith(StringRef("/*"))) {
362 size_t p = 2, len = c.size() - 2;
363 // emit each line in comment as separate newline.
365 size_t newp = std::min(len, c.find_first_of("\r\n", p));
366 ExplicitCommentToEmit.append("\t");
367 ExplicitCommentToEmit.append(MAI->getCommentString());
368 ExplicitCommentToEmit.append(c.slice(p, newp).str());
369 // If we have another line in this comment add line
371 ExplicitCommentToEmit.append("\n");
374 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
375 ExplicitCommentToEmit.append("\t");
376 ExplicitCommentToEmit.append(c.str());
377 } else if (c.front() == '#') {
379 ExplicitCommentToEmit.append("\t");
380 ExplicitCommentToEmit.append(MAI->getCommentString());
381 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
383 assert(false && "Unexpected Assembly Comment");
384 // full line comments immediately output
385 if (c.back() == '\n')
386 emitExplicitComments();
389 void MCAsmStreamer::emitExplicitComments() {
390 StringRef Comments = ExplicitCommentToEmit;
391 if (!Comments.empty())
393 ExplicitCommentToEmit.clear();
396 void MCAsmStreamer::ChangeSection(MCSection *Section,
397 const MCExpr *Subsection) {
398 assert(Section && "Cannot switch to a null section!");
399 Section->PrintSwitchToSection(
400 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
404 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
405 MCStreamer::EmitLabel(Symbol, Loc);
407 Symbol->print(OS, MAI);
408 OS << MAI->getLabelSuffix();
413 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
414 StringRef str = MCLOHIdToName(Kind);
417 int NbArgs = MCLOHIdToNbArgs(Kind);
418 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
419 assert(str != "" && "Invalid LOH name");
422 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
424 for (const MCSymbol *Arg : Args) {
433 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
435 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
436 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
437 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
438 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
439 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
444 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
445 assert(!Options.empty() && "At least one option is required!");
446 OS << "\t.linker_option \"" << Options[0] << '"';
447 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
448 ie = Options.end(); it != ie; ++it) {
449 OS << ", " << '"' << *it << '"';
454 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
455 if (!MAI->doesSupportDataRegionDirectives())
458 case MCDR_DataRegion: OS << "\t.data_region"; break;
459 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
460 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
461 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
462 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
467 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
468 unsigned Minor, unsigned Update) {
470 case MCVM_WatchOSVersionMin: OS << "\t.watchos_version_min"; break;
471 case MCVM_TvOSVersionMin: OS << "\t.tvos_version_min"; break;
472 case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break;
473 case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break;
475 OS << " " << Major << ", " << Minor;
477 OS << ", " << Update;
481 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
482 // This needs to emit to a temporary string to get properly quoted
483 // MCSymbols when they have spaces in them.
484 OS << "\t.thumb_func";
485 // Only Mach-O hasSubsectionsViaSymbols()
486 if (MAI->hasSubsectionsViaSymbols()) {
488 Func->print(OS, MAI);
493 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
494 Symbol->print(OS, MAI);
496 Value->print(OS, MAI);
500 MCStreamer::EmitAssignment(Symbol, Value);
503 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
505 Alias->print(OS, MAI);
507 Symbol->print(OS, MAI);
511 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
512 MCSymbolAttr Attribute) {
514 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
515 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
516 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
517 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
518 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
519 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
520 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
521 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
522 if (!MAI->hasDotTypeDotSizeDirective())
523 return false; // Symbol attribute not supported
525 Symbol->print(OS, MAI);
526 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
528 default: return false;
529 case MCSA_ELF_TypeFunction: OS << "function"; break;
530 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
531 case MCSA_ELF_TypeObject: OS << "object"; break;
532 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
533 case MCSA_ELF_TypeCommon: OS << "common"; break;
534 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
535 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
539 case MCSA_Global: // .globl/.global
540 OS << MAI->getGlobalDirective();
542 case MCSA_Hidden: OS << "\t.hidden\t"; break;
543 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
544 case MCSA_Internal: OS << "\t.internal\t"; break;
545 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
546 case MCSA_Local: OS << "\t.local\t"; break;
547 case MCSA_NoDeadStrip:
548 if (!MAI->hasNoDeadStrip())
550 OS << "\t.no_dead_strip\t";
552 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
553 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
554 case MCSA_PrivateExtern:
555 OS << "\t.private_extern\t";
557 case MCSA_Protected: OS << "\t.protected\t"; break;
558 case MCSA_Reference: OS << "\t.reference\t"; break;
559 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
560 case MCSA_WeakDefinition:
561 OS << "\t.weak_definition\t";
564 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
565 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
568 Symbol->print(OS, MAI);
574 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
575 OS << ".desc" << ' ';
576 Symbol->print(OS, MAI);
577 OS << ',' << DescValue;
581 void MCAsmStreamer::EmitSyntaxDirective() {
582 if (MAI->getAssemblerDialect() == 1) {
583 OS << "\t.intel_syntax noprefix";
586 // FIXME: Currently emit unprefix'ed registers.
587 // The intel_syntax directive has one optional argument
588 // with may have a value of prefix or noprefix.
591 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
593 Symbol->print(OS, MAI);
598 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
599 OS << "\t.scl\t" << StorageClass << ';';
603 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
604 OS << "\t.type\t" << Type << ';';
608 void MCAsmStreamer::EndCOFFSymbolDef() {
613 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
614 OS << "\t.safeseh\t";
615 Symbol->print(OS, MAI);
619 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
621 Symbol->print(OS, MAI);
625 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
626 OS << "\t.secrel32\t";
627 Symbol->print(OS, MAI);
633 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
634 assert(MAI->hasDotTypeDotSizeDirective());
636 Symbol->print(OS, MAI);
638 Value->print(OS, MAI);
642 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
643 unsigned ByteAlignment) {
645 Symbol->print(OS, MAI);
648 if (ByteAlignment != 0) {
649 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
650 OS << ',' << ByteAlignment;
652 OS << ',' << Log2_32(ByteAlignment);
657 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
659 /// @param Symbol - The common symbol to emit.
660 /// @param Size - The size of the common symbol.
661 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
662 unsigned ByteAlign) {
664 Symbol->print(OS, MAI);
668 switch (MAI->getLCOMMDirectiveAlignmentType()) {
669 case LCOMM::NoAlignment:
670 llvm_unreachable("alignment not supported on .lcomm!");
671 case LCOMM::ByteAlignment:
672 OS << ',' << ByteAlign;
674 case LCOMM::Log2Alignment:
675 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
676 OS << ',' << Log2_32(ByteAlign);
683 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
684 uint64_t Size, unsigned ByteAlignment) {
686 AssignFragment(Symbol, &Section->getDummyFragment());
688 // Note: a .zerofill directive does not switch sections.
691 // This is a mach-o specific directive.
692 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
693 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
697 Symbol->print(OS, MAI);
699 if (ByteAlignment != 0)
700 OS << ',' << Log2_32(ByteAlignment);
705 // .tbss sym, size, align
706 // This depends that the symbol has already been mangled from the original,
708 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
709 uint64_t Size, unsigned ByteAlignment) {
710 AssignFragment(Symbol, &Section->getDummyFragment());
712 assert(Symbol && "Symbol shouldn't be NULL!");
713 // Instead of using the Section we'll just use the shortcut.
714 // This is a mach-o specific directive and section.
716 Symbol->print(OS, MAI);
719 // Output align if we have it. We default to 1 so don't bother printing
721 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
726 static inline char toOctal(int X) { return (X&7)+'0'; }
728 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
731 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
732 unsigned char C = Data[i];
733 if (C == '"' || C == '\\') {
734 OS << '\\' << (char)C;
738 if (isprint((unsigned char)C)) {
744 case '\b': OS << "\\b"; break;
745 case '\f': OS << "\\f"; break;
746 case '\n': OS << "\\n"; break;
747 case '\r': OS << "\\r"; break;
748 case '\t': OS << "\\t"; break;
751 OS << toOctal(C >> 6);
752 OS << toOctal(C >> 3);
753 OS << toOctal(C >> 0);
761 void MCAsmStreamer::EmitBytes(StringRef Data) {
762 assert(getCurrentSectionOnly() &&
763 "Cannot emit contents before setting section!");
764 if (Data.empty()) return;
766 if (Data.size() == 1) {
767 OS << MAI->getData8bitsDirective();
768 OS << (unsigned)(unsigned char)Data[0];
773 // If the data ends with 0 and the target supports .asciz, use it, otherwise
775 if (MAI->getAscizDirective() && Data.back() == 0) {
776 OS << MAI->getAscizDirective();
777 Data = Data.substr(0, Data.size()-1);
779 OS << MAI->getAsciiDirective();
782 PrintQuotedString(Data, OS);
786 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
787 // This is binary data. Print it in a grid of hex bytes for readability.
788 const size_t Cols = 4;
789 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
790 size_t J = I, EJ = std::min(I + Cols, Data.size());
792 OS << MAI->getData8bitsDirective();
793 for (; J < EJ - 1; ++J)
794 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
795 OS << format("0x%02x", uint8_t(Data[J]));
800 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
801 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
804 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
806 assert(Size <= 8 && "Invalid size");
807 assert(getCurrentSectionOnly() &&
808 "Cannot emit contents before setting section!");
809 const char *Directive = nullptr;
812 case 1: Directive = MAI->getData8bitsDirective(); break;
813 case 2: Directive = MAI->getData16bitsDirective(); break;
814 case 4: Directive = MAI->getData32bitsDirective(); break;
815 case 8: Directive = MAI->getData64bitsDirective(); break;
820 if (!Value->evaluateAsAbsolute(IntValue))
821 report_fatal_error("Don't know how to emit this value.");
823 // We couldn't handle the requested integer size so we fallback by breaking
824 // the request down into several, smaller, integers.
825 // Since sizes greater or equal to "Size" are invalid, we use the greatest
826 // power of 2 that is less than "Size" as our largest piece of granularity.
827 bool IsLittleEndian = MAI->isLittleEndian();
828 for (unsigned Emitted = 0; Emitted != Size;) {
829 unsigned Remaining = Size - Emitted;
830 // The size of our partial emission must be a power of two less than
832 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
833 // Calculate the byte offset of our partial emission taking into account
834 // the endianness of the target.
835 unsigned ByteOffset =
836 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
837 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
838 // We truncate our partial emission to fit within the bounds of the
839 // emission domain. This produces nicer output and silences potential
840 // truncation warnings when round tripping through another assembler.
841 uint64_t Shift = 64 - EmissionSize * 8;
842 assert(Shift < static_cast<uint64_t>(
843 std::numeric_limits<unsigned long long>::digits) &&
844 "undefined behavior");
845 ValueToEmit &= ~0ULL >> Shift;
846 EmitIntValue(ValueToEmit, EmissionSize);
847 Emitted += EmissionSize;
852 assert(Directive && "Invalid size for machine code value!");
854 Value->print(OS, MAI);
858 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
860 if (Value->evaluateAsAbsolute(IntValue)) {
861 EmitULEB128IntValue(IntValue);
865 Value->print(OS, MAI);
869 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
871 if (Value->evaluateAsAbsolute(IntValue)) {
872 EmitSLEB128IntValue(IntValue);
876 Value->print(OS, MAI);
880 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
881 assert(MAI->getDTPRel64Directive() != nullptr);
882 OS << MAI->getDTPRel64Directive();
883 Value->print(OS, MAI);
887 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
888 assert(MAI->getDTPRel32Directive() != nullptr);
889 OS << MAI->getDTPRel32Directive();
890 Value->print(OS, MAI);
894 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
895 assert(MAI->getTPRel64Directive() != nullptr);
896 OS << MAI->getTPRel64Directive();
897 Value->print(OS, MAI);
901 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
902 assert(MAI->getTPRel32Directive() != nullptr);
903 OS << MAI->getTPRel32Directive();
904 Value->print(OS, MAI);
908 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
909 assert(MAI->getGPRel64Directive() != nullptr);
910 OS << MAI->getGPRel64Directive();
911 Value->print(OS, MAI);
915 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
916 assert(MAI->getGPRel32Directive() != nullptr);
917 OS << MAI->getGPRel32Directive();
918 Value->print(OS, MAI);
922 /// emitFill - Emit NumBytes bytes worth of the value specified by
923 /// FillValue. This implements directives such as '.space'.
924 void MCAsmStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
925 if (NumBytes == 0) return;
927 const MCExpr *E = MCConstantExpr::create(NumBytes, getContext());
928 emitFill(*E, FillValue);
931 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
933 if (const char *ZeroDirective = MAI->getZeroDirective()) {
934 // FIXME: Emit location directives
936 NumBytes.print(OS, MAI);
938 OS << ',' << (int)FillValue;
943 MCStreamer::emitFill(NumBytes, FillValue);
946 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
950 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
951 emitFill(*E, Size, Expr);
954 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
955 int64_t Expr, SMLoc Loc) {
956 // FIXME: Emit location directives
958 NumValues.print(OS, MAI);
959 OS << ", " << Size << ", 0x";
960 OS.write_hex(truncateToSize(Expr, 4));
964 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
966 unsigned MaxBytesToEmit) {
967 // Some assemblers don't support non-power of two alignments, so we always
968 // emit alignments as a power of two if possible.
969 if (isPowerOf2_32(ByteAlignment)) {
972 llvm_unreachable("Invalid size for machine code value!");
974 OS << "\t.p2align\t";
983 llvm_unreachable("Unsupported alignment size!");
986 OS << Log2_32(ByteAlignment);
988 if (Value || MaxBytesToEmit) {
990 OS.write_hex(truncateToSize(Value, ValueSize));
993 OS << ", " << MaxBytesToEmit;
999 // Non-power of two alignment. This is not widely supported by assemblers.
1000 // FIXME: Parameterize this based on MAI.
1001 switch (ValueSize) {
1002 default: llvm_unreachable("Invalid size for machine code value!");
1003 case 1: OS << ".balign"; break;
1004 case 2: OS << ".balignw"; break;
1005 case 4: OS << ".balignl"; break;
1006 case 8: llvm_unreachable("Unsupported alignment size!");
1009 OS << ' ' << ByteAlignment;
1010 OS << ", " << truncateToSize(Value, ValueSize);
1012 OS << ", " << MaxBytesToEmit;
1016 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1017 unsigned MaxBytesToEmit) {
1018 // Emit with a text fill value.
1019 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1023 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1024 unsigned char Value,
1026 // FIXME: Verify that Offset is associated with the current section.
1028 Offset->print(OS, MAI);
1029 OS << ", " << (unsigned)Value;
1033 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1034 assert(MAI->hasSingleParameterDotFile());
1036 PrintQuotedString(Filename, OS);
1040 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1041 StringRef Directory,
1046 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1047 unsigned NumFiles = Table.getMCDwarfFiles().size();
1048 FileNo = Table.getFile(Directory, Filename, FileNo);
1051 if (NumFiles == Table.getMCDwarfFiles().size())
1054 SmallString<128> FullPathName;
1056 if (!UseDwarfDirectory && !Directory.empty()) {
1057 if (sys::path::is_absolute(Filename))
1060 FullPathName = Directory;
1061 sys::path::append(FullPathName, Filename);
1063 Filename = FullPathName;
1067 OS << "\t.file\t" << FileNo << ' ';
1068 if (!Directory.empty()) {
1069 PrintQuotedString(Directory, OS);
1072 PrintQuotedString(Filename, OS);
1078 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1079 unsigned Column, unsigned Flags,
1081 unsigned Discriminator,
1082 StringRef FileName) {
1083 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1084 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1085 OS << " basic_block";
1086 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1087 OS << " prologue_end";
1088 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1089 OS << " epilogue_begin";
1091 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1092 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1095 if (Flags & DWARF2_FLAG_IS_STMT)
1102 OS << " isa " << Isa;
1104 OS << " discriminator " << Discriminator;
1107 OS.PadToColumn(MAI->getCommentColumn());
1108 OS << MAI->getCommentString() << ' ' << FileName << ':'
1109 << Line << ':' << Column;
1112 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1113 Isa, Discriminator, FileName);
1116 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1117 // Always use the zeroth line table, since asm syntax only supports one line
1119 return MCStreamer::getDwarfLineTableSymbol(0);
1122 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename) {
1123 if (!getContext().getCVContext().addFile(FileNo, Filename))
1126 OS << "\t.cv_file\t" << FileNo << ' ';
1128 PrintQuotedString(Filename, OS);
1133 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1134 OS << "\t.cv_func_id " << FuncId << '\n';
1135 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1138 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1141 unsigned IALine, unsigned IACol,
1143 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1144 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1145 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1146 IALine, IACol, Loc);
1149 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1150 unsigned Line, unsigned Column,
1151 bool PrologueEnd, bool IsStmt,
1152 StringRef FileName, SMLoc Loc) {
1153 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1156 OS << " prologue_end";
1158 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1159 if (IsStmt != OldIsStmt) {
1169 OS.PadToColumn(MAI->getCommentColumn());
1170 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1174 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1175 PrologueEnd, IsStmt, FileName, Loc);
1178 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1179 const MCSymbol *FnStart,
1180 const MCSymbol *FnEnd) {
1181 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1182 FnStart->print(OS, MAI);
1184 FnEnd->print(OS, MAI);
1186 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1189 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1190 unsigned SourceFileId,
1191 unsigned SourceLineNum,
1192 const MCSymbol *FnStartSym,
1193 const MCSymbol *FnEndSym) {
1194 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1195 << ' ' << SourceLineNum << ' ';
1196 FnStartSym->print(OS, MAI);
1198 FnEndSym->print(OS, MAI);
1200 this->MCStreamer::EmitCVInlineLinetableDirective(
1201 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1204 void MCAsmStreamer::EmitCVDefRangeDirective(
1205 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1206 StringRef FixedSizePortion) {
1207 OS << "\t.cv_def_range\t";
1208 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1210 Range.first->print(OS, MAI);
1212 Range.second->print(OS, MAI);
1215 PrintQuotedString(FixedSizePortion, OS);
1217 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1220 void MCAsmStreamer::EmitCVStringTableDirective() {
1221 OS << "\t.cv_stringtable";
1225 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1226 OS << "\t.cv_filechecksums";
1230 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1231 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1233 PrintQuotedString(IdentString, OS);
1237 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1238 MCStreamer::EmitCFISections(EH, Debug);
1239 OS << "\t.cfi_sections ";
1243 OS << ", .debug_frame";
1245 OS << ".debug_frame";
1251 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1252 OS << "\t.cfi_startproc";
1258 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1259 MCStreamer::EmitCFIEndProcImpl(Frame);
1260 OS << "\t.cfi_endproc";
1264 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1265 if (!MAI->useDwarfRegNumForCFI()) {
1266 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1267 unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true);
1268 InstPrinter->printRegName(OS, LLVMRegister);
1274 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1275 MCStreamer::EmitCFIDefCfa(Register, Offset);
1276 OS << "\t.cfi_def_cfa ";
1277 EmitRegisterName(Register);
1278 OS << ", " << Offset;
1282 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1283 MCStreamer::EmitCFIDefCfaOffset(Offset);
1284 OS << "\t.cfi_def_cfa_offset " << Offset;
1288 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1289 OS << "\t.cfi_escape ";
1290 if (!Values.empty()) {
1291 size_t e = Values.size() - 1;
1292 for (size_t i = 0; i < e; ++i)
1293 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1294 OS << format("0x%02x", uint8_t(Values[e]));
1298 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1299 MCStreamer::EmitCFIEscape(Values);
1300 PrintCFIEscape(OS, Values);
1304 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1305 MCStreamer::EmitCFIGnuArgsSize(Size);
1307 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1308 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1310 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1314 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1315 MCStreamer::EmitCFIDefCfaRegister(Register);
1316 OS << "\t.cfi_def_cfa_register ";
1317 EmitRegisterName(Register);
1321 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1322 this->MCStreamer::EmitCFIOffset(Register, Offset);
1323 OS << "\t.cfi_offset ";
1324 EmitRegisterName(Register);
1325 OS << ", " << Offset;
1329 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1330 unsigned Encoding) {
1331 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1332 OS << "\t.cfi_personality " << Encoding << ", ";
1333 Sym->print(OS, MAI);
1337 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1338 MCStreamer::EmitCFILsda(Sym, Encoding);
1339 OS << "\t.cfi_lsda " << Encoding << ", ";
1340 Sym->print(OS, MAI);
1344 void MCAsmStreamer::EmitCFIRememberState() {
1345 MCStreamer::EmitCFIRememberState();
1346 OS << "\t.cfi_remember_state";
1350 void MCAsmStreamer::EmitCFIRestoreState() {
1351 MCStreamer::EmitCFIRestoreState();
1352 OS << "\t.cfi_restore_state";
1356 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1357 MCStreamer::EmitCFISameValue(Register);
1358 OS << "\t.cfi_same_value ";
1359 EmitRegisterName(Register);
1363 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1364 MCStreamer::EmitCFIRelOffset(Register, Offset);
1365 OS << "\t.cfi_rel_offset ";
1366 EmitRegisterName(Register);
1367 OS << ", " << Offset;
1371 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1372 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1373 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1377 void MCAsmStreamer::EmitCFISignalFrame() {
1378 MCStreamer::EmitCFISignalFrame();
1379 OS << "\t.cfi_signal_frame";
1383 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1384 MCStreamer::EmitCFIUndefined(Register);
1385 OS << "\t.cfi_undefined " << Register;
1389 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1390 MCStreamer::EmitCFIRegister(Register1, Register2);
1391 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1395 void MCAsmStreamer::EmitCFIWindowSave() {
1396 MCStreamer::EmitCFIWindowSave();
1397 OS << "\t.cfi_window_save";
1401 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) {
1402 MCStreamer::EmitWinCFIStartProc(Symbol);
1405 Symbol->print(OS, MAI);
1409 void MCAsmStreamer::EmitWinCFIEndProc() {
1410 MCStreamer::EmitWinCFIEndProc();
1412 OS << "\t.seh_endproc";
1416 void MCAsmStreamer::EmitWinCFIStartChained() {
1417 MCStreamer::EmitWinCFIStartChained();
1419 OS << "\t.seh_startchained";
1423 void MCAsmStreamer::EmitWinCFIEndChained() {
1424 MCStreamer::EmitWinCFIEndChained();
1426 OS << "\t.seh_endchained";
1430 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1432 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except);
1434 OS << "\t.seh_handler ";
1435 Sym->print(OS, MAI);
1443 void MCAsmStreamer::EmitWinEHHandlerData() {
1444 MCStreamer::EmitWinEHHandlerData();
1446 // Switch sections. Don't call SwitchSection directly, because that will
1447 // cause the section switch to be visible in the emitted assembly.
1448 // We only do this so the section switch that terminates the handler
1449 // data block is visible.
1450 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1451 MCSection *TextSec = &CurFrame->Function->getSection();
1452 MCSection *XData = getAssociatedXDataSection(TextSec);
1453 SwitchSectionNoChange(XData);
1455 OS << "\t.seh_handlerdata";
1459 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) {
1460 MCStreamer::EmitWinCFIPushReg(Register);
1462 OS << "\t.seh_pushreg " << Register;
1466 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) {
1467 MCStreamer::EmitWinCFISetFrame(Register, Offset);
1469 OS << "\t.seh_setframe " << Register << ", " << Offset;
1473 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) {
1474 MCStreamer::EmitWinCFIAllocStack(Size);
1476 OS << "\t.seh_stackalloc " << Size;
1480 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) {
1481 MCStreamer::EmitWinCFISaveReg(Register, Offset);
1483 OS << "\t.seh_savereg " << Register << ", " << Offset;
1487 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) {
1488 MCStreamer::EmitWinCFISaveXMM(Register, Offset);
1490 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1494 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) {
1495 MCStreamer::EmitWinCFIPushFrame(Code);
1497 OS << "\t.seh_pushframe";
1503 void MCAsmStreamer::EmitWinCFIEndProlog() {
1504 MCStreamer::EmitWinCFIEndProlog();
1506 OS << "\t.seh_endprologue";
1510 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1511 const MCSubtargetInfo &STI,
1512 bool PrintSchedInfo) {
1513 raw_ostream &OS = GetCommentOS();
1514 SmallString<256> Code;
1515 SmallVector<MCFixup, 4> Fixups;
1516 raw_svector_ostream VecOS(Code);
1517 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1519 // If we are showing fixups, create symbolic markers in the encoded
1520 // representation. We do this by making a per-bit map to the fixup item index,
1521 // then trying to display it as nicely as possible.
1522 SmallVector<uint8_t, 64> FixupMap;
1523 FixupMap.resize(Code.size() * 8);
1524 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1527 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1528 MCFixup &F = Fixups[i];
1529 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1530 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1531 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1532 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1533 FixupMap[Index] = 1 + i;
1537 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1538 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1539 OS << "encoding: [";
1540 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1544 // See if all bits are the same map entry.
1545 uint8_t MapEntry = FixupMap[i * 8 + 0];
1546 for (unsigned j = 1; j != 8; ++j) {
1547 if (FixupMap[i * 8 + j] == MapEntry)
1550 MapEntry = uint8_t(~0U);
1554 if (MapEntry != uint8_t(~0U)) {
1555 if (MapEntry == 0) {
1556 OS << format("0x%02x", uint8_t(Code[i]));
1559 // FIXME: Some of the 8 bits require fix up.
1560 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1561 << char('A' + MapEntry - 1) << '\'';
1563 OS << char('A' + MapEntry - 1);
1566 // Otherwise, write out in binary.
1568 for (unsigned j = 8; j--;) {
1569 unsigned Bit = (Code[i] >> j) & 1;
1572 if (MAI->isLittleEndian())
1573 FixupBit = i * 8 + j;
1575 FixupBit = i * 8 + (7-j);
1577 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1578 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1579 OS << char('A' + MapEntry - 1);
1586 // If we are not going to add fixup or schedul comments after this point then
1587 // we have to end the current comment line with "\n".
1588 if (Fixups.size() || !PrintSchedInfo)
1591 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1592 MCFixup &F = Fixups[i];
1593 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1594 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1595 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1599 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1600 const MCSubtargetInfo &STI,
1601 bool PrintSchedInfo) {
1602 assert(getCurrentSectionOnly() &&
1603 "Cannot emit contents before setting section!");
1605 // Show the encoding in a comment if we have a code emitter.
1607 AddEncodingComment(Inst, STI, PrintSchedInfo);
1609 // Show the MCInst if enabled.
1612 GetCommentOS() << "\n";
1613 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1614 GetCommentOS() << "\n";
1617 if(getTargetStreamer())
1618 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1620 InstPrinter->printInst(&Inst, OS, "", STI);
1622 if (PrintSchedInfo) {
1623 std::string SI = STI.getSchedInfoStr(Inst);
1625 GetCommentOS() << SI;
1628 StringRef Comments = CommentToEmit;
1629 if (Comments.size() && Comments.back() != '\n')
1630 GetCommentOS() << "\n";
1635 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1636 OS << "\t.bundle_align_mode " << AlignPow2;
1640 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1641 OS << "\t.bundle_lock";
1643 OS << " align_to_end";
1647 void MCAsmStreamer::EmitBundleUnlock() {
1648 OS << "\t.bundle_unlock";
1652 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1653 const MCExpr *Expr, SMLoc) {
1655 Offset.print(OS, MAI);
1659 Expr->print(OS, MAI);
1665 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1666 /// the specified string in the output .s file. This capability is
1667 /// indicated by the hasRawTextSupport() predicate.
1668 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1669 if (!String.empty() && String.back() == '\n')
1670 String = String.substr(0, String.size()-1);
1675 void MCAsmStreamer::FinishImpl() {
1676 // If we are generating dwarf for assembly source files dump out the sections.
1677 if (getContext().getGenDwarfForAssembly())
1678 MCGenDwarfInfo::Emit(this);
1680 // Emit the label for the line table, if requested - since the rest of the
1681 // line table will be defined by .loc/.file directives, and not emitted
1682 // directly, the label is the only work required here.
1683 auto &Tables = getContext().getMCDwarfLineTables();
1684 if (!Tables.empty()) {
1685 assert(Tables.size() == 1 && "asm output only supports one line table");
1686 if (auto *Label = Tables.begin()->second.getLabel()) {
1687 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1693 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1694 std::unique_ptr<formatted_raw_ostream> OS,
1695 bool isVerboseAsm, bool useDwarfDirectory,
1696 MCInstPrinter *IP, MCCodeEmitter *CE,
1697 MCAsmBackend *MAB, bool ShowInst) {
1698 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1699 useDwarfDirectory, IP, CE, MAB, ShowInst);