LLVM  5.0.0
WebAssemblyAsmPrinter.cpp
Go to the documentation of this file.
1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
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 /// \file
11 /// \brief This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
13 /// language.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "WebAssemblyAsmPrinter.h"
21 #include "WebAssembly.h"
22 #include "WebAssemblyMCInstLower.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolWasm.h"
37 #include "llvm/MC/MCSymbolELF.h"
38 #include "llvm/Support/Debug.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "asm-printer"
44 
45 //===----------------------------------------------------------------------===//
46 // Helpers.
47 //===----------------------------------------------------------------------===//
48 
49 MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
50  const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
51  const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
54  if (TRI->isTypeLegalForClass(*TRC, T))
55  return T;
56  DEBUG(errs() << "Unknown type for register number: " << RegNo);
57  llvm_unreachable("Unknown register type");
58  return MVT::Other;
59 }
60 
62  unsigned RegNo = MO.getReg();
64  "Unlowered physical register encountered during assembly printing");
65  assert(!MFI->isVRegStackified(RegNo));
66  unsigned WAReg = MFI->getWAReg(RegNo);
68  return '$' + utostr(WAReg);
69 }
70 
72  MCTargetStreamer *TS = OutStreamer->getTargetStreamer();
73  return static_cast<WebAssemblyTargetStreamer *>(TS);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // WebAssemblyAsmPrinter Implementation.
78 //===----------------------------------------------------------------------===//
79 
81  for (const auto &F : M) {
82  // Emit function type info for all undefined functions
83  if (F.isDeclarationForLinker() && !F.isIntrinsic()) {
85  SmallVector<MVT, 4> Params;
86  ComputeSignatureVTs(F, TM, Params, Results);
88  Results);
89  }
90  }
91  for (const auto &G : M.globals()) {
92  if (!G.hasInitializer() && G.hasExternalLinkage()) {
93  uint16_t Size = M.getDataLayout().getTypeAllocSize(G.getValueType());
94  getTargetStreamer()->emitGlobalImport(G.getGlobalIdentifier());
95  OutStreamer->emitELFSize(getSymbol(&G),
97  }
98  }
99 }
100 
102  assert(MF->getConstantPool()->getConstants().empty() &&
103  "WebAssembly disables constant pools");
104 }
105 
107  // Nothing to do; jump tables are incorporated into the instruction stream.
108 }
109 
112 
113  SmallVector<MVT, 4> ResultVTs;
114  const Function &F(*MF->getFunction());
115 
116  // Emit the function index.
117  if (MDNode *Idx = F.getMetadata("wasm.index")) {
118  assert(Idx->getNumOperands() == 1);
119 
121  cast<ConstantAsMetadata>(Idx->getOperand(0))->getValue()));
122  }
123 
124  ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
125 
126  // If the return type needs to be legalized it will get converted into
127  // passing a pointer.
128  if (ResultVTs.size() == 1)
130  else
132 
134  assert(MFI->getLocals().empty());
135  for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
136  unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
137  unsigned WAReg = MFI->getWAReg(VReg);
138  // Don't declare unused registers.
140  continue;
141  // Don't redeclare parameters.
142  if (WAReg < MFI->getParams().size())
143  continue;
144  // Don't declare stackified registers.
145  if (int(WAReg) < 0)
146  continue;
147  MFI->addLocal(getRegType(VReg));
148  }
149  }
150 
152 
154 }
155 
159 }
160 
162  DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
163 
164  switch (MI->getOpcode()) {
165  case WebAssembly::ARGUMENT_I32:
166  case WebAssembly::ARGUMENT_I64:
167  case WebAssembly::ARGUMENT_F32:
168  case WebAssembly::ARGUMENT_F64:
169  case WebAssembly::ARGUMENT_v16i8:
170  case WebAssembly::ARGUMENT_v8i16:
171  case WebAssembly::ARGUMENT_v4i32:
172  case WebAssembly::ARGUMENT_v4f32:
173  // These represent values which are live into the function entry, so there's
174  // no instruction to emit.
175  break;
176  case WebAssembly::FALLTHROUGH_RETURN_I32:
177  case WebAssembly::FALLTHROUGH_RETURN_I64:
178  case WebAssembly::FALLTHROUGH_RETURN_F32:
179  case WebAssembly::FALLTHROUGH_RETURN_F64:
180  case WebAssembly::FALLTHROUGH_RETURN_v16i8:
181  case WebAssembly::FALLTHROUGH_RETURN_v8i16:
182  case WebAssembly::FALLTHROUGH_RETURN_v4i32:
183  case WebAssembly::FALLTHROUGH_RETURN_v4f32: {
184  // These instructions represent the implicit return at the end of a
185  // function body. The operand is always a pop.
186  assert(MFI->isVRegStackified(MI->getOperand(0).getReg()));
187 
188  if (isVerbose()) {
189  OutStreamer->AddComment("fallthrough-return: $pop" +
190  utostr(MFI->getWARegStackId(
191  MFI->getWAReg(MI->getOperand(0).getReg()))));
192  OutStreamer->AddBlankLine();
193  }
194  break;
195  }
196  case WebAssembly::FALLTHROUGH_RETURN_VOID:
197  // This instruction represents the implicit return at the end of a
198  // function body with no return value.
199  if (isVerbose()) {
200  OutStreamer->AddComment("fallthrough-return");
201  OutStreamer->AddBlankLine();
202  }
203  break;
204  default: {
205  WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
206  MCInst TmpInst;
207  MCInstLowering.Lower(MI, TmpInst);
208  EmitToStreamer(*OutStreamer, TmpInst);
209  break;
210  }
211  }
212 }
213 
215  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
216  if (GV->getValueType()->isFunctionTy()) {
219  }
220  return AsmPrinter::lowerConstant(CV);
221 }
222 
224  unsigned OpNo, unsigned AsmVariant,
225  const char *ExtraCode,
226  raw_ostream &OS) {
227  if (AsmVariant != 0)
228  report_fatal_error("There are no defined alternate asm variants");
229 
230  // First try the generic code, which knows about modifiers like 'c' and 'n'.
231  if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
232  return false;
233 
234  if (!ExtraCode) {
235  const MachineOperand &MO = MI->getOperand(OpNo);
236  switch (MO.getType()) {
238  OS << MO.getImm();
239  return false;
241  OS << regToString(MO);
242  return false;
244  getSymbol(MO.getGlobal())->print(OS, MAI);
245  printOffset(MO.getOffset(), OS);
246  return false;
249  printOffset(MO.getOffset(), OS);
250  return false;
252  MO.getMBB()->getSymbol()->print(OS, MAI);
253  return false;
254  default:
255  break;
256  }
257  }
258 
259  return true;
260 }
261 
263  unsigned OpNo,
264  unsigned AsmVariant,
265  const char *ExtraCode,
266  raw_ostream &OS) {
267  if (AsmVariant != 0)
268  report_fatal_error("There are no defined alternate asm variants");
269 
270  if (!ExtraCode) {
271  // TODO: For now, we just hard-code 0 as the constant offset; teach
272  // SelectInlineAsmMemoryOperand how to do address mode matching.
273  OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
274  return false;
275  }
276 
277  return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
278 }
279 
280 // Force static initialization.
284 }
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
const GlobalValue * getGlobal() const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:305
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:420
This class is used to lower an MachineInstr into an MCInst.
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:59
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
MachineBasicBlock * getMBB() const
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
This class prints an WebAssembly MCInst to wasm file syntax.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Target specific streamer interface.
Definition: MCStreamer.h:78
const MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
virtual void emitGlobalImport(StringRef name)=0
.import_global
This file declares the class to lower WebAssembly MachineInstrs to their corresponding MCInst records...
void EmitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
Function Alias Analysis Results
MachineBasicBlock reference.
const char * getSymbolName() const
Metadata node.
Definition: Metadata.h:862
bool isVRegStackified(unsigned VReg) const
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
const Triple & getTargetTriple() const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM, Type *Ty, SmallVectorImpl< MVT > &ValueVTs)
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Name of external global symbol.
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
unsigned getWAReg(unsigned Reg) const
#define F(x, y, z)
Definition: MD5.cpp:55
std::string regToString(const MachineOperand &MO)
MVT getRegType(unsigned RegNo) const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
virtual void emitEndFunc()=0
.endfunc
int64_t getImm() const
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:159
WebAssembly-specific streamer interface, to implement support WebAssembly-specific assembly directive...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
Address of a global value.
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:107
Machine Value Type.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
virtual void emitResult(MCSymbol *Symbol, ArrayRef< MVT > Types)=0
.result
void ComputeSignatureVTs(const Function &F, const TargetMachine &TM, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)
This is an important base class in LLVM.
Definition: Constant.h:42
void EmitEndOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the end of their file...
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
This file provides WebAssembly-specific target descriptions.
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:80
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MCExpr * lowerConstant(const Constant *CV) override
Lower the specified LLVM Constant to an MCExpr.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
This file declares WebAssembly-specific target streamer classes.
This file contains the WebAssembly implementation of the WebAssemblyRegisterInfo class.
void LLVMInitializeWebAssemblyAsmPrinter()
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:209
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
virtual void EmitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:369
void EmitConstantPool() override
Print to the current output stream assembly representations of the constants in the constant pool MCP...
void Lower(const MachineInstr *MI, MCInst &OutMI) const
virtual void emitIndirectFunctionType(MCSymbol *Symbol, SmallVectorImpl< MVT > &Params, SmallVectorImpl< MVT > &Results)=0
.functype
void EmitFunctionBodyEnd() override
Targets can override this to emit stuff after the last basic block in the function.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
const WebAssemblyRegisterInfo * getRegisterInfo() const override
llvm_unreachable("Unknown RegBank!")
const std::vector< MVT > & getParams() const
void EmitJumpTableInfo() override
Print assembly representations of the jump tables used by the current function to the current output ...
Representation of each machine instruction.
Definition: MachineInstr.h:59
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:577
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
This file declares WebAssembly-specific per-machine-function information.
const std::vector< MVT > & getLocals() const
void EmitFunctionBodyStart() override
Targets can override this to emit stuff before the first basic block in the function.
virtual void emitParam(MCSymbol *Symbol, ArrayRef< MVT > Types)=0
.param
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const
Return true if the given TargetRegisterClass has the ValueType T.
RegisterAsmPrinter - Helper template for registering a target specific assembly printer, for use in the target machine initialization function.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
virtual void emitLocal(ArrayRef< MVT > Types)=0
.local
const std::vector< MachineConstantPoolEntry > & getConstants() const
IRTranslator LLVM IR MI
virtual void print(raw_ostream &O, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:117
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
Target & getTheWebAssemblyTarget32()
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:191
Target & getTheWebAssemblyTarget64()
WebAssemblyTargetStreamer * getTargetStreamer()
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:159
virtual void emitIndIdx(const MCExpr *Value)=0
.indidx
static unsigned getWARegStackId(unsigned Reg)