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         // Alignment not specified (or atomics, must use default alignment).
425         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
426         // an opcode until after the assembly matcher, so set a default to fix
427         // up later.
428         auto Tok = Lexer.getTok();
429         Operands.push_back(std::make_unique<WebAssemblyOperand>(
430             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
431             WebAssemblyOperand::IntOp{-1}));
432       }
433     }
434     return false;
435   }
436 
437   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
438                            WebAssembly::BlockType BT) {
439     Operands.push_back(std::make_unique<WebAssemblyOperand>(
440         WebAssemblyOperand::Integer, NameLoc, NameLoc,
441         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
442   }
443 
444   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
445                         SMLoc NameLoc, OperandVector &Operands) override {
446     // Note: Name does NOT point into the sourcecode, but to a local, so
447     // use NameLoc instead.
448     Name = StringRef(NameLoc.getPointer(), Name.size());
449 
450     // WebAssembly has instructions with / in them, which AsmLexer parses
451     // as separate tokens, so if we find such tokens immediately adjacent (no
452     // whitespace), expand the name to include them:
453     for (;;) {
454       auto &Sep = Lexer.getTok();
455       if (Sep.getLoc().getPointer() != Name.end() ||
456           Sep.getKind() != AsmToken::Slash)
457         break;
458       // Extend name with /
459       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
460       Parser.Lex();
461       // We must now find another identifier, or error.
462       auto &Id = Lexer.getTok();
463       if (Id.getKind() != AsmToken::Identifier ||
464           Id.getLoc().getPointer() != Name.end())
465         return error("Incomplete instruction name: ", Id);
466       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
467       Parser.Lex();
468     }
469 
470     // Now construct the name as first operand.
471     Operands.push_back(std::make_unique<WebAssemblyOperand>(
472         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
473         WebAssemblyOperand::TokOp{Name}));
474 
475     // If this instruction is part of a control flow structure, ensure
476     // proper nesting.
477     bool ExpectBlockType = false;
478     bool ExpectFuncType = false;
479     if (Name == "block") {
480       push(Block);
481       ExpectBlockType = true;
482     } else if (Name == "loop") {
483       push(Loop);
484       ExpectBlockType = true;
485     } else if (Name == "try") {
486       push(Try);
487       ExpectBlockType = true;
488     } else if (Name == "if") {
489       push(If);
490       ExpectBlockType = true;
491     } else if (Name == "else") {
492       if (pop(Name, If))
493         return true;
494       push(Else);
495     } else if (Name == "catch") {
496       if (pop(Name, Try))
497         return true;
498       push(Try);
499     } else if (Name == "end_if") {
500       if (pop(Name, If, Else))
501         return true;
502     } else if (Name == "end_try") {
503       if (pop(Name, Try))
504         return true;
505     } else if (Name == "end_loop") {
506       if (pop(Name, Loop))
507         return true;
508     } else if (Name == "end_block") {
509       if (pop(Name, Block))
510         return true;
511     } else if (Name == "end_function") {
512       ensureLocals(getStreamer());
513       CurrentState = EndFunction;
514       if (pop(Name, Function) || ensureEmptyNestingStack())
515         return true;
516     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
517       ExpectFuncType = true;
518     }
519 
520     if (ExpectFuncType || (ExpectBlockType && Lexer.is(AsmToken::LParen))) {
521       // This has a special TYPEINDEX operand which in text we
522       // represent as a signature, such that we can re-build this signature,
523       // attach it to an anonymous symbol, which is what WasmObjectWriter
524       // expects to be able to recreate the actual unique-ified type indices.
525       auto Loc = Parser.getTok();
526       auto Signature = std::make_unique<wasm::WasmSignature>();
527       if (parseSignature(Signature.get()))
528         return true;
529       // Got signature as block type, don't need more
530       ExpectBlockType = false;
531       auto &Ctx = getStreamer().getContext();
532       // The "true" here will cause this to be a nameless symbol.
533       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
534       auto *WasmSym = cast<MCSymbolWasm>(Sym);
535       WasmSym->setSignature(Signature.get());
536       addSignature(std::move(Signature));
537       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
538       const MCExpr *Expr = MCSymbolRefExpr::create(
539           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
540       Operands.push_back(std::make_unique<WebAssemblyOperand>(
541           WebAssemblyOperand::Symbol, Loc.getLoc(), Loc.getEndLoc(),
542           WebAssemblyOperand::SymOp{Expr}));
543     }
544 
545     while (Lexer.isNot(AsmToken::EndOfStatement)) {
546       auto &Tok = Lexer.getTok();
547       switch (Tok.getKind()) {
548       case AsmToken::Identifier: {
549         if (!parseSpecialFloatMaybe(false, Operands))
550           break;
551         auto &Id = Lexer.getTok();
552         if (ExpectBlockType) {
553           // Assume this identifier is a block_type.
554           auto BT = parseBlockType(Id.getString());
555           if (BT == WebAssembly::BlockType::Invalid)
556             return error("Unknown block type: ", Id);
557           addBlockTypeOperand(Operands, NameLoc, BT);
558           Parser.Lex();
559         } else {
560           // Assume this identifier is a label.
561           const MCExpr *Val;
562           SMLoc End;
563           if (Parser.parseExpression(Val, End))
564             return error("Cannot parse symbol: ", Lexer.getTok());
565           Operands.push_back(std::make_unique<WebAssemblyOperand>(
566               WebAssemblyOperand::Symbol, Id.getLoc(), Id.getEndLoc(),
567               WebAssemblyOperand::SymOp{Val}));
568           if (checkForP2AlignIfLoadStore(Operands, Name))
569             return true;
570         }
571         break;
572       }
573       case AsmToken::Minus:
574         Parser.Lex();
575         if (Lexer.is(AsmToken::Integer)) {
576           parseSingleInteger(true, Operands);
577           if (checkForP2AlignIfLoadStore(Operands, Name))
578             return true;
579         } else if(Lexer.is(AsmToken::Real)) {
580           if (parseSingleFloat(true, Operands))
581             return true;
582         } else if (!parseSpecialFloatMaybe(true, Operands)) {
583         } else {
584           return error("Expected numeric constant instead got: ",
585                        Lexer.getTok());
586         }
587         break;
588       case AsmToken::Integer:
589         parseSingleInteger(false, Operands);
590         if (checkForP2AlignIfLoadStore(Operands, Name))
591           return true;
592         break;
593       case AsmToken::Real: {
594         if (parseSingleFloat(false, Operands))
595           return true;
596         break;
597       }
598       case AsmToken::LCurly: {
599         Parser.Lex();
600         auto Op = std::make_unique<WebAssemblyOperand>(
601             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
602         if (!Lexer.is(AsmToken::RCurly))
603           for (;;) {
604             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
605             expect(AsmToken::Integer, "integer");
606             if (!isNext(AsmToken::Comma))
607               break;
608           }
609         expect(AsmToken::RCurly, "}");
610         Operands.push_back(std::move(Op));
611         break;
612       }
613       default:
614         return error("Unexpected token in operand: ", Tok);
615       }
616       if (Lexer.isNot(AsmToken::EndOfStatement)) {
617         if (expect(AsmToken::Comma, ","))
618           return true;
619       }
620     }
621     if (ExpectBlockType && Operands.size() == 1) {
622       // Support blocks with no operands as default to void.
623       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
624     }
625     Parser.Lex();
626     return false;
627   }
628 
629   void onLabelParsed(MCSymbol *Symbol) override {
630     LastLabel = Symbol;
631     CurrentState = Label;
632   }
633 
634   bool parseSignature(wasm::WasmSignature *Signature) {
635     if (expect(AsmToken::LParen, "("))
636       return true;
637     if (parseRegTypeList(Signature->Params))
638       return true;
639     if (expect(AsmToken::RParen, ")"))
640       return true;
641     if (expect(AsmToken::MinusGreater, "->"))
642       return true;
643     if (expect(AsmToken::LParen, "("))
644       return true;
645     if (parseRegTypeList(Signature->Returns))
646       return true;
647     if (expect(AsmToken::RParen, ")"))
648       return true;
649     return false;
650   }
651 
652   bool CheckDataSection() {
653     if (CurrentState != DataSection) {
654       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
655       if (WS && WS->getKind().isText())
656         return error("data directive must occur in a data segment: ",
657                      Lexer.getTok());
658     }
659     CurrentState = DataSection;
660     return false;
661   }
662 
663   // This function processes wasm-specific directives streamed to
664   // WebAssemblyTargetStreamer, all others go to the generic parser
665   // (see WasmAsmParser).
666   bool ParseDirective(AsmToken DirectiveID) override {
667     // This function has a really weird return value behavior that is different
668     // from all the other parsing functions:
669     // - return true && no tokens consumed -> don't know this directive / let
670     //   the generic parser handle it.
671     // - return true && tokens consumed -> a parsing error occurred.
672     // - return false -> processed this directive successfully.
673     assert(DirectiveID.getKind() == AsmToken::Identifier);
674     auto &Out = getStreamer();
675     auto &TOut =
676         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
677     auto &Ctx = Out.getContext();
678 
679     // TODO: any time we return an error, at least one token must have been
680     // consumed, otherwise this will not signal an error to the caller.
681     if (DirectiveID.getString() == ".globaltype") {
682       auto SymName = expectIdent();
683       if (SymName.empty())
684         return true;
685       if (expect(AsmToken::Comma, ","))
686         return true;
687       auto TypeTok = Lexer.getTok();
688       auto TypeName = expectIdent();
689       if (TypeName.empty())
690         return true;
691       auto Type = parseType(TypeName);
692       if (!Type)
693         return error("Unknown type in .globaltype directive: ", TypeTok);
694       // Optional mutable modifier. Default to mutable for historical reasons.
695       // Ideally we would have gone with immutable as the default and used `mut`
696       // as the modifier to match the `.wat` format.
697       bool Mutable = true;
698       if (isNext(AsmToken::Comma)) {
699         TypeTok = Lexer.getTok();
700         auto Id = expectIdent();
701         if (Id == "immutable")
702           Mutable = false;
703         else
704           // Should we also allow `mutable` and `mut` here for clarity?
705           return error("Unknown type in .globaltype modifier: ", TypeTok);
706       }
707       // Now set this symbol with the correct type.
708       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
709       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
710       WasmSym->setGlobalType(
711           wasm::WasmGlobalType{uint8_t(Type.getValue()), Mutable});
712       // And emit the directive again.
713       TOut.emitGlobalType(WasmSym);
714       return expect(AsmToken::EndOfStatement, "EOL");
715     }
716 
717     if (DirectiveID.getString() == ".tabletype") {
718       auto SymName = expectIdent();
719       if (SymName.empty())
720         return true;
721       if (expect(AsmToken::Comma, ","))
722         return true;
723       auto TypeTok = Lexer.getTok();
724       auto TypeName = expectIdent();
725       if (TypeName.empty())
726         return true;
727       auto Type = parseType(TypeName);
728       if (!Type)
729         return error("Unknown type in .tabletype directive: ", TypeTok);
730 
731       // Now that we have the name and table type, we can actually create the
732       // symbol
733       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
734       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
735       WasmSym->setTableType(Type.getValue());
736       TOut.emitTableType(WasmSym);
737       return expect(AsmToken::EndOfStatement, "EOL");
738     }
739 
740     if (DirectiveID.getString() == ".functype") {
741       // This code has to send things to the streamer similar to
742       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
743       // TODO: would be good to factor this into a common function, but the
744       // assembler and backend really don't share any common code, and this code
745       // parses the locals separately.
746       auto SymName = expectIdent();
747       if (SymName.empty())
748         return true;
749       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
750       if (CurrentState == Label && WasmSym == LastLabel) {
751         // This .functype indicates a start of a function.
752         if (ensureEmptyNestingStack())
753           return true;
754         CurrentState = FunctionStart;
755         LastFunctionLabel = LastLabel;
756         push(Function);
757       }
758       auto Signature = std::make_unique<wasm::WasmSignature>();
759       if (parseSignature(Signature.get()))
760         return true;
761       WasmSym->setSignature(Signature.get());
762       addSignature(std::move(Signature));
763       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
764       TOut.emitFunctionType(WasmSym);
765       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
766       return expect(AsmToken::EndOfStatement, "EOL");
767     }
768 
769     if (DirectiveID.getString() == ".export_name") {
770       auto SymName = expectIdent();
771       if (SymName.empty())
772         return true;
773       if (expect(AsmToken::Comma, ","))
774         return true;
775       auto ExportName = expectIdent();
776       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
777       WasmSym->setExportName(storeName(ExportName));
778       TOut.emitExportName(WasmSym, ExportName);
779     }
780 
781     if (DirectiveID.getString() == ".import_module") {
782       auto SymName = expectIdent();
783       if (SymName.empty())
784         return true;
785       if (expect(AsmToken::Comma, ","))
786         return true;
787       auto ImportModule = expectIdent();
788       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
789       WasmSym->setImportModule(storeName(ImportModule));
790       TOut.emitImportModule(WasmSym, ImportModule);
791     }
792 
793     if (DirectiveID.getString() == ".import_name") {
794       auto SymName = expectIdent();
795       if (SymName.empty())
796         return true;
797       if (expect(AsmToken::Comma, ","))
798         return true;
799       auto ImportName = expectIdent();
800       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
801       WasmSym->setImportName(storeName(ImportName));
802       TOut.emitImportName(WasmSym, ImportName);
803     }
804 
805     if (DirectiveID.getString() == ".eventtype") {
806       auto SymName = expectIdent();
807       if (SymName.empty())
808         return true;
809       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
810       auto Signature = std::make_unique<wasm::WasmSignature>();
811       if (parseRegTypeList(Signature->Params))
812         return true;
813       WasmSym->setSignature(Signature.get());
814       addSignature(std::move(Signature));
815       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_EVENT);
816       TOut.emitEventType(WasmSym);
817       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
818       return expect(AsmToken::EndOfStatement, "EOL");
819     }
820 
821     if (DirectiveID.getString() == ".local") {
822       if (CurrentState != FunctionStart)
823         return error(".local directive should follow the start of a function",
824                      Lexer.getTok());
825       SmallVector<wasm::ValType, 4> Locals;
826       if (parseRegTypeList(Locals))
827         return true;
828       TOut.emitLocal(Locals);
829       CurrentState = FunctionLocals;
830       return expect(AsmToken::EndOfStatement, "EOL");
831     }
832 
833     if (DirectiveID.getString() == ".int8" ||
834         DirectiveID.getString() == ".int16" ||
835         DirectiveID.getString() == ".int32" ||
836         DirectiveID.getString() == ".int64") {
837       if (CheckDataSection()) return true;
838       const MCExpr *Val;
839       SMLoc End;
840       if (Parser.parseExpression(Val, End))
841         return error("Cannot parse .int expression: ", Lexer.getTok());
842       size_t NumBits = 0;
843       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
844       Out.emitValue(Val, NumBits / 8, End);
845       return expect(AsmToken::EndOfStatement, "EOL");
846     }
847 
848     if (DirectiveID.getString() == ".asciz") {
849       if (CheckDataSection()) return true;
850       std::string S;
851       if (Parser.parseEscapedString(S))
852         return error("Cannot parse string constant: ", Lexer.getTok());
853       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
854       return expect(AsmToken::EndOfStatement, "EOL");
855     }
856 
857     return true; // We didn't process this directive.
858   }
859 
860   // Called either when the first instruction is parsed of the function ends.
861   void ensureLocals(MCStreamer &Out) {
862     if (CurrentState == FunctionStart) {
863       // We haven't seen a .local directive yet. The streamer requires locals to
864       // be encoded as a prelude to the instructions, so emit an empty list of
865       // locals here.
866       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
867           *Out.getTargetStreamer());
868       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
869       CurrentState = FunctionLocals;
870     }
871   }
872 
873   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
874                                OperandVector &Operands, MCStreamer &Out,
875                                uint64_t &ErrorInfo,
876                                bool MatchingInlineAsm) override {
877     MCInst Inst;
878     Inst.setLoc(IDLoc);
879     FeatureBitset MissingFeatures;
880     unsigned MatchResult = MatchInstructionImpl(
881         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm);
882     switch (MatchResult) {
883     case Match_Success: {
884       ensureLocals(Out);
885       // Fix unknown p2align operands.
886       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
887       if (Align != -1U) {
888         auto &Op0 = Inst.getOperand(0);
889         if (Op0.getImm() == -1)
890           Op0.setImm(Align);
891       }
892       if (getSTI().getTargetTriple().isArch64Bit()) {
893         // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having
894         // an offset64 arg instead of offset32, but to the assembler matcher
895         // they're both immediates so don't get selected for.
896         auto Opc64 = WebAssembly::getWasm64Opcode(
897             static_cast<uint16_t>(Inst.getOpcode()));
898         if (Opc64 >= 0) {
899           Inst.setOpcode(Opc64);
900         }
901       }
902       Out.emitInstruction(Inst, getSTI());
903       if (CurrentState == EndFunction) {
904         onEndOfFunction();
905       } else {
906         CurrentState = Instructions;
907       }
908       return false;
909     }
910     case Match_MissingFeature: {
911       assert(MissingFeatures.count() > 0 && "Expected missing features");
912       SmallString<128> Message;
913       raw_svector_ostream OS(Message);
914       OS << "instruction requires:";
915       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
916         if (MissingFeatures.test(i))
917           OS << ' ' << getSubtargetFeatureName(i);
918       return Parser.Error(IDLoc, Message);
919     }
920     case Match_MnemonicFail:
921       return Parser.Error(IDLoc, "invalid instruction");
922     case Match_NearMisses:
923       return Parser.Error(IDLoc, "ambiguous instruction");
924     case Match_InvalidTiedOperand:
925     case Match_InvalidOperand: {
926       SMLoc ErrorLoc = IDLoc;
927       if (ErrorInfo != ~0ULL) {
928         if (ErrorInfo >= Operands.size())
929           return Parser.Error(IDLoc, "too few operands for instruction");
930         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
931         if (ErrorLoc == SMLoc())
932           ErrorLoc = IDLoc;
933       }
934       return Parser.Error(ErrorLoc, "invalid operand for instruction");
935     }
936     }
937     llvm_unreachable("Implement any new match types added!");
938   }
939 
940   void doBeforeLabelEmit(MCSymbol *Symbol) override {
941     // Start a new section for the next function automatically, since our
942     // object writer expects each function to have its own section. This way
943     // The user can't forget this "convention".
944     auto SymName = Symbol->getName();
945     if (SymName.startswith(".L"))
946       return; // Local Symbol.
947     // Only create a new text section if we're already in one.
948     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
949     if (!CWS || !CWS->getKind().isText())
950       return;
951     auto SecName = ".text." + SymName;
952     auto WS = getContext().getWasmSection(SecName, SectionKind::getText());
953     getStreamer().SwitchSection(WS);
954     // Also generate DWARF for this section if requested.
955     if (getContext().getGenDwarfForAssembly())
956       getContext().addGenDwarfSection(WS);
957   }
958 
959   void onEndOfFunction() {
960     // Automatically output a .size directive, so it becomes optional for the
961     // user.
962     if (!LastFunctionLabel) return;
963     auto TempSym = getContext().createLinkerPrivateTempSymbol();
964     getStreamer().emitLabel(TempSym);
965     auto Start = MCSymbolRefExpr::create(LastFunctionLabel, getContext());
966     auto End = MCSymbolRefExpr::create(TempSym, getContext());
967     auto Expr =
968         MCBinaryExpr::create(MCBinaryExpr::Sub, End, Start, getContext());
969     getStreamer().emitELFSize(LastFunctionLabel, Expr);
970   }
971 
972   void onEndOfFile() override { ensureEmptyNestingStack(); }
973 };
974 } // end anonymous namespace
975 
976 // Force static initialization.
977 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
978   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
979   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
980 }
981 
982 #define GET_REGISTER_MATCHER
983 #define GET_SUBTARGET_FEATURE_NAME
984 #define GET_MATCHER_IMPLEMENTATION
985 #include "WebAssemblyGenAsmMatcher.inc"
986