1 //==- WebAssemblyAsmParser.cpp - Assembler for WebAssembly -*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file is part of the WebAssembly Assembler.
11 ///
12 /// It contains code to translate a parsed .s file into MCInsts.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
18 #include "TargetInfo/WebAssemblyTargetInfo.h"
19 #include "WebAssembly.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
26 #include "llvm/MC/MCSectionWasm.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCSymbolWasm.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/TargetRegistry.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "wasm-asm-parser"
37 
38 static const char *getSubtargetFeatureName(uint64_t Val);
39 
40 namespace {
41 
42 /// WebAssemblyOperand - Instances of this class represent the operands in a
43 /// parsed Wasm machine instruction.
44 struct WebAssemblyOperand : public MCParsedAsmOperand {
45   enum KindTy { Token, Integer, Float, Symbol, BrList } Kind;
46 
47   SMLoc StartLoc, EndLoc;
48 
49   struct TokOp {
50     StringRef Tok;
51   };
52 
53   struct IntOp {
54     int64_t Val;
55   };
56 
57   struct FltOp {
58     double Val;
59   };
60 
61   struct SymOp {
62     const MCExpr *Exp;
63   };
64 
65   struct BrLOp {
66     std::vector<unsigned> List;
67   };
68 
69   union {
70     struct TokOp Tok;
71     struct IntOp Int;
72     struct FltOp Flt;
73     struct SymOp Sym;
74     struct BrLOp BrL;
75   };
76 
77   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
78       : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
79   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
80       : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
81   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
82       : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
83   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
84       : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
85   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End)
86       : Kind(K), StartLoc(Start), EndLoc(End), BrL() {}
87 
88   ~WebAssemblyOperand() {
89     if (isBrList())
90       BrL.~BrLOp();
91   }
92 
93   bool isToken() const override { return Kind == Token; }
94   bool isImm() const override { return Kind == Integer || Kind == Symbol; }
95   bool isFPImm() const { return Kind == Float; }
96   bool isMem() const override { return false; }
97   bool isReg() const override { return false; }
98   bool isBrList() const { return Kind == BrList; }
99 
100   unsigned getReg() const override {
101     llvm_unreachable("Assembly inspects a register operand");
102     return 0;
103   }
104 
105   StringRef getToken() const {
106     assert(isToken());
107     return Tok.Tok;
108   }
109 
110   SMLoc getStartLoc() const override { return StartLoc; }
111   SMLoc getEndLoc() const override { return EndLoc; }
112 
113   void addRegOperands(MCInst &, unsigned) const {
114     // Required by the assembly matcher.
115     llvm_unreachable("Assembly matcher creates register operands");
116   }
117 
118   void addImmOperands(MCInst &Inst, unsigned N) const {
119     assert(N == 1 && "Invalid number of operands!");
120     if (Kind == Integer)
121       Inst.addOperand(MCOperand::createImm(Int.Val));
122     else if (Kind == Symbol)
123       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
124     else
125       llvm_unreachable("Should be integer immediate or symbol!");
126   }
127 
128   void addFPImmOperands(MCInst &Inst, unsigned N) const {
129     assert(N == 1 && "Invalid number of operands!");
130     if (Kind == Float)
131       Inst.addOperand(MCOperand::createFPImm(Flt.Val));
132     else
133       llvm_unreachable("Should be float immediate!");
134   }
135 
136   void addBrListOperands(MCInst &Inst, unsigned N) const {
137     assert(N == 1 && isBrList() && "Invalid BrList!");
138     for (auto Br : BrL.List)
139       Inst.addOperand(MCOperand::createImm(Br));
140   }
141 
142   void print(raw_ostream &OS) const override {
143     switch (Kind) {
144     case Token:
145       OS << "Tok:" << Tok.Tok;
146       break;
147     case Integer:
148       OS << "Int:" << Int.Val;
149       break;
150     case Float:
151       OS << "Flt:" << Flt.Val;
152       break;
153     case Symbol:
154       OS << "Sym:" << Sym.Exp;
155       break;
156     case BrList:
157       OS << "BrList:" << BrL.List.size();
158       break;
159     }
160   }
161 };
162 
163 class WebAssemblyAsmParser final : public MCTargetAsmParser {
164   MCAsmParser &Parser;
165   MCAsmLexer &Lexer;
166 
167   // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
168   std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
169   std::vector<std::unique_ptr<std::string>> Names;
170 
171   // Order of labels, directives and instructions in a .s file have no
172   // syntactical enforcement. This class is a callback from the actual parser,
173   // and yet we have to be feeding data to the streamer in a very particular
174   // order to ensure a correct binary encoding that matches the regular backend
175   // (the streamer does not enforce this). This "state machine" enum helps
176   // guarantee that correct order.
177   enum ParserState {
178     FileStart,
179     Label,
180     FunctionStart,
181     FunctionLocals,
182     Instructions,
183     EndFunction,
184     DataSection,
185   } CurrentState = FileStart;
186 
187   // For ensuring blocks are properly nested.
188   enum NestingType {
189     Function,
190     Block,
191     Loop,
192     Try,
193     If,
194     Else,
195     Undefined,
196   };
197   std::vector<NestingType> NestingStack;
198 
199   // We track this to see if a .functype following a label is the same,
200   // as this is how we recognize the start of a function.
201   MCSymbol *LastLabel = nullptr;
202   MCSymbol *LastFunctionLabel = nullptr;
203 
204 public:
205   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
206                        const MCInstrInfo &MII, const MCTargetOptions &Options)
207       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
208         Lexer(Parser.getLexer()) {
209     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
210   }
211 
212 #define GET_ASSEMBLER_HEADER
213 #include "WebAssemblyGenAsmMatcher.inc"
214 
215   // TODO: This is required to be implemented, but appears unused.
216   bool ParseRegister(unsigned & /*RegNo*/, SMLoc & /*StartLoc*/,
217                      SMLoc & /*EndLoc*/) override {
218     llvm_unreachable("ParseRegister is not implemented.");
219   }
220   OperandMatchResultTy tryParseRegister(unsigned & /*RegNo*/,
221                                         SMLoc & /*StartLoc*/,
222                                         SMLoc & /*EndLoc*/) override {
223     llvm_unreachable("tryParseRegister is not implemented.");
224   }
225 
226   bool error(const Twine &Msg, const AsmToken &Tok) {
227     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
228   }
229 
230   bool error(const Twine &Msg) {
231     return Parser.Error(Lexer.getTok().getLoc(), Msg);
232   }
233 
234   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
235     Signatures.push_back(std::move(Sig));
236   }
237 
238   StringRef storeName(StringRef Name) {
239     std::unique_ptr<std::string> N = std::make_unique<std::string>(Name);
240     Names.push_back(std::move(N));
241     return *Names.back();
242   }
243 
244   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
245     switch (NT) {
246     case Function:
247       return {"function", "end_function"};
248     case Block:
249       return {"block", "end_block"};
250     case Loop:
251       return {"loop", "end_loop"};
252     case Try:
253       return {"try", "end_try"};
254     case If:
255       return {"if", "end_if"};
256     case Else:
257       return {"else", "end_if"};
258     default:
259       llvm_unreachable("unknown NestingType");
260     }
261   }
262 
263   void push(NestingType NT) { NestingStack.push_back(NT); }
264 
265   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
266     if (NestingStack.empty())
267       return error(Twine("End of block construct with no start: ") + Ins);
268     auto Top = NestingStack.back();
269     if (Top != NT1 && Top != NT2)
270       return error(Twine("Block construct type mismatch, expected: ") +
271                    nestingString(Top).second + ", instead got: " + Ins);
272     NestingStack.pop_back();
273     return false;
274   }
275 
276   bool ensureEmptyNestingStack() {
277     auto Err = !NestingStack.empty();
278     while (!NestingStack.empty()) {
279       error(Twine("Unmatched block construct(s) at function end: ") +
280             nestingString(NestingStack.back()).first);
281       NestingStack.pop_back();
282     }
283     return Err;
284   }
285 
286   bool isNext(AsmToken::TokenKind Kind) {
287     auto Ok = Lexer.is(Kind);
288     if (Ok)
289       Parser.Lex();
290     return Ok;
291   }
292 
293   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
294     if (!isNext(Kind))
295       return error(std::string("Expected ") + KindName + ", instead got: ",
296                    Lexer.getTok());
297     return false;
298   }
299 
300   StringRef expectIdent() {
301     if (!Lexer.is(AsmToken::Identifier)) {
302       error("Expected identifier, got: ", Lexer.getTok());
303       return StringRef();
304     }
305     auto Name = Lexer.getTok().getString();
306     Parser.Lex();
307     return Name;
308   }
309 
310   Optional<wasm::ValType> parseType(const StringRef &Type) {
311     // FIXME: can't use StringSwitch because wasm::ValType doesn't have a
312     // "invalid" value.
313     if (Type == "i32")
314       return wasm::ValType::I32;
315     if (Type == "i64")
316       return wasm::ValType::I64;
317     if (Type == "f32")
318       return wasm::ValType::F32;
319     if (Type == "f64")
320       return wasm::ValType::F64;
321     if (Type == "v128" || Type == "i8x16" || Type == "i16x8" ||
322         Type == "i32x4" || Type == "i64x2" || Type == "f32x4" ||
323         Type == "f64x2")
324       return wasm::ValType::V128;
325     if (Type == "exnref")
326       return wasm::ValType::EXNREF;
327     if (Type == "funcref")
328       return wasm::ValType::FUNCREF;
329     if (Type == "externref")
330       return wasm::ValType::EXTERNREF;
331     return Optional<wasm::ValType>();
332   }
333 
334   WebAssembly::BlockType parseBlockType(StringRef ID) {
335     // Multivalue block types are handled separately in parseSignature
336     return StringSwitch<WebAssembly::BlockType>(ID)
337         .Case("i32", WebAssembly::BlockType::I32)
338         .Case("i64", WebAssembly::BlockType::I64)
339         .Case("f32", WebAssembly::BlockType::F32)
340         .Case("f64", WebAssembly::BlockType::F64)
341         .Case("v128", WebAssembly::BlockType::V128)
342         .Case("exnref", WebAssembly::BlockType::Exnref)
343         .Case("void", WebAssembly::BlockType::Void)
344         .Default(WebAssembly::BlockType::Invalid);
345   }
346 
347   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
348     while (Lexer.is(AsmToken::Identifier)) {
349       auto Type = parseType(Lexer.getTok().getString());
350       if (!Type)
351         return error("unknown type: ", Lexer.getTok());
352       Types.push_back(Type.getValue());
353       Parser.Lex();
354       if (!isNext(AsmToken::Comma))
355         break;
356     }
357     return false;
358   }
359 
360   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
361     auto &Int = Lexer.getTok();
362     int64_t Val = Int.getIntVal();
363     if (IsNegative)
364       Val = -Val;
365     Operands.push_back(std::make_unique<WebAssemblyOperand>(
366         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
367         WebAssemblyOperand::IntOp{Val}));
368     Parser.Lex();
369   }
370 
371   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
372     auto &Flt = Lexer.getTok();
373     double Val;
374     if (Flt.getString().getAsDouble(Val, false))
375       return error("Cannot parse real: ", Flt);
376     if (IsNegative)
377       Val = -Val;
378     Operands.push_back(std::make_unique<WebAssemblyOperand>(
379         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
380         WebAssemblyOperand::FltOp{Val}));
381     Parser.Lex();
382     return false;
383   }
384 
385   bool parseSpecialFloatMaybe(bool IsNegative, OperandVector &Operands) {
386     if (Lexer.isNot(AsmToken::Identifier))
387       return true;
388     auto &Flt = Lexer.getTok();
389     auto S = Flt.getString();
390     double Val;
391     if (S.compare_lower("infinity") == 0) {
392       Val = std::numeric_limits<double>::infinity();
393     } else if (S.compare_lower("nan") == 0) {
394       Val = std::numeric_limits<double>::quiet_NaN();
395     } else {
396       return true;
397     }
398     if (IsNegative)
399       Val = -Val;
400     Operands.push_back(std::make_unique<WebAssemblyOperand>(
401         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
402         WebAssemblyOperand::FltOp{Val}));
403     Parser.Lex();
404     return false;
405   }
406 
407   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
408     // FIXME: there is probably a cleaner way to do this.
409     auto IsLoadStore = InstName.find(".load") != StringRef::npos ||
410                        InstName.find(".store") != StringRef::npos;
411     auto IsAtomic = InstName.find("atomic.") != StringRef::npos;
412     if (IsLoadStore || IsAtomic) {
413       // Parse load/store operands of the form: offset:p2align=align
414       if (IsLoadStore && isNext(AsmToken::Colon)) {
415         auto Id = expectIdent();
416         if (Id != "p2align")
417           return error("Expected p2align, instead got: " + Id);
418         if (expect(AsmToken::Equal, "="))
419           return true;
420         if (!Lexer.is(AsmToken::Integer))
421           return error("Expected integer constant");
422         parseSingleInteger(false, Operands);
423       } else {
424         // v128.{load,store}{8,16,32,64}_lane has both a memarg and a lane
425         // index. We need to avoid parsing an extra alignment operand for the
426         // lane index.
427         auto IsLoadStoreLane = InstName.find("_lane") != StringRef::npos;
428         if (IsLoadStoreLane && Operands.size() == 4)
429           return false;
430         // Alignment not specified (or atomics, must use default alignment).
431         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
432         // an opcode until after the assembly matcher, so set a default to fix
433         // up later.
434         auto Tok = Lexer.getTok();
435         Operands.push_back(std::make_unique<WebAssemblyOperand>(
436             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
437             WebAssemblyOperand::IntOp{-1}));
438       }
439     }
440     return false;
441   }
442 
443   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
444                            WebAssembly::BlockType BT) {
445     Operands.push_back(std::make_unique<WebAssemblyOperand>(
446         WebAssemblyOperand::Integer, NameLoc, NameLoc,
447         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
448   }
449 
450   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
451                         SMLoc NameLoc, OperandVector &Operands) override {
452     // Note: Name does NOT point into the sourcecode, but to a local, so
453     // use NameLoc instead.
454     Name = StringRef(NameLoc.getPointer(), Name.size());
455 
456     // WebAssembly has instructions with / in them, which AsmLexer parses
457     // as separate tokens, so if we find such tokens immediately adjacent (no
458     // whitespace), expand the name to include them:
459     for (;;) {
460       auto &Sep = Lexer.getTok();
461       if (Sep.getLoc().getPointer() != Name.end() ||
462           Sep.getKind() != AsmToken::Slash)
463         break;
464       // Extend name with /
465       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
466       Parser.Lex();
467       // We must now find another identifier, or error.
468       auto &Id = Lexer.getTok();
469       if (Id.getKind() != AsmToken::Identifier ||
470           Id.getLoc().getPointer() != Name.end())
471         return error("Incomplete instruction name: ", Id);
472       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
473       Parser.Lex();
474     }
475 
476     // Now construct the name as first operand.
477     Operands.push_back(std::make_unique<WebAssemblyOperand>(
478         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
479         WebAssemblyOperand::TokOp{Name}));
480 
481     // If this instruction is part of a control flow structure, ensure
482     // proper nesting.
483     bool ExpectBlockType = false;
484     bool ExpectFuncType = false;
485     if (Name == "block") {
486       push(Block);
487       ExpectBlockType = true;
488     } else if (Name == "loop") {
489       push(Loop);
490       ExpectBlockType = true;
491     } else if (Name == "try") {
492       push(Try);
493       ExpectBlockType = true;
494     } else if (Name == "if") {
495       push(If);
496       ExpectBlockType = true;
497     } else if (Name == "else") {
498       if (pop(Name, If))
499         return true;
500       push(Else);
501     } else if (Name == "catch") {
502       if (pop(Name, Try))
503         return true;
504       push(Try);
505     } else if (Name == "end_if") {
506       if (pop(Name, If, Else))
507         return true;
508     } else if (Name == "end_try") {
509       if (pop(Name, Try))
510         return true;
511     } else if (Name == "end_loop") {
512       if (pop(Name, Loop))
513         return true;
514     } else if (Name == "end_block") {
515       if (pop(Name, Block))
516         return true;
517     } else if (Name == "end_function") {
518       ensureLocals(getStreamer());
519       CurrentState = EndFunction;
520       if (pop(Name, Function) || ensureEmptyNestingStack())
521         return true;
522     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
523       ExpectFuncType = true;
524     }
525 
526     if (ExpectFuncType || (ExpectBlockType && Lexer.is(AsmToken::LParen))) {
527       // This has a special TYPEINDEX operand which in text we
528       // represent as a signature, such that we can re-build this signature,
529       // attach it to an anonymous symbol, which is what WasmObjectWriter
530       // expects to be able to recreate the actual unique-ified type indices.
531       auto Loc = Parser.getTok();
532       auto Signature = std::make_unique<wasm::WasmSignature>();
533       if (parseSignature(Signature.get()))
534         return true;
535       // Got signature as block type, don't need more
536       ExpectBlockType = false;
537       auto &Ctx = getStreamer().getContext();
538       // The "true" here will cause this to be a nameless symbol.
539       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
540       auto *WasmSym = cast<MCSymbolWasm>(Sym);
541       WasmSym->setSignature(Signature.get());
542       addSignature(std::move(Signature));
543       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
544       const MCExpr *Expr = MCSymbolRefExpr::create(
545           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
546       Operands.push_back(std::make_unique<WebAssemblyOperand>(
547           WebAssemblyOperand::Symbol, Loc.getLoc(), Loc.getEndLoc(),
548           WebAssemblyOperand::SymOp{Expr}));
549     }
550 
551     while (Lexer.isNot(AsmToken::EndOfStatement)) {
552       auto &Tok = Lexer.getTok();
553       switch (Tok.getKind()) {
554       case AsmToken::Identifier: {
555         if (!parseSpecialFloatMaybe(false, Operands))
556           break;
557         auto &Id = Lexer.getTok();
558         if (ExpectBlockType) {
559           // Assume this identifier is a block_type.
560           auto BT = parseBlockType(Id.getString());
561           if (BT == WebAssembly::BlockType::Invalid)
562             return error("Unknown block type: ", Id);
563           addBlockTypeOperand(Operands, NameLoc, BT);
564           Parser.Lex();
565         } else {
566           // Assume this identifier is a label.
567           const MCExpr *Val;
568           SMLoc End;
569           if (Parser.parseExpression(Val, End))
570             return error("Cannot parse symbol: ", Lexer.getTok());
571           Operands.push_back(std::make_unique<WebAssemblyOperand>(
572               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
573               WebAssemblyOperand::SymOp{Val}));
574           if (checkForP2AlignIfLoadStore(Operands, Name))
575             return true;
576         }
577         break;
578       }
579       case AsmToken::Minus:
580         Parser.Lex();
581         if (Lexer.is(AsmToken::Integer)) {
582           parseSingleInteger(true, Operands);
583           if (checkForP2AlignIfLoadStore(Operands, Name))
584             return true;
585         } else if(Lexer.is(AsmToken::Real)) {
586           if (parseSingleFloat(true, Operands))
587             return true;
588         } else if (!parseSpecialFloatMaybe(true, Operands)) {
589         } else {
590           return error("Expected numeric constant instead got: ",
591                        Lexer.getTok());
592         }
593         break;
594       case AsmToken::Integer:
595         parseSingleInteger(false, Operands);
596         if (checkForP2AlignIfLoadStore(Operands, Name))
597           return true;
598         break;
599       case AsmToken::Real: {
600         if (parseSingleFloat(false, Operands))
601           return true;
602         break;
603       }
604       case AsmToken::LCurly: {
605         Parser.Lex();
606         auto Op = std::make_unique<WebAssemblyOperand>(
607             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
608         if (!Lexer.is(AsmToken::RCurly))
609           for (;;) {
610             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
611             expect(AsmToken::Integer, "integer");
612             if (!isNext(AsmToken::Comma))
613               break;
614           }
615         expect(AsmToken::RCurly, "}");
616         Operands.push_back(std::move(Op));
617         break;
618       }
619       default:
620         return error("Unexpected token in operand: ", Tok);
621       }
622       if (Lexer.isNot(AsmToken::EndOfStatement)) {
623         if (expect(AsmToken::Comma, ","))
624           return true;
625       }
626     }
627     if (ExpectBlockType && Operands.size() == 1) {
628       // Support blocks with no operands as default to void.
629       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
630     }
631     Parser.Lex();
632     return false;
633   }
634 
635   void onLabelParsed(MCSymbol *Symbol) override {
636     LastLabel = Symbol;
637     CurrentState = Label;
638   }
639 
640   bool parseSignature(wasm::WasmSignature *Signature) {
641     if (expect(AsmToken::LParen, "("))
642       return true;
643     if (parseRegTypeList(Signature->Params))
644       return true;
645     if (expect(AsmToken::RParen, ")"))
646       return true;
647     if (expect(AsmToken::MinusGreater, "->"))
648       return true;
649     if (expect(AsmToken::LParen, "("))
650       return true;
651     if (parseRegTypeList(Signature->Returns))
652       return true;
653     if (expect(AsmToken::RParen, ")"))
654       return true;
655     return false;
656   }
657 
658   bool CheckDataSection() {
659     if (CurrentState != DataSection) {
660       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
661       if (WS && WS->getKind().isText())
662         return error("data directive must occur in a data segment: ",
663                      Lexer.getTok());
664     }
665     CurrentState = DataSection;
666     return false;
667   }
668 
669   // This function processes wasm-specific directives streamed to
670   // WebAssemblyTargetStreamer, all others go to the generic parser
671   // (see WasmAsmParser).
672   bool ParseDirective(AsmToken DirectiveID) override {
673     // This function has a really weird return value behavior that is different
674     // from all the other parsing functions:
675     // - return true && no tokens consumed -> don't know this directive / let
676     //   the generic parser handle it.
677     // - return true && tokens consumed -> a parsing error occurred.
678     // - return false -> processed this directive successfully.
679     assert(DirectiveID.getKind() == AsmToken::Identifier);
680     auto &Out = getStreamer();
681     auto &TOut =
682         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
683     auto &Ctx = Out.getContext();
684 
685     // TODO: any time we return an error, at least one token must have been
686     // consumed, otherwise this will not signal an error to the caller.
687     if (DirectiveID.getString() == ".globaltype") {
688       auto SymName = expectIdent();
689       if (SymName.empty())
690         return true;
691       if (expect(AsmToken::Comma, ","))
692         return true;
693       auto TypeTok = Lexer.getTok();
694       auto TypeName = expectIdent();
695       if (TypeName.empty())
696         return true;
697       auto Type = parseType(TypeName);
698       if (!Type)
699         return error("Unknown type in .globaltype directive: ", TypeTok);
700       // Optional mutable modifier. Default to mutable for historical reasons.
701       // Ideally we would have gone with immutable as the default and used `mut`
702       // as the modifier to match the `.wat` format.
703       bool Mutable = true;
704       if (isNext(AsmToken::Comma)) {
705         TypeTok = Lexer.getTok();
706         auto Id = expectIdent();
707         if (Id == "immutable")
708           Mutable = false;
709         else
710           // Should we also allow `mutable` and `mut` here for clarity?
711           return error("Unknown type in .globaltype modifier: ", TypeTok);
712       }
713       // Now set this symbol with the correct type.
714       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
715       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
716       WasmSym->setGlobalType(
717           wasm::WasmGlobalType{uint8_t(Type.getValue()), Mutable});
718       // And emit the directive again.
719       TOut.emitGlobalType(WasmSym);
720       return expect(AsmToken::EndOfStatement, "EOL");
721     }
722 
723     if (DirectiveID.getString() == ".tabletype") {
724       auto SymName = expectIdent();
725       if (SymName.empty())
726         return true;
727       if (expect(AsmToken::Comma, ","))
728         return true;
729       auto TypeTok = Lexer.getTok();
730       auto TypeName = expectIdent();
731       if (TypeName.empty())
732         return true;
733       auto Type = parseType(TypeName);
734       if (!Type)
735         return error("Unknown type in .tabletype directive: ", TypeTok);
736 
737       // Now that we have the name and table type, we can actually create the
738       // symbol
739       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
740       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
741       WasmSym->setTableType(Type.getValue());
742       TOut.emitTableType(WasmSym);
743       return expect(AsmToken::EndOfStatement, "EOL");
744     }
745 
746     if (DirectiveID.getString() == ".functype") {
747       // This code has to send things to the streamer similar to
748       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
749       // TODO: would be good to factor this into a common function, but the
750       // assembler and backend really don't share any common code, and this code
751       // parses the locals separately.
752       auto SymName = expectIdent();
753       if (SymName.empty())
754         return true;
755       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
756       if (CurrentState == Label && WasmSym == LastLabel) {
757         // This .functype indicates a start of a function.
758         if (ensureEmptyNestingStack())
759           return true;
760         CurrentState = FunctionStart;
761         LastFunctionLabel = LastLabel;
762         push(Function);
763       }
764       auto Signature = std::make_unique<wasm::WasmSignature>();
765       if (parseSignature(Signature.get()))
766         return true;
767       WasmSym->setSignature(Signature.get());
768       addSignature(std::move(Signature));
769       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
770       TOut.emitFunctionType(WasmSym);
771       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
772       return expect(AsmToken::EndOfStatement, "EOL");
773     }
774 
775     if (DirectiveID.getString() == ".export_name") {
776       auto SymName = expectIdent();
777       if (SymName.empty())
778         return true;
779       if (expect(AsmToken::Comma, ","))
780         return true;
781       auto ExportName = expectIdent();
782       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
783       WasmSym->setExportName(storeName(ExportName));
784       TOut.emitExportName(WasmSym, ExportName);
785     }
786 
787     if (DirectiveID.getString() == ".import_module") {
788       auto SymName = expectIdent();
789       if (SymName.empty())
790         return true;
791       if (expect(AsmToken::Comma, ","))
792         return true;
793       auto ImportModule = expectIdent();
794       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
795       WasmSym->setImportModule(storeName(ImportModule));
796       TOut.emitImportModule(WasmSym, ImportModule);
797     }
798 
799     if (DirectiveID.getString() == ".import_name") {
800       auto SymName = expectIdent();
801       if (SymName.empty())
802         return true;
803       if (expect(AsmToken::Comma, ","))
804         return true;
805       auto ImportName = expectIdent();
806       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
807       WasmSym->setImportName(storeName(ImportName));
808       TOut.emitImportName(WasmSym, ImportName);
809     }
810 
811     if (DirectiveID.getString() == ".eventtype") {
812       auto SymName = expectIdent();
813       if (SymName.empty())
814         return true;
815       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
816       auto Signature = std::make_unique<wasm::WasmSignature>();
817       if (parseRegTypeList(Signature->Params))
818         return true;
819       WasmSym->setSignature(Signature.get());
820       addSignature(std::move(Signature));
821       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
822       TOut.emitEventType(WasmSym);
823       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
824       return expect(AsmToken::EndOfStatement, "EOL");
825     }
826 
827     if (DirectiveID.getString() == ".local") {
828       if (CurrentState != FunctionStart)
829         return error(".local directive should follow the start of a function",
830                      Lexer.getTok());
831       SmallVector<wasm::ValType, 4> Locals;
832       if (parseRegTypeList(Locals))
833         return true;
834       TOut.emitLocal(Locals);
835       CurrentState = FunctionLocals;
836       return expect(AsmToken::EndOfStatement, "EOL");
837     }
838 
839     if (DirectiveID.getString() == ".int8" ||
840         DirectiveID.getString() == ".int16" ||
841         DirectiveID.getString() == ".int32" ||
842         DirectiveID.getString() == ".int64") {
843       if (CheckDataSection()) return true;
844       const MCExpr *Val;
845       SMLoc End;
846       if (Parser.parseExpression(Val, End))
847         return error("Cannot parse .int expression: ", Lexer.getTok());
848       size_t NumBits = 0;
849       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
850       Out.emitValue(Val, NumBits / 8, End);
851       return expect(AsmToken::EndOfStatement, "EOL");
852     }
853 
854     if (DirectiveID.getString() == ".asciz") {
855       if (CheckDataSection()) return true;
856       std::string S;
857       if (Parser.parseEscapedString(S))
858         return error("Cannot parse string constant: ", Lexer.getTok());
859       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
860       return expect(AsmToken::EndOfStatement, "EOL");
861     }
862 
863     return true; // We didn't process this directive.
864   }
865 
866   // Called either when the first instruction is parsed of the function ends.
867   void ensureLocals(MCStreamer &Out) {
868     if (CurrentState == FunctionStart) {
869       // We haven't seen a .local directive yet. The streamer requires locals to
870       // be encoded as a prelude to the instructions, so emit an empty list of
871       // locals here.
872       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
873           *Out.getTargetStreamer());
874       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
875       CurrentState = FunctionLocals;
876     }
877   }
878 
879   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
880                                OperandVector &Operands, MCStreamer &Out,
881                                uint64_t &ErrorInfo,
882                                bool MatchingInlineAsm) override {
883     MCInst Inst;
884     Inst.setLoc(IDLoc);
885     FeatureBitset MissingFeatures;
886     unsigned MatchResult = MatchInstructionImpl(
887         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm);
888     switch (MatchResult) {
889     case Match_Success: {
890       ensureLocals(Out);
891       // Fix unknown p2align operands.
892       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
893       if (Align != -1U) {
894         auto &Op0 = Inst.getOperand(0);
895         if (Op0.getImm() == -1)
896           Op0.setImm(Align);
897       }
898       if (getSTI().getTargetTriple().isArch64Bit()) {
899         // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having
900         // an offset64 arg instead of offset32, but to the assembler matcher
901         // they're both immediates so don't get selected for.
902         auto Opc64 = WebAssembly::getWasm64Opcode(
903             static_cast<uint16_t>(Inst.getOpcode()));
904         if (Opc64 >= 0) {
905           Inst.setOpcode(Opc64);
906         }
907       }
908       Out.emitInstruction(Inst, getSTI());
909       if (CurrentState == EndFunction) {
910         onEndOfFunction();
911       } else {
912         CurrentState = Instructions;
913       }
914       return false;
915     }
916     case Match_MissingFeature: {
917       assert(MissingFeatures.count() > 0 && "Expected missing features");
918       SmallString<128> Message;
919       raw_svector_ostream OS(Message);
920       OS << "instruction requires:";
921       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
922         if (MissingFeatures.test(i))
923           OS << ' ' << getSubtargetFeatureName(i);
924       return Parser.Error(IDLoc, Message);
925     }
926     case Match_MnemonicFail:
927       return Parser.Error(IDLoc, "invalid instruction");
928     case Match_NearMisses:
929       return Parser.Error(IDLoc, "ambiguous instruction");
930     case Match_InvalidTiedOperand:
931     case Match_InvalidOperand: {
932       SMLoc ErrorLoc = IDLoc;
933       if (ErrorInfo != ~0ULL) {
934         if (ErrorInfo >= Operands.size())
935           return Parser.Error(IDLoc, "too few operands for instruction");
936         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
937         if (ErrorLoc == SMLoc())
938           ErrorLoc = IDLoc;
939       }
940       return Parser.Error(ErrorLoc, "invalid operand for instruction");
941     }
942     }
943     llvm_unreachable("Implement any new match types added!");
944   }
945 
946   void doBeforeLabelEmit(MCSymbol *Symbol) override {
947     // Start a new section for the next function automatically, since our
948     // object writer expects each function to have its own section. This way
949     // The user can't forget this "convention".
950     auto SymName = Symbol->getName();
951     if (SymName.startswith(".L"))
952       return; // Local Symbol.
953     // Only create a new text section if we're already in one.
954     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
955     if (!CWS || !CWS->getKind().isText())
956       return;
957     auto SecName = ".text." + SymName;
958     auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
959     getStreamer().SwitchSection(WS);
960     // Also generate DWARF for this section if requested.
961     if (getContext().getGenDwarfForAssembly())
962       getContext().addGenDwarfSection(WS);
963   }
964 
965   void onEndOfFunction() {
966     // Automatically output a .size directive, so it becomes optional for the
967     // user.
968     if (!LastFunctionLabel) return;
969     auto TempSym = getContext().createLinkerPrivateTempSymbol();
970     getStreamer().emitLabel(TempSym);
971     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
972     auto End = MCSymbolRefExpr::create(TempSym, getContext());
973     auto Expr =
974         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
975     getStreamer().emitELFSize(LastFunctionLabel, Expr);
976   }
977 
978   void onEndOfFile() override { ensureEmptyNestingStack(); }
979 };
980 } // end anonymous namespace
981 
982 // Force static initialization.
983 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
984   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
985   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
986 }
987 
988 #define GET_REGISTER_MATCHER
989 #define GET_SUBTARGET_FEATURE_NAME
990 #define GET_MATCHER_IMPLEMENTATION
991 #include "WebAssemblyGenAsmMatcher.inc"
992