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