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