1 //===- MCStreamer.h - High-level Streaming Machine Code 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 // This file declares the MCStreamer class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_MC_MCSTREAMER_H
14 #define LLVM_MC_MCSTREAMER_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/MC/MCDirectives.h"
22 #include "llvm/MC/MCLinkerOptimizationHint.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCWinEH.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/MD5.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/TargetParser.h"
29 #include "llvm/Support/VersionTuple.h"
30 #include <cassert>
31 #include <cstdint>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 namespace llvm {
38 
39 class AssemblerConstantPools;
40 class formatted_raw_ostream;
41 class MCAsmBackend;
42 class MCCodeEmitter;
43 class MCContext;
44 struct MCDwarfFrameInfo;
45 class MCExpr;
46 class MCInst;
47 class MCInstPrinter;
48 class MCRegister;
49 class MCSection;
50 class MCStreamer;
51 class MCSymbolRefExpr;
52 class MCSubtargetInfo;
53 class raw_ostream;
54 class Twine;
55 
56 namespace codeview {
57 struct DefRangeRegisterRelHeader;
58 struct DefRangeSubfieldRegisterHeader;
59 struct DefRangeRegisterHeader;
60 struct DefRangeFramePointerRelHeader;
61 }
62 
63 using MCSectionSubPair = std::pair<MCSection *, const MCExpr *>;
64 
65 /// Target specific streamer interface. This is used so that targets can
66 /// implement support for target specific assembly directives.
67 ///
68 /// If target foo wants to use this, it should implement 3 classes:
69 /// * FooTargetStreamer : public MCTargetStreamer
70 /// * FooTargetAsmStreamer : public FooTargetStreamer
71 /// * FooTargetELFStreamer : public FooTargetStreamer
72 ///
73 /// FooTargetStreamer should have a pure virtual method for each directive. For
74 /// example, for a ".bar symbol_name" directive, it should have
75 /// virtual emitBar(const MCSymbol &Symbol) = 0;
76 ///
77 /// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the
78 /// method. The assembly streamer just prints ".bar symbol_name". The object
79 /// streamer does whatever is needed to implement .bar in the object file.
80 ///
81 /// In the assembly printer and parser the target streamer can be used by
82 /// calling getTargetStreamer and casting it to FooTargetStreamer:
83 ///
84 /// MCTargetStreamer &TS = OutStreamer.getTargetStreamer();
85 /// FooTargetStreamer &ATS = static_cast<FooTargetStreamer &>(TS);
86 ///
87 /// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should
88 /// *never* be treated differently. Callers should always talk to a
89 /// FooTargetStreamer.
90 class MCTargetStreamer {
91 protected:
92   MCStreamer &Streamer;
93 
94 public:
95   MCTargetStreamer(MCStreamer &S);
96   virtual ~MCTargetStreamer();
97 
98   MCStreamer &getStreamer() { return Streamer; }
99 
100   // Allow a target to add behavior to the EmitLabel of MCStreamer.
101   virtual void emitLabel(MCSymbol *Symbol);
102   // Allow a target to add behavior to the emitAssignment of MCStreamer.
103   virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value);
104 
105   virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, uint64_t Address,
106                               const MCInst &Inst, const MCSubtargetInfo &STI,
107                               raw_ostream &OS);
108 
109   virtual void emitDwarfFileDirective(StringRef Directive);
110 
111   /// Update streamer for a new active section.
112   ///
113   /// This is called by PopSection and SwitchSection, if the current
114   /// section changes.
115   virtual void changeSection(const MCSection *CurSection, MCSection *Section,
116                              const MCExpr *SubSection, raw_ostream &OS);
117 
118   virtual void emitValue(const MCExpr *Value);
119 
120   /// Emit the bytes in \p Data into the output.
121   ///
122   /// This is used to emit bytes in \p Data as sequence of .byte directives.
123   virtual void emitRawBytes(StringRef Data);
124 
125   virtual void finish();
126 };
127 
128 // FIXME: declared here because it is used from
129 // lib/CodeGen/AsmPrinter/ARMException.cpp.
130 class ARMTargetStreamer : public MCTargetStreamer {
131 public:
132   ARMTargetStreamer(MCStreamer &S);
133   ~ARMTargetStreamer() override;
134 
135   virtual void emitFnStart();
136   virtual void emitFnEnd();
137   virtual void emitCantUnwind();
138   virtual void emitPersonality(const MCSymbol *Personality);
139   virtual void emitPersonalityIndex(unsigned Index);
140   virtual void emitHandlerData();
141   virtual void emitSetFP(unsigned FpReg, unsigned SpReg,
142                          int64_t Offset = 0);
143   virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
144   virtual void emitPad(int64_t Offset);
145   virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
146                            bool isVector);
147   virtual void emitUnwindRaw(int64_t StackOffset,
148                              const SmallVectorImpl<uint8_t> &Opcodes);
149 
150   virtual void switchVendor(StringRef Vendor);
151   virtual void emitAttribute(unsigned Attribute, unsigned Value);
152   virtual void emitTextAttribute(unsigned Attribute, StringRef String);
153   virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
154                                     StringRef StringValue = "");
155   virtual void emitFPU(unsigned FPU);
156   virtual void emitArch(ARM::ArchKind Arch);
157   virtual void emitArchExtension(uint64_t ArchExt);
158   virtual void emitObjectArch(ARM::ArchKind Arch);
159   void emitTargetAttributes(const MCSubtargetInfo &STI);
160   virtual void finishAttributeSection();
161   virtual void emitInst(uint32_t Inst, char Suffix = '\0');
162 
163   virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
164 
165   virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value);
166 
167   void finish() override;
168 
169   /// Reset any state between object emissions, i.e. the equivalent of
170   /// MCStreamer's reset method.
171   virtual void reset();
172 
173   /// Callback used to implement the ldr= pseudo.
174   /// Add a new entry to the constant pool for the current section and return an
175   /// MCExpr that can be used to refer to the constant pool location.
176   const MCExpr *addConstantPoolEntry(const MCExpr *, SMLoc Loc);
177 
178   /// Callback used to implemnt the .ltorg directive.
179   /// Emit contents of constant pool for the current section.
180   void emitCurrentConstantPool();
181 
182 private:
183   std::unique_ptr<AssemblerConstantPools> ConstantPools;
184 };
185 
186 /// Streaming machine code generation interface.
187 ///
188 /// This interface is intended to provide a programatic interface that is very
189 /// similar to the level that an assembler .s file provides.  It has callbacks
190 /// to emit bytes, handle directives, etc.  The implementation of this interface
191 /// retains state to know what the current section is etc.
192 ///
193 /// There are multiple implementations of this interface: one for writing out
194 /// a .s file, and implementations that write out .o files of various formats.
195 ///
196 class MCStreamer {
197   MCContext &Context;
198   std::unique_ptr<MCTargetStreamer> TargetStreamer;
199 
200   std::vector<MCDwarfFrameInfo> DwarfFrameInfos;
201   MCDwarfFrameInfo *getCurrentDwarfFrameInfo();
202 
203   /// Similar to DwarfFrameInfos, but for SEH unwind info. Chained frames may
204   /// refer to each other, so use std::unique_ptr to provide pointer stability.
205   std::vector<std::unique_ptr<WinEH::FrameInfo>> WinFrameInfos;
206 
207   WinEH::FrameInfo *CurrentWinFrameInfo;
208 
209   /// Tracks an index to represent the order a symbol was emitted in.
210   /// Zero means we did not emit that symbol.
211   DenseMap<const MCSymbol *, unsigned> SymbolOrdering;
212 
213   /// This is stack of current and previous section values saved by
214   /// PushSection.
215   SmallVector<std::pair<MCSectionSubPair, MCSectionSubPair>, 4> SectionStack;
216 
217   /// The next unique ID to use when creating a WinCFI-related section (.pdata
218   /// or .xdata). This ID ensures that we have a one-to-one mapping from
219   /// code section to unwind info section, which MSVC's incremental linker
220   /// requires.
221   unsigned NextWinCFIID = 0;
222 
223   bool UseAssemblerInfoForParsing;
224 
225   /// Is the assembler allowed to insert padding automatically?  For
226   /// correctness reasons, we sometimes need to ensure instructions aren't
227   /// seperated in unexpected ways.  At the moment, this feature is only
228   /// useable from an integrated assembler, but assembly syntax is under
229   /// discussion for future inclusion.
230   bool AllowAutoPadding = false;
231 
232 protected:
233   MCStreamer(MCContext &Ctx);
234 
235   virtual void emitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
236   virtual void emitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
237 
238   WinEH::FrameInfo *getCurrentWinFrameInfo() {
239     return CurrentWinFrameInfo;
240   }
241 
242   virtual void EmitWindowsUnwindTables();
243 
244   virtual void emitRawTextImpl(StringRef String);
245 
246   /// Returns true if the the .cv_loc directive is in the right section.
247   bool checkCVLocSection(unsigned FuncId, unsigned FileNo, SMLoc Loc);
248 
249 public:
250   MCStreamer(const MCStreamer &) = delete;
251   MCStreamer &operator=(const MCStreamer &) = delete;
252   virtual ~MCStreamer();
253 
254   void visitUsedExpr(const MCExpr &Expr);
255   virtual void visitUsedSymbol(const MCSymbol &Sym);
256 
257   void setTargetStreamer(MCTargetStreamer *TS) {
258     TargetStreamer.reset(TS);
259   }
260 
261   /// State management
262   ///
263   virtual void reset();
264 
265   MCContext &getContext() const { return Context; }
266 
267   virtual MCAssembler *getAssemblerPtr() { return nullptr; }
268 
269   void setUseAssemblerInfoForParsing(bool v) { UseAssemblerInfoForParsing = v; }
270   bool getUseAssemblerInfoForParsing() { return UseAssemblerInfoForParsing; }
271 
272   MCTargetStreamer *getTargetStreamer() {
273     return TargetStreamer.get();
274   }
275 
276   void setAllowAutoPadding(bool v) { AllowAutoPadding = v; }
277   bool getAllowAutoPadding() const { return AllowAutoPadding; }
278 
279   /// When emitting an object file, create and emit a real label. When emitting
280   /// textual assembly, this should do nothing to avoid polluting our output.
281   virtual MCSymbol *emitCFILabel();
282 
283   /// Retreive the current frame info if one is available and it is not yet
284   /// closed. Otherwise, issue an error and return null.
285   WinEH::FrameInfo *EnsureValidWinFrameInfo(SMLoc Loc);
286 
287   unsigned getNumFrameInfos();
288   ArrayRef<MCDwarfFrameInfo> getDwarfFrameInfos() const;
289 
290   bool hasUnfinishedDwarfFrameInfo();
291 
292   unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); }
293   ArrayRef<std::unique_ptr<WinEH::FrameInfo>> getWinFrameInfos() const {
294     return WinFrameInfos;
295   }
296 
297   void generateCompactUnwindEncodings(MCAsmBackend *MAB);
298 
299   /// \name Assembly File Formatting.
300   /// @{
301 
302   /// Return true if this streamer supports verbose assembly and if it is
303   /// enabled.
304   virtual bool isVerboseAsm() const { return false; }
305 
306   /// Return true if this asm streamer supports emitting unformatted text
307   /// to the .s file with EmitRawText.
308   virtual bool hasRawTextSupport() const { return false; }
309 
310   /// Is the integrated assembler required for this streamer to function
311   /// correctly?
312   virtual bool isIntegratedAssemblerRequired() const { return false; }
313 
314   /// Add a textual comment.
315   ///
316   /// Typically for comments that can be emitted to the generated .s
317   /// file if applicable as a QoI issue to make the output of the compiler
318   /// more readable.  This only affects the MCAsmStreamer, and only when
319   /// verbose assembly output is enabled.
320   ///
321   /// If the comment includes embedded \n's, they will each get the comment
322   /// prefix as appropriate.  The added comment should not end with a \n.
323   /// By default, each comment is terminated with an end of line, i.e. the
324   /// EOL param is set to true by default. If one prefers not to end the
325   /// comment with a new line then the EOL param should be passed
326   /// with a false value.
327   virtual void AddComment(const Twine &T, bool EOL = true) {}
328 
329   /// Return a raw_ostream that comments can be written to. Unlike
330   /// AddComment, you are required to terminate comments with \n if you use this
331   /// method.
332   virtual raw_ostream &GetCommentOS();
333 
334   /// Print T and prefix it with the comment string (normally #) and
335   /// optionally a tab. This prints the comment immediately, not at the end of
336   /// the current line. It is basically a safe version of EmitRawText: since it
337   /// only prints comments, the object streamer ignores it instead of asserting.
338   virtual void emitRawComment(const Twine &T, bool TabPrefix = true);
339 
340   /// Add explicit comment T. T is required to be a valid
341   /// comment in the output and does not need to be escaped.
342   virtual void addExplicitComment(const Twine &T);
343 
344   /// Emit added explicit comments.
345   virtual void emitExplicitComments();
346 
347   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
348   virtual void AddBlankLine() {}
349 
350   /// @}
351 
352   /// \name Symbol & Section Management
353   /// @{
354 
355   /// Return the current section that the streamer is emitting code to.
356   MCSectionSubPair getCurrentSection() const {
357     if (!SectionStack.empty())
358       return SectionStack.back().first;
359     return MCSectionSubPair();
360   }
361   MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; }
362 
363   /// Return the previous section that the streamer is emitting code to.
364   MCSectionSubPair getPreviousSection() const {
365     if (!SectionStack.empty())
366       return SectionStack.back().second;
367     return MCSectionSubPair();
368   }
369 
370   /// Returns an index to represent the order a symbol was emitted in.
371   /// (zero if we did not emit that symbol)
372   unsigned GetSymbolOrder(const MCSymbol *Sym) const {
373     return SymbolOrdering.lookup(Sym);
374   }
375 
376   /// Update streamer for a new active section.
377   ///
378   /// This is called by PopSection and SwitchSection, if the current
379   /// section changes.
380   virtual void changeSection(MCSection *, const MCExpr *);
381 
382   /// Save the current and previous section on the section stack.
383   void PushSection() {
384     SectionStack.push_back(
385         std::make_pair(getCurrentSection(), getPreviousSection()));
386   }
387 
388   /// Restore the current and previous section from the section stack.
389   /// Calls changeSection as needed.
390   ///
391   /// Returns false if the stack was empty.
392   bool PopSection() {
393     if (SectionStack.size() <= 1)
394       return false;
395     auto I = SectionStack.end();
396     --I;
397     MCSectionSubPair OldSection = I->first;
398     --I;
399     MCSectionSubPair NewSection = I->first;
400 
401     if (NewSection.first && OldSection != NewSection)
402       changeSection(NewSection.first, NewSection.second);
403     SectionStack.pop_back();
404     return true;
405   }
406 
407   bool SubSection(const MCExpr *Subsection) {
408     if (SectionStack.empty())
409       return false;
410 
411     SwitchSection(SectionStack.back().first.first, Subsection);
412     return true;
413   }
414 
415   /// Set the current section where code is being emitted to \p Section.  This
416   /// is required to update CurSection.
417   ///
418   /// This corresponds to assembler directives like .section, .text, etc.
419   virtual void SwitchSection(MCSection *Section,
420                              const MCExpr *Subsection = nullptr);
421 
422   /// Set the current section where code is being emitted to \p Section.
423   /// This is required to update CurSection. This version does not call
424   /// changeSection.
425   void SwitchSectionNoChange(MCSection *Section,
426                              const MCExpr *Subsection = nullptr) {
427     assert(Section && "Cannot switch to a null section!");
428     MCSectionSubPair curSection = SectionStack.back().first;
429     SectionStack.back().second = curSection;
430     if (MCSectionSubPair(Section, Subsection) != curSection)
431       SectionStack.back().first = MCSectionSubPair(Section, Subsection);
432   }
433 
434   /// Create the default sections and set the initial one.
435   virtual void InitSections(bool NoExecStack);
436 
437   MCSymbol *endSection(MCSection *Section);
438 
439   /// Sets the symbol's section.
440   ///
441   /// Each emitted symbol will be tracked in the ordering table,
442   /// so we can sort on them later.
443   void AssignFragment(MCSymbol *Symbol, MCFragment *Fragment);
444 
445   /// Emit a label for \p Symbol into the current section.
446   ///
447   /// This corresponds to an assembler statement such as:
448   ///   foo:
449   ///
450   /// \param Symbol - The symbol to emit. A given symbol should only be
451   /// emitted as a label once, and symbols emitted as a label should never be
452   /// used in an assignment.
453   // FIXME: These emission are non-const because we mutate the symbol to
454   // add the section we're emitting it to later.
455   virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc());
456 
457   virtual void emitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol);
458 
459   /// Note in the output the specified \p Flag.
460   virtual void emitAssemblerFlag(MCAssemblerFlag Flag);
461 
462   /// Emit the given list \p Options of strings as linker
463   /// options into the output.
464   virtual void emitLinkerOptions(ArrayRef<std::string> Kind) {}
465 
466   /// Note in the output the specified region \p Kind.
467   virtual void emitDataRegion(MCDataRegionType Kind) {}
468 
469   /// Specify the Mach-O minimum deployment target version.
470   virtual void emitVersionMin(MCVersionMinType Type, unsigned Major,
471                               unsigned Minor, unsigned Update,
472                               VersionTuple SDKVersion) {}
473 
474   /// Emit/Specify Mach-O build version command.
475   /// \p Platform should be one of MachO::PlatformType.
476   virtual void emitBuildVersion(unsigned Platform, unsigned Major,
477                                 unsigned Minor, unsigned Update,
478                                 VersionTuple SDKVersion) {}
479 
480   void emitVersionForTarget(const Triple &Target,
481                             const VersionTuple &SDKVersion);
482 
483   /// Note in the output that the specified \p Func is a Thumb mode
484   /// function (ARM target only).
485   virtual void emitThumbFunc(MCSymbol *Func);
486 
487   /// Emit an assignment of \p Value to \p Symbol.
488   ///
489   /// This corresponds to an assembler statement such as:
490   ///  symbol = value
491   ///
492   /// The assignment generates no code, but has the side effect of binding the
493   /// value in the current context. For the assembly streamer, this prints the
494   /// binding into the .s file.
495   ///
496   /// \param Symbol - The symbol being assigned to.
497   /// \param Value - The value for the symbol.
498   virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value);
499 
500   /// Emit an weak reference from \p Alias to \p Symbol.
501   ///
502   /// This corresponds to an assembler statement such as:
503   ///  .weakref alias, symbol
504   ///
505   /// \param Alias - The alias that is being created.
506   /// \param Symbol - The symbol being aliased.
507   virtual void emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
508 
509   /// Add the given \p Attribute to \p Symbol.
510   virtual bool emitSymbolAttribute(MCSymbol *Symbol,
511                                    MCSymbolAttr Attribute) = 0;
512 
513   /// Set the \p DescValue for the \p Symbol.
514   ///
515   /// \param Symbol - The symbol to have its n_desc field set.
516   /// \param DescValue - The value to set into the n_desc field.
517   virtual void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
518 
519   /// Start emitting COFF symbol definition
520   ///
521   /// \param Symbol - The symbol to have its External & Type fields set.
522   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
523 
524   /// Emit the storage class of the symbol.
525   ///
526   /// \param StorageClass - The storage class the symbol should have.
527   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
528 
529   /// Emit the type of the symbol.
530   ///
531   /// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
532   virtual void EmitCOFFSymbolType(int Type);
533 
534   /// Marks the end of the symbol definition.
535   virtual void EndCOFFSymbolDef();
536 
537   virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol);
538 
539   /// Emits the symbol table index of a Symbol into the current section.
540   virtual void EmitCOFFSymbolIndex(MCSymbol const *Symbol);
541 
542   /// Emits a COFF section index.
543   ///
544   /// \param Symbol - Symbol the section number relocation should point to.
545   virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
546 
547   /// Emits a COFF section relative relocation.
548   ///
549   /// \param Symbol - Symbol the section relative relocation should point to.
550   virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset);
551 
552   /// Emits a COFF image relative relocation.
553   ///
554   /// \param Symbol - Symbol the image relative relocation should point to.
555   virtual void EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset);
556 
557   /// Emits an lcomm directive with XCOFF csect information.
558   ///
559   /// \param LabelSym - Label on the block of storage.
560   /// \param Size - The size of the block of storage.
561   /// \param CsectSym - Csect name for the block of storage.
562   /// \param ByteAlignment - The alignment of the symbol in bytes. Must be a
563   /// power of 2.
564   virtual void emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
565                                           MCSymbol *CsectSym,
566                                           unsigned ByteAlignment);
567 
568   /// Emit a symbol's linkage and visibilty with a linkage directive for XCOFF.
569   ///
570   /// \param Symbol - The symbol to emit.
571   /// \param Linkage - The linkage of the symbol to emit.
572   /// \param Visibility - The visibility of the symbol to emit or MCSA_Invalid
573   /// if the symbol does not have an explicit visibility.
574   virtual void emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
575                                                     MCSymbolAttr Linkage,
576                                                     MCSymbolAttr Visibility);
577 
578   /// Emit a XCOFF .rename directive which creates a synonym for an illegal or
579   /// undesirable name.
580   ///
581   /// \param Name - The name used internally in the assembly for references to
582   /// the symbol.
583   /// \param Rename - The value to which the Name parameter is
584   /// changed at the end of assembly.
585   virtual void emitXCOFFRenameDirective(const MCSymbol *Name, StringRef Rename);
586 
587   /// Emit an ELF .size directive.
588   ///
589   /// This corresponds to an assembler statement such as:
590   ///  .size symbol, expression
591   virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value);
592 
593   /// Emit an ELF .symver directive.
594   ///
595   /// This corresponds to an assembler statement such as:
596   ///  .symver _start, foo@@SOME_VERSION
597   /// \param AliasName - The versioned alias (i.e. "foo@@SOME_VERSION")
598   /// \param Aliasee - The aliased symbol (i.e. "_start")
599   virtual void emitELFSymverDirective(StringRef AliasName,
600                                       const MCSymbol *Aliasee);
601 
602   /// Emit a Linker Optimization Hint (LOH) directive.
603   /// \param Args - Arguments of the LOH.
604   virtual void emitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
605 
606   /// Emit a common symbol.
607   ///
608   /// \param Symbol - The common symbol to emit.
609   /// \param Size - The size of the common symbol.
610   /// \param ByteAlignment - The alignment of the symbol if
611   /// non-zero. This must be a power of 2.
612   virtual void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
613                                 unsigned ByteAlignment) = 0;
614 
615   /// Emit a local common (.lcomm) symbol.
616   ///
617   /// \param Symbol - The common symbol to emit.
618   /// \param Size - The size of the common symbol.
619   /// \param ByteAlignment - The alignment of the common symbol in bytes.
620   virtual void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
621                                      unsigned ByteAlignment);
622 
623   /// Emit the zerofill section and an optional symbol.
624   ///
625   /// \param Section - The zerofill section to create and or to put the symbol
626   /// \param Symbol - The zerofill symbol to emit, if non-NULL.
627   /// \param Size - The size of the zerofill symbol.
628   /// \param ByteAlignment - The alignment of the zerofill symbol if
629   /// non-zero. This must be a power of 2 on some targets.
630   virtual void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
631                             uint64_t Size = 0, unsigned ByteAlignment = 0,
632                             SMLoc Loc = SMLoc()) = 0;
633 
634   /// Emit a thread local bss (.tbss) symbol.
635   ///
636   /// \param Section - The thread local common section.
637   /// \param Symbol - The thread local common symbol to emit.
638   /// \param Size - The size of the symbol.
639   /// \param ByteAlignment - The alignment of the thread local common symbol
640   /// if non-zero.  This must be a power of 2 on some targets.
641   virtual void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
642                               uint64_t Size, unsigned ByteAlignment = 0);
643 
644   /// @}
645   /// \name Generating Data
646   /// @{
647 
648   /// Emit the bytes in \p Data into the output.
649   ///
650   /// This is used to implement assembler directives such as .byte, .ascii,
651   /// etc.
652   virtual void emitBytes(StringRef Data);
653 
654   /// Functionally identical to EmitBytes. When emitting textual assembly, this
655   /// method uses .byte directives instead of .ascii or .asciz for readability.
656   virtual void emitBinaryData(StringRef Data);
657 
658   /// Emit the expression \p Value into the output as a native
659   /// integer of the given \p Size bytes.
660   ///
661   /// This is used to implement assembler directives such as .word, .quad,
662   /// etc.
663   ///
664   /// \param Value - The value to emit.
665   /// \param Size - The size of the integer (in bytes) to emit. This must
666   /// match a native machine width.
667   /// \param Loc - The location of the expression for error reporting.
668   virtual void emitValueImpl(const MCExpr *Value, unsigned Size,
669                              SMLoc Loc = SMLoc());
670 
671   void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc());
672 
673   /// Special case of EmitValue that avoids the client having
674   /// to pass in a MCExpr for constant integers.
675   virtual void emitIntValue(uint64_t Value, unsigned Size);
676 
677   /// Special case of EmitValue that avoids the client having to pass
678   /// in a MCExpr for constant integers & prints in Hex format for certain
679   /// modes.
680   virtual void emitIntValueInHex(uint64_t Value, unsigned Size) {
681     emitIntValue(Value, Size);
682   }
683 
684   void emitInt8(uint64_t Value) { emitIntValue(Value, 1); }
685   void emitInt16(uint64_t Value) { emitIntValue(Value, 2); }
686   void emitInt32(uint64_t Value) { emitIntValue(Value, 4); }
687   void emitInt64(uint64_t Value) { emitIntValue(Value, 8); }
688 
689   /// Special case of EmitValue that avoids the client having to pass
690   /// in a MCExpr for constant integers & prints in Hex format for certain
691   /// modes, pads the field with leading zeros to Size width
692   virtual void emitIntValueInHexWithPadding(uint64_t Value, unsigned Size) {
693     emitIntValue(Value, Size);
694   }
695 
696   virtual void emitULEB128Value(const MCExpr *Value);
697 
698   virtual void emitSLEB128Value(const MCExpr *Value);
699 
700   /// Special case of EmitULEB128Value that avoids the client having to
701   /// pass in a MCExpr for constant integers.
702   void emitULEB128IntValue(uint64_t Value, unsigned PadTo = 0);
703 
704   /// Special case of EmitSLEB128Value that avoids the client having to
705   /// pass in a MCExpr for constant integers.
706   void emitSLEB128IntValue(int64_t Value);
707 
708   /// Special case of EmitValue that avoids the client having to pass in
709   /// a MCExpr for MCSymbols.
710   void emitSymbolValue(const MCSymbol *Sym, unsigned Size,
711                        bool IsSectionRelative = false);
712 
713   /// Emit the expression \p Value into the output as a dtprel
714   /// (64-bit DTP relative) value.
715   ///
716   /// This is used to implement assembler directives such as .dtpreldword on
717   /// targets that support them.
718   virtual void emitDTPRel64Value(const MCExpr *Value);
719 
720   /// Emit the expression \p Value into the output as a dtprel
721   /// (32-bit DTP relative) value.
722   ///
723   /// This is used to implement assembler directives such as .dtprelword on
724   /// targets that support them.
725   virtual void emitDTPRel32Value(const MCExpr *Value);
726 
727   /// Emit the expression \p Value into the output as a tprel
728   /// (64-bit TP relative) value.
729   ///
730   /// This is used to implement assembler directives such as .tpreldword on
731   /// targets that support them.
732   virtual void emitTPRel64Value(const MCExpr *Value);
733 
734   /// Emit the expression \p Value into the output as a tprel
735   /// (32-bit TP relative) value.
736   ///
737   /// This is used to implement assembler directives such as .tprelword on
738   /// targets that support them.
739   virtual void emitTPRel32Value(const MCExpr *Value);
740 
741   /// Emit the expression \p Value into the output as a gprel64 (64-bit
742   /// GP relative) value.
743   ///
744   /// This is used to implement assembler directives such as .gpdword on
745   /// targets that support them.
746   virtual void emitGPRel64Value(const MCExpr *Value);
747 
748   /// Emit the expression \p Value into the output as a gprel32 (32-bit
749   /// GP relative) value.
750   ///
751   /// This is used to implement assembler directives such as .gprel32 on
752   /// targets that support them.
753   virtual void emitGPRel32Value(const MCExpr *Value);
754 
755   /// Emit NumBytes bytes worth of the value specified by FillValue.
756   /// This implements directives such as '.space'.
757   void emitFill(uint64_t NumBytes, uint8_t FillValue);
758 
759   /// Emit \p Size bytes worth of the value specified by \p FillValue.
760   ///
761   /// This is used to implement assembler directives such as .space or .skip.
762   ///
763   /// \param NumBytes - The number of bytes to emit.
764   /// \param FillValue - The value to use when filling bytes.
765   /// \param Loc - The location of the expression for error reporting.
766   virtual void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
767                         SMLoc Loc = SMLoc());
768 
769   /// Emit \p NumValues copies of \p Size bytes. Each \p Size bytes is
770   /// taken from the lowest order 4 bytes of \p Expr expression.
771   ///
772   /// This is used to implement assembler directives such as .fill.
773   ///
774   /// \param NumValues - The number of copies of \p Size bytes to emit.
775   /// \param Size - The size (in bytes) of each repeated value.
776   /// \param Expr - The expression from which \p Size bytes are used.
777   virtual void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
778                         SMLoc Loc = SMLoc());
779 
780   /// Emit NumBytes worth of zeros.
781   /// This function properly handles data in virtual sections.
782   void emitZeros(uint64_t NumBytes);
783 
784   /// Emit some number of copies of \p Value until the byte alignment \p
785   /// ByteAlignment is reached.
786   ///
787   /// If the number of bytes need to emit for the alignment is not a multiple
788   /// of \p ValueSize, then the contents of the emitted fill bytes is
789   /// undefined.
790   ///
791   /// This used to implement the .align assembler directive.
792   ///
793   /// \param ByteAlignment - The alignment to reach. This must be a power of
794   /// two on some targets.
795   /// \param Value - The value to use when filling bytes.
796   /// \param ValueSize - The size of the integer (in bytes) to emit for
797   /// \p Value. This must match a native machine width.
798   /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
799   /// the alignment cannot be reached in this many bytes, no bytes are
800   /// emitted.
801   virtual void emitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
802                                     unsigned ValueSize = 1,
803                                     unsigned MaxBytesToEmit = 0);
804 
805   /// Emit nops until the byte alignment \p ByteAlignment is reached.
806   ///
807   /// This used to align code where the alignment bytes may be executed.  This
808   /// can emit different bytes for different sizes to optimize execution.
809   ///
810   /// \param ByteAlignment - The alignment to reach. This must be a power of
811   /// two on some targets.
812   /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
813   /// the alignment cannot be reached in this many bytes, no bytes are
814   /// emitted.
815   virtual void emitCodeAlignment(unsigned ByteAlignment,
816                                  unsigned MaxBytesToEmit = 0);
817 
818   /// Emit some number of copies of \p Value until the byte offset \p
819   /// Offset is reached.
820   ///
821   /// This is used to implement assembler directives such as .org.
822   ///
823   /// \param Offset - The offset to reach. This may be an expression, but the
824   /// expression must be associated with the current section.
825   /// \param Value - The value to use when filling bytes.
826   virtual void emitValueToOffset(const MCExpr *Offset, unsigned char Value,
827                                  SMLoc Loc);
828 
829   /// @}
830 
831   /// Switch to a new logical file.  This is used to implement the '.file
832   /// "foo.c"' assembler directive.
833   virtual void emitFileDirective(StringRef Filename);
834 
835   /// Emit the "identifiers" directive.  This implements the
836   /// '.ident "version foo"' assembler directive.
837   virtual void emitIdent(StringRef IdentString) {}
838 
839   /// Associate a filename with a specified logical file number.  This
840   /// implements the DWARF2 '.file 4 "foo.c"' assembler directive.
841   unsigned emitDwarfFileDirective(unsigned FileNo, StringRef Directory,
842                                   StringRef Filename,
843                                   Optional<MD5::MD5Result> Checksum = None,
844                                   Optional<StringRef> Source = None,
845                                   unsigned CUID = 0) {
846     return cantFail(
847         tryEmitDwarfFileDirective(FileNo, Directory, Filename, Checksum,
848                                   Source, CUID));
849   }
850 
851   /// Associate a filename with a specified logical file number.
852   /// Also associate a directory, optional checksum, and optional source
853   /// text with the logical file.  This implements the DWARF2
854   /// '.file 4 "dir/foo.c"' assembler directive, and the DWARF5
855   /// '.file 4 "dir/foo.c" md5 "..." source "..."' assembler directive.
856   virtual Expected<unsigned> tryEmitDwarfFileDirective(
857       unsigned FileNo, StringRef Directory, StringRef Filename,
858       Optional<MD5::MD5Result> Checksum = None, Optional<StringRef> Source = None,
859       unsigned CUID = 0);
860 
861   /// Specify the "root" file of the compilation, using the ".file 0" extension.
862   virtual void emitDwarfFile0Directive(StringRef Directory, StringRef Filename,
863                                        Optional<MD5::MD5Result> Checksum,
864                                        Optional<StringRef> Source,
865                                        unsigned CUID = 0);
866 
867   virtual void emitCFIBKeyFrame();
868 
869   /// This implements the DWARF2 '.loc fileno lineno ...' assembler
870   /// directive.
871   virtual void emitDwarfLocDirective(unsigned FileNo, unsigned Line,
872                                      unsigned Column, unsigned Flags,
873                                      unsigned Isa, unsigned Discriminator,
874                                      StringRef FileName);
875 
876   /// Associate a filename with a specified logical file number, and also
877   /// specify that file's checksum information.  This implements the '.cv_file 4
878   /// "foo.c"' assembler directive. Returns true on success.
879   virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
880                                    ArrayRef<uint8_t> Checksum,
881                                    unsigned ChecksumKind);
882 
883   /// Introduces a function id for use with .cv_loc.
884   virtual bool EmitCVFuncIdDirective(unsigned FunctionId);
885 
886   /// Introduces an inline call site id for use with .cv_loc. Includes
887   /// extra information for inline line table generation.
888   virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
889                                            unsigned IAFile, unsigned IALine,
890                                            unsigned IACol, SMLoc Loc);
891 
892   /// This implements the CodeView '.cv_loc' assembler directive.
893   virtual void emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
894                                   unsigned Line, unsigned Column,
895                                   bool PrologueEnd, bool IsStmt,
896                                   StringRef FileName, SMLoc Loc);
897 
898   /// This implements the CodeView '.cv_linetable' assembler directive.
899   virtual void emitCVLinetableDirective(unsigned FunctionId,
900                                         const MCSymbol *FnStart,
901                                         const MCSymbol *FnEnd);
902 
903   /// This implements the CodeView '.cv_inline_linetable' assembler
904   /// directive.
905   virtual void emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
906                                               unsigned SourceFileId,
907                                               unsigned SourceLineNum,
908                                               const MCSymbol *FnStartSym,
909                                               const MCSymbol *FnEndSym);
910 
911   /// This implements the CodeView '.cv_def_range' assembler
912   /// directive.
913   virtual void emitCVDefRangeDirective(
914       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
915       StringRef FixedSizePortion);
916 
917   virtual void emitCVDefRangeDirective(
918       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
919       codeview::DefRangeRegisterRelHeader DRHdr);
920 
921   virtual void emitCVDefRangeDirective(
922       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
923       codeview::DefRangeSubfieldRegisterHeader DRHdr);
924 
925   virtual void emitCVDefRangeDirective(
926       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
927       codeview::DefRangeRegisterHeader DRHdr);
928 
929   virtual void emitCVDefRangeDirective(
930       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
931       codeview::DefRangeFramePointerRelHeader DRHdr);
932 
933   /// This implements the CodeView '.cv_stringtable' assembler directive.
934   virtual void emitCVStringTableDirective() {}
935 
936   /// This implements the CodeView '.cv_filechecksums' assembler directive.
937   virtual void emitCVFileChecksumsDirective() {}
938 
939   /// This implements the CodeView '.cv_filechecksumoffset' assembler
940   /// directive.
941   virtual void emitCVFileChecksumOffsetDirective(unsigned FileNo) {}
942 
943   /// This implements the CodeView '.cv_fpo_data' assembler directive.
944   virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc = {}) {}
945 
946   /// Emit the absolute difference between two symbols.
947   ///
948   /// \pre Offset of \c Hi is greater than the offset \c Lo.
949   virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
950                                       unsigned Size);
951 
952   /// Emit the absolute difference between two symbols encoded with ULEB128.
953   virtual void emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
954                                                const MCSymbol *Lo);
955 
956   virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID);
957   virtual void emitCFISections(bool EH, bool Debug);
958   void emitCFIStartProc(bool IsSimple, SMLoc Loc = SMLoc());
959   void emitCFIEndProc();
960   virtual void emitCFIDefCfa(int64_t Register, int64_t Offset);
961   virtual void emitCFIDefCfaOffset(int64_t Offset);
962   virtual void emitCFIDefCfaRegister(int64_t Register);
963   virtual void emitCFIOffset(int64_t Register, int64_t Offset);
964   virtual void emitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
965   virtual void emitCFILsda(const MCSymbol *Sym, unsigned Encoding);
966   virtual void emitCFIRememberState();
967   virtual void emitCFIRestoreState();
968   virtual void emitCFISameValue(int64_t Register);
969   virtual void emitCFIRestore(int64_t Register);
970   virtual void emitCFIRelOffset(int64_t Register, int64_t Offset);
971   virtual void emitCFIAdjustCfaOffset(int64_t Adjustment);
972   virtual void emitCFIEscape(StringRef Values);
973   virtual void emitCFIReturnColumn(int64_t Register);
974   virtual void emitCFIGnuArgsSize(int64_t Size);
975   virtual void emitCFISignalFrame();
976   virtual void emitCFIUndefined(int64_t Register);
977   virtual void emitCFIRegister(int64_t Register1, int64_t Register2);
978   virtual void emitCFIWindowSave();
979   virtual void emitCFINegateRAState();
980 
981   virtual void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc = SMLoc());
982   virtual void EmitWinCFIEndProc(SMLoc Loc = SMLoc());
983   /// This is used on platforms, such as Windows on ARM64, that require function
984   /// or funclet sizes to be emitted in .xdata before the End marker is emitted
985   /// for the frame.  We cannot use the End marker, as it is not set at the
986   /// point of emitting .xdata, in order to indicate that the frame is active.
987   virtual void EmitWinCFIFuncletOrFuncEnd(SMLoc Loc = SMLoc());
988   virtual void EmitWinCFIStartChained(SMLoc Loc = SMLoc());
989   virtual void EmitWinCFIEndChained(SMLoc Loc = SMLoc());
990   virtual void EmitWinCFIPushReg(MCRegister Register, SMLoc Loc = SMLoc());
991   virtual void EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
992                                   SMLoc Loc = SMLoc());
993   virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc = SMLoc());
994   virtual void EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
995                                  SMLoc Loc = SMLoc());
996   virtual void EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
997                                  SMLoc Loc = SMLoc());
998   virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc = SMLoc());
999   virtual void EmitWinCFIEndProlog(SMLoc Loc = SMLoc());
1000   virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
1001                                 SMLoc Loc = SMLoc());
1002   virtual void EmitWinEHHandlerData(SMLoc Loc = SMLoc());
1003 
1004   virtual void emitCGProfileEntry(const MCSymbolRefExpr *From,
1005                                   const MCSymbolRefExpr *To, uint64_t Count);
1006 
1007   /// Get the .pdata section used for the given section. Typically the given
1008   /// section is either the main .text section or some other COMDAT .text
1009   /// section, but it may be any section containing code.
1010   MCSection *getAssociatedPDataSection(const MCSection *TextSec);
1011 
1012   /// Get the .xdata section used for the given section.
1013   MCSection *getAssociatedXDataSection(const MCSection *TextSec);
1014 
1015   virtual void emitSyntaxDirective();
1016 
1017   /// Record a relocation described by the .reloc directive. Return None if
1018   /// succeeded. Otherwise, return a pair (Name is invalid, error message).
1019   virtual Optional<std::pair<bool, std::string>>
1020   emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr,
1021                      SMLoc Loc, const MCSubtargetInfo &STI) {
1022     return None;
1023   }
1024 
1025   virtual void emitAddrsig() {}
1026   virtual void emitAddrsigSym(const MCSymbol *Sym) {}
1027 
1028   /// Emit the given \p Instruction into the current section.
1029   virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI);
1030 
1031   /// Set the bundle alignment mode from now on in the section.
1032   /// The argument is the power of 2 to which the alignment is set. The
1033   /// value 0 means turn the bundle alignment off.
1034   virtual void emitBundleAlignMode(unsigned AlignPow2);
1035 
1036   /// The following instructions are a bundle-locked group.
1037   ///
1038   /// \param AlignToEnd - If true, the bundle-locked group will be aligned to
1039   ///                     the end of a bundle.
1040   virtual void emitBundleLock(bool AlignToEnd);
1041 
1042   /// Ends a bundle-locked group.
1043   virtual void emitBundleUnlock();
1044 
1045   /// If this file is backed by a assembly streamer, this dumps the
1046   /// specified string in the output .s file.  This capability is indicated by
1047   /// the hasRawTextSupport() predicate.  By default this aborts.
1048   void emitRawText(const Twine &String);
1049 
1050   /// Streamer specific finalization.
1051   virtual void finishImpl();
1052   /// Finish emission of machine code.
1053   void Finish();
1054 
1055   virtual bool mayHaveInstructions(MCSection &Sec) const { return true; }
1056 };
1057 
1058 /// Create a dummy machine code streamer, which does nothing. This is useful for
1059 /// timing the assembler front end.
1060 MCStreamer *createNullStreamer(MCContext &Ctx);
1061 
1062 /// Create a machine code streamer which will print out assembly for the native
1063 /// target, suitable for compiling with a native assembler.
1064 ///
1065 /// \param InstPrint - If given, the instruction printer to use. If not given
1066 /// the MCInst representation will be printed.  This method takes ownership of
1067 /// InstPrint.
1068 ///
1069 /// \param CE - If given, a code emitter to use to show the instruction
1070 /// encoding inline with the assembly. This method takes ownership of \p CE.
1071 ///
1072 /// \param TAB - If given, a target asm backend to use to show the fixup
1073 /// information in conjunction with encoding information. This method takes
1074 /// ownership of \p TAB.
1075 ///
1076 /// \param ShowInst - Whether to show the MCInst representation inline with
1077 /// the assembly.
1078 MCStreamer *createAsmStreamer(MCContext &Ctx,
1079                               std::unique_ptr<formatted_raw_ostream> OS,
1080                               bool isVerboseAsm, bool useDwarfDirectory,
1081                               MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1082                               MCAsmBackend *TAB, bool ShowInst);
1083 
1084 } // end namespace llvm
1085 
1086 #endif // LLVM_MC_MCSTREAMER_H
1087