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/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Path.h"
39 class MCAsmStreamer final : public MCStreamer {
40 std::unique_ptr<formatted_raw_ostream> OSOwner;
41 formatted_raw_ostream &OS;
43 std::unique_ptr<MCInstPrinter> InstPrinter;
44 std::unique_ptr<MCCodeEmitter> Emitter;
45 std::unique_ptr<MCAsmBackend> AsmBackend;
47 SmallString<128> ExplicitCommentToEmit;
48 SmallString<128> CommentToEmit;
49 raw_svector_ostream CommentStream;
51 unsigned IsVerboseAsm : 1;
52 unsigned ShowInst : 1;
53 unsigned UseDwarfDirectory : 1;
55 void EmitRegisterName(int64_t Register);
56 void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
57 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
60 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
61 bool isVerboseAsm, bool useDwarfDirectory,
62 MCInstPrinter *printer, MCCodeEmitter *emitter,
63 MCAsmBackend *asmbackend, bool showInst)
64 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
65 MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
66 AsmBackend(asmbackend), CommentStream(CommentToEmit),
67 IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
68 UseDwarfDirectory(useDwarfDirectory) {
71 InstPrinter->setCommentStream(CommentStream);
74 inline void EmitEOL() {
75 // Dump Explicit Comments here.
76 emitExplicitComments();
77 // If we don't have any comments, just emit a \n.
85 void EmitSyntaxDirective() override;
87 void EmitCommentsAndEOL();
89 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
91 bool isVerboseAsm() const override { return IsVerboseAsm; }
93 /// hasRawTextSupport - We support EmitRawText.
94 bool hasRawTextSupport() const override { return true; }
96 /// AddComment - Add a comment that can be emitted to the generated .s
97 /// file if applicable as a QoI issue to make the output of the compiler
98 /// more readable. This only affects the MCAsmStreamer, and only when
99 /// verbose assembly output is enabled.
100 void AddComment(const Twine &T, bool EOL = true) override;
102 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
103 /// If PrintSchedInfo - is true then the comment sched:[x:y] should
104 // be added to output if it's being supported by target
105 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &,
106 bool PrintSchedInfo);
108 /// GetCommentOS - Return a raw_ostream that comments can be written to.
109 /// Unlike AddComment, you are required to terminate comments with \n if you
111 raw_ostream &GetCommentOS() override {
113 return nulls(); // Discard comments unless in verbose asm mode.
114 return CommentStream;
117 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
119 void addExplicitComment(const Twine &T) override;
120 void emitExplicitComments() override;
122 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
123 void AddBlankLine() override {
127 /// @name MCStreamer Interface
130 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
132 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
133 void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
135 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
136 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
137 void EmitDataRegion(MCDataRegionType Kind) override;
138 void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
139 unsigned Update) override;
140 void EmitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
141 unsigned Update) override;
142 void EmitThumbFunc(MCSymbol *Func) override;
144 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
145 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
146 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
148 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
149 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
150 void EmitCOFFSymbolStorageClass(int StorageClass) override;
151 void EmitCOFFSymbolType(int Type) override;
152 void EndCOFFSymbolDef() override;
153 void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
154 void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
155 void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
156 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
157 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
158 unsigned ByteAlignment) override;
160 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
162 /// @param Symbol - The common symbol to emit.
163 /// @param Size - The size of the common symbol.
164 /// @param ByteAlignment - The alignment of the common symbol in bytes.
165 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
166 unsigned ByteAlignment) override;
168 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
169 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
171 void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
172 unsigned ByteAlignment = 0) override;
174 void EmitBinaryData(StringRef Data) override;
176 void EmitBytes(StringRef Data) override;
178 void EmitValueImpl(const MCExpr *Value, unsigned Size,
179 SMLoc Loc = SMLoc()) override;
180 void EmitIntValue(uint64_t Value, unsigned Size) override;
182 void EmitULEB128Value(const MCExpr *Value) override;
184 void EmitSLEB128Value(const MCExpr *Value) override;
186 void EmitDTPRel32Value(const MCExpr *Value) override;
187 void EmitDTPRel64Value(const MCExpr *Value) override;
188 void EmitTPRel32Value(const MCExpr *Value) override;
189 void EmitTPRel64Value(const MCExpr *Value) override;
191 void EmitGPRel64Value(const MCExpr *Value) override;
193 void EmitGPRel32Value(const MCExpr *Value) override;
196 void emitFill(uint64_t NumBytes, uint8_t FillValue) override;
198 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
199 SMLoc Loc = SMLoc()) override;
201 void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override;
203 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
204 SMLoc Loc = SMLoc()) override;
206 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
207 unsigned ValueSize = 1,
208 unsigned MaxBytesToEmit = 0) override;
210 void EmitCodeAlignment(unsigned ByteAlignment,
211 unsigned MaxBytesToEmit = 0) override;
213 void emitValueToOffset(const MCExpr *Offset,
217 void EmitFileDirective(StringRef Filename) override;
218 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
220 unsigned CUID = 0) override;
221 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
222 unsigned Column, unsigned Flags,
223 unsigned Isa, unsigned Discriminator,
224 StringRef FileName) override;
225 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
227 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
228 ArrayRef<uint8_t> Checksum,
229 unsigned ChecksumKind) override;
230 bool EmitCVFuncIdDirective(unsigned FuncId) override;
231 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
232 unsigned IAFile, unsigned IALine,
233 unsigned IACol, SMLoc Loc) override;
234 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
235 unsigned Column, bool PrologueEnd, bool IsStmt,
236 StringRef FileName, SMLoc Loc) override;
237 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
238 const MCSymbol *FnEnd) override;
239 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
240 unsigned SourceFileId,
241 unsigned SourceLineNum,
242 const MCSymbol *FnStartSym,
243 const MCSymbol *FnEndSym) override;
244 void EmitCVDefRangeDirective(
245 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
246 StringRef FixedSizePortion) override;
247 void EmitCVStringTableDirective() override;
248 void EmitCVFileChecksumsDirective() override;
249 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
250 void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
252 void EmitIdent(StringRef IdentString) override;
253 void EmitCFISections(bool EH, bool Debug) override;
254 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
255 void EmitCFIDefCfaOffset(int64_t Offset) override;
256 void EmitCFIDefCfaRegister(int64_t Register) override;
257 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
258 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
259 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
260 void EmitCFIRememberState() override;
261 void EmitCFIRestoreState() override;
262 void EmitCFIRestore(int64_t Register) override;
263 void EmitCFISameValue(int64_t Register) override;
264 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
265 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
266 void EmitCFIEscape(StringRef Values) override;
267 void EmitCFIGnuArgsSize(int64_t Size) override;
268 void EmitCFISignalFrame() override;
269 void EmitCFIUndefined(int64_t Register) override;
270 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
271 void EmitCFIWindowSave() override;
272 void EmitCFIReturnColumn(int64_t Register) override;
274 void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
275 void EmitWinCFIEndProc(SMLoc Loc) override;
276 void EmitWinCFIStartChained(SMLoc Loc) override;
277 void EmitWinCFIEndChained(SMLoc Loc) override;
278 void EmitWinCFIPushReg(unsigned Register, SMLoc Loc) override;
279 void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
281 void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
282 void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
284 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
286 void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
287 void EmitWinCFIEndProlog(SMLoc Loc) override;
289 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
291 void EmitWinEHHandlerData(SMLoc Loc) override;
293 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
294 bool PrintSchedInfo) override;
296 void EmitBundleAlignMode(unsigned AlignPow2) override;
297 void EmitBundleLock(bool AlignToEnd) override;
298 void EmitBundleUnlock() override;
300 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
301 const MCExpr *Expr, SMLoc Loc) override;
303 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
304 /// the specified string in the output .s file. This capability is
305 /// indicated by the hasRawTextSupport() predicate.
306 void EmitRawTextImpl(StringRef String) override;
308 void FinishImpl() override;
311 } // end anonymous namespace.
313 /// AddComment - Add a comment that can be emitted to the generated .s
314 /// file if applicable as a QoI issue to make the output of the compiler
315 /// more readable. This only affects the MCAsmStreamer, and only when
316 /// verbose assembly output is enabled.
317 /// By deafult EOL is set to true so that each comment goes on its own line.
318 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
319 if (!IsVerboseAsm) return;
321 T.toVector(CommentToEmit);
324 CommentToEmit.push_back('\n'); // Place comment in a new line.
327 void MCAsmStreamer::EmitCommentsAndEOL() {
328 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
333 StringRef Comments = CommentToEmit;
335 assert(Comments.back() == '\n' &&
336 "Comment array not newline terminated");
338 // Emit a line of comments.
339 OS.PadToColumn(MAI->getCommentColumn());
340 size_t Position = Comments.find('\n');
341 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
343 Comments = Comments.substr(Position+1);
344 } while (!Comments.empty());
346 CommentToEmit.clear();
349 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
350 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
351 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
354 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
357 OS << MAI->getCommentString() << T;
361 void MCAsmStreamer::addExplicitComment(const Twine &T) {
362 StringRef c = T.getSingleStringRef();
363 if (c.equals(StringRef(MAI->getSeparatorString())))
365 if (c.startswith(StringRef("//"))) {
366 ExplicitCommentToEmit.append("\t");
367 ExplicitCommentToEmit.append(MAI->getCommentString());
369 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
370 } else if (c.startswith(StringRef("/*"))) {
371 size_t p = 2, len = c.size() - 2;
372 // emit each line in comment as separate newline.
374 size_t newp = std::min(len, c.find_first_of("\r\n", p));
375 ExplicitCommentToEmit.append("\t");
376 ExplicitCommentToEmit.append(MAI->getCommentString());
377 ExplicitCommentToEmit.append(c.slice(p, newp).str());
378 // If we have another line in this comment add line
380 ExplicitCommentToEmit.append("\n");
383 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
384 ExplicitCommentToEmit.append("\t");
385 ExplicitCommentToEmit.append(c.str());
386 } else if (c.front() == '#') {
388 ExplicitCommentToEmit.append("\t");
389 ExplicitCommentToEmit.append(MAI->getCommentString());
390 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
392 assert(false && "Unexpected Assembly Comment");
393 // full line comments immediately output
394 if (c.back() == '\n')
395 emitExplicitComments();
398 void MCAsmStreamer::emitExplicitComments() {
399 StringRef Comments = ExplicitCommentToEmit;
400 if (!Comments.empty())
402 ExplicitCommentToEmit.clear();
405 void MCAsmStreamer::ChangeSection(MCSection *Section,
406 const MCExpr *Subsection) {
407 assert(Section && "Cannot switch to a null section!");
408 if (MCTargetStreamer *TS = getTargetStreamer()) {
409 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
411 Section->PrintSwitchToSection(
412 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
417 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
418 MCStreamer::EmitLabel(Symbol, Loc);
420 Symbol->print(OS, MAI);
421 OS << MAI->getLabelSuffix();
426 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
427 StringRef str = MCLOHIdToName(Kind);
430 int NbArgs = MCLOHIdToNbArgs(Kind);
431 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
432 assert(str != "" && "Invalid LOH name");
435 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
437 for (const MCSymbol *Arg : Args) {
446 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
448 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
449 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
450 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
451 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
452 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
457 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
458 assert(!Options.empty() && "At least one option is required!");
459 OS << "\t.linker_option \"" << Options[0] << '"';
460 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
461 ie = Options.end(); it != ie; ++it) {
462 OS << ", " << '"' << *it << '"';
467 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
468 if (!MAI->doesSupportDataRegionDirectives())
471 case MCDR_DataRegion: OS << "\t.data_region"; break;
472 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
473 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
474 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
475 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
480 static const char *getVersionMinDirective(MCVersionMinType Type) {
482 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
483 case MCVM_TvOSVersionMin: return ".tvos_version_min";
484 case MCVM_IOSVersionMin: return ".ios_version_min";
485 case MCVM_OSXVersionMin: return ".macosx_version_min";
487 llvm_unreachable("Invalid MC version min type");
490 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
491 unsigned Minor, unsigned Update) {
492 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
494 OS << ", " << Update;
498 static const char *getPlatformName(MachO::PlatformType Type) {
500 case MachO::PLATFORM_MACOS: return "macos";
501 case MachO::PLATFORM_IOS: return "ios";
502 case MachO::PLATFORM_TVOS: return "tvos";
503 case MachO::PLATFORM_WATCHOS: return "watchos";
504 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
506 llvm_unreachable("Invalid Mach-O platform type");
509 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
510 unsigned Minor, unsigned Update) {
511 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
512 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
514 OS << ", " << Update;
518 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
519 // This needs to emit to a temporary string to get properly quoted
520 // MCSymbols when they have spaces in them.
521 OS << "\t.thumb_func";
522 // Only Mach-O hasSubsectionsViaSymbols()
523 if (MAI->hasSubsectionsViaSymbols()) {
525 Func->print(OS, MAI);
530 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
531 Symbol->print(OS, MAI);
533 Value->print(OS, MAI);
537 MCStreamer::EmitAssignment(Symbol, Value);
540 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
542 Alias->print(OS, MAI);
544 Symbol->print(OS, MAI);
548 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
549 MCSymbolAttr Attribute) {
551 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
552 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
553 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
554 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
555 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
556 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
557 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
558 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
559 if (!MAI->hasDotTypeDotSizeDirective())
560 return false; // Symbol attribute not supported
562 Symbol->print(OS, MAI);
563 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
565 default: return false;
566 case MCSA_ELF_TypeFunction: OS << "function"; break;
567 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
568 case MCSA_ELF_TypeObject: OS << "object"; break;
569 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
570 case MCSA_ELF_TypeCommon: OS << "common"; break;
571 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
572 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
576 case MCSA_Global: // .globl/.global
577 OS << MAI->getGlobalDirective();
579 case MCSA_Hidden: OS << "\t.hidden\t"; break;
580 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
581 case MCSA_Internal: OS << "\t.internal\t"; break;
582 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
583 case MCSA_Local: OS << "\t.local\t"; break;
584 case MCSA_NoDeadStrip:
585 if (!MAI->hasNoDeadStrip())
587 OS << "\t.no_dead_strip\t";
589 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
590 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
591 case MCSA_PrivateExtern:
592 OS << "\t.private_extern\t";
594 case MCSA_Protected: OS << "\t.protected\t"; break;
595 case MCSA_Reference: OS << "\t.reference\t"; break;
596 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
597 case MCSA_WeakDefinition:
598 OS << "\t.weak_definition\t";
601 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
602 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
605 Symbol->print(OS, MAI);
611 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
612 OS << ".desc" << ' ';
613 Symbol->print(OS, MAI);
614 OS << ',' << DescValue;
618 void MCAsmStreamer::EmitSyntaxDirective() {
619 if (MAI->getAssemblerDialect() == 1) {
620 OS << "\t.intel_syntax noprefix";
623 // FIXME: Currently emit unprefix'ed registers.
624 // The intel_syntax directive has one optional argument
625 // with may have a value of prefix or noprefix.
628 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
630 Symbol->print(OS, MAI);
635 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
636 OS << "\t.scl\t" << StorageClass << ';';
640 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
641 OS << "\t.type\t" << Type << ';';
645 void MCAsmStreamer::EndCOFFSymbolDef() {
650 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
651 OS << "\t.safeseh\t";
652 Symbol->print(OS, MAI);
656 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
658 Symbol->print(OS, MAI);
662 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
663 OS << "\t.secrel32\t";
664 Symbol->print(OS, MAI);
670 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
671 assert(MAI->hasDotTypeDotSizeDirective());
673 Symbol->print(OS, MAI);
675 Value->print(OS, MAI);
679 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
680 unsigned ByteAlignment) {
682 Symbol->print(OS, MAI);
685 if (ByteAlignment != 0) {
686 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
687 OS << ',' << ByteAlignment;
689 OS << ',' << Log2_32(ByteAlignment);
694 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
696 /// @param Symbol - The common symbol to emit.
697 /// @param Size - The size of the common symbol.
698 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
699 unsigned ByteAlign) {
701 Symbol->print(OS, MAI);
705 switch (MAI->getLCOMMDirectiveAlignmentType()) {
706 case LCOMM::NoAlignment:
707 llvm_unreachable("alignment not supported on .lcomm!");
708 case LCOMM::ByteAlignment:
709 OS << ',' << ByteAlign;
711 case LCOMM::Log2Alignment:
712 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
713 OS << ',' << Log2_32(ByteAlign);
720 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
721 uint64_t Size, unsigned ByteAlignment) {
723 AssignFragment(Symbol, &Section->getDummyFragment());
725 // Note: a .zerofill directive does not switch sections.
728 // This is a mach-o specific directive.
729 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
730 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
734 Symbol->print(OS, MAI);
736 if (ByteAlignment != 0)
737 OS << ',' << Log2_32(ByteAlignment);
742 // .tbss sym, size, align
743 // This depends that the symbol has already been mangled from the original,
745 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
746 uint64_t Size, unsigned ByteAlignment) {
747 AssignFragment(Symbol, &Section->getDummyFragment());
749 assert(Symbol && "Symbol shouldn't be NULL!");
750 // Instead of using the Section we'll just use the shortcut.
751 // This is a mach-o specific directive and section.
753 Symbol->print(OS, MAI);
756 // Output align if we have it. We default to 1 so don't bother printing
758 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
763 static inline char toOctal(int X) { return (X&7)+'0'; }
765 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
768 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
769 unsigned char C = Data[i];
770 if (C == '"' || C == '\\') {
771 OS << '\\' << (char)C;
775 if (isprint((unsigned char)C)) {
781 case '\b': OS << "\\b"; break;
782 case '\f': OS << "\\f"; break;
783 case '\n': OS << "\\n"; break;
784 case '\r': OS << "\\r"; break;
785 case '\t': OS << "\\t"; break;
788 OS << toOctal(C >> 6);
789 OS << toOctal(C >> 3);
790 OS << toOctal(C >> 0);
798 void MCAsmStreamer::EmitBytes(StringRef Data) {
799 assert(getCurrentSectionOnly() &&
800 "Cannot emit contents before setting section!");
801 if (Data.empty()) return;
803 // If only single byte is provided or no ascii or asciz directives is
804 // supported, emit as vector of 8bits data.
805 if (Data.size() == 1 ||
806 !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
807 const char *Directive = MAI->getData8bitsDirective();
808 for (const unsigned char C : Data.bytes()) {
809 OS << Directive << (unsigned)C;
815 // If the data ends with 0 and the target supports .asciz, use it, otherwise
817 if (MAI->getAscizDirective() && Data.back() == 0) {
818 OS << MAI->getAscizDirective();
819 Data = Data.substr(0, Data.size()-1);
821 OS << MAI->getAsciiDirective();
824 PrintQuotedString(Data, OS);
828 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
829 // This is binary data. Print it in a grid of hex bytes for readability.
830 const size_t Cols = 4;
831 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
832 size_t J = I, EJ = std::min(I + Cols, Data.size());
834 OS << MAI->getData8bitsDirective();
835 for (; J < EJ - 1; ++J)
836 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
837 OS << format("0x%02x", uint8_t(Data[J]));
842 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
843 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
846 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
848 assert(Size <= 8 && "Invalid size");
849 assert(getCurrentSectionOnly() &&
850 "Cannot emit contents before setting section!");
851 const char *Directive = nullptr;
854 case 1: Directive = MAI->getData8bitsDirective(); break;
855 case 2: Directive = MAI->getData16bitsDirective(); break;
856 case 4: Directive = MAI->getData32bitsDirective(); break;
857 case 8: Directive = MAI->getData64bitsDirective(); break;
862 if (!Value->evaluateAsAbsolute(IntValue))
863 report_fatal_error("Don't know how to emit this value.");
865 // We couldn't handle the requested integer size so we fallback by breaking
866 // the request down into several, smaller, integers.
867 // Since sizes greater or equal to "Size" are invalid, we use the greatest
868 // power of 2 that is less than "Size" as our largest piece of granularity.
869 bool IsLittleEndian = MAI->isLittleEndian();
870 for (unsigned Emitted = 0; Emitted != Size;) {
871 unsigned Remaining = Size - Emitted;
872 // The size of our partial emission must be a power of two less than
874 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
875 // Calculate the byte offset of our partial emission taking into account
876 // the endianness of the target.
877 unsigned ByteOffset =
878 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
879 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
880 // We truncate our partial emission to fit within the bounds of the
881 // emission domain. This produces nicer output and silences potential
882 // truncation warnings when round tripping through another assembler.
883 uint64_t Shift = 64 - EmissionSize * 8;
884 assert(Shift < static_cast<uint64_t>(
885 std::numeric_limits<unsigned long long>::digits) &&
886 "undefined behavior");
887 ValueToEmit &= ~0ULL >> Shift;
888 EmitIntValue(ValueToEmit, EmissionSize);
889 Emitted += EmissionSize;
894 assert(Directive && "Invalid size for machine code value!");
896 if (MCTargetStreamer *TS = getTargetStreamer()) {
897 TS->emitValue(Value);
899 Value->print(OS, MAI);
904 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
906 if (Value->evaluateAsAbsolute(IntValue)) {
907 EmitULEB128IntValue(IntValue);
911 Value->print(OS, MAI);
915 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
917 if (Value->evaluateAsAbsolute(IntValue)) {
918 EmitSLEB128IntValue(IntValue);
922 Value->print(OS, MAI);
926 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
927 assert(MAI->getDTPRel64Directive() != nullptr);
928 OS << MAI->getDTPRel64Directive();
929 Value->print(OS, MAI);
933 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
934 assert(MAI->getDTPRel32Directive() != nullptr);
935 OS << MAI->getDTPRel32Directive();
936 Value->print(OS, MAI);
940 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
941 assert(MAI->getTPRel64Directive() != nullptr);
942 OS << MAI->getTPRel64Directive();
943 Value->print(OS, MAI);
947 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
948 assert(MAI->getTPRel32Directive() != nullptr);
949 OS << MAI->getTPRel32Directive();
950 Value->print(OS, MAI);
954 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
955 assert(MAI->getGPRel64Directive() != nullptr);
956 OS << MAI->getGPRel64Directive();
957 Value->print(OS, MAI);
961 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
962 assert(MAI->getGPRel32Directive() != nullptr);
963 OS << MAI->getGPRel32Directive();
964 Value->print(OS, MAI);
968 /// emitFill - Emit NumBytes bytes worth of the value specified by
969 /// FillValue. This implements directives such as '.space'.
970 void MCAsmStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
971 if (NumBytes == 0) return;
973 const MCExpr *E = MCConstantExpr::create(NumBytes, getContext());
974 emitFill(*E, FillValue);
977 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
979 if (const char *ZeroDirective = MAI->getZeroDirective()) {
980 // FIXME: Emit location directives
982 NumBytes.print(OS, MAI);
984 OS << ',' << (int)FillValue;
989 MCStreamer::emitFill(NumBytes, FillValue);
992 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
996 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
997 emitFill(*E, Size, Expr);
1000 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1001 int64_t Expr, SMLoc Loc) {
1002 // FIXME: Emit location directives
1004 NumValues.print(OS, MAI);
1005 OS << ", " << Size << ", 0x";
1006 OS.write_hex(truncateToSize(Expr, 4));
1010 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1012 unsigned MaxBytesToEmit) {
1013 // Some assemblers don't support non-power of two alignments, so we always
1014 // emit alignments as a power of two if possible.
1015 if (isPowerOf2_32(ByteAlignment)) {
1016 switch (ValueSize) {
1018 llvm_unreachable("Invalid size for machine code value!");
1020 OS << "\t.p2align\t";
1029 llvm_unreachable("Unsupported alignment size!");
1032 OS << Log2_32(ByteAlignment);
1034 if (Value || MaxBytesToEmit) {
1036 OS.write_hex(truncateToSize(Value, ValueSize));
1039 OS << ", " << MaxBytesToEmit;
1045 // Non-power of two alignment. This is not widely supported by assemblers.
1046 // FIXME: Parameterize this based on MAI.
1047 switch (ValueSize) {
1048 default: llvm_unreachable("Invalid size for machine code value!");
1049 case 1: OS << ".balign"; break;
1050 case 2: OS << ".balignw"; break;
1051 case 4: OS << ".balignl"; break;
1052 case 8: llvm_unreachable("Unsupported alignment size!");
1055 OS << ' ' << ByteAlignment;
1056 OS << ", " << truncateToSize(Value, ValueSize);
1058 OS << ", " << MaxBytesToEmit;
1062 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1063 unsigned MaxBytesToEmit) {
1064 // Emit with a text fill value.
1065 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1069 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1070 unsigned char Value,
1072 // FIXME: Verify that Offset is associated with the current section.
1074 Offset->print(OS, MAI);
1075 OS << ", " << (unsigned)Value;
1079 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1080 assert(MAI->hasSingleParameterDotFile());
1082 PrintQuotedString(Filename, OS);
1086 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1087 StringRef Directory,
1092 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1093 unsigned NumFiles = Table.getMCDwarfFiles().size();
1094 FileNo = Table.getFile(Directory, Filename, FileNo);
1097 if (NumFiles == Table.getMCDwarfFiles().size())
1100 SmallString<128> FullPathName;
1102 if (!UseDwarfDirectory && !Directory.empty()) {
1103 if (sys::path::is_absolute(Filename))
1106 FullPathName = Directory;
1107 sys::path::append(FullPathName, Filename);
1109 Filename = FullPathName;
1113 SmallString<128> Str;
1114 raw_svector_ostream OS1(Str);
1115 OS1 << "\t.file\t" << FileNo << ' ';
1116 if (!Directory.empty()) {
1117 PrintQuotedString(Directory, OS1);
1120 PrintQuotedString(Filename, OS1);
1121 if (MCTargetStreamer *TS = getTargetStreamer()) {
1122 TS->emitDwarfFileDirective(OS1.str());
1124 EmitRawText(OS1.str());
1130 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1131 unsigned Column, unsigned Flags,
1133 unsigned Discriminator,
1134 StringRef FileName) {
1135 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1136 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1137 OS << " basic_block";
1138 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1139 OS << " prologue_end";
1140 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1141 OS << " epilogue_begin";
1143 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1144 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1147 if (Flags & DWARF2_FLAG_IS_STMT)
1154 OS << " isa " << Isa;
1156 OS << " discriminator " << Discriminator;
1159 OS.PadToColumn(MAI->getCommentColumn());
1160 OS << MAI->getCommentString() << ' ' << FileName << ':'
1161 << Line << ':' << Column;
1164 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1165 Isa, Discriminator, FileName);
1168 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1169 // Always use the zeroth line table, since asm syntax only supports one line
1171 return MCStreamer::getDwarfLineTableSymbol(0);
1174 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1175 ArrayRef<uint8_t> Checksum,
1176 unsigned ChecksumKind) {
1177 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1181 OS << "\t.cv_file\t" << FileNo << ' ';
1182 PrintQuotedString(Filename, OS);
1184 if (!ChecksumKind) {
1190 PrintQuotedString(toHex(Checksum), OS);
1191 OS << ' ' << ChecksumKind;
1197 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1198 OS << "\t.cv_func_id " << FuncId << '\n';
1199 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1202 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1205 unsigned IALine, unsigned IACol,
1207 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1208 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1209 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1210 IALine, IACol, Loc);
1213 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1214 unsigned Line, unsigned Column,
1215 bool PrologueEnd, bool IsStmt,
1216 StringRef FileName, SMLoc Loc) {
1217 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1220 OS << " prologue_end";
1222 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1223 if (IsStmt != OldIsStmt) {
1233 OS.PadToColumn(MAI->getCommentColumn());
1234 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1238 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1239 PrologueEnd, IsStmt, FileName, Loc);
1242 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1243 const MCSymbol *FnStart,
1244 const MCSymbol *FnEnd) {
1245 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1246 FnStart->print(OS, MAI);
1248 FnEnd->print(OS, MAI);
1250 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1253 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1254 unsigned SourceFileId,
1255 unsigned SourceLineNum,
1256 const MCSymbol *FnStartSym,
1257 const MCSymbol *FnEndSym) {
1258 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1259 << ' ' << SourceLineNum << ' ';
1260 FnStartSym->print(OS, MAI);
1262 FnEndSym->print(OS, MAI);
1264 this->MCStreamer::EmitCVInlineLinetableDirective(
1265 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1268 void MCAsmStreamer::EmitCVDefRangeDirective(
1269 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1270 StringRef FixedSizePortion) {
1271 OS << "\t.cv_def_range\t";
1272 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1274 Range.first->print(OS, MAI);
1276 Range.second->print(OS, MAI);
1279 PrintQuotedString(FixedSizePortion, OS);
1281 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1284 void MCAsmStreamer::EmitCVStringTableDirective() {
1285 OS << "\t.cv_stringtable";
1289 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1290 OS << "\t.cv_filechecksums";
1294 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1295 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1299 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1300 OS << "\t.cv_fpo_data\t";
1301 ProcSym->print(OS, MAI);
1305 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1306 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1308 PrintQuotedString(IdentString, OS);
1312 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1313 MCStreamer::EmitCFISections(EH, Debug);
1314 OS << "\t.cfi_sections ";
1318 OS << ", .debug_frame";
1320 OS << ".debug_frame";
1326 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1327 OS << "\t.cfi_startproc";
1333 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1334 MCStreamer::EmitCFIEndProcImpl(Frame);
1335 OS << "\t.cfi_endproc";
1339 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1340 if (!MAI->useDwarfRegNumForCFI()) {
1341 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1342 // just ones that map to LLVM register numbers and have known names.
1343 // Fall back to using the original number directly if no name is known.
1344 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1345 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1346 if (LLVMRegister != -1) {
1347 InstPrinter->printRegName(OS, LLVMRegister);
1354 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1355 MCStreamer::EmitCFIDefCfa(Register, Offset);
1356 OS << "\t.cfi_def_cfa ";
1357 EmitRegisterName(Register);
1358 OS << ", " << Offset;
1362 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1363 MCStreamer::EmitCFIDefCfaOffset(Offset);
1364 OS << "\t.cfi_def_cfa_offset " << Offset;
1368 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1369 OS << "\t.cfi_escape ";
1370 if (!Values.empty()) {
1371 size_t e = Values.size() - 1;
1372 for (size_t i = 0; i < e; ++i)
1373 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1374 OS << format("0x%02x", uint8_t(Values[e]));
1378 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1379 MCStreamer::EmitCFIEscape(Values);
1380 PrintCFIEscape(OS, Values);
1384 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1385 MCStreamer::EmitCFIGnuArgsSize(Size);
1387 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1388 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1390 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1394 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1395 MCStreamer::EmitCFIDefCfaRegister(Register);
1396 OS << "\t.cfi_def_cfa_register ";
1397 EmitRegisterName(Register);
1401 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1402 this->MCStreamer::EmitCFIOffset(Register, Offset);
1403 OS << "\t.cfi_offset ";
1404 EmitRegisterName(Register);
1405 OS << ", " << Offset;
1409 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1410 unsigned Encoding) {
1411 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1412 OS << "\t.cfi_personality " << Encoding << ", ";
1413 Sym->print(OS, MAI);
1417 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1418 MCStreamer::EmitCFILsda(Sym, Encoding);
1419 OS << "\t.cfi_lsda " << Encoding << ", ";
1420 Sym->print(OS, MAI);
1424 void MCAsmStreamer::EmitCFIRememberState() {
1425 MCStreamer::EmitCFIRememberState();
1426 OS << "\t.cfi_remember_state";
1430 void MCAsmStreamer::EmitCFIRestoreState() {
1431 MCStreamer::EmitCFIRestoreState();
1432 OS << "\t.cfi_restore_state";
1436 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1437 MCStreamer::EmitCFIRestore(Register);
1438 OS << "\t.cfi_restore ";
1439 EmitRegisterName(Register);
1443 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1444 MCStreamer::EmitCFISameValue(Register);
1445 OS << "\t.cfi_same_value ";
1446 EmitRegisterName(Register);
1450 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1451 MCStreamer::EmitCFIRelOffset(Register, Offset);
1452 OS << "\t.cfi_rel_offset ";
1453 EmitRegisterName(Register);
1454 OS << ", " << Offset;
1458 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1459 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1460 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1464 void MCAsmStreamer::EmitCFISignalFrame() {
1465 MCStreamer::EmitCFISignalFrame();
1466 OS << "\t.cfi_signal_frame";
1470 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1471 MCStreamer::EmitCFIUndefined(Register);
1472 OS << "\t.cfi_undefined " << Register;
1476 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1477 MCStreamer::EmitCFIRegister(Register1, Register2);
1478 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1482 void MCAsmStreamer::EmitCFIWindowSave() {
1483 MCStreamer::EmitCFIWindowSave();
1484 OS << "\t.cfi_window_save";
1488 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1489 MCStreamer::EmitCFIReturnColumn(Register);
1490 OS << "\t.cfi_return_column " << Register;
1494 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1495 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1498 Symbol->print(OS, MAI);
1502 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1503 MCStreamer::EmitWinCFIEndProc(Loc);
1505 OS << "\t.seh_endproc";
1509 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1510 MCStreamer::EmitWinCFIStartChained(Loc);
1512 OS << "\t.seh_startchained";
1516 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1517 MCStreamer::EmitWinCFIEndChained(Loc);
1519 OS << "\t.seh_endchained";
1523 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1524 bool Except, SMLoc Loc) {
1525 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1527 OS << "\t.seh_handler ";
1528 Sym->print(OS, MAI);
1536 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1537 MCStreamer::EmitWinEHHandlerData(Loc);
1539 // Switch sections. Don't call SwitchSection directly, because that will
1540 // cause the section switch to be visible in the emitted assembly.
1541 // We only do this so the section switch that terminates the handler
1542 // data block is visible.
1543 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1544 MCSection *TextSec = &CurFrame->Function->getSection();
1545 MCSection *XData = getAssociatedXDataSection(TextSec);
1546 SwitchSectionNoChange(XData);
1548 OS << "\t.seh_handlerdata";
1552 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) {
1553 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1555 OS << "\t.seh_pushreg " << Register;
1559 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset,
1561 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1563 OS << "\t.seh_setframe " << Register << ", " << Offset;
1567 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1568 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1570 OS << "\t.seh_stackalloc " << Size;
1574 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset,
1576 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1578 OS << "\t.seh_savereg " << Register << ", " << Offset;
1582 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
1584 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1586 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1590 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1591 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1593 OS << "\t.seh_pushframe";
1599 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1600 MCStreamer::EmitWinCFIEndProlog(Loc);
1602 OS << "\t.seh_endprologue";
1606 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1607 const MCSubtargetInfo &STI,
1608 bool PrintSchedInfo) {
1609 raw_ostream &OS = GetCommentOS();
1610 SmallString<256> Code;
1611 SmallVector<MCFixup, 4> Fixups;
1612 raw_svector_ostream VecOS(Code);
1613 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1615 // If we are showing fixups, create symbolic markers in the encoded
1616 // representation. We do this by making a per-bit map to the fixup item index,
1617 // then trying to display it as nicely as possible.
1618 SmallVector<uint8_t, 64> FixupMap;
1619 FixupMap.resize(Code.size() * 8);
1620 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1623 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1624 MCFixup &F = Fixups[i];
1625 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1626 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1627 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1628 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1629 FixupMap[Index] = 1 + i;
1633 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1634 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1635 OS << "encoding: [";
1636 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1640 // See if all bits are the same map entry.
1641 uint8_t MapEntry = FixupMap[i * 8 + 0];
1642 for (unsigned j = 1; j != 8; ++j) {
1643 if (FixupMap[i * 8 + j] == MapEntry)
1646 MapEntry = uint8_t(~0U);
1650 if (MapEntry != uint8_t(~0U)) {
1651 if (MapEntry == 0) {
1652 OS << format("0x%02x", uint8_t(Code[i]));
1655 // FIXME: Some of the 8 bits require fix up.
1656 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1657 << char('A' + MapEntry - 1) << '\'';
1659 OS << char('A' + MapEntry - 1);
1662 // Otherwise, write out in binary.
1664 for (unsigned j = 8; j--;) {
1665 unsigned Bit = (Code[i] >> j) & 1;
1668 if (MAI->isLittleEndian())
1669 FixupBit = i * 8 + j;
1671 FixupBit = i * 8 + (7-j);
1673 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1674 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1675 OS << char('A' + MapEntry - 1);
1682 // If we are not going to add fixup or schedule comments after this point
1683 // then we have to end the current comment line with "\n".
1684 if (Fixups.size() || !PrintSchedInfo)
1687 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1688 MCFixup &F = Fixups[i];
1689 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1690 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1691 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1695 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1696 const MCSubtargetInfo &STI,
1697 bool PrintSchedInfo) {
1698 assert(getCurrentSectionOnly() &&
1699 "Cannot emit contents before setting section!");
1701 // Show the encoding in a comment if we have a code emitter.
1703 AddEncodingComment(Inst, STI, PrintSchedInfo);
1705 // Show the MCInst if enabled.
1708 GetCommentOS() << "\n";
1709 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1710 GetCommentOS() << "\n";
1713 if(getTargetStreamer())
1714 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1716 InstPrinter->printInst(&Inst, OS, "", STI);
1718 if (PrintSchedInfo) {
1719 std::string SI = STI.getSchedInfoStr(Inst);
1721 GetCommentOS() << SI;
1724 StringRef Comments = CommentToEmit;
1725 if (Comments.size() && Comments.back() != '\n')
1726 GetCommentOS() << "\n";
1731 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1732 OS << "\t.bundle_align_mode " << AlignPow2;
1736 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1737 OS << "\t.bundle_lock";
1739 OS << " align_to_end";
1743 void MCAsmStreamer::EmitBundleUnlock() {
1744 OS << "\t.bundle_unlock";
1748 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1749 const MCExpr *Expr, SMLoc) {
1751 Offset.print(OS, MAI);
1755 Expr->print(OS, MAI);
1761 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1762 /// the specified string in the output .s file. This capability is
1763 /// indicated by the hasRawTextSupport() predicate.
1764 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1765 if (!String.empty() && String.back() == '\n')
1766 String = String.substr(0, String.size()-1);
1771 void MCAsmStreamer::FinishImpl() {
1772 // If we are generating dwarf for assembly source files dump out the sections.
1773 if (getContext().getGenDwarfForAssembly())
1774 MCGenDwarfInfo::Emit(this);
1776 // Emit the label for the line table, if requested - since the rest of the
1777 // line table will be defined by .loc/.file directives, and not emitted
1778 // directly, the label is the only work required here.
1779 auto &Tables = getContext().getMCDwarfLineTables();
1780 if (!Tables.empty()) {
1781 assert(Tables.size() == 1 && "asm output only supports one line table");
1782 if (auto *Label = Tables.begin()->second.getLabel()) {
1783 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1789 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1790 std::unique_ptr<formatted_raw_ostream> OS,
1791 bool isVerboseAsm, bool useDwarfDirectory,
1792 MCInstPrinter *IP, MCCodeEmitter *CE,
1793 MCAsmBackend *MAB, bool ShowInst) {
1794 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1795 useDwarfDirectory, IP, CE, MAB, ShowInst);