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;
195 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
196 SMLoc Loc = SMLoc()) override;
198 void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) override;
200 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
201 SMLoc Loc = SMLoc()) override;
203 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
204 unsigned ValueSize = 1,
205 unsigned MaxBytesToEmit = 0) override;
207 void EmitCodeAlignment(unsigned ByteAlignment,
208 unsigned MaxBytesToEmit = 0) override;
210 void emitValueToOffset(const MCExpr *Offset,
214 void EmitFileDirective(StringRef Filename) override;
215 unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
217 unsigned CUID = 0) override;
218 void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
219 unsigned Column, unsigned Flags,
220 unsigned Isa, unsigned Discriminator,
221 StringRef FileName) override;
222 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
224 bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
225 ArrayRef<uint8_t> Checksum,
226 unsigned ChecksumKind) override;
227 bool EmitCVFuncIdDirective(unsigned FuncId) override;
228 bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
229 unsigned IAFile, unsigned IALine,
230 unsigned IACol, SMLoc Loc) override;
231 void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
232 unsigned Column, bool PrologueEnd, bool IsStmt,
233 StringRef FileName, SMLoc Loc) override;
234 void EmitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
235 const MCSymbol *FnEnd) override;
236 void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
237 unsigned SourceFileId,
238 unsigned SourceLineNum,
239 const MCSymbol *FnStartSym,
240 const MCSymbol *FnEndSym) override;
241 void EmitCVDefRangeDirective(
242 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
243 StringRef FixedSizePortion) override;
244 void EmitCVStringTableDirective() override;
245 void EmitCVFileChecksumsDirective() override;
246 void EmitCVFileChecksumOffsetDirective(unsigned FileNo) override;
247 void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
249 void EmitIdent(StringRef IdentString) override;
250 void EmitCFISections(bool EH, bool Debug) override;
251 void EmitCFIDefCfa(int64_t Register, int64_t Offset) override;
252 void EmitCFIDefCfaOffset(int64_t Offset) override;
253 void EmitCFIDefCfaRegister(int64_t Register) override;
254 void EmitCFIOffset(int64_t Register, int64_t Offset) override;
255 void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
256 void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
257 void EmitCFIRememberState() override;
258 void EmitCFIRestoreState() override;
259 void EmitCFIRestore(int64_t Register) override;
260 void EmitCFISameValue(int64_t Register) override;
261 void EmitCFIRelOffset(int64_t Register, int64_t Offset) override;
262 void EmitCFIAdjustCfaOffset(int64_t Adjustment) override;
263 void EmitCFIEscape(StringRef Values) override;
264 void EmitCFIGnuArgsSize(int64_t Size) override;
265 void EmitCFISignalFrame() override;
266 void EmitCFIUndefined(int64_t Register) override;
267 void EmitCFIRegister(int64_t Register1, int64_t Register2) override;
268 void EmitCFIWindowSave() override;
269 void EmitCFIReturnColumn(int64_t Register) override;
271 void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
272 void EmitWinCFIEndProc(SMLoc Loc) override;
273 void EmitWinCFIStartChained(SMLoc Loc) override;
274 void EmitWinCFIEndChained(SMLoc Loc) override;
275 void EmitWinCFIPushReg(unsigned Register, SMLoc Loc) override;
276 void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
278 void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
279 void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
281 void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
283 void EmitWinCFIPushFrame(bool Code, SMLoc Loc) override;
284 void EmitWinCFIEndProlog(SMLoc Loc) override;
286 void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
288 void EmitWinEHHandlerData(SMLoc Loc) override;
290 void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
291 bool PrintSchedInfo) override;
293 void EmitBundleAlignMode(unsigned AlignPow2) override;
294 void EmitBundleLock(bool AlignToEnd) override;
295 void EmitBundleUnlock() override;
297 bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
298 const MCExpr *Expr, SMLoc Loc) override;
300 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
301 /// the specified string in the output .s file. This capability is
302 /// indicated by the hasRawTextSupport() predicate.
303 void EmitRawTextImpl(StringRef String) override;
305 void FinishImpl() override;
308 } // end anonymous namespace.
310 /// AddComment - Add a comment that can be emitted to the generated .s
311 /// file if applicable as a QoI issue to make the output of the compiler
312 /// more readable. This only affects the MCAsmStreamer, and only when
313 /// verbose assembly output is enabled.
314 /// By deafult EOL is set to true so that each comment goes on its own line.
315 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
316 if (!IsVerboseAsm) return;
318 T.toVector(CommentToEmit);
321 CommentToEmit.push_back('\n'); // Place comment in a new line.
324 void MCAsmStreamer::EmitCommentsAndEOL() {
325 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
330 StringRef Comments = CommentToEmit;
332 assert(Comments.back() == '\n' &&
333 "Comment array not newline terminated");
335 // Emit a line of comments.
336 OS.PadToColumn(MAI->getCommentColumn());
337 size_t Position = Comments.find('\n');
338 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
340 Comments = Comments.substr(Position+1);
341 } while (!Comments.empty());
343 CommentToEmit.clear();
346 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
347 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
348 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
351 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
354 OS << MAI->getCommentString() << T;
358 void MCAsmStreamer::addExplicitComment(const Twine &T) {
359 StringRef c = T.getSingleStringRef();
360 if (c.equals(StringRef(MAI->getSeparatorString())))
362 if (c.startswith(StringRef("//"))) {
363 ExplicitCommentToEmit.append("\t");
364 ExplicitCommentToEmit.append(MAI->getCommentString());
366 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
367 } else if (c.startswith(StringRef("/*"))) {
368 size_t p = 2, len = c.size() - 2;
369 // emit each line in comment as separate newline.
371 size_t newp = std::min(len, c.find_first_of("\r\n", p));
372 ExplicitCommentToEmit.append("\t");
373 ExplicitCommentToEmit.append(MAI->getCommentString());
374 ExplicitCommentToEmit.append(c.slice(p, newp).str());
375 // If we have another line in this comment add line
377 ExplicitCommentToEmit.append("\n");
380 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
381 ExplicitCommentToEmit.append("\t");
382 ExplicitCommentToEmit.append(c.str());
383 } else if (c.front() == '#') {
385 ExplicitCommentToEmit.append("\t");
386 ExplicitCommentToEmit.append(MAI->getCommentString());
387 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
389 assert(false && "Unexpected Assembly Comment");
390 // full line comments immediately output
391 if (c.back() == '\n')
392 emitExplicitComments();
395 void MCAsmStreamer::emitExplicitComments() {
396 StringRef Comments = ExplicitCommentToEmit;
397 if (!Comments.empty())
399 ExplicitCommentToEmit.clear();
402 void MCAsmStreamer::ChangeSection(MCSection *Section,
403 const MCExpr *Subsection) {
404 assert(Section && "Cannot switch to a null section!");
405 if (MCTargetStreamer *TS = getTargetStreamer()) {
406 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
408 Section->PrintSwitchToSection(
409 *MAI, getContext().getObjectFileInfo()->getTargetTriple(), OS,
414 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
415 MCStreamer::EmitLabel(Symbol, Loc);
417 Symbol->print(OS, MAI);
418 OS << MAI->getLabelSuffix();
423 void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
424 StringRef str = MCLOHIdToName(Kind);
427 int NbArgs = MCLOHIdToNbArgs(Kind);
428 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
429 assert(str != "" && "Invalid LOH name");
432 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
434 for (const MCSymbol *Arg : Args) {
443 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
445 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
446 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
447 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
448 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
449 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
454 void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
455 assert(!Options.empty() && "At least one option is required!");
456 OS << "\t.linker_option \"" << Options[0] << '"';
457 for (ArrayRef<std::string>::iterator it = Options.begin() + 1,
458 ie = Options.end(); it != ie; ++it) {
459 OS << ", " << '"' << *it << '"';
464 void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) {
465 if (!MAI->doesSupportDataRegionDirectives())
468 case MCDR_DataRegion: OS << "\t.data_region"; break;
469 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
470 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
471 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
472 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
477 static const char *getVersionMinDirective(MCVersionMinType Type) {
479 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
480 case MCVM_TvOSVersionMin: return ".tvos_version_min";
481 case MCVM_IOSVersionMin: return ".ios_version_min";
482 case MCVM_OSXVersionMin: return ".macosx_version_min";
484 llvm_unreachable("Invalid MC version min type");
487 void MCAsmStreamer::EmitVersionMin(MCVersionMinType Type, unsigned Major,
488 unsigned Minor, unsigned Update) {
489 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
491 OS << ", " << Update;
495 static const char *getPlatformName(MachO::PlatformType Type) {
497 case MachO::PLATFORM_MACOS: return "macos";
498 case MachO::PLATFORM_IOS: return "ios";
499 case MachO::PLATFORM_TVOS: return "tvos";
500 case MachO::PLATFORM_WATCHOS: return "watchos";
501 case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
503 llvm_unreachable("Invalid Mach-O platform type");
506 void MCAsmStreamer::EmitBuildVersion(unsigned Platform, unsigned Major,
507 unsigned Minor, unsigned Update) {
508 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
509 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
511 OS << ", " << Update;
515 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
516 // This needs to emit to a temporary string to get properly quoted
517 // MCSymbols when they have spaces in them.
518 OS << "\t.thumb_func";
519 // Only Mach-O hasSubsectionsViaSymbols()
520 if (MAI->hasSubsectionsViaSymbols()) {
522 Func->print(OS, MAI);
527 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
528 Symbol->print(OS, MAI);
530 Value->print(OS, MAI);
534 MCStreamer::EmitAssignment(Symbol, Value);
537 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
539 Alias->print(OS, MAI);
541 Symbol->print(OS, MAI);
545 bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
546 MCSymbolAttr Attribute) {
548 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
549 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
550 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
551 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
552 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
553 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
554 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
555 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
556 if (!MAI->hasDotTypeDotSizeDirective())
557 return false; // Symbol attribute not supported
559 Symbol->print(OS, MAI);
560 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
562 default: return false;
563 case MCSA_ELF_TypeFunction: OS << "function"; break;
564 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
565 case MCSA_ELF_TypeObject: OS << "object"; break;
566 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
567 case MCSA_ELF_TypeCommon: OS << "common"; break;
568 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
569 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
573 case MCSA_Global: // .globl/.global
574 OS << MAI->getGlobalDirective();
576 case MCSA_Hidden: OS << "\t.hidden\t"; break;
577 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
578 case MCSA_Internal: OS << "\t.internal\t"; break;
579 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
580 case MCSA_Local: OS << "\t.local\t"; break;
581 case MCSA_NoDeadStrip:
582 if (!MAI->hasNoDeadStrip())
584 OS << "\t.no_dead_strip\t";
586 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
587 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
588 case MCSA_PrivateExtern:
589 OS << "\t.private_extern\t";
591 case MCSA_Protected: OS << "\t.protected\t"; break;
592 case MCSA_Reference: OS << "\t.reference\t"; break;
593 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
594 case MCSA_WeakDefinition:
595 OS << "\t.weak_definition\t";
598 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
599 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
602 Symbol->print(OS, MAI);
608 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
609 OS << ".desc" << ' ';
610 Symbol->print(OS, MAI);
611 OS << ',' << DescValue;
615 void MCAsmStreamer::EmitSyntaxDirective() {
616 if (MAI->getAssemblerDialect() == 1) {
617 OS << "\t.intel_syntax noprefix";
620 // FIXME: Currently emit unprefix'ed registers.
621 // The intel_syntax directive has one optional argument
622 // with may have a value of prefix or noprefix.
625 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
627 Symbol->print(OS, MAI);
632 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
633 OS << "\t.scl\t" << StorageClass << ';';
637 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
638 OS << "\t.type\t" << Type << ';';
642 void MCAsmStreamer::EndCOFFSymbolDef() {
647 void MCAsmStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
648 OS << "\t.safeseh\t";
649 Symbol->print(OS, MAI);
653 void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {
655 Symbol->print(OS, MAI);
659 void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
660 OS << "\t.secrel32\t";
661 Symbol->print(OS, MAI);
667 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
668 assert(MAI->hasDotTypeDotSizeDirective());
670 Symbol->print(OS, MAI);
672 Value->print(OS, MAI);
676 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
677 unsigned ByteAlignment) {
679 Symbol->print(OS, MAI);
682 if (ByteAlignment != 0) {
683 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
684 OS << ',' << ByteAlignment;
686 OS << ',' << Log2_32(ByteAlignment);
691 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
693 /// @param Symbol - The common symbol to emit.
694 /// @param Size - The size of the common symbol.
695 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
696 unsigned ByteAlign) {
698 Symbol->print(OS, MAI);
702 switch (MAI->getLCOMMDirectiveAlignmentType()) {
703 case LCOMM::NoAlignment:
704 llvm_unreachable("alignment not supported on .lcomm!");
705 case LCOMM::ByteAlignment:
706 OS << ',' << ByteAlign;
708 case LCOMM::Log2Alignment:
709 assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2");
710 OS << ',' << Log2_32(ByteAlign);
717 void MCAsmStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
718 uint64_t Size, unsigned ByteAlignment) {
720 AssignFragment(Symbol, &Section->getDummyFragment());
722 // Note: a .zerofill directive does not switch sections.
725 // This is a mach-o specific directive.
726 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
727 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
731 Symbol->print(OS, MAI);
733 if (ByteAlignment != 0)
734 OS << ',' << Log2_32(ByteAlignment);
739 // .tbss sym, size, align
740 // This depends that the symbol has already been mangled from the original,
742 void MCAsmStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
743 uint64_t Size, unsigned ByteAlignment) {
744 AssignFragment(Symbol, &Section->getDummyFragment());
746 assert(Symbol && "Symbol shouldn't be NULL!");
747 // Instead of using the Section we'll just use the shortcut.
748 // This is a mach-o specific directive and section.
750 Symbol->print(OS, MAI);
753 // Output align if we have it. We default to 1 so don't bother printing
755 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
760 static inline char toOctal(int X) { return (X&7)+'0'; }
762 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
765 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
766 unsigned char C = Data[i];
767 if (C == '"' || C == '\\') {
768 OS << '\\' << (char)C;
772 if (isprint((unsigned char)C)) {
778 case '\b': OS << "\\b"; break;
779 case '\f': OS << "\\f"; break;
780 case '\n': OS << "\\n"; break;
781 case '\r': OS << "\\r"; break;
782 case '\t': OS << "\\t"; break;
785 OS << toOctal(C >> 6);
786 OS << toOctal(C >> 3);
787 OS << toOctal(C >> 0);
795 void MCAsmStreamer::EmitBytes(StringRef Data) {
796 assert(getCurrentSectionOnly() &&
797 "Cannot emit contents before setting section!");
798 if (Data.empty()) return;
800 // If only single byte is provided or no ascii or asciz directives is
801 // supported, emit as vector of 8bits data.
802 if (Data.size() == 1 ||
803 !(MAI->getAscizDirective() || MAI->getAsciiDirective())) {
804 const char *Directive = MAI->getData8bitsDirective();
805 for (const unsigned char C : Data.bytes()) {
806 OS << Directive << (unsigned)C;
812 // If the data ends with 0 and the target supports .asciz, use it, otherwise
814 if (MAI->getAscizDirective() && Data.back() == 0) {
815 OS << MAI->getAscizDirective();
816 Data = Data.substr(0, Data.size()-1);
818 OS << MAI->getAsciiDirective();
821 PrintQuotedString(Data, OS);
825 void MCAsmStreamer::EmitBinaryData(StringRef Data) {
826 // This is binary data. Print it in a grid of hex bytes for readability.
827 const size_t Cols = 4;
828 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
829 size_t J = I, EJ = std::min(I + Cols, Data.size());
831 OS << MAI->getData8bitsDirective();
832 for (; J < EJ - 1; ++J)
833 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
834 OS << format("0x%02x", uint8_t(Data[J]));
839 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) {
840 EmitValue(MCConstantExpr::create(Value, getContext()), Size);
843 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
845 assert(Size <= 8 && "Invalid size");
846 assert(getCurrentSectionOnly() &&
847 "Cannot emit contents before setting section!");
848 const char *Directive = nullptr;
851 case 1: Directive = MAI->getData8bitsDirective(); break;
852 case 2: Directive = MAI->getData16bitsDirective(); break;
853 case 4: Directive = MAI->getData32bitsDirective(); break;
854 case 8: Directive = MAI->getData64bitsDirective(); break;
859 if (!Value->evaluateAsAbsolute(IntValue))
860 report_fatal_error("Don't know how to emit this value.");
862 // We couldn't handle the requested integer size so we fallback by breaking
863 // the request down into several, smaller, integers.
864 // Since sizes greater or equal to "Size" are invalid, we use the greatest
865 // power of 2 that is less than "Size" as our largest piece of granularity.
866 bool IsLittleEndian = MAI->isLittleEndian();
867 for (unsigned Emitted = 0; Emitted != Size;) {
868 unsigned Remaining = Size - Emitted;
869 // The size of our partial emission must be a power of two less than
871 unsigned EmissionSize = PowerOf2Floor(std::min(Remaining, Size - 1));
872 // Calculate the byte offset of our partial emission taking into account
873 // the endianness of the target.
874 unsigned ByteOffset =
875 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
876 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
877 // We truncate our partial emission to fit within the bounds of the
878 // emission domain. This produces nicer output and silences potential
879 // truncation warnings when round tripping through another assembler.
880 uint64_t Shift = 64 - EmissionSize * 8;
881 assert(Shift < static_cast<uint64_t>(
882 std::numeric_limits<unsigned long long>::digits) &&
883 "undefined behavior");
884 ValueToEmit &= ~0ULL >> Shift;
885 EmitIntValue(ValueToEmit, EmissionSize);
886 Emitted += EmissionSize;
891 assert(Directive && "Invalid size for machine code value!");
893 if (MCTargetStreamer *TS = getTargetStreamer()) {
894 TS->emitValue(Value);
896 Value->print(OS, MAI);
901 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
903 if (Value->evaluateAsAbsolute(IntValue)) {
904 EmitULEB128IntValue(IntValue);
908 Value->print(OS, MAI);
912 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
914 if (Value->evaluateAsAbsolute(IntValue)) {
915 EmitSLEB128IntValue(IntValue);
919 Value->print(OS, MAI);
923 void MCAsmStreamer::EmitDTPRel64Value(const MCExpr *Value) {
924 assert(MAI->getDTPRel64Directive() != nullptr);
925 OS << MAI->getDTPRel64Directive();
926 Value->print(OS, MAI);
930 void MCAsmStreamer::EmitDTPRel32Value(const MCExpr *Value) {
931 assert(MAI->getDTPRel32Directive() != nullptr);
932 OS << MAI->getDTPRel32Directive();
933 Value->print(OS, MAI);
937 void MCAsmStreamer::EmitTPRel64Value(const MCExpr *Value) {
938 assert(MAI->getTPRel64Directive() != nullptr);
939 OS << MAI->getTPRel64Directive();
940 Value->print(OS, MAI);
944 void MCAsmStreamer::EmitTPRel32Value(const MCExpr *Value) {
945 assert(MAI->getTPRel32Directive() != nullptr);
946 OS << MAI->getTPRel32Directive();
947 Value->print(OS, MAI);
951 void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
952 assert(MAI->getGPRel64Directive() != nullptr);
953 OS << MAI->getGPRel64Directive();
954 Value->print(OS, MAI);
958 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
959 assert(MAI->getGPRel32Directive() != nullptr);
960 OS << MAI->getGPRel32Directive();
961 Value->print(OS, MAI);
965 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
968 if (NumBytes.evaluateAsAbsolute(IntNumBytes) && IntNumBytes == 0)
971 if (const char *ZeroDirective = MAI->getZeroDirective()) {
972 // FIXME: Emit location directives
974 NumBytes.print(OS, MAI);
976 OS << ',' << (int)FillValue;
981 MCStreamer::emitFill(NumBytes, FillValue);
984 void MCAsmStreamer::emitFill(uint64_t NumValues, int64_t Size, int64_t Expr) {
988 const MCExpr *E = MCConstantExpr::create(NumValues, getContext());
989 emitFill(*E, Size, Expr);
992 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
993 int64_t Expr, SMLoc Loc) {
994 // FIXME: Emit location directives
996 NumValues.print(OS, MAI);
997 OS << ", " << Size << ", 0x";
998 OS.write_hex(truncateToSize(Expr, 4));
1002 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
1004 unsigned MaxBytesToEmit) {
1005 // Some assemblers don't support non-power of two alignments, so we always
1006 // emit alignments as a power of two if possible.
1007 if (isPowerOf2_32(ByteAlignment)) {
1008 switch (ValueSize) {
1010 llvm_unreachable("Invalid size for machine code value!");
1012 OS << "\t.p2align\t";
1021 llvm_unreachable("Unsupported alignment size!");
1024 OS << Log2_32(ByteAlignment);
1026 if (Value || MaxBytesToEmit) {
1028 OS.write_hex(truncateToSize(Value, ValueSize));
1031 OS << ", " << MaxBytesToEmit;
1037 // Non-power of two alignment. This is not widely supported by assemblers.
1038 // FIXME: Parameterize this based on MAI.
1039 switch (ValueSize) {
1040 default: llvm_unreachable("Invalid size for machine code value!");
1041 case 1: OS << ".balign"; break;
1042 case 2: OS << ".balignw"; break;
1043 case 4: OS << ".balignl"; break;
1044 case 8: llvm_unreachable("Unsupported alignment size!");
1047 OS << ' ' << ByteAlignment;
1048 OS << ", " << truncateToSize(Value, ValueSize);
1050 OS << ", " << MaxBytesToEmit;
1054 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
1055 unsigned MaxBytesToEmit) {
1056 // Emit with a text fill value.
1057 EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(),
1061 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1062 unsigned char Value,
1064 // FIXME: Verify that Offset is associated with the current section.
1066 Offset->print(OS, MAI);
1067 OS << ", " << (unsigned)Value;
1071 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
1072 assert(MAI->hasSingleParameterDotFile());
1074 PrintQuotedString(Filename, OS);
1078 unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
1079 StringRef Directory,
1084 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1085 unsigned NumFiles = Table.getMCDwarfFiles().size();
1086 FileNo = Table.getFile(Directory, Filename, FileNo);
1089 if (NumFiles == Table.getMCDwarfFiles().size())
1092 SmallString<128> FullPathName;
1094 if (!UseDwarfDirectory && !Directory.empty()) {
1095 if (sys::path::is_absolute(Filename))
1098 FullPathName = Directory;
1099 sys::path::append(FullPathName, Filename);
1101 Filename = FullPathName;
1105 SmallString<128> Str;
1106 raw_svector_ostream OS1(Str);
1107 OS1 << "\t.file\t" << FileNo << ' ';
1108 if (!Directory.empty()) {
1109 PrintQuotedString(Directory, OS1);
1112 PrintQuotedString(Filename, OS1);
1113 if (MCTargetStreamer *TS = getTargetStreamer()) {
1114 TS->emitDwarfFileDirective(OS1.str());
1116 EmitRawText(OS1.str());
1122 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
1123 unsigned Column, unsigned Flags,
1125 unsigned Discriminator,
1126 StringRef FileName) {
1127 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1128 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1129 OS << " basic_block";
1130 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1131 OS << " prologue_end";
1132 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1133 OS << " epilogue_begin";
1135 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1136 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1139 if (Flags & DWARF2_FLAG_IS_STMT)
1146 OS << " isa " << Isa;
1148 OS << " discriminator " << Discriminator;
1151 OS.PadToColumn(MAI->getCommentColumn());
1152 OS << MAI->getCommentString() << ' ' << FileName << ':'
1153 << Line << ':' << Column;
1156 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
1157 Isa, Discriminator, FileName);
1160 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1161 // Always use the zeroth line table, since asm syntax only supports one line
1163 return MCStreamer::getDwarfLineTableSymbol(0);
1166 bool MCAsmStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
1167 ArrayRef<uint8_t> Checksum,
1168 unsigned ChecksumKind) {
1169 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1173 OS << "\t.cv_file\t" << FileNo << ' ';
1174 PrintQuotedString(Filename, OS);
1176 if (!ChecksumKind) {
1182 PrintQuotedString(toHex(Checksum), OS);
1183 OS << ' ' << ChecksumKind;
1189 bool MCAsmStreamer::EmitCVFuncIdDirective(unsigned FuncId) {
1190 OS << "\t.cv_func_id " << FuncId << '\n';
1191 return MCStreamer::EmitCVFuncIdDirective(FuncId);
1194 bool MCAsmStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
1197 unsigned IALine, unsigned IACol,
1199 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1200 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1201 return MCStreamer::EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1202 IALine, IACol, Loc);
1205 void MCAsmStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1206 unsigned Line, unsigned Column,
1207 bool PrologueEnd, bool IsStmt,
1208 StringRef FileName, SMLoc Loc) {
1209 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1212 OS << " prologue_end";
1214 unsigned OldIsStmt = getContext().getCVContext().getCurrentCVLoc().isStmt();
1215 if (IsStmt != OldIsStmt) {
1225 OS.PadToColumn(MAI->getCommentColumn());
1226 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1230 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
1231 PrologueEnd, IsStmt, FileName, Loc);
1234 void MCAsmStreamer::EmitCVLinetableDirective(unsigned FunctionId,
1235 const MCSymbol *FnStart,
1236 const MCSymbol *FnEnd) {
1237 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1238 FnStart->print(OS, MAI);
1240 FnEnd->print(OS, MAI);
1242 this->MCStreamer::EmitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1245 void MCAsmStreamer::EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1246 unsigned SourceFileId,
1247 unsigned SourceLineNum,
1248 const MCSymbol *FnStartSym,
1249 const MCSymbol *FnEndSym) {
1250 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1251 << ' ' << SourceLineNum << ' ';
1252 FnStartSym->print(OS, MAI);
1254 FnEndSym->print(OS, MAI);
1256 this->MCStreamer::EmitCVInlineLinetableDirective(
1257 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1260 void MCAsmStreamer::EmitCVDefRangeDirective(
1261 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1262 StringRef FixedSizePortion) {
1263 OS << "\t.cv_def_range\t";
1264 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1266 Range.first->print(OS, MAI);
1268 Range.second->print(OS, MAI);
1271 PrintQuotedString(FixedSizePortion, OS);
1273 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
1276 void MCAsmStreamer::EmitCVStringTableDirective() {
1277 OS << "\t.cv_stringtable";
1281 void MCAsmStreamer::EmitCVFileChecksumsDirective() {
1282 OS << "\t.cv_filechecksums";
1286 void MCAsmStreamer::EmitCVFileChecksumOffsetDirective(unsigned FileNo) {
1287 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1291 void MCAsmStreamer::EmitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1292 OS << "\t.cv_fpo_data\t";
1293 ProcSym->print(OS, MAI);
1297 void MCAsmStreamer::EmitIdent(StringRef IdentString) {
1298 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1300 PrintQuotedString(IdentString, OS);
1304 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
1305 MCStreamer::EmitCFISections(EH, Debug);
1306 OS << "\t.cfi_sections ";
1310 OS << ", .debug_frame";
1312 OS << ".debug_frame";
1318 void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1319 OS << "\t.cfi_startproc";
1325 void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1326 MCStreamer::EmitCFIEndProcImpl(Frame);
1327 OS << "\t.cfi_endproc";
1331 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1332 if (!MAI->useDwarfRegNumForCFI()) {
1333 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1334 // just ones that map to LLVM register numbers and have known names.
1335 // Fall back to using the original number directly if no name is known.
1336 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1337 int LLVMRegister = MRI->getLLVMRegNumFromEH(Register);
1338 if (LLVMRegister != -1) {
1339 InstPrinter->printRegName(OS, LLVMRegister);
1346 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
1347 MCStreamer::EmitCFIDefCfa(Register, Offset);
1348 OS << "\t.cfi_def_cfa ";
1349 EmitRegisterName(Register);
1350 OS << ", " << Offset;
1354 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
1355 MCStreamer::EmitCFIDefCfaOffset(Offset);
1356 OS << "\t.cfi_def_cfa_offset " << Offset;
1360 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1361 OS << "\t.cfi_escape ";
1362 if (!Values.empty()) {
1363 size_t e = Values.size() - 1;
1364 for (size_t i = 0; i < e; ++i)
1365 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1366 OS << format("0x%02x", uint8_t(Values[e]));
1370 void MCAsmStreamer::EmitCFIEscape(StringRef Values) {
1371 MCStreamer::EmitCFIEscape(Values);
1372 PrintCFIEscape(OS, Values);
1376 void MCAsmStreamer::EmitCFIGnuArgsSize(int64_t Size) {
1377 MCStreamer::EmitCFIGnuArgsSize(Size);
1379 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
1380 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
1382 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
1386 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
1387 MCStreamer::EmitCFIDefCfaRegister(Register);
1388 OS << "\t.cfi_def_cfa_register ";
1389 EmitRegisterName(Register);
1393 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
1394 this->MCStreamer::EmitCFIOffset(Register, Offset);
1395 OS << "\t.cfi_offset ";
1396 EmitRegisterName(Register);
1397 OS << ", " << Offset;
1401 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
1402 unsigned Encoding) {
1403 MCStreamer::EmitCFIPersonality(Sym, Encoding);
1404 OS << "\t.cfi_personality " << Encoding << ", ";
1405 Sym->print(OS, MAI);
1409 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
1410 MCStreamer::EmitCFILsda(Sym, Encoding);
1411 OS << "\t.cfi_lsda " << Encoding << ", ";
1412 Sym->print(OS, MAI);
1416 void MCAsmStreamer::EmitCFIRememberState() {
1417 MCStreamer::EmitCFIRememberState();
1418 OS << "\t.cfi_remember_state";
1422 void MCAsmStreamer::EmitCFIRestoreState() {
1423 MCStreamer::EmitCFIRestoreState();
1424 OS << "\t.cfi_restore_state";
1428 void MCAsmStreamer::EmitCFIRestore(int64_t Register) {
1429 MCStreamer::EmitCFIRestore(Register);
1430 OS << "\t.cfi_restore ";
1431 EmitRegisterName(Register);
1435 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
1436 MCStreamer::EmitCFISameValue(Register);
1437 OS << "\t.cfi_same_value ";
1438 EmitRegisterName(Register);
1442 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
1443 MCStreamer::EmitCFIRelOffset(Register, Offset);
1444 OS << "\t.cfi_rel_offset ";
1445 EmitRegisterName(Register);
1446 OS << ", " << Offset;
1450 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
1451 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
1452 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
1456 void MCAsmStreamer::EmitCFISignalFrame() {
1457 MCStreamer::EmitCFISignalFrame();
1458 OS << "\t.cfi_signal_frame";
1462 void MCAsmStreamer::EmitCFIUndefined(int64_t Register) {
1463 MCStreamer::EmitCFIUndefined(Register);
1464 OS << "\t.cfi_undefined " << Register;
1468 void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) {
1469 MCStreamer::EmitCFIRegister(Register1, Register2);
1470 OS << "\t.cfi_register " << Register1 << ", " << Register2;
1474 void MCAsmStreamer::EmitCFIWindowSave() {
1475 MCStreamer::EmitCFIWindowSave();
1476 OS << "\t.cfi_window_save";
1480 void MCAsmStreamer::EmitCFIReturnColumn(int64_t Register) {
1481 MCStreamer::EmitCFIReturnColumn(Register);
1482 OS << "\t.cfi_return_column " << Register;
1486 void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
1487 MCStreamer::EmitWinCFIStartProc(Symbol, Loc);
1490 Symbol->print(OS, MAI);
1494 void MCAsmStreamer::EmitWinCFIEndProc(SMLoc Loc) {
1495 MCStreamer::EmitWinCFIEndProc(Loc);
1497 OS << "\t.seh_endproc";
1501 void MCAsmStreamer::EmitWinCFIStartChained(SMLoc Loc) {
1502 MCStreamer::EmitWinCFIStartChained(Loc);
1504 OS << "\t.seh_startchained";
1508 void MCAsmStreamer::EmitWinCFIEndChained(SMLoc Loc) {
1509 MCStreamer::EmitWinCFIEndChained(Loc);
1511 OS << "\t.seh_endchained";
1515 void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind,
1516 bool Except, SMLoc Loc) {
1517 MCStreamer::EmitWinEHHandler(Sym, Unwind, Except, Loc);
1519 OS << "\t.seh_handler ";
1520 Sym->print(OS, MAI);
1528 void MCAsmStreamer::EmitWinEHHandlerData(SMLoc Loc) {
1529 MCStreamer::EmitWinEHHandlerData(Loc);
1531 // Switch sections. Don't call SwitchSection directly, because that will
1532 // cause the section switch to be visible in the emitted assembly.
1533 // We only do this so the section switch that terminates the handler
1534 // data block is visible.
1535 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
1536 MCSection *TextSec = &CurFrame->Function->getSection();
1537 MCSection *XData = getAssociatedXDataSection(TextSec);
1538 SwitchSectionNoChange(XData);
1540 OS << "\t.seh_handlerdata";
1544 void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register, SMLoc Loc) {
1545 MCStreamer::EmitWinCFIPushReg(Register, Loc);
1547 OS << "\t.seh_pushreg " << Register;
1551 void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset,
1553 MCStreamer::EmitWinCFISetFrame(Register, Offset, Loc);
1555 OS << "\t.seh_setframe " << Register << ", " << Offset;
1559 void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
1560 MCStreamer::EmitWinCFIAllocStack(Size, Loc);
1562 OS << "\t.seh_stackalloc " << Size;
1566 void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset,
1568 MCStreamer::EmitWinCFISaveReg(Register, Offset, Loc);
1570 OS << "\t.seh_savereg " << Register << ", " << Offset;
1574 void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
1576 MCStreamer::EmitWinCFISaveXMM(Register, Offset, Loc);
1578 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1582 void MCAsmStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
1583 MCStreamer::EmitWinCFIPushFrame(Code, Loc);
1585 OS << "\t.seh_pushframe";
1591 void MCAsmStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
1592 MCStreamer::EmitWinCFIEndProlog(Loc);
1594 OS << "\t.seh_endprologue";
1598 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
1599 const MCSubtargetInfo &STI,
1600 bool PrintSchedInfo) {
1601 raw_ostream &OS = GetCommentOS();
1602 SmallString<256> Code;
1603 SmallVector<MCFixup, 4> Fixups;
1604 raw_svector_ostream VecOS(Code);
1605 Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
1607 // If we are showing fixups, create symbolic markers in the encoded
1608 // representation. We do this by making a per-bit map to the fixup item index,
1609 // then trying to display it as nicely as possible.
1610 SmallVector<uint8_t, 64> FixupMap;
1611 FixupMap.resize(Code.size() * 8);
1612 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1615 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1616 MCFixup &F = Fixups[i];
1617 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1618 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1619 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1620 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1621 FixupMap[Index] = 1 + i;
1625 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1626 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1627 OS << "encoding: [";
1628 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1632 // See if all bits are the same map entry.
1633 uint8_t MapEntry = FixupMap[i * 8 + 0];
1634 for (unsigned j = 1; j != 8; ++j) {
1635 if (FixupMap[i * 8 + j] == MapEntry)
1638 MapEntry = uint8_t(~0U);
1642 if (MapEntry != uint8_t(~0U)) {
1643 if (MapEntry == 0) {
1644 OS << format("0x%02x", uint8_t(Code[i]));
1647 // FIXME: Some of the 8 bits require fix up.
1648 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1649 << char('A' + MapEntry - 1) << '\'';
1651 OS << char('A' + MapEntry - 1);
1654 // Otherwise, write out in binary.
1656 for (unsigned j = 8; j--;) {
1657 unsigned Bit = (Code[i] >> j) & 1;
1660 if (MAI->isLittleEndian())
1661 FixupBit = i * 8 + j;
1663 FixupBit = i * 8 + (7-j);
1665 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1666 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1667 OS << char('A' + MapEntry - 1);
1674 // If we are not going to add fixup or schedule comments after this point
1675 // then we have to end the current comment line with "\n".
1676 if (Fixups.size() || !PrintSchedInfo)
1679 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1680 MCFixup &F = Fixups[i];
1681 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1682 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1683 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1687 void MCAsmStreamer::EmitInstruction(const MCInst &Inst,
1688 const MCSubtargetInfo &STI,
1689 bool PrintSchedInfo) {
1690 assert(getCurrentSectionOnly() &&
1691 "Cannot emit contents before setting section!");
1693 // Show the encoding in a comment if we have a code emitter.
1695 AddEncodingComment(Inst, STI, PrintSchedInfo);
1697 // Show the MCInst if enabled.
1700 GetCommentOS() << "\n";
1701 Inst.dump_pretty(GetCommentOS(), InstPrinter.get(), "\n ");
1702 GetCommentOS() << "\n";
1705 if(getTargetStreamer())
1706 getTargetStreamer()->prettyPrintAsm(*InstPrinter, OS, Inst, STI);
1708 InstPrinter->printInst(&Inst, OS, "", STI);
1710 if (PrintSchedInfo) {
1711 std::string SI = STI.getSchedInfoStr(Inst);
1713 GetCommentOS() << SI;
1716 StringRef Comments = CommentToEmit;
1717 if (Comments.size() && Comments.back() != '\n')
1718 GetCommentOS() << "\n";
1723 void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
1724 OS << "\t.bundle_align_mode " << AlignPow2;
1728 void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) {
1729 OS << "\t.bundle_lock";
1731 OS << " align_to_end";
1735 void MCAsmStreamer::EmitBundleUnlock() {
1736 OS << "\t.bundle_unlock";
1740 bool MCAsmStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
1741 const MCExpr *Expr, SMLoc) {
1743 Offset.print(OS, MAI);
1747 Expr->print(OS, MAI);
1753 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1754 /// the specified string in the output .s file. This capability is
1755 /// indicated by the hasRawTextSupport() predicate.
1756 void MCAsmStreamer::EmitRawTextImpl(StringRef String) {
1757 if (!String.empty() && String.back() == '\n')
1758 String = String.substr(0, String.size()-1);
1763 void MCAsmStreamer::FinishImpl() {
1764 // If we are generating dwarf for assembly source files dump out the sections.
1765 if (getContext().getGenDwarfForAssembly())
1766 MCGenDwarfInfo::Emit(this);
1768 // Emit the label for the line table, if requested - since the rest of the
1769 // line table will be defined by .loc/.file directives, and not emitted
1770 // directly, the label is the only work required here.
1771 auto &Tables = getContext().getMCDwarfLineTables();
1772 if (!Tables.empty()) {
1773 assert(Tables.size() == 1 && "asm output only supports one line table");
1774 if (auto *Label = Tables.begin()->second.getLabel()) {
1775 SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
1781 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1782 std::unique_ptr<formatted_raw_ostream> OS,
1783 bool isVerboseAsm, bool useDwarfDirectory,
1784 MCInstPrinter *IP, MCCodeEmitter *CE,
1785 MCAsmBackend *MAB, bool ShowInst) {
1786 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
1787 useDwarfDirectory, IP, CE, MAB, ShowInst);