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