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