cf4a9e5edc73eb3b1fbb6870cedf40f9ce9d752d
[oota-llvm.git] / include / llvm / MC / MCStreamer.h
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
22 namespace 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     bool EmitEHFrame;
54     bool EmitDebugFrame;
55
56     std::vector<MCDwarfFrameInfo> FrameInfos;
57     MCDwarfFrameInfo *getCurrentFrameInfo();
58     void EnsureValidFrame();
59
60     const MCSymbol* LastNonPrivate;
61
62     /// SectionStack - This is stack of current and previous section
63     /// values saved by PushSection.
64     SmallVector<std::pair<const MCSection *,
65                 const MCSection *>, 4> SectionStack;
66
67   protected:
68     MCStreamer(MCContext &Ctx);
69
70     const MCExpr *BuildSymbolDiff(MCContext &Context, const MCSymbol *A,
71                                   const MCSymbol *B);
72
73     const MCExpr *ForceExpAbs(MCStreamer *Streamer, MCContext &Context,
74                               const MCExpr* Expr);
75
76     void EmitFrames(bool usingCFI);
77
78   public:
79     virtual ~MCStreamer();
80
81     MCContext &getContext() const { return Context; }
82
83     unsigned getNumFrameInfos() {
84       return FrameInfos.size();
85     }
86
87     const MCDwarfFrameInfo &getFrameInfo(unsigned i) {
88       return FrameInfos[i];
89     }
90
91     /// @name Assembly File Formatting.
92     /// @{
93
94     /// isVerboseAsm - Return true if this streamer supports verbose assembly
95     /// and if it is enabled.
96     virtual bool isVerboseAsm() const { return false; }
97
98     /// hasRawTextSupport - Return true if this asm streamer supports emitting
99     /// unformatted text to the .s file with EmitRawText.
100     virtual bool hasRawTextSupport() const { return false; }
101
102     /// AddComment - Add a comment that can be emitted to the generated .s
103     /// file if applicable as a QoI issue to make the output of the compiler
104     /// more readable.  This only affects the MCAsmStreamer, and only when
105     /// verbose assembly output is enabled.
106     ///
107     /// If the comment includes embedded \n's, they will each get the comment
108     /// prefix as appropriate.  The added comment should not end with a \n.
109     virtual void AddComment(const Twine &T) {}
110
111     /// GetCommentOS - Return a raw_ostream that comments can be written to.
112     /// Unlike AddComment, you are required to terminate comments with \n if you
113     /// use this method.
114     virtual raw_ostream &GetCommentOS();
115
116     /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
117     virtual void AddBlankLine() {}
118
119     /// @}
120
121     /// @name Symbol & Section Management
122     /// @{
123
124     /// getCurrentSection - Return the current section that the streamer is
125     /// emitting code to.
126     const MCSection *getCurrentSection() const {
127       if (!SectionStack.empty())
128         return SectionStack.back().first;
129       return NULL;
130     }
131
132     /// getPreviousSection - Return the previous section that the streamer is
133     /// emitting code to.
134     const MCSection *getPreviousSection() const {
135       if (!SectionStack.empty())
136         return SectionStack.back().second;
137       return NULL;
138     }
139
140     /// ChangeSection - Update streamer for a new active section.
141     ///
142     /// This is called by PopSection and SwitchSection, if the current
143     /// section changes.
144     virtual void ChangeSection(const MCSection *) = 0;
145
146     /// pushSection - Save the current and previous section on the
147     /// section stack.
148     void PushSection() {
149       SectionStack.push_back(std::make_pair(getCurrentSection(),
150                                             getPreviousSection()));
151     }
152
153     /// popSection - Restore the current and previous section from
154     /// the section stack.  Calls ChangeSection as needed.
155     ///
156     /// Returns false if the stack was empty.
157     bool PopSection() {
158       if (SectionStack.size() <= 1)
159         return false;
160       const MCSection *oldSection = SectionStack.pop_back_val().first;
161       const MCSection *curSection = SectionStack.back().first;
162
163       if (oldSection != curSection)
164         ChangeSection(curSection);
165       return true;
166     }
167
168     /// SwitchSection - Set the current section where code is being emitted to
169     /// @p Section.  This is required to update CurSection.
170     ///
171     /// This corresponds to assembler directives like .section, .text, etc.
172     void SwitchSection(const MCSection *Section) {
173       assert(Section && "Cannot switch to a null section!");
174       const MCSection *curSection = SectionStack.back().first;
175       SectionStack.back().second = curSection;
176       if (Section != curSection) {
177         SectionStack.back().first = Section;
178         ChangeSection(Section);
179       }
180     }
181
182     /// InitSections - Create the default sections and set the initial one.
183     virtual void InitSections() = 0;
184
185     /// EmitLabel - Emit a label for @p Symbol into the current section.
186     ///
187     /// This corresponds to an assembler statement such as:
188     ///   foo:
189     ///
190     /// @param Symbol - The symbol to emit. A given symbol should only be
191     /// emitted as a label once, and symbols emitted as a label should never be
192     /// used in an assignment.
193     virtual void EmitLabel(MCSymbol *Symbol);
194
195     virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
196                                      MCSymbol *EHSymbol);
197
198     /// EmitAssemblerFlag - Note in the output the specified @p Flag
199     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) = 0;
200
201     /// EmitThumbFunc - Note in the output that the specified @p Func is
202     /// a Thumb mode function (ARM target only).
203     virtual void EmitThumbFunc(MCSymbol *Func) = 0;
204
205     /// EmitAssignment - Emit an assignment of @p Value to @p Symbol.
206     ///
207     /// This corresponds to an assembler statement such as:
208     ///  symbol = value
209     ///
210     /// The assignment generates no code, but has the side effect of binding the
211     /// value in the current context. For the assembly streamer, this prints the
212     /// binding into the .s file.
213     ///
214     /// @param Symbol - The symbol being assigned to.
215     /// @param Value - The value for the symbol.
216     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) = 0;
217
218     /// EmitWeakReference - Emit an weak reference from @p Alias to @p Symbol.
219     ///
220     /// This corresponds to an assembler statement such as:
221     ///  .weakref alias, symbol
222     ///
223     /// @param Alias - The alias that is being created.
224     /// @param Symbol - The symbol being aliased.
225     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) = 0;
226
227     /// EmitSymbolAttribute - Add the given @p Attribute to @p Symbol.
228     virtual void EmitSymbolAttribute(MCSymbol *Symbol,
229                                      MCSymbolAttr Attribute) = 0;
230
231     /// EmitSymbolDesc - Set the @p DescValue for the @p Symbol.
232     ///
233     /// @param Symbol - The symbol to have its n_desc field set.
234     /// @param DescValue - The value to set into the n_desc field.
235     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) = 0;
236
237     /// BeginCOFFSymbolDef - Start emitting COFF symbol definition
238     ///
239     /// @param Symbol - The symbol to have its External & Type fields set.
240     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) = 0;
241
242     /// EmitCOFFSymbolStorageClass - Emit the storage class of the symbol.
243     ///
244     /// @param StorageClass - The storage class the symbol should have.
245     virtual void EmitCOFFSymbolStorageClass(int StorageClass) = 0;
246
247     /// EmitCOFFSymbolType - Emit the type of the symbol.
248     ///
249     /// @param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
250     virtual void EmitCOFFSymbolType(int Type) = 0;
251
252     /// EndCOFFSymbolDef - Marks the end of the symbol definition.
253     virtual void EndCOFFSymbolDef() = 0;
254
255     /// EmitELFSize - Emit an ELF .size directive.
256     ///
257     /// This corresponds to an assembler statement such as:
258     ///  .size symbol, expression
259     ///
260     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) = 0;
261
262     /// EmitCommonSymbol - Emit a common symbol.
263     ///
264     /// @param Symbol - The common symbol to emit.
265     /// @param Size - The size of the common symbol.
266     /// @param ByteAlignment - The alignment of the symbol if
267     /// non-zero. This must be a power of 2.
268     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
269                                   unsigned ByteAlignment) = 0;
270
271     /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
272     ///
273     /// @param Symbol - The common symbol to emit.
274     /// @param Size - The size of the common symbol.
275     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) = 0;
276
277     /// EmitZerofill - Emit the zerofill section and an optional symbol.
278     ///
279     /// @param Section - The zerofill section to create and or to put the symbol
280     /// @param Symbol - The zerofill symbol to emit, if non-NULL.
281     /// @param Size - The size of the zerofill symbol.
282     /// @param ByteAlignment - The alignment of the zerofill symbol if
283     /// non-zero. This must be a power of 2 on some targets.
284     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
285                               unsigned Size = 0,unsigned ByteAlignment = 0) = 0;
286
287     /// EmitTBSSSymbol - Emit a thread local bss (.tbss) symbol.
288     ///
289     /// @param Section - The thread local common section.
290     /// @param Symbol - The thread local common symbol to emit.
291     /// @param Size - The size of the symbol.
292     /// @param ByteAlignment - The alignment of the thread local common symbol
293     /// if non-zero.  This must be a power of 2 on some targets.
294     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
295                                 uint64_t Size, unsigned ByteAlignment = 0) = 0;
296     /// @}
297     /// @name Generating Data
298     /// @{
299
300     /// EmitBytes - Emit the bytes in \arg Data into the output.
301     ///
302     /// This is used to implement assembler directives such as .byte, .ascii,
303     /// etc.
304     virtual void EmitBytes(StringRef Data, unsigned AddrSpace) = 0;
305
306     /// EmitValue - Emit the expression @p Value into the output as a native
307     /// integer of the given @p Size bytes.
308     ///
309     /// This is used to implement assembler directives such as .word, .quad,
310     /// etc.
311     ///
312     /// @param Value - The value to emit.
313     /// @param Size - The size of the integer (in bytes) to emit. This must
314     /// match a native machine width.
315     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
316                                unsigned AddrSpace) = 0;
317
318     void EmitValue(const MCExpr *Value, unsigned Size, unsigned AddrSpace = 0);
319
320     /// EmitIntValue - Special case of EmitValue that avoids the client having
321     /// to pass in a MCExpr for constant integers.
322     virtual void EmitIntValue(uint64_t Value, unsigned Size,
323                               unsigned AddrSpace = 0);
324
325     /// EmitAbsValue - Emit the Value, but try to avoid relocations. On MachO
326     /// this is done by producing
327     /// foo = value
328     /// .long foo
329     void EmitAbsValue(const MCExpr *Value, unsigned Size,
330                       unsigned AddrSpace = 0);
331
332     virtual void EmitULEB128Value(const MCExpr *Value) = 0;
333
334     virtual void EmitSLEB128Value(const MCExpr *Value) = 0;
335
336     /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
337     /// client having to pass in a MCExpr for constant integers.
338     void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace = 0);
339
340     /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
341     /// client having to pass in a MCExpr for constant integers.
342     void EmitSLEB128IntValue(int64_t Value, unsigned AddrSpace = 0);
343
344     /// EmitSymbolValue - Special case of EmitValue that avoids the client
345     /// having to pass in a MCExpr for MCSymbols.
346     void EmitSymbolValue(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                                        StringRef FileName);
432
433     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
434                                           const MCSymbol *LastLabel,
435                                           const MCSymbol *Label) = 0;
436
437     virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
438                                            const MCSymbol *Label) {
439     }
440
441     void EmitDwarfSetLineAddr(int64_t LineDelta, const MCSymbol *Label,
442                               int PointerSize);
443
444     virtual void EmitCFISections(bool EH, bool Debug);
445     virtual void EmitCFIStartProc();
446     virtual void EmitCFIEndProc();
447     virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
448     virtual void EmitCFIDefCfaOffset(int64_t Offset);
449     virtual void EmitCFIDefCfaRegister(int64_t Register);
450     virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
451     virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
452     virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
453     virtual void EmitCFIRememberState();
454     virtual void EmitCFIRestoreState();
455     virtual void EmitCFISameValue(int64_t Register);
456     virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
457     virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
458
459     /// EmitInstruction - Emit the given @p Instruction into the current
460     /// section.
461     virtual void EmitInstruction(const MCInst &Inst) = 0;
462
463     /// EmitRawText - If this file is backed by a assembly streamer, this dumps
464     /// the specified string in the output .s file.  This capability is
465     /// indicated by the hasRawTextSupport() predicate.  By default this aborts.
466     virtual void EmitRawText(StringRef String);
467     void EmitRawText(const Twine &String);
468
469     /// ARM-related methods.
470     /// FIXME: Eventually we should have some "target MC streamer" and move
471     /// these methods there.
472     virtual void EmitFnStart();
473     virtual void EmitFnEnd();
474     virtual void EmitCantUnwind();
475     virtual void EmitPersonality(const MCSymbol *Personality);
476     virtual void EmitHandlerData();
477     virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
478     virtual void EmitPad(int64_t Offset);
479     virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
480                              bool isVector);
481
482     /// Finish - Finish emission of machine code.
483     virtual void Finish() = 0;
484   };
485
486   /// createNullStreamer - Create a dummy machine code streamer, which does
487   /// nothing. This is useful for timing the assembler front end.
488   MCStreamer *createNullStreamer(MCContext &Ctx);
489
490   /// createAsmStreamer - Create a machine code streamer which will print out
491   /// assembly for the native target, suitable for compiling with a native
492   /// assembler.
493   ///
494   /// \param InstPrint - If given, the instruction printer to use. If not given
495   /// the MCInst representation will be printed.  This method takes ownership of
496   /// InstPrint.
497   ///
498   /// \param CE - If given, a code emitter to use to show the instruction
499   /// encoding inline with the assembly. This method takes ownership of \arg CE.
500   ///
501   /// \param TAB - If given, a target asm backend to use to show the fixup
502   /// information in conjunction with encoding information. This method takes
503   /// ownership of \arg TAB.
504   ///
505   /// \param ShowInst - Whether to show the MCInst representation inline with
506   /// the assembly.
507   MCStreamer *createAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
508                                 bool isVerboseAsm,
509                                 bool useLoc,
510                                 bool useCFI,
511                                 MCInstPrinter *InstPrint = 0,
512                                 MCCodeEmitter *CE = 0,
513                                 TargetAsmBackend *TAB = 0,
514                                 bool ShowInst = false);
515
516   /// createMachOStreamer - Create a machine code streamer which will generate
517   /// Mach-O format object files.
518   ///
519   /// Takes ownership of \arg TAB and \arg CE.
520   MCStreamer *createMachOStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
521                                   raw_ostream &OS, MCCodeEmitter *CE,
522                                   bool RelaxAll = false);
523
524   /// createWinCOFFStreamer - Create a machine code streamer which will
525   /// generate Microsoft COFF format object files.
526   ///
527   /// Takes ownership of \arg TAB and \arg CE.
528   MCStreamer *createWinCOFFStreamer(MCContext &Ctx,
529                                     TargetAsmBackend &TAB,
530                                     MCCodeEmitter &CE, raw_ostream &OS,
531                                     bool RelaxAll = false);
532
533   /// createELFStreamer - Create a machine code streamer which will generate
534   /// ELF format object files.
535   MCStreamer *createELFStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
536                                 raw_ostream &OS, MCCodeEmitter *CE,
537                                 bool RelaxAll, bool NoExecStack);
538
539   /// createLoggingStreamer - Create a machine code streamer which just logs the
540   /// API calls and then dispatches to another streamer.
541   ///
542   /// The new streamer takes ownership of the \arg Child.
543   MCStreamer *createLoggingStreamer(MCStreamer *Child, raw_ostream &OS);
544
545   /// createPureStreamer - Create a machine code streamer which will generate
546   /// "pure" MC object files, for use with MC-JIT and testing tools.
547   ///
548   /// Takes ownership of \arg TAB and \arg CE.
549   MCStreamer *createPureStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
550                                  raw_ostream &OS, MCCodeEmitter *CE);
551
552 } // end namespace llvm
553
554 #endif