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