1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- 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 /// \file
11 /// \brief This file is part of the WebAssembly Assembler.
12 ///
13 /// It contains code to translate a parsed .s file into MCInsts.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
18 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
19 #include "WebAssembly.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/TargetRegistry.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "wasm-asm-parser"
34 
35 // TODO: TableGen generates this register name matcher, but it is not used
36 // anywhere. Mark it with the "unused" attribute to suppress warnings.
37 static unsigned LLVM_ATTRIBUTE_UNUSED MatchRegisterName(StringRef Name);
38 
39 namespace {
40 
41 // We store register types as SimpleValueType to retain SIMD layout
42 // information, but must also be able to supply them as the (unnamed)
43 // register enum from WebAssemblyRegisterInfo.td/.inc.
44 static unsigned MVTToWasmReg(MVT::SimpleValueType Type) {
45   switch(Type) {
46     case MVT::i32: return WebAssembly::I32_0;
47     case MVT::i64: return WebAssembly::I64_0;
48     case MVT::f32: return WebAssembly::F32_0;
49     case MVT::f64: return WebAssembly::F64_0;
50     case MVT::v16i8: return WebAssembly::V128_0;
51     case MVT::v8i16: return WebAssembly::V128_0;
52     case MVT::v4i32: return WebAssembly::V128_0;
53     case MVT::v4f32: return WebAssembly::V128_0;
54     default: return MVT::INVALID_SIMPLE_VALUE_TYPE;
55   }
56 }
57 
58 /// WebAssemblyOperand - Instances of this class represent the operands in a
59 /// parsed WASM machine instruction.
60 struct WebAssemblyOperand : public MCParsedAsmOperand {
61   enum KindTy { Token, Local, Stack, Integer, Float, Symbol } Kind;
62 
63   SMLoc StartLoc, EndLoc;
64 
65   struct TokOp {
66     StringRef Tok;
67   };
68 
69   struct RegOp {
70     // This is a (virtual) local or stack register represented as 0..
71     unsigned RegNo;
72     // In most targets, the register number also encodes the type, but for
73     // wasm we have to track that seperately since we have an unbounded
74     // number of registers.
75     // This has the unfortunate side effect that we supply a different value
76     // to the table-gen matcher at different times in the process (when it
77     // calls getReg() or addRegOperands().
78     // TODO: While this works, it feels brittle. and would be nice to clean up.
79     MVT::SimpleValueType Type;
80   };
81 
82   struct IntOp {
83     int64_t Val;
84   };
85 
86   struct FltOp {
87     double Val;
88   };
89 
90   struct SymOp {
91     const MCExpr *Exp;
92   };
93 
94   union {
95     struct TokOp Tok;
96     struct RegOp Reg;
97     struct IntOp Int;
98     struct FltOp Flt;
99     struct SymOp Sym;
100   };
101 
102   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
103     : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
104   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, RegOp R)
105     : Kind(K), StartLoc(Start), EndLoc(End), Reg(R) {}
106   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
107     : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
108   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
109     : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
110   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
111     : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
112 
113   bool isToken() const override { return Kind == Token; }
114   bool isImm() const override { return Kind == Integer ||
115                                        Kind == Float ||
116                                        Kind == Symbol; }
117   bool isReg() const override { return Kind == Local || Kind == Stack; }
118   bool isMem() const override { return false; }
119 
120   unsigned getReg() const override {
121     assert(isReg());
122     // This is called from the tablegen matcher (MatchInstructionImpl)
123     // where it expects to match the type of register, see RegOp above.
124     return MVTToWasmReg(Reg.Type);
125   }
126 
127   StringRef getToken() const {
128     assert(isToken());
129     return Tok.Tok;
130   }
131 
132   SMLoc getStartLoc() const override { return StartLoc; }
133   SMLoc getEndLoc() const override { return EndLoc; }
134 
135   void addRegOperands(MCInst &Inst, unsigned N) const {
136     assert(N == 1 && "Invalid number of operands!");
137     assert(isReg() && "Not a register operand!");
138     // This is called from the tablegen matcher (MatchInstructionImpl)
139     // where it expects to output the actual register index, see RegOp above.
140     unsigned R = Reg.RegNo;
141     if (Kind == Stack) {
142       // A stack register is represented as a large negative number.
143       // See WebAssemblyRegNumbering::runOnMachineFunction and
144       // getWARegStackId for why this | is needed.
145       R |= INT32_MIN;
146     }
147     Inst.addOperand(MCOperand::createReg(R));
148   }
149 
150   void addImmOperands(MCInst &Inst, unsigned N) const {
151     assert(N == 1 && "Invalid number of operands!");
152     if (Kind == Integer)
153       Inst.addOperand(MCOperand::createImm(Int.Val));
154     else if (Kind == Float)
155       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
156     else if (Kind == Symbol)
157       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
158     else
159       llvm_unreachable("Should be immediate or symbol!");
160   }
161 
162   void print(raw_ostream &OS) const override {
163     switch (Kind) {
164     case Token:
165       OS << "Tok:" << Tok.Tok;
166       break;
167     case Local:
168       OS << "Loc:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
169       break;
170     case Stack:
171       OS << "Stk:" << Reg.RegNo << ":" << static_cast<int>(Reg.Type);
172       break;
173     case Integer:
174       OS << "Int:" << Int.Val;
175       break;
176     case Float:
177       OS << "Flt:" << Flt.Val;
178       break;
179     case Symbol:
180       OS << "Sym:" << Sym.Exp;
181       break;
182     }
183   }
184 };
185 
186 class WebAssemblyAsmParser final : public MCTargetAsmParser {
187   MCAsmParser &Parser;
188   MCAsmLexer &Lexer;
189   // These are for the current function being parsed:
190   // These are vectors since register assignments are so far non-sparse.
191   // Replace by map if necessary.
192   std::vector<MVT::SimpleValueType> LocalTypes;
193   std::vector<MVT::SimpleValueType> StackTypes;
194   MCSymbol *LastLabel;
195 
196 public:
197   WebAssemblyAsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
198                        const MCInstrInfo &mii, const MCTargetOptions &Options)
199       : MCTargetAsmParser(Options, sti, mii), Parser(Parser),
200         Lexer(Parser.getLexer()), LastLabel(nullptr) {
201   }
202 
203 #define GET_ASSEMBLER_HEADER
204 #include "WebAssemblyGenAsmMatcher.inc"
205 
206   // TODO: This is required to be implemented, but appears unused.
207   bool ParseRegister(unsigned &/*RegNo*/, SMLoc &/*StartLoc*/,
208                      SMLoc &/*EndLoc*/) override {
209     llvm_unreachable("ParseRegister is not implemented.");
210   }
211 
212   bool Error(const StringRef &msg, const AsmToken &tok) {
213     return Parser.Error(tok.getLoc(), msg + tok.getString());
214   }
215 
216   bool IsNext(AsmToken::TokenKind Kind) {
217     auto ok = Lexer.is(Kind);
218     if (ok) Parser.Lex();
219     return ok;
220   }
221 
222   bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
223     if (!IsNext(Kind))
224       return Error(std::string("Expected ") + KindName + ", instead got: ",
225                    Lexer.getTok());
226     return false;
227   }
228 
229   MVT::SimpleValueType ParseRegType(const StringRef &RegType) {
230     // Derive type from .param .local decls, or the instruction itself.
231     return StringSwitch<MVT::SimpleValueType>(RegType)
232         .Case("i32", MVT::i32)
233         .Case("i64", MVT::i64)
234         .Case("f32", MVT::f32)
235         .Case("f64", MVT::f64)
236         .Case("i8x16", MVT::v16i8)
237         .Case("i16x8", MVT::v8i16)
238         .Case("i32x4", MVT::v4i32)
239         .Case("f32x4", MVT::v4f32)
240         .Default(MVT::INVALID_SIMPLE_VALUE_TYPE);
241   }
242 
243   MVT::SimpleValueType &GetType(
244       std::vector<MVT::SimpleValueType> &Types, size_t i) {
245     Types.resize(std::max(i + 1, Types.size()), MVT::INVALID_SIMPLE_VALUE_TYPE);
246     return Types[i];
247   }
248 
249   bool ParseReg(OperandVector &Operands, StringRef TypePrefix) {
250     if (Lexer.is(AsmToken::Integer)) {
251       auto &Local = Lexer.getTok();
252       // This is a reference to a local, turn it into a virtual register.
253       auto LocalNo = static_cast<unsigned>(Local.getIntVal());
254       Operands.push_back(make_unique<WebAssemblyOperand>(
255                            WebAssemblyOperand::Local, Local.getLoc(),
256                            Local.getEndLoc(),
257                            WebAssemblyOperand::RegOp{LocalNo,
258                                GetType(LocalTypes, LocalNo)}));
259       Parser.Lex();
260     } else if (Lexer.is(AsmToken::Identifier)) {
261       auto &StackRegTok = Lexer.getTok();
262       // These are push/pop/drop pseudo stack registers, which we turn
263       // into virtual registers also. The stackify pass will later turn them
264       // back into implicit stack references if possible.
265       auto StackReg = StackRegTok.getString();
266       auto StackOp = StackReg.take_while([](char c) { return isalpha(c); });
267       auto Reg = StackReg.drop_front(StackOp.size());
268       unsigned long long ParsedRegNo = 0;
269       if (!Reg.empty() && getAsUnsignedInteger(Reg, 10, ParsedRegNo))
270         return Error("Cannot parse stack register index: ", StackRegTok);
271       unsigned RegNo = static_cast<unsigned>(ParsedRegNo);
272       if (StackOp == "push") {
273         // This defines a result, record register type.
274         auto RegType = ParseRegType(TypePrefix);
275         GetType(StackTypes, RegNo) = RegType;
276         Operands.push_back(make_unique<WebAssemblyOperand>(
277                              WebAssemblyOperand::Stack,
278                              StackRegTok.getLoc(),
279                              StackRegTok.getEndLoc(),
280                              WebAssemblyOperand::RegOp{RegNo, RegType}));
281       } else if (StackOp == "pop") {
282         // This uses a previously defined stack value.
283         auto RegType = GetType(StackTypes, RegNo);
284         Operands.push_back(make_unique<WebAssemblyOperand>(
285                              WebAssemblyOperand::Stack,
286                              StackRegTok.getLoc(),
287                              StackRegTok.getEndLoc(),
288                              WebAssemblyOperand::RegOp{RegNo, RegType}));
289       } else if (StackOp == "drop") {
290         // This operand will be dropped, since it is part of an instruction
291         // whose result is void.
292       } else {
293         return Error("Unknown stack register prefix: ", StackRegTok);
294       }
295       Parser.Lex();
296     } else {
297       return Error(
298             "Expected identifier/integer following $, instead got: ",
299             Lexer.getTok());
300     }
301     IsNext(AsmToken::Equal);
302     return false;
303   }
304 
305   void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
306     auto &Int = Lexer.getTok();
307     int64_t Val = Int.getIntVal();
308     if (IsNegative) Val = -Val;
309     Operands.push_back(make_unique<WebAssemblyOperand>(
310                          WebAssemblyOperand::Integer, Int.getLoc(),
311                          Int.getEndLoc(), WebAssemblyOperand::IntOp{Val}));
312     Parser.Lex();
313   }
314 
315   bool ParseOperandStartingWithInteger(bool IsNegative,
316                                        OperandVector &Operands,
317                                        StringRef InstType) {
318     ParseSingleInteger(IsNegative, Operands);
319     if (Lexer.is(AsmToken::LParen)) {
320       // Parse load/store operands of the form: offset($reg)align
321       auto &LParen = Lexer.getTok();
322       Operands.push_back(
323             make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
324                                             LParen.getLoc(),
325                                             LParen.getEndLoc(),
326                                             WebAssemblyOperand::TokOp{
327                                               LParen.getString()}));
328       Parser.Lex();
329       if (Expect(AsmToken::Dollar, "register")) return true;
330       if (ParseReg(Operands, InstType)) return true;
331       auto &RParen = Lexer.getTok();
332       Operands.push_back(
333             make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token,
334                                             RParen.getLoc(),
335                                             RParen.getEndLoc(),
336                                             WebAssemblyOperand::TokOp{
337                                               RParen.getString()}));
338       if (Expect(AsmToken::RParen, ")")) return true;
339       if (Lexer.is(AsmToken::Integer)) {
340         ParseSingleInteger(false, Operands);
341       } else {
342         // Alignment not specified.
343         // FIXME: correctly derive a default from the instruction.
344         Operands.push_back(make_unique<WebAssemblyOperand>(
345                              WebAssemblyOperand::Integer, RParen.getLoc(),
346                              RParen.getEndLoc(), WebAssemblyOperand::IntOp{0}));
347       }
348     }
349     return false;
350   }
351 
352   bool ParseInstruction(ParseInstructionInfo &/*Info*/, StringRef Name,
353                         SMLoc NameLoc, OperandVector &Operands) override {
354     Operands.push_back(
355           make_unique<WebAssemblyOperand>(WebAssemblyOperand::Token, NameLoc,
356                                           SMLoc::getFromPointer(
357                                             NameLoc.getPointer() + Name.size()),
358                                           WebAssemblyOperand::TokOp{
359                                             StringRef(NameLoc.getPointer(),
360                                                     Name.size())}));
361     auto NamePair = Name.split('.');
362     // If no '.', there is no type prefix.
363     if (NamePair.second.empty()) std::swap(NamePair.first, NamePair.second);
364     while (Lexer.isNot(AsmToken::EndOfStatement)) {
365       auto &Tok = Lexer.getTok();
366       switch (Tok.getKind()) {
367       case AsmToken::Dollar: {
368         Parser.Lex();
369         if (ParseReg(Operands, NamePair.first)) return true;
370         break;
371       }
372       case AsmToken::Identifier: {
373         auto &Id = Lexer.getTok();
374         const MCExpr *Val;
375         SMLoc End;
376         if (Parser.parsePrimaryExpr(Val, End))
377           return Error("Cannot parse symbol: ", Lexer.getTok());
378         Operands.push_back(make_unique<WebAssemblyOperand>(
379                              WebAssemblyOperand::Symbol, Id.getLoc(),
380                              Id.getEndLoc(), WebAssemblyOperand::SymOp{Val}));
381         break;
382       }
383       case AsmToken::Minus:
384         Parser.Lex();
385         if (Lexer.isNot(AsmToken::Integer))
386           return Error("Expected integer instead got: ", Lexer.getTok());
387         if (ParseOperandStartingWithInteger(true, Operands, NamePair.first))
388           return true;
389         break;
390       case AsmToken::Integer:
391         if (ParseOperandStartingWithInteger(false, Operands, NamePair.first))
392           return true;
393         break;
394       case AsmToken::Real: {
395         double Val;
396         if (Tok.getString().getAsDouble(Val, false))
397           return Error("Cannot parse real: ", Tok);
398         Operands.push_back(make_unique<WebAssemblyOperand>(
399                              WebAssemblyOperand::Float, Tok.getLoc(),
400                              Tok.getEndLoc(), WebAssemblyOperand::FltOp{Val}));
401         Parser.Lex();
402         break;
403       }
404       default:
405         return Error("Unexpected token in operand: ", Tok);
406       }
407       if (Lexer.isNot(AsmToken::EndOfStatement)) {
408         if (Expect(AsmToken::Comma, ",")) return true;
409       }
410     }
411     Parser.Lex();
412     // Call instructions are vararg, but the tablegen matcher doesn't seem to
413     // support that, so for now we strip these extra operands.
414     // This is problematic if these arguments are not simple $pop stack
415     // registers, since e.g. a local register would get lost, so we check for
416     // this. This can be the case when using -disable-wasm-explicit-locals
417     // which currently s2wasm requires.
418     // TODO: Instead, we can move this code to MatchAndEmitInstruction below and
419     // actually generate get_local instructions on the fly.
420     // Or even better, improve the matcher to support vararg?
421     auto IsIndirect = NamePair.second == "call_indirect";
422     if (IsIndirect || NamePair.second == "call") {
423       // Figure out number of fixed operands from the instruction.
424       size_t CallOperands = 1;  // The name token.
425       if (!IsIndirect) CallOperands++;  // The function index.
426       if (!NamePair.first.empty()) CallOperands++;  // The result register.
427       if (Operands.size() > CallOperands) {
428         // Ensure operands we drop are all $pop.
429         for (size_t I = CallOperands; I < Operands.size(); I++) {
430           auto Operand =
431               reinterpret_cast<WebAssemblyOperand *>(Operands[I].get());
432           if (Operand->Kind != WebAssemblyOperand::Stack)
433             Parser.Error(NameLoc,
434               "Call instruction has non-stack arguments, if this code was "
435               "generated with -disable-wasm-explicit-locals please remove it");
436         }
437         // Drop unneeded operands.
438         Operands.resize(CallOperands);
439       }
440     }
441     // Block instructions require a signature index, but these are missing in
442     // assembly, so we add a dummy one explicitly (since we have no control
443     // over signature tables here, we assume these will be regenerated when
444     // the wasm module is generated).
445     if (NamePair.second == "block" || NamePair.second == "loop") {
446       Operands.push_back(make_unique<WebAssemblyOperand>(
447                            WebAssemblyOperand::Integer, NameLoc,
448                            NameLoc, WebAssemblyOperand::IntOp{-1}));
449     }
450     // These don't specify the type, which has to derived from the local index.
451     if (NamePair.second == "get_local" || NamePair.second == "tee_local") {
452       if (Operands.size() >= 3 && Operands[1]->isReg() &&
453           Operands[2]->isImm()) {
454         auto Op1 = reinterpret_cast<WebAssemblyOperand *>(Operands[1].get());
455         auto Op2 = reinterpret_cast<WebAssemblyOperand *>(Operands[2].get());
456         auto Type = GetType(LocalTypes, static_cast<size_t>(Op2->Int.Val));
457         Op1->Reg.Type = Type;
458         GetType(StackTypes, Op1->Reg.RegNo) = Type;
459       }
460     }
461     return false;
462   }
463 
464   void onLabelParsed(MCSymbol *Symbol) override {
465     LastLabel = Symbol;
466   }
467 
468   bool ParseDirective(AsmToken DirectiveID) override {
469     assert(DirectiveID.getKind() == AsmToken::Identifier);
470     auto &Out = getStreamer();
471     auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
472                    *Out.getTargetStreamer());
473     // TODO: we're just parsing the subset of directives we're interested in,
474     // and ignoring ones we don't recognise. We should ideally verify
475     // all directives here.
476     if (DirectiveID.getString() == ".type") {
477       // This could be the start of a function, check if followed by
478       // "label,@function"
479       if (!(IsNext(AsmToken::Identifier) &&
480             IsNext(AsmToken::Comma) &&
481             IsNext(AsmToken::At) &&
482             Lexer.is(AsmToken::Identifier)))
483         return Error("Expected label,@type declaration, got: ", Lexer.getTok());
484       if (Lexer.getTok().getString() == "function") {
485         // Track locals from start of function.
486         LocalTypes.clear();
487         StackTypes.clear();
488       }
489       Parser.Lex();
490       //Out.EmitSymbolAttribute(??, MCSA_ELF_TypeFunction);
491     } else if (DirectiveID.getString() == ".param" ||
492                DirectiveID.getString() == ".local") {
493       // Track the number of locals, needed for correct virtual register
494       // assignment elsewhere.
495       // Also output a directive to the streamer.
496       std::vector<MVT> Params;
497       std::vector<MVT> Locals;
498       while (Lexer.is(AsmToken::Identifier)) {
499         auto RegType = ParseRegType(Lexer.getTok().getString());
500         if (RegType == MVT::INVALID_SIMPLE_VALUE_TYPE) return true;
501         LocalTypes.push_back(RegType);
502         if (DirectiveID.getString() == ".param") {
503           Params.push_back(RegType);
504         } else {
505           Locals.push_back(RegType);
506         }
507         Parser.Lex();
508         if (!IsNext(AsmToken::Comma)) break;
509       }
510       assert(LastLabel);
511       TOut.emitParam(LastLabel, Params);
512       TOut.emitLocal(Locals);
513     } else {
514       // For now, ignore anydirective we don't recognize:
515       while (Lexer.isNot(AsmToken::EndOfStatement)) Parser.Lex();
516     }
517     return Expect(AsmToken::EndOfStatement, "EOL");
518   }
519 
520   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &/*Opcode*/,
521                                OperandVector &Operands,
522                                MCStreamer &Out, uint64_t &ErrorInfo,
523                                bool MatchingInlineAsm) override {
524     MCInst Inst;
525     unsigned MatchResult =
526         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
527     switch (MatchResult) {
528     case Match_Success: {
529       Out.EmitInstruction(Inst, getSTI());
530       return false;
531     }
532     case Match_MissingFeature:
533       return Parser.Error(IDLoc,
534           "instruction requires a WASM feature not currently enabled");
535     case Match_MnemonicFail:
536       return Parser.Error(IDLoc, "invalid instruction");
537     case Match_NearMisses:
538       return Parser.Error(IDLoc, "ambiguous instruction");
539     case Match_InvalidTiedOperand:
540     case Match_InvalidOperand: {
541       SMLoc ErrorLoc = IDLoc;
542       if (ErrorInfo != ~0ULL) {
543         if (ErrorInfo >= Operands.size())
544           return Parser.Error(IDLoc, "too few operands for instruction");
545         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
546         if (ErrorLoc == SMLoc())
547           ErrorLoc = IDLoc;
548       }
549       return Parser.Error(ErrorLoc, "invalid operand for instruction");
550     }
551     }
552     llvm_unreachable("Implement any new match types added!");
553   }
554 };
555 } // end anonymous namespace
556 
557 // Force static initialization.
558 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
559   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
560   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
561 }
562 
563 #define GET_REGISTER_MATCHER
564 #define GET_MATCHER_IMPLEMENTATION
565 #include "WebAssemblyGenAsmMatcher.inc"
566