Coverage Report

Created: 2018-11-13 17:19

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