xref: /llvm-project/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp (revision a479be0f39a3301e9ca634d37cf6454b6d3865c6)
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 "AsmParser/WebAssemblyAsmTypeCheck.h"
17 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
18 #include "MCTargetDesc/WebAssemblyMCTypeUtilities.h"
19 #include "MCTargetDesc/WebAssemblyTargetStreamer.h"
20 #include "TargetInfo/WebAssemblyTargetInfo.h"
21 #include "WebAssembly.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCParser/MCAsmLexer.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
29 #include "llvm/MC/MCSectionWasm.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCSymbolWasm.h"
34 #include "llvm/MC/TargetRegistry.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/SourceMgr.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "wasm-asm-parser"
41 
42 static const char *getSubtargetFeatureName(uint64_t Val);
43 
44 namespace {
45 
46 /// WebAssemblyOperand - Instances of this class represent the operands in a
47 /// parsed Wasm machine instruction.
48 struct WebAssemblyOperand : public MCParsedAsmOperand {
49   enum KindTy { Token, Integer, Float, Symbol, BrList } Kind;
50 
51   SMLoc StartLoc, EndLoc;
52 
53   struct TokOp {
54     StringRef Tok;
55   };
56 
57   struct IntOp {
58     int64_t Val;
59   };
60 
61   struct FltOp {
62     double Val;
63   };
64 
65   struct SymOp {
66     const MCExpr *Exp;
67   };
68 
69   struct BrLOp {
70     std::vector<unsigned> List;
71   };
72 
73   union {
74     struct TokOp Tok;
75     struct IntOp Int;
76     struct FltOp Flt;
77     struct SymOp Sym;
78     struct BrLOp BrL;
79   };
80 
81   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, TokOp T)
82       : Kind(K), StartLoc(Start), EndLoc(End), Tok(T) {}
83   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, IntOp I)
84       : Kind(K), StartLoc(Start), EndLoc(End), Int(I) {}
85   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, FltOp F)
86       : Kind(K), StartLoc(Start), EndLoc(End), Flt(F) {}
87   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End, SymOp S)
88       : Kind(K), StartLoc(Start), EndLoc(End), Sym(S) {}
89   WebAssemblyOperand(KindTy K, SMLoc Start, SMLoc End)
90       : Kind(K), StartLoc(Start), EndLoc(End), BrL() {}
91 
92   ~WebAssemblyOperand() {
93     if (isBrList())
94       BrL.~BrLOp();
95   }
96 
97   bool isToken() const override { return Kind == Token; }
98   bool isImm() const override { return Kind == Integer || Kind == Symbol; }
99   bool isFPImm() const { return Kind == Float; }
100   bool isMem() const override { return false; }
101   bool isReg() const override { return false; }
102   bool isBrList() const { return Kind == BrList; }
103 
104   unsigned getReg() const override {
105     llvm_unreachable("Assembly inspects a register operand");
106     return 0;
107   }
108 
109   StringRef getToken() const {
110     assert(isToken());
111     return Tok.Tok;
112   }
113 
114   SMLoc getStartLoc() const override { return StartLoc; }
115   SMLoc getEndLoc() const override { return EndLoc; }
116 
117   void addRegOperands(MCInst &, unsigned) const {
118     // Required by the assembly matcher.
119     llvm_unreachable("Assembly matcher creates register operands");
120   }
121 
122   void addImmOperands(MCInst &Inst, unsigned N) const {
123     assert(N == 1 && "Invalid number of operands!");
124     if (Kind == Integer)
125       Inst.addOperand(MCOperand::createImm(Int.Val));
126     else if (Kind == Symbol)
127       Inst.addOperand(MCOperand::createExpr(Sym.Exp));
128     else
129       llvm_unreachable("Should be integer immediate or symbol!");
130   }
131 
132   void addFPImmf32Operands(MCInst &Inst, unsigned N) const {
133     assert(N == 1 && "Invalid number of operands!");
134     if (Kind == Float)
135       Inst.addOperand(
136           MCOperand::createSFPImm(bit_cast<uint32_t>(float(Flt.Val))));
137     else
138       llvm_unreachable("Should be float immediate!");
139   }
140 
141   void addFPImmf64Operands(MCInst &Inst, unsigned N) const {
142     assert(N == 1 && "Invalid number of operands!");
143     if (Kind == Float)
144       Inst.addOperand(MCOperand::createDFPImm(bit_cast<uint64_t>(Flt.Val)));
145     else
146       llvm_unreachable("Should be float immediate!");
147   }
148 
149   void addBrListOperands(MCInst &Inst, unsigned N) const {
150     assert(N == 1 && isBrList() && "Invalid BrList!");
151     for (auto Br : BrL.List)
152       Inst.addOperand(MCOperand::createImm(Br));
153   }
154 
155   void print(raw_ostream &OS) const override {
156     switch (Kind) {
157     case Token:
158       OS << "Tok:" << Tok.Tok;
159       break;
160     case Integer:
161       OS << "Int:" << Int.Val;
162       break;
163     case Float:
164       OS << "Flt:" << Flt.Val;
165       break;
166     case Symbol:
167       OS << "Sym:" << Sym.Exp;
168       break;
169     case BrList:
170       OS << "BrList:" << BrL.List.size();
171       break;
172     }
173   }
174 };
175 
176 // Perhaps this should go somewhere common.
177 static wasm::WasmLimits DefaultLimits() {
178   return {wasm::WASM_LIMITS_FLAG_NONE, 0, 0};
179 }
180 
181 static MCSymbolWasm *GetOrCreateFunctionTableSymbol(MCContext &Ctx,
182                                                     const StringRef &Name) {
183   MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(Name));
184   if (Sym) {
185     if (!Sym->isFunctionTable())
186       Ctx.reportError(SMLoc(), "symbol is not a wasm funcref table");
187   } else {
188     Sym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(Name));
189     Sym->setFunctionTable();
190     // The default function table is synthesized by the linker.
191     Sym->setUndefined();
192   }
193   return Sym;
194 }
195 
196 class WebAssemblyAsmParser final : public MCTargetAsmParser {
197   MCAsmParser &Parser;
198   MCAsmLexer &Lexer;
199 
200   // Much like WebAssemblyAsmPrinter in the backend, we have to own these.
201   std::vector<std::unique_ptr<wasm::WasmSignature>> Signatures;
202   std::vector<std::unique_ptr<std::string>> Names;
203 
204   // Order of labels, directives and instructions in a .s file have no
205   // syntactical enforcement. This class is a callback from the actual parser,
206   // and yet we have to be feeding data to the streamer in a very particular
207   // order to ensure a correct binary encoding that matches the regular backend
208   // (the streamer does not enforce this). This "state machine" enum helps
209   // guarantee that correct order.
210   enum ParserState {
211     FileStart,
212     FunctionLabel,
213     FunctionStart,
214     FunctionLocals,
215     Instructions,
216     EndFunction,
217     DataSection,
218   } CurrentState = FileStart;
219 
220   // For ensuring blocks are properly nested.
221   enum NestingType {
222     Function,
223     Block,
224     Loop,
225     Try,
226     CatchAll,
227     If,
228     Else,
229     Undefined,
230   };
231   struct Nested {
232     NestingType NT;
233     wasm::WasmSignature Sig;
234   };
235   std::vector<Nested> NestingStack;
236 
237   MCSymbolWasm *DefaultFunctionTable = nullptr;
238   MCSymbol *LastFunctionLabel = nullptr;
239 
240   bool is64;
241 
242   WebAssemblyAsmTypeCheck TC;
243   // Don't type check if -no-type-check was set.
244   bool SkipTypeCheck;
245 
246 public:
247   WebAssemblyAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
248                        const MCInstrInfo &MII, const MCTargetOptions &Options)
249       : MCTargetAsmParser(Options, STI, MII), Parser(Parser),
250         Lexer(Parser.getLexer()), is64(STI.getTargetTriple().isArch64Bit()),
251         TC(Parser, MII, is64), SkipTypeCheck(Options.MCNoTypeCheck) {
252     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
253     // Don't type check if this is inline asm, since that is a naked sequence of
254     // instructions without a function/locals decl.
255     auto &SM = Parser.getSourceManager();
256     auto BufferName =
257         SM.getBufferInfo(SM.getMainFileID()).Buffer->getBufferIdentifier();
258     if (BufferName == "<inline asm>")
259       SkipTypeCheck = true;
260   }
261 
262   void Initialize(MCAsmParser &Parser) override {
263     MCAsmParserExtension::Initialize(Parser);
264 
265     DefaultFunctionTable = GetOrCreateFunctionTableSymbol(
266         getContext(), "__indirect_function_table");
267     if (!STI->checkFeatures("+reference-types"))
268       DefaultFunctionTable->setOmitFromLinkingSection();
269   }
270 
271 #define GET_ASSEMBLER_HEADER
272 #include "WebAssemblyGenAsmMatcher.inc"
273 
274   // TODO: This is required to be implemented, but appears unused.
275   bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override {
276     llvm_unreachable("parseRegister is not implemented.");
277   }
278   ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
279                                SMLoc &EndLoc) override {
280     llvm_unreachable("tryParseRegister is not implemented.");
281   }
282 
283   bool error(const Twine &Msg, const AsmToken &Tok) {
284     return Parser.Error(Tok.getLoc(), Msg + Tok.getString());
285   }
286 
287   bool error(const Twine &Msg, SMLoc Loc = SMLoc()) {
288     return Parser.Error(Loc.isValid() ? Loc : Lexer.getTok().getLoc(), Msg);
289   }
290 
291   void addSignature(std::unique_ptr<wasm::WasmSignature> &&Sig) {
292     Signatures.push_back(std::move(Sig));
293   }
294 
295   StringRef storeName(StringRef Name) {
296     std::unique_ptr<std::string> N = std::make_unique<std::string>(Name);
297     Names.push_back(std::move(N));
298     return *Names.back();
299   }
300 
301   std::pair<StringRef, StringRef> nestingString(NestingType NT) {
302     switch (NT) {
303     case Function:
304       return {"function", "end_function"};
305     case Block:
306       return {"block", "end_block"};
307     case Loop:
308       return {"loop", "end_loop"};
309     case Try:
310       return {"try", "end_try/delegate"};
311     case CatchAll:
312       return {"catch_all", "end_try"};
313     case If:
314       return {"if", "end_if"};
315     case Else:
316       return {"else", "end_if"};
317     default:
318       llvm_unreachable("unknown NestingType");
319     }
320   }
321 
322   void push(NestingType NT, wasm::WasmSignature Sig = wasm::WasmSignature()) {
323     NestingStack.push_back({NT, Sig});
324   }
325 
326   bool pop(StringRef Ins, NestingType NT1, NestingType NT2 = Undefined) {
327     if (NestingStack.empty())
328       return error(Twine("End of block construct with no start: ") + Ins);
329     auto Top = NestingStack.back();
330     if (Top.NT != NT1 && Top.NT != NT2)
331       return error(Twine("Block construct type mismatch, expected: ") +
332                    nestingString(Top.NT).second + ", instead got: " + Ins);
333     TC.setLastSig(Top.Sig);
334     NestingStack.pop_back();
335     return false;
336   }
337 
338   // Pop a NestingType and push a new NestingType with the same signature. Used
339   // for if-else and try-catch(_all).
340   bool popAndPushWithSameSignature(StringRef Ins, NestingType PopNT,
341                                    NestingType PushNT) {
342     if (NestingStack.empty())
343       return error(Twine("End of block construct with no start: ") + Ins);
344     auto Sig = NestingStack.back().Sig;
345     if (pop(Ins, PopNT))
346       return true;
347     push(PushNT, Sig);
348     return false;
349   }
350 
351   bool ensureEmptyNestingStack(SMLoc Loc = SMLoc()) {
352     auto Err = !NestingStack.empty();
353     while (!NestingStack.empty()) {
354       error(Twine("Unmatched block construct(s) at function end: ") +
355                 nestingString(NestingStack.back().NT).first,
356             Loc);
357       NestingStack.pop_back();
358     }
359     return Err;
360   }
361 
362   bool isNext(AsmToken::TokenKind Kind) {
363     auto Ok = Lexer.is(Kind);
364     if (Ok)
365       Parser.Lex();
366     return Ok;
367   }
368 
369   bool expect(AsmToken::TokenKind Kind, const char *KindName) {
370     if (!isNext(Kind))
371       return error(std::string("Expected ") + KindName + ", instead got: ",
372                    Lexer.getTok());
373     return false;
374   }
375 
376   StringRef expectIdent() {
377     if (!Lexer.is(AsmToken::Identifier)) {
378       error("Expected identifier, got: ", Lexer.getTok());
379       return StringRef();
380     }
381     auto Name = Lexer.getTok().getString();
382     Parser.Lex();
383     return Name;
384   }
385 
386   bool parseRegTypeList(SmallVectorImpl<wasm::ValType> &Types) {
387     while (Lexer.is(AsmToken::Identifier)) {
388       auto Type = WebAssembly::parseType(Lexer.getTok().getString());
389       if (!Type)
390         return error("unknown type: ", Lexer.getTok());
391       Types.push_back(*Type);
392       Parser.Lex();
393       if (!isNext(AsmToken::Comma))
394         break;
395     }
396     return false;
397   }
398 
399   void parseSingleInteger(bool IsNegative, OperandVector &Operands) {
400     auto &Int = Lexer.getTok();
401     int64_t Val = Int.getIntVal();
402     if (IsNegative)
403       Val = -Val;
404     Operands.push_back(std::make_unique<WebAssemblyOperand>(
405         WebAssemblyOperand::Integer, Int.getLoc(), Int.getEndLoc(),
406         WebAssemblyOperand::IntOp{Val}));
407     Parser.Lex();
408   }
409 
410   bool parseSingleFloat(bool IsNegative, OperandVector &Operands) {
411     auto &Flt = Lexer.getTok();
412     double Val;
413     if (Flt.getString().getAsDouble(Val, false))
414       return error("Cannot parse real: ", Flt);
415     if (IsNegative)
416       Val = -Val;
417     Operands.push_back(std::make_unique<WebAssemblyOperand>(
418         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
419         WebAssemblyOperand::FltOp{Val}));
420     Parser.Lex();
421     return false;
422   }
423 
424   bool parseSpecialFloatMaybe(bool IsNegative, OperandVector &Operands) {
425     if (Lexer.isNot(AsmToken::Identifier))
426       return true;
427     auto &Flt = Lexer.getTok();
428     auto S = Flt.getString();
429     double Val;
430     if (S.compare_insensitive("infinity") == 0) {
431       Val = std::numeric_limits<double>::infinity();
432     } else if (S.compare_insensitive("nan") == 0) {
433       Val = std::numeric_limits<double>::quiet_NaN();
434     } else {
435       return true;
436     }
437     if (IsNegative)
438       Val = -Val;
439     Operands.push_back(std::make_unique<WebAssemblyOperand>(
440         WebAssemblyOperand::Float, Flt.getLoc(), Flt.getEndLoc(),
441         WebAssemblyOperand::FltOp{Val}));
442     Parser.Lex();
443     return false;
444   }
445 
446   bool checkForP2AlignIfLoadStore(OperandVector &Operands, StringRef InstName) {
447     // FIXME: there is probably a cleaner way to do this.
448     auto IsLoadStore = InstName.contains(".load") ||
449                        InstName.contains(".store") ||
450                        InstName.contains("prefetch");
451     auto IsAtomic = InstName.contains("atomic.");
452     if (IsLoadStore || IsAtomic) {
453       // Parse load/store operands of the form: offset:p2align=align
454       if (IsLoadStore && isNext(AsmToken::Colon)) {
455         auto Id = expectIdent();
456         if (Id != "p2align")
457           return error("Expected p2align, instead got: " + Id);
458         if (expect(AsmToken::Equal, "="))
459           return true;
460         if (!Lexer.is(AsmToken::Integer))
461           return error("Expected integer constant");
462         parseSingleInteger(false, Operands);
463       } else {
464         // v128.{load,store}{8,16,32,64}_lane has both a memarg and a lane
465         // index. We need to avoid parsing an extra alignment operand for the
466         // lane index.
467         auto IsLoadStoreLane = InstName.contains("_lane");
468         if (IsLoadStoreLane && Operands.size() == 4)
469           return false;
470         // Alignment not specified (or atomics, must use default alignment).
471         // We can't just call WebAssembly::GetDefaultP2Align since we don't have
472         // an opcode until after the assembly matcher, so set a default to fix
473         // up later.
474         auto Tok = Lexer.getTok();
475         Operands.push_back(std::make_unique<WebAssemblyOperand>(
476             WebAssemblyOperand::Integer, Tok.getLoc(), Tok.getEndLoc(),
477             WebAssemblyOperand::IntOp{-1}));
478       }
479     }
480     return false;
481   }
482 
483   void addBlockTypeOperand(OperandVector &Operands, SMLoc NameLoc,
484                            WebAssembly::BlockType BT) {
485     if (BT != WebAssembly::BlockType::Void) {
486       wasm::WasmSignature Sig({static_cast<wasm::ValType>(BT)}, {});
487       TC.setLastSig(Sig);
488       NestingStack.back().Sig = Sig;
489     }
490     Operands.push_back(std::make_unique<WebAssemblyOperand>(
491         WebAssemblyOperand::Integer, NameLoc, NameLoc,
492         WebAssemblyOperand::IntOp{static_cast<int64_t>(BT)}));
493   }
494 
495   bool parseLimits(wasm::WasmLimits *Limits) {
496     auto Tok = Lexer.getTok();
497     if (!Tok.is(AsmToken::Integer))
498       return error("Expected integer constant, instead got: ", Tok);
499     int64_t Val = Tok.getIntVal();
500     assert(Val >= 0);
501     Limits->Minimum = Val;
502     Parser.Lex();
503 
504     if (isNext(AsmToken::Comma)) {
505       Limits->Flags |= wasm::WASM_LIMITS_FLAG_HAS_MAX;
506       auto Tok = Lexer.getTok();
507       if (!Tok.is(AsmToken::Integer))
508         return error("Expected integer constant, instead got: ", Tok);
509       int64_t Val = Tok.getIntVal();
510       assert(Val >= 0);
511       Limits->Maximum = Val;
512       Parser.Lex();
513     }
514     return false;
515   }
516 
517   bool parseFunctionTableOperand(std::unique_ptr<WebAssemblyOperand> *Op) {
518     if (STI->checkFeatures("+reference-types")) {
519       // If the reference-types feature is enabled, there is an explicit table
520       // operand.  To allow the same assembly to be compiled with or without
521       // reference types, we allow the operand to be omitted, in which case we
522       // default to __indirect_function_table.
523       auto &Tok = Lexer.getTok();
524       if (Tok.is(AsmToken::Identifier)) {
525         auto *Sym =
526             GetOrCreateFunctionTableSymbol(getContext(), Tok.getString());
527         const auto *Val = MCSymbolRefExpr::create(Sym, getContext());
528         *Op = std::make_unique<WebAssemblyOperand>(
529             WebAssemblyOperand::Symbol, Tok.getLoc(), Tok.getEndLoc(),
530             WebAssemblyOperand::SymOp{Val});
531         Parser.Lex();
532         return expect(AsmToken::Comma, ",");
533       } else {
534         const auto *Val =
535             MCSymbolRefExpr::create(DefaultFunctionTable, getContext());
536         *Op = std::make_unique<WebAssemblyOperand>(
537             WebAssemblyOperand::Symbol, SMLoc(), SMLoc(),
538             WebAssemblyOperand::SymOp{Val});
539         return false;
540       }
541     } else {
542       // For the MVP there is at most one table whose number is 0, but we can't
543       // write a table symbol or issue relocations.  Instead we just ensure the
544       // table is live and write a zero.
545       getStreamer().emitSymbolAttribute(DefaultFunctionTable, MCSA_NoDeadStrip);
546       *Op = std::make_unique<WebAssemblyOperand>(WebAssemblyOperand::Integer,
547                                                  SMLoc(), SMLoc(),
548                                                  WebAssemblyOperand::IntOp{0});
549       return false;
550     }
551   }
552 
553   bool ParseInstruction(ParseInstructionInfo & /*Info*/, StringRef Name,
554                         SMLoc NameLoc, OperandVector &Operands) override {
555     // Note: Name does NOT point into the sourcecode, but to a local, so
556     // use NameLoc instead.
557     Name = StringRef(NameLoc.getPointer(), Name.size());
558 
559     // WebAssembly has instructions with / in them, which AsmLexer parses
560     // as separate tokens, so if we find such tokens immediately adjacent (no
561     // whitespace), expand the name to include them:
562     for (;;) {
563       auto &Sep = Lexer.getTok();
564       if (Sep.getLoc().getPointer() != Name.end() ||
565           Sep.getKind() != AsmToken::Slash)
566         break;
567       // Extend name with /
568       Name = StringRef(Name.begin(), Name.size() + Sep.getString().size());
569       Parser.Lex();
570       // We must now find another identifier, or error.
571       auto &Id = Lexer.getTok();
572       if (Id.getKind() != AsmToken::Identifier ||
573           Id.getLoc().getPointer() != Name.end())
574         return error("Incomplete instruction name: ", Id);
575       Name = StringRef(Name.begin(), Name.size() + Id.getString().size());
576       Parser.Lex();
577     }
578 
579     // Now construct the name as first operand.
580     Operands.push_back(std::make_unique<WebAssemblyOperand>(
581         WebAssemblyOperand::Token, NameLoc, SMLoc::getFromPointer(Name.end()),
582         WebAssemblyOperand::TokOp{Name}));
583 
584     // If this instruction is part of a control flow structure, ensure
585     // proper nesting.
586     bool ExpectBlockType = false;
587     bool ExpectFuncType = false;
588     std::unique_ptr<WebAssemblyOperand> FunctionTable;
589     if (Name == "block") {
590       push(Block);
591       ExpectBlockType = true;
592     } else if (Name == "loop") {
593       push(Loop);
594       ExpectBlockType = true;
595     } else if (Name == "try") {
596       push(Try);
597       ExpectBlockType = true;
598     } else if (Name == "if") {
599       push(If);
600       ExpectBlockType = true;
601     } else if (Name == "else") {
602       if (popAndPushWithSameSignature(Name, If, Else))
603         return true;
604     } else if (Name == "catch") {
605       if (popAndPushWithSameSignature(Name, Try, Try))
606         return true;
607     } else if (Name == "catch_all") {
608       if (popAndPushWithSameSignature(Name, Try, CatchAll))
609         return true;
610     } else if (Name == "end_if") {
611       if (pop(Name, If, Else))
612         return true;
613     } else if (Name == "end_try") {
614       if (pop(Name, Try, CatchAll))
615         return true;
616     } else if (Name == "delegate") {
617       if (pop(Name, Try))
618         return true;
619     } else if (Name == "end_loop") {
620       if (pop(Name, Loop))
621         return true;
622     } else if (Name == "end_block") {
623       if (pop(Name, Block))
624         return true;
625     } else if (Name == "end_function") {
626       ensureLocals(getStreamer());
627       CurrentState = EndFunction;
628       if (pop(Name, Function) || ensureEmptyNestingStack())
629         return true;
630     } else if (Name == "call_indirect" || Name == "return_call_indirect") {
631       // These instructions have differing operand orders in the text format vs
632       // the binary formats.  The MC instructions follow the binary format, so
633       // here we stash away the operand and append it later.
634       if (parseFunctionTableOperand(&FunctionTable))
635         return true;
636       ExpectFuncType = true;
637     }
638 
639     if (ExpectFuncType || (ExpectBlockType && Lexer.is(AsmToken::LParen))) {
640       // This has a special TYPEINDEX operand which in text we
641       // represent as a signature, such that we can re-build this signature,
642       // attach it to an anonymous symbol, which is what WasmObjectWriter
643       // expects to be able to recreate the actual unique-ified type indices.
644       auto Loc = Parser.getTok();
645       auto Signature = std::make_unique<wasm::WasmSignature>();
646       if (parseSignature(Signature.get()))
647         return true;
648       // Got signature as block type, don't need more
649       TC.setLastSig(*Signature.get());
650       if (ExpectBlockType)
651         NestingStack.back().Sig = *Signature.get();
652       ExpectBlockType = false;
653       auto &Ctx = getContext();
654       // The "true" here will cause this to be a nameless symbol.
655       MCSymbol *Sym = Ctx.createTempSymbol("typeindex", true);
656       auto *WasmSym = cast<MCSymbolWasm>(Sym);
657       WasmSym->setSignature(Signature.get());
658       addSignature(std::move(Signature));
659       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
660       const MCExpr *Expr = MCSymbolRefExpr::create(
661           WasmSym, MCSymbolRefExpr::VK_WASM_TYPEINDEX, Ctx);
662       Operands.push_back(std::make_unique<WebAssemblyOperand>(
663           WebAssemblyOperand::Symbol, Loc.getLoc(), Loc.getEndLoc(),
664           WebAssemblyOperand::SymOp{Expr}));
665     }
666 
667     while (Lexer.isNot(AsmToken::EndOfStatement)) {
668       auto &Tok = Lexer.getTok();
669       switch (Tok.getKind()) {
670       case AsmToken::Identifier: {
671         if (!parseSpecialFloatMaybe(false, Operands))
672           break;
673         auto &Id = Lexer.getTok();
674         if (ExpectBlockType) {
675           // Assume this identifier is a block_type.
676           auto BT = WebAssembly::parseBlockType(Id.getString());
677           if (BT == WebAssembly::BlockType::Invalid)
678             return error("Unknown block type: ", Id);
679           addBlockTypeOperand(Operands, NameLoc, BT);
680           Parser.Lex();
681         } else {
682           // Assume this identifier is a label.
683           const MCExpr *Val;
684           SMLoc Start = Id.getLoc();
685           SMLoc End;
686           if (Parser.parseExpression(Val, End))
687             return error("Cannot parse symbol: ", Lexer.getTok());
688           Operands.push_back(std::make_unique<WebAssemblyOperand>(
689               WebAssemblyOperand::Symbol, Start, End,
690               WebAssemblyOperand::SymOp{Val}));
691           if (checkForP2AlignIfLoadStore(Operands, Name))
692             return true;
693         }
694         break;
695       }
696       case AsmToken::Minus:
697         Parser.Lex();
698         if (Lexer.is(AsmToken::Integer)) {
699           parseSingleInteger(true, Operands);
700           if (checkForP2AlignIfLoadStore(Operands, Name))
701             return true;
702         } else if (Lexer.is(AsmToken::Real)) {
703           if (parseSingleFloat(true, Operands))
704             return true;
705         } else if (!parseSpecialFloatMaybe(true, Operands)) {
706         } else {
707           return error("Expected numeric constant instead got: ",
708                        Lexer.getTok());
709         }
710         break;
711       case AsmToken::Integer:
712         parseSingleInteger(false, Operands);
713         if (checkForP2AlignIfLoadStore(Operands, Name))
714           return true;
715         break;
716       case AsmToken::Real: {
717         if (parseSingleFloat(false, Operands))
718           return true;
719         break;
720       }
721       case AsmToken::LCurly: {
722         Parser.Lex();
723         auto Op = std::make_unique<WebAssemblyOperand>(
724             WebAssemblyOperand::BrList, Tok.getLoc(), Tok.getEndLoc());
725         if (!Lexer.is(AsmToken::RCurly))
726           for (;;) {
727             Op->BrL.List.push_back(Lexer.getTok().getIntVal());
728             expect(AsmToken::Integer, "integer");
729             if (!isNext(AsmToken::Comma))
730               break;
731           }
732         expect(AsmToken::RCurly, "}");
733         Operands.push_back(std::move(Op));
734         break;
735       }
736       default:
737         return error("Unexpected token in operand: ", Tok);
738       }
739       if (Lexer.isNot(AsmToken::EndOfStatement)) {
740         if (expect(AsmToken::Comma, ","))
741           return true;
742       }
743     }
744     if (ExpectBlockType && Operands.size() == 1) {
745       // Support blocks with no operands as default to void.
746       addBlockTypeOperand(Operands, NameLoc, WebAssembly::BlockType::Void);
747     }
748     if (FunctionTable)
749       Operands.push_back(std::move(FunctionTable));
750     Parser.Lex();
751     return false;
752   }
753 
754   bool parseSignature(wasm::WasmSignature *Signature) {
755     if (expect(AsmToken::LParen, "("))
756       return true;
757     if (parseRegTypeList(Signature->Params))
758       return true;
759     if (expect(AsmToken::RParen, ")"))
760       return true;
761     if (expect(AsmToken::MinusGreater, "->"))
762       return true;
763     if (expect(AsmToken::LParen, "("))
764       return true;
765     if (parseRegTypeList(Signature->Returns))
766       return true;
767     if (expect(AsmToken::RParen, ")"))
768       return true;
769     return false;
770   }
771 
772   bool CheckDataSection() {
773     if (CurrentState != DataSection) {
774       auto WS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
775       if (WS && WS->getKind().isText())
776         return error("data directive must occur in a data segment: ",
777                      Lexer.getTok());
778     }
779     CurrentState = DataSection;
780     return false;
781   }
782 
783   // This function processes wasm-specific directives streamed to
784   // WebAssemblyTargetStreamer, all others go to the generic parser
785   // (see WasmAsmParser).
786   ParseStatus parseDirective(AsmToken DirectiveID) override {
787     assert(DirectiveID.getKind() == AsmToken::Identifier);
788     auto &Out = getStreamer();
789     auto &TOut =
790         reinterpret_cast<WebAssemblyTargetStreamer &>(*Out.getTargetStreamer());
791     auto &Ctx = Out.getContext();
792 
793     if (DirectiveID.getString() == ".globaltype") {
794       auto SymName = expectIdent();
795       if (SymName.empty())
796         return ParseStatus::Failure;
797       if (expect(AsmToken::Comma, ","))
798         return ParseStatus::Failure;
799       auto TypeTok = Lexer.getTok();
800       auto TypeName = expectIdent();
801       if (TypeName.empty())
802         return ParseStatus::Failure;
803       auto Type = WebAssembly::parseType(TypeName);
804       if (!Type)
805         return error("Unknown type in .globaltype directive: ", TypeTok);
806       // Optional mutable modifier. Default to mutable for historical reasons.
807       // Ideally we would have gone with immutable as the default and used `mut`
808       // as the modifier to match the `.wat` format.
809       bool Mutable = true;
810       if (isNext(AsmToken::Comma)) {
811         TypeTok = Lexer.getTok();
812         auto Id = expectIdent();
813         if (Id.empty())
814           return ParseStatus::Failure;
815         if (Id == "immutable")
816           Mutable = false;
817         else
818           // Should we also allow `mutable` and `mut` here for clarity?
819           return error("Unknown type in .globaltype modifier: ", TypeTok);
820       }
821       // Now set this symbol with the correct type.
822       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
823       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
824       WasmSym->setGlobalType(wasm::WasmGlobalType{uint8_t(*Type), Mutable});
825       // And emit the directive again.
826       TOut.emitGlobalType(WasmSym);
827       return expect(AsmToken::EndOfStatement, "EOL");
828     }
829 
830     if (DirectiveID.getString() == ".tabletype") {
831       // .tabletype SYM, ELEMTYPE[, MINSIZE[, MAXSIZE]]
832       auto SymName = expectIdent();
833       if (SymName.empty())
834         return ParseStatus::Failure;
835       if (expect(AsmToken::Comma, ","))
836         return ParseStatus::Failure;
837 
838       auto ElemTypeTok = Lexer.getTok();
839       auto ElemTypeName = expectIdent();
840       if (ElemTypeName.empty())
841         return ParseStatus::Failure;
842       std::optional<wasm::ValType> ElemType =
843           WebAssembly::parseType(ElemTypeName);
844       if (!ElemType)
845         return error("Unknown type in .tabletype directive: ", ElemTypeTok);
846 
847       wasm::WasmLimits Limits = DefaultLimits();
848       if (isNext(AsmToken::Comma) && parseLimits(&Limits))
849         return ParseStatus::Failure;
850 
851       // Now that we have the name and table type, we can actually create the
852       // symbol
853       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
854       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TABLE);
855       wasm::WasmTableType Type = {uint8_t(*ElemType), Limits};
856       WasmSym->setTableType(Type);
857       TOut.emitTableType(WasmSym);
858       return expect(AsmToken::EndOfStatement, "EOL");
859     }
860 
861     if (DirectiveID.getString() == ".functype") {
862       // This code has to send things to the streamer similar to
863       // WebAssemblyAsmPrinter::EmitFunctionBodyStart.
864       // TODO: would be good to factor this into a common function, but the
865       // assembler and backend really don't share any common code, and this code
866       // parses the locals separately.
867       auto SymName = expectIdent();
868       if (SymName.empty())
869         return ParseStatus::Failure;
870       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
871       if (WasmSym->isDefined()) {
872         // We push 'Function' either when a label is parsed or a .functype
873         // directive is parsed. The reason it is not easy to do this uniformly
874         // in a single place is,
875         // 1. We can't do this at label parsing time only because there are
876         //    cases we don't have .functype directive before a function label,
877         //    in which case we don't know if the label is a function at the time
878         //    of parsing.
879         // 2. We can't do this at .functype parsing time only because we want to
880         //    detect a function started with a label and not ended correctly
881         //    without encountering a .functype directive after the label.
882         if (CurrentState != FunctionLabel) {
883           // This .functype indicates a start of a function.
884           if (ensureEmptyNestingStack())
885             return ParseStatus::Failure;
886           push(Function);
887         }
888         CurrentState = FunctionStart;
889         LastFunctionLabel = WasmSym;
890       }
891       auto Signature = std::make_unique<wasm::WasmSignature>();
892       if (parseSignature(Signature.get()))
893         return ParseStatus::Failure;
894       TC.funcDecl(*Signature);
895       WasmSym->setSignature(Signature.get());
896       addSignature(std::move(Signature));
897       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
898       TOut.emitFunctionType(WasmSym);
899       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
900       return expect(AsmToken::EndOfStatement, "EOL");
901     }
902 
903     if (DirectiveID.getString() == ".export_name") {
904       auto SymName = expectIdent();
905       if (SymName.empty())
906         return ParseStatus::Failure;
907       if (expect(AsmToken::Comma, ","))
908         return ParseStatus::Failure;
909       auto ExportName = expectIdent();
910       if (ExportName.empty())
911         return ParseStatus::Failure;
912       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
913       WasmSym->setExportName(storeName(ExportName));
914       TOut.emitExportName(WasmSym, ExportName);
915       return expect(AsmToken::EndOfStatement, "EOL");
916     }
917 
918     if (DirectiveID.getString() == ".import_module") {
919       auto SymName = expectIdent();
920       if (SymName.empty())
921         return ParseStatus::Failure;
922       if (expect(AsmToken::Comma, ","))
923         return ParseStatus::Failure;
924       auto ImportModule = expectIdent();
925       if (ImportModule.empty())
926         return ParseStatus::Failure;
927       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
928       WasmSym->setImportModule(storeName(ImportModule));
929       TOut.emitImportModule(WasmSym, ImportModule);
930       return expect(AsmToken::EndOfStatement, "EOL");
931     }
932 
933     if (DirectiveID.getString() == ".import_name") {
934       auto SymName = expectIdent();
935       if (SymName.empty())
936         return ParseStatus::Failure;
937       if (expect(AsmToken::Comma, ","))
938         return ParseStatus::Failure;
939       auto ImportName = expectIdent();
940       if (ImportName.empty())
941         return ParseStatus::Failure;
942       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
943       WasmSym->setImportName(storeName(ImportName));
944       TOut.emitImportName(WasmSym, ImportName);
945       return expect(AsmToken::EndOfStatement, "EOL");
946     }
947 
948     if (DirectiveID.getString() == ".tagtype") {
949       auto SymName = expectIdent();
950       if (SymName.empty())
951         return ParseStatus::Failure;
952       auto WasmSym = cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SymName));
953       auto Signature = std::make_unique<wasm::WasmSignature>();
954       if (parseRegTypeList(Signature->Params))
955         return ParseStatus::Failure;
956       WasmSym->setSignature(Signature.get());
957       addSignature(std::move(Signature));
958       WasmSym->setType(wasm::WASM_SYMBOL_TYPE_TAG);
959       TOut.emitTagType(WasmSym);
960       // TODO: backend also calls TOut.emitIndIdx, but that is not implemented.
961       return expect(AsmToken::EndOfStatement, "EOL");
962     }
963 
964     if (DirectiveID.getString() == ".local") {
965       if (CurrentState != FunctionStart)
966         return error(".local directive should follow the start of a function: ",
967                      Lexer.getTok());
968       SmallVector<wasm::ValType, 4> Locals;
969       if (parseRegTypeList(Locals))
970         return ParseStatus::Failure;
971       TC.localDecl(Locals);
972       TOut.emitLocal(Locals);
973       CurrentState = FunctionLocals;
974       return expect(AsmToken::EndOfStatement, "EOL");
975     }
976 
977     if (DirectiveID.getString() == ".int8" ||
978         DirectiveID.getString() == ".int16" ||
979         DirectiveID.getString() == ".int32" ||
980         DirectiveID.getString() == ".int64") {
981       if (CheckDataSection())
982         return ParseStatus::Failure;
983       const MCExpr *Val;
984       SMLoc End;
985       if (Parser.parseExpression(Val, End))
986         return error("Cannot parse .int expression: ", Lexer.getTok());
987       size_t NumBits = 0;
988       DirectiveID.getString().drop_front(4).getAsInteger(10, NumBits);
989       Out.emitValue(Val, NumBits / 8, End);
990       return expect(AsmToken::EndOfStatement, "EOL");
991     }
992 
993     if (DirectiveID.getString() == ".asciz") {
994       if (CheckDataSection())
995         return ParseStatus::Failure;
996       std::string S;
997       if (Parser.parseEscapedString(S))
998         return error("Cannot parse string constant: ", Lexer.getTok());
999       Out.emitBytes(StringRef(S.c_str(), S.length() + 1));
1000       return expect(AsmToken::EndOfStatement, "EOL");
1001     }
1002 
1003     return ParseStatus::NoMatch; // We didn't process this directive.
1004   }
1005 
1006   // Called either when the first instruction is parsed of the function ends.
1007   void ensureLocals(MCStreamer &Out) {
1008     if (CurrentState == FunctionStart) {
1009       // We haven't seen a .local directive yet. The streamer requires locals to
1010       // be encoded as a prelude to the instructions, so emit an empty list of
1011       // locals here.
1012       auto &TOut = reinterpret_cast<WebAssemblyTargetStreamer &>(
1013           *Out.getTargetStreamer());
1014       TOut.emitLocal(SmallVector<wasm::ValType, 0>());
1015       CurrentState = FunctionLocals;
1016     }
1017   }
1018 
1019   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned & /*Opcode*/,
1020                                OperandVector &Operands, MCStreamer &Out,
1021                                uint64_t &ErrorInfo,
1022                                bool MatchingInlineAsm) override {
1023     MCInst Inst;
1024     Inst.setLoc(IDLoc);
1025     FeatureBitset MissingFeatures;
1026     unsigned MatchResult = MatchInstructionImpl(
1027         Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm);
1028     switch (MatchResult) {
1029     case Match_Success: {
1030       ensureLocals(Out);
1031       // Fix unknown p2align operands.
1032       auto Align = WebAssembly::GetDefaultP2AlignAny(Inst.getOpcode());
1033       if (Align != -1U) {
1034         auto &Op0 = Inst.getOperand(0);
1035         if (Op0.getImm() == -1)
1036           Op0.setImm(Align);
1037       }
1038       if (is64) {
1039         // Upgrade 32-bit loads/stores to 64-bit. These mostly differ by having
1040         // an offset64 arg instead of offset32, but to the assembler matcher
1041         // they're both immediates so don't get selected for.
1042         auto Opc64 = WebAssembly::getWasm64Opcode(
1043             static_cast<uint16_t>(Inst.getOpcode()));
1044         if (Opc64 >= 0) {
1045           Inst.setOpcode(Opc64);
1046         }
1047       }
1048       if (!SkipTypeCheck && TC.typeCheck(IDLoc, Inst, Operands))
1049         return true;
1050       Out.emitInstruction(Inst, getSTI());
1051       if (CurrentState == EndFunction) {
1052         onEndOfFunction(IDLoc);
1053       } else {
1054         CurrentState = Instructions;
1055       }
1056       return false;
1057     }
1058     case Match_MissingFeature: {
1059       assert(MissingFeatures.count() > 0 && "Expected missing features");
1060       SmallString<128> Message;
1061       raw_svector_ostream OS(Message);
1062       OS << "instruction requires:";
1063       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
1064         if (MissingFeatures.test(i))
1065           OS << ' ' << getSubtargetFeatureName(i);
1066       return Parser.Error(IDLoc, Message);
1067     }
1068     case Match_MnemonicFail:
1069       return Parser.Error(IDLoc, "invalid instruction");
1070     case Match_NearMisses:
1071       return Parser.Error(IDLoc, "ambiguous instruction");
1072     case Match_InvalidTiedOperand:
1073     case Match_InvalidOperand: {
1074       SMLoc ErrorLoc = IDLoc;
1075       if (ErrorInfo != ~0ULL) {
1076         if (ErrorInfo >= Operands.size())
1077           return Parser.Error(IDLoc, "too few operands for instruction");
1078         ErrorLoc = Operands[ErrorInfo]->getStartLoc();
1079         if (ErrorLoc == SMLoc())
1080           ErrorLoc = IDLoc;
1081       }
1082       return Parser.Error(ErrorLoc, "invalid operand for instruction");
1083     }
1084     }
1085     llvm_unreachable("Implement any new match types added!");
1086   }
1087 
1088   void doBeforeLabelEmit(MCSymbol *Symbol, SMLoc IDLoc) override {
1089     // Code below only applies to labels in text sections.
1090     auto CWS = cast<MCSectionWasm>(getStreamer().getCurrentSection().first);
1091     if (!CWS || !CWS->getKind().isText())
1092       return;
1093 
1094     auto WasmSym = cast<MCSymbolWasm>(Symbol);
1095     // Unlike other targets, we don't allow data in text sections (labels
1096     // declared with .type @object).
1097     if (WasmSym->getType() == wasm::WASM_SYMBOL_TYPE_DATA) {
1098       Parser.Error(IDLoc,
1099                    "Wasm doesn\'t support data symbols in text sections");
1100       return;
1101     }
1102 
1103     // Start a new section for the next function automatically, since our
1104     // object writer expects each function to have its own section. This way
1105     // The user can't forget this "convention".
1106     auto SymName = Symbol->getName();
1107     if (SymName.startswith(".L"))
1108       return; // Local Symbol.
1109 
1110     // TODO: If the user explicitly creates a new function section, we ignore
1111     // its name when we create this one. It would be nice to honor their
1112     // choice, while still ensuring that we create one if they forget.
1113     // (that requires coordination with WasmAsmParser::parseSectionDirective)
1114     auto SecName = ".text." + SymName;
1115 
1116     auto *Group = CWS->getGroup();
1117     // If the current section is a COMDAT, also set the flag on the symbol.
1118     // TODO: Currently the only place that the symbols' comdat flag matters is
1119     // for importing comdat functions. But there's no way to specify that in
1120     // assembly currently.
1121     if (Group)
1122       WasmSym->setComdat(true);
1123     auto *WS =
1124         getContext().getWasmSection(SecName, SectionKind::getText(), 0, Group,
1125                                     MCContext::GenericSectionID, nullptr);
1126     getStreamer().switchSection(WS);
1127     // Also generate DWARF for this section if requested.
1128     if (getContext().getGenDwarfForAssembly())
1129       getContext().addGenDwarfSection(WS);
1130 
1131     if (WasmSym->isFunction()) {
1132       // We give the location of the label (IDLoc) here, because otherwise the
1133       // lexer's next location will be used, which can be confusing. For
1134       // example:
1135       //
1136       // test0: ; This function does not end properly
1137       //   ...
1138       //
1139       // test1: ; We would like to point to this line for error
1140       //   ...  . Not this line, which can contain any instruction
1141       ensureEmptyNestingStack(IDLoc);
1142       CurrentState = FunctionLabel;
1143       LastFunctionLabel = Symbol;
1144       push(Function);
1145     }
1146   }
1147 
1148   void onEndOfFunction(SMLoc ErrorLoc) {
1149     if (!SkipTypeCheck)
1150       TC.endOfFunction(ErrorLoc);
1151     // Reset the type checker state.
1152     TC.Clear();
1153   }
1154 
1155   void onEndOfFile() override { ensureEmptyNestingStack(); }
1156 };
1157 } // end anonymous namespace
1158 
1159 // Force static initialization.
1160 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyAsmParser() {
1161   RegisterMCAsmParser<WebAssemblyAsmParser> X(getTheWebAssemblyTarget32());
1162   RegisterMCAsmParser<WebAssemblyAsmParser> Y(getTheWebAssemblyTarget64());
1163 }
1164 
1165 #define GET_REGISTER_MATCHER
1166 #define GET_SUBTARGET_FEATURE_NAME
1167 #define GET_MATCHER_IMPLEMENTATION
1168 #include "WebAssemblyGenAsmMatcher.inc"
1169 
1170 StringRef GetMnemonic(unsigned Opc) {
1171   // FIXME: linear search!
1172   for (auto &ME : MatchTable0) {
1173     if (ME.Opcode == Opc) {
1174       return ME.getMnemonic();
1175     }
1176   }
1177   assert(false && "mnemonic not found");
1178   return StringRef();
1179 }
1180