Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / MC / MCAsmStreamer.cpp
blobfb809f4010f77bd065428b3a727647ba82a3ccfb
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCAssembler.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/MCObjectWriter.h"
25 #include "llvm/MC/MCPseudoProbe.h"
26 #include "llvm/MC/MCRegister.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbolXCOFF.h"
31 #include "llvm/MC/TargetRegistry.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Path.h"
39 #include <algorithm>
40 #include <optional>
42 using namespace llvm;
44 namespace {
46 class MCAsmStreamer final : public MCStreamer {
47 std::unique_ptr<formatted_raw_ostream> OSOwner;
48 formatted_raw_ostream &OS;
49 const MCAsmInfo *MAI;
50 std::unique_ptr<MCInstPrinter> InstPrinter;
51 std::unique_ptr<MCAssembler> Assembler;
53 SmallString<128> ExplicitCommentToEmit;
54 SmallString<128> CommentToEmit;
55 raw_svector_ostream CommentStream;
56 raw_null_ostream NullStream;
58 unsigned IsVerboseAsm : 1;
59 unsigned ShowInst : 1;
60 unsigned UseDwarfDirectory : 1;
62 void EmitRegisterName(int64_t Register);
63 void PrintQuotedString(StringRef Data, raw_ostream &OS) const;
64 void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
65 StringRef Filename,
66 std::optional<MD5::MD5Result> Checksum,
67 std::optional<StringRef> Source,
68 bool UseDwarfDirectory,
69 raw_svector_ostream &OS) const;
70 void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
71 void emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
73 public:
74 MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
75 bool isVerboseAsm, bool useDwarfDirectory,
76 MCInstPrinter *printer, std::unique_ptr<MCCodeEmitter> emitter,
77 std::unique_ptr<MCAsmBackend> asmbackend, bool showInst)
78 : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
79 MAI(Context.getAsmInfo()), InstPrinter(printer),
80 Assembler(std::make_unique<MCAssembler>(
81 Context, std::move(asmbackend), std::move(emitter),
82 (asmbackend) ? asmbackend->createObjectWriter(NullStream)
83 : nullptr)),
84 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
85 ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
86 assert(InstPrinter);
87 if (IsVerboseAsm)
88 InstPrinter->setCommentStream(CommentStream);
89 if (Assembler->getBackendPtr())
90 setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
92 Context.setUseNamesOnTempLabels(true);
95 MCAssembler &getAssembler() { return *Assembler; }
96 MCAssembler *getAssemblerPtr() override { return nullptr; }
98 inline void EmitEOL() {
99 // Dump Explicit Comments here.
100 emitExplicitComments();
101 // If we don't have any comments, just emit a \n.
102 if (!IsVerboseAsm) {
103 OS << '\n';
104 return;
106 EmitCommentsAndEOL();
109 void emitSyntaxDirective() override;
111 void EmitCommentsAndEOL();
113 /// Return true if this streamer supports verbose assembly at all.
114 bool isVerboseAsm() const override { return IsVerboseAsm; }
116 /// Do we support EmitRawText?
117 bool hasRawTextSupport() const override { return true; }
119 /// Add a comment that can be emitted to the generated .s file to make the
120 /// output of the compiler more readable. This only affects the MCAsmStreamer
121 /// and only when verbose assembly output is enabled.
122 void AddComment(const Twine &T, bool EOL = true) override;
124 /// Add a comment showing the encoding of an instruction.
125 void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
127 /// Return a raw_ostream that comments can be written to.
128 /// Unlike AddComment, you are required to terminate comments with \n if you
129 /// use this method.
130 raw_ostream &getCommentOS() override {
131 if (!IsVerboseAsm)
132 return nulls(); // Discard comments unless in verbose asm mode.
133 return CommentStream;
136 void emitRawComment(const Twine &T, bool TabPrefix = true) override;
138 void addExplicitComment(const Twine &T) override;
139 void emitExplicitComments() override;
141 /// Emit a blank line to a .s file to pretty it up.
142 void addBlankLine() override { EmitEOL(); }
144 /// @name MCStreamer Interface
145 /// @{
147 void changeSection(MCSection *Section, const MCExpr *Subsection) override;
149 void emitELFSymverDirective(const MCSymbol *OriginalSym, StringRef Name,
150 bool KeepOriginalSym) override;
152 void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
154 void emitGNUAttribute(unsigned Tag, unsigned Value) override;
156 StringRef getMnemonic(MCInst &MI) override {
157 return InstPrinter->getMnemonic(&MI).first;
160 void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
162 void emitAssemblerFlag(MCAssemblerFlag Flag) override;
163 void emitLinkerOptions(ArrayRef<std::string> Options) override;
164 void emitDataRegion(MCDataRegionType Kind) override;
165 void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
166 unsigned Update, VersionTuple SDKVersion) override;
167 void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
168 unsigned Update, VersionTuple SDKVersion) override;
169 void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
170 unsigned Minor, unsigned Update,
171 VersionTuple SDKVersion) override;
172 void emitThumbFunc(MCSymbol *Func) override;
174 void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
175 void emitConditionalAssignment(MCSymbol *Symbol,
176 const MCExpr *Value) override;
177 void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
178 bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
180 void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
181 void beginCOFFSymbolDef(const MCSymbol *Symbol) override;
182 void emitCOFFSymbolStorageClass(int StorageClass) override;
183 void emitCOFFSymbolType(int Type) override;
184 void endCOFFSymbolDef() override;
185 void emitCOFFSafeSEH(MCSymbol const *Symbol) override;
186 void emitCOFFSymbolIndex(MCSymbol const *Symbol) override;
187 void emitCOFFSectionIndex(MCSymbol const *Symbol) override;
188 void emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
189 void emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
190 void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
191 MCSymbol *CsectSym, Align Alignment) override;
192 void emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
193 MCSymbolAttr Linakge,
194 MCSymbolAttr Visibility) override;
195 void emitXCOFFRenameDirective(const MCSymbol *Name,
196 StringRef Rename) override;
198 void emitXCOFFRefDirective(const MCSymbol *Symbol) override;
200 void emitXCOFFExceptDirective(const MCSymbol *Symbol,
201 const MCSymbol *Trap,
202 unsigned Lang, unsigned Reason,
203 unsigned FunctionSize, bool hasDebug) override;
204 void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
206 void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
207 void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
208 Align ByteAlignment) override;
210 /// Emit a local common (.lcomm) symbol.
212 /// @param Symbol - The common symbol to emit.
213 /// @param Size - The size of the common symbol.
214 /// @param ByteAlignment - The alignment of the common symbol in bytes.
215 void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
216 Align ByteAlignment) override;
218 void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
219 uint64_t Size = 0, Align ByteAlignment = Align(1),
220 SMLoc Loc = SMLoc()) override;
222 void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
223 Align ByteAlignment = Align(1)) override;
225 void emitBinaryData(StringRef Data) override;
227 void emitBytes(StringRef Data) override;
229 void emitValueImpl(const MCExpr *Value, unsigned Size,
230 SMLoc Loc = SMLoc()) override;
231 void emitIntValue(uint64_t Value, unsigned Size) override;
232 void emitIntValueInHex(uint64_t Value, unsigned Size) override;
233 void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) override;
235 void emitULEB128Value(const MCExpr *Value) override;
237 void emitSLEB128Value(const MCExpr *Value) override;
239 void emitDTPRel32Value(const MCExpr *Value) override;
240 void emitDTPRel64Value(const MCExpr *Value) override;
241 void emitTPRel32Value(const MCExpr *Value) override;
242 void emitTPRel64Value(const MCExpr *Value) override;
244 void emitGPRel64Value(const MCExpr *Value) override;
246 void emitGPRel32Value(const MCExpr *Value) override;
248 void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
249 SMLoc Loc = SMLoc()) override;
251 void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
252 SMLoc Loc = SMLoc()) override;
254 void emitAlignmentDirective(unsigned ByteAlignment,
255 std::optional<int64_t> Value, unsigned ValueSize,
256 unsigned MaxBytesToEmit);
258 void emitValueToAlignment(Align Alignment, int64_t Value = 0,
259 unsigned ValueSize = 1,
260 unsigned MaxBytesToEmit = 0) override;
262 void emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI,
263 unsigned MaxBytesToEmit = 0) override;
265 void emitValueToOffset(const MCExpr *Offset,
266 unsigned char Value,
267 SMLoc Loc) override;
269 void emitFileDirective(StringRef Filename) override;
270 void emitFileDirective(StringRef Filename, StringRef CompilerVerion,
271 StringRef TimeStamp, StringRef Description) override;
272 Expected<unsigned> tryEmitDwarfFileDirective(
273 unsigned FileNo, StringRef Directory, StringRef Filename,
274 std::optional<MD5::MD5Result> Checksum = std::nullopt,
275 std::optional<StringRef> Source = std::nullopt,
276 unsigned CUID = 0) override;
277 void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
278 std::optional<MD5::MD5Result> Checksum,
279 std::optional<StringRef> Source,
280 unsigned CUID = 0) override;
281 void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column,
282 unsigned Flags, unsigned Isa,
283 unsigned Discriminator,
284 StringRef FileName) override;
285 MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
287 bool emitCVFileDirective(unsigned FileNo, StringRef Filename,
288 ArrayRef<uint8_t> Checksum,
289 unsigned ChecksumKind) override;
290 bool emitCVFuncIdDirective(unsigned FuncId) override;
291 bool emitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
292 unsigned IAFile, unsigned IALine,
293 unsigned IACol, SMLoc Loc) override;
294 void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
295 unsigned Column, bool PrologueEnd, bool IsStmt,
296 StringRef FileName, SMLoc Loc) override;
297 void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
298 const MCSymbol *FnEnd) override;
299 void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
300 unsigned SourceFileId,
301 unsigned SourceLineNum,
302 const MCSymbol *FnStartSym,
303 const MCSymbol *FnEndSym) override;
305 void PrintCVDefRangePrefix(
306 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
308 void emitCVDefRangeDirective(
309 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
310 codeview::DefRangeRegisterRelHeader DRHdr) override;
312 void emitCVDefRangeDirective(
313 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
314 codeview::DefRangeSubfieldRegisterHeader DRHdr) override;
316 void emitCVDefRangeDirective(
317 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
318 codeview::DefRangeRegisterHeader DRHdr) override;
320 void emitCVDefRangeDirective(
321 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
322 codeview::DefRangeFramePointerRelHeader DRHdr) override;
324 void emitCVStringTableDirective() override;
325 void emitCVFileChecksumsDirective() override;
326 void emitCVFileChecksumOffsetDirective(unsigned FileNo) override;
327 void emitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
329 void emitIdent(StringRef IdentString) override;
330 void emitCFIBKeyFrame() override;
331 void emitCFIMTETaggedFrame() override;
332 void emitCFISections(bool EH, bool Debug) override;
333 void emitCFIDefCfa(int64_t Register, int64_t Offset, SMLoc Loc) override;
334 void emitCFIDefCfaOffset(int64_t Offset, SMLoc Loc) override;
335 void emitCFIDefCfaRegister(int64_t Register, SMLoc Loc) override;
336 void emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
337 int64_t AddressSpace, SMLoc Loc) override;
338 void emitCFIOffset(int64_t Register, int64_t Offset, SMLoc Loc) override;
339 void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
340 void emitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
341 void emitCFIRememberState(SMLoc Loc) override;
342 void emitCFIRestoreState(SMLoc Loc) override;
343 void emitCFIRestore(int64_t Register, SMLoc Loc) override;
344 void emitCFISameValue(int64_t Register, SMLoc Loc) override;
345 void emitCFIRelOffset(int64_t Register, int64_t Offset, SMLoc Loc) override;
346 void emitCFIAdjustCfaOffset(int64_t Adjustment, SMLoc Loc) override;
347 void emitCFIEscape(StringRef Values, SMLoc Loc) override;
348 void emitCFIGnuArgsSize(int64_t Size, SMLoc Loc) override;
349 void emitCFISignalFrame() override;
350 void emitCFIUndefined(int64_t Register, SMLoc Loc) override;
351 void emitCFIRegister(int64_t Register1, int64_t Register2,
352 SMLoc Loc) override;
353 void emitCFIWindowSave(SMLoc Loc) override;
354 void emitCFINegateRAState(SMLoc Loc) override;
355 void emitCFIReturnColumn(int64_t Register) override;
357 void emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
358 void emitWinCFIEndProc(SMLoc Loc) override;
359 void emitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
360 void emitWinCFIStartChained(SMLoc Loc) override;
361 void emitWinCFIEndChained(SMLoc Loc) override;
362 void emitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
363 void emitWinCFISetFrame(MCRegister Register, unsigned Offset,
364 SMLoc Loc) override;
365 void emitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
366 void emitWinCFISaveReg(MCRegister Register, unsigned Offset,
367 SMLoc Loc) override;
368 void emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
369 SMLoc Loc) override;
370 void emitWinCFIPushFrame(bool Code, SMLoc Loc) override;
371 void emitWinCFIEndProlog(SMLoc Loc) override;
373 void emitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
374 SMLoc Loc) override;
375 void emitWinEHHandlerData(SMLoc Loc) override;
377 void emitCGProfileEntry(const MCSymbolRefExpr *From,
378 const MCSymbolRefExpr *To, uint64_t Count) override;
380 void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
382 void emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
383 uint64_t Attr, uint64_t Discriminator,
384 const MCPseudoProbeInlineStack &InlineStack,
385 MCSymbol *FnSym) override;
387 void emitBundleAlignMode(Align Alignment) override;
388 void emitBundleLock(bool AlignToEnd) override;
389 void emitBundleUnlock() override;
391 std::optional<std::pair<bool, std::string>>
392 emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr,
393 SMLoc Loc, const MCSubtargetInfo &STI) override;
395 void emitAddrsig() override;
396 void emitAddrsigSym(const MCSymbol *Sym) override;
398 /// If this file is backed by an assembly streamer, this dumps the specified
399 /// string in the output .s file. This capability is indicated by the
400 /// hasRawTextSupport() predicate.
401 void emitRawTextImpl(StringRef String) override;
403 void finishImpl() override;
405 void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) override;
407 MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
408 const Twine &Comment) override;
410 void emitDwarfLineStartLabel(MCSymbol *StartSym) override;
412 void emitDwarfLineEndEntry(MCSection *Section, MCSymbol *LastLabel) override;
414 void emitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
415 const MCSymbol *Label,
416 unsigned PointerSize) override;
418 void doFinalizationAtSectionEnd(MCSection *Section) override;
421 } // end anonymous namespace.
423 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
424 if (!IsVerboseAsm) return;
426 T.toVector(CommentToEmit);
428 if (EOL)
429 CommentToEmit.push_back('\n'); // Place comment in a new line.
432 void MCAsmStreamer::EmitCommentsAndEOL() {
433 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
434 OS << '\n';
435 return;
438 StringRef Comments = CommentToEmit;
440 assert(Comments.back() == '\n' &&
441 "Comment array not newline terminated");
442 do {
443 // Emit a line of comments.
444 OS.PadToColumn(MAI->getCommentColumn());
445 size_t Position = Comments.find('\n');
446 OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
448 Comments = Comments.substr(Position+1);
449 } while (!Comments.empty());
451 CommentToEmit.clear();
454 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
455 assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
456 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
459 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
460 if (TabPrefix)
461 OS << '\t';
462 OS << MAI->getCommentString() << T;
463 EmitEOL();
466 void MCAsmStreamer::addExplicitComment(const Twine &T) {
467 StringRef c = T.getSingleStringRef();
468 if (c.equals(StringRef(MAI->getSeparatorString())))
469 return;
470 if (c.startswith(StringRef("//"))) {
471 ExplicitCommentToEmit.append("\t");
472 ExplicitCommentToEmit.append(MAI->getCommentString());
473 // drop //
474 ExplicitCommentToEmit.append(c.slice(2, c.size()).str());
475 } else if (c.startswith(StringRef("/*"))) {
476 size_t p = 2, len = c.size() - 2;
477 // emit each line in comment as separate newline.
478 do {
479 size_t newp = std::min(len, c.find_first_of("\r\n", p));
480 ExplicitCommentToEmit.append("\t");
481 ExplicitCommentToEmit.append(MAI->getCommentString());
482 ExplicitCommentToEmit.append(c.slice(p, newp).str());
483 // If we have another line in this comment add line
484 if (newp < len)
485 ExplicitCommentToEmit.append("\n");
486 p = newp + 1;
487 } while (p < len);
488 } else if (c.startswith(StringRef(MAI->getCommentString()))) {
489 ExplicitCommentToEmit.append("\t");
490 ExplicitCommentToEmit.append(c.str());
491 } else if (c.front() == '#') {
493 ExplicitCommentToEmit.append("\t");
494 ExplicitCommentToEmit.append(MAI->getCommentString());
495 ExplicitCommentToEmit.append(c.slice(1, c.size()).str());
496 } else
497 assert(false && "Unexpected Assembly Comment");
498 // full line comments immediately output
499 if (c.back() == '\n')
500 emitExplicitComments();
503 void MCAsmStreamer::emitExplicitComments() {
504 StringRef Comments = ExplicitCommentToEmit;
505 if (!Comments.empty())
506 OS << Comments;
507 ExplicitCommentToEmit.clear();
510 void MCAsmStreamer::changeSection(MCSection *Section,
511 const MCExpr *Subsection) {
512 assert(Section && "Cannot switch to a null section!");
513 if (MCTargetStreamer *TS = getTargetStreamer()) {
514 TS->changeSection(getCurrentSectionOnly(), Section, Subsection, OS);
515 } else {
516 Section->printSwitchToSection(*MAI, getContext().getTargetTriple(), OS,
517 Subsection);
521 void MCAsmStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
522 StringRef Name,
523 bool KeepOriginalSym) {
524 OS << ".symver ";
525 OriginalSym->print(OS, MAI);
526 OS << ", " << Name;
527 if (!KeepOriginalSym && !Name.contains("@@@"))
528 OS << ", remove";
529 EmitEOL();
532 void MCAsmStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
533 MCStreamer::emitLabel(Symbol, Loc);
535 Symbol->print(OS, MAI);
536 OS << MAI->getLabelSuffix();
538 EmitEOL();
541 void MCAsmStreamer::emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
542 StringRef str = MCLOHIdToName(Kind);
544 #ifndef NDEBUG
545 int NbArgs = MCLOHIdToNbArgs(Kind);
546 assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
547 assert(str != "" && "Invalid LOH name");
548 #endif
550 OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
551 bool IsFirst = true;
552 for (const MCSymbol *Arg : Args) {
553 if (!IsFirst)
554 OS << ", ";
555 IsFirst = false;
556 Arg->print(OS, MAI);
558 EmitEOL();
561 void MCAsmStreamer::emitGNUAttribute(unsigned Tag, unsigned Value) {
562 OS << "\t.gnu_attribute " << Tag << ", " << Value << "\n";
565 void MCAsmStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
566 switch (Flag) {
567 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
568 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
569 case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break;
570 case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break;
571 case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break;
573 EmitEOL();
576 void MCAsmStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
577 assert(!Options.empty() && "At least one option is required!");
578 OS << "\t.linker_option \"" << Options[0] << '"';
579 for (const std::string &Opt : llvm::drop_begin(Options))
580 OS << ", " << '"' << Opt << '"';
581 EmitEOL();
584 void MCAsmStreamer::emitDataRegion(MCDataRegionType Kind) {
585 if (!MAI->doesSupportDataRegionDirectives())
586 return;
587 switch (Kind) {
588 case MCDR_DataRegion: OS << "\t.data_region"; break;
589 case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break;
590 case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break;
591 case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break;
592 case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break;
594 EmitEOL();
597 static const char *getVersionMinDirective(MCVersionMinType Type) {
598 switch (Type) {
599 case MCVM_WatchOSVersionMin: return ".watchos_version_min";
600 case MCVM_TvOSVersionMin: return ".tvos_version_min";
601 case MCVM_IOSVersionMin: return ".ios_version_min";
602 case MCVM_OSXVersionMin: return ".macosx_version_min";
604 llvm_unreachable("Invalid MC version min type");
607 static void EmitSDKVersionSuffix(raw_ostream &OS,
608 const VersionTuple &SDKVersion) {
609 if (SDKVersion.empty())
610 return;
611 OS << '\t' << "sdk_version " << SDKVersion.getMajor();
612 if (auto Minor = SDKVersion.getMinor()) {
613 OS << ", " << *Minor;
614 if (auto Subminor = SDKVersion.getSubminor()) {
615 OS << ", " << *Subminor;
620 void MCAsmStreamer::emitVersionMin(MCVersionMinType Type, unsigned Major,
621 unsigned Minor, unsigned Update,
622 VersionTuple SDKVersion) {
623 OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
624 if (Update)
625 OS << ", " << Update;
626 EmitSDKVersionSuffix(OS, SDKVersion);
627 EmitEOL();
630 static const char *getPlatformName(MachO::PlatformType Type) {
631 switch (Type) {
632 #define PLATFORM(platform, id, name, build_name, target, tapi_target, \
633 marketing) \
634 case MachO::PLATFORM_##platform: \
635 return #build_name;
636 #include "llvm/BinaryFormat/MachO.def"
638 llvm_unreachable("Invalid Mach-O platform type");
641 void MCAsmStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
642 unsigned Minor, unsigned Update,
643 VersionTuple SDKVersion) {
644 const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
645 OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
646 if (Update)
647 OS << ", " << Update;
648 EmitSDKVersionSuffix(OS, SDKVersion);
649 EmitEOL();
652 void MCAsmStreamer::emitDarwinTargetVariantBuildVersion(
653 unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
654 VersionTuple SDKVersion) {
655 emitBuildVersion(Platform, Major, Minor, Update, SDKVersion);
658 void MCAsmStreamer::emitThumbFunc(MCSymbol *Func) {
659 // This needs to emit to a temporary string to get properly quoted
660 // MCSymbols when they have spaces in them.
661 OS << "\t.thumb_func";
662 // Only Mach-O hasSubsectionsViaSymbols()
663 if (MAI->hasSubsectionsViaSymbols()) {
664 OS << '\t';
665 Func->print(OS, MAI);
667 EmitEOL();
670 void MCAsmStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
671 // Do not emit a .set on inlined target assignments.
672 bool EmitSet = true;
673 if (auto *E = dyn_cast<MCTargetExpr>(Value))
674 if (E->inlineAssignedExpr())
675 EmitSet = false;
676 if (EmitSet) {
677 OS << ".set ";
678 Symbol->print(OS, MAI);
679 OS << ", ";
680 Value->print(OS, MAI);
682 EmitEOL();
685 MCStreamer::emitAssignment(Symbol, Value);
688 void MCAsmStreamer::emitConditionalAssignment(MCSymbol *Symbol,
689 const MCExpr *Value) {
690 OS << ".lto_set_conditional ";
691 Symbol->print(OS, MAI);
692 OS << ", ";
693 Value->print(OS, MAI);
694 EmitEOL();
697 void MCAsmStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
698 OS << ".weakref ";
699 Alias->print(OS, MAI);
700 OS << ", ";
701 Symbol->print(OS, MAI);
702 EmitEOL();
705 bool MCAsmStreamer::emitSymbolAttribute(MCSymbol *Symbol,
706 MCSymbolAttr Attribute) {
707 switch (Attribute) {
708 case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
709 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
710 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
711 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
712 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
713 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
714 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
715 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
716 if (!MAI->hasDotTypeDotSizeDirective())
717 return false; // Symbol attribute not supported
718 OS << "\t.type\t";
719 Symbol->print(OS, MAI);
720 OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
721 switch (Attribute) {
722 default: return false;
723 case MCSA_ELF_TypeFunction: OS << "function"; break;
724 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
725 case MCSA_ELF_TypeObject: OS << "object"; break;
726 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
727 case MCSA_ELF_TypeCommon: OS << "common"; break;
728 case MCSA_ELF_TypeNoType: OS << "notype"; break;
729 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
731 EmitEOL();
732 return true;
733 case MCSA_Global: // .globl/.global
734 OS << MAI->getGlobalDirective();
735 break;
736 case MCSA_LGlobal: OS << "\t.lglobl\t"; break;
737 case MCSA_Hidden: OS << "\t.hidden\t"; break;
738 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
739 case MCSA_Internal: OS << "\t.internal\t"; break;
740 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
741 case MCSA_Local: OS << "\t.local\t"; break;
742 case MCSA_NoDeadStrip:
743 if (!MAI->hasNoDeadStrip())
744 return false;
745 OS << "\t.no_dead_strip\t";
746 break;
747 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
748 case MCSA_AltEntry: OS << "\t.alt_entry\t"; break;
749 case MCSA_PrivateExtern:
750 OS << "\t.private_extern\t";
751 break;
752 case MCSA_Protected: OS << "\t.protected\t"; break;
753 case MCSA_Reference: OS << "\t.reference\t"; break;
754 case MCSA_Extern:
755 OS << "\t.extern\t";
756 break;
757 case MCSA_Weak: OS << MAI->getWeakDirective(); break;
758 case MCSA_WeakDefinition:
759 OS << "\t.weak_definition\t";
760 break;
761 // .weak_reference
762 case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break;
763 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
764 case MCSA_Cold:
765 // Assemblers currently do not support a .cold directive.
766 case MCSA_Exported:
767 // Non-AIX assemblers currently do not support exported visibility.
768 return false;
769 case MCSA_Memtag:
770 OS << "\t.memtag\t";
771 break;
772 case MCSA_WeakAntiDep:
773 OS << "\t.weak_anti_dep\t";
774 break;
777 Symbol->print(OS, MAI);
778 EmitEOL();
780 return true;
783 void MCAsmStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
784 OS << ".desc" << ' ';
785 Symbol->print(OS, MAI);
786 OS << ',' << DescValue;
787 EmitEOL();
790 void MCAsmStreamer::emitSyntaxDirective() {
791 if (MAI->getAssemblerDialect() == 1) {
792 OS << "\t.intel_syntax noprefix";
793 EmitEOL();
795 // FIXME: Currently emit unprefix'ed registers.
796 // The intel_syntax directive has one optional argument
797 // with may have a value of prefix or noprefix.
800 void MCAsmStreamer::beginCOFFSymbolDef(const MCSymbol *Symbol) {
801 OS << "\t.def\t";
802 Symbol->print(OS, MAI);
803 OS << ';';
804 EmitEOL();
807 void MCAsmStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
808 OS << "\t.scl\t" << StorageClass << ';';
809 EmitEOL();
812 void MCAsmStreamer::emitCOFFSymbolType(int Type) {
813 OS << "\t.type\t" << Type << ';';
814 EmitEOL();
817 void MCAsmStreamer::endCOFFSymbolDef() {
818 OS << "\t.endef";
819 EmitEOL();
822 void MCAsmStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {
823 OS << "\t.safeseh\t";
824 Symbol->print(OS, MAI);
825 EmitEOL();
828 void MCAsmStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {
829 OS << "\t.symidx\t";
830 Symbol->print(OS, MAI);
831 EmitEOL();
834 void MCAsmStreamer::emitCOFFSectionIndex(MCSymbol const *Symbol) {
835 OS << "\t.secidx\t";
836 Symbol->print(OS, MAI);
837 EmitEOL();
840 void MCAsmStreamer::emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
841 OS << "\t.secrel32\t";
842 Symbol->print(OS, MAI);
843 if (Offset != 0)
844 OS << '+' << Offset;
845 EmitEOL();
848 void MCAsmStreamer::emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
849 OS << "\t.rva\t";
850 Symbol->print(OS, MAI);
851 if (Offset > 0)
852 OS << '+' << Offset;
853 else if (Offset < 0)
854 OS << '-' << -Offset;
855 EmitEOL();
858 // We need an XCOFF-specific version of this directive as the AIX syntax
859 // requires a QualName argument identifying the csect name and storage mapping
860 // class to appear before the alignment if we are specifying it.
861 void MCAsmStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym,
862 uint64_t Size,
863 MCSymbol *CsectSym,
864 Align Alignment) {
865 assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
866 "We only support writing log base-2 alignment format with XCOFF.");
868 OS << "\t.lcomm\t";
869 LabelSym->print(OS, MAI);
870 OS << ',' << Size << ',';
871 CsectSym->print(OS, MAI);
872 OS << ',' << Log2(Alignment);
874 EmitEOL();
876 // Print symbol's rename (original name contains invalid character(s)) if
877 // there is one.
878 MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(CsectSym);
879 if (XSym->hasRename())
880 emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
883 void MCAsmStreamer::emitXCOFFSymbolLinkageWithVisibility(
884 MCSymbol *Symbol, MCSymbolAttr Linkage, MCSymbolAttr Visibility) {
886 switch (Linkage) {
887 case MCSA_Global:
888 OS << MAI->getGlobalDirective();
889 break;
890 case MCSA_Weak:
891 OS << MAI->getWeakDirective();
892 break;
893 case MCSA_Extern:
894 OS << "\t.extern\t";
895 break;
896 case MCSA_LGlobal:
897 OS << "\t.lglobl\t";
898 break;
899 default:
900 report_fatal_error("unhandled linkage type");
903 Symbol->print(OS, MAI);
905 switch (Visibility) {
906 case MCSA_Invalid:
907 // Nothing to do.
908 break;
909 case MCSA_Hidden:
910 OS << ",hidden";
911 break;
912 case MCSA_Protected:
913 OS << ",protected";
914 break;
915 case MCSA_Exported:
916 OS << ",exported";
917 break;
918 default:
919 report_fatal_error("unexpected value for Visibility type");
921 EmitEOL();
923 // Print symbol's rename (original name contains invalid character(s)) if
924 // there is one.
925 if (cast<MCSymbolXCOFF>(Symbol)->hasRename())
926 emitXCOFFRenameDirective(Symbol,
927 cast<MCSymbolXCOFF>(Symbol)->getSymbolTableName());
930 void MCAsmStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
931 StringRef Rename) {
932 OS << "\t.rename\t";
933 Name->print(OS, MAI);
934 const char DQ = '"';
935 OS << ',' << DQ;
936 for (char C : Rename) {
937 // To escape a double quote character, the character should be doubled.
938 if (C == DQ)
939 OS << DQ;
940 OS << C;
942 OS << DQ;
943 EmitEOL();
946 void MCAsmStreamer::emitXCOFFRefDirective(const MCSymbol *Symbol) {
947 OS << "\t.ref ";
948 Symbol->print(OS, MAI);
949 EmitEOL();
952 void MCAsmStreamer::emitXCOFFExceptDirective(const MCSymbol *Symbol,
953 const MCSymbol *Trap,
954 unsigned Lang,
955 unsigned Reason,
956 unsigned FunctionSize,
957 bool hasDebug) {
958 OS << "\t.except\t";
959 Symbol->print(OS, MAI);
960 OS << ", " << Lang << ", " << Reason;
961 EmitEOL();
964 void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
965 const char InfoDirective[] = "\t.info ";
966 const char *Separator = ", ";
967 constexpr int WordSize = sizeof(uint32_t);
969 // Start by emitting the .info pseudo-op and C_INFO symbol name.
970 OS << InfoDirective;
971 PrintQuotedString(Name, OS);
972 OS << Separator;
974 size_t MetadataSize = Metadata.size();
976 // Emit the 4-byte length of the metadata.
977 OS << format_hex(MetadataSize, 10) << Separator;
979 // Nothing left to do if there's no metadata.
980 if (MetadataSize == 0) {
981 EmitEOL();
982 return;
985 // Metadata needs to be padded out to an even word size when generating
986 // assembly because the .info pseudo-op can only generate words of data. We
987 // apply the same restriction to the object case for consistency, however the
988 // linker doesn't require padding, so it will only save bytes specified by the
989 // length and discard any padding.
990 uint32_t PaddedSize = alignTo(MetadataSize, WordSize);
991 uint32_t PaddingSize = PaddedSize - MetadataSize;
993 // Write out the payload a word at a time.
995 // The assembler has a limit on the number of operands in an expression,
996 // so we need multiple .info pseudo-ops. We choose a small number of words
997 // per pseudo-op to keep the assembly readable.
998 constexpr int WordsPerDirective = 5;
999 // Force emitting a new directive to keep the first directive purely about the
1000 // name and size of the note.
1001 int WordsBeforeNextDirective = 0;
1002 auto PrintWord = [&](const uint8_t *WordPtr) {
1003 if (WordsBeforeNextDirective-- == 0) {
1004 EmitEOL();
1005 OS << InfoDirective;
1006 WordsBeforeNextDirective = WordsPerDirective;
1008 OS << Separator;
1009 uint32_t Word = llvm::support::endian::read32be(WordPtr);
1010 OS << format_hex(Word, 10);
1013 size_t Index = 0;
1014 for (; Index + WordSize <= MetadataSize; Index += WordSize)
1015 PrintWord(reinterpret_cast<const uint8_t *>(Metadata.data()) + Index);
1017 // If there is padding, then we have at least one byte of payload left
1018 // to emit.
1019 if (PaddingSize) {
1020 assert(PaddedSize - Index == WordSize);
1021 std::array<uint8_t, WordSize> LastWord = {0};
1022 ::memcpy(LastWord.data(), Metadata.data() + Index, MetadataSize - Index);
1023 PrintWord(LastWord.data());
1025 EmitEOL();
1028 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
1029 assert(MAI->hasDotTypeDotSizeDirective());
1030 OS << "\t.size\t";
1031 Symbol->print(OS, MAI);
1032 OS << ", ";
1033 Value->print(OS, MAI);
1034 EmitEOL();
1037 void MCAsmStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1038 Align ByteAlignment) {
1039 OS << "\t.comm\t";
1040 Symbol->print(OS, MAI);
1041 OS << ',' << Size;
1043 if (MAI->getCOMMDirectiveAlignmentIsInBytes())
1044 OS << ',' << ByteAlignment.value();
1045 else
1046 OS << ',' << Log2(ByteAlignment);
1047 EmitEOL();
1049 // Print symbol's rename (original name contains invalid character(s)) if
1050 // there is one.
1051 MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(Symbol);
1052 if (XSym && XSym->hasRename())
1053 emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
1056 void MCAsmStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1057 Align ByteAlign) {
1058 OS << "\t.lcomm\t";
1059 Symbol->print(OS, MAI);
1060 OS << ',' << Size;
1062 if (ByteAlign > 1) {
1063 switch (MAI->getLCOMMDirectiveAlignmentType()) {
1064 case LCOMM::NoAlignment:
1065 llvm_unreachable("alignment not supported on .lcomm!");
1066 case LCOMM::ByteAlignment:
1067 OS << ',' << ByteAlign.value();
1068 break;
1069 case LCOMM::Log2Alignment:
1070 OS << ',' << Log2(ByteAlign);
1071 break;
1074 EmitEOL();
1077 void MCAsmStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
1078 uint64_t Size, Align ByteAlignment,
1079 SMLoc Loc) {
1080 if (Symbol)
1081 assignFragment(Symbol, &Section->getDummyFragment());
1083 // Note: a .zerofill directive does not switch sections.
1084 OS << ".zerofill ";
1086 assert(Section->getVariant() == MCSection::SV_MachO &&
1087 ".zerofill is a Mach-O specific directive");
1088 // This is a mach-o specific directive.
1090 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
1091 OS << MOSection->getSegmentName() << "," << MOSection->getName();
1093 if (Symbol) {
1094 OS << ',';
1095 Symbol->print(OS, MAI);
1096 OS << ',' << Size;
1097 OS << ',' << Log2(ByteAlignment);
1099 EmitEOL();
1102 // .tbss sym, size, align
1103 // This depends that the symbol has already been mangled from the original,
1104 // e.g. _a.
1105 void MCAsmStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
1106 uint64_t Size, Align ByteAlignment) {
1107 assignFragment(Symbol, &Section->getDummyFragment());
1109 assert(Symbol && "Symbol shouldn't be NULL!");
1110 // Instead of using the Section we'll just use the shortcut.
1112 assert(Section->getVariant() == MCSection::SV_MachO &&
1113 ".zerofill is a Mach-O specific directive");
1114 // This is a mach-o specific directive and section.
1116 OS << ".tbss ";
1117 Symbol->print(OS, MAI);
1118 OS << ", " << Size;
1120 // Output align if we have it. We default to 1 so don't bother printing
1121 // that.
1122 if (ByteAlignment > 1)
1123 OS << ", " << Log2(ByteAlignment);
1125 EmitEOL();
1128 static inline bool isPrintableString(StringRef Data) {
1129 const auto BeginPtr = Data.begin(), EndPtr = Data.end();
1130 for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
1131 if (!isPrint(C))
1132 return false;
1134 return isPrint(Data.back()) || Data.back() == 0;
1137 static inline char toOctal(int X) { return (X&7)+'0'; }
1139 static void PrintByteList(StringRef Data, raw_ostream &OS,
1140 MCAsmInfo::AsmCharLiteralSyntax ACLS) {
1141 assert(!Data.empty() && "Cannot generate an empty list.");
1142 const auto printCharacterInOctal = [&OS](unsigned char C) {
1143 OS << '0';
1144 OS << toOctal(C >> 6);
1145 OS << toOctal(C >> 3);
1146 OS << toOctal(C >> 0);
1148 const auto printOneCharacterFor = [printCharacterInOctal](
1149 auto printOnePrintingCharacter) {
1150 return [printCharacterInOctal, printOnePrintingCharacter](unsigned char C) {
1151 if (isPrint(C)) {
1152 printOnePrintingCharacter(static_cast<char>(C));
1153 return;
1155 printCharacterInOctal(C);
1158 const auto printCharacterList = [Data, &OS](const auto &printOneCharacter) {
1159 const auto BeginPtr = Data.begin(), EndPtr = Data.end();
1160 for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
1161 printOneCharacter(C);
1162 OS << ',';
1164 printOneCharacter(*(EndPtr - 1));
1166 switch (ACLS) {
1167 case MCAsmInfo::ACLS_Unknown:
1168 printCharacterList(printCharacterInOctal);
1169 return;
1170 case MCAsmInfo::ACLS_SingleQuotePrefix:
1171 printCharacterList(printOneCharacterFor([&OS](char C) {
1172 const char AsmCharLitBuf[2] = {'\'', C};
1173 OS << StringRef(AsmCharLitBuf, sizeof(AsmCharLitBuf));
1174 }));
1175 return;
1177 llvm_unreachable("Invalid AsmCharLiteralSyntax value!");
1180 void MCAsmStreamer::PrintQuotedString(StringRef Data, raw_ostream &OS) const {
1181 OS << '"';
1183 if (MAI->hasPairedDoubleQuoteStringConstants()) {
1184 for (unsigned char C : Data) {
1185 if (C == '"')
1186 OS << "\"\"";
1187 else
1188 OS << (char)C;
1190 } else {
1191 for (unsigned char C : Data) {
1192 if (C == '"' || C == '\\') {
1193 OS << '\\' << (char)C;
1194 continue;
1197 if (isPrint((unsigned char)C)) {
1198 OS << (char)C;
1199 continue;
1202 switch (C) {
1203 case '\b':
1204 OS << "\\b";
1205 break;
1206 case '\f':
1207 OS << "\\f";
1208 break;
1209 case '\n':
1210 OS << "\\n";
1211 break;
1212 case '\r':
1213 OS << "\\r";
1214 break;
1215 case '\t':
1216 OS << "\\t";
1217 break;
1218 default:
1219 OS << '\\';
1220 OS << toOctal(C >> 6);
1221 OS << toOctal(C >> 3);
1222 OS << toOctal(C >> 0);
1223 break;
1228 OS << '"';
1231 void MCAsmStreamer::emitBytes(StringRef Data) {
1232 assert(getCurrentSectionOnly() &&
1233 "Cannot emit contents before setting section!");
1234 if (Data.empty()) return;
1236 const auto emitAsString = [this](StringRef Data) {
1237 // If the data ends with 0 and the target supports .asciz, use it, otherwise
1238 // use .ascii or a byte-list directive
1239 if (MAI->getAscizDirective() && Data.back() == 0) {
1240 OS << MAI->getAscizDirective();
1241 Data = Data.substr(0, Data.size() - 1);
1242 } else if (LLVM_LIKELY(MAI->getAsciiDirective())) {
1243 OS << MAI->getAsciiDirective();
1244 } else if (MAI->hasPairedDoubleQuoteStringConstants() &&
1245 isPrintableString(Data)) {
1246 // For target with DoubleQuoteString constants, .string and .byte are used
1247 // as replacement of .asciz and .ascii.
1248 assert(MAI->getPlainStringDirective() &&
1249 "hasPairedDoubleQuoteStringConstants target must support "
1250 "PlainString Directive");
1251 assert(MAI->getByteListDirective() &&
1252 "hasPairedDoubleQuoteStringConstants target must support ByteList "
1253 "Directive");
1254 if (Data.back() == 0) {
1255 OS << MAI->getPlainStringDirective();
1256 Data = Data.substr(0, Data.size() - 1);
1257 } else {
1258 OS << MAI->getByteListDirective();
1260 } else if (MAI->getByteListDirective()) {
1261 OS << MAI->getByteListDirective();
1262 PrintByteList(Data, OS, MAI->characterLiteralSyntax());
1263 EmitEOL();
1264 return true;
1265 } else {
1266 return false;
1269 PrintQuotedString(Data, OS);
1270 EmitEOL();
1271 return true;
1274 if (Data.size() != 1 && emitAsString(Data))
1275 return;
1277 // Only single byte is provided or no ascii, asciz, or byte-list directives
1278 // are applicable. Emit as vector of individual 8bits data elements.
1279 if (MCTargetStreamer *TS = getTargetStreamer()) {
1280 TS->emitRawBytes(Data);
1281 return;
1283 const char *Directive = MAI->getData8bitsDirective();
1284 for (const unsigned char C : Data.bytes()) {
1285 OS << Directive << (unsigned)C;
1286 EmitEOL();
1290 void MCAsmStreamer::emitBinaryData(StringRef Data) {
1291 // This is binary data. Print it in a grid of hex bytes for readability.
1292 const size_t Cols = 4;
1293 for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
1294 size_t J = I, EJ = std::min(I + Cols, Data.size());
1295 assert(EJ > 0);
1296 OS << MAI->getData8bitsDirective();
1297 for (; J < EJ - 1; ++J)
1298 OS << format("0x%02x", uint8_t(Data[J])) << ", ";
1299 OS << format("0x%02x", uint8_t(Data[J]));
1300 EmitEOL();
1304 void MCAsmStreamer::emitIntValue(uint64_t Value, unsigned Size) {
1305 emitValue(MCConstantExpr::create(Value, getContext()), Size);
1308 void MCAsmStreamer::emitIntValueInHex(uint64_t Value, unsigned Size) {
1309 emitValue(MCConstantExpr::create(Value, getContext(), true), Size);
1312 void MCAsmStreamer::emitIntValueInHexWithPadding(uint64_t Value,
1313 unsigned Size) {
1314 emitValue(MCConstantExpr::create(Value, getContext(), true, Size), Size);
1317 void MCAsmStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
1318 SMLoc Loc) {
1319 assert(Size <= 8 && "Invalid size");
1320 assert(getCurrentSectionOnly() &&
1321 "Cannot emit contents before setting section!");
1322 const char *Directive = nullptr;
1323 switch (Size) {
1324 default: break;
1325 case 1: Directive = MAI->getData8bitsDirective(); break;
1326 case 2: Directive = MAI->getData16bitsDirective(); break;
1327 case 4: Directive = MAI->getData32bitsDirective(); break;
1328 case 8: Directive = MAI->getData64bitsDirective(); break;
1331 if (!Directive) {
1332 int64_t IntValue;
1333 if (!Value->evaluateAsAbsolute(IntValue))
1334 report_fatal_error("Don't know how to emit this value.");
1336 // We couldn't handle the requested integer size so we fallback by breaking
1337 // the request down into several, smaller, integers.
1338 // Since sizes greater or equal to "Size" are invalid, we use the greatest
1339 // power of 2 that is less than "Size" as our largest piece of granularity.
1340 bool IsLittleEndian = MAI->isLittleEndian();
1341 for (unsigned Emitted = 0; Emitted != Size;) {
1342 unsigned Remaining = Size - Emitted;
1343 // The size of our partial emission must be a power of two less than
1344 // Size.
1345 unsigned EmissionSize = llvm::bit_floor(std::min(Remaining, Size - 1));
1346 // Calculate the byte offset of our partial emission taking into account
1347 // the endianness of the target.
1348 unsigned ByteOffset =
1349 IsLittleEndian ? Emitted : (Remaining - EmissionSize);
1350 uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
1351 // We truncate our partial emission to fit within the bounds of the
1352 // emission domain. This produces nicer output and silences potential
1353 // truncation warnings when round tripping through another assembler.
1354 uint64_t Shift = 64 - EmissionSize * 8;
1355 assert(Shift < static_cast<uint64_t>(
1356 std::numeric_limits<unsigned long long>::digits) &&
1357 "undefined behavior");
1358 ValueToEmit &= ~0ULL >> Shift;
1359 emitIntValue(ValueToEmit, EmissionSize);
1360 Emitted += EmissionSize;
1362 return;
1365 assert(Directive && "Invalid size for machine code value!");
1366 OS << Directive;
1367 if (MCTargetStreamer *TS = getTargetStreamer()) {
1368 TS->emitValue(Value);
1369 } else {
1370 Value->print(OS, MAI);
1371 EmitEOL();
1375 void MCAsmStreamer::emitULEB128Value(const MCExpr *Value) {
1376 int64_t IntValue;
1377 if (Value->evaluateAsAbsolute(IntValue)) {
1378 emitULEB128IntValue(IntValue);
1379 return;
1381 OS << "\t.uleb128 ";
1382 Value->print(OS, MAI);
1383 EmitEOL();
1386 void MCAsmStreamer::emitSLEB128Value(const MCExpr *Value) {
1387 int64_t IntValue;
1388 if (Value->evaluateAsAbsolute(IntValue)) {
1389 emitSLEB128IntValue(IntValue);
1390 return;
1392 OS << "\t.sleb128 ";
1393 Value->print(OS, MAI);
1394 EmitEOL();
1397 void MCAsmStreamer::emitDTPRel64Value(const MCExpr *Value) {
1398 assert(MAI->getDTPRel64Directive() != nullptr);
1399 OS << MAI->getDTPRel64Directive();
1400 Value->print(OS, MAI);
1401 EmitEOL();
1404 void MCAsmStreamer::emitDTPRel32Value(const MCExpr *Value) {
1405 assert(MAI->getDTPRel32Directive() != nullptr);
1406 OS << MAI->getDTPRel32Directive();
1407 Value->print(OS, MAI);
1408 EmitEOL();
1411 void MCAsmStreamer::emitTPRel64Value(const MCExpr *Value) {
1412 assert(MAI->getTPRel64Directive() != nullptr);
1413 OS << MAI->getTPRel64Directive();
1414 Value->print(OS, MAI);
1415 EmitEOL();
1418 void MCAsmStreamer::emitTPRel32Value(const MCExpr *Value) {
1419 assert(MAI->getTPRel32Directive() != nullptr);
1420 OS << MAI->getTPRel32Directive();
1421 Value->print(OS, MAI);
1422 EmitEOL();
1425 void MCAsmStreamer::emitGPRel64Value(const MCExpr *Value) {
1426 assert(MAI->getGPRel64Directive() != nullptr);
1427 OS << MAI->getGPRel64Directive();
1428 Value->print(OS, MAI);
1429 EmitEOL();
1432 void MCAsmStreamer::emitGPRel32Value(const MCExpr *Value) {
1433 assert(MAI->getGPRel32Directive() != nullptr);
1434 OS << MAI->getGPRel32Directive();
1435 Value->print(OS, MAI);
1436 EmitEOL();
1439 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
1440 SMLoc Loc) {
1441 int64_t IntNumBytes;
1442 const bool IsAbsolute = NumBytes.evaluateAsAbsolute(IntNumBytes);
1443 if (IsAbsolute && IntNumBytes == 0)
1444 return;
1446 if (const char *ZeroDirective = MAI->getZeroDirective()) {
1447 if (MAI->doesZeroDirectiveSupportNonZeroValue() || FillValue == 0) {
1448 // FIXME: Emit location directives
1449 OS << ZeroDirective;
1450 NumBytes.print(OS, MAI);
1451 if (FillValue != 0)
1452 OS << ',' << (int)FillValue;
1453 EmitEOL();
1454 } else {
1455 if (!IsAbsolute)
1456 report_fatal_error(
1457 "Cannot emit non-absolute expression lengths of fill.");
1458 for (int i = 0; i < IntNumBytes; ++i) {
1459 OS << MAI->getData8bitsDirective() << (int)FillValue;
1460 EmitEOL();
1463 return;
1466 MCStreamer::emitFill(NumBytes, FillValue);
1469 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1470 int64_t Expr, SMLoc Loc) {
1471 // FIXME: Emit location directives
1472 OS << "\t.fill\t";
1473 NumValues.print(OS, MAI);
1474 OS << ", " << Size << ", 0x";
1475 OS.write_hex(truncateToSize(Expr, 4));
1476 EmitEOL();
1479 void MCAsmStreamer::emitAlignmentDirective(unsigned ByteAlignment,
1480 std::optional<int64_t> Value,
1481 unsigned ValueSize,
1482 unsigned MaxBytesToEmit) {
1483 if (MAI->useDotAlignForAlignment()) {
1484 if (!isPowerOf2_32(ByteAlignment))
1485 report_fatal_error("Only power-of-two alignments are supported "
1486 "with .align.");
1487 OS << "\t.align\t";
1488 OS << Log2_32(ByteAlignment);
1489 EmitEOL();
1490 return;
1493 // Some assemblers don't support non-power of two alignments, so we always
1494 // emit alignments as a power of two if possible.
1495 if (isPowerOf2_32(ByteAlignment)) {
1496 switch (ValueSize) {
1497 default:
1498 llvm_unreachable("Invalid size for machine code value!");
1499 case 1:
1500 OS << "\t.p2align\t";
1501 break;
1502 case 2:
1503 OS << ".p2alignw ";
1504 break;
1505 case 4:
1506 OS << ".p2alignl ";
1507 break;
1508 case 8:
1509 llvm_unreachable("Unsupported alignment size!");
1512 OS << Log2_32(ByteAlignment);
1514 if (Value.has_value() || MaxBytesToEmit) {
1515 if (Value.has_value()) {
1516 OS << ", 0x";
1517 OS.write_hex(truncateToSize(*Value, ValueSize));
1518 } else {
1519 OS << ", ";
1522 if (MaxBytesToEmit)
1523 OS << ", " << MaxBytesToEmit;
1525 EmitEOL();
1526 return;
1529 // Non-power of two alignment. This is not widely supported by assemblers.
1530 // FIXME: Parameterize this based on MAI.
1531 switch (ValueSize) {
1532 default: llvm_unreachable("Invalid size for machine code value!");
1533 case 1: OS << ".balign"; break;
1534 case 2: OS << ".balignw"; break;
1535 case 4: OS << ".balignl"; break;
1536 case 8: llvm_unreachable("Unsupported alignment size!");
1539 OS << ' ' << ByteAlignment;
1540 if (Value.has_value())
1541 OS << ", " << truncateToSize(*Value, ValueSize);
1542 else if (MaxBytesToEmit)
1543 OS << ", ";
1544 if (MaxBytesToEmit)
1545 OS << ", " << MaxBytesToEmit;
1546 EmitEOL();
1549 void MCAsmStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
1550 unsigned ValueSize,
1551 unsigned MaxBytesToEmit) {
1552 emitAlignmentDirective(Alignment.value(), Value, ValueSize, MaxBytesToEmit);
1555 void MCAsmStreamer::emitCodeAlignment(Align Alignment,
1556 const MCSubtargetInfo *STI,
1557 unsigned MaxBytesToEmit) {
1558 // Emit with a text fill value.
1559 if (MAI->getTextAlignFillValue())
1560 emitAlignmentDirective(Alignment.value(), MAI->getTextAlignFillValue(), 1,
1561 MaxBytesToEmit);
1562 else
1563 emitAlignmentDirective(Alignment.value(), std::nullopt, 1, MaxBytesToEmit);
1566 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1567 unsigned char Value,
1568 SMLoc Loc) {
1569 // FIXME: Verify that Offset is associated with the current section.
1570 OS << ".org ";
1571 Offset->print(OS, MAI);
1572 OS << ", " << (unsigned)Value;
1573 EmitEOL();
1576 void MCAsmStreamer::emitFileDirective(StringRef Filename) {
1577 assert(MAI->hasSingleParameterDotFile());
1578 OS << "\t.file\t";
1579 PrintQuotedString(Filename, OS);
1580 EmitEOL();
1583 void MCAsmStreamer::emitFileDirective(StringRef Filename,
1584 StringRef CompilerVerion,
1585 StringRef TimeStamp,
1586 StringRef Description) {
1587 assert(MAI->hasFourStringsDotFile());
1588 OS << "\t.file\t";
1589 PrintQuotedString(Filename, OS);
1590 OS << ",";
1591 if (!CompilerVerion.empty()) {
1592 PrintQuotedString(CompilerVerion, OS);
1594 if (!TimeStamp.empty()) {
1595 OS << ",";
1596 PrintQuotedString(TimeStamp, OS);
1598 if (!Description.empty()) {
1599 OS << ",";
1600 PrintQuotedString(Description, OS);
1602 EmitEOL();
1605 void MCAsmStreamer::printDwarfFileDirective(
1606 unsigned FileNo, StringRef Directory, StringRef Filename,
1607 std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1608 bool UseDwarfDirectory, raw_svector_ostream &OS) const {
1609 SmallString<128> FullPathName;
1611 if (!UseDwarfDirectory && !Directory.empty()) {
1612 if (sys::path::is_absolute(Filename))
1613 Directory = "";
1614 else {
1615 FullPathName = Directory;
1616 sys::path::append(FullPathName, Filename);
1617 Directory = "";
1618 Filename = FullPathName;
1622 OS << "\t.file\t" << FileNo << ' ';
1623 if (!Directory.empty()) {
1624 PrintQuotedString(Directory, OS);
1625 OS << ' ';
1627 PrintQuotedString(Filename, OS);
1628 if (Checksum)
1629 OS << " md5 0x" << Checksum->digest();
1630 if (Source) {
1631 OS << " source ";
1632 PrintQuotedString(*Source, OS);
1636 Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1637 unsigned FileNo, StringRef Directory, StringRef Filename,
1638 std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1639 unsigned CUID) {
1640 assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
1642 MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1643 unsigned NumFiles = Table.getMCDwarfFiles().size();
1644 Expected<unsigned> FileNoOrErr =
1645 Table.tryGetFile(Directory, Filename, Checksum, Source,
1646 getContext().getDwarfVersion(), FileNo);
1647 if (!FileNoOrErr)
1648 return FileNoOrErr.takeError();
1649 FileNo = FileNoOrErr.get();
1651 // Return early if this file is already emitted before or if target doesn't
1652 // support .file directive.
1653 if (NumFiles == Table.getMCDwarfFiles().size() ||
1654 !MAI->usesDwarfFileAndLocDirectives())
1655 return FileNo;
1657 SmallString<128> Str;
1658 raw_svector_ostream OS1(Str);
1659 printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
1660 UseDwarfDirectory, OS1);
1662 if (MCTargetStreamer *TS = getTargetStreamer())
1663 TS->emitDwarfFileDirective(OS1.str());
1664 else
1665 emitRawText(OS1.str());
1667 return FileNo;
1670 void MCAsmStreamer::emitDwarfFile0Directive(
1671 StringRef Directory, StringRef Filename,
1672 std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1673 unsigned CUID) {
1674 assert(CUID == 0);
1675 // .file 0 is new for DWARF v5.
1676 if (getContext().getDwarfVersion() < 5)
1677 return;
1678 // Inform MCDwarf about the root file.
1679 getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
1680 Source);
1682 // Target doesn't support .loc/.file directives, return early.
1683 if (!MAI->usesDwarfFileAndLocDirectives())
1684 return;
1686 SmallString<128> Str;
1687 raw_svector_ostream OS1(Str);
1688 printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
1689 UseDwarfDirectory, OS1);
1691 if (MCTargetStreamer *TS = getTargetStreamer())
1692 TS->emitDwarfFileDirective(OS1.str());
1693 else
1694 emitRawText(OS1.str());
1697 void MCAsmStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
1698 unsigned Column, unsigned Flags,
1699 unsigned Isa, unsigned Discriminator,
1700 StringRef FileName) {
1701 // If target doesn't support .loc/.file directive, we need to record the lines
1702 // same way like we do in object mode.
1703 if (!MAI->usesDwarfFileAndLocDirectives()) {
1704 // In case we see two .loc directives in a row, make sure the
1705 // first one gets a line entry.
1706 MCDwarfLineEntry::make(this, getCurrentSectionOnly());
1707 this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
1708 Discriminator, FileName);
1709 return;
1712 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1713 if (MAI->supportsExtendedDwarfLocDirective()) {
1714 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1715 OS << " basic_block";
1716 if (Flags & DWARF2_FLAG_PROLOGUE_END)
1717 OS << " prologue_end";
1718 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1719 OS << " epilogue_begin";
1721 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1722 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1723 OS << " is_stmt ";
1725 if (Flags & DWARF2_FLAG_IS_STMT)
1726 OS << "1";
1727 else
1728 OS << "0";
1731 if (Isa)
1732 OS << " isa " << Isa;
1733 if (Discriminator)
1734 OS << " discriminator " << Discriminator;
1737 if (IsVerboseAsm) {
1738 OS.PadToColumn(MAI->getCommentColumn());
1739 OS << MAI->getCommentString() << ' ' << FileName << ':'
1740 << Line << ':' << Column;
1742 EmitEOL();
1743 this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
1744 Discriminator, FileName);
1747 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1748 // Always use the zeroth line table, since asm syntax only supports one line
1749 // table for now.
1750 return MCStreamer::getDwarfLineTableSymbol(0);
1753 bool MCAsmStreamer::emitCVFileDirective(unsigned FileNo, StringRef Filename,
1754 ArrayRef<uint8_t> Checksum,
1755 unsigned ChecksumKind) {
1756 if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1757 ChecksumKind))
1758 return false;
1760 OS << "\t.cv_file\t" << FileNo << ' ';
1761 PrintQuotedString(Filename, OS);
1763 if (!ChecksumKind) {
1764 EmitEOL();
1765 return true;
1768 OS << ' ';
1769 PrintQuotedString(toHex(Checksum), OS);
1770 OS << ' ' << ChecksumKind;
1772 EmitEOL();
1773 return true;
1776 bool MCAsmStreamer::emitCVFuncIdDirective(unsigned FuncId) {
1777 OS << "\t.cv_func_id " << FuncId << '\n';
1778 return MCStreamer::emitCVFuncIdDirective(FuncId);
1781 bool MCAsmStreamer::emitCVInlineSiteIdDirective(unsigned FunctionId,
1782 unsigned IAFunc,
1783 unsigned IAFile,
1784 unsigned IALine, unsigned IACol,
1785 SMLoc Loc) {
1786 OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1787 << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1788 return MCStreamer::emitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1789 IALine, IACol, Loc);
1792 void MCAsmStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1793 unsigned Line, unsigned Column,
1794 bool PrologueEnd, bool IsStmt,
1795 StringRef FileName, SMLoc Loc) {
1796 // Validate the directive.
1797 if (!checkCVLocSection(FunctionId, FileNo, Loc))
1798 return;
1800 OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1801 << Column;
1802 if (PrologueEnd)
1803 OS << " prologue_end";
1805 if (IsStmt)
1806 OS << " is_stmt 1";
1808 if (IsVerboseAsm) {
1809 OS.PadToColumn(MAI->getCommentColumn());
1810 OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1811 << Column;
1813 EmitEOL();
1816 void MCAsmStreamer::emitCVLinetableDirective(unsigned FunctionId,
1817 const MCSymbol *FnStart,
1818 const MCSymbol *FnEnd) {
1819 OS << "\t.cv_linetable\t" << FunctionId << ", ";
1820 FnStart->print(OS, MAI);
1821 OS << ", ";
1822 FnEnd->print(OS, MAI);
1823 EmitEOL();
1824 this->MCStreamer::emitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1827 void MCAsmStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1828 unsigned SourceFileId,
1829 unsigned SourceLineNum,
1830 const MCSymbol *FnStartSym,
1831 const MCSymbol *FnEndSym) {
1832 OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1833 << ' ' << SourceLineNum << ' ';
1834 FnStartSym->print(OS, MAI);
1835 OS << ' ';
1836 FnEndSym->print(OS, MAI);
1837 EmitEOL();
1838 this->MCStreamer::emitCVInlineLinetableDirective(
1839 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1842 void MCAsmStreamer::PrintCVDefRangePrefix(
1843 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
1844 OS << "\t.cv_def_range\t";
1845 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1846 OS << ' ';
1847 Range.first->print(OS, MAI);
1848 OS << ' ';
1849 Range.second->print(OS, MAI);
1853 void MCAsmStreamer::emitCVDefRangeDirective(
1854 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1855 codeview::DefRangeRegisterRelHeader DRHdr) {
1856 PrintCVDefRangePrefix(Ranges);
1857 OS << ", reg_rel, ";
1858 OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
1859 << DRHdr.BasePointerOffset;
1860 EmitEOL();
1863 void MCAsmStreamer::emitCVDefRangeDirective(
1864 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1865 codeview::DefRangeSubfieldRegisterHeader DRHdr) {
1866 PrintCVDefRangePrefix(Ranges);
1867 OS << ", subfield_reg, ";
1868 OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
1869 EmitEOL();
1872 void MCAsmStreamer::emitCVDefRangeDirective(
1873 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1874 codeview::DefRangeRegisterHeader DRHdr) {
1875 PrintCVDefRangePrefix(Ranges);
1876 OS << ", reg, ";
1877 OS << DRHdr.Register;
1878 EmitEOL();
1881 void MCAsmStreamer::emitCVDefRangeDirective(
1882 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1883 codeview::DefRangeFramePointerRelHeader DRHdr) {
1884 PrintCVDefRangePrefix(Ranges);
1885 OS << ", frame_ptr_rel, ";
1886 OS << DRHdr.Offset;
1887 EmitEOL();
1890 void MCAsmStreamer::emitCVStringTableDirective() {
1891 OS << "\t.cv_stringtable";
1892 EmitEOL();
1895 void MCAsmStreamer::emitCVFileChecksumsDirective() {
1896 OS << "\t.cv_filechecksums";
1897 EmitEOL();
1900 void MCAsmStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
1901 OS << "\t.cv_filechecksumoffset\t" << FileNo;
1902 EmitEOL();
1905 void MCAsmStreamer::emitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1906 OS << "\t.cv_fpo_data\t";
1907 ProcSym->print(OS, MAI);
1908 EmitEOL();
1911 void MCAsmStreamer::emitIdent(StringRef IdentString) {
1912 assert(MAI->hasIdentDirective() && ".ident directive not supported");
1913 OS << "\t.ident\t";
1914 PrintQuotedString(IdentString, OS);
1915 EmitEOL();
1918 void MCAsmStreamer::emitCFISections(bool EH, bool Debug) {
1919 MCStreamer::emitCFISections(EH, Debug);
1920 OS << "\t.cfi_sections ";
1921 if (EH) {
1922 OS << ".eh_frame";
1923 if (Debug)
1924 OS << ", .debug_frame";
1925 } else if (Debug) {
1926 OS << ".debug_frame";
1929 EmitEOL();
1932 void MCAsmStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1933 OS << "\t.cfi_startproc";
1934 if (Frame.IsSimple)
1935 OS << " simple";
1936 EmitEOL();
1939 void MCAsmStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1940 MCStreamer::emitCFIEndProcImpl(Frame);
1941 OS << "\t.cfi_endproc";
1942 EmitEOL();
1945 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1946 if (!MAI->useDwarfRegNumForCFI()) {
1947 // User .cfi_* directives can use arbitrary DWARF register numbers, not
1948 // just ones that map to LLVM register numbers and have known names.
1949 // Fall back to using the original number directly if no name is known.
1950 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1951 if (std::optional<unsigned> LLVMRegister =
1952 MRI->getLLVMRegNum(Register, true)) {
1953 InstPrinter->printRegName(OS, *LLVMRegister);
1954 return;
1957 OS << Register;
1960 void MCAsmStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset, SMLoc Loc) {
1961 MCStreamer::emitCFIDefCfa(Register, Offset, Loc);
1962 OS << "\t.cfi_def_cfa ";
1963 EmitRegisterName(Register);
1964 OS << ", " << Offset;
1965 EmitEOL();
1968 void MCAsmStreamer::emitCFIDefCfaOffset(int64_t Offset, SMLoc Loc) {
1969 MCStreamer::emitCFIDefCfaOffset(Offset, Loc);
1970 OS << "\t.cfi_def_cfa_offset " << Offset;
1971 EmitEOL();
1974 void MCAsmStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
1975 int64_t AddressSpace, SMLoc Loc) {
1976 MCStreamer::emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace, Loc);
1977 OS << "\t.cfi_llvm_def_aspace_cfa ";
1978 EmitRegisterName(Register);
1979 OS << ", " << Offset;
1980 OS << ", " << AddressSpace;
1981 EmitEOL();
1984 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1985 OS << "\t.cfi_escape ";
1986 if (!Values.empty()) {
1987 size_t e = Values.size() - 1;
1988 for (size_t i = 0; i < e; ++i)
1989 OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1990 OS << format("0x%02x", uint8_t(Values[e]));
1994 void MCAsmStreamer::emitCFIEscape(StringRef Values, SMLoc Loc) {
1995 MCStreamer::emitCFIEscape(Values, Loc);
1996 PrintCFIEscape(OS, Values);
1997 EmitEOL();
2000 void MCAsmStreamer::emitCFIGnuArgsSize(int64_t Size, SMLoc Loc) {
2001 MCStreamer::emitCFIGnuArgsSize(Size, Loc);
2003 uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
2004 unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
2006 PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
2007 EmitEOL();
2010 void MCAsmStreamer::emitCFIDefCfaRegister(int64_t Register, SMLoc Loc) {
2011 MCStreamer::emitCFIDefCfaRegister(Register, Loc);
2012 OS << "\t.cfi_def_cfa_register ";
2013 EmitRegisterName(Register);
2014 EmitEOL();
2017 void MCAsmStreamer::emitCFIOffset(int64_t Register, int64_t Offset, SMLoc Loc) {
2018 MCStreamer::emitCFIOffset(Register, Offset, Loc);
2019 OS << "\t.cfi_offset ";
2020 EmitRegisterName(Register);
2021 OS << ", " << Offset;
2022 EmitEOL();
2025 void MCAsmStreamer::emitCFIPersonality(const MCSymbol *Sym,
2026 unsigned Encoding) {
2027 MCStreamer::emitCFIPersonality(Sym, Encoding);
2028 OS << "\t.cfi_personality " << Encoding << ", ";
2029 Sym->print(OS, MAI);
2030 EmitEOL();
2033 void MCAsmStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
2034 MCStreamer::emitCFILsda(Sym, Encoding);
2035 OS << "\t.cfi_lsda " << Encoding << ", ";
2036 Sym->print(OS, MAI);
2037 EmitEOL();
2040 void MCAsmStreamer::emitCFIRememberState(SMLoc Loc) {
2041 MCStreamer::emitCFIRememberState(Loc);
2042 OS << "\t.cfi_remember_state";
2043 EmitEOL();
2046 void MCAsmStreamer::emitCFIRestoreState(SMLoc Loc) {
2047 MCStreamer::emitCFIRestoreState(Loc);
2048 OS << "\t.cfi_restore_state";
2049 EmitEOL();
2052 void MCAsmStreamer::emitCFIRestore(int64_t Register, SMLoc Loc) {
2053 MCStreamer::emitCFIRestore(Register, Loc);
2054 OS << "\t.cfi_restore ";
2055 EmitRegisterName(Register);
2056 EmitEOL();
2059 void MCAsmStreamer::emitCFISameValue(int64_t Register, SMLoc Loc) {
2060 MCStreamer::emitCFISameValue(Register, Loc);
2061 OS << "\t.cfi_same_value ";
2062 EmitRegisterName(Register);
2063 EmitEOL();
2066 void MCAsmStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset,
2067 SMLoc Loc) {
2068 MCStreamer::emitCFIRelOffset(Register, Offset, Loc);
2069 OS << "\t.cfi_rel_offset ";
2070 EmitRegisterName(Register);
2071 OS << ", " << Offset;
2072 EmitEOL();
2075 void MCAsmStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment, SMLoc Loc) {
2076 MCStreamer::emitCFIAdjustCfaOffset(Adjustment, Loc);
2077 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
2078 EmitEOL();
2081 void MCAsmStreamer::emitCFISignalFrame() {
2082 MCStreamer::emitCFISignalFrame();
2083 OS << "\t.cfi_signal_frame";
2084 EmitEOL();
2087 void MCAsmStreamer::emitCFIUndefined(int64_t Register, SMLoc Loc) {
2088 MCStreamer::emitCFIUndefined(Register, Loc);
2089 OS << "\t.cfi_undefined ";
2090 EmitRegisterName(Register);
2091 EmitEOL();
2094 void MCAsmStreamer::emitCFIRegister(int64_t Register1, int64_t Register2,
2095 SMLoc Loc) {
2096 MCStreamer::emitCFIRegister(Register1, Register2, Loc);
2097 OS << "\t.cfi_register ";
2098 EmitRegisterName(Register1);
2099 OS << ", ";
2100 EmitRegisterName(Register2);
2101 EmitEOL();
2104 void MCAsmStreamer::emitCFIWindowSave(SMLoc Loc) {
2105 MCStreamer::emitCFIWindowSave(Loc);
2106 OS << "\t.cfi_window_save";
2107 EmitEOL();
2110 void MCAsmStreamer::emitCFINegateRAState(SMLoc Loc) {
2111 MCStreamer::emitCFINegateRAState(Loc);
2112 OS << "\t.cfi_negate_ra_state";
2113 EmitEOL();
2116 void MCAsmStreamer::emitCFIReturnColumn(int64_t Register) {
2117 MCStreamer::emitCFIReturnColumn(Register);
2118 OS << "\t.cfi_return_column ";
2119 EmitRegisterName(Register);
2120 EmitEOL();
2123 void MCAsmStreamer::emitCFIBKeyFrame() {
2124 MCStreamer::emitCFIBKeyFrame();
2125 OS << "\t.cfi_b_key_frame";
2126 EmitEOL();
2129 void MCAsmStreamer::emitCFIMTETaggedFrame() {
2130 MCStreamer::emitCFIMTETaggedFrame();
2131 OS << "\t.cfi_mte_tagged_frame";
2132 EmitEOL();
2135 void MCAsmStreamer::emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
2136 MCStreamer::emitWinCFIStartProc(Symbol, Loc);
2138 OS << ".seh_proc ";
2139 Symbol->print(OS, MAI);
2140 EmitEOL();
2143 void MCAsmStreamer::emitWinCFIEndProc(SMLoc Loc) {
2144 MCStreamer::emitWinCFIEndProc(Loc);
2146 OS << "\t.seh_endproc";
2147 EmitEOL();
2150 void MCAsmStreamer::emitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
2151 MCStreamer::emitWinCFIFuncletOrFuncEnd(Loc);
2153 OS << "\t.seh_endfunclet";
2154 EmitEOL();
2157 void MCAsmStreamer::emitWinCFIStartChained(SMLoc Loc) {
2158 MCStreamer::emitWinCFIStartChained(Loc);
2160 OS << "\t.seh_startchained";
2161 EmitEOL();
2164 void MCAsmStreamer::emitWinCFIEndChained(SMLoc Loc) {
2165 MCStreamer::emitWinCFIEndChained(Loc);
2167 OS << "\t.seh_endchained";
2168 EmitEOL();
2171 void MCAsmStreamer::emitWinEHHandler(const MCSymbol *Sym, bool Unwind,
2172 bool Except, SMLoc Loc) {
2173 MCStreamer::emitWinEHHandler(Sym, Unwind, Except, Loc);
2175 OS << "\t.seh_handler ";
2176 Sym->print(OS, MAI);
2177 char Marker = '@';
2178 const Triple &T = getContext().getTargetTriple();
2179 if (T.getArch() == Triple::arm || T.getArch() == Triple::thumb)
2180 Marker = '%';
2181 if (Unwind)
2182 OS << ", " << Marker << "unwind";
2183 if (Except)
2184 OS << ", " << Marker << "except";
2185 EmitEOL();
2188 void MCAsmStreamer::emitWinEHHandlerData(SMLoc Loc) {
2189 MCStreamer::emitWinEHHandlerData(Loc);
2191 // Switch sections. Don't call switchSection directly, because that will
2192 // cause the section switch to be visible in the emitted assembly.
2193 // We only do this so the section switch that terminates the handler
2194 // data block is visible.
2195 WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
2197 // Do nothing if no frame is open. MCStreamer should've already reported an
2198 // error.
2199 if (!CurFrame)
2200 return;
2202 MCSection *TextSec = &CurFrame->Function->getSection();
2203 MCSection *XData = getAssociatedXDataSection(TextSec);
2204 switchSectionNoChange(XData);
2206 OS << "\t.seh_handlerdata";
2207 EmitEOL();
2210 void MCAsmStreamer::emitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
2211 MCStreamer::emitWinCFIPushReg(Register, Loc);
2213 OS << "\t.seh_pushreg ";
2214 InstPrinter->printRegName(OS, Register);
2215 EmitEOL();
2218 void MCAsmStreamer::emitWinCFISetFrame(MCRegister Register, unsigned Offset,
2219 SMLoc Loc) {
2220 MCStreamer::emitWinCFISetFrame(Register, Offset, Loc);
2222 OS << "\t.seh_setframe ";
2223 InstPrinter->printRegName(OS, Register);
2224 OS << ", " << Offset;
2225 EmitEOL();
2228 void MCAsmStreamer::emitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
2229 MCStreamer::emitWinCFIAllocStack(Size, Loc);
2231 OS << "\t.seh_stackalloc " << Size;
2232 EmitEOL();
2235 void MCAsmStreamer::emitWinCFISaveReg(MCRegister Register, unsigned Offset,
2236 SMLoc Loc) {
2237 MCStreamer::emitWinCFISaveReg(Register, Offset, Loc);
2239 OS << "\t.seh_savereg ";
2240 InstPrinter->printRegName(OS, Register);
2241 OS << ", " << Offset;
2242 EmitEOL();
2245 void MCAsmStreamer::emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
2246 SMLoc Loc) {
2247 MCStreamer::emitWinCFISaveXMM(Register, Offset, Loc);
2249 OS << "\t.seh_savexmm ";
2250 InstPrinter->printRegName(OS, Register);
2251 OS << ", " << Offset;
2252 EmitEOL();
2255 void MCAsmStreamer::emitWinCFIPushFrame(bool Code, SMLoc Loc) {
2256 MCStreamer::emitWinCFIPushFrame(Code, Loc);
2258 OS << "\t.seh_pushframe";
2259 if (Code)
2260 OS << " @code";
2261 EmitEOL();
2264 void MCAsmStreamer::emitWinCFIEndProlog(SMLoc Loc) {
2265 MCStreamer::emitWinCFIEndProlog(Loc);
2267 OS << "\t.seh_endprologue";
2268 EmitEOL();
2271 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
2272 const MCSymbolRefExpr *To,
2273 uint64_t Count) {
2274 OS << "\t.cg_profile ";
2275 From->getSymbol().print(OS, MAI);
2276 OS << ", ";
2277 To->getSymbol().print(OS, MAI);
2278 OS << ", " << Count;
2279 EmitEOL();
2282 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
2283 const MCSubtargetInfo &STI) {
2284 raw_ostream &OS = getCommentOS();
2285 SmallString<256> Code;
2286 SmallVector<MCFixup, 4> Fixups;
2288 // If we have no code emitter, don't emit code.
2289 if (!getAssembler().getEmitterPtr())
2290 return;
2292 getAssembler().getEmitter().encodeInstruction(Inst, Code, Fixups, STI);
2294 // If we are showing fixups, create symbolic markers in the encoded
2295 // representation. We do this by making a per-bit map to the fixup item index,
2296 // then trying to display it as nicely as possible.
2297 SmallVector<uint8_t, 64> FixupMap;
2298 FixupMap.resize(Code.size() * 8);
2299 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
2300 FixupMap[i] = 0;
2302 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
2303 MCFixup &F = Fixups[i];
2304 const MCFixupKindInfo &Info =
2305 getAssembler().getBackend().getFixupKindInfo(F.getKind());
2306 for (unsigned j = 0; j != Info.TargetSize; ++j) {
2307 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
2308 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
2309 FixupMap[Index] = 1 + i;
2313 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
2314 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
2315 OS << "encoding: [";
2316 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
2317 if (i)
2318 OS << ',';
2320 // See if all bits are the same map entry.
2321 uint8_t MapEntry = FixupMap[i * 8 + 0];
2322 for (unsigned j = 1; j != 8; ++j) {
2323 if (FixupMap[i * 8 + j] == MapEntry)
2324 continue;
2326 MapEntry = uint8_t(~0U);
2327 break;
2330 if (MapEntry != uint8_t(~0U)) {
2331 if (MapEntry == 0) {
2332 OS << format("0x%02x", uint8_t(Code[i]));
2333 } else {
2334 if (Code[i]) {
2335 // FIXME: Some of the 8 bits require fix up.
2336 OS << format("0x%02x", uint8_t(Code[i])) << '\''
2337 << char('A' + MapEntry - 1) << '\'';
2338 } else
2339 OS << char('A' + MapEntry - 1);
2341 } else {
2342 // Otherwise, write out in binary.
2343 OS << "0b";
2344 for (unsigned j = 8; j--;) {
2345 unsigned Bit = (Code[i] >> j) & 1;
2347 unsigned FixupBit;
2348 if (MAI->isLittleEndian())
2349 FixupBit = i * 8 + j;
2350 else
2351 FixupBit = i * 8 + (7-j);
2353 if (uint8_t MapEntry = FixupMap[FixupBit]) {
2354 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
2355 OS << char('A' + MapEntry - 1);
2356 } else
2357 OS << Bit;
2361 OS << "]\n";
2363 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
2364 MCFixup &F = Fixups[i];
2365 const MCFixupKindInfo &Info =
2366 getAssembler().getBackend().getFixupKindInfo(F.getKind());
2367 OS << " fixup " << char('A' + i) << " - "
2368 << "offset: " << F.getOffset() << ", value: ";
2369 F.getValue()->print(OS, MAI);
2370 OS << ", kind: " << Info.Name << "\n";
2374 void MCAsmStreamer::emitInstruction(const MCInst &Inst,
2375 const MCSubtargetInfo &STI) {
2376 assert(getCurrentSectionOnly() &&
2377 "Cannot emit contents before setting section!");
2379 if (!MAI->usesDwarfFileAndLocDirectives())
2380 // Now that a machine instruction has been assembled into this section, make
2381 // a line entry for any .loc directive that has been seen.
2382 MCDwarfLineEntry::make(this, getCurrentSectionOnly());
2384 // Show the encoding in a comment if we have a code emitter.
2385 AddEncodingComment(Inst, STI);
2387 // Show the MCInst if enabled.
2388 if (ShowInst) {
2389 Inst.dump_pretty(getCommentOS(), InstPrinter.get(), "\n ");
2390 getCommentOS() << "\n";
2393 if(getTargetStreamer())
2394 getTargetStreamer()->prettyPrintAsm(*InstPrinter, 0, Inst, STI, OS);
2395 else
2396 InstPrinter->printInst(&Inst, 0, "", STI, OS);
2398 StringRef Comments = CommentToEmit;
2399 if (Comments.size() && Comments.back() != '\n')
2400 getCommentOS() << "\n";
2402 EmitEOL();
2405 void MCAsmStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index,
2406 uint64_t Type, uint64_t Attr,
2407 uint64_t Discriminator,
2408 const MCPseudoProbeInlineStack &InlineStack,
2409 MCSymbol *FnSym) {
2410 OS << "\t.pseudoprobe\t" << Guid << " " << Index << " " << Type << " " << Attr;
2411 if (Discriminator)
2412 OS << " " << Discriminator;
2413 // Emit inline stack like
2414 // @ GUIDmain:3 @ GUIDCaller:1 @ GUIDDirectCaller:11
2415 for (const auto &Site : InlineStack)
2416 OS << " @ " << std::get<0>(Site) << ":" << std::get<1>(Site);
2418 OS << " " << FnSym->getName();
2420 EmitEOL();
2423 void MCAsmStreamer::emitBundleAlignMode(Align Alignment) {
2424 OS << "\t.bundle_align_mode " << Log2(Alignment);
2425 EmitEOL();
2428 void MCAsmStreamer::emitBundleLock(bool AlignToEnd) {
2429 OS << "\t.bundle_lock";
2430 if (AlignToEnd)
2431 OS << " align_to_end";
2432 EmitEOL();
2435 void MCAsmStreamer::emitBundleUnlock() {
2436 OS << "\t.bundle_unlock";
2437 EmitEOL();
2440 std::optional<std::pair<bool, std::string>>
2441 MCAsmStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
2442 const MCExpr *Expr, SMLoc,
2443 const MCSubtargetInfo &STI) {
2444 OS << "\t.reloc ";
2445 Offset.print(OS, MAI);
2446 OS << ", " << Name;
2447 if (Expr) {
2448 OS << ", ";
2449 Expr->print(OS, MAI);
2451 EmitEOL();
2452 return std::nullopt;
2455 void MCAsmStreamer::emitAddrsig() {
2456 OS << "\t.addrsig";
2457 EmitEOL();
2460 void MCAsmStreamer::emitAddrsigSym(const MCSymbol *Sym) {
2461 OS << "\t.addrsig_sym ";
2462 Sym->print(OS, MAI);
2463 EmitEOL();
2466 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
2467 /// the specified string in the output .s file. This capability is
2468 /// indicated by the hasRawTextSupport() predicate.
2469 void MCAsmStreamer::emitRawTextImpl(StringRef String) {
2470 if (!String.empty() && String.back() == '\n')
2471 String = String.substr(0, String.size()-1);
2472 OS << String;
2473 EmitEOL();
2476 void MCAsmStreamer::finishImpl() {
2477 // If we are generating dwarf for assembly source files dump out the sections.
2478 if (getContext().getGenDwarfForAssembly())
2479 MCGenDwarfInfo::Emit(this);
2481 // Now it is time to emit debug line sections if target doesn't support .loc
2482 // and .line directives.
2483 if (!MAI->usesDwarfFileAndLocDirectives()) {
2484 MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
2485 return;
2488 // Emit the label for the line table, if requested - since the rest of the
2489 // line table will be defined by .loc/.file directives, and not emitted
2490 // directly, the label is the only work required here.
2491 const auto &Tables = getContext().getMCDwarfLineTables();
2492 if (!Tables.empty()) {
2493 assert(Tables.size() == 1 && "asm output only supports one line table");
2494 if (auto *Label = Tables.begin()->second.getLabel()) {
2495 switchSection(getContext().getObjectFileInfo()->getDwarfLineSection());
2496 emitLabel(Label);
2501 void MCAsmStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
2502 // If the assembler on some target fills in the DWARF unit length, we
2503 // don't want to emit the length in the compiler. For example, the AIX
2504 // assembler requires the assembly file with the unit length omitted from
2505 // the debug section headers. In such cases, any label we placed occurs
2506 // after the implied length field. We need to adjust the reference here
2507 // to account for the offset introduced by the inserted length field.
2508 if (!MAI->needsDwarfSectionSizeInHeader())
2509 return;
2510 MCStreamer::emitDwarfUnitLength(Length, Comment);
2513 MCSymbol *MCAsmStreamer::emitDwarfUnitLength(const Twine &Prefix,
2514 const Twine &Comment) {
2515 // If the assembler on some target fills in the DWARF unit length, we
2516 // don't want to emit the length in the compiler. For example, the AIX
2517 // assembler requires the assembly file with the unit length omitted from
2518 // the debug section headers. In such cases, any label we placed occurs
2519 // after the implied length field. We need to adjust the reference here
2520 // to account for the offset introduced by the inserted length field.
2521 if (!MAI->needsDwarfSectionSizeInHeader())
2522 return getContext().createTempSymbol(Prefix + "_end");
2523 return MCStreamer::emitDwarfUnitLength(Prefix, Comment);
2526 void MCAsmStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
2527 // If the assembler on some target fills in the DWARF unit length, we
2528 // don't want to emit the length in the compiler. For example, the AIX
2529 // assembler requires the assembly file with the unit length omitted from
2530 // the debug section headers. In such cases, any label we placed occurs
2531 // after the implied length field. We need to adjust the reference here
2532 // to account for the offset introduced by the inserted length field.
2533 MCContext &Ctx = getContext();
2534 if (!MAI->needsDwarfSectionSizeInHeader()) {
2535 MCSymbol *DebugLineSymTmp = Ctx.createTempSymbol("debug_line_");
2536 // Emit the symbol which does not contain the unit length field.
2537 emitLabel(DebugLineSymTmp);
2539 // Adjust the outer reference to account for the offset introduced by the
2540 // inserted length field.
2541 unsigned LengthFieldSize =
2542 dwarf::getUnitLengthFieldByteSize(Ctx.getDwarfFormat());
2543 const MCExpr *EntrySize = MCConstantExpr::create(LengthFieldSize, Ctx);
2544 const MCExpr *OuterSym = MCBinaryExpr::createSub(
2545 MCSymbolRefExpr::create(DebugLineSymTmp, Ctx), EntrySize, Ctx);
2547 emitAssignment(StartSym, OuterSym);
2548 return;
2550 MCStreamer::emitDwarfLineStartLabel(StartSym);
2553 void MCAsmStreamer::emitDwarfLineEndEntry(MCSection *Section,
2554 MCSymbol *LastLabel) {
2555 // If the targets write the raw debug line data for assembly output (We can
2556 // not switch to Section and add the end symbol there for assembly output)
2557 // we currently use the .text end label as any section end. This will not
2558 // impact the debugability as we will jump to the caller of the last function
2559 // in the section before we come into the .text end address.
2560 assert(!MAI->usesDwarfFileAndLocDirectives() &&
2561 ".loc should not be generated together with raw data!");
2563 MCContext &Ctx = getContext();
2565 // FIXME: use section end symbol as end of the Section. We need to consider
2566 // the explicit sections and -ffunction-sections when we try to generate or
2567 // find section end symbol for the Section.
2568 MCSection *TextSection = Ctx.getObjectFileInfo()->getTextSection();
2569 assert(TextSection->hasEnded() && ".text section is not end!");
2571 MCSymbol *SectionEnd = TextSection->getEndSymbol(Ctx);
2572 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
2573 emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
2574 AsmInfo->getCodePointerSize());
2577 // Generate DWARF line sections for assembly mode without .loc/.file
2578 void MCAsmStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
2579 const MCSymbol *LastLabel,
2580 const MCSymbol *Label,
2581 unsigned PointerSize) {
2582 assert(!MAI->usesDwarfFileAndLocDirectives() &&
2583 ".loc/.file don't need raw data in debug line section!");
2585 // Set to new address.
2586 AddComment("Set address to " + Label->getName());
2587 emitIntValue(dwarf::DW_LNS_extended_op, 1);
2588 emitULEB128IntValue(PointerSize + 1);
2589 emitIntValue(dwarf::DW_LNE_set_address, 1);
2590 emitSymbolValue(Label, PointerSize);
2592 if (!LastLabel) {
2593 // Emit the sequence for the LineDelta (from 1) and a zero address delta.
2594 AddComment("Start sequence");
2595 MCDwarfLineAddr::Emit(this, MCDwarfLineTableParams(), LineDelta, 0);
2596 return;
2599 // INT64_MAX is a signal of the end of the section. Emit DW_LNE_end_sequence
2600 // for the end of the section.
2601 if (LineDelta == INT64_MAX) {
2602 AddComment("End sequence");
2603 emitIntValue(dwarf::DW_LNS_extended_op, 1);
2604 emitULEB128IntValue(1);
2605 emitIntValue(dwarf::DW_LNE_end_sequence, 1);
2606 return;
2609 // Advance line.
2610 AddComment("Advance line " + Twine(LineDelta));
2611 emitIntValue(dwarf::DW_LNS_advance_line, 1);
2612 emitSLEB128IntValue(LineDelta);
2613 emitIntValue(dwarf::DW_LNS_copy, 1);
2616 void MCAsmStreamer::doFinalizationAtSectionEnd(MCSection *Section) {
2617 // Emit section end. This is used to tell the debug line section where the end
2618 // is for a text section if we don't use .loc to represent the debug line.
2619 if (MAI->usesDwarfFileAndLocDirectives())
2620 return;
2622 switchSectionNoChange(Section);
2624 MCSymbol *Sym = getCurrentSectionOnly()->getEndSymbol(getContext());
2626 if (!Sym->isInSection())
2627 emitLabel(Sym);
2630 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
2631 std::unique_ptr<formatted_raw_ostream> OS,
2632 bool isVerboseAsm, bool useDwarfDirectory,
2633 MCInstPrinter *IP,
2634 std::unique_ptr<MCCodeEmitter> &&CE,
2635 std::unique_ptr<MCAsmBackend> &&MAB,
2636 bool ShowInst) {
2637 return new MCAsmStreamer(Context, std::move(OS), isVerboseAsm,
2638 useDwarfDirectory, IP, std::move(CE), std::move(MAB),
2639 ShowInst);