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 Section->PrintSwitchToSection(
409 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
413 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
414 MCStreamer::EmitLabel(Symbol, Loc);
416 Symbol->print(OS, MAI);
417 OS << MAI->getLabelSuffix();
422 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
423 StringRef str = MCLOHIdToName(Kind);
426 int NbArgs = MCLOHIdToNbArgs(Kind);
427 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
428 assert(str != "" && "Invalid LOH name");
431 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
433 for (const MCSymbol *Arg : Args) {
442 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
444 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
445 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
446 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
447 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
448 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
453 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
454 assert(!Options.empty() && "At least one option is required!");
455 OS << "\t.linker_option \"" << Options[0] << '"';
456 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
457 ie = Options.end(); it != ie; ++it) {
458 OS << ", " << '"' << *it << '"';
463 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
464 if (!MAI->doesSupportDataRegionDirectives())
467 case MCDR_DataRegion: OS << "\t.data_region"; break;
468 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
469 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
470 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
471 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
476 static const char *getVersionMinDirective(MCVersionMinType Type) {
478 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
479 case MCVM_TvOSVersionMin: return ".tvos_version_min";
480 case MCVM_IOSVersionMin: return ".ios_version_min";
481 case MCVM_OSXVersionMin: return ".macosx_version_min";
483 llvm_unreachable("Invalid MC version min type");
486 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
487 unsigned Minor, unsigned Update) {
488 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
490 OS << ", " << Update;
494 static const char *getPlatformName(MachO::PlatformType Type) {
496 case MachO::PLATFORM_MACOS: return "macos";
497 case MachO::PLATFORM_IOS: return "ios";
498 case MachO::PLATFORM_TVOS: return "tvos";
499 case MachO::PLATFORM_WATCHOS: return "watchos";
500 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
502 llvm_unreachable("Invalid Mach-O platform type");
505 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
506 unsigned Minor, unsigned Update) {
507 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
508 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
510 OS << ", " << Update;
514 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
515 // This needs to emit to a temporary string to get properly quoted
516 // MCSymbols when they have spaces in them.
517 OS << "\t.thumb_func";
518 // Only Mach-O hasSubsectionsViaSymbols()
519 if (MAI->hasSubsectionsViaSymbols()) {
521 Func->print(OS, MAI);
526 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
527 Symbol->print(OS, MAI);
529 Value->print(OS, MAI);
533 MCStreamer::EmitAssignment(Symbol, Value);
536 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
538 Alias->print(OS, MAI);
540 Symbol->print(OS, MAI);
544 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
545 MCSymbolAttr Attribute) {
547 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
548 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
549 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
550 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
551 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
552 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
553 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
554 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
555 if (!MAI->hasDotTypeDotSizeDirective())
556 return false; // Symbol attribute not supported
558 Symbol->print(OS, MAI);
559 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
561 default: return false;
562 case MCSA_ELF_TypeFunction: OS << "function"; break;
563 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
564 case MCSA_ELF_TypeObject: OS << "object"; break;
565 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
566 case MCSA_ELF_TypeCommon: OS << "common"; break;
567 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
568 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
572 case MCSA_Global: // .globl/.global
573 OS << MAI->getGlobalDirective();
575 case MCSA_Hidden: OS << "\t.hidden\t"; break;
576 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
577 case MCSA_Internal: OS << "\t.internal\t"; break;
578 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
579 case MCSA_Local: OS << "\t.local\t"; break;
580 case MCSA_NoDeadStrip:
581 if (!MAI->hasNoDeadStrip())
583 OS << "\t.no_dead_strip\t";
585 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
586 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
587 case MCSA_PrivateExtern:
588 OS << "\t.private_extern\t";
590 case MCSA_Protected: OS << "\t.protected\t"; break;
591 case MCSA_Reference: OS << "\t.reference\t"; break;
592 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
593 case MCSA_WeakDefinition:
594 OS << "\t.weak_definition\t";
597 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
598 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
601 Symbol->print(OS, MAI);
607 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
608 OS << ".desc" << ' ';
609 Symbol->print(OS, MAI);
610 OS << ',' << DescValue;
614 void MCAsmStreamer::EmitSyntaxDirective() {
615 if (MAI->getAssemblerDialect() == 1) {
616 OS << "\t.intel_syntax noprefix";
619 // FIXME: Currently emit unprefix'ed registers.
620 // The intel_syntax directive has one optional argument
621 // with may have a value of prefix or noprefix.
624 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
626 Symbol->print(OS, MAI);
631 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
632 OS << "\t.scl\t" << StorageClass << ';';
636 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
637 OS << "\t.type\t" << Type << ';';
641 void MCAsmStreamer::EndCOFFSymbolDef() {
646 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
647 OS << "\t.safeseh\t";
648 Symbol->print(OS, MAI);
652 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
654 Symbol->print(OS, MAI);
658 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
659 OS << "\t.secrel32\t";
660 Symbol->print(OS, MAI);
666 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
667 assert(MAI->hasDotTypeDotSizeDirective());
669 Symbol->print(OS, MAI);
671 Value->print(OS, MAI);
675 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
676 unsigned ByteAlignment) {
678 Symbol->print(OS, MAI);
681 if (ByteAlignment != 0) {
682 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
683 OS << ',' << ByteAlignment;
685 OS << ',' << Log2_32(ByteAlignment);
690 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
692 /// @param Symbol - The common symbol to emit.
693 /// @param Size - The size of the common symbol.
694 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
695 unsigned ByteAlign) {
697 Symbol->print(OS, MAI);
701 switch (MAI->getLCOMMDirectiveAlignmentType()) {
702 case LCOMM::NoAlignment:
703 llvm_unreachable("alignment not supported on .lcomm!");
704 case LCOMM::ByteAlignment:
705 OS << ',' << ByteAlign;
707 case LCOMM::Log2Alignment:
708 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
709 OS << ',' << Log2_32(ByteAlign);
716 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
717 uint64_t Size, unsigned ByteAlignment) {
719 AssignFragment(Symbol, &Section->getDummyFragment());
721 // Note: a .zerofill directive does not switch sections.
724 // This is a mach-o specific directive.
725 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
726 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
730 Symbol->print(OS, MAI);
732 if (ByteAlignment != 0)
733 OS << ',' << Log2_32(ByteAlignment);
738 // .tbss sym, size, align
739 // This depends that the symbol has already been mangled from the original,
741 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
742 uint64_t Size, unsigned ByteAlignment) {
743 AssignFragment(Symbol, &Section->getDummyFragment());
745 assert(Symbol && "Symbol shouldn't be NULL!");
746 // Instead of using the Section we'll just use the shortcut.
747 // This is a mach-o specific directive and section.
749 Symbol->print(OS, MAI);
752 // Output align if we have it. We default to 1 so don't bother printing
754 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
759 static inline char toOctal(int X) { return (X&7)+'0'; }
761 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
764 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
765 unsigned char C = Data[i];
766 if (C == '"' || C == '\\') {
767 OS << '\\' << (char)C;
771 if (isprint((unsigned char)C)) {
777 case '\b': OS << "\\b"; break;
778 case '\f': OS << "\\f"; break;
779 case '\n': OS << "\\n"; break;
780 case '\r': OS << "\\r"; break;
781 case '\t': OS << "\\t"; break;
784 OS << toOctal(C >> 6);
785 OS << toOctal(C >> 3);
786 OS << toOctal(C >> 0);
794 void MCAsmStreamer::EmitBytes(StringRef Data) {
795 assert(getCurrentSectionOnly() &&
796 "Cannot emit contents before setting section!");
797 if (Data.empty()) return;
799 if (Data.size() == 1) {
800 OS << MAI->getData8bitsDirective();
801 OS << (unsigned)(unsigned char)Data[0];
806 // If the data ends with 0 and the target supports .asciz, use it, otherwise
808 if (MAI->getAscizDirective() && Data.back() == 0) {
809 OS << MAI->getAscizDirective();
810 Data = Data.substr(0, Data.size()-1);
812 OS << MAI->getAsciiDirective();
815 PrintQuotedString(Data, OS);
819 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
820 // This is binary data. Print it in a grid of hex bytes for readability.
821 const size_t Cols = 4;
822 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
823 size_t J = I, EJ = std::min(I + Cols, Data.size());
825 OS << MAI->getData8bitsDirective();
826 for (; J < EJ - 1; ++J)
827 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
828 OS << format("0x%02x", uint8_t(Data[J]));
833 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
834 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
837 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
839 assert(Size <= 8 && "Invalid size");
840 assert(getCurrentSectionOnly() &&
841 "Cannot emit contents before setting section!");
842 const char *Directive = nullptr;
845 case 1: Directive = MAI->getData8bitsDirective(); break;
846 case 2: Directive = MAI->getData16bitsDirective(); break;
847 case 4: Directive = MAI->getData32bitsDirective(); break;
848 case 8: Directive = MAI->getData64bitsDirective(); break;
853 if (!Value->evaluateAsAbsolute(IntValue))
854 report_fatal_error("Don't know how to emit this value.");
856 // We couldn't handle the requested integer size so we fallback by breaking
857 // the request down into several, smaller, integers.
858 // Since sizes greater or equal to "Size" are invalid, we use the greatest
859 // power of 2 that is less than "Size" as our largest piece of granularity.
860 bool IsLittleEndian = MAI->isLittleEndian();
861 for (unsigned Emitted = 0; Emitted != Size;) {
862 unsigned Remaining = Size - Emitted;
863 // The size of our partial emission must be a power of two less than
865 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
866 // Calculate the byte offset of our partial emission taking into account
867 // the endianness of the target.
868 unsigned ByteOffset =
869 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
870 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
871 // We truncate our partial emission to fit within the bounds of the
872 // emission domain. This produces nicer output and silences potential
873 // truncation warnings when round tripping through another assembler.
874 uint64_t Shift = 64 - EmissionSize * 8;
875 assert(Shift < static_cast<uint64_t>(
876 std::numeric_limits<unsigned long long>::digits) &&
877 "undefined behavior");
878 ValueToEmit &= ~0ULL >> Shift;
879 EmitIntValue(ValueToEmit, EmissionSize);
880 Emitted += EmissionSize;
885 assert(Directive && "Invalid size for machine code value!");
887 Value->print(OS, MAI);
891 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
893 if (Value->evaluateAsAbsolute(IntValue)) {
894 EmitULEB128IntValue(IntValue);
898 Value->print(OS, MAI);
902 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
904 if (Value->evaluateAsAbsolute(IntValue)) {
905 EmitSLEB128IntValue(IntValue);
909 Value->print(OS, MAI);
913 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
914 assert(MAI->getDTPRel64Directive() != nullptr);
915 OS << MAI->getDTPRel64Directive();
916 Value->print(OS, MAI);
920 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
921 assert(MAI->getDTPRel32Directive() != nullptr);
922 OS << MAI->getDTPRel32Directive();
923 Value->print(OS, MAI);
927 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
928 assert(MAI->getTPRel64Directive() != nullptr);
929 OS << MAI->getTPRel64Directive();
930 Value->print(OS, MAI);
934 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
935 assert(MAI->getTPRel32Directive() != nullptr);
936 OS << MAI->getTPRel32Directive();
937 Value->print(OS, MAI);
941 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
942 assert(MAI->getGPRel64Directive() != nullptr);
943 OS << MAI->getGPRel64Directive();
944 Value->print(OS, MAI);
948 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
949 assert(MAI->getGPRel32Directive() != nullptr);
950 OS << MAI->getGPRel32Directive();
951 Value->print(OS, MAI);
955 /// emitFill - Emit NumBytes bytes worth of the value specified by
956 /// FillValue. This implements directives such as '.space'.
957 void MCAsmStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
958 if (NumBytes == 0) return;
960 const MCExpr *E = MCConstantExpr::create(NumBytes, getContext());
961 emitFill(*E, FillValue);
964 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
966 if (const char *ZeroDirective = MAI->getZeroDirective()) {
967 // FIXME: Emit location directives
969 NumBytes.print(OS, MAI);
971 OS << ',' << (int)FillValue;
976 MCStreamer::emitFill(NumBytes, FillValue);
979 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
983 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
984 emitFill(*E, Size, Expr);
987 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
988 int64_t Expr, SMLoc Loc) {
989 // FIXME: Emit location directives
991 NumValues.print(OS, MAI);
992 OS << ", " << Size << ", 0x";
993 OS.write_hex(truncateToSize(Expr, 4));
997 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
999 unsigned MaxBytesToEmit) {
1000 // Some assemblers don't support non-power of two alignments, so we always
1001 // emit alignments as a power of two if possible.
1002 if (isPowerOf2_32(ByteAlignment)) {
1003 switch (ValueSize) {
1005 llvm_unreachable("Invalid size for machine code value!");
1007 OS << "\t.p2align\t";
1016 llvm_unreachable("Unsupported alignment size!");
1019 OS << Log2_32(ByteAlignment);
1021 if (Value || MaxBytesToEmit) {
1023 OS.write_hex(truncateToSize(Value, ValueSize));
1026 OS << ", " << MaxBytesToEmit;
1032 // Non-power of two alignment. This is not widely supported by assemblers.
1033 // FIXME: Parameterize this based on MAI.
1034 switch (ValueSize) {
1035 default: llvm_unreachable("Invalid size for machine code value!");
1036 case 1: OS << ".balign"; break;
1037 case 2: OS << ".balignw"; break;
1038 case 4: OS << ".balignl"; break;
1039 case 8: llvm_unreachable("Unsupported alignment size!");
1042 OS << ' ' << ByteAlignment;
1043 OS << ", " << truncateToSize(Value, ValueSize);
1045 OS << ", " << MaxBytesToEmit;
1049 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1050 unsigned MaxBytesToEmit) {
1051 // Emit with a text fill value.
1052 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1056 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1057 unsigned char Value,
1059 // FIXME: Verify that Offset is associated with the current section.
1061 Offset->print(OS, MAI);
1062 OS << ", " << (unsigned)Value;
1066 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1067 assert(MAI->hasSingleParameterDotFile());
1069 PrintQuotedString(Filename, OS);
1073 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1074 StringRef Directory,
1079 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1080 unsigned NumFiles = Table.getMCDwarfFiles().size();
1081 FileNo = Table.getFile(Directory, Filename, FileNo);
1084 if (NumFiles == Table.getMCDwarfFiles().size())
1087 SmallString<128> FullPathName;
1089 if (!UseDwarfDirectory && !Directory.empty()) {
1090 if (sys::path::is_absolute(Filename))
1093 FullPathName = Directory;
1094 sys::path::append(FullPathName, Filename);
1096 Filename = FullPathName;
1100 OS << "\t.file\t" << FileNo << ' ';
1101 if (!Directory.empty()) {
1102 PrintQuotedString(Directory, OS);
1105 PrintQuotedString(Filename, OS);
1111 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1112 unsigned Column, unsigned Flags,
1114 unsigned Discriminator,
1115 StringRef FileName) {
1116 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1117 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1118 OS << " basic_block";
1119 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1120 OS << " prologue_end";
1121 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1122 OS << " epilogue_begin";
1124 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1125 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1128 if (Flags & DWARF2_FLAG_IS_STMT)
1135 OS << " isa " << Isa;
1137 OS << " discriminator " << Discriminator;
1140 OS.PadToColumn(MAI->getCommentColumn());
1141 OS << MAI->getCommentString() << ' ' << FileName << ':'
1142 << Line << ':' << Column;
1145 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1146 Isa, Discriminator, FileName);
1149 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1150 // Always use the zeroth line table, since asm syntax only supports one line
1152 return MCStreamer::getDwarfLineTableSymbol(0);
1155 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1156 ArrayRef<uint8_t> Checksum,
1157 unsigned ChecksumKind) {
1158 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1162 OS << "\t.cv_file\t" << FileNo << ' ';
1163 PrintQuotedString(Filename, OS);
1165 if (!ChecksumKind) {
1171 PrintQuotedString(toHex(Checksum), OS);
1172 OS << ' ' << ChecksumKind;
1178 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1179 OS << "\t.cv_func_id " << FuncId << '\n';
1180 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1183 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1186 unsigned IALine, unsigned IACol,
1188 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1189 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1190 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1191 IALine, IACol, Loc);
1194 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1195 unsigned Line, unsigned Column,
1196 bool PrologueEnd, bool IsStmt,
1197 StringRef FileName, SMLoc Loc) {
1198 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1201 OS << " prologue_end";
1203 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1204 if (IsStmt != OldIsStmt) {
1214 OS.PadToColumn(MAI->getCommentColumn());
1215 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1219 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1220 PrologueEnd, IsStmt, FileName, Loc);
1223 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1224 const MCSymbol *FnStart,
1225 const MCSymbol *FnEnd) {
1226 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1227 FnStart->print(OS, MAI);
1229 FnEnd->print(OS, MAI);
1231 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1234 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1235 unsigned SourceFileId,
1236 unsigned SourceLineNum,
1237 const MCSymbol *FnStartSym,
1238 const MCSymbol *FnEndSym) {
1239 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1240 << ' ' << SourceLineNum << ' ';
1241 FnStartSym->print(OS, MAI);
1243 FnEndSym->print(OS, MAI);
1245 this->MCStreamer::EmitCVInlineLinetableDirective(
1246 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1249 void MCAsmStreamer::EmitCVDefRangeDirective(
1250 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1251 StringRef FixedSizePortion) {
1252 OS << "\t.cv_def_range\t";
1253 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1255 Range.first->print(OS, MAI);
1257 Range.second->print(OS, MAI);
1260 PrintQuotedString(FixedSizePortion, OS);
1262 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1265 void MCAsmStreamer::EmitCVStringTableDirective() {
1266 OS << "\t.cv_stringtable";
1270 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1271 OS << "\t.cv_filechecksums";
1275 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1276 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1280 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1281 OS << "\t.cv_fpo_data\t";
1282 ProcSym->print(OS, MAI);
1286 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1287 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1289 PrintQuotedString(IdentString, OS);
1293 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1294 MCStreamer::EmitCFISections(EH, Debug);
1295 OS << "\t.cfi_sections ";
1299 OS << ", .debug_frame";
1301 OS << ".debug_frame";
1307 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1308 OS << "\t.cfi_startproc";
1314 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1315 MCStreamer::EmitCFIEndProcImpl(Frame);
1316 OS << "\t.cfi_endproc";
1320 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1321 if (!MAI->useDwarfRegNumForCFI()) {
1322 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1323 // just ones that map to LLVM register numbers and have known names.
1324 // Fall back to using the original number directly if no name is known.
1325 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1326 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1327 if (LLVMRegister != -1) {
1328 InstPrinter->printRegName(OS, LLVMRegister);
1335 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1336 MCStreamer::EmitCFIDefCfa(Register, Offset);
1337 OS << "\t.cfi_def_cfa ";
1338 EmitRegisterName(Register);
1339 OS << ", " << Offset;
1343 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1344 MCStreamer::EmitCFIDefCfaOffset(Offset);
1345 OS << "\t.cfi_def_cfa_offset " << Offset;
1349 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1350 OS << "\t.cfi_escape ";
1351 if (!Values.empty()) {
1352 size_t e = Values.size() - 1;
1353 for (size_t i = 0; i < e; ++i)
1354 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1355 OS << format("0x%02x", uint8_t(Values[e]));
1359 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1360 MCStreamer::EmitCFIEscape(Values);
1361 PrintCFIEscape(OS, Values);
1365 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1366 MCStreamer::EmitCFIGnuArgsSize(Size);
1368 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1369 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1371 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1375 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1376 MCStreamer::EmitCFIDefCfaRegister(Register);
1377 OS << "\t.cfi_def_cfa_register ";
1378 EmitRegisterName(Register);
1382 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1383 this->MCStreamer::EmitCFIOffset(Register, Offset);
1384 OS << "\t.cfi_offset ";
1385 EmitRegisterName(Register);
1386 OS << ", " << Offset;
1390 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1391 unsigned Encoding) {
1392 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1393 OS << "\t.cfi_personality " << Encoding << ", ";
1394 Sym->print(OS, MAI);
1398 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1399 MCStreamer::EmitCFILsda(Sym, Encoding);
1400 OS << "\t.cfi_lsda " << Encoding << ", ";
1401 Sym->print(OS, MAI);
1405 void MCAsmStreamer::EmitCFIRememberState() {
1406 MCStreamer::EmitCFIRememberState();
1407 OS << "\t.cfi_remember_state";
1411 void MCAsmStreamer::EmitCFIRestoreState() {
1412 MCStreamer::EmitCFIRestoreState();
1413 OS << "\t.cfi_restore_state";
1417 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1418 MCStreamer::EmitCFIRestore(Register);
1419 OS << "\t.cfi_restore ";
1420 EmitRegisterName(Register);
1424 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1425 MCStreamer::EmitCFISameValue(Register);
1426 OS << "\t.cfi_same_value ";
1427 EmitRegisterName(Register);
1431 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1432 MCStreamer::EmitCFIRelOffset(Register, Offset);
1433 OS << "\t.cfi_rel_offset ";
1434 EmitRegisterName(Register);
1435 OS << ", " << Offset;
1439 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1440 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1441 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1445 void MCAsmStreamer::EmitCFISignalFrame() {
1446 MCStreamer::EmitCFISignalFrame();
1447 OS << "\t.cfi_signal_frame";
1451 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1452 MCStreamer::EmitCFIUndefined(Register);
1453 OS << "\t.cfi_undefined " << Register;
1457 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1458 MCStreamer::EmitCFIRegister(Register1, Register2);
1459 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1463 void MCAsmStreamer::EmitCFIWindowSave() {
1464 MCStreamer::EmitCFIWindowSave();
1465 OS << "\t.cfi_window_save";
1469 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1470 MCStreamer::EmitCFIReturnColumn(Register);
1471 OS << "\t.cfi_return_column " << Register;
1475 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1476 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1479 Symbol->print(OS, MAI);
1483 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1484 MCStreamer::EmitWinCFIEndProc(Loc);
1486 OS << "\t.seh_endproc";
1490 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1491 MCStreamer::EmitWinCFIStartChained(Loc);
1493 OS << "\t.seh_startchained";
1497 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1498 MCStreamer::EmitWinCFIEndChained(Loc);
1500 OS << "\t.seh_endchained";
1504 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1505 bool Except, SMLoc Loc) {
1506 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1508 OS << "\t.seh_handler ";
1509 Sym->print(OS, MAI);
1517 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1518 MCStreamer::EmitWinEHHandlerData(Loc);
1520 // Switch sections. Don't call SwitchSection directly, because that will
1521 // cause the section switch to be visible in the emitted assembly.
1522 // We only do this so the section switch that terminates the handler
1523 // data block is visible.
1524 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1525 MCSection *TextSec = &CurFrame->Function->getSection();
1526 MCSection *XData = getAssociatedXDataSection(TextSec);
1527 SwitchSectionNoChange(XData);
1529 OS << "\t.seh_handlerdata";
1533 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) {
1534 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1536 OS << "\t.seh_pushreg " << Register;
1540 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset,
1542 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1544 OS << "\t.seh_setframe " << Register << ", " << Offset;
1548 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1549 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1551 OS << "\t.seh_stackalloc " << Size;
1555 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset,
1557 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1559 OS << "\t.seh_savereg " << Register << ", " << Offset;
1563 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
1565 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1567 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1571 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1572 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1574 OS << "\t.seh_pushframe";
1580 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1581 MCStreamer::EmitWinCFIEndProlog(Loc);
1583 OS << "\t.seh_endprologue";
1587 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1588 const MCSubtargetInfo &STI,
1589 bool PrintSchedInfo) {
1590 raw_ostream &OS = GetCommentOS();
1591 SmallString<256> Code;
1592 SmallVector<MCFixup, 4> Fixups;
1593 raw_svector_ostream VecOS(Code);
1594 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1596 // If we are showing fixups, create symbolic markers in the encoded
1597 // representation. We do this by making a per-bit map to the fixup item index,
1598 // then trying to display it as nicely as possible.
1599 SmallVector<uint8_t, 64> FixupMap;
1600 FixupMap.resize(Code.size() * 8);
1601 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1604 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1605 MCFixup &F = Fixups[i];
1606 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1607 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1608 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1609 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1610 FixupMap[Index] = 1 + i;
1614 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1615 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1616 OS << "encoding: [";
1617 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1621 // See if all bits are the same map entry.
1622 uint8_t MapEntry = FixupMap[i * 8 + 0];
1623 for (unsigned j = 1; j != 8; ++j) {
1624 if (FixupMap[i * 8 + j] == MapEntry)
1627 MapEntry = uint8_t(~0U);
1631 if (MapEntry != uint8_t(~0U)) {
1632 if (MapEntry == 0) {
1633 OS << format("0x%02x", uint8_t(Code[i]));
1636 // FIXME: Some of the 8 bits require fix up.
1637 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1638 << char('A' + MapEntry - 1) << '\'';
1640 OS << char('A' + MapEntry - 1);
1643 // Otherwise, write out in binary.
1645 for (unsigned j = 8; j--;) {
1646 unsigned Bit = (Code[i] >> j) & 1;
1649 if (MAI->isLittleEndian())
1650 FixupBit = i * 8 + j;
1652 FixupBit = i * 8 + (7-j);
1654 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1655 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1656 OS << char('A' + MapEntry - 1);
1663 // If we are not going to add fixup or schedule comments after this point
1664 // then we have to end the current comment line with "\n".
1665 if (Fixups.size() || !PrintSchedInfo)
1668 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1669 MCFixup &F = Fixups[i];
1670 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1671 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1672 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1676 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1677 const MCSubtargetInfo &STI,
1678 bool PrintSchedInfo) {
1679 assert(getCurrentSectionOnly() &&
1680 "Cannot emit contents before setting section!");
1682 // Show the encoding in a comment if we have a code emitter.
1684 AddEncodingComment(Inst, STI, PrintSchedInfo);
1686 // Show the MCInst if enabled.
1689 GetCommentOS() << "\n";
1690 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1691 GetCommentOS() << "\n";
1694 if(getTargetStreamer())
1695 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1697 InstPrinter->printInst(&Inst, OS, "", STI);
1699 if (PrintSchedInfo) {
1700 std::string SI = STI.getSchedInfoStr(Inst);
1702 GetCommentOS() << SI;
1705 StringRef Comments = CommentToEmit;
1706 if (Comments.size() && Comments.back() != '\n')
1707 GetCommentOS() << "\n";
1712 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1713 OS << "\t.bundle_align_mode " << AlignPow2;
1717 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1718 OS << "\t.bundle_lock";
1720 OS << " align_to_end";
1724 void MCAsmStreamer::EmitBundleUnlock() {
1725 OS << "\t.bundle_unlock";
1729 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1730 const MCExpr *Expr, SMLoc) {
1732 Offset.print(OS, MAI);
1736 Expr->print(OS, MAI);
1742 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1743 /// the specified string in the output .s file. This capability is
1744 /// indicated by the hasRawTextSupport() predicate.
1745 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1746 if (!String.empty() && String.back() == '\n')
1747 String = String.substr(0, String.size()-1);
1752 void MCAsmStreamer::FinishImpl() {
1753 // If we are generating dwarf for assembly source files dump out the sections.
1754 if (getContext().getGenDwarfForAssembly())
1755 MCGenDwarfInfo::Emit(this);
1757 // Emit the label for the line table, if requested - since the rest of the
1758 // line table will be defined by .loc/.file directives, and not emitted
1759 // directly, the label is the only work required here.
1760 auto &Tables = getContext().getMCDwarfLineTables();
1761 if (!Tables.empty()) {
1762 assert(Tables.size() == 1 && "asm output only supports one line table");
1763 if (auto *Label = Tables.begin()->second.getLabel()) {
1764 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1770 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1771 std::unique_ptr<formatted_raw_ostream> OS,
1772 bool isVerboseAsm, bool useDwarfDirectory,
1773 MCInstPrinter *IP, MCCodeEmitter *CE,
1774 MCAsmBackend *MAB, bool ShowInst) {
1775 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1776 useDwarfDirectory, IP, CE, MAB, ShowInst);