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