1//===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- 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 contains a class to be used as the base class for target specific
11// asm writers.  This class primarily handles common functionality used by
12// all asm writers.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CODEGEN_ASMPRINTER_H
17#define LLVM_CODEGEN_ASMPRINTER_H
18
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/Support/DataTypes.h"
21#include "llvm/Support/ErrorHandling.h"
22
23namespace llvm {
24  class BlockAddress;
25  class GCStrategy;
26  class Constant;
27  class GCMetadataPrinter;
28  class GlobalValue;
29  class GlobalVariable;
30  class MachineBasicBlock;
31  class MachineFunction;
32  class MachineInstr;
33  class MachineLocation;
34  class MachineLoopInfo;
35  class MachineLoop;
36  class MachineConstantPoolValue;
37  class MachineJumpTableInfo;
38  class MachineModuleInfo;
39  class MachineMove;
40  class MCAsmInfo;
41  class MCContext;
42  class MCSection;
43  class MCStreamer;
44  class MCSymbol;
45  class MDNode;
46  class DwarfDebug;
47  class DwarfException;
48  class Mangler;
49  class TargetLoweringObjectFile;
50  class TargetData;
51  class TargetMachine;
52
53  /// AsmPrinter - This class is intended to be used as a driving class for all
54  /// asm writers.
55  class AsmPrinter : public MachineFunctionPass {
56  public:
57    /// Target machine description.
58    ///
59    TargetMachine &TM;
60
61    /// Target Asm Printer information.
62    ///
63    const MCAsmInfo *MAI;
64
65    /// OutContext - This is the context for the output file that we are
66    /// streaming.  This owns all of the global MC-related objects for the
67    /// generated translation unit.
68    MCContext &OutContext;
69
70    /// OutStreamer - This is the MCStreamer object for the file we are
71    /// generating.  This contains the transient state for the current
72    /// translation unit that we are generating (such as the current section
73    /// etc).
74    MCStreamer &OutStreamer;
75
76    /// The current machine function.
77    const MachineFunction *MF;
78
79    /// MMI - This is a pointer to the current MachineModuleInfo.
80    MachineModuleInfo *MMI;
81
82    /// Name-mangler for global names.
83    ///
84    Mangler *Mang;
85
86    /// The symbol for the current function. This is recalculated at the
87    /// beginning of each call to runOnMachineFunction().
88    ///
89    MCSymbol *CurrentFnSym;
90
91    /// The symbol used to represent the start of the current function for the
92    /// purpose of calculating its size (e.g. using the .size directive). By
93    /// default, this is equal to CurrentFnSym.
94    MCSymbol *CurrentFnSymForSize;
95
96  private:
97    // GCMetadataPrinters - The garbage collection metadata printer table.
98    void *GCMetadataPrinters;  // Really a DenseMap.
99
100    /// VerboseAsm - Emit comments in assembly output if this is true.
101    ///
102    bool VerboseAsm;
103    static char ID;
104
105    /// If VerboseAsm is set, a pointer to the loop info for this
106    /// function.
107    MachineLoopInfo *LI;
108
109    /// DD - If the target supports dwarf debug info, this pointer is non-null.
110    DwarfDebug *DD;
111
112    /// DE - If the target supports dwarf exception info, this pointer is
113    /// non-null.
114    DwarfException *DE;
115
116  protected:
117    explicit AsmPrinter(TargetMachine &TM, MCStreamer &Streamer);
118
119  public:
120    virtual ~AsmPrinter();
121
122    /// isVerbose - Return true if assembly output should contain comments.
123    ///
124    bool isVerbose() const { return VerboseAsm; }
125
126    /// getFunctionNumber - Return a unique ID for the current function.
127    ///
128    unsigned getFunctionNumber() const;
129
130    /// getObjFileLowering - Return information about object file lowering.
131    const TargetLoweringObjectFile &getObjFileLowering() const;
132
133    /// getTargetData - Return information about data layout.
134    const TargetData &getTargetData() const;
135
136    /// getCurrentSection() - Return the current section we are emitting to.
137    const MCSection *getCurrentSection() const;
138
139
140    //===------------------------------------------------------------------===//
141    // MachineFunctionPass Implementation.
142    //===------------------------------------------------------------------===//
143
144    /// getAnalysisUsage - Record analysis usage.
145    ///
146    void getAnalysisUsage(AnalysisUsage &AU) const;
147
148    /// doInitialization - Set up the AsmPrinter when we are working on a new
149    /// module.  If your pass overrides this, it must make sure to explicitly
150    /// call this implementation.
151    bool doInitialization(Module &M);
152
153    /// doFinalization - Shut down the asmprinter.  If you override this in your
154    /// pass, you must make sure to call it explicitly.
155    bool doFinalization(Module &M);
156
157    /// runOnMachineFunction - Emit the specified function out to the
158    /// OutStreamer.
159    virtual bool runOnMachineFunction(MachineFunction &MF) {
160      SetupMachineFunction(MF);
161      EmitFunctionHeader();
162      EmitFunctionBody();
163      return false;
164    }
165
166    //===------------------------------------------------------------------===//
167    // Coarse grained IR lowering routines.
168    //===------------------------------------------------------------------===//
169
170    /// SetupMachineFunction - This should be called when a new MachineFunction
171    /// is being processed from runOnMachineFunction.
172    void SetupMachineFunction(MachineFunction &MF);
173
174    /// EmitFunctionHeader - This method emits the header for the current
175    /// function.
176    void EmitFunctionHeader();
177
178    /// EmitFunctionBody - This method emits the body and trailer for a
179    /// function.
180    void EmitFunctionBody();
181
182    void emitPrologLabel(const MachineInstr &MI);
183
184    enum CFIMoveType {
185      CFI_M_None,
186      CFI_M_EH,
187      CFI_M_Debug
188    };
189    CFIMoveType needsCFIMoves();
190
191    bool needsSEHMoves();
192
193    /// needsRelocationsForDwarfStringPool - Specifies whether the object format
194    /// expects to use relocations to refer to debug entries. Alternatively we
195    /// emit section offsets in bytes from the start of the string pool.
196    bool needsRelocationsForDwarfStringPool() const;
197
198    /// EmitConstantPool - Print to the current output stream assembly
199    /// representations of the constants in the constant pool MCP. This is
200    /// used to print out constants which have been "spilled to memory" by
201    /// the code generator.
202    ///
203    virtual void EmitConstantPool();
204
205    /// EmitJumpTableInfo - Print assembly representations of the jump tables
206    /// used by the current function to the current output stream.
207    ///
208    void EmitJumpTableInfo();
209
210    /// EmitGlobalVariable - Emit the specified global variable to the .s file.
211    virtual void EmitGlobalVariable(const GlobalVariable *GV);
212
213    /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
214    /// special global used by LLVM.  If so, emit it and return true, otherwise
215    /// do nothing and return false.
216    bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
217
218    /// EmitAlignment - Emit an alignment directive to the specified power of
219    /// two boundary.  For example, if you pass in 3 here, you will get an 8
220    /// byte alignment.  If a global value is specified, and if that global has
221    /// an explicit alignment requested, it will override the alignment request
222    /// if required for correctness.
223    ///
224    void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const;
225
226    /// EmitBasicBlockStart - This method prints the label for the specified
227    /// MachineBasicBlock, an alignment (if present) and a comment describing
228    /// it if appropriate.
229    void EmitBasicBlockStart(const MachineBasicBlock *MBB) const;
230
231    /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
232    void EmitGlobalConstant(const Constant *CV, unsigned AddrSpace = 0);
233
234
235    //===------------------------------------------------------------------===//
236    // Overridable Hooks
237    //===------------------------------------------------------------------===//
238
239    // Targets can, or in the case of EmitInstruction, must implement these to
240    // customize output.
241
242    /// EmitStartOfAsmFile - This virtual method can be overridden by targets
243    /// that want to emit something at the start of their file.
244    virtual void EmitStartOfAsmFile(Module &) {}
245
246    /// EmitEndOfAsmFile - This virtual method can be overridden by targets that
247    /// want to emit something at the end of their file.
248    virtual void EmitEndOfAsmFile(Module &) {}
249
250    /// EmitFunctionBodyStart - Targets can override this to emit stuff before
251    /// the first basic block in the function.
252    virtual void EmitFunctionBodyStart() {}
253
254    /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
255    /// the last basic block in the function.
256    virtual void EmitFunctionBodyEnd() {}
257
258    /// EmitInstruction - Targets should implement this to emit instructions.
259    virtual void EmitInstruction(const MachineInstr *) {
260      llvm_unreachable("EmitInstruction not implemented");
261    }
262
263    virtual void EmitFunctionEntryLabel();
264
265    virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
266
267    /// EmitXXStructor - Targets can override this to change how global
268    /// constants that are part of a C++ static/global constructor list are
269    /// emitted.
270    virtual void EmitXXStructor(const Constant *CV) {
271      EmitGlobalConstant(CV);
272    }
273
274    /// isBlockOnlyReachableByFallthough - Return true if the basic block has
275    /// exactly one predecessor and the control transfer mechanism between
276    /// the predecessor and this block is a fall-through.
277    virtual bool
278    isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
279
280    //===------------------------------------------------------------------===//
281    // Symbol Lowering Routines.
282    //===------------------------------------------------------------------===//
283  public:
284
285    /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
286    /// temporary label with the specified stem and unique ID.
287    MCSymbol *GetTempSymbol(StringRef Name, unsigned ID) const;
288
289    /// GetTempSymbol - Return an assembler temporary label with the specified
290    /// stem.
291    MCSymbol *GetTempSymbol(StringRef Name) const;
292
293
294    /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
295    /// global value name as its base, with the specified suffix, and where the
296    /// symbol is forced to have private linkage if ForcePrivate is true.
297    MCSymbol *GetSymbolWithGlobalValueBase(const GlobalValue *GV,
298                                           StringRef Suffix,
299                                           bool ForcePrivate = true) const;
300
301    /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
302    /// ExternalSymbol.
303    MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
304
305    /// GetCPISymbol - Return the symbol for the specified constant pool entry.
306    MCSymbol *GetCPISymbol(unsigned CPID) const;
307
308    /// GetJTISymbol - Return the symbol for the specified jump table entry.
309    MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
310
311    /// GetJTSetSymbol - Return the symbol for the specified jump table .set
312    /// FIXME: privatize to AsmPrinter.
313    MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
314
315    /// GetBlockAddressSymbol - Return the MCSymbol used to satisfy BlockAddress
316    /// uses of the specified basic block.
317    MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
318    MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
319
320    //===------------------------------------------------------------------===//
321    // Emission Helper Routines.
322    //===------------------------------------------------------------------===//
323  public:
324    /// printOffset - This is just convenient handler for printing offsets.
325    void printOffset(int64_t Offset, raw_ostream &OS) const;
326
327    /// EmitInt8 - Emit a byte directive and value.
328    ///
329    void EmitInt8(int Value) const;
330
331    /// EmitInt16 - Emit a short directive and value.
332    ///
333    void EmitInt16(int Value) const;
334
335    /// EmitInt32 - Emit a long directive and value.
336    ///
337    void EmitInt32(int Value) const;
338
339    /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
340    /// in bytes of the directive is specified by Size and Hi/Lo specify the
341    /// labels.  This implicitly uses .set if it is available.
342    void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
343                             unsigned Size) const;
344
345    /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
346    /// where the size in bytes of the directive is specified by Size and Hi/Lo
347    /// specify the labels.  This implicitly uses .set if it is available.
348    void EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
349                                   const MCSymbol *Lo, unsigned Size) const;
350
351    /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
352    /// where the size in bytes of the directive is specified by Size and Label
353    /// specifies the label.  This implicitly uses .set if it is available.
354    void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
355                                   unsigned Size) const;
356
357    //===------------------------------------------------------------------===//
358    // Dwarf Emission Helper Routines
359    //===------------------------------------------------------------------===//
360
361    /// EmitSLEB128 - emit the specified signed leb128 value.
362    void EmitSLEB128(int Value, const char *Desc = 0) const;
363
364    /// EmitULEB128 - emit the specified unsigned leb128 value.
365    void EmitULEB128(unsigned Value, const char *Desc = 0,
366                     unsigned PadTo = 0) const;
367
368    /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
369    void EmitCFAByte(unsigned Val) const;
370
371    /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
372    /// encoding.  If verbose assembly output is enabled, we output comments
373    /// describing the encoding.  Desc is a string saying what the encoding is
374    /// specifying (e.g. "LSDA").
375    void EmitEncodingByte(unsigned Val, const char *Desc = 0) const;
376
377    /// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
378    unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
379
380    /// EmitReference - Emit a reference to a label with a specified encoding.
381    ///
382    void EmitReference(const MCSymbol *Sym, unsigned Encoding) const;
383    void EmitReference(const GlobalValue *GV, unsigned Encoding) const;
384
385    /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of
386    /// its section.  This can be done with a special directive if the target
387    /// supports it (e.g. cygwin) or by emitting it as an offset from a label at
388    /// the start of the section.
389    ///
390    /// SectionLabel is a temporary label emitted at the start of the section
391    /// that Label lives in.
392    void EmitSectionOffset(const MCSymbol *Label,
393                           const MCSymbol *SectionLabel) const;
394
395    /// getDebugValueLocation - Get location information encoded by DBG_VALUE
396    /// operands.
397    virtual MachineLocation getDebugValueLocation(const MachineInstr *MI) const;
398
399    /// getISAEncoding - Get the value for DW_AT_APPLE_isa. Zero if no isa
400    /// encoding specified.
401    virtual unsigned getISAEncoding() { return 0; }
402
403    /// EmitDwarfRegOp - Emit dwarf register operation.
404    virtual void EmitDwarfRegOp(const MachineLocation &MLoc) const;
405
406    //===------------------------------------------------------------------===//
407    // Dwarf Lowering Routines
408    //===------------------------------------------------------------------===//
409
410    /// EmitCFIFrameMove - Emit frame instruction to describe the layout of the
411    /// frame.
412    void EmitCFIFrameMove(const MachineMove &Move) const;
413
414    //===------------------------------------------------------------------===//
415    // Inline Asm Support
416    //===------------------------------------------------------------------===//
417  public:
418    // These are hooks that targets can override to implement inline asm
419    // support.  These should probably be moved out of AsmPrinter someday.
420
421    /// PrintSpecial - Print information related to the specified machine instr
422    /// that is independent of the operand, and may be independent of the instr
423    /// itself.  This can be useful for portably encoding the comment character
424    /// or other bits of target-specific knowledge into the asmstrings.  The
425    /// syntax used is ${:comment}.  Targets can override this to add support
426    /// for their own strange codes.
427    virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
428                              const char *Code) const;
429
430    /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
431    /// instruction, using the specified assembler variant.  Targets should
432    /// override this to format as appropriate.  This method can return true if
433    /// the operand is erroneous.
434    virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
435                                 unsigned AsmVariant, const char *ExtraCode,
436                                 raw_ostream &OS);
437
438    /// PrintAsmMemoryOperand - Print the specified operand of MI, an INLINEASM
439    /// instruction, using the specified assembler variant as an address.
440    /// Targets should override this to format as appropriate.  This method can
441    /// return true if the operand is erroneous.
442    virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
443                                       unsigned AsmVariant,
444                                       const char *ExtraCode,
445                                       raw_ostream &OS);
446
447  private:
448    /// Private state for PrintSpecial()
449    // Assign a unique ID to this machine instruction.
450    mutable const MachineInstr *LastMI;
451    mutable unsigned LastFn;
452    mutable unsigned Counter;
453    mutable unsigned SetCounter;
454
455    /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
456    void EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = 0) const;
457
458    /// EmitInlineAsm - This method formats and emits the specified machine
459    /// instruction that is an inline asm.
460    void EmitInlineAsm(const MachineInstr *MI) const;
461
462    //===------------------------------------------------------------------===//
463    // Internal Implementation Details
464    //===------------------------------------------------------------------===//
465
466    /// EmitVisibility - This emits visibility information about symbol, if
467    /// this is suported by the target.
468    void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
469                        bool IsDefinition = true) const;
470
471    void EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const;
472
473    void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
474                            const MachineBasicBlock *MBB,
475                            unsigned uid) const;
476    void EmitLLVMUsedList(const Constant *List);
477    void EmitXXStructorList(const Constant *List, bool isCtor);
478    GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
479  };
480}
481
482#endif
483