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