xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCAsmStreamer.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
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 //===----------------------------------------------------------------------===//
8 
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/MCInst.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCPseudoProbe.h"
25 #include "llvm/MC/MCRegister.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbolXCOFF.h"
30 #include "llvm/MC/TargetRegistry.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/LEB128.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include <algorithm>
39 #include <optional>
40 
41 using namespace llvm;
42 
43 namespace {
44 
45 class MCAsmStreamer final : public MCStreamer {
46   std::unique_ptr<formatted_raw_ostream> OSOwner;
47   formatted_raw_ostream &OS;
48   const MCAsmInfo *MAI;
49   std::unique_ptr<MCInstPrinter> InstPrinter;
50   std::unique_ptr<MCAssembler> Assembler;
51 
52   SmallString<128> ExplicitCommentToEmit;
53   SmallString<128> CommentToEmit;
54   raw_svector_ostream CommentStream;
55   raw_null_ostream NullStream;
56 
57   bool EmittedSectionDirective = false;
58 
59   bool IsVerboseAsm = false;
60   bool ShowInst = false;
61   bool UseDwarfDirectory = false;
62 
63   void EmitRegisterName(int64_t Register);
64   void PrintQuotedString(StringRef Data, raw_ostream &OS) const;
65   void printDwarfFileDirective(unsigned FileNo, StringRef Directory,
66                                StringRef Filename,
67                                std::optional<MD5::MD5Result> Checksum,
68                                std::optional<StringRef> Source,
69                                bool UseDwarfDirectory,
70                                raw_svector_ostream &OS) const;
71   void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
72   void emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
73 
74 public:
MCAsmStreamer(MCContext & Context,std::unique_ptr<formatted_raw_ostream> os,std::unique_ptr<MCInstPrinter> printer,std::unique_ptr<MCCodeEmitter> emitter,std::unique_ptr<MCAsmBackend> asmbackend)75   MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
76                 std::unique_ptr<MCInstPrinter> printer,
77                 std::unique_ptr<MCCodeEmitter> emitter,
78                 std::unique_ptr<MCAsmBackend> asmbackend)
79       : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
80         MAI(Context.getAsmInfo()), InstPrinter(std::move(printer)),
81         Assembler(std::make_unique<MCAssembler>(
82             Context, std::move(asmbackend), std::move(emitter),
83             (asmbackend) ? asmbackend->createObjectWriter(NullStream)
84                          : nullptr)),
85         CommentStream(CommentToEmit) {
86     assert(InstPrinter);
87     if (Assembler->getBackendPtr())
88       setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
89 
90     Context.setUseNamesOnTempLabels(true);
91 
92     auto *TO = Context.getTargetOptions();
93     if (!TO)
94       return;
95     IsVerboseAsm = TO->AsmVerbose;
96     if (IsVerboseAsm)
97       InstPrinter->setCommentStream(CommentStream);
98     ShowInst = TO->ShowMCInst;
99     switch (TO->MCUseDwarfDirectory) {
100     case MCTargetOptions::DisableDwarfDirectory:
101       UseDwarfDirectory = false;
102       break;
103     case MCTargetOptions::EnableDwarfDirectory:
104       UseDwarfDirectory = true;
105       break;
106     case MCTargetOptions::DefaultDwarfDirectory:
107       UseDwarfDirectory =
108           Context.getAsmInfo()->enableDwarfFileDirectoryDefault();
109       break;
110     }
111   }
112 
getAssembler()113   MCAssembler &getAssembler() { return *Assembler; }
getAssemblerPtr()114   MCAssembler *getAssemblerPtr() override { return nullptr; }
115 
EmitEOL()116   inline void EmitEOL() {
117     // Dump Explicit Comments here.
118     emitExplicitComments();
119     // If we don't have any comments, just emit a \n.
120     if (!IsVerboseAsm) {
121       OS << '\n';
122       return;
123     }
124     EmitCommentsAndEOL();
125   }
126 
127   void emitSyntaxDirective() override;
128 
129   void EmitCommentsAndEOL();
130 
131   /// Return true if this streamer supports verbose assembly at all.
isVerboseAsm() const132   bool isVerboseAsm() const override { return IsVerboseAsm; }
133 
134   /// Do we support EmitRawText?
hasRawTextSupport() const135   bool hasRawTextSupport() const override { return true; }
136 
137   /// Add a comment that can be emitted to the generated .s file to make the
138   /// output of the compiler more readable. This only affects the MCAsmStreamer
139   /// and only when verbose assembly output is enabled.
140   void AddComment(const Twine &T, bool EOL = true) override;
141 
142   /// Add a comment showing the encoding of an instruction.
143   void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &);
144 
145   /// Return a raw_ostream that comments can be written to.
146   /// Unlike AddComment, you are required to terminate comments with \n if you
147   /// use this method.
getCommentOS()148   raw_ostream &getCommentOS() override {
149     if (!IsVerboseAsm)
150       return nulls();  // Discard comments unless in verbose asm mode.
151     return CommentStream;
152   }
153 
154   void emitRawComment(const Twine &T, bool TabPrefix = true) override;
155 
156   void addExplicitComment(const Twine &T) override;
157   void emitExplicitComments() override;
158 
159   /// Emit a blank line to a .s file to pretty it up.
addBlankLine()160   void addBlankLine() override { EmitEOL(); }
161 
162   /// @name MCStreamer Interface
163   /// @{
164 
165   void switchSection(MCSection *Section, uint32_t Subsection) override;
166   bool popSection() override;
167 
168   void emitELFSymverDirective(const MCSymbol *OriginalSym, StringRef Name,
169                               bool KeepOriginalSym) override;
170 
171   void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override;
172 
173   void emitGNUAttribute(unsigned Tag, unsigned Value) override;
174 
getMnemonic(const MCInst & MI) const175   StringRef getMnemonic(const MCInst &MI) const override {
176     auto [Ptr, Bits] = InstPrinter->getMnemonic(MI);
177     assert((Bits != 0 || Ptr == nullptr) &&
178            "Invalid char pointer for instruction with no mnemonic");
179     return Ptr;
180   }
181 
182   void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
183 
184   void emitSubsectionsViaSymbols() override;
185   void emitLinkerOptions(ArrayRef<std::string> Options) override;
186   void emitDataRegion(MCDataRegionType Kind) override;
187   void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
188                       unsigned Update, VersionTuple SDKVersion) override;
189   void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
190                         unsigned Update, VersionTuple SDKVersion) override;
191   void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
192                                            unsigned Minor, unsigned Update,
193                                            VersionTuple SDKVersion) override;
194 
195   void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
196   void emitConditionalAssignment(MCSymbol *Symbol,
197                                  const MCExpr *Value) override;
198   void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
199   bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
200 
201   void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
202   void beginCOFFSymbolDef(const MCSymbol *Symbol) override;
203   void emitCOFFSymbolStorageClass(int StorageClass) override;
204   void emitCOFFSymbolType(int Type) override;
205   void endCOFFSymbolDef() override;
206   void emitCOFFSafeSEH(MCSymbol const *Symbol) override;
207   void emitCOFFSymbolIndex(MCSymbol const *Symbol) override;
208   void emitCOFFSectionIndex(MCSymbol const *Symbol) override;
209   void emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) override;
210   void emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) override;
211   void emitCOFFSecNumber(MCSymbol const *Symbol) override;
212   void emitCOFFSecOffset(MCSymbol const *Symbol) override;
213   void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
214                                   MCSymbol *CsectSym, Align Alignment) override;
215   void emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
216                                             MCSymbolAttr Linkage,
217                                             MCSymbolAttr Visibility) override;
218   void emitXCOFFRenameDirective(const MCSymbol *Name,
219                                 StringRef Rename) override;
220 
221   void emitXCOFFRefDirective(const MCSymbol *Symbol) override;
222 
223   void emitXCOFFExceptDirective(const MCSymbol *Symbol,
224                                 const MCSymbol *Trap,
225                                 unsigned Lang, unsigned Reason,
226                                 unsigned FunctionSize, bool hasDebug) override;
227   void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
228 
229   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
230   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
231                         Align ByteAlignment) override;
232 
233   /// Emit a local common (.lcomm) symbol.
234   ///
235   /// @param Symbol - The common symbol to emit.
236   /// @param Size - The size of the common symbol.
237   /// @param ByteAlignment - The alignment of the common symbol in bytes.
238   void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
239                              Align ByteAlignment) override;
240 
241   void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
242                     uint64_t Size = 0, Align ByteAlignment = Align(1),
243                     SMLoc Loc = SMLoc()) override;
244 
245   void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
246                       Align ByteAlignment = Align(1)) override;
247 
248   void emitBinaryData(StringRef Data) override;
249 
250   void emitBytes(StringRef Data) override;
251 
252   void emitValueImpl(const MCExpr *Value, unsigned Size,
253                      SMLoc Loc = SMLoc()) override;
254   void emitIntValue(uint64_t Value, unsigned Size) override;
255   void emitIntValueInHex(uint64_t Value, unsigned Size) override;
256   void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) override;
257 
258   void emitULEB128Value(const MCExpr *Value) override;
259 
260   void emitSLEB128Value(const MCExpr *Value) override;
261 
262   void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
263                 SMLoc Loc = SMLoc()) override;
264 
265   void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
266                 SMLoc Loc = SMLoc()) override;
267 
268   void emitAlignmentDirective(uint64_t ByteAlignment,
269                               std::optional<int64_t> Value, unsigned ValueSize,
270                               unsigned MaxBytesToEmit);
271 
272   void emitValueToAlignment(Align Alignment, int64_t Fill = 0,
273                             uint8_t FillLen = 1,
274                             unsigned MaxBytesToEmit = 0) override;
275 
276   void emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI,
277                          unsigned MaxBytesToEmit = 0) override;
278 
279   void emitValueToOffset(const MCExpr *Offset,
280                          unsigned char Value,
281                          SMLoc Loc) override;
282 
283   void emitFileDirective(StringRef Filename) override;
284   void emitFileDirective(StringRef Filename, StringRef CompilerVersion,
285                          StringRef TimeStamp, StringRef Description) override;
286   Expected<unsigned> tryEmitDwarfFileDirective(
287       unsigned FileNo, StringRef Directory, StringRef Filename,
288       std::optional<MD5::MD5Result> Checksum = std::nullopt,
289       std::optional<StringRef> Source = std::nullopt,
290       unsigned CUID = 0) override;
291   void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
292                                std::optional<MD5::MD5Result> Checksum,
293                                std::optional<StringRef> Source,
294                                unsigned CUID = 0) override;
295   void emitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column,
296                              unsigned Flags, unsigned Isa,
297                              unsigned Discriminator, StringRef FileName,
298                              StringRef Location = {}) override;
299   virtual void emitDwarfLocLabelDirective(SMLoc Loc, StringRef Name) override;
300 
301   MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override;
302 
303   bool emitCVFileDirective(unsigned FileNo, StringRef Filename,
304                            ArrayRef<uint8_t> Checksum,
305                            unsigned ChecksumKind) override;
306   bool emitCVFuncIdDirective(unsigned FuncId) override;
307   bool emitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
308                                    unsigned IAFile, unsigned IALine,
309                                    unsigned IACol, SMLoc Loc) override;
310   void emitCVLocDirective(unsigned FunctionId, unsigned FileNo, unsigned Line,
311                           unsigned Column, bool PrologueEnd, bool IsStmt,
312                           StringRef FileName, SMLoc Loc) override;
313   void emitCVLinetableDirective(unsigned FunctionId, const MCSymbol *FnStart,
314                                 const MCSymbol *FnEnd) override;
315   void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
316                                       unsigned SourceFileId,
317                                       unsigned SourceLineNum,
318                                       const MCSymbol *FnStartSym,
319                                       const MCSymbol *FnEndSym) override;
320 
321   void PrintCVDefRangePrefix(
322       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges);
323 
324   void emitCVDefRangeDirective(
325       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
326       codeview::DefRangeRegisterRelHeader DRHdr) override;
327 
328   void emitCVDefRangeDirective(
329       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
330       codeview::DefRangeSubfieldRegisterHeader DRHdr) override;
331 
332   void emitCVDefRangeDirective(
333       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
334       codeview::DefRangeRegisterHeader DRHdr) override;
335 
336   void emitCVDefRangeDirective(
337       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
338       codeview::DefRangeFramePointerRelHeader DRHdr) override;
339 
340   void emitCVStringTableDirective() override;
341   void emitCVFileChecksumsDirective() override;
342   void emitCVFileChecksumOffsetDirective(unsigned FileNo) override;
343   void emitCVFPOData(const MCSymbol *ProcSym, SMLoc L) override;
344 
345   void emitIdent(StringRef IdentString) override;
346   void emitCFIBKeyFrame() override;
347   void emitCFIMTETaggedFrame() override;
348   void emitCFISections(bool EH, bool Debug) override;
349   void emitCFIDefCfa(int64_t Register, int64_t Offset, SMLoc Loc) override;
350   void emitCFIDefCfaOffset(int64_t Offset, SMLoc Loc) override;
351   void emitCFIDefCfaRegister(int64_t Register, SMLoc Loc) override;
352   void emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
353                                int64_t AddressSpace, SMLoc Loc) override;
354   void emitCFIOffset(int64_t Register, int64_t Offset, SMLoc Loc) override;
355   void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override;
356   void emitCFILsda(const MCSymbol *Sym, unsigned Encoding) override;
357   void emitCFIRememberState(SMLoc Loc) override;
358   void emitCFIRestoreState(SMLoc Loc) override;
359   void emitCFIRestore(int64_t Register, SMLoc Loc) override;
360   void emitCFISameValue(int64_t Register, SMLoc Loc) override;
361   void emitCFIRelOffset(int64_t Register, int64_t Offset, SMLoc Loc) override;
362   void emitCFIAdjustCfaOffset(int64_t Adjustment, SMLoc Loc) override;
363   void emitCFIEscape(StringRef Values, SMLoc Loc) override;
364   void emitCFIGnuArgsSize(int64_t Size, SMLoc Loc) override;
365   void emitCFISignalFrame() override;
366   void emitCFIUndefined(int64_t Register, SMLoc Loc) override;
367   void emitCFIRegister(int64_t Register1, int64_t Register2,
368                        SMLoc Loc) override;
369   void emitCFIWindowSave(SMLoc Loc) override;
370   void emitCFINegateRAState(SMLoc Loc) override;
371   void emitCFINegateRAStateWithPC(SMLoc Loc) override;
372   void emitCFIReturnColumn(int64_t Register) override;
373   void emitCFILabelDirective(SMLoc Loc, StringRef Name) override;
374   void emitCFIValOffset(int64_t Register, int64_t Offset, SMLoc Loc) override;
375 
376   void emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) override;
377   void emitWinCFIEndProc(SMLoc Loc) override;
378   void emitWinCFIFuncletOrFuncEnd(SMLoc Loc) override;
379   void emitWinCFIStartChained(SMLoc Loc) override;
380   void emitWinCFIEndChained(SMLoc Loc) override;
381   void emitWinCFIPushReg(MCRegister Register, SMLoc Loc) override;
382   void emitWinCFISetFrame(MCRegister Register, unsigned Offset,
383                           SMLoc Loc) override;
384   void emitWinCFIAllocStack(unsigned Size, SMLoc Loc) override;
385   void emitWinCFISaveReg(MCRegister Register, unsigned Offset,
386                          SMLoc Loc) override;
387   void emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
388                          SMLoc Loc) override;
389   void emitWinCFIPushFrame(bool Code, SMLoc Loc) override;
390   void emitWinCFIEndProlog(SMLoc Loc) override;
391   void emitWinCFIBeginEpilogue(SMLoc Loc) override;
392   void emitWinCFIEndEpilogue(SMLoc Loc) override;
393   void emitWinCFIUnwindV2Start(SMLoc Loc) override;
394   void emitWinCFIUnwindVersion(uint8_t Version, SMLoc Loc) override;
395 
396   void emitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
397                         SMLoc Loc) override;
398   void emitWinEHHandlerData(SMLoc Loc) override;
399 
400   void emitCGProfileEntry(const MCSymbolRefExpr *From,
401                           const MCSymbolRefExpr *To, uint64_t Count) override;
402 
403   void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override;
404 
405   void emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
406                        uint64_t Attr, uint64_t Discriminator,
407                        const MCPseudoProbeInlineStack &InlineStack,
408                        MCSymbol *FnSym) override;
409 
410   void emitBundleAlignMode(Align Alignment) override;
411   void emitBundleLock(bool AlignToEnd) override;
412   void emitBundleUnlock() override;
413 
414   std::optional<std::pair<bool, std::string>>
415   emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr,
416                      SMLoc Loc, const MCSubtargetInfo &STI) override;
417 
418   void emitAddrsig() override;
419   void emitAddrsigSym(const MCSymbol *Sym) override;
420 
421   /// If this file is backed by an assembly streamer, this dumps the specified
422   /// string in the output .s file. This capability is indicated by the
423   /// hasRawTextSupport() predicate.
424   void emitRawTextImpl(StringRef String) override;
425 
426   void finishImpl() override;
427 
428   void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) override;
429 
430   MCSymbol *emitDwarfUnitLength(const Twine &Prefix,
431                                 const Twine &Comment) override;
432 
433   void emitDwarfLineStartLabel(MCSymbol *StartSym) override;
434 
435   void emitDwarfLineEndEntry(MCSection *Section, MCSymbol *LastLabel,
436                              MCSymbol *EndLabel = nullptr) override;
437 
438   void emitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
439                                 const MCSymbol *Label,
440                                 unsigned PointerSize) override;
441 };
442 
443 } // end anonymous namespace.
444 
AddComment(const Twine & T,bool EOL)445 void MCAsmStreamer::AddComment(const Twine &T, bool EOL) {
446   if (!IsVerboseAsm) return;
447 
448   T.toVector(CommentToEmit);
449 
450   if (EOL)
451     CommentToEmit.push_back('\n'); // Place comment in a new line.
452 }
453 
EmitCommentsAndEOL()454 void MCAsmStreamer::EmitCommentsAndEOL() {
455   if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
456     OS << '\n';
457     return;
458   }
459 
460   StringRef Comments = CommentToEmit;
461 
462   assert(Comments.back() == '\n' &&
463          "Comment array not newline terminated");
464   do {
465     // Emit a line of comments.
466     OS.PadToColumn(MAI->getCommentColumn());
467     size_t Position = Comments.find('\n');
468     OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n';
469 
470     Comments = Comments.substr(Position+1);
471   } while (!Comments.empty());
472 
473   CommentToEmit.clear();
474 }
475 
truncateToSize(int64_t Value,unsigned Bytes)476 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
477   assert(Bytes > 0 && Bytes <= 8 && "Invalid size!");
478   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
479 }
480 
emitRawComment(const Twine & T,bool TabPrefix)481 void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
482   if (TabPrefix)
483     OS << '\t';
484   OS << MAI->getCommentString() << T;
485   EmitEOL();
486 }
487 
addExplicitComment(const Twine & T)488 void MCAsmStreamer::addExplicitComment(const Twine &T) {
489   StringRef c = T.getSingleStringRef();
490   if (c == MAI->getSeparatorString())
491     return;
492   if (c.starts_with(StringRef("//"))) {
493     ExplicitCommentToEmit.append("\t");
494     ExplicitCommentToEmit.append(MAI->getCommentString());
495     // drop //
496     ExplicitCommentToEmit.append(c.substr(2).str());
497   } else if (c.starts_with(StringRef("/*"))) {
498     size_t p = 2, len = c.size() - 2;
499     // emit each line in comment as separate newline.
500     do {
501       size_t newp = std::min(len, c.find_first_of("\r\n", p));
502       ExplicitCommentToEmit.append("\t");
503       ExplicitCommentToEmit.append(MAI->getCommentString());
504       ExplicitCommentToEmit.append(c.slice(p, newp).str());
505       // If we have another line in this comment add line
506       if (newp < len)
507         ExplicitCommentToEmit.append("\n");
508       p = newp + 1;
509     } while (p < len);
510   } else if (c.starts_with(StringRef(MAI->getCommentString()))) {
511     ExplicitCommentToEmit.append("\t");
512     ExplicitCommentToEmit.append(c.str());
513   } else if (c.front() == '#') {
514 
515     ExplicitCommentToEmit.append("\t");
516     ExplicitCommentToEmit.append(MAI->getCommentString());
517     ExplicitCommentToEmit.append(c.substr(1).str());
518   } else
519     assert(false && "Unexpected Assembly Comment");
520   // full line comments immediately output
521   if (c.back() == '\n')
522     emitExplicitComments();
523 }
524 
emitExplicitComments()525 void MCAsmStreamer::emitExplicitComments() {
526   StringRef Comments = ExplicitCommentToEmit;
527   if (!Comments.empty())
528     OS << Comments;
529   ExplicitCommentToEmit.clear();
530 }
531 
switchSection(MCSection * Section,uint32_t Subsection)532 void MCAsmStreamer::switchSection(MCSection *Section, uint32_t Subsection) {
533   MCSectionSubPair Cur = getCurrentSection();
534   if (!EmittedSectionDirective ||
535       MCSectionSubPair(Section, Subsection) != Cur) {
536     EmittedSectionDirective = true;
537     if (MCTargetStreamer *TS = getTargetStreamer()) {
538       TS->changeSection(Cur.first, Section, Subsection, OS);
539     } else {
540       Section->printSwitchToSection(*MAI, getContext().getTargetTriple(), OS,
541                                     Subsection);
542     }
543   }
544   MCStreamer::switchSection(Section, Subsection);
545 }
546 
popSection()547 bool MCAsmStreamer::popSection() {
548   if (!MCStreamer::popSection())
549     return false;
550   auto [Sec, Subsec] = getCurrentSection();
551   Sec->printSwitchToSection(*MAI, getContext().getTargetTriple(), OS, Subsec);
552   return true;
553 }
554 
emitELFSymverDirective(const MCSymbol * OriginalSym,StringRef Name,bool KeepOriginalSym)555 void MCAsmStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
556                                            StringRef Name,
557                                            bool KeepOriginalSym) {
558   OS << ".symver ";
559   OriginalSym->print(OS, MAI);
560   OS << ", " << Name;
561   if (!KeepOriginalSym && !Name.contains("@@@"))
562     OS << ", remove";
563   EmitEOL();
564 }
565 
emitLabel(MCSymbol * Symbol,SMLoc Loc)566 void MCAsmStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
567   MCStreamer::emitLabel(Symbol, Loc);
568   // FIXME: Fix CodeGen/AArch64/arm64ec-varargs.ll. emitLabel is followed by
569   // setVariableValue, leading to an assertion failure if setOffset(0) is
570   // called.
571   if (!Symbol->isVariable() &&
572       getContext().getObjectFileType() != MCContext::IsCOFF)
573     Symbol->setOffset(0);
574 
575   Symbol->print(OS, MAI);
576   OS << MAI->getLabelSuffix();
577 
578   EmitEOL();
579 }
580 
emitLOHDirective(MCLOHType Kind,const MCLOHArgs & Args)581 void MCAsmStreamer::emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {
582   StringRef str = MCLOHIdToName(Kind);
583 
584 #ifndef NDEBUG
585   int NbArgs = MCLOHIdToNbArgs(Kind);
586   assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!");
587   assert(str != "" && "Invalid LOH name");
588 #endif
589 
590   OS << "\t" << MCLOHDirectiveName() << " " << str << "\t";
591   bool IsFirst = true;
592   for (const MCSymbol *Arg : Args) {
593     if (!IsFirst)
594       OS << ", ";
595     IsFirst = false;
596     Arg->print(OS, MAI);
597   }
598   EmitEOL();
599 }
600 
emitGNUAttribute(unsigned Tag,unsigned Value)601 void MCAsmStreamer::emitGNUAttribute(unsigned Tag, unsigned Value) {
602   OS << "\t.gnu_attribute " << Tag << ", " << Value << "\n";
603 }
604 
emitSubsectionsViaSymbols()605 void MCAsmStreamer::emitSubsectionsViaSymbols() {
606   OS << ".subsections_via_symbols\n";
607 }
608 
emitLinkerOptions(ArrayRef<std::string> Options)609 void MCAsmStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
610   assert(!Options.empty() && "At least one option is required!");
611   OS << "\t.linker_option \"" << Options[0] << '"';
612   for (const std::string &Opt : llvm::drop_begin(Options))
613     OS << ", " << '"' << Opt << '"';
614   EmitEOL();
615 }
616 
emitDataRegion(MCDataRegionType Kind)617 void MCAsmStreamer::emitDataRegion(MCDataRegionType Kind) {
618   if (!MAI->doesSupportDataRegionDirectives())
619     return;
620   switch (Kind) {
621   case MCDR_DataRegion:            OS << "\t.data_region"; break;
622   case MCDR_DataRegionJT8:         OS << "\t.data_region jt8"; break;
623   case MCDR_DataRegionJT16:        OS << "\t.data_region jt16"; break;
624   case MCDR_DataRegionJT32:        OS << "\t.data_region jt32"; break;
625   case MCDR_DataRegionEnd:         OS << "\t.end_data_region"; break;
626   }
627   EmitEOL();
628 }
629 
getVersionMinDirective(MCVersionMinType Type)630 static const char *getVersionMinDirective(MCVersionMinType Type) {
631   switch (Type) {
632   case MCVM_WatchOSVersionMin: return ".watchos_version_min";
633   case MCVM_TvOSVersionMin:    return ".tvos_version_min";
634   case MCVM_IOSVersionMin:     return ".ios_version_min";
635   case MCVM_OSXVersionMin:     return ".macosx_version_min";
636   }
637   llvm_unreachable("Invalid MC version min type");
638 }
639 
EmitSDKVersionSuffix(raw_ostream & OS,const VersionTuple & SDKVersion)640 static void EmitSDKVersionSuffix(raw_ostream &OS,
641                                  const VersionTuple &SDKVersion) {
642   if (SDKVersion.empty())
643     return;
644   OS << '\t' << "sdk_version " << SDKVersion.getMajor();
645   if (auto Minor = SDKVersion.getMinor()) {
646     OS << ", " << *Minor;
647     if (auto Subminor = SDKVersion.getSubminor()) {
648       OS << ", " << *Subminor;
649     }
650   }
651 }
652 
emitVersionMin(MCVersionMinType Type,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)653 void MCAsmStreamer::emitVersionMin(MCVersionMinType Type, unsigned Major,
654                                    unsigned Minor, unsigned Update,
655                                    VersionTuple SDKVersion) {
656   OS << '\t' << getVersionMinDirective(Type) << ' ' << Major << ", " << Minor;
657   if (Update)
658     OS << ", " << Update;
659   EmitSDKVersionSuffix(OS, SDKVersion);
660   EmitEOL();
661 }
662 
getPlatformName(MachO::PlatformType Type)663 static const char *getPlatformName(MachO::PlatformType Type) {
664   switch (Type) {
665 #define PLATFORM(platform, id, name, build_name, target, tapi_target,          \
666                  marketing)                                                    \
667   case MachO::PLATFORM_##platform:                                             \
668     return #build_name;
669 #include "llvm/BinaryFormat/MachO.def"
670   }
671   llvm_unreachable("Invalid Mach-O platform type");
672 }
673 
emitBuildVersion(unsigned Platform,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)674 void MCAsmStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
675                                      unsigned Minor, unsigned Update,
676                                      VersionTuple SDKVersion) {
677   const char *PlatformName = getPlatformName((MachO::PlatformType)Platform);
678   OS << "\t.build_version " << PlatformName << ", " << Major << ", " << Minor;
679   if (Update)
680     OS << ", " << Update;
681   EmitSDKVersionSuffix(OS, SDKVersion);
682   EmitEOL();
683 }
684 
emitDarwinTargetVariantBuildVersion(unsigned Platform,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)685 void MCAsmStreamer::emitDarwinTargetVariantBuildVersion(
686     unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
687     VersionTuple SDKVersion) {
688   emitBuildVersion(Platform, Major, Minor, Update, SDKVersion);
689 }
690 
emitAssignment(MCSymbol * Symbol,const MCExpr * Value)691 void MCAsmStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
692   bool UseSet = MAI->usesSetToEquateSymbol();
693   if (UseSet)
694     OS << ".set ";
695   Symbol->print(OS, MAI);
696   OS << (UseSet ? ", " : " = ");
697   MAI->printExpr(OS, *Value);
698 
699   EmitEOL();
700   MCStreamer::emitAssignment(Symbol, Value);
701 }
702 
emitConditionalAssignment(MCSymbol * Symbol,const MCExpr * Value)703 void MCAsmStreamer::emitConditionalAssignment(MCSymbol *Symbol,
704                                               const MCExpr *Value) {
705   OS << ".lto_set_conditional ";
706   Symbol->print(OS, MAI);
707   OS << ", ";
708   MAI->printExpr(OS, *Value);
709   EmitEOL();
710 }
711 
emitWeakReference(MCSymbol * Alias,const MCSymbol * Symbol)712 void MCAsmStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
713   OS << ".weakref ";
714   Alias->print(OS, MAI);
715   OS << ", ";
716   Symbol->print(OS, MAI);
717   EmitEOL();
718 }
719 
emitSymbolAttribute(MCSymbol * Symbol,MCSymbolAttr Attribute)720 bool MCAsmStreamer::emitSymbolAttribute(MCSymbol *Symbol,
721                                         MCSymbolAttr Attribute) {
722   switch (Attribute) {
723   case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
724   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
725   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
726   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
727   case MCSA_ELF_TypeTLS:         /// .type _foo, STT_TLS     # aka @tls_object
728   case MCSA_ELF_TypeCommon:      /// .type _foo, STT_COMMON  # aka @common
729   case MCSA_ELF_TypeNoType:      /// .type _foo, STT_NOTYPE  # aka @notype
730   case MCSA_ELF_TypeGnuUniqueObject:  /// .type _foo, @gnu_unique_object
731     if (!MAI->hasDotTypeDotSizeDirective())
732       return false; // Symbol attribute not supported
733     OS << "\t.type\t";
734     Symbol->print(OS, MAI);
735     OS << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%');
736     switch (Attribute) {
737     default: return false;
738     case MCSA_ELF_TypeFunction:    OS << "function"; break;
739     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
740     case MCSA_ELF_TypeObject:      OS << "object"; break;
741     case MCSA_ELF_TypeTLS:         OS << "tls_object"; break;
742     case MCSA_ELF_TypeCommon:      OS << "common"; break;
743     case MCSA_ELF_TypeNoType:      OS << "notype"; break;
744     case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
745     }
746     EmitEOL();
747     return true;
748   case MCSA_Global: // .globl/.global
749     OS << MAI->getGlobalDirective();
750     break;
751   case MCSA_LGlobal:        OS << "\t.lglobl\t";          break;
752   case MCSA_Hidden:         OS << "\t.hidden\t";          break;
753   case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
754   case MCSA_Internal:       OS << "\t.internal\t";        break;
755   case MCSA_LazyReference:  OS << "\t.lazy_reference\t";  break;
756   case MCSA_Local:          OS << "\t.local\t";           break;
757   case MCSA_NoDeadStrip:
758     if (!MAI->hasNoDeadStrip())
759       return false;
760     OS << "\t.no_dead_strip\t";
761     break;
762   case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
763   case MCSA_AltEntry:       OS << "\t.alt_entry\t";       break;
764   case MCSA_PrivateExtern:
765     OS << "\t.private_extern\t";
766     break;
767   case MCSA_Protected:      OS << "\t.protected\t";       break;
768   case MCSA_Reference:      OS << "\t.reference\t";       break;
769   case MCSA_Extern:
770     OS << "\t.extern\t";
771     break;
772   case MCSA_Weak:           OS << MAI->getWeakDirective(); break;
773   case MCSA_WeakDefinition:
774     OS << "\t.weak_definition\t";
775     break;
776       // .weak_reference
777   case MCSA_WeakReference:  OS << MAI->getWeakRefDirective(); break;
778   case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
779   case MCSA_Cold:
780     // Assemblers currently do not support a .cold directive.
781   case MCSA_Exported:
782     // Non-AIX assemblers currently do not support exported visibility.
783     return false;
784   case MCSA_Memtag:
785     OS << "\t.memtag\t";
786     break;
787   case MCSA_WeakAntiDep:
788     OS << "\t.weak_anti_dep\t";
789     break;
790   }
791 
792   Symbol->print(OS, MAI);
793   EmitEOL();
794 
795   return true;
796 }
797 
emitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)798 void MCAsmStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
799   OS << ".desc" << ' ';
800   Symbol->print(OS, MAI);
801   OS << ',' << DescValue;
802   EmitEOL();
803 }
804 
emitSyntaxDirective()805 void MCAsmStreamer::emitSyntaxDirective() {
806   if (MAI->getAssemblerDialect() == 1) {
807     OS << "\t.intel_syntax noprefix";
808     EmitEOL();
809   }
810   // FIXME: Currently emit unprefix'ed registers.
811   // The intel_syntax directive has one optional argument
812   // with may have a value of prefix or noprefix.
813 }
814 
beginCOFFSymbolDef(const MCSymbol * Symbol)815 void MCAsmStreamer::beginCOFFSymbolDef(const MCSymbol *Symbol) {
816   OS << "\t.def\t";
817   Symbol->print(OS, MAI);
818   OS << ';';
819   EmitEOL();
820 }
821 
emitCOFFSymbolStorageClass(int StorageClass)822 void MCAsmStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
823   OS << "\t.scl\t" << StorageClass << ';';
824   EmitEOL();
825 }
826 
emitCOFFSymbolType(int Type)827 void MCAsmStreamer::emitCOFFSymbolType(int Type) {
828   OS << "\t.type\t" << Type << ';';
829   EmitEOL();
830 }
831 
endCOFFSymbolDef()832 void MCAsmStreamer::endCOFFSymbolDef() {
833   OS << "\t.endef";
834   EmitEOL();
835 }
836 
emitCOFFSafeSEH(MCSymbol const * Symbol)837 void MCAsmStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {
838   OS << "\t.safeseh\t";
839   Symbol->print(OS, MAI);
840   EmitEOL();
841 }
842 
emitCOFFSymbolIndex(MCSymbol const * Symbol)843 void MCAsmStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {
844   OS << "\t.symidx\t";
845   Symbol->print(OS, MAI);
846   EmitEOL();
847 }
848 
emitCOFFSectionIndex(MCSymbol const * Symbol)849 void MCAsmStreamer::emitCOFFSectionIndex(MCSymbol const *Symbol) {
850   OS << "\t.secidx\t";
851   Symbol->print(OS, MAI);
852   EmitEOL();
853 }
854 
emitCOFFSecRel32(MCSymbol const * Symbol,uint64_t Offset)855 void MCAsmStreamer::emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {
856   OS << "\t.secrel32\t";
857   Symbol->print(OS, MAI);
858   if (Offset != 0)
859     OS << '+' << Offset;
860   EmitEOL();
861 }
862 
emitCOFFImgRel32(MCSymbol const * Symbol,int64_t Offset)863 void MCAsmStreamer::emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {
864   OS << "\t.rva\t";
865   Symbol->print(OS, MAI);
866   if (Offset > 0)
867     OS << '+' << Offset;
868   else if (Offset < 0)
869     OS << '-' << -Offset;
870   EmitEOL();
871 }
872 
emitCOFFSecNumber(MCSymbol const * Symbol)873 void MCAsmStreamer::emitCOFFSecNumber(MCSymbol const *Symbol) {
874   OS << "\t.secnum\t";
875   Symbol->print(OS, MAI);
876   EmitEOL();
877 }
878 
emitCOFFSecOffset(MCSymbol const * Symbol)879 void MCAsmStreamer::emitCOFFSecOffset(MCSymbol const *Symbol) {
880   OS << "\t.secoffset\t";
881   Symbol->print(OS, MAI);
882   EmitEOL();
883 }
884 
885 // We need an XCOFF-specific version of this directive as the AIX syntax
886 // requires a QualName argument identifying the csect name and storage mapping
887 // class to appear before the alignment if we are specifying it.
emitXCOFFLocalCommonSymbol(MCSymbol * LabelSym,uint64_t Size,MCSymbol * CsectSym,Align Alignment)888 void MCAsmStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym,
889                                                uint64_t Size,
890                                                MCSymbol *CsectSym,
891                                                Align Alignment) {
892   assert(MAI->getLCOMMDirectiveAlignmentType() == LCOMM::Log2Alignment &&
893          "We only support writing log base-2 alignment format with XCOFF.");
894 
895   OS << "\t.lcomm\t";
896   LabelSym->print(OS, MAI);
897   OS << ',' << Size << ',';
898   CsectSym->print(OS, MAI);
899   OS << ',' << Log2(Alignment);
900 
901   EmitEOL();
902 
903   // Print symbol's rename (original name contains invalid character(s)) if
904   // there is one.
905   MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(CsectSym);
906   if (XSym->hasRename())
907     emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
908 }
909 
emitXCOFFSymbolLinkageWithVisibility(MCSymbol * Symbol,MCSymbolAttr Linkage,MCSymbolAttr Visibility)910 void MCAsmStreamer::emitXCOFFSymbolLinkageWithVisibility(
911     MCSymbol *Symbol, MCSymbolAttr Linkage, MCSymbolAttr Visibility) {
912 
913   switch (Linkage) {
914   case MCSA_Global:
915     OS << MAI->getGlobalDirective();
916     break;
917   case MCSA_Weak:
918     OS << MAI->getWeakDirective();
919     break;
920   case MCSA_Extern:
921     OS << "\t.extern\t";
922     break;
923   case MCSA_LGlobal:
924     OS << "\t.lglobl\t";
925     break;
926   default:
927     report_fatal_error("unhandled linkage type");
928   }
929 
930   Symbol->print(OS, MAI);
931 
932   switch (Visibility) {
933   case MCSA_Invalid:
934     // Nothing to do.
935     break;
936   case MCSA_Hidden:
937     OS << ",hidden";
938     break;
939   case MCSA_Protected:
940     OS << ",protected";
941     break;
942   case MCSA_Exported:
943     OS << ",exported";
944     break;
945   default:
946     report_fatal_error("unexpected value for Visibility type");
947   }
948   EmitEOL();
949 
950   // Print symbol's rename (original name contains invalid character(s)) if
951   // there is one.
952   if (cast<MCSymbolXCOFF>(Symbol)->hasRename())
953     emitXCOFFRenameDirective(Symbol,
954                              cast<MCSymbolXCOFF>(Symbol)->getSymbolTableName());
955 }
956 
emitXCOFFRenameDirective(const MCSymbol * Name,StringRef Rename)957 void MCAsmStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
958                                              StringRef Rename) {
959   OS << "\t.rename\t";
960   Name->print(OS, MAI);
961   const char DQ = '"';
962   OS << ',' << DQ;
963   for (char C : Rename) {
964     // To escape a double quote character, the character should be doubled.
965     if (C == DQ)
966       OS << DQ;
967     OS << C;
968   }
969   OS << DQ;
970   EmitEOL();
971 }
972 
emitXCOFFRefDirective(const MCSymbol * Symbol)973 void MCAsmStreamer::emitXCOFFRefDirective(const MCSymbol *Symbol) {
974   OS << "\t.ref ";
975   Symbol->print(OS, MAI);
976   EmitEOL();
977 }
978 
emitXCOFFExceptDirective(const MCSymbol * Symbol,const MCSymbol * Trap,unsigned Lang,unsigned Reason,unsigned FunctionSize,bool hasDebug)979 void MCAsmStreamer::emitXCOFFExceptDirective(const MCSymbol *Symbol,
980                                              const MCSymbol *Trap,
981                                              unsigned Lang,
982                                              unsigned Reason,
983                                              unsigned FunctionSize,
984                                              bool hasDebug) {
985   OS << "\t.except\t";
986   Symbol->print(OS, MAI);
987   OS << ", " << Lang << ", " << Reason;
988   EmitEOL();
989 }
990 
emitXCOFFCInfoSym(StringRef Name,StringRef Metadata)991 void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
992   const char InfoDirective[] = "\t.info ";
993   const char *Separator = ", ";
994   constexpr int WordSize = sizeof(uint32_t);
995 
996   // Start by emitting the .info pseudo-op and C_INFO symbol name.
997   OS << InfoDirective;
998   PrintQuotedString(Name, OS);
999   OS << Separator;
1000 
1001   size_t MetadataSize = Metadata.size();
1002 
1003   // Emit the 4-byte length of the metadata.
1004   OS << format_hex(MetadataSize, 10) << Separator;
1005 
1006   // Nothing left to do if there's no metadata.
1007   if (MetadataSize == 0) {
1008     EmitEOL();
1009     return;
1010   }
1011 
1012   // Metadata needs to be padded out to an even word size when generating
1013   // assembly because the .info pseudo-op can only generate words of data. We
1014   // apply the same restriction to the object case for consistency, however the
1015   // linker doesn't require padding, so it will only save bytes specified by the
1016   // length and discard any padding.
1017   uint32_t PaddedSize = alignTo(MetadataSize, WordSize);
1018   uint32_t PaddingSize = PaddedSize - MetadataSize;
1019 
1020   // Write out the payload a word at a time.
1021   //
1022   // The assembler has a limit on the number of operands in an expression,
1023   // so we need multiple .info pseudo-ops. We choose a small number of words
1024   // per pseudo-op to keep the assembly readable.
1025   constexpr int WordsPerDirective = 5;
1026   // Force emitting a new directive to keep the first directive purely about the
1027   // name and size of the note.
1028   int WordsBeforeNextDirective = 0;
1029   auto PrintWord = [&](const uint8_t *WordPtr) {
1030     if (WordsBeforeNextDirective-- == 0) {
1031       EmitEOL();
1032       OS << InfoDirective;
1033       WordsBeforeNextDirective = WordsPerDirective;
1034     }
1035     OS << Separator;
1036     uint32_t Word = llvm::support::endian::read32be(WordPtr);
1037     OS << format_hex(Word, 10);
1038   };
1039 
1040   size_t Index = 0;
1041   for (; Index + WordSize <= MetadataSize; Index += WordSize)
1042     PrintWord(reinterpret_cast<const uint8_t *>(Metadata.data()) + Index);
1043 
1044   // If there is padding, then we have at least one byte of payload left
1045   // to emit.
1046   if (PaddingSize) {
1047     assert(PaddedSize - Index == WordSize);
1048     std::array<uint8_t, WordSize> LastWord = {0};
1049     ::memcpy(LastWord.data(), Metadata.data() + Index, MetadataSize - Index);
1050     PrintWord(LastWord.data());
1051   }
1052   EmitEOL();
1053 }
1054 
emitELFSize(MCSymbol * Symbol,const MCExpr * Value)1055 void MCAsmStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
1056   assert(MAI->hasDotTypeDotSizeDirective());
1057   OS << "\t.size\t";
1058   Symbol->print(OS, MAI);
1059   OS << ", ";
1060   MAI->printExpr(OS, *Value);
1061   EmitEOL();
1062 }
1063 
emitCommonSymbol(MCSymbol * Symbol,uint64_t Size,Align ByteAlignment)1064 void MCAsmStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1065                                      Align ByteAlignment) {
1066   OS << "\t.comm\t";
1067   Symbol->print(OS, MAI);
1068   OS << ',' << Size;
1069 
1070   if (MAI->getCOMMDirectiveAlignmentIsInBytes())
1071     OS << ',' << ByteAlignment.value();
1072   else
1073     OS << ',' << Log2(ByteAlignment);
1074   EmitEOL();
1075 
1076   // Print symbol's rename (original name contains invalid character(s)) if
1077   // there is one.
1078   MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(Symbol);
1079   if (XSym && XSym->hasRename())
1080     emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
1081 }
1082 
emitLocalCommonSymbol(MCSymbol * Symbol,uint64_t Size,Align ByteAlign)1083 void MCAsmStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1084                                           Align ByteAlign) {
1085   OS << "\t.lcomm\t";
1086   Symbol->print(OS, MAI);
1087   OS << ',' << Size;
1088 
1089   if (ByteAlign > 1) {
1090     switch (MAI->getLCOMMDirectiveAlignmentType()) {
1091     case LCOMM::NoAlignment:
1092       llvm_unreachable("alignment not supported on .lcomm!");
1093     case LCOMM::ByteAlignment:
1094       OS << ',' << ByteAlign.value();
1095       break;
1096     case LCOMM::Log2Alignment:
1097       OS << ',' << Log2(ByteAlign);
1098       break;
1099     }
1100   }
1101   EmitEOL();
1102 }
1103 
emitZerofill(MCSection * Section,MCSymbol * Symbol,uint64_t Size,Align ByteAlignment,SMLoc Loc)1104 void MCAsmStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
1105                                  uint64_t Size, Align ByteAlignment,
1106                                  SMLoc Loc) {
1107   if (Symbol)
1108     Symbol->setFragment(&Section->getDummyFragment());
1109 
1110   // Note: a .zerofill directive does not switch sections.
1111   OS << ".zerofill ";
1112 
1113   assert(Section->getVariant() == MCSection::SV_MachO &&
1114          ".zerofill is a Mach-O specific directive");
1115   // This is a mach-o specific directive.
1116 
1117   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
1118   OS << MOSection->getSegmentName() << "," << MOSection->getName();
1119 
1120   if (Symbol) {
1121     OS << ',';
1122     Symbol->print(OS, MAI);
1123     OS << ',' << Size;
1124     OS << ',' << Log2(ByteAlignment);
1125   }
1126   EmitEOL();
1127 }
1128 
1129 // .tbss sym, size, align
1130 // This depends that the symbol has already been mangled from the original,
1131 // e.g. _a.
emitTBSSSymbol(MCSection * Section,MCSymbol * Symbol,uint64_t Size,Align ByteAlignment)1132 void MCAsmStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
1133                                    uint64_t Size, Align ByteAlignment) {
1134   Symbol->setFragment(&Section->getDummyFragment());
1135 
1136   // Instead of using the Section we'll just use the shortcut.
1137 
1138   assert(Section->getVariant() == MCSection::SV_MachO &&
1139          ".zerofill is a Mach-O specific directive");
1140   // This is a mach-o specific directive and section.
1141 
1142   OS << ".tbss ";
1143   Symbol->print(OS, MAI);
1144   OS << ", " << Size;
1145 
1146   // Output align if we have it.  We default to 1 so don't bother printing
1147   // that.
1148   if (ByteAlignment > 1)
1149     OS << ", " << Log2(ByteAlignment);
1150 
1151   EmitEOL();
1152 }
1153 
isPrintableString(StringRef Data)1154 static inline bool isPrintableString(StringRef Data) {
1155   const auto BeginPtr = Data.begin(), EndPtr = Data.end();
1156   for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
1157     if (!isPrint(C))
1158       return false;
1159   }
1160   return isPrint(Data.back()) || Data.back() == 0;
1161 }
1162 
toOctal(int X)1163 static inline char toOctal(int X) { return (X&7)+'0'; }
1164 
PrintByteList(StringRef Data,raw_ostream & OS,MCAsmInfo::AsmCharLiteralSyntax ACLS)1165 static void PrintByteList(StringRef Data, raw_ostream &OS,
1166                           MCAsmInfo::AsmCharLiteralSyntax ACLS) {
1167   assert(!Data.empty() && "Cannot generate an empty list.");
1168   const auto printCharacterInOctal = [&OS](unsigned char C) {
1169     OS << '0';
1170     OS << toOctal(C >> 6);
1171     OS << toOctal(C >> 3);
1172     OS << toOctal(C >> 0);
1173   };
1174   const auto printOneCharacterFor = [printCharacterInOctal](
1175                                         auto printOnePrintingCharacter) {
1176     return [printCharacterInOctal, printOnePrintingCharacter](unsigned char C) {
1177       if (isPrint(C)) {
1178         printOnePrintingCharacter(static_cast<char>(C));
1179         return;
1180       }
1181       printCharacterInOctal(C);
1182     };
1183   };
1184   const auto printCharacterList = [Data, &OS](const auto &printOneCharacter) {
1185     const auto BeginPtr = Data.begin(), EndPtr = Data.end();
1186     for (const unsigned char C : make_range(BeginPtr, EndPtr - 1)) {
1187       printOneCharacter(C);
1188       OS << ',';
1189     }
1190     printOneCharacter(*(EndPtr - 1));
1191   };
1192   switch (ACLS) {
1193   case MCAsmInfo::ACLS_Unknown:
1194     printCharacterList(printCharacterInOctal);
1195     return;
1196   case MCAsmInfo::ACLS_SingleQuotePrefix:
1197     printCharacterList(printOneCharacterFor([&OS](char C) {
1198       const char AsmCharLitBuf[2] = {'\'', C};
1199       OS << StringRef(AsmCharLitBuf, sizeof(AsmCharLitBuf));
1200     }));
1201     return;
1202   }
1203   llvm_unreachable("Invalid AsmCharLiteralSyntax value!");
1204 }
1205 
PrintQuotedString(StringRef Data,raw_ostream & OS) const1206 void MCAsmStreamer::PrintQuotedString(StringRef Data, raw_ostream &OS) const {
1207   OS << '"';
1208 
1209   if (MAI->isAIX()) {
1210     for (unsigned char C : Data) {
1211       if (C == '"')
1212         OS << "\"\"";
1213       else
1214         OS << (char)C;
1215     }
1216   } else {
1217     for (unsigned char C : Data) {
1218       if (C == '"' || C == '\\') {
1219         OS << '\\' << (char)C;
1220         continue;
1221       }
1222 
1223       if (isPrint(C)) {
1224         OS << (char)C;
1225         continue;
1226       }
1227 
1228       switch (C) {
1229       case '\b':
1230         OS << "\\b";
1231         break;
1232       case '\f':
1233         OS << "\\f";
1234         break;
1235       case '\n':
1236         OS << "\\n";
1237         break;
1238       case '\r':
1239         OS << "\\r";
1240         break;
1241       case '\t':
1242         OS << "\\t";
1243         break;
1244       default:
1245         OS << '\\';
1246         OS << toOctal(C >> 6);
1247         OS << toOctal(C >> 3);
1248         OS << toOctal(C >> 0);
1249         break;
1250       }
1251     }
1252   }
1253 
1254   OS << '"';
1255 }
1256 
emitBytes(StringRef Data)1257 void MCAsmStreamer::emitBytes(StringRef Data) {
1258   assert(getCurrentSectionOnly() &&
1259          "Cannot emit contents before setting section!");
1260   if (Data.empty()) return;
1261 
1262   const auto emitAsString = [this](StringRef Data) {
1263     if (MAI->isAIX()) {
1264       if (isPrintableString(Data)) {
1265         // For target with DoubleQuoteString constants, .string and .byte are
1266         // used as replacement of .asciz and .ascii.
1267         if (Data.back() == 0) {
1268           OS << "\t.string\t";
1269           Data = Data.substr(0, Data.size() - 1);
1270         } else {
1271           OS << "\t.byte\t";
1272         }
1273         PrintQuotedString(Data, OS);
1274       } else {
1275         OS << "\t.byte\t";
1276         PrintByteList(Data, OS, MAI->characterLiteralSyntax());
1277       }
1278       EmitEOL();
1279       return true;
1280     }
1281 
1282     // If the data ends with 0 and the target supports .asciz, use it, otherwise
1283     // use .ascii or a byte-list directive
1284     if (MAI->getAscizDirective() && Data.back() == 0) {
1285       OS << MAI->getAscizDirective();
1286       Data = Data.substr(0, Data.size() - 1);
1287     } else if (LLVM_LIKELY(MAI->getAsciiDirective())) {
1288       OS << MAI->getAsciiDirective();
1289     } else {
1290       return false;
1291     }
1292 
1293     PrintQuotedString(Data, OS);
1294     EmitEOL();
1295     return true;
1296   };
1297 
1298   if (Data.size() != 1 && emitAsString(Data))
1299     return;
1300 
1301   // Only single byte is provided or no ascii, asciz, or byte-list directives
1302   // are applicable. Emit as vector of individual 8bits data elements.
1303   if (MCTargetStreamer *TS = getTargetStreamer()) {
1304     TS->emitRawBytes(Data);
1305     return;
1306   }
1307   const char *Directive = MAI->getData8bitsDirective();
1308   for (const unsigned char C : Data.bytes()) {
1309     OS << Directive << (unsigned)C;
1310     EmitEOL();
1311   }
1312 }
1313 
emitBinaryData(StringRef Data)1314 void MCAsmStreamer::emitBinaryData(StringRef Data) {
1315   // This is binary data. Print it in a grid of hex bytes for readability.
1316   const size_t Cols = 4;
1317   for (size_t I = 0, EI = alignTo(Data.size(), Cols); I < EI; I += Cols) {
1318     size_t J = I, EJ = std::min(I + Cols, Data.size());
1319     assert(EJ > 0);
1320     OS << MAI->getData8bitsDirective();
1321     for (; J < EJ - 1; ++J)
1322       OS << format("0x%02x", uint8_t(Data[J])) << ", ";
1323     OS << format("0x%02x", uint8_t(Data[J]));
1324     EmitEOL();
1325   }
1326 }
1327 
emitIntValue(uint64_t Value,unsigned Size)1328 void MCAsmStreamer::emitIntValue(uint64_t Value, unsigned Size) {
1329   emitValue(MCConstantExpr::create(Value, getContext()), Size);
1330 }
1331 
emitIntValueInHex(uint64_t Value,unsigned Size)1332 void MCAsmStreamer::emitIntValueInHex(uint64_t Value, unsigned Size) {
1333   emitValue(MCConstantExpr::create(Value, getContext(), true), Size);
1334 }
1335 
emitIntValueInHexWithPadding(uint64_t Value,unsigned Size)1336 void MCAsmStreamer::emitIntValueInHexWithPadding(uint64_t Value,
1337                                                  unsigned Size) {
1338   emitValue(MCConstantExpr::create(Value, getContext(), true, Size), Size);
1339 }
1340 
emitValueImpl(const MCExpr * Value,unsigned Size,SMLoc Loc)1341 void MCAsmStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
1342                                   SMLoc Loc) {
1343   assert(Size <= 8 && "Invalid size");
1344   assert(getCurrentSectionOnly() &&
1345          "Cannot emit contents before setting section!");
1346   const char *Directive = nullptr;
1347   switch (Size) {
1348   default: break;
1349   case 1: Directive = MAI->getData8bitsDirective();  break;
1350   case 2: Directive = MAI->getData16bitsDirective(); break;
1351   case 4: Directive = MAI->getData32bitsDirective(); break;
1352   case 8: Directive = MAI->getData64bitsDirective(); break;
1353   }
1354 
1355   if (!Directive) {
1356     int64_t IntValue;
1357     if (!Value->evaluateAsAbsolute(IntValue))
1358       report_fatal_error("Don't know how to emit this value.");
1359 
1360     // We couldn't handle the requested integer size so we fallback by breaking
1361     // the request down into several, smaller, integers.
1362     // Since sizes greater or equal to "Size" are invalid, we use the greatest
1363     // power of 2 that is less than "Size" as our largest piece of granularity.
1364     bool IsLittleEndian = MAI->isLittleEndian();
1365     for (unsigned Emitted = 0; Emitted != Size;) {
1366       unsigned Remaining = Size - Emitted;
1367       // The size of our partial emission must be a power of two less than
1368       // Size.
1369       unsigned EmissionSize = llvm::bit_floor(std::min(Remaining, Size - 1));
1370       // Calculate the byte offset of our partial emission taking into account
1371       // the endianness of the target.
1372       unsigned ByteOffset =
1373           IsLittleEndian ? Emitted : (Remaining - EmissionSize);
1374       uint64_t ValueToEmit = IntValue >> (ByteOffset * 8);
1375       // We truncate our partial emission to fit within the bounds of the
1376       // emission domain.  This produces nicer output and silences potential
1377       // truncation warnings when round tripping through another assembler.
1378       uint64_t Shift = 64 - EmissionSize * 8;
1379       assert(Shift < static_cast<uint64_t>(
1380                          std::numeric_limits<unsigned long long>::digits) &&
1381              "undefined behavior");
1382       ValueToEmit &= ~0ULL >> Shift;
1383       emitIntValue(ValueToEmit, EmissionSize);
1384       Emitted += EmissionSize;
1385     }
1386     return;
1387   }
1388 
1389   assert(Directive && "Invalid size for machine code value!");
1390   OS << Directive;
1391   if (MCTargetStreamer *TS = getTargetStreamer()) {
1392     TS->emitValue(Value);
1393   } else {
1394     MAI->printExpr(OS, *Value);
1395     EmitEOL();
1396   }
1397 }
1398 
emitULEB128Value(const MCExpr * Value)1399 void MCAsmStreamer::emitULEB128Value(const MCExpr *Value) {
1400   int64_t IntValue;
1401   if (Value->evaluateAsAbsolute(IntValue)) {
1402     emitULEB128IntValue(IntValue);
1403     return;
1404   }
1405   OS << "\t.uleb128 ";
1406   MAI->printExpr(OS, *Value);
1407   EmitEOL();
1408 }
1409 
emitSLEB128Value(const MCExpr * Value)1410 void MCAsmStreamer::emitSLEB128Value(const MCExpr *Value) {
1411   int64_t IntValue;
1412   if (Value->evaluateAsAbsolute(IntValue)) {
1413     emitSLEB128IntValue(IntValue);
1414     return;
1415   }
1416   OS << "\t.sleb128 ";
1417   MAI->printExpr(OS, *Value);
1418   EmitEOL();
1419 }
1420 
emitFill(const MCExpr & NumBytes,uint64_t FillValue,SMLoc Loc)1421 void MCAsmStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
1422                              SMLoc Loc) {
1423   int64_t IntNumBytes;
1424   const bool IsAbsolute = NumBytes.evaluateAsAbsolute(IntNumBytes);
1425   if (IsAbsolute && IntNumBytes == 0)
1426     return;
1427 
1428   if (const char *ZeroDirective = MAI->getZeroDirective()) {
1429     if (!MAI->isAIX() || FillValue == 0) {
1430       // FIXME: Emit location directives
1431       OS << ZeroDirective;
1432       MAI->printExpr(OS, NumBytes);
1433       if (FillValue != 0)
1434         OS << ',' << (int)FillValue;
1435       EmitEOL();
1436     } else {
1437       if (!IsAbsolute)
1438         report_fatal_error(
1439             "Cannot emit non-absolute expression lengths of fill.");
1440       for (int i = 0; i < IntNumBytes; ++i) {
1441         OS << MAI->getData8bitsDirective() << (int)FillValue;
1442         EmitEOL();
1443       }
1444     }
1445     return;
1446   }
1447 
1448   MCStreamer::emitFill(NumBytes, FillValue);
1449 }
1450 
emitFill(const MCExpr & NumValues,int64_t Size,int64_t Expr,SMLoc Loc)1451 void MCAsmStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
1452                              int64_t Expr, SMLoc Loc) {
1453   // FIXME: Emit location directives
1454   OS << "\t.fill\t";
1455   MAI->printExpr(OS, NumValues);
1456   OS << ", " << Size << ", 0x";
1457   OS.write_hex(truncateToSize(Expr, 4));
1458   EmitEOL();
1459 }
1460 
emitAlignmentDirective(uint64_t ByteAlignment,std::optional<int64_t> Value,unsigned ValueSize,unsigned MaxBytesToEmit)1461 void MCAsmStreamer::emitAlignmentDirective(uint64_t ByteAlignment,
1462                                            std::optional<int64_t> Value,
1463                                            unsigned ValueSize,
1464                                            unsigned MaxBytesToEmit) {
1465   if (MAI->isAIX()) {
1466     if (!isPowerOf2_64(ByteAlignment))
1467       report_fatal_error("Only power-of-two alignments are supported "
1468                          "with .align.");
1469     OS << "\t.align\t";
1470     OS << Log2_64(ByteAlignment);
1471     EmitEOL();
1472     return;
1473   }
1474 
1475   // Some assemblers don't support non-power of two alignments, so we always
1476   // emit alignments as a power of two if possible.
1477   if (isPowerOf2_64(ByteAlignment)) {
1478     switch (ValueSize) {
1479     default:
1480       llvm_unreachable("Invalid size for machine code value!");
1481     case 1:
1482       OS << "\t.p2align\t";
1483       break;
1484     case 2:
1485       OS << ".p2alignw ";
1486       break;
1487     case 4:
1488       OS << ".p2alignl ";
1489       break;
1490     case 8:
1491       llvm_unreachable("Unsupported alignment size!");
1492     }
1493 
1494     OS << Log2_64(ByteAlignment);
1495 
1496     if (Value.has_value() || MaxBytesToEmit) {
1497       if (Value.has_value()) {
1498         OS << ", 0x";
1499         OS.write_hex(truncateToSize(*Value, ValueSize));
1500       } else {
1501         OS << ", ";
1502       }
1503 
1504       if (MaxBytesToEmit)
1505         OS << ", " << MaxBytesToEmit;
1506     }
1507     EmitEOL();
1508     return;
1509   }
1510 
1511   // Non-power of two alignment.  This is not widely supported by assemblers.
1512   // FIXME: Parameterize this based on MAI.
1513   switch (ValueSize) {
1514   default: llvm_unreachable("Invalid size for machine code value!");
1515   case 1: OS << ".balign";  break;
1516   case 2: OS << ".balignw"; break;
1517   case 4: OS << ".balignl"; break;
1518   case 8: llvm_unreachable("Unsupported alignment size!");
1519   }
1520 
1521   OS << ' ' << ByteAlignment;
1522   if (Value.has_value())
1523     OS << ", " << truncateToSize(*Value, ValueSize);
1524   else if (MaxBytesToEmit)
1525     OS << ", ";
1526   if (MaxBytesToEmit)
1527     OS << ", " << MaxBytesToEmit;
1528   EmitEOL();
1529 }
1530 
emitValueToAlignment(Align Alignment,int64_t Fill,uint8_t FillLen,unsigned MaxBytesToEmit)1531 void MCAsmStreamer::emitValueToAlignment(Align Alignment, int64_t Fill,
1532                                          uint8_t FillLen,
1533                                          unsigned MaxBytesToEmit) {
1534   emitAlignmentDirective(Alignment.value(), Fill, FillLen, MaxBytesToEmit);
1535 }
1536 
emitCodeAlignment(Align Alignment,const MCSubtargetInfo * STI,unsigned MaxBytesToEmit)1537 void MCAsmStreamer::emitCodeAlignment(Align Alignment,
1538                                       const MCSubtargetInfo *STI,
1539                                       unsigned MaxBytesToEmit) {
1540   // Emit with a text fill value.
1541   if (MAI->getTextAlignFillValue())
1542     emitAlignmentDirective(Alignment.value(), MAI->getTextAlignFillValue(), 1,
1543                            MaxBytesToEmit);
1544   else
1545     emitAlignmentDirective(Alignment.value(), std::nullopt, 1, MaxBytesToEmit);
1546 }
1547 
emitValueToOffset(const MCExpr * Offset,unsigned char Value,SMLoc Loc)1548 void MCAsmStreamer::emitValueToOffset(const MCExpr *Offset,
1549                                       unsigned char Value,
1550                                       SMLoc Loc) {
1551   // FIXME: Verify that Offset is associated with the current section.
1552   OS << ".org ";
1553   MAI->printExpr(OS, *Offset);
1554   OS << ", " << (unsigned)Value;
1555   EmitEOL();
1556 }
1557 
emitFileDirective(StringRef Filename)1558 void MCAsmStreamer::emitFileDirective(StringRef Filename) {
1559   assert(MAI->hasSingleParameterDotFile());
1560   OS << "\t.file\t";
1561   PrintQuotedString(Filename, OS);
1562   EmitEOL();
1563 }
1564 
emitFileDirective(StringRef Filename,StringRef CompilerVersion,StringRef TimeStamp,StringRef Description)1565 void MCAsmStreamer::emitFileDirective(StringRef Filename,
1566                                       StringRef CompilerVersion,
1567                                       StringRef TimeStamp,
1568                                       StringRef Description) {
1569   assert(MAI->isAIX());
1570   OS << "\t.file\t";
1571   PrintQuotedString(Filename, OS);
1572   bool useTimeStamp = !TimeStamp.empty();
1573   bool useCompilerVersion = !CompilerVersion.empty();
1574   bool useDescription = !Description.empty();
1575   if (useTimeStamp || useCompilerVersion || useDescription) {
1576     OS << ",";
1577     if (useTimeStamp)
1578       PrintQuotedString(TimeStamp, OS);
1579     if (useCompilerVersion || useDescription) {
1580       OS << ",";
1581       if (useCompilerVersion)
1582         PrintQuotedString(CompilerVersion, OS);
1583       if (useDescription) {
1584         OS << ",";
1585         PrintQuotedString(Description, OS);
1586       }
1587     }
1588   }
1589   EmitEOL();
1590 }
1591 
printDwarfFileDirective(unsigned FileNo,StringRef Directory,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,bool UseDwarfDirectory,raw_svector_ostream & OS) const1592 void MCAsmStreamer::printDwarfFileDirective(
1593     unsigned FileNo, StringRef Directory, StringRef Filename,
1594     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1595     bool UseDwarfDirectory, raw_svector_ostream &OS) const {
1596   SmallString<128> FullPathName;
1597 
1598   if (!UseDwarfDirectory && !Directory.empty()) {
1599     if (sys::path::is_absolute(Filename))
1600       Directory = "";
1601     else {
1602       FullPathName = Directory;
1603       sys::path::append(FullPathName, Filename);
1604       Directory = "";
1605       Filename = FullPathName;
1606     }
1607   }
1608 
1609   OS << "\t.file\t" << FileNo << ' ';
1610   if (!Directory.empty()) {
1611     PrintQuotedString(Directory, OS);
1612     OS << ' ';
1613   }
1614   PrintQuotedString(Filename, OS);
1615   if (Checksum)
1616     OS << " md5 0x" << Checksum->digest();
1617   if (Source) {
1618     OS << " source ";
1619     PrintQuotedString(*Source, OS);
1620   }
1621 }
1622 
tryEmitDwarfFileDirective(unsigned FileNo,StringRef Directory,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,unsigned CUID)1623 Expected<unsigned> MCAsmStreamer::tryEmitDwarfFileDirective(
1624     unsigned FileNo, StringRef Directory, StringRef Filename,
1625     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1626     unsigned CUID) {
1627   assert(CUID == 0 && "multiple CUs not supported by MCAsmStreamer");
1628 
1629   MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
1630   unsigned NumFiles = Table.getMCDwarfFiles().size();
1631   Expected<unsigned> FileNoOrErr =
1632       Table.tryGetFile(Directory, Filename, Checksum, Source,
1633                        getContext().getDwarfVersion(), FileNo);
1634   if (!FileNoOrErr)
1635     return FileNoOrErr.takeError();
1636   FileNo = FileNoOrErr.get();
1637 
1638   // Return early if this file is already emitted before or if target doesn't
1639   // support .file directive.
1640   if (NumFiles == Table.getMCDwarfFiles().size() || MAI->isAIX())
1641     return FileNo;
1642 
1643   SmallString<128> Str;
1644   raw_svector_ostream OS1(Str);
1645   printDwarfFileDirective(FileNo, Directory, Filename, Checksum, Source,
1646                           UseDwarfDirectory, OS1);
1647 
1648   if (MCTargetStreamer *TS = getTargetStreamer())
1649     TS->emitDwarfFileDirective(OS1.str());
1650   else
1651     emitRawText(OS1.str());
1652 
1653   return FileNo;
1654 }
1655 
emitDwarfFile0Directive(StringRef Directory,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,unsigned CUID)1656 void MCAsmStreamer::emitDwarfFile0Directive(
1657     StringRef Directory, StringRef Filename,
1658     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1659     unsigned CUID) {
1660   assert(CUID == 0);
1661   // .file 0 is new for DWARF v5.
1662   if (getContext().getDwarfVersion() < 5)
1663     return;
1664   // Inform MCDwarf about the root file.
1665   getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
1666                                       Source);
1667 
1668   // Target doesn't support .loc/.file directives, return early.
1669   if (MAI->isAIX())
1670     return;
1671 
1672   SmallString<128> Str;
1673   raw_svector_ostream OS1(Str);
1674   printDwarfFileDirective(0, Directory, Filename, Checksum, Source,
1675                           UseDwarfDirectory, OS1);
1676 
1677   if (MCTargetStreamer *TS = getTargetStreamer())
1678     TS->emitDwarfFileDirective(OS1.str());
1679   else
1680     emitRawText(OS1.str());
1681 }
1682 
emitDwarfLocDirective(unsigned FileNo,unsigned Line,unsigned Column,unsigned Flags,unsigned Isa,unsigned Discriminator,StringRef FileName,StringRef Comment)1683 void MCAsmStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
1684                                           unsigned Column, unsigned Flags,
1685                                           unsigned Isa, unsigned Discriminator,
1686                                           StringRef FileName,
1687                                           StringRef Comment) {
1688   // If target doesn't support .loc/.file directive, we need to record the lines
1689   // same way like we do in object mode.
1690   if (MAI->isAIX()) {
1691     // In case we see two .loc directives in a row, make sure the
1692     // first one gets a line entry.
1693     MCDwarfLineEntry::make(this, getCurrentSectionOnly());
1694     this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
1695                                             Discriminator, FileName, Comment);
1696     return;
1697   }
1698 
1699   OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
1700   if (MAI->supportsExtendedDwarfLocDirective()) {
1701     if (Flags & DWARF2_FLAG_BASIC_BLOCK)
1702       OS << " basic_block";
1703     if (Flags & DWARF2_FLAG_PROLOGUE_END)
1704       OS << " prologue_end";
1705     if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
1706       OS << " epilogue_begin";
1707 
1708     unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
1709     if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
1710       OS << " is_stmt ";
1711 
1712       if (Flags & DWARF2_FLAG_IS_STMT)
1713         OS << "1";
1714       else
1715         OS << "0";
1716     }
1717 
1718     if (Isa)
1719       OS << " isa " << Isa;
1720     if (Discriminator)
1721       OS << " discriminator " << Discriminator;
1722   }
1723 
1724   if (IsVerboseAsm) {
1725     OS.PadToColumn(MAI->getCommentColumn());
1726     OS << MAI->getCommentString() << ' ';
1727     if (Comment.empty())
1728       OS << FileName << ':' << Line << ':' << Column;
1729     else
1730       OS << Comment;
1731   }
1732   EmitEOL();
1733   this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
1734                                           Discriminator, FileName, Comment);
1735 }
1736 
emitDwarfLocLabelDirective(SMLoc Loc,StringRef Name)1737 void MCAsmStreamer::emitDwarfLocLabelDirective(SMLoc Loc, StringRef Name) {
1738   MCStreamer::emitDwarfLocLabelDirective(Loc, Name);
1739   OS << ".loc_label\t" << Name;
1740   EmitEOL();
1741 }
1742 
getDwarfLineTableSymbol(unsigned CUID)1743 MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) {
1744   // Always use the zeroth line table, since asm syntax only supports one line
1745   // table for now.
1746   return MCStreamer::getDwarfLineTableSymbol(0);
1747 }
1748 
emitCVFileDirective(unsigned FileNo,StringRef Filename,ArrayRef<uint8_t> Checksum,unsigned ChecksumKind)1749 bool MCAsmStreamer::emitCVFileDirective(unsigned FileNo, StringRef Filename,
1750                                         ArrayRef<uint8_t> Checksum,
1751                                         unsigned ChecksumKind) {
1752   if (!getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
1753                                            ChecksumKind))
1754     return false;
1755 
1756   OS << "\t.cv_file\t" << FileNo << ' ';
1757   PrintQuotedString(Filename, OS);
1758 
1759   if (!ChecksumKind) {
1760     EmitEOL();
1761     return true;
1762   }
1763 
1764   OS << ' ';
1765   PrintQuotedString(toHex(Checksum), OS);
1766   OS << ' ' << ChecksumKind;
1767 
1768   EmitEOL();
1769   return true;
1770 }
1771 
emitCVFuncIdDirective(unsigned FuncId)1772 bool MCAsmStreamer::emitCVFuncIdDirective(unsigned FuncId) {
1773   OS << "\t.cv_func_id " << FuncId << '\n';
1774   return MCStreamer::emitCVFuncIdDirective(FuncId);
1775 }
1776 
emitCVInlineSiteIdDirective(unsigned FunctionId,unsigned IAFunc,unsigned IAFile,unsigned IALine,unsigned IACol,SMLoc Loc)1777 bool MCAsmStreamer::emitCVInlineSiteIdDirective(unsigned FunctionId,
1778                                                 unsigned IAFunc,
1779                                                 unsigned IAFile,
1780                                                 unsigned IALine, unsigned IACol,
1781                                                 SMLoc Loc) {
1782   OS << "\t.cv_inline_site_id " << FunctionId << " within " << IAFunc
1783      << " inlined_at " << IAFile << ' ' << IALine << ' ' << IACol << '\n';
1784   return MCStreamer::emitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
1785                                                  IALine, IACol, Loc);
1786 }
1787 
emitCVLocDirective(unsigned FunctionId,unsigned FileNo,unsigned Line,unsigned Column,bool PrologueEnd,bool IsStmt,StringRef FileName,SMLoc Loc)1788 void MCAsmStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
1789                                        unsigned Line, unsigned Column,
1790                                        bool PrologueEnd, bool IsStmt,
1791                                        StringRef FileName, SMLoc Loc) {
1792   // Validate the directive.
1793   if (!checkCVLocSection(FunctionId, FileNo, Loc))
1794     return;
1795 
1796   OS << "\t.cv_loc\t" << FunctionId << " " << FileNo << " " << Line << " "
1797      << Column;
1798   if (PrologueEnd)
1799     OS << " prologue_end";
1800 
1801   if (IsStmt)
1802     OS << " is_stmt 1";
1803 
1804   if (IsVerboseAsm) {
1805     OS.PadToColumn(MAI->getCommentColumn());
1806     OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':'
1807        << Column;
1808   }
1809   EmitEOL();
1810 }
1811 
emitCVLinetableDirective(unsigned FunctionId,const MCSymbol * FnStart,const MCSymbol * FnEnd)1812 void MCAsmStreamer::emitCVLinetableDirective(unsigned FunctionId,
1813                                              const MCSymbol *FnStart,
1814                                              const MCSymbol *FnEnd) {
1815   OS << "\t.cv_linetable\t" << FunctionId << ", ";
1816   FnStart->print(OS, MAI);
1817   OS << ", ";
1818   FnEnd->print(OS, MAI);
1819   EmitEOL();
1820   this->MCStreamer::emitCVLinetableDirective(FunctionId, FnStart, FnEnd);
1821 }
1822 
emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,unsigned SourceFileId,unsigned SourceLineNum,const MCSymbol * FnStartSym,const MCSymbol * FnEndSym)1823 void MCAsmStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
1824                                                    unsigned SourceFileId,
1825                                                    unsigned SourceLineNum,
1826                                                    const MCSymbol *FnStartSym,
1827                                                    const MCSymbol *FnEndSym) {
1828   OS << "\t.cv_inline_linetable\t" << PrimaryFunctionId << ' ' << SourceFileId
1829      << ' ' << SourceLineNum << ' ';
1830   FnStartSym->print(OS, MAI);
1831   OS << ' ';
1832   FnEndSym->print(OS, MAI);
1833   EmitEOL();
1834   this->MCStreamer::emitCVInlineLinetableDirective(
1835       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
1836 }
1837 
PrintCVDefRangePrefix(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges)1838 void MCAsmStreamer::PrintCVDefRangePrefix(
1839     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges) {
1840   OS << "\t.cv_def_range\t";
1841   for (std::pair<const MCSymbol *, const MCSymbol *> Range : Ranges) {
1842     OS << ' ';
1843     Range.first->print(OS, MAI);
1844     OS << ' ';
1845     Range.second->print(OS, MAI);
1846   }
1847 }
1848 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeRegisterRelHeader DRHdr)1849 void MCAsmStreamer::emitCVDefRangeDirective(
1850     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1851     codeview::DefRangeRegisterRelHeader DRHdr) {
1852   PrintCVDefRangePrefix(Ranges);
1853   OS << ", reg_rel, ";
1854   OS << DRHdr.Register << ", " << DRHdr.Flags << ", "
1855      << DRHdr.BasePointerOffset;
1856   EmitEOL();
1857 }
1858 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeSubfieldRegisterHeader DRHdr)1859 void MCAsmStreamer::emitCVDefRangeDirective(
1860     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1861     codeview::DefRangeSubfieldRegisterHeader DRHdr) {
1862   PrintCVDefRangePrefix(Ranges);
1863   OS << ", subfield_reg, ";
1864   OS << DRHdr.Register << ", " << DRHdr.OffsetInParent;
1865   EmitEOL();
1866 }
1867 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeRegisterHeader DRHdr)1868 void MCAsmStreamer::emitCVDefRangeDirective(
1869     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1870     codeview::DefRangeRegisterHeader DRHdr) {
1871   PrintCVDefRangePrefix(Ranges);
1872   OS << ", reg, ";
1873   OS << DRHdr.Register;
1874   EmitEOL();
1875 }
1876 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeFramePointerRelHeader DRHdr)1877 void MCAsmStreamer::emitCVDefRangeDirective(
1878     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
1879     codeview::DefRangeFramePointerRelHeader DRHdr) {
1880   PrintCVDefRangePrefix(Ranges);
1881   OS << ", frame_ptr_rel, ";
1882   OS << DRHdr.Offset;
1883   EmitEOL();
1884 }
1885 
emitCVStringTableDirective()1886 void MCAsmStreamer::emitCVStringTableDirective() {
1887   OS << "\t.cv_stringtable";
1888   EmitEOL();
1889 }
1890 
emitCVFileChecksumsDirective()1891 void MCAsmStreamer::emitCVFileChecksumsDirective() {
1892   OS << "\t.cv_filechecksums";
1893   EmitEOL();
1894 }
1895 
emitCVFileChecksumOffsetDirective(unsigned FileNo)1896 void MCAsmStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
1897   OS << "\t.cv_filechecksumoffset\t" << FileNo;
1898   EmitEOL();
1899 }
1900 
emitCVFPOData(const MCSymbol * ProcSym,SMLoc L)1901 void MCAsmStreamer::emitCVFPOData(const MCSymbol *ProcSym, SMLoc L) {
1902   OS << "\t.cv_fpo_data\t";
1903   ProcSym->print(OS, MAI);
1904   EmitEOL();
1905 }
1906 
emitIdent(StringRef IdentString)1907 void MCAsmStreamer::emitIdent(StringRef IdentString) {
1908   assert(MAI->hasIdentDirective() && ".ident directive not supported");
1909   OS << "\t.ident\t";
1910   PrintQuotedString(IdentString, OS);
1911   EmitEOL();
1912 }
1913 
emitCFISections(bool EH,bool Debug)1914 void MCAsmStreamer::emitCFISections(bool EH, bool Debug) {
1915   MCStreamer::emitCFISections(EH, Debug);
1916   OS << "\t.cfi_sections ";
1917   if (EH) {
1918     OS << ".eh_frame";
1919     if (Debug)
1920       OS << ", .debug_frame";
1921   } else if (Debug) {
1922     OS << ".debug_frame";
1923   }
1924 
1925   EmitEOL();
1926 }
1927 
emitCFIStartProcImpl(MCDwarfFrameInfo & Frame)1928 void MCAsmStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
1929   OS << "\t.cfi_startproc";
1930   if (Frame.IsSimple)
1931     OS << " simple";
1932   EmitEOL();
1933 }
1934 
emitCFIEndProcImpl(MCDwarfFrameInfo & Frame)1935 void MCAsmStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
1936   MCStreamer::emitCFIEndProcImpl(Frame);
1937   OS << "\t.cfi_endproc";
1938   EmitEOL();
1939 }
1940 
EmitRegisterName(int64_t Register)1941 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
1942   if (!MAI->useDwarfRegNumForCFI()) {
1943     // User .cfi_* directives can use arbitrary DWARF register numbers, not
1944     // just ones that map to LLVM register numbers and have known names.
1945     // Fall back to using the original number directly if no name is known.
1946     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1947     if (std::optional<MCRegister> LLVMRegister =
1948             MRI->getLLVMRegNum(Register, true)) {
1949       InstPrinter->printRegName(OS, *LLVMRegister);
1950       return;
1951     }
1952   }
1953   OS << Register;
1954 }
1955 
emitCFIDefCfa(int64_t Register,int64_t Offset,SMLoc Loc)1956 void MCAsmStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset, SMLoc Loc) {
1957   MCStreamer::emitCFIDefCfa(Register, Offset, Loc);
1958   OS << "\t.cfi_def_cfa ";
1959   EmitRegisterName(Register);
1960   OS << ", " << Offset;
1961   EmitEOL();
1962 }
1963 
emitCFIDefCfaOffset(int64_t Offset,SMLoc Loc)1964 void MCAsmStreamer::emitCFIDefCfaOffset(int64_t Offset, SMLoc Loc) {
1965   MCStreamer::emitCFIDefCfaOffset(Offset, Loc);
1966   OS << "\t.cfi_def_cfa_offset " << Offset;
1967   EmitEOL();
1968 }
1969 
emitCFILLVMDefAspaceCfa(int64_t Register,int64_t Offset,int64_t AddressSpace,SMLoc Loc)1970 void MCAsmStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
1971                                             int64_t AddressSpace, SMLoc Loc) {
1972   MCStreamer::emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace, Loc);
1973   OS << "\t.cfi_llvm_def_aspace_cfa ";
1974   EmitRegisterName(Register);
1975   OS << ", " << Offset;
1976   OS << ", " << AddressSpace;
1977   EmitEOL();
1978 }
1979 
PrintCFIEscape(llvm::formatted_raw_ostream & OS,StringRef Values)1980 static void PrintCFIEscape(llvm::formatted_raw_ostream &OS, StringRef Values) {
1981   OS << "\t.cfi_escape ";
1982   if (!Values.empty()) {
1983     size_t e = Values.size() - 1;
1984     for (size_t i = 0; i < e; ++i)
1985       OS << format("0x%02x", uint8_t(Values[i])) << ", ";
1986     OS << format("0x%02x", uint8_t(Values[e]));
1987   }
1988 }
1989 
emitCFIEscape(StringRef Values,SMLoc Loc)1990 void MCAsmStreamer::emitCFIEscape(StringRef Values, SMLoc Loc) {
1991   MCStreamer::emitCFIEscape(Values, Loc);
1992   PrintCFIEscape(OS, Values);
1993   EmitEOL();
1994 }
1995 
emitCFIGnuArgsSize(int64_t Size,SMLoc Loc)1996 void MCAsmStreamer::emitCFIGnuArgsSize(int64_t Size, SMLoc Loc) {
1997   MCStreamer::emitCFIGnuArgsSize(Size, Loc);
1998 
1999   uint8_t Buffer[16] = { dwarf::DW_CFA_GNU_args_size };
2000   unsigned Len = encodeULEB128(Size, Buffer + 1) + 1;
2001 
2002   PrintCFIEscape(OS, StringRef((const char *)&Buffer[0], Len));
2003   EmitEOL();
2004 }
2005 
emitCFIDefCfaRegister(int64_t Register,SMLoc Loc)2006 void MCAsmStreamer::emitCFIDefCfaRegister(int64_t Register, SMLoc Loc) {
2007   MCStreamer::emitCFIDefCfaRegister(Register, Loc);
2008   OS << "\t.cfi_def_cfa_register ";
2009   EmitRegisterName(Register);
2010   EmitEOL();
2011 }
2012 
emitCFIOffset(int64_t Register,int64_t Offset,SMLoc Loc)2013 void MCAsmStreamer::emitCFIOffset(int64_t Register, int64_t Offset, SMLoc Loc) {
2014   MCStreamer::emitCFIOffset(Register, Offset, Loc);
2015   OS << "\t.cfi_offset ";
2016   EmitRegisterName(Register);
2017   OS << ", " << Offset;
2018   EmitEOL();
2019 }
2020 
emitCFIPersonality(const MCSymbol * Sym,unsigned Encoding)2021 void MCAsmStreamer::emitCFIPersonality(const MCSymbol *Sym,
2022                                        unsigned Encoding) {
2023   MCStreamer::emitCFIPersonality(Sym, Encoding);
2024   OS << "\t.cfi_personality " << Encoding << ", ";
2025   Sym->print(OS, MAI);
2026   EmitEOL();
2027 }
2028 
emitCFILsda(const MCSymbol * Sym,unsigned Encoding)2029 void MCAsmStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
2030   MCStreamer::emitCFILsda(Sym, Encoding);
2031   OS << "\t.cfi_lsda " << Encoding << ", ";
2032   Sym->print(OS, MAI);
2033   EmitEOL();
2034 }
2035 
emitCFIRememberState(SMLoc Loc)2036 void MCAsmStreamer::emitCFIRememberState(SMLoc Loc) {
2037   MCStreamer::emitCFIRememberState(Loc);
2038   OS << "\t.cfi_remember_state";
2039   EmitEOL();
2040 }
2041 
emitCFIRestoreState(SMLoc Loc)2042 void MCAsmStreamer::emitCFIRestoreState(SMLoc Loc) {
2043   MCStreamer::emitCFIRestoreState(Loc);
2044   OS << "\t.cfi_restore_state";
2045   EmitEOL();
2046 }
2047 
emitCFIRestore(int64_t Register,SMLoc Loc)2048 void MCAsmStreamer::emitCFIRestore(int64_t Register, SMLoc Loc) {
2049   MCStreamer::emitCFIRestore(Register, Loc);
2050   OS << "\t.cfi_restore ";
2051   EmitRegisterName(Register);
2052   EmitEOL();
2053 }
2054 
emitCFISameValue(int64_t Register,SMLoc Loc)2055 void MCAsmStreamer::emitCFISameValue(int64_t Register, SMLoc Loc) {
2056   MCStreamer::emitCFISameValue(Register, Loc);
2057   OS << "\t.cfi_same_value ";
2058   EmitRegisterName(Register);
2059   EmitEOL();
2060 }
2061 
emitCFIRelOffset(int64_t Register,int64_t Offset,SMLoc Loc)2062 void MCAsmStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset,
2063                                      SMLoc Loc) {
2064   MCStreamer::emitCFIRelOffset(Register, Offset, Loc);
2065   OS << "\t.cfi_rel_offset ";
2066   EmitRegisterName(Register);
2067   OS << ", " << Offset;
2068   EmitEOL();
2069 }
2070 
emitCFIAdjustCfaOffset(int64_t Adjustment,SMLoc Loc)2071 void MCAsmStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment, SMLoc Loc) {
2072   MCStreamer::emitCFIAdjustCfaOffset(Adjustment, Loc);
2073   OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
2074   EmitEOL();
2075 }
2076 
emitCFISignalFrame()2077 void MCAsmStreamer::emitCFISignalFrame() {
2078   MCStreamer::emitCFISignalFrame();
2079   OS << "\t.cfi_signal_frame";
2080   EmitEOL();
2081 }
2082 
emitCFIUndefined(int64_t Register,SMLoc Loc)2083 void MCAsmStreamer::emitCFIUndefined(int64_t Register, SMLoc Loc) {
2084   MCStreamer::emitCFIUndefined(Register, Loc);
2085   OS << "\t.cfi_undefined ";
2086   EmitRegisterName(Register);
2087   EmitEOL();
2088 }
2089 
emitCFIRegister(int64_t Register1,int64_t Register2,SMLoc Loc)2090 void MCAsmStreamer::emitCFIRegister(int64_t Register1, int64_t Register2,
2091                                     SMLoc Loc) {
2092   MCStreamer::emitCFIRegister(Register1, Register2, Loc);
2093   OS << "\t.cfi_register ";
2094   EmitRegisterName(Register1);
2095   OS << ", ";
2096   EmitRegisterName(Register2);
2097   EmitEOL();
2098 }
2099 
emitCFIWindowSave(SMLoc Loc)2100 void MCAsmStreamer::emitCFIWindowSave(SMLoc Loc) {
2101   MCStreamer::emitCFIWindowSave(Loc);
2102   OS << "\t.cfi_window_save";
2103   EmitEOL();
2104 }
2105 
emitCFINegateRAState(SMLoc Loc)2106 void MCAsmStreamer::emitCFINegateRAState(SMLoc Loc) {
2107   MCStreamer::emitCFINegateRAState(Loc);
2108   OS << "\t.cfi_negate_ra_state";
2109   EmitEOL();
2110 }
2111 
emitCFINegateRAStateWithPC(SMLoc Loc)2112 void MCAsmStreamer::emitCFINegateRAStateWithPC(SMLoc Loc) {
2113   MCStreamer::emitCFINegateRAStateWithPC(Loc);
2114   OS << "\t.cfi_negate_ra_state_with_pc";
2115   EmitEOL();
2116 }
2117 
emitCFIReturnColumn(int64_t Register)2118 void MCAsmStreamer::emitCFIReturnColumn(int64_t Register) {
2119   MCStreamer::emitCFIReturnColumn(Register);
2120   OS << "\t.cfi_return_column ";
2121   EmitRegisterName(Register);
2122   EmitEOL();
2123 }
2124 
emitCFILabelDirective(SMLoc Loc,StringRef Name)2125 void MCAsmStreamer::emitCFILabelDirective(SMLoc Loc, StringRef Name) {
2126   MCStreamer::emitCFILabelDirective(Loc, Name);
2127   OS << "\t.cfi_label " << Name;
2128   EmitEOL();
2129 }
2130 
emitCFIBKeyFrame()2131 void MCAsmStreamer::emitCFIBKeyFrame() {
2132   MCStreamer::emitCFIBKeyFrame();
2133   OS << "\t.cfi_b_key_frame";
2134   EmitEOL();
2135 }
2136 
emitCFIMTETaggedFrame()2137 void MCAsmStreamer::emitCFIMTETaggedFrame() {
2138   MCStreamer::emitCFIMTETaggedFrame();
2139   OS << "\t.cfi_mte_tagged_frame";
2140   EmitEOL();
2141 }
2142 
emitCFIValOffset(int64_t Register,int64_t Offset,SMLoc Loc)2143 void MCAsmStreamer::emitCFIValOffset(int64_t Register, int64_t Offset,
2144                                      SMLoc Loc) {
2145   MCStreamer::emitCFIValOffset(Register, Offset, Loc);
2146   OS << "\t.cfi_val_offset ";
2147   EmitRegisterName(Register);
2148   OS << ", " << Offset;
2149   EmitEOL();
2150 }
2151 
emitWinCFIStartProc(const MCSymbol * Symbol,SMLoc Loc)2152 void MCAsmStreamer::emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
2153   MCStreamer::emitWinCFIStartProc(Symbol, Loc);
2154 
2155   OS << ".seh_proc ";
2156   Symbol->print(OS, MAI);
2157   EmitEOL();
2158 }
2159 
emitWinCFIEndProc(SMLoc Loc)2160 void MCAsmStreamer::emitWinCFIEndProc(SMLoc Loc) {
2161   MCStreamer::emitWinCFIEndProc(Loc);
2162 
2163   OS << "\t.seh_endproc";
2164   EmitEOL();
2165 }
2166 
emitWinCFIFuncletOrFuncEnd(SMLoc Loc)2167 void MCAsmStreamer::emitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
2168   MCStreamer::emitWinCFIFuncletOrFuncEnd(Loc);
2169 
2170   OS << "\t.seh_endfunclet";
2171   EmitEOL();
2172 }
2173 
emitWinCFIStartChained(SMLoc Loc)2174 void MCAsmStreamer::emitWinCFIStartChained(SMLoc Loc) {
2175   MCStreamer::emitWinCFIStartChained(Loc);
2176 
2177   OS << "\t.seh_startchained";
2178   EmitEOL();
2179 }
2180 
emitWinCFIEndChained(SMLoc Loc)2181 void MCAsmStreamer::emitWinCFIEndChained(SMLoc Loc) {
2182   MCStreamer::emitWinCFIEndChained(Loc);
2183 
2184   OS << "\t.seh_endchained";
2185   EmitEOL();
2186 }
2187 
emitWinEHHandler(const MCSymbol * Sym,bool Unwind,bool Except,SMLoc Loc)2188 void MCAsmStreamer::emitWinEHHandler(const MCSymbol *Sym, bool Unwind,
2189                                      bool Except, SMLoc Loc) {
2190   MCStreamer::emitWinEHHandler(Sym, Unwind, Except, Loc);
2191 
2192   OS << "\t.seh_handler ";
2193   Sym->print(OS, MAI);
2194   char Marker = '@';
2195   const Triple &T = getContext().getTargetTriple();
2196   if (T.getArch() == Triple::arm || T.getArch() == Triple::thumb)
2197     Marker = '%';
2198   if (Unwind)
2199     OS << ", " << Marker << "unwind";
2200   if (Except)
2201     OS << ", " << Marker << "except";
2202   EmitEOL();
2203 }
2204 
emitWinEHHandlerData(SMLoc Loc)2205 void MCAsmStreamer::emitWinEHHandlerData(SMLoc Loc) {
2206   MCStreamer::emitWinEHHandlerData(Loc);
2207 
2208   // Switch sections. Don't call switchSection directly, because that will
2209   // cause the section switch to be visible in the emitted assembly.
2210   // We only do this so the section switch that terminates the handler
2211   // data block is visible.
2212   WinEH::FrameInfo *CurFrame = getCurrentWinFrameInfo();
2213 
2214   // Do nothing if no frame is open. MCStreamer should've already reported an
2215   // error.
2216   if (!CurFrame)
2217     return;
2218 
2219   MCSection *TextSec = &CurFrame->Function->getSection();
2220   MCSection *XData = getAssociatedXDataSection(TextSec);
2221   switchSectionNoPrint(XData);
2222 
2223   OS << "\t.seh_handlerdata";
2224   EmitEOL();
2225 }
2226 
emitWinCFIPushReg(MCRegister Register,SMLoc Loc)2227 void MCAsmStreamer::emitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
2228   MCStreamer::emitWinCFIPushReg(Register, Loc);
2229 
2230   OS << "\t.seh_pushreg ";
2231   InstPrinter->printRegName(OS, Register);
2232   EmitEOL();
2233 }
2234 
emitWinCFISetFrame(MCRegister Register,unsigned Offset,SMLoc Loc)2235 void MCAsmStreamer::emitWinCFISetFrame(MCRegister Register, unsigned Offset,
2236                                        SMLoc Loc) {
2237   MCStreamer::emitWinCFISetFrame(Register, Offset, Loc);
2238 
2239   OS << "\t.seh_setframe ";
2240   InstPrinter->printRegName(OS, Register);
2241   OS << ", " << Offset;
2242   EmitEOL();
2243 }
2244 
emitWinCFIAllocStack(unsigned Size,SMLoc Loc)2245 void MCAsmStreamer::emitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
2246   MCStreamer::emitWinCFIAllocStack(Size, Loc);
2247 
2248   OS << "\t.seh_stackalloc " << Size;
2249   EmitEOL();
2250 }
2251 
emitWinCFISaveReg(MCRegister Register,unsigned Offset,SMLoc Loc)2252 void MCAsmStreamer::emitWinCFISaveReg(MCRegister Register, unsigned Offset,
2253                                       SMLoc Loc) {
2254   MCStreamer::emitWinCFISaveReg(Register, Offset, Loc);
2255 
2256   OS << "\t.seh_savereg ";
2257   InstPrinter->printRegName(OS, Register);
2258   OS << ", " << Offset;
2259   EmitEOL();
2260 }
2261 
emitWinCFISaveXMM(MCRegister Register,unsigned Offset,SMLoc Loc)2262 void MCAsmStreamer::emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
2263                                       SMLoc Loc) {
2264   MCStreamer::emitWinCFISaveXMM(Register, Offset, Loc);
2265 
2266   OS << "\t.seh_savexmm ";
2267   InstPrinter->printRegName(OS, Register);
2268   OS << ", " << Offset;
2269   EmitEOL();
2270 }
2271 
emitWinCFIPushFrame(bool Code,SMLoc Loc)2272 void MCAsmStreamer::emitWinCFIPushFrame(bool Code, SMLoc Loc) {
2273   MCStreamer::emitWinCFIPushFrame(Code, Loc);
2274 
2275   OS << "\t.seh_pushframe";
2276   if (Code)
2277     OS << " @code";
2278   EmitEOL();
2279 }
2280 
emitWinCFIEndProlog(SMLoc Loc)2281 void MCAsmStreamer::emitWinCFIEndProlog(SMLoc Loc) {
2282   MCStreamer::emitWinCFIEndProlog(Loc);
2283 
2284   OS << "\t.seh_endprologue";
2285   EmitEOL();
2286 }
2287 
emitWinCFIBeginEpilogue(SMLoc Loc)2288 void MCAsmStreamer::emitWinCFIBeginEpilogue(SMLoc Loc) {
2289   MCStreamer::emitWinCFIBeginEpilogue(Loc);
2290 
2291   OS << "\t.seh_startepilogue";
2292   EmitEOL();
2293 }
2294 
emitWinCFIEndEpilogue(SMLoc Loc)2295 void MCAsmStreamer::emitWinCFIEndEpilogue(SMLoc Loc) {
2296   MCStreamer::emitWinCFIEndEpilogue(Loc);
2297 
2298   OS << "\t.seh_endepilogue";
2299   EmitEOL();
2300 }
2301 
emitWinCFIUnwindV2Start(SMLoc Loc)2302 void MCAsmStreamer::emitWinCFIUnwindV2Start(SMLoc Loc) {
2303   MCStreamer::emitWinCFIUnwindV2Start(Loc);
2304 
2305   OS << "\t.seh_unwindv2start";
2306   EmitEOL();
2307 }
2308 
emitWinCFIUnwindVersion(uint8_t Version,SMLoc Loc)2309 void MCAsmStreamer::emitWinCFIUnwindVersion(uint8_t Version, SMLoc Loc) {
2310   MCStreamer::emitWinCFIUnwindVersion(Version, Loc);
2311 
2312   OS << "\t.seh_unwindversion " << (unsigned)Version;
2313   EmitEOL();
2314 }
2315 
emitCGProfileEntry(const MCSymbolRefExpr * From,const MCSymbolRefExpr * To,uint64_t Count)2316 void MCAsmStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
2317                                        const MCSymbolRefExpr *To,
2318                                        uint64_t Count) {
2319   OS << "\t.cg_profile ";
2320   From->getSymbol().print(OS, MAI);
2321   OS << ", ";
2322   To->getSymbol().print(OS, MAI);
2323   OS << ", " << Count;
2324   EmitEOL();
2325 }
2326 
AddEncodingComment(const MCInst & Inst,const MCSubtargetInfo & STI)2327 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
2328                                        const MCSubtargetInfo &STI) {
2329   raw_ostream &OS = getCommentOS();
2330   SmallString<256> Code;
2331   SmallVector<MCFixup, 4> Fixups;
2332 
2333   // If we have no code emitter, don't emit code.
2334   if (!getAssembler().getEmitterPtr())
2335     return;
2336 
2337   getAssembler().getEmitter().encodeInstruction(Inst, Code, Fixups, STI);
2338 
2339   // If we are showing fixups, create symbolic markers in the encoded
2340   // representation. We do this by making a per-bit map to the fixup item index,
2341   // then trying to display it as nicely as possible.
2342   SmallVector<uint8_t, 64> FixupMap;
2343   FixupMap.resize(Code.size() * 8);
2344   for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
2345     FixupMap[i] = 0;
2346 
2347   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
2348     MCFixup &F = Fixups[i];
2349     MCFixupKindInfo Info =
2350         getAssembler().getBackend().getFixupKindInfo(F.getKind());
2351     for (unsigned j = 0; j != Info.TargetSize; ++j) {
2352       unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
2353       assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
2354       FixupMap[Index] = 1 + i;
2355     }
2356   }
2357 
2358   // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
2359   // high order halfword of a 32-bit Thumb2 instruction is emitted first.
2360   OS << "encoding: [";
2361   for (unsigned i = 0, e = Code.size(); i != e; ++i) {
2362     if (i)
2363       OS << ',';
2364 
2365     // See if all bits are the same map entry.
2366     uint8_t MapEntry = FixupMap[i * 8 + 0];
2367     for (unsigned j = 1; j != 8; ++j) {
2368       if (FixupMap[i * 8 + j] == MapEntry)
2369         continue;
2370 
2371       MapEntry = uint8_t(~0U);
2372       break;
2373     }
2374 
2375     if (MapEntry != uint8_t(~0U)) {
2376       if (MapEntry == 0) {
2377         OS << format("0x%02x", uint8_t(Code[i]));
2378       } else {
2379         if (Code[i]) {
2380           // FIXME: Some of the 8 bits require fix up.
2381           OS << format("0x%02x", uint8_t(Code[i])) << '\''
2382              << char('A' + MapEntry - 1) << '\'';
2383         } else
2384           OS << char('A' + MapEntry - 1);
2385       }
2386     } else {
2387       // Otherwise, write out in binary.
2388       OS << "0b";
2389       for (unsigned j = 8; j--;) {
2390         unsigned Bit = (Code[i] >> j) & 1;
2391 
2392         unsigned FixupBit;
2393         if (MAI->isLittleEndian())
2394           FixupBit = i * 8 + j;
2395         else
2396           FixupBit = i * 8 + (7-j);
2397 
2398         if (uint8_t MapEntry = FixupMap[FixupBit]) {
2399           assert(Bit == 0 && "Encoder wrote into fixed up bit!");
2400           OS << char('A' + MapEntry - 1);
2401         } else
2402           OS << Bit;
2403       }
2404     }
2405   }
2406   OS << "]\n";
2407 
2408   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
2409     MCFixup &F = Fixups[i];
2410     OS << "  fixup " << char('A' + i) << " - "
2411        << "offset: " << F.getOffset() << ", value: ";
2412     MAI->printExpr(OS, *F.getValue());
2413     auto Kind = F.getKind();
2414     if (mc::isRelocation(Kind))
2415       OS << ", relocation type: " << Kind;
2416     else {
2417       OS << ", kind: ";
2418       auto Info = getAssembler().getBackend().getFixupKindInfo(Kind);
2419       if (F.isPCRel() && StringRef(Info.Name).starts_with("FK_Data_"))
2420         OS << "FK_PCRel_" << (Info.TargetSize / 8);
2421       else
2422         OS << Info.Name;
2423     }
2424     OS << '\n';
2425   }
2426 }
2427 
emitInstruction(const MCInst & Inst,const MCSubtargetInfo & STI)2428 void MCAsmStreamer::emitInstruction(const MCInst &Inst,
2429                                     const MCSubtargetInfo &STI) {
2430   if (MAI->isAIX() && CurFrag)
2431     // Now that a machine instruction has been assembled into this section, make
2432     // a line entry for any .loc directive that has been seen.
2433     MCDwarfLineEntry::make(this, getCurrentSectionOnly());
2434 
2435   // Show the encoding in a comment if we have a code emitter.
2436   AddEncodingComment(Inst, STI);
2437 
2438   // Show the MCInst if enabled.
2439   if (ShowInst) {
2440     Inst.dump_pretty(getCommentOS(), InstPrinter.get(), "\n ");
2441     getCommentOS() << "\n";
2442   }
2443 
2444   if(getTargetStreamer())
2445     getTargetStreamer()->prettyPrintAsm(*InstPrinter, 0, Inst, STI, OS);
2446   else
2447     InstPrinter->printInst(&Inst, 0, "", STI, OS);
2448 
2449   StringRef Comments = CommentToEmit;
2450   if (Comments.size() && Comments.back() != '\n')
2451     getCommentOS() << "\n";
2452 
2453   EmitEOL();
2454 }
2455 
emitPseudoProbe(uint64_t Guid,uint64_t Index,uint64_t Type,uint64_t Attr,uint64_t Discriminator,const MCPseudoProbeInlineStack & InlineStack,MCSymbol * FnSym)2456 void MCAsmStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index,
2457                                     uint64_t Type, uint64_t Attr,
2458                                     uint64_t Discriminator,
2459                                     const MCPseudoProbeInlineStack &InlineStack,
2460                                     MCSymbol *FnSym) {
2461   OS << "\t.pseudoprobe\t" << Guid << " " << Index << " " << Type << " " << Attr;
2462   if (Discriminator)
2463     OS << " " << Discriminator;
2464   // Emit inline stack like
2465   //  @ GUIDmain:3 @ GUIDCaller:1 @ GUIDDirectCaller:11
2466   for (const auto &Site : InlineStack)
2467     OS << " @ " << std::get<0>(Site) << ":" << std::get<1>(Site);
2468 
2469   OS << " ";
2470   FnSym->print(OS, MAI);
2471 
2472   EmitEOL();
2473 }
2474 
emitBundleAlignMode(Align Alignment)2475 void MCAsmStreamer::emitBundleAlignMode(Align Alignment) {
2476   OS << "\t.bundle_align_mode " << Log2(Alignment);
2477   EmitEOL();
2478 }
2479 
emitBundleLock(bool AlignToEnd)2480 void MCAsmStreamer::emitBundleLock(bool AlignToEnd) {
2481   OS << "\t.bundle_lock";
2482   if (AlignToEnd)
2483     OS << " align_to_end";
2484   EmitEOL();
2485 }
2486 
emitBundleUnlock()2487 void MCAsmStreamer::emitBundleUnlock() {
2488   OS << "\t.bundle_unlock";
2489   EmitEOL();
2490 }
2491 
2492 std::optional<std::pair<bool, std::string>>
emitRelocDirective(const MCExpr & Offset,StringRef Name,const MCExpr * Expr,SMLoc,const MCSubtargetInfo & STI)2493 MCAsmStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
2494                                   const MCExpr *Expr, SMLoc,
2495                                   const MCSubtargetInfo &STI) {
2496   OS << "\t.reloc ";
2497   MAI->printExpr(OS, Offset);
2498   OS << ", " << Name;
2499   if (Expr) {
2500     OS << ", ";
2501     MAI->printExpr(OS, *Expr);
2502   }
2503   EmitEOL();
2504   return std::nullopt;
2505 }
2506 
emitAddrsig()2507 void MCAsmStreamer::emitAddrsig() {
2508   OS << "\t.addrsig";
2509   EmitEOL();
2510 }
2511 
emitAddrsigSym(const MCSymbol * Sym)2512 void MCAsmStreamer::emitAddrsigSym(const MCSymbol *Sym) {
2513   OS << "\t.addrsig_sym ";
2514   Sym->print(OS, MAI);
2515   EmitEOL();
2516 }
2517 
2518 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
2519 /// the specified string in the output .s file.  This capability is
2520 /// indicated by the hasRawTextSupport() predicate.
emitRawTextImpl(StringRef String)2521 void MCAsmStreamer::emitRawTextImpl(StringRef String) {
2522   String.consume_back("\n");
2523   OS << String;
2524   EmitEOL();
2525 }
2526 
finishImpl()2527 void MCAsmStreamer::finishImpl() {
2528   // If we are generating dwarf for assembly source files dump out the sections.
2529   if (getContext().getGenDwarfForAssembly())
2530     MCGenDwarfInfo::Emit(this);
2531 
2532   // Now it is time to emit debug line sections if target doesn't support .loc
2533   // and .line directives.
2534   if (MAI->isAIX()) {
2535     MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
2536     return;
2537   }
2538 
2539   // Emit the label for the line table, if requested - since the rest of the
2540   // line table will be defined by .loc/.file directives, and not emitted
2541   // directly, the label is the only work required here.
2542   const auto &Tables = getContext().getMCDwarfLineTables();
2543   if (!Tables.empty()) {
2544     assert(Tables.size() == 1 && "asm output only supports one line table");
2545     if (auto *Label = Tables.begin()->second.getLabel()) {
2546       switchSection(getContext().getObjectFileInfo()->getDwarfLineSection(), 0);
2547       emitLabel(Label);
2548     }
2549   }
2550 }
2551 
emitDwarfUnitLength(uint64_t Length,const Twine & Comment)2552 void MCAsmStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
2553   // If the assembler on some target fills in the DWARF unit length, we
2554   // don't want to emit the length in the compiler. For example, the AIX
2555   // assembler requires the assembly file with the unit length omitted from
2556   // the debug section headers. In such cases, any label we placed occurs
2557   // after the implied length field. We need to adjust the reference here
2558   // to account for the offset introduced by the inserted length field.
2559   if (MAI->isAIX())
2560     return;
2561   MCStreamer::emitDwarfUnitLength(Length, Comment);
2562 }
2563 
emitDwarfUnitLength(const Twine & Prefix,const Twine & Comment)2564 MCSymbol *MCAsmStreamer::emitDwarfUnitLength(const Twine &Prefix,
2565                                              const Twine &Comment) {
2566   // If the assembler on some target fills in the DWARF unit length, we
2567   // don't want to emit the length in the compiler. For example, the AIX
2568   // assembler requires the assembly file with the unit length omitted from
2569   // the debug section headers. In such cases, any label we placed occurs
2570   // after the implied length field. We need to adjust the reference here
2571   // to account for the offset introduced by the inserted length field.
2572   if (MAI->isAIX())
2573     return getContext().createTempSymbol(Prefix + "_end");
2574   return MCStreamer::emitDwarfUnitLength(Prefix, Comment);
2575 }
2576 
emitDwarfLineStartLabel(MCSymbol * StartSym)2577 void MCAsmStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
2578   // If the assembler on some target fills in the DWARF unit length, we
2579   // don't want to emit the length in the compiler. For example, the AIX
2580   // assembler requires the assembly file with the unit length omitted from
2581   // the debug section headers. In such cases, any label we placed occurs
2582   // after the implied length field. We need to adjust the reference here
2583   // to account for the offset introduced by the inserted length field.
2584   MCContext &Ctx = getContext();
2585   if (MAI->isAIX()) {
2586     MCSymbol *DebugLineSymTmp = Ctx.createTempSymbol("debug_line_");
2587     // Emit the symbol which does not contain the unit length field.
2588     emitLabel(DebugLineSymTmp);
2589 
2590     // Adjust the outer reference to account for the offset introduced by the
2591     // inserted length field.
2592     unsigned LengthFieldSize =
2593         dwarf::getUnitLengthFieldByteSize(Ctx.getDwarfFormat());
2594     const MCExpr *EntrySize = MCConstantExpr::create(LengthFieldSize, Ctx);
2595     const MCExpr *OuterSym = MCBinaryExpr::createSub(
2596         MCSymbolRefExpr::create(DebugLineSymTmp, Ctx), EntrySize, Ctx);
2597 
2598     emitAssignment(StartSym, OuterSym);
2599     return;
2600   }
2601   MCStreamer::emitDwarfLineStartLabel(StartSym);
2602 }
2603 
emitDwarfLineEndEntry(MCSection * Section,MCSymbol * LastLabel,MCSymbol * EndLabel)2604 void MCAsmStreamer::emitDwarfLineEndEntry(MCSection *Section,
2605                                           MCSymbol *LastLabel,
2606                                           MCSymbol *EndLabel) {
2607   // If the targets write the raw debug line data for assembly output (We can
2608   // not switch to Section and add the end symbol there for assembly output)
2609   // we currently use the .text end label as any section end. This will not
2610   // impact the debugability as we will jump to the caller of the last function
2611   // in the section before we come into the .text end address.
2612   assert(MAI->isAIX() &&
2613          ".loc should not be generated together with raw data!");
2614 
2615   MCContext &Ctx = getContext();
2616 
2617   // FIXME: use section end symbol as end of the Section. We need to consider
2618   // the explicit sections and -ffunction-sections when we try to generate or
2619   // find section end symbol for the Section.
2620   MCSection *TextSection = Ctx.getObjectFileInfo()->getTextSection();
2621   assert(TextSection->hasEnded() && ".text section is not end!");
2622 
2623   if (!EndLabel)
2624     EndLabel = TextSection->getEndSymbol(Ctx);
2625   const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
2626   emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, EndLabel,
2627                            AsmInfo->getCodePointerSize());
2628 }
2629 
2630 // Generate DWARF line sections for assembly mode without .loc/.file
emitDwarfAdvanceLineAddr(int64_t LineDelta,const MCSymbol * LastLabel,const MCSymbol * Label,unsigned PointerSize)2631 void MCAsmStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
2632                                              const MCSymbol *LastLabel,
2633                                              const MCSymbol *Label,
2634                                              unsigned PointerSize) {
2635   assert(MAI->isAIX() &&
2636          ".loc/.file don't need raw data in debug line section!");
2637 
2638   // Set to new address.
2639   AddComment("Set address to " + Label->getName());
2640   emitIntValue(dwarf::DW_LNS_extended_op, 1);
2641   emitULEB128IntValue(PointerSize + 1);
2642   emitIntValue(dwarf::DW_LNE_set_address, 1);
2643   emitSymbolValue(Label, PointerSize);
2644 
2645   if (!LastLabel) {
2646     // Emit the sequence for the LineDelta (from 1) and a zero address delta.
2647     AddComment("Start sequence");
2648     MCDwarfLineAddr::Emit(this, MCDwarfLineTableParams(), LineDelta, 0);
2649     return;
2650   }
2651 
2652   // INT64_MAX is a signal of the end of the section. Emit DW_LNE_end_sequence
2653   // for the end of the section.
2654   if (LineDelta == INT64_MAX) {
2655     AddComment("End sequence");
2656     emitIntValue(dwarf::DW_LNS_extended_op, 1);
2657     emitULEB128IntValue(1);
2658     emitIntValue(dwarf::DW_LNE_end_sequence, 1);
2659     return;
2660   }
2661 
2662   // Advance line.
2663   AddComment("Advance line " + Twine(LineDelta));
2664   emitIntValue(dwarf::DW_LNS_advance_line, 1);
2665   emitSLEB128IntValue(LineDelta);
2666   emitIntValue(dwarf::DW_LNS_copy, 1);
2667 }
2668 
createAsmStreamer(MCContext & Context,std::unique_ptr<formatted_raw_ostream> OS,std::unique_ptr<MCInstPrinter> IP,std::unique_ptr<MCCodeEmitter> CE,std::unique_ptr<MCAsmBackend> MAB)2669 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
2670                                     std::unique_ptr<formatted_raw_ostream> OS,
2671                                     std::unique_ptr<MCInstPrinter> IP,
2672                                     std::unique_ptr<MCCodeEmitter> CE,
2673                                     std::unique_ptr<MCAsmBackend> MAB) {
2674   return new MCAsmStreamer(Context, std::move(OS), std::move(IP), std::move(CE),
2675                            std::move(MAB));
2676 }
2677