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