1 //===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_ASMPRINTER_H
17 #define LLVM_CODEGEN_ASMPRINTER_H
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"
26 class AsmPrinterHandler;
32 class GCMetadataPrinter;
35 class MachineBasicBlock;
36 class MachineFunction;
38 class MachineLocation;
39 class MachineLoopInfo;
41 class MachineConstantPoolValue;
42 class MachineJumpTableInfo;
43 class MachineModuleInfo;
45 class MCCFIInstruction;
52 class MCSubtargetInfo;
57 class TargetLoweringObjectFile;
61 /// This class is intended to be used as a driving class for all asm writers.
62 class AsmPrinter : public MachineFunctionPass {
64 /// Target machine description.
68 /// Target Asm Printer information.
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;
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;
82 /// The current machine function.
83 const MachineFunction *MF;
85 /// This is a pointer to the current MachineModuleInfo.
86 MachineModuleInfo *MMI;
88 /// Name-mangler for global names.
92 /// The symbol for the current function. This is recalculated at the beginning
93 /// of each call to runOnMachineFunction().
95 MCSymbol *CurrentFnSym;
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;
103 // The garbage collection metadata printer table.
104 void *GCMetadataPrinters; // Really a DenseMap.
106 /// Emit comments in assembly output if this is true.
111 /// If VerboseAsm is set, a pointer to the loop info for this function.
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) {}
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;
126 /// If the target supports dwarf debug info, this pointer is non-null.
130 explicit AsmPrinter(TargetMachine &TM, MCStreamer &Streamer);
133 virtual ~AsmPrinter();
135 DwarfDebug *getDwarfDebug() { return DD; }
136 DwarfDebug *getDwarfDebug() const { return DD; }
138 /// Return true if assembly output should contain comments.
140 bool isVerbose() const { return VerboseAsm; }
142 /// Return a unique ID for the current function.
144 unsigned getFunctionNumber() const;
146 /// Return information about object file lowering.
147 const TargetLoweringObjectFile &getObjFileLowering() const;
149 /// Return information about data layout.
150 const DataLayout &getDataLayout() const;
152 /// Return information about subtarget.
153 const MCSubtargetInfo &getSubtargetInfo() const;
155 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
157 /// Return the target triple string.
158 StringRef getTargetTriple() const;
160 /// Return the current section we are emitting to.
161 const MCSection *getCurrentSection() const;
163 void getNameWithPrefix(SmallVectorImpl<char> &Name,
164 const GlobalValue *GV) const;
166 MCSymbol *getSymbol(const GlobalValue *GV) const;
168 //===------------------------------------------------------------------===//
169 // MachineFunctionPass Implementation.
170 //===------------------------------------------------------------------===//
172 /// Record analysis usage.
174 void getAnalysisUsage(AnalysisUsage &AU) const override;
176 /// Set up the AsmPrinter when we are working on a new module. If your pass
177 /// overrides this, it must make sure to explicitly call this implementation.
178 bool doInitialization(Module &M) override;
180 /// Shut down the asmprinter. If you override this in your pass, you must make
181 /// sure to call it explicitly.
182 bool doFinalization(Module &M) override;
184 /// Emit the specified function out to the OutStreamer.
185 bool runOnMachineFunction(MachineFunction &MF) override {
186 SetupMachineFunction(MF);
187 EmitFunctionHeader();
192 //===------------------------------------------------------------------===//
193 // Coarse grained IR lowering routines.
194 //===------------------------------------------------------------------===//
196 /// This should be called when a new MachineFunction is being processed from
197 /// runOnMachineFunction.
198 void SetupMachineFunction(MachineFunction &MF);
200 /// This method emits the header for the current function.
201 void EmitFunctionHeader();
203 /// This method emits the body and trailer for a function.
204 void EmitFunctionBody();
206 void emitCFIInstruction(const MachineInstr &MI);
208 enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
209 CFIMoveType needsCFIMoves();
211 bool needsSEHMoves();
213 /// Print to the current output stream assembly representations of the
214 /// constants in the constant pool MCP. This is used to print out constants
215 /// which have been "spilled to memory" by the code generator.
217 virtual void EmitConstantPool();
219 /// Print assembly representations of the jump tables used by the current
220 /// function to the current output stream.
222 void EmitJumpTableInfo();
224 /// Emit the specified global variable to the .s file.
225 virtual void EmitGlobalVariable(const GlobalVariable *GV);
227 /// Check to see if the specified global is a special global used by LLVM. If
228 /// so, emit it and return true, otherwise do nothing and return false.
229 bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
231 /// Emit an alignment directive to the specified power of two boundary. For
232 /// example, if you pass in 3 here, you will get an 8 byte alignment. If a
233 /// global value is specified, and if that global has an explicit alignment
234 /// requested, it will override the alignment request if required for
237 void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
239 /// This method prints the label for the specified MachineBasicBlock, an
240 /// alignment (if present) and a comment describing it if appropriate.
241 void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
243 /// Lower the specified LLVM Constant to an MCExpr.
244 const MCExpr *lowerConstant(const Constant *CV);
246 /// \brief Print a general LLVM constant to the .s file.
247 void EmitGlobalConstant(const Constant *CV);
249 //===------------------------------------------------------------------===//
251 //===------------------------------------------------------------------===//
253 // Targets can, or in the case of EmitInstruction, must implement these to
256 /// This virtual method can be overridden by targets that want to emit
257 /// something at the start of their file.
258 virtual void EmitStartOfAsmFile(Module &) {}
260 /// This virtual method can be overridden by targets that want to emit
261 /// something at the end of their file.
262 virtual void EmitEndOfAsmFile(Module &) {}
264 /// Targets can override this to emit stuff before the first basic block in
266 virtual void EmitFunctionBodyStart() {}
268 /// Targets can override this to emit stuff after the last basic block in the
270 virtual void EmitFunctionBodyEnd() {}
272 /// Targets can override this to emit stuff at the end of a basic block.
273 virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
275 /// Targets should implement this to emit instructions.
276 virtual void EmitInstruction(const MachineInstr *) {
277 llvm_unreachable("EmitInstruction not implemented");
280 /// Return the symbol for the specified constant pool entry.
281 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
283 virtual void EmitFunctionEntryLabel();
285 virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
287 /// Targets can override this to change how global constants that are part of
288 /// a C++ static/global constructor list are emitted.
289 virtual void EmitXXStructor(const Constant *CV) { EmitGlobalConstant(CV); }
291 /// Return true if the basic block has exactly one predecessor and the control
292 /// transfer mechanism between the predecessor and this block is a
295 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
297 /// Targets can override this to customize the output of IMPLICIT_DEF
298 /// instructions in verbose mode.
299 virtual void emitImplicitDef(const MachineInstr *MI) const;
301 //===------------------------------------------------------------------===//
302 // Symbol Lowering Routines.
303 //===------------------------------------------------------------------===//
305 /// Return the MCSymbol corresponding to the assembler temporary label with
306 /// the specified stem and unique ID.
307 MCSymbol *GetTempSymbol(Twine Name, unsigned ID) const;
309 /// Return an assembler temporary label with the specified stem.
310 MCSymbol *GetTempSymbol(Twine Name) const;
312 /// Return the MCSymbol for a private symbol with global value name as its
313 /// base, with the specified suffix.
314 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
315 StringRef Suffix) const;
317 /// Return the MCSymbol for the specified ExternalSymbol.
318 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
320 /// Return the symbol for the specified jump table entry.
321 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
323 /// Return the symbol for the specified jump table .set
324 /// FIXME: privatize to AsmPrinter.
325 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
327 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
329 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
330 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
332 //===------------------------------------------------------------------===//
333 // Emission Helper Routines.
334 //===------------------------------------------------------------------===//
336 /// This is just convenient handler for printing offsets.
337 void printOffset(int64_t Offset, raw_ostream &OS) const;
339 /// Emit a byte directive and value.
341 void EmitInt8(int Value) const;
343 /// Emit a short directive and value.
345 void EmitInt16(int Value) const;
347 /// Emit a long directive and value.
349 void EmitInt32(int Value) const;
351 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
352 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
353 /// .set if it is available.
354 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
355 unsigned Size) const;
357 /// Emit something like ".long Label+Offset" where the size in bytes of the
358 /// directive is specified by Size and Label specifies the label. This
359 /// implicitly uses .set if it is available.
360 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
361 unsigned Size, bool IsSectionRelative = false) const;
363 /// Emit something like ".long Label" where the size in bytes of the directive
364 /// is specified by Size and Label specifies the label.
365 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
366 bool IsSectionRelative = false) const {
367 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
370 //===------------------------------------------------------------------===//
371 // Dwarf Emission Helper Routines
372 //===------------------------------------------------------------------===//
374 /// Emit the specified signed leb128 value.
375 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
377 /// Emit the specified unsigned leb128 value.
378 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
379 unsigned PadTo = 0) const;
381 /// Emit a .byte 42 directive for a DW_CFA_xxx value.
382 void EmitCFAByte(unsigned Val) const;
384 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
385 /// assembly output is enabled, we output comments describing the encoding.
386 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
387 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
389 /// Return the size of the encoding in bytes.
390 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
392 /// Emit reference to a ttype global with a specified encoding.
393 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
395 /// Emit the 4-byte offset of Label from the start of its section. This can
396 /// be done with a special directive if the target supports it (e.g. cygwin)
397 /// or by emitting it as an offset from a label at the start of the section.
399 /// SectionLabel is a temporary label emitted at the start of the section
400 /// that Label lives in.
401 void EmitSectionOffset(const MCSymbol *Label,
402 const MCSymbol *SectionLabel) const;
404 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
405 virtual unsigned getISAEncoding() { return 0; }
407 /// Emit a dwarf register operation for describing
408 /// - a small value occupying only part of a register or
409 /// - a register representing only part of a value.
410 void EmitDwarfOpPiece(ByteStreamer &Streamer, unsigned SizeInBits,
411 unsigned OffsetInBits = 0) const;
414 /// \brief Emit a partial DWARF register operation.
415 /// \param MLoc the register
416 /// \param PieceSize size and
417 /// \param PieceOffset offset of the piece in bits, if this is one
418 /// piece of an aggregate value.
420 /// If size and offset is zero an operation for the entire
421 /// register is emitted: Some targets do not provide a DWARF
422 /// register number for every register. If this is the case, this
423 /// function will attempt to emit a DWARF register by emitting a
424 /// piece of a super-register or by piecing together multiple
425 /// subregisters that alias the register.
426 void EmitDwarfRegOpPiece(ByteStreamer &BS, const MachineLocation &MLoc,
427 unsigned PieceSize = 0,
428 unsigned PieceOffset = 0) const;
430 /// EmitDwarfRegOp - Emit a dwarf register operation.
431 /// \param Indirect whether this is a register-indirect address
432 virtual void EmitDwarfRegOp(ByteStreamer &BS, const MachineLocation &MLoc,
433 bool Indirect) const;
435 //===------------------------------------------------------------------===//
436 // Dwarf Lowering Routines
437 //===------------------------------------------------------------------===//
439 /// \brief Emit frame instruction to describe the layout of the frame.
440 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
442 //===------------------------------------------------------------------===//
443 // Inline Asm Support
444 //===------------------------------------------------------------------===//
446 // These are hooks that targets can override to implement inline asm
447 // support. These should probably be moved out of AsmPrinter someday.
449 /// Print information related to the specified machine instr that is
450 /// independent of the operand, and may be independent of the instr itself.
451 /// This can be useful for portably encoding the comment character or other
452 /// bits of target-specific knowledge into the asmstrings. The syntax used is
453 /// ${:comment}. Targets can override this to add support for their own
455 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
456 const char *Code) const;
458 /// Print the specified operand of MI, an INLINEASM instruction, using the
459 /// specified assembler variant. Targets should override this to format as
460 /// appropriate. This method can return true if the operand is erroneous.
461 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
462 unsigned AsmVariant, const char *ExtraCode,
465 /// Print the specified operand of MI, an INLINEASM instruction, using the
466 /// specified assembler variant as an address. Targets should override this to
467 /// format as appropriate. This method can return true if the operand is
469 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
470 unsigned AsmVariant, const char *ExtraCode,
473 /// Let the target do anything it needs to do before emitting inlineasm.
474 /// \p StartInfo - the subtarget info before parsing inline asm
475 virtual void emitInlineAsmStart(const MCSubtargetInfo &StartInfo) const;
477 /// Let the target do anything it needs to do after emitting inlineasm.
478 /// This callback can be used restore the original mode in case the
479 /// inlineasm contains directives to switch modes.
480 /// \p StartInfo - the original subtarget info before inline asm
481 /// \p EndInfo - the final subtarget info after parsing the inline asm,
482 /// or NULL if the value is unknown.
483 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
484 const MCSubtargetInfo *EndInfo) const;
487 /// Private state for PrintSpecial()
488 // Assign a unique ID to this machine instruction.
489 mutable const MachineInstr *LastMI;
490 mutable unsigned LastFn;
491 mutable unsigned Counter;
492 mutable unsigned SetCounter;
494 /// Emit a blob of inline asm to the output streamer.
496 EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = nullptr,
497 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
499 /// This method formats and emits the specified machine instruction that is an
501 void EmitInlineAsm(const MachineInstr *MI) const;
503 //===------------------------------------------------------------------===//
504 // Internal Implementation Details
505 //===------------------------------------------------------------------===//
507 /// This emits visibility information about symbol, if this is suported by the
509 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
510 bool IsDefinition = true) const;
512 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
514 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
515 const MachineBasicBlock *MBB, unsigned uid) const;
516 void EmitLLVMUsedList(const ConstantArray *InitList);
517 /// Emit llvm.ident metadata in an '.ident' directive.
518 void EmitModuleIdents(Module &M);
519 void EmitXXStructorList(const Constant *List, bool isCtor);
520 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);