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