1 //===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===//
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 //===----------------------------------------------------------------------===//
11 /// \brief This file contains a printer that converts from our internal
12 /// representation of machine-dependent LLVM code to the WebAssembly assembly
15 //===----------------------------------------------------------------------===//
17 #include "WebAssembly.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyRegisterInfo.h"
20 #include "WebAssemblySubtarget.h"
21 #include "InstPrinter/WebAssemblyInstPrinter.h"
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
38 #define DEBUG_TYPE "asm-printer"
42 class WebAssemblyAsmPrinter final : public AsmPrinter {
44 const WebAssemblyInstrInfo *TII;
47 WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
48 : AsmPrinter(TM, std::move(Streamer)), TII(nullptr) {}
51 const char *getPassName() const override {
52 return "WebAssembly Assembly Printer";
55 //===------------------------------------------------------------------===//
56 // MachineFunctionPass Implementation.
57 //===------------------------------------------------------------------===//
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AsmPrinter::getAnalysisUsage(AU);
63 bool runOnMachineFunction(MachineFunction &MF) override {
64 const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
65 hasAddr64 = Subtarget.hasAddr64();
66 TII = Subtarget.getInstrInfo();
67 return AsmPrinter::runOnMachineFunction(MF);
70 //===------------------------------------------------------------------===//
71 // AsmPrinter Implementation.
72 //===------------------------------------------------------------------===//
74 void EmitGlobalVariable(const GlobalVariable *GV) override;
76 void EmitConstantPool() override;
77 void EmitFunctionEntryLabel() override;
78 void EmitFunctionBodyStart() override;
79 void EmitFunctionBodyEnd() override;
81 void EmitInstruction(const MachineInstr *MI) override;
84 } // end anonymous namespace
86 //===----------------------------------------------------------------------===//
88 //===----------------------------------------------------------------------===//
90 // Untyped, lower-case version of the opcode's name matching the names
91 // WebAssembly opcodes are expected to have. The tablegen names are uppercase
92 // and suffixed with their type (after an underscore).
93 static SmallString<32> OpcodeName(const WebAssemblyInstrInfo *TII,
94 const MachineInstr *MI) {
95 std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
96 std::string::size_type End = N.rfind('_');
97 End = std::string::npos == End ? N.length() : End;
98 return SmallString<32>(&N[0], &N[End]);
101 static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
103 static std::string toString(const APFloat &FP) {
104 static const size_t BufBytes = 128;
107 assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
109 APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
110 "convertToHexString handles neither SNaN nor NaN payloads");
111 // Use C99's hexadecimal floating-point representation.
112 auto Written = FP.convertToHexString(
113 buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
115 assert(Written != 0);
116 assert(Written < BufBytes);
120 static const char *toString(const Type *Ty, bool hasAddr64) {
121 switch (Ty->getTypeID()) {
123 // Treat all pointers as the underlying integer into linear memory.
124 case Type::PointerTyID: return hasAddr64 ? "i64" : "i32";
125 case Type::FloatTyID: return "f32";
126 case Type::DoubleTyID: return "f64";
127 case Type::IntegerTyID:
128 switch (Ty->getIntegerBitWidth()) {
130 case 16: return "i16";
131 case 32: return "i32";
132 case 64: return "i64";
136 DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
137 llvm_unreachable("invalid type");
142 //===----------------------------------------------------------------------===//
143 // WebAssemblyAsmPrinter Implementation.
144 //===----------------------------------------------------------------------===//
146 void WebAssemblyAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
147 SmallString<128> Str;
148 raw_svector_ostream OS(Str);
149 StringRef Name = GV->getName();
150 DEBUG(dbgs() << "Global " << Name << '\n');
152 if (!GV->hasInitializer()) {
153 DEBUG(dbgs() << " Skipping declaration.\n");
157 // Check to see if this is a special global used by LLVM.
158 static const char *Ignored[] = {"llvm.used", "llvm.metadata"};
159 for (const char *I : Ignored)
162 // FIXME: Handle the following globals.
163 static const char *Unhandled[] = {"llvm.global_ctors", "llvm.global_dtors"};
164 for (const char *U : Unhandled)
166 report_fatal_error("Unhandled global");
167 if (Name.startswith("llvm."))
168 report_fatal_error("Unknown LLVM-internal global");
170 if (GV->isThreadLocal())
171 report_fatal_error("TLS isn't yet supported by WebAssembly");
173 const DataLayout &DL = getDataLayout();
174 const Constant *Init = GV->getInitializer();
175 if (isa<UndefValue>(Init))
176 Init = Constant::getNullValue(Init->getType());
177 unsigned Align = DL.getPrefTypeAlignment(Init->getType());
179 switch (GV->getLinkage()) {
180 case GlobalValue::InternalLinkage:
181 case GlobalValue::PrivateLinkage:
183 case GlobalValue::AppendingLinkage:
184 case GlobalValue::LinkOnceAnyLinkage:
185 case GlobalValue::LinkOnceODRLinkage:
186 case GlobalValue::WeakAnyLinkage:
187 case GlobalValue::WeakODRLinkage:
188 case GlobalValue::ExternalLinkage:
189 case GlobalValue::CommonLinkage:
190 report_fatal_error("Linkage types other than internal and private aren't "
191 "supported by WebAssembly yet");
193 llvm_unreachable("Unknown linkage type");
197 OS << "(global " << toSymbol(Name) << ' '
198 << toString(Init->getType(), hasAddr64) << ' ';
199 if (const auto *C = dyn_cast<ConstantInt>(Init)) {
200 assert(C->getBitWidth() <= 64 && "Printing wider types unimplemented");
201 OS << C->getZExtValue();
202 } else if (const auto *C = dyn_cast<ConstantFP>(Init)) {
203 OS << toString(C->getValueAPF());
205 assert(false && "Only integer and floating-point constants are supported");
207 OS << ") ;; align " << Align << "\n";
208 OutStreamer->EmitRawText(OS.str());
211 void WebAssemblyAsmPrinter::EmitConstantPool() {
212 assert(MF->getConstantPool()->getConstants().empty() &&
213 "WebAssembly disables constant pools");
216 void WebAssemblyAsmPrinter::EmitFunctionEntryLabel() {
217 SmallString<128> Str;
218 raw_svector_ostream OS(Str);
220 CurrentFnSym->redefineIfPossible();
222 // The function label could have already been emitted if two symbols end up
223 // conflicting due to asm renaming. Detect this and emit an error.
224 if (CurrentFnSym->isVariable())
225 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
226 "' is a protected alias");
227 if (CurrentFnSym->isDefined())
228 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
229 "' label emitted multiple times to assembly file");
231 OS << "(func " << toSymbol(CurrentFnSym->getName());
232 OutStreamer->EmitRawText(OS.str());
235 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
236 SmallString<128> Str;
237 raw_svector_ostream OS(Str);
238 const Function *F = MF->getFunction();
239 for (const Argument &A : F->args())
240 OS << " (param " << toString(A.getType(), hasAddr64) << ')';
241 const Type *Rt = F->getReturnType();
243 OS << " (result " << toString(Rt, hasAddr64) << ')';
245 OutStreamer->EmitRawText(OS.str());
248 void WebAssemblyAsmPrinter::EmitFunctionBodyEnd() {
249 SmallString<128> Str;
250 raw_svector_ostream OS(Str);
251 OS << ") ;; end func " << toSymbol(CurrentFnSym->getName()) << '\n';
252 OutStreamer->EmitRawText(OS.str());
255 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
256 DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
257 SmallString<128> Str;
258 raw_svector_ostream OS(Str);
260 unsigned NumDefs = MI->getDesc().getNumDefs();
261 assert(NumDefs <= 1 &&
262 "Instructions with multiple result values not implemented");
267 const MachineOperand &MO = MI->getOperand(0);
268 unsigned Reg = MO.getReg();
269 OS << "(setlocal @" << TargetRegisterInfo::virtReg2Index(Reg) << ' ';
272 OS << '(' << OpcodeName(TII, MI);
273 for (const MachineOperand &MO : MI->uses())
274 switch (MO.getType()) {
276 llvm_unreachable("unexpected machine operand type");
277 case MachineOperand::MO_Register: {
280 unsigned Reg = MO.getReg();
281 OS << " @" << TargetRegisterInfo::virtReg2Index(Reg);
283 case MachineOperand::MO_Immediate: {
284 OS << ' ' << MO.getImm();
286 case MachineOperand::MO_FPImmediate: {
287 OS << ' ' << toString(MO.getFPImm()->getValueAPF());
289 case MachineOperand::MO_GlobalAddress: {
290 OS << ' ' << toSymbol(MO.getGlobal()->getName());
300 OutStreamer->EmitRawText(OS.str());
303 // Force static initialization.
304 extern "C" void LLVMInitializeWebAssemblyAsmPrinter() {
305 RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32);
306 RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64);