MCStreamer.h revision 7768a9dce14431018133cd586f5c8ce3e057f069
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/SmallVector.h"
18#include "llvm/Support/DataTypes.h"
19#include "llvm/MC/MCDirectives.h"
20#include "llvm/MC/MCDwarf.h"
21
22namespace llvm {
23  class MCAsmInfo;
24  class MCCodeEmitter;
25  class MCContext;
26  class MCExpr;
27  class MCInst;
28  class MCInstPrinter;
29  class MCSection;
30  class MCSymbol;
31  class StringRef;
32  class TargetAsmBackend;
33  class TargetLoweringObjectFile;
34  class Twine;
35  class raw_ostream;
36  class formatted_raw_ostream;
37
38  /// MCStreamer - Streaming machine code generation interface.  This interface
39  /// is intended to provide a programatic interface that is very similar to the
40  /// level that an assembler .s file provides.  It has callbacks to emit bytes,
41  /// handle directives, etc.  The implementation of this interface retains
42  /// state to know what the current section is etc.
43  ///
44  /// There are multiple implementations of this interface: one for writing out
45  /// a .s file, and implementations that write out .o files of various formats.
46  ///
47  class MCStreamer {
48    MCContext &Context;
49
50    MCStreamer(const MCStreamer&); // DO NOT IMPLEMENT
51    MCStreamer &operator=(const MCStreamer&); // DO NOT IMPLEMENT
52
53    void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
54                         bool isPCRel, unsigned AddrSpace);
55
56    std::vector<MCDwarfFrameInfo> FrameInfos;
57    MCDwarfFrameInfo *getCurrentFrameInfo();
58    void EnsureValidFrame();
59
60    /// CurSectionStack - This is stack of CurSection values saved by
61    /// PushSection.
62    SmallVector<const MCSection *, 4> CurSectionStack;
63
64    /// PrevSectionStack - This is stack of PrevSection values saved by
65    /// PushSection.
66    SmallVector<const MCSection *, 4> PrevSectionStack;
67
68  protected:
69    MCStreamer(MCContext &Ctx);
70
71  public:
72    virtual ~MCStreamer();
73
74    MCContext &getContext() const { return Context; }
75
76    unsigned getNumFrameInfos() {
77      return FrameInfos.size();
78    }
79
80    const MCDwarfFrameInfo &getFrameInfo(unsigned i) {
81      return FrameInfos[i];
82    }
83
84    /// @name Assembly File Formatting.
85    /// @{
86
87    /// isVerboseAsm - Return true if this streamer supports verbose assembly
88    /// and if it is enabled.
89    virtual bool isVerboseAsm() const { return false; }
90
91    /// hasRawTextSupport - Return true if this asm streamer supports emitting
92    /// unformatted text to the .s file with EmitRawText.
93    virtual bool hasRawTextSupport() const { return false; }
94
95    /// AddComment - Add a comment that can be emitted to the generated .s
96    /// file if applicable as a QoI issue to make the output of the compiler
97    /// more readable.  This only affects the MCAsmStreamer, and only when
98    /// verbose assembly output is enabled.
99    ///
100    /// If the comment includes embedded \n's, they will each get the comment
101    /// prefix as appropriate.  The added comment should not end with a \n.
102    virtual void AddComment(const Twine &T) {}
103
104    /// GetCommentOS - Return a raw_ostream that comments can be written to.
105    /// Unlike AddComment, you are required to terminate comments with \n if you
106    /// use this method.
107    virtual raw_ostream &GetCommentOS();
108
109    /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
110    virtual void AddBlankLine() {}
111
112    /// @}
113
114    /// @name Symbol & Section Management
115    /// @{
116
117    /// getCurrentSection - Return the current section that the streamer is
118    /// emitting code to.
119    const MCSection *getCurrentSection() const {
120      if (!CurSectionStack.empty())
121        return CurSectionStack.back();
122      return NULL;
123    }
124
125    /// getPreviousSection - Return the previous section that the streamer is
126    /// emitting code to.
127    const MCSection *getPreviousSection() const {
128      if (!PrevSectionStack.empty())
129        return PrevSectionStack.back();
130      return NULL;
131    }
132
133    /// ChangeSection - Update streamer for a new active section.
134    ///
135    /// This is called by PopSection and SwitchSection, if the current
136    /// section changes.
137    virtual void ChangeSection(const MCSection *) = 0;
138
139    /// pushSection - Save the current and previous section on the
140    /// section stack.
141    void PushSection() {
142      PrevSectionStack.push_back(getPreviousSection());
143      CurSectionStack.push_back(getCurrentSection());
144    }
145
146    /// popSection - Restore the current and previous section from
147    /// the section stack.  Calls ChangeSection as needed.
148    ///
149    /// Returns false if the stack was empty.
150    bool PopSection() {
151      if (PrevSectionStack.size() <= 1)
152        return false;
153      assert(CurSectionStack.size() > 1);
154      PrevSectionStack.pop_back();
155      const MCSection *oldSection = CurSectionStack.pop_back_val();
156      const MCSection *curSection = CurSectionStack.back();
157
158      if (oldSection != curSection)
159        ChangeSection(curSection);
160      return true;
161    }
162
163    /// SwitchSection - Set the current section where code is being emitted to
164    /// @p Section.  This is required to update CurSection.
165    ///
166    /// This corresponds to assembler directives like .section, .text, etc.
167    void SwitchSection(const MCSection *Section) {
168      assert(Section && "Cannot switch to a null section!");
169      const MCSection *curSection = CurSectionStack.back();
170      PrevSectionStack.back() = curSection;
171      if (Section != curSection) {
172        CurSectionStack.back() = Section;
173        ChangeSection(Section);
174      }
175    }
176
177    /// InitSections - Create the default sections and set the initial one.
178    virtual void InitSections() = 0;
179
180    /// EmitLabel - Emit a label for @p Symbol into the current section.
181    ///
182    /// This corresponds to an assembler statement such as:
183    ///   foo:
184    ///
185    /// @param Symbol - The symbol to emit. A given symbol should only be
186    /// emitted as a label once, and symbols emitted as a label should never be
187    /// used in an assignment.
188    virtual void EmitLabel(MCSymbol *Symbol) = 0;
189
190    /// EmitAssemblerFlag - Note in the output the specified @p Flag
191    virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) = 0;
192
193    /// EmitThumbFunc - Note in the output that the specified @p Func is
194    /// a Thumb mode function (ARM target only).
195    virtual void EmitThumbFunc(MCSymbol *Func) = 0;
196
197    /// EmitAssignment - Emit an assignment of @p Value to @p Symbol.
198    ///
199    /// This corresponds to an assembler statement such as:
200    ///  symbol = value
201    ///
202    /// The assignment generates no code, but has the side effect of binding the
203    /// value in the current context. For the assembly streamer, this prints the
204    /// binding into the .s file.
205    ///
206    /// @param Symbol - The symbol being assigned to.
207    /// @param Value - The value for the symbol.
208    virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) = 0;
209
210    /// EmitWeakReference - Emit an weak reference from @p Alias to @p Symbol.
211    ///
212    /// This corresponds to an assembler statement such as:
213    ///  .weakref alias, symbol
214    ///
215    /// @param Alias - The alias that is being created.
216    /// @param Symbol - The symbol being aliased.
217    virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) = 0;
218
219    /// EmitSymbolAttribute - Add the given @p Attribute to @p Symbol.
220    virtual void EmitSymbolAttribute(MCSymbol *Symbol,
221                                     MCSymbolAttr Attribute) = 0;
222
223    /// EmitSymbolDesc - Set the @p DescValue for the @p Symbol.
224    ///
225    /// @param Symbol - The symbol to have its n_desc field set.
226    /// @param DescValue - The value to set into the n_desc field.
227    virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) = 0;
228
229    /// BeginCOFFSymbolDef - Start emitting COFF symbol definition
230    ///
231    /// @param Symbol - The symbol to have its External & Type fields set.
232    virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) = 0;
233
234    /// EmitCOFFSymbolStorageClass - Emit the storage class of the symbol.
235    ///
236    /// @param StorageClass - The storage class the symbol should have.
237    virtual void EmitCOFFSymbolStorageClass(int StorageClass) = 0;
238
239    /// EmitCOFFSymbolType - Emit the type of the symbol.
240    ///
241    /// @param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
242    virtual void EmitCOFFSymbolType(int Type) = 0;
243
244    /// EndCOFFSymbolDef - Marks the end of the symbol definition.
245    virtual void EndCOFFSymbolDef() = 0;
246
247    /// EmitELFSize - Emit an ELF .size directive.
248    ///
249    /// This corresponds to an assembler statement such as:
250    ///  .size symbol, expression
251    ///
252    virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) = 0;
253
254    /// EmitCommonSymbol - Emit a common symbol.
255    ///
256    /// @param Symbol - The common symbol to emit.
257    /// @param Size - The size of the common symbol.
258    /// @param ByteAlignment - The alignment of the symbol if
259    /// non-zero. This must be a power of 2.
260    virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261                                  unsigned ByteAlignment) = 0;
262
263    /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
264    ///
265    /// @param Symbol - The common symbol to emit.
266    /// @param Size - The size of the common symbol.
267    virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) = 0;
268
269    /// EmitZerofill - Emit the zerofill section and an optional symbol.
270    ///
271    /// @param Section - The zerofill section to create and or to put the symbol
272    /// @param Symbol - The zerofill symbol to emit, if non-NULL.
273    /// @param Size - The size of the zerofill symbol.
274    /// @param ByteAlignment - The alignment of the zerofill symbol if
275    /// non-zero. This must be a power of 2 on some targets.
276    virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
277                              unsigned Size = 0,unsigned ByteAlignment = 0) = 0;
278
279    /// EmitTBSSSymbol - Emit a thread local bss (.tbss) symbol.
280    ///
281    /// @param Section - The thread local common section.
282    /// @param Symbol - The thread local common symbol to emit.
283    /// @param Size - The size of the symbol.
284    /// @param ByteAlignment - The alignment of the thread local common symbol
285    /// if non-zero.  This must be a power of 2 on some targets.
286    virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
287                                uint64_t Size, unsigned ByteAlignment = 0) = 0;
288    /// @}
289    /// @name Generating Data
290    /// @{
291
292    /// EmitBytes - Emit the bytes in \arg Data into the output.
293    ///
294    /// This is used to implement assembler directives such as .byte, .ascii,
295    /// etc.
296    virtual void EmitBytes(StringRef Data, unsigned AddrSpace) = 0;
297
298    /// EmitValue - Emit the expression @p Value into the output as a native
299    /// integer of the given @p Size bytes.
300    ///
301    /// This is used to implement assembler directives such as .word, .quad,
302    /// etc.
303    ///
304    /// @param Value - The value to emit.
305    /// @param Size - The size of the integer (in bytes) to emit. This must
306    /// match a native machine width.
307    virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
308                               bool isPCRel, unsigned AddrSpace) = 0;
309
310    void EmitValue(const MCExpr *Value, unsigned Size, unsigned AddrSpace = 0);
311
312    void EmitPCRelValue(const MCExpr *Value, unsigned Size,
313                        unsigned AddrSpace = 0);
314
315    /// EmitIntValue - Special case of EmitValue that avoids the client having
316    /// to pass in a MCExpr for constant integers.
317    virtual void EmitIntValue(uint64_t Value, unsigned Size,
318                              unsigned AddrSpace = 0);
319
320    /// EmitAbsValue - Emit the Value, but try to avoid relocations. On MachO
321    /// this is done by producing
322    /// foo = value
323    /// .long foo
324    void EmitAbsValue(const MCExpr *Value, unsigned Size,
325                      unsigned AddrSpace = 0);
326
327    virtual void EmitULEB128Value(const MCExpr *Value,
328                                  unsigned AddrSpace = 0) = 0;
329
330    virtual void EmitSLEB128Value(const MCExpr *Value,
331                                  unsigned AddrSpace = 0) = 0;
332
333    /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
334    /// client having to pass in a MCExpr for constant integers.
335    void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace = 0);
336
337    /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
338    /// client having to pass in a MCExpr for constant integers.
339    void EmitSLEB128IntValue(int64_t Value, unsigned AddrSpace = 0);
340
341    /// EmitSymbolValue - Special case of EmitValue that avoids the client
342    /// having to pass in a MCExpr for MCSymbols.
343    void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
344                         unsigned AddrSpace = 0);
345
346    void EmitPCRelSymbolValue(const MCSymbol *Sym, unsigned Size,
347                              unsigned AddrSpace = 0);
348
349    /// EmitGPRel32Value - Emit the expression @p Value into the output as a
350    /// gprel32 (32-bit GP relative) value.
351    ///
352    /// This is used to implement assembler directives such as .gprel32 on
353    /// targets that support them.
354    virtual void EmitGPRel32Value(const MCExpr *Value);
355
356    /// EmitFill - Emit NumBytes bytes worth of the value specified by
357    /// FillValue.  This implements directives such as '.space'.
358    virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
359                          unsigned AddrSpace);
360
361    /// EmitZeros - Emit NumBytes worth of zeros.  This is a convenience
362    /// function that just wraps EmitFill.
363    void EmitZeros(uint64_t NumBytes, unsigned AddrSpace) {
364      EmitFill(NumBytes, 0, AddrSpace);
365    }
366
367
368    /// EmitValueToAlignment - Emit some number of copies of @p Value until
369    /// the byte alignment @p ByteAlignment is reached.
370    ///
371    /// If the number of bytes need to emit for the alignment is not a multiple
372    /// of @p ValueSize, then the contents of the emitted fill bytes is
373    /// undefined.
374    ///
375    /// This used to implement the .align assembler directive.
376    ///
377    /// @param ByteAlignment - The alignment to reach. This must be a power of
378    /// two on some targets.
379    /// @param Value - The value to use when filling bytes.
380    /// @param ValueSize - The size of the integer (in bytes) to emit for
381    /// @p Value. This must match a native machine width.
382    /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
383    /// the alignment cannot be reached in this many bytes, no bytes are
384    /// emitted.
385    virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
386                                      unsigned ValueSize = 1,
387                                      unsigned MaxBytesToEmit = 0) = 0;
388
389    /// EmitCodeAlignment - Emit nops until the byte alignment @p ByteAlignment
390    /// is reached.
391    ///
392    /// This used to align code where the alignment bytes may be executed.  This
393    /// can emit different bytes for different sizes to optimize execution.
394    ///
395    /// @param ByteAlignment - The alignment to reach. This must be a power of
396    /// two on some targets.
397    /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
398    /// the alignment cannot be reached in this many bytes, no bytes are
399    /// emitted.
400    virtual void EmitCodeAlignment(unsigned ByteAlignment,
401                                   unsigned MaxBytesToEmit = 0) = 0;
402
403    /// EmitValueToOffset - Emit some number of copies of @p Value until the
404    /// byte offset @p Offset is reached.
405    ///
406    /// This is used to implement assembler directives such as .org.
407    ///
408    /// @param Offset - The offset to reach. This may be an expression, but the
409    /// expression must be associated with the current section.
410    /// @param Value - The value to use when filling bytes.
411    virtual void EmitValueToOffset(const MCExpr *Offset,
412                                   unsigned char Value = 0) = 0;
413
414    /// @}
415
416    /// EmitFileDirective - Switch to a new logical file.  This is used to
417    /// implement the '.file "foo.c"' assembler directive.
418    virtual void EmitFileDirective(StringRef Filename) = 0;
419
420    /// EmitDwarfFileDirective - Associate a filename with a specified logical
421    /// file number.  This implements the DWARF2 '.file 4 "foo.c"' assembler
422    /// directive.
423    virtual bool EmitDwarfFileDirective(unsigned FileNo,StringRef Filename);
424
425    /// EmitDwarfLocDirective - This implements the DWARF2
426    // '.loc fileno lineno ...' assembler directive.
427    virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
428                                       unsigned Column, unsigned Flags,
429                                       unsigned Isa,
430                                       unsigned Discriminator);
431
432    virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
433                                          const MCSymbol *LastLabel,
434                                          const MCSymbol *Label) = 0;
435
436    virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
437                                           const MCSymbol *Label) {
438    }
439
440    void EmitDwarfSetLineAddr(int64_t LineDelta, const MCSymbol *Label,
441                              int PointerSize);
442
443    virtual bool EmitCFIStartProc();
444    virtual bool EmitCFIEndProc();
445    virtual bool EmitCFIDefCfa(int64_t Register, int64_t Offset);
446    virtual bool EmitCFIDefCfaOffset(int64_t Offset);
447    virtual bool EmitCFIDefCfaRegister(int64_t Register);
448    virtual bool EmitCFIOffset(int64_t Register, int64_t Offset);
449    virtual bool EmitCFIPersonality(const MCSymbol *Sym,
450                                    unsigned Encoding);
451    virtual bool EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
452    virtual bool EmitCFIRememberState();
453    virtual bool EmitCFIRestoreState();
454
455    /// EmitInstruction - Emit the given @p Instruction into the current
456    /// section.
457    virtual void EmitInstruction(const MCInst &Inst) = 0;
458
459    /// EmitRawText - If this file is backed by a assembly streamer, this dumps
460    /// the specified string in the output .s file.  This capability is
461    /// indicated by the hasRawTextSupport() predicate.  By default this aborts.
462    virtual void EmitRawText(StringRef String);
463    void EmitRawText(const Twine &String);
464
465    /// Finish - Finish emission of machine code.
466    virtual void Finish() = 0;
467  };
468
469  /// createNullStreamer - Create a dummy machine code streamer, which does
470  /// nothing. This is useful for timing the assembler front end.
471  MCStreamer *createNullStreamer(MCContext &Ctx);
472
473  /// createAsmStreamer - Create a machine code streamer which will print out
474  /// assembly for the native target, suitable for compiling with a native
475  /// assembler.
476  ///
477  /// \param InstPrint - If given, the instruction printer to use. If not given
478  /// the MCInst representation will be printed.  This method takes ownership of
479  /// InstPrint.
480  ///
481  /// \param CE - If given, a code emitter to use to show the instruction
482  /// encoding inline with the assembly. This method takes ownership of \arg CE.
483  ///
484  /// \param TAB - If given, a target asm backend to use to show the fixup
485  /// information in conjunction with encoding information. This method takes
486  /// ownership of \arg TAB.
487  ///
488  /// \param ShowInst - Whether to show the MCInst representation inline with
489  /// the assembly.
490  MCStreamer *createAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
491                                bool isVerboseAsm,
492                                bool useLoc,
493                                MCInstPrinter *InstPrint = 0,
494                                MCCodeEmitter *CE = 0,
495                                TargetAsmBackend *TAB = 0,
496                                bool ShowInst = false);
497
498  /// createMachOStreamer - Create a machine code streamer which will generate
499  /// Mach-O format object files.
500  ///
501  /// Takes ownership of \arg TAB and \arg CE.
502  MCStreamer *createMachOStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
503                                  raw_ostream &OS, MCCodeEmitter *CE,
504                                  bool RelaxAll = false);
505
506  /// createWinCOFFStreamer - Create a machine code streamer which will
507  /// generate Microsoft COFF format object files.
508  ///
509  /// Takes ownership of \arg TAB and \arg CE.
510  MCStreamer *createWinCOFFStreamer(MCContext &Ctx,
511                                    TargetAsmBackend &TAB,
512                                    MCCodeEmitter &CE, raw_ostream &OS,
513                                    bool RelaxAll = false);
514
515  /// createELFStreamer - Create a machine code streamer which will generate
516  /// ELF format object files.
517  MCStreamer *createELFStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
518				raw_ostream &OS, MCCodeEmitter *CE,
519				bool RelaxAll, bool NoExecStack);
520
521  /// createLoggingStreamer - Create a machine code streamer which just logs the
522  /// API calls and then dispatches to another streamer.
523  ///
524  /// The new streamer takes ownership of the \arg Child.
525  MCStreamer *createLoggingStreamer(MCStreamer *Child, raw_ostream &OS);
526
527  /// createPureStreamer - Create a machine code streamer which will generate
528  /// "pure" MC object files, for use with MC-JIT and testing tools.
529  ///
530  /// Takes ownership of \arg TAB and \arg CE.
531  MCStreamer *createPureStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
532                                 raw_ostream &OS, MCCodeEmitter *CE);
533
534} // end namespace llvm
535
536#endif
537