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