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