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 /// 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/MCInst.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCSymbolWasm.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/TargetRegistry.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm-asm-parser"
35 
36 namespace {
37 
38 /// WebAssemblyOperand - Instances of this class represent the operands in a
39 /// parsed WASM machine instruction.
40 struct WebAssemblyOperand : public MCParsedAsmOperand {
41   enum KindTy { Token, Integer, Float, Symbol } Kind;
42 
43   SMLoc StartLoc, EndLoc;
44 
45   struct TokOp {
46     StringRef Tok;
47   };
48 
49   struct IntOp {
50     int64_t Val;
51   };
52 
53   struct FltOp {
54     double Val;
55   };
56 
57   struct SymOp {
58     const MCExpr *Exp;
59   };
60 
61   union {
62     struct TokOp Tok;
63     struct IntOp Int;
64     struct FltOp Flt;
65     struct SymOp Sym;
66   };
67 
68   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
69       : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
70   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
71       : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
72   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
73       : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
74   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
75       : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
76 
77   bool isToken() const override { return Kind == Token; }
78   bool isImm() const override {
79     return Kind == Integer || Kind == Float || Kind == Symbol;
80   }
81   bool isMem() const override { return false; }
82   bool isReg() const override { return false; }
83 
84   unsigned getReg() const override {
85     llvm_unreachable("Assembly inspects a register operand");
86     return 0;
87   }
88 
89   StringRef getToken() const {
90     assert(isToken());
91     return Tok.Tok;
92   }
93 
94   SMLoc getStartLoc() const override { return StartLoc; }
95   SMLoc getEndLoc() const override { return EndLoc; }
96 
97   void addRegOperands(MCInst &, unsigned) const {
98     // Required by the assembly matcher.
99     llvm_unreachable("Assembly matcher creates register operands");
100   }
101 
102   void addImmOperands(MCInst &Inst, unsigned N) const {
103     assert(N == 1 && "Invalid number of operands!");
104     if (Kind == Integer)
105       Inst.addOperand(MCOperand::createImm(Int.Val));
106     else if (Kind == Float)
107       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
108     else if (Kind == Symbol)
109       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
110     else
111       llvm_unreachable("Should be immediate or symbol!");
112   }
113 
114   void print(raw_ostream &OS) const override {
115     switch (Kind) {
116     case Token:
117       OS << "Tok:" << Tok.Tok;
118       break;
119     case Integer:
120       OS << "Int:" << Int.Val;
121       break;
122     case Float:
123       OS << "Flt:" << Flt.Val;
124       break;
125     case Symbol:
126       OS << "Sym:" << Sym.Exp;
127       break;
128     }
129   }
130 };
131 
132 class WebAssemblyAsmParser final : public MCTargetAsmParser {
133   MCAsmParser &Parser;
134   MCAsmLexer &Lexer;
135 
136   // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
137   std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
138 
139 public:
140   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
141                        const MCInstrInfo &MII, const MCTargetOptions &Options)
142       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
143         Lexer(Parser.getLexer()) {
144     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
145   }
146 
147   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
148     Signatures.push_back(std::move(Sig));
149   }
150 
151 #define GET_ASSEMBLER_HEADER
152 #include "WebAssemblyGenAsmMatcher.inc"
153 
154   // TODO: This is required to be implemented, but appears unused.
155   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
156                      SMLoc & /*EndLoc*/) override {
157     llvm_unreachable("ParseRegister is not implemented.");
158   }
159 
160   bool Error(const StringRef &msg, const AsmToken &tok) {
161     return Parser.Error(tok.getLoc(), msg + tok.getString());
162   }
163 
164   bool IsNext(AsmToken::TokenKind Kind) {
165     auto ok = Lexer.is(Kind);
166     if (ok)
167       Parser.Lex();
168     return ok;
169   }
170 
171   bool Expect(AsmToken::TokenKind Kind, const char *KindName) {
172     if (!IsNext(Kind))
173       return Error(std::string("Expected ") + KindName + ", instead got: ",
174                    Lexer.getTok());
175     return false;
176   }
177 
178   StringRef ExpectIdent() {
179     if (!Lexer.is(AsmToken::Identifier)) {
180       Error("Expected identifier, got: ", Lexer.getTok());
181       return StringRef();
182     }
183     auto Name = Lexer.getTok().getString();
184     Parser.Lex();
185     return Name;
186   }
187 
188   Optional<wasm::ValType> ParseType(const StringRef &Type) {
189     // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
190     // "invalid" value.
191     if (Type == "i32") return wasm::ValType::I32;
192     if (Type == "i64") return wasm::ValType::I64;
193     if (Type == "f32") return wasm::ValType::F32;
194     if (Type == "f64") return wasm::ValType::F64;
195     if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
196         Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
197         Type == "f64x2") return wasm::ValType::V128;
198     return Optional<wasm::ValType>();
199   }
200 
201   bool ParseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
202     while (Lexer.is(AsmToken::Identifier)) {
203       auto Type = ParseType(Lexer.getTok().getString());
204       if (!Type)
205         return true;
206       Types.push_back(Type.getValue());
207       Parser.Lex();
208       if (!IsNext(AsmToken::Comma))
209         break;
210     }
211     return false;
212   }
213 
214   void ParseSingleInteger(bool IsNegative, OperandVector &Operands) {
215     auto &Int = Lexer.getTok();
216     int64_t Val = Int.getIntVal();
217     if (IsNegative)
218       Val = -Val;
219     Operands.push_back(make_unique<WebAssemblyOperand>(
220         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
221         WebAssemblyOperand::IntOp{Val}));
222     Parser.Lex();
223   }
224 
225   bool ParseOperandStartingWithInteger(bool IsNegative, OperandVector &Operands,
226                                        StringRef InstName) {
227     ParseSingleInteger(IsNegative, Operands);
228     // FIXME: there is probably a cleaner way to do this.
229     auto IsLoadStore = InstName.startswith("load") ||
230                        InstName.startswith("store") ||
231                        InstName.startswith("atomic_load") ||
232                        InstName.startswith("atomic_store");
233     if (IsLoadStore) {
234       // Parse load/store operands of the form: offset align
235       auto &Offset = Lexer.getTok();
236       if (Offset.is(AsmToken::Integer)) {
237         ParseSingleInteger(false, Operands);
238       } else {
239         // Alignment not specified.
240         // FIXME: correctly derive a default from the instruction.
241         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
242         // an opcode until after the assembly matcher.
243         Operands.push_back(make_unique<WebAssemblyOperand>(
244             WebAssemblyOperand::Integer, Offset.getLoc(), Offset.getEndLoc(),
245             WebAssemblyOperand::IntOp{0}));
246       }
247     }
248     return false;
249   }
250 
251   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
252                         SMLoc NameLoc, OperandVector &Operands) override {
253     // Note: Name does NOT point into the sourcecode, but to a local, so
254     // use NameLoc instead.
255     Name = StringRef(NameLoc.getPointer(), Name.size());
256     // WebAssembly has instructions with / in them, which AsmLexer parses
257     // as seperate tokens, so if we find such tokens immediately adjacent (no
258     // whitespace), expand the name to include them:
259     for (;;) {
260       auto &Sep = Lexer.getTok();
261       if (Sep.getLoc().getPointer() != Name.end() ||
262           Sep.getKind() != AsmToken::Slash) break;
263       // Extend name with /
264       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
265       Parser.Lex();
266       // We must now find another identifier, or error.
267       auto &Id = Lexer.getTok();
268       if (Id.getKind() != AsmToken::Identifier ||
269           Id.getLoc().getPointer() != Name.end())
270         return Error("Incomplete instruction name: ", Id);
271       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
272       Parser.Lex();
273     }
274     // Now construct the name as first operand.
275     Operands.push_back(make_unique<WebAssemblyOperand>(
276         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
277         WebAssemblyOperand::TokOp{Name}));
278     auto NamePair = Name.split('.');
279     // If no '.', there is no type prefix.
280     auto BaseName = NamePair.second.empty() ? NamePair.first : NamePair.second;
281     while (Lexer.isNot(AsmToken::EndOfStatement)) {
282       auto &Tok = Lexer.getTok();
283       switch (Tok.getKind()) {
284       case AsmToken::Identifier: {
285         auto &Id = Lexer.getTok();
286         const MCExpr *Val;
287         SMLoc End;
288         if (Parser.parsePrimaryExpr(Val, End))
289           return Error("Cannot parse symbol: ", Lexer.getTok());
290         Operands.push_back(make_unique<WebAssemblyOperand>(
291             WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
292             WebAssemblyOperand::SymOp{Val}));
293         break;
294       }
295       case AsmToken::Minus:
296         Parser.Lex();
297         if (Lexer.isNot(AsmToken::Integer))
298           return Error("Expected integer instead got: ", Lexer.getTok());
299         if (ParseOperandStartingWithInteger(true, Operands, BaseName))
300           return true;
301         break;
302       case AsmToken::Integer:
303         if (ParseOperandStartingWithInteger(false, Operands, BaseName))
304           return true;
305         break;
306       case AsmToken::Real: {
307         double Val;
308         if (Tok.getString().getAsDouble(Val, false))
309           return Error("Cannot parse real: ", Tok);
310         Operands.push_back(make_unique<WebAssemblyOperand>(
311             WebAssemblyOperand::Float, Tok.getLoc(), Tok.getEndLoc(),
312             WebAssemblyOperand::FltOp{Val}));
313         Parser.Lex();
314         break;
315       }
316       default:
317         return Error("Unexpected token in operand: ", Tok);
318       }
319       if (Lexer.isNot(AsmToken::EndOfStatement)) {
320         if (Expect(AsmToken::Comma, ","))
321           return true;
322       }
323     }
324     Parser.Lex();
325     // Block instructions require a signature index, but these are missing in
326     // assembly, so we add a dummy one explicitly (since we have no control
327     // over signature tables here, we assume these will be regenerated when
328     // the wasm module is generated).
329     if (BaseName == "block" || BaseName == "loop" || BaseName == "try") {
330       Operands.push_back(make_unique<WebAssemblyOperand>(
331           WebAssemblyOperand::Integer, NameLoc, NameLoc,
332           WebAssemblyOperand::IntOp{-1}));
333     }
334     return false;
335   }
336 
337   // This function processes wasm-specific directives streamed to
338   // WebAssemblyTargetStreamer, all others go to the generic parser
339   // (see WasmAsmParser).
340   bool ParseDirective(AsmToken DirectiveID) override {
341     // This function has a really weird return value behavior that is different
342     // from all the other parsing functions:
343     // - return true && no tokens consumed -> don't know this directive / let
344     //   the generic parser handle it.
345     // - return true && tokens consumed -> a parsing error occurred.
346     // - return false -> processed this directive successfully.
347     assert(DirectiveID.getKind() == AsmToken::Identifier);
348     auto &Out = getStreamer();
349     auto &TOut =
350         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
351     // TODO: any time we return an error, at least one token must have been
352     // consumed, otherwise this will not signal an error to the caller.
353     if (DirectiveID.getString() == ".globaltype") {
354       auto SymName = ExpectIdent();
355       if (SymName.empty()) return true;
356       if (Expect(AsmToken::Comma, ",")) return true;
357       auto TypeTok = Lexer.getTok();
358       auto TypeName = ExpectIdent();
359       if (TypeName.empty()) return true;
360       auto Type = ParseType(TypeName);
361       if (!Type)
362         return Error("Unknown type in .globaltype directive: ", TypeTok);
363       // Now set this symbol with the correct type.
364       auto WasmSym = cast<MCSymbolWasm>(
365                     TOut.getStreamer().getContext().getOrCreateSymbol(SymName));
366       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
367       WasmSym->setGlobalType(
368             wasm::WasmGlobalType{uint8_t(Type.getValue()), true});
369       // And emit the directive again.
370       TOut.emitGlobalType(WasmSym);
371       return Expect(AsmToken::EndOfStatement, "EOL");
372     } else if (DirectiveID.getString() == ".functype") {
373       auto SymName = ExpectIdent();
374       if (SymName.empty()) return true;
375       auto WasmSym = cast<MCSymbolWasm>(
376                     TOut.getStreamer().getContext().getOrCreateSymbol(SymName));
377       auto Signature = make_unique<wasm::WasmSignature>();
378       if (Expect(AsmToken::LParen, "(")) return true;
379       if (ParseRegTypeList(Signature->Params)) return true;
380       if (Expect(AsmToken::RParen, ")")) return true;
381       if (Expect(AsmToken::MinusGreater, "->")) return true;
382       if (Expect(AsmToken::LParen, "(")) return true;
383       if (ParseRegTypeList(Signature->Returns)) return true;
384       if (Expect(AsmToken::RParen, ")")) return true;
385       WasmSym->setSignature(Signature.get());
386       addSignature(std::move(Signature));
387       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
388       TOut.emitFunctionType(WasmSym);
389       return Expect(AsmToken::EndOfStatement, "EOL");
390     } else if (DirectiveID.getString() == ".local") {
391       SmallVector<wasm::ValType, 4> Locals;
392       if (ParseRegTypeList(Locals)) return true;
393       TOut.emitLocal(Locals);
394       return Expect(AsmToken::EndOfStatement, "EOL");
395     }
396     return true;  // We didn't process this directive.
397   }
398 
399   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
400                                OperandVector &Operands, MCStreamer &Out,
401                                uint64_t &ErrorInfo,
402                                bool MatchingInlineAsm) override {
403     MCInst Inst;
404     unsigned MatchResult =
405         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
406     switch (MatchResult) {
407     case Match_Success: {
408       Out.EmitInstruction(Inst, getSTI());
409       return false;
410     }
411     case Match_MissingFeature:
412       return Parser.Error(
413           IDLoc, "instruction requires a WASM feature not currently enabled");
414     case Match_MnemonicFail:
415       return Parser.Error(IDLoc, "invalid instruction");
416     case Match_NearMisses:
417       return Parser.Error(IDLoc, "ambiguous instruction");
418     case Match_InvalidTiedOperand:
419     case Match_InvalidOperand: {
420       SMLoc ErrorLoc = IDLoc;
421       if (ErrorInfo != ~0ULL) {
422         if (ErrorInfo >= Operands.size())
423           return Parser.Error(IDLoc, "too few operands for instruction");
424         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
425         if (ErrorLoc == SMLoc())
426           ErrorLoc = IDLoc;
427       }
428       return Parser.Error(ErrorLoc, "invalid operand for instruction");
429     }
430     }
431     llvm_unreachable("Implement any new match types added!");
432   }
433 };
434 } // end anonymous namespace
435 
436 // Force static initialization.
437 extern "C" void LLVMInitializeWebAssemblyAsmParser() {
438   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
439   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
440 }
441 
442 #define GET_REGISTER_MATCHER
443 #define GET_MATCHER_IMPLEMENTATION
444 #include "WebAssemblyGenAsmMatcher.inc"
445