MLIR 24.0.0git
TranslateFromWasm.cpp
Go to the documentation of this file.
1//===- TranslateFromWasm.cpp - Translating to WasmSSA dialect -------------===//
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// This file implements the WebAssembly importer.
10//
11//===----------------------------------------------------------------------===//
12
14#include "mlir/IR/Attributes.h"
15#include "mlir/IR/Builders.h"
19#include "mlir/IR/Diagnostics.h"
20#include "mlir/IR/Location.h"
21#include "mlir/Support/LLVM.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/DebugLog.h"
26#include "llvm/Support/Endian.h"
27#include "llvm/Support/FormatVariadic.h"
28#include "llvm/Support/LEB128.h"
29#include "llvm/Support/LogicalResult.h"
30
31#include <cassert>
32#include <cstddef>
33#include <cstdint>
34#include <type_traits>
35#include <variant>
36
37#define DEBUG_TYPE "wasm-translate"
38
39static_assert(CHAR_BIT == 8,
40 "This code expects std::byte to be exactly 8 bits");
41
42using namespace mlir;
43using namespace mlir::wasm;
44using namespace mlir::wasmssa;
45
46namespace {
47using section_id_t = uint8_t;
48enum struct WasmSectionType : section_id_t {
49 CUSTOM = 0,
50 TYPE = 1,
51 IMPORT = 2,
52 FUNCTION = 3,
53 TABLE = 4,
54 MEMORY = 5,
55 GLOBAL = 6,
56 EXPORT = 7,
57 START = 8,
58 ELEMENT = 9,
59 CODE = 10,
60 DATA = 11,
61 DATACOUNT = 12
62};
63
64constexpr section_id_t highestWasmSectionID{
65 static_cast<section_id_t>(WasmSectionType::DATACOUNT)};
66
67#define APPLY_WASM_SEC_TRANSFORM \
68 WASM_SEC_TRANSFORM(CUSTOM) \
69 WASM_SEC_TRANSFORM(TYPE) \
70 WASM_SEC_TRANSFORM(IMPORT) \
71 WASM_SEC_TRANSFORM(FUNCTION) \
72 WASM_SEC_TRANSFORM(TABLE) \
73 WASM_SEC_TRANSFORM(MEMORY) \
74 WASM_SEC_TRANSFORM(GLOBAL) \
75 WASM_SEC_TRANSFORM(EXPORT) \
76 WASM_SEC_TRANSFORM(START) \
77 WASM_SEC_TRANSFORM(ELEMENT) \
78 WASM_SEC_TRANSFORM(CODE) \
79 WASM_SEC_TRANSFORM(DATA) \
80 WASM_SEC_TRANSFORM(DATACOUNT)
81
82template <WasmSectionType>
83constexpr const char *wasmSectionName = "";
84
85#define WASM_SEC_TRANSFORM(section) \
86 template <> \
87 [[maybe_unused]] constexpr const char \
88 *wasmSectionName<WasmSectionType::section> = #section;
90#undef WASM_SEC_TRANSFORM
91
92constexpr bool sectionShouldBeUnique(WasmSectionType secType) {
93 return secType != WasmSectionType::CUSTOM;
94}
95
96template <std::byte... Bytes>
97struct ByteSequence {};
98
99/// Template class for representing a byte sequence of only one byte
100template <std::byte Byte>
101struct UniqueByte : ByteSequence<Byte> {};
102
103[[maybe_unused]] constexpr ByteSequence<
106 WasmBinaryEncoding::Type::v128> valueTypesEncodings{};
107
108template <std::byte... allowedFlags>
109constexpr bool isValueOneOf(std::byte value,
110 ByteSequence<allowedFlags...> = {}) {
111 return ((value == allowedFlags) | ... | false);
112}
113
114template <std::byte... flags>
115constexpr bool isNotIn(std::byte value, ByteSequence<flags...> = {}) {
116 return !isValueOneOf<flags...>(value);
117}
118
119struct GlobalTypeRecord {
120 Type type;
121 bool isMutable;
122};
123
124struct TypeIdxRecord {
125 size_t id;
126};
127
128struct SymbolRefContainer {
129 FlatSymbolRefAttr symbol;
130};
131
132struct GlobalSymbolRefContainer : SymbolRefContainer {
133 Type globalType;
134};
135
136struct FunctionSymbolRefContainer : SymbolRefContainer {
137 FunctionType functionType;
138};
139
140using ImportDesc =
141 std::variant<TypeIdxRecord, TableType, LimitType, GlobalTypeRecord>;
142
143using parsed_inst_t = FailureOr<SmallVector<Value>>;
144
145struct EmptyBlockMarker {};
146using BlockTypeParseResult =
147 std::variant<EmptyBlockMarker, TypeIdxRecord, Type>;
148
149struct WasmModuleSymbolTables {
150 SmallVector<FunctionSymbolRefContainer> funcSymbols;
151 SmallVector<GlobalSymbolRefContainer> globalSymbols;
152 SmallVector<SymbolRefContainer> memSymbols;
153 SmallVector<SymbolRefContainer> tableSymbols;
154 SmallVector<FunctionType> moduleFuncTypes;
155
156 std::string getNewSymbolName(StringRef prefix, size_t id) const {
157 return (prefix + Twine{id}).str();
158 }
159
160 std::string getNewFuncSymbolName() const {
161 size_t id = funcSymbols.size();
162 return getNewSymbolName("func_", id);
163 }
164
165 std::string getNewGlobalSymbolName() const {
166 size_t id = globalSymbols.size();
167 return getNewSymbolName("global_", id);
168 }
169
170 std::string getNewMemorySymbolName() const {
171 size_t id = memSymbols.size();
172 return getNewSymbolName("mem_", id);
173 }
174
175 std::string getNewTableSymbolName() const {
176 size_t id = tableSymbols.size();
177 return getNewSymbolName("table_", id);
178 }
179};
180
181class ParserHead;
182
183/// Wrapper around SmallVector to only allow access as push and pop on the
184/// stack. Makes sure that there are no "free accesses" on the stack to preserve
185/// its state.
186/// This class also keep tracks of the Wasm labels defined by different ops,
187/// which can be targeted by control flow ops. This can be modeled as part of
188/// the Value Stack as Wasm control flow ops can only target enclosing labels.
189class ValueStack {
190private:
191 struct LabelLevel {
192 size_t stackIdx;
193 LabelLevelOpInterface levelOp;
194 };
195
196public:
197 bool empty() const { return values.empty(); }
198
199 size_t size() const { return values.size(); }
200
201 /// Pops values from the stack because they are being used in an operation.
202 /// @param operandTypes The list of expected types of the operation, used
203 /// to know how many values to pop and check if the types match the
204 /// expectation.
205 /// @param opLoc Location of the caller, used to report accurately the
206 /// location
207 /// if an error occurs.
208 /// @return Failure or the vector of popped values.
209 FailureOr<SmallVector<Value>> popOperands(TypeRange operandTypes,
210 Location *opLoc);
211
212 /// Push the results of an operation to the stack so they can be used in a
213 /// following operation.
214 /// @param results The list of results of the operation
215 /// @param opLoc Location of the caller, used to report accurately the
216 /// location
217 /// if an error occurs.
218 LogicalResult pushResults(ValueRange results, Location *opLoc);
219
220 void addLabelLevel(LabelLevelOpInterface levelOp) {
221 labelLevel.push_back({values.size(), levelOp});
222 LDBG() << "Adding a new frame context to ValueStack";
223 }
224
225 void dropLabelLevel() {
226 assert(!labelLevel.empty() && "Trying to drop a frame from empty context");
227 auto newSize = labelLevel.pop_back_val().stackIdx;
228 values.truncate(newSize);
229 }
230#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
231 /// A simple dump function for debugging.
232 /// Writes output to llvm::dbgs().
233 LLVM_DUMP_METHOD void dump() const;
234#endif
235
236private:
237 SmallVector<Value> values;
238 SmallVector<LabelLevel> labelLevel;
239};
240
241using local_val_t = TypedValue<wasmssa::LocalRefType>;
242
243// MSVC 19.29 cannot parse a pack expansion of a braced conversion
244// (std::byte{IS}...) as a non-type template argument.
245template <size_t I>
246constexpr std::byte byteAt = static_cast<std::byte>(I);
247
248template <size_t... IS>
249constexpr ByteSequence<byteAt<IS>...>
250castIndexSequenceToBytes(std::index_sequence<IS...>) {
251 return {};
252}
253
254constexpr auto all8bitsBytes =
255 castIndexSequenceToBytes(std::make_index_sequence<256>());
256
257template <std::byte>
258struct OpCode {};
259
260class ExpressionParser {
261public:
262 using locals_t = SmallVector<local_val_t>;
263 ExpressionParser(ParserHead &parser, WasmModuleSymbolTables const &symbols,
264 ArrayRef<local_val_t> initLocal)
265 : parser{parser}, symbols{symbols}, locals{initLocal} {}
266
267private:
268 inline parsed_inst_t dispatchToInstParser(std::byte opCode,
269 OpBuilder &builder);
270 ///
271 /// RAII guard class for creating a nesting level
272 ///
273 struct NestingContextGuard {
274 NestingContextGuard(ExpressionParser &parser, LabelLevelOpInterface levelOp)
275 : parser{parser} {
276 parser.addNestingContextLevel(levelOp);
277 }
278 NestingContextGuard(NestingContextGuard &&other) : parser{other.parser} {
279 other.shouldDropOnDestruct = false;
280 }
281 NestingContextGuard(NestingContextGuard const &) = delete;
282 ~NestingContextGuard() {
283 if (shouldDropOnDestruct)
284 parser.dropNestingContextLevel();
285 }
286 ExpressionParser &parser;
287 bool shouldDropOnDestruct = true;
288 };
289
290 void addNestingContextLevel(LabelLevelOpInterface levelOp) {
291 valueStack.addLabelLevel(levelOp);
292 }
293
294 void dropNestingContextLevel() {
295 // Should always succeed as we are droping the frame that was previously
296 // created.
297 valueStack.dropLabelLevel();
298 }
299
300 llvm::FailureOr<FunctionType> getFuncTypeFor(OpBuilder &builder,
301 EmptyBlockMarker) {
302 return builder.getFunctionType({}, {});
303 }
304
305 llvm::FailureOr<FunctionType> getFuncTypeFor(OpBuilder &builder,
306 TypeIdxRecord type) {
307 if (type.id >= symbols.moduleFuncTypes.size())
308 return emitError(*currentOpLoc,
309 "type index references nonexistent type (")
310 << type.id << "). Only " << symbols.moduleFuncTypes.size()
311 << " types are registered";
312 return symbols.moduleFuncTypes[type.id];
313 }
314
315 llvm::FailureOr<FunctionType> getFuncTypeFor(OpBuilder &builder,
316 Type valType) {
317 return builder.getFunctionType({}, {valType});
318 }
319
320 llvm::FailureOr<FunctionType>
321 getFuncTypeFor(OpBuilder &builder, BlockTypeParseResult parseResult) {
322 return std::visit(
323 [this, &builder](auto value) { return getFuncTypeFor(builder, value); },
324 parseResult);
325 }
326
327 llvm::FailureOr<FunctionType>
328 getFuncTypeFor(OpBuilder &builder,
329 llvm::FailureOr<BlockTypeParseResult> parseResult) {
330 if (llvm::failed(parseResult))
331 return failure();
332 return getFuncTypeFor(builder, *parseResult);
333 }
334
335 struct ParseResultWithInfo {
336 SmallVector<Value> opResults;
337 std::byte endingByte;
338 };
339
340 llvm::FailureOr<FunctionType> parseBlockFuncType(OpBuilder &builder);
341
342public:
343 template <std::byte ParseEndByte = WasmBinaryEncoding::endByte>
344 parsed_inst_t parse(OpBuilder &builder, UniqueByte<ParseEndByte> = {});
345
346 template <std::byte... ExpressionParseEnd>
347 FailureOr<ParseResultWithInfo>
348 parse(OpBuilder &builder,
349 ByteSequence<ExpressionParseEnd...> parsingEndFilters);
350
351 NestingContextGuard addNesting(LabelLevelOpInterface levelOp) {
352 return NestingContextGuard{*this, levelOp};
353 }
354
355 FailureOr<llvm::SmallVector<Value>> popOperands(TypeRange operandTypes) {
356 return valueStack.popOperands(operandTypes, &currentOpLoc.value());
357 }
358
359 LogicalResult pushResults(ValueRange results) {
360 return valueStack.pushResults(results, &currentOpLoc.value());
361 }
362
363 /// The local.set and local.tee operations behave similarly and only differ
364 /// on their return value. This function factorizes the behavior of the two
365 /// operations in one place.
366 template <typename OpToCreate>
367 parsed_inst_t parseSetOrTee(OpBuilder &);
368
369 Location getCurrentOpLoc() {
370 assert(currentOpLoc.has_value() &&
371 "expects current opcode location to be set");
372 return *currentOpLoc;
373 }
374
375 class ExprParserProxy {
376 public:
377 friend ExpressionParser;
378 inline auto parseBlockFuncType(OpBuilder &builder) {
379 return exprParser.parseBlockFuncType(builder);
380 }
381
382 /// @param blockToFill: the block which content will be populated
383 /// @param resType: the type that this block is supposed to return
384 template <typename FilterT = ByteSequence<WasmBinaryEncoding::endByte>>
385 llvm::FailureOr<std::byte>
386 parseBlockContent(OpBuilder &builder, Block *blockToFill,
387 TypeRange resTypes, Location opLoc,
388 LabelLevelOpInterface levelOp,
389 FilterT parseEndBytes = {}) {
390 OpBuilder::InsertionGuard guard(builder);
391 assert(blockToFill && blockToFill->empty() && "expected an empty block");
392 builder.setInsertionPointToStart(blockToFill);
393 LDBG() << "parsing a block of type "
394 << builder.getFunctionType(blockToFill->getArgumentTypes(),
395 resTypes);
396 auto nestingGuard = exprParser.addNesting(levelOp);
397
398 if (failed(exprParser.pushResults(blockToFill->getArguments())))
399 return failure();
400 auto bodyParsingRes = exprParser.parse(builder, parseEndBytes);
401 if (failed(bodyParsingRes))
402 return failure();
403 auto returnOperands = exprParser.popOperands(resTypes);
404 if (failed(returnOperands))
405 return failure();
406 BlockReturnOp::create(builder, opLoc, *returnOperands);
407 LDBG() << "end of parsing of a block";
408 return bodyParsingRes->endingByte;
409 }
410
411 inline ParserHead &parser() { return exprParser.parser; }
412
413 /// Blocks and Loops have a similar format and differ only in how their exit
414 /// is handled which doesn´t matter at parsing time. Factorizes in one
415 /// function.
416 template <typename OpToCreate>
417 parsed_inst_t parseBlockLikeOp(OpBuilder &);
418
419 inline auto getCurrentOpLoc() { return exprParser.getCurrentOpLoc(); }
420
421 inline auto popOperands(TypeRange operandTypes) {
422 return exprParser.popOperands(operandTypes);
423 }
424
425 inline auto &symbols() { return exprParser.symbols; }
426
427 inline auto &locals() { return exprParser.locals; }
428
429 template <typename OpToCreate>
430 parsed_inst_t parseSetOrTee(OpBuilder &builder) {
431 return exprParser.parseSetOrTee<OpToCreate>(builder);
432 }
433
434 template <typename valueT>
435 parsed_inst_t
436 parseConstInst(OpBuilder &builder,
437 std::enable_if_t<std::is_arithmetic_v<valueT>> * = nullptr);
438
439 /// Construct an operation with \p numOperands operands and a single result.
440 /// Each operand must have the same type. Suitable for e.g. binops, unary
441 /// ops, etc.
442 ///
443 /// \p opcode - The WASM opcode to build.
444 /// \p valueType - The operand and result type for the built instruction.
445 /// \p numOperands - The number of operands for the built operation.
446 ///
447 /// \returns The parsed instruction result, or failure.
448 template <typename opcode, typename valueType, unsigned int numOperands>
449 inline parsed_inst_t buildNumericOp(
450 OpBuilder &builder,
451 std::enable_if_t<std::is_arithmetic_v<valueType>> * = nullptr);
452
453 /// Construct a conversion operation of type \p opType that takes a value
454 /// from
455 /// type \p inputType on the stack and will produce a value of type
456 /// \p outputType.
457 ///
458 /// \p opType - The WASM dialect operation to build.
459 /// \p inputType - The operand type for the built instruction.
460 /// \p outputType - The result type for the built instruction.
461 ///
462 /// \returns The parsed instruction result, or failure.
463 template <typename opType, typename inputType, typename outputType,
464 typename... extraArgsT>
465 inline parsed_inst_t buildConvertOp(OpBuilder &builder, extraArgsT...);
466
467 private:
468 explicit ExprParserProxy(ExpressionParser &exprParser)
469 : exprParser{exprParser} {};
470
471 private:
472 ExpressionParser &exprParser;
473 };
474
475private:
476 std::optional<Location> currentOpLoc;
477 ParserHead &parser;
478 WasmModuleSymbolTables const &symbols;
479 locals_t locals;
480 ValueStack valueStack;
481};
482
483class ParserHead {
484public:
485 ParserHead(StringRef src, StringAttr name) : head{src}, locName{name} {}
486 ParserHead(ParserHead &&) = default;
487
488private:
489 ParserHead(ParserHead const &other) = default;
490
491public:
492 auto getLocation() const {
493 return FileLineColLoc::get(locName, 0, anchorOffset + offset);
494 }
495
496 FailureOr<StringRef> consumeNBytes(size_t nBytes) {
497 LDBG() << "Consume " << nBytes << " bytes";
498 LDBG() << " Bytes remaining: " << size();
499 LDBG() << " Current offset: " << offset;
500 if (nBytes > size())
501 return emitError(getLocation(), "trying to extract ")
502 << nBytes << "bytes when only " << size() << "are available";
503
504 StringRef res = head.slice(offset, offset + nBytes);
505 offset += nBytes;
506 LDBG() << " Updated offset (+" << nBytes << "): " << offset;
507 return res;
508 }
509
510 FailureOr<std::byte> consumeByte() {
511 FailureOr<StringRef> res = consumeNBytes(1);
512 if (failed(res))
513 return failure();
514 return std::byte{*res->bytes_begin()};
515 }
516
517 template <typename T>
518 FailureOr<T> parseLiteral();
519
520 FailureOr<uint32_t> parseVectorSize();
521
522private:
523 // TODO: This is equivalent to parseLiteral<uint32_t> and could be removed
524 // if parseLiteral specialization were moved here, but default GCC on Ubuntu
525 // 22.04 has bug with template specialization in class declaration
526 inline FailureOr<uint32_t> parseUI32();
527 inline FailureOr<int64_t> parseI64();
528
529public:
530 FailureOr<StringRef> parseName() {
531 FailureOr<uint32_t> size = parseVectorSize();
532 if (failed(size))
533 return failure();
534
535 return consumeNBytes(*size);
536 }
537
538 FailureOr<WasmSectionType> parseWasmSectionType() {
539 FailureOr<std::byte> id = consumeByte();
540 if (failed(id))
541 return failure();
542 if (std::to_integer<unsigned>(*id) > highestWasmSectionID)
543 return emitError(getLocation(), "invalid section ID: ")
544 << static_cast<int>(*id);
545 return static_cast<WasmSectionType>(*id);
546 }
547
548 FailureOr<LimitType> parseLimit(MLIRContext *ctx) {
549 using WasmLimits = WasmBinaryEncoding::LimitHeader;
550 FileLineColLoc limitLocation = getLocation();
551 FailureOr<std::byte> limitHeader = consumeByte();
552 if (failed(limitHeader))
553 return failure();
554
555 if (isNotIn<WasmLimits::bothLimits, WasmLimits::lowLimitOnly>(*limitHeader))
556 return emitError(limitLocation, "invalid limit header: ")
557 << static_cast<int>(*limitHeader);
558 FailureOr<uint32_t> minParse = parseUI32();
559 if (failed(minParse))
560 return failure();
561 std::optional<uint32_t> max{std::nullopt};
562 if (*limitHeader == WasmLimits::bothLimits) {
563 FailureOr<uint32_t> maxParse = parseUI32();
564 if (failed(maxParse))
565 return failure();
566 max = *maxParse;
567 }
568 return LimitType::get(ctx, *minParse, max);
569 }
570
571 FailureOr<Type> parseValueType(MLIRContext *ctx) {
572 FileLineColLoc typeLoc = getLocation();
573 FailureOr<std::byte> typeEncoding = consumeByte();
574 if (failed(typeEncoding))
575 return failure();
576 switch (*typeEncoding) {
578 return IntegerType::get(ctx, 32);
580 return IntegerType::get(ctx, 64);
582 return Float32Type::get(ctx);
584 return Float64Type::get(ctx);
586 return IntegerType::get(ctx, 128);
588 return wasmssa::FuncRefType::get(ctx);
590 return wasmssa::ExternRefType::get(ctx);
591 default:
592 return emitError(typeLoc, "invalid value type encoding: ")
593 << static_cast<int>(*typeEncoding);
594 }
595 }
596
597 FailureOr<GlobalTypeRecord> parseGlobalType(MLIRContext *ctx) {
598 using WasmGlobalMut = WasmBinaryEncoding::GlobalMutability;
599 FailureOr<Type> typeParsed = parseValueType(ctx);
600 if (failed(typeParsed))
601 return failure();
602 FileLineColLoc mutLoc = getLocation();
603 FailureOr<std::byte> mutSpec = consumeByte();
604 if (failed(mutSpec))
605 return failure();
606 if (isNotIn<WasmGlobalMut::isConst, WasmGlobalMut::isMutable>(*mutSpec))
607 return emitError(mutLoc, "invalid global mutability specifier: ")
608 << static_cast<int>(*mutSpec);
609 return GlobalTypeRecord{*typeParsed, *mutSpec == WasmGlobalMut::isMutable};
610 }
611
612 FailureOr<TupleType> parseResultType(MLIRContext *ctx) {
613 FailureOr<uint32_t> nParamsParsed = parseVectorSize();
614 if (failed(nParamsParsed))
615 return failure();
616 uint32_t nParams = *nParamsParsed;
617 SmallVector<Type> res{};
618 res.reserve(nParams);
619 for (size_t i = 0; i < nParams; ++i) {
620 FailureOr<Type> parsedType = parseValueType(ctx);
621 if (failed(parsedType))
622 return failure();
623 res.push_back(*parsedType);
624 }
625 return TupleType::get(ctx, res);
626 }
627
628 FailureOr<FunctionType> parseFunctionType(MLIRContext *ctx) {
629 FileLineColLoc typeLoc = getLocation();
630 FailureOr<std::byte> funcTypeHeader = consumeByte();
631 if (failed(funcTypeHeader))
632 return failure();
633 if (*funcTypeHeader != WasmBinaryEncoding::Type::funcType)
634 return emitError(typeLoc, "invalid function type header byte. Expecting ")
635 << std::to_integer<unsigned>(WasmBinaryEncoding::Type::funcType)
636 << " got " << std::to_integer<unsigned>(*funcTypeHeader);
637 FailureOr<TupleType> inputTypes = parseResultType(ctx);
638 if (failed(inputTypes))
639 return failure();
640
641 FailureOr<TupleType> resTypes = parseResultType(ctx);
642 if (failed(resTypes))
643 return failure();
644
645 return FunctionType::get(ctx, inputTypes->getTypes(), resTypes->getTypes());
646 }
647
648 FailureOr<TypeIdxRecord> parseTypeIndex() {
649 FailureOr<uint32_t> res = parseUI32();
650 if (failed(res))
651 return failure();
652 return TypeIdxRecord{*res};
653 }
654
655 FailureOr<TableType> parseTableType(MLIRContext *ctx) {
656 FailureOr<Type> elmTypeParse = parseValueType(ctx);
657 if (failed(elmTypeParse))
658 return failure();
659 if (!isWasmRefType(*elmTypeParse))
660 return emitError(getLocation(), "invalid element type for table");
661 FailureOr<LimitType> limitParse = parseLimit(ctx);
662 if (failed(limitParse))
663 return failure();
664 return TableType::get(ctx, *elmTypeParse, *limitParse);
665 }
666
667 FailureOr<ImportDesc> parseImportDesc(MLIRContext *ctx) {
668 FileLineColLoc importLoc = getLocation();
669 FailureOr<std::byte> importType = consumeByte();
670 auto packager = [](auto parseResult) -> FailureOr<ImportDesc> {
671 if (failed(parseResult))
672 return failure();
673 return {*parseResult};
674 };
675 if (failed(importType))
676 return failure();
677 switch (*importType) {
679 return packager(parseTypeIndex());
681 return packager(parseTableType(ctx));
683 return packager(parseLimit(ctx));
685 return packager(parseGlobalType(ctx));
686 default:
687 return emitError(importLoc, "invalid import type descriptor: ")
688 << static_cast<int>(*importType);
689 }
690 }
691
692 parsed_inst_t parseExpression(OpBuilder &builder,
693 WasmModuleSymbolTables const &symbols,
694 ArrayRef<local_val_t> locals = {}) {
695 auto eParser = ExpressionParser{*this, symbols, locals};
696 return eParser.parse(builder);
697 }
698
699 LogicalResult parseCodeFor(FuncOp func,
700 WasmModuleSymbolTables const &symbols) {
701 SmallVector<local_val_t> locals{};
702 // Populating locals with function argument
703 Block &block = func.getBody().front();
704 // Delete temporary return argument which was only created for IR validity
705 assert(func.getBody().getBlocks().size() == 1 &&
706 "Function should only have its default created block at this point");
707 assert(block.getOperations().size() == 1 &&
708 "Only the placeholder return op should be present at this point");
709 auto returnOp = cast<ReturnOp>(&block.back());
710 assert(returnOp);
711
712 FailureOr<uint32_t> codeSizeInBytes = parseUI32();
713 if (failed(codeSizeInBytes))
714 return failure();
715 FailureOr<StringRef> codeContent = consumeNBytes(*codeSizeInBytes);
716 if (failed(codeContent))
717 return failure();
718 auto name = StringAttr::get(func->getContext(),
719 locName.str() + "::" + func.getSymName());
720 auto cParser = ParserHead{*codeContent, name};
721 FailureOr<uint32_t> localVecSize = cParser.parseVectorSize();
722 if (failed(localVecSize))
723 return failure();
724 OpBuilder builder{&func.getBody().front().back()};
725 for (auto arg : block.getArguments())
726 locals.push_back(cast<TypedValue<LocalRefType>>(arg));
727 // Declare the local ops
728 uint32_t nVarVec = *localVecSize;
729 for (size_t i = 0; i < nVarVec; ++i) {
730 FileLineColLoc varLoc = cParser.getLocation();
731 FailureOr<uint32_t> nSubVar = cParser.parseUI32();
732 if (failed(nSubVar))
733 return failure();
734 FailureOr<Type> varT = cParser.parseValueType(func->getContext());
735 if (failed(varT))
736 return failure();
737 for (size_t j = 0; j < *nSubVar; ++j) {
738 auto local = LocalOp::create(builder, varLoc, *varT);
739 locals.push_back(local.getResult());
740 }
741 }
742 parsed_inst_t res = cParser.parseExpression(builder, symbols, locals);
743 if (failed(res))
744 return failure();
745 if (!cParser.end())
746 return emitError(cParser.getLocation(),
747 "unparsed garbage remaining at end of code block");
748 ReturnOp::create(builder, func->getLoc(), *res);
749 returnOp->erase();
750 return success();
751 }
752
753 llvm::FailureOr<BlockTypeParseResult> parseBlockType(MLIRContext *ctx) {
754 auto loc = getLocation();
755 auto blockIndicator = peek();
756 if (failed(blockIndicator))
757 return failure();
758 if (*blockIndicator == WasmBinaryEncoding::Type::emptyBlockType) {
759 offset += 1;
760 return {EmptyBlockMarker{}};
761 }
762 if (isValueOneOf(*blockIndicator, valueTypesEncodings))
763 return parseValueType(ctx);
764 /// Block type idx is a 32 bit positive integer encoded as a 33 bit signed
765 /// value
766 auto typeIdx = parseI64();
767 if (failed(typeIdx))
768 return failure();
769 if (*typeIdx < 0 || *typeIdx > std::numeric_limits<uint32_t>::max())
770 return emitError(loc, "type ID should be representable with an unsigned "
771 "32 bits integer. Got ")
772 << *typeIdx;
773 return {TypeIdxRecord{static_cast<uint32_t>(*typeIdx)}};
774 }
775
776 bool end() const { return curHead().empty(); }
777
778 ParserHead copy() const { return *this; }
779
780private:
781 StringRef curHead() const { return head.drop_front(offset); }
782
783 FailureOr<std::byte> peek() const {
784 if (end())
785 return emitError(
786 getLocation(),
787 "trying to peek at next byte, but input stream is empty");
788 return static_cast<std::byte>(curHead().front());
789 }
790
791 size_t size() const { return head.size() - offset; }
792
793 StringRef head;
794 StringAttr locName;
795 unsigned anchorOffset{0};
796 unsigned offset{0};
797};
798
799template <>
800FailureOr<float> ParserHead::parseLiteral<float>() {
801 FailureOr<StringRef> bytes = consumeNBytes(4);
802 if (failed(bytes))
803 return failure();
804 return llvm::support::endian::read<float>(bytes->bytes_begin(),
805 llvm::endianness::little);
806}
807
808template <>
809FailureOr<double> ParserHead::parseLiteral<double>() {
810 FailureOr<StringRef> bytes = consumeNBytes(8);
811 if (failed(bytes))
812 return failure();
813 return llvm::support::endian::read<double>(bytes->bytes_begin(),
814 llvm::endianness::little);
815}
816
817template <>
818FailureOr<uint32_t> ParserHead::parseLiteral<uint32_t>() {
819 char const *error = nullptr;
820 uint32_t res{0};
821 unsigned encodingSize{0};
822 StringRef src = curHead();
823 uint64_t decoded = llvm::decodeULEB128(src.bytes_begin(), &encodingSize,
824 src.bytes_end(), &error);
825 if (error)
826 return emitError(getLocation(), error);
827
828 if (std::isgreater(decoded, std::numeric_limits<uint32_t>::max()))
829 return emitError(getLocation()) << "literal does not fit on 32 bits";
830
831 res = static_cast<uint32_t>(decoded);
832 offset += encodingSize;
833 return res;
834}
835
836template <>
837FailureOr<int32_t> ParserHead::parseLiteral<int32_t>() {
838 char const *error = nullptr;
839 int32_t res{0};
840 unsigned encodingSize{0};
841 StringRef src = curHead();
842 int64_t decoded = llvm::decodeSLEB128(src.bytes_begin(), &encodingSize,
843 src.bytes_end(), &error);
844 if (error)
845 return emitError(getLocation(), error);
846 if (std::isgreater(decoded, std::numeric_limits<int32_t>::max()) ||
847 std::isgreater(std::numeric_limits<int32_t>::min(), decoded))
848 return emitError(getLocation()) << "literal does not fit on 32 bits";
849
850 res = static_cast<int32_t>(decoded);
851 offset += encodingSize;
852 return res;
853}
854
855template <>
856FailureOr<int64_t> ParserHead::parseLiteral<int64_t>() {
857 char const *error = nullptr;
858 unsigned encodingSize{0};
859 StringRef src = curHead();
860 int64_t res = llvm::decodeSLEB128(src.bytes_begin(), &encodingSize,
861 src.bytes_end(), &error);
862 if (error)
863 return emitError(getLocation(), error);
864
865 offset += encodingSize;
866 return res;
867}
868
869FailureOr<uint32_t> ParserHead::parseVectorSize() {
870 return parseLiteral<uint32_t>();
871}
872
873inline FailureOr<uint32_t> ParserHead::parseUI32() {
874 return parseLiteral<uint32_t>();
875}
876
877inline FailureOr<int64_t> ParserHead::parseI64() {
878 return parseLiteral<int64_t>();
879}
880
881#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
882void ValueStack::dump() const {
883 llvm::dbgs() << "================= Wasm ValueStack =======================\n";
884 llvm::dbgs() << "size: " << size() << "\n";
885 llvm::dbgs() << "nbFrames: " << labelLevel.size() << '\n';
886 llvm::dbgs() << "<Top>"
887 << "\n";
888 // Stack is pushed to via push_back. Therefore the top of the stack is the
889 // end of the vector. Iterate in reverse so that the first thing we print
890 // is the top of the stack.
891 auto indexGetter = [this]() {
892 size_t idx = labelLevel.size();
893 return [this, idx]() mutable -> std::optional<std::pair<size_t, size_t>> {
894 llvm::dbgs() << "IDX: " << idx << '\n';
895 if (idx == 0)
896 return std::nullopt;
897 auto frameId = idx - 1;
898 auto frameLimit = labelLevel[frameId].stackIdx;
899 idx -= 1;
900 return {{frameId, frameLimit}};
901 };
902 };
903 auto getNextFrameIndex = indexGetter();
904 auto nextFrameIdx = getNextFrameIndex();
905 size_t stackSize = size();
906 for (size_t idx = 0; idx < stackSize; ++idx) {
907 size_t actualIdx = stackSize - 1 - idx;
908 while (nextFrameIdx && (nextFrameIdx->second > actualIdx)) {
909 llvm::dbgs() << " --------------- Frame (" << nextFrameIdx->first
910 << ")\n";
911 nextFrameIdx = getNextFrameIndex();
912 }
913 llvm::dbgs() << " ";
914 values[actualIdx].dump();
915 }
916 while (nextFrameIdx) {
917 llvm::dbgs() << " --------------- Frame (" << nextFrameIdx->first << ")\n";
918 nextFrameIdx = getNextFrameIndex();
919 }
920 llvm::dbgs() << "<Bottom>"
921 << "\n";
922 llvm::dbgs() << "=========================================================\n";
923}
924#endif
925
926parsed_inst_t ValueStack::popOperands(TypeRange operandTypes, Location *opLoc) {
927 size_t frameSize =
928 values.size() - (labelLevel.empty() ? 0 : labelLevel.back().stackIdx);
929 LDBG() << "Popping from ValueStack\n"
930 << " Elements to pop: " << operandTypes.size() << "\n"
931 << " Current stack size: " << values.size() << "\n"
932 << " Current frame size: " << frameSize;
933 if (operandTypes.size() > frameSize)
934 return emitError(*opLoc, "operand stack underflow: expected ")
935 << operandTypes.size() << ", but the current frame contains "
936 << frameSize;
937 size_t stackIdxOffset = values.size() - operandTypes.size();
938 SmallVector<Value> res{};
939 res.reserve(operandTypes.size());
940 for (size_t i{0}; i < operandTypes.size(); ++i) {
941 Value operand = values[i + stackIdxOffset];
942 Type stackType = operand.getType();
943 if (stackType != operandTypes[i])
944 return emitError(*opLoc, "invalid operand type on stack. expecting ")
945 << operandTypes[i] << ", value on stack is of type " << stackType;
946 LDBG() << " POP: " << operand;
947 res.push_back(operand);
948 }
949 values.resize(values.size() - operandTypes.size());
950 LDBG() << " Updated stack size: " << values.size() << "\n"
951 << " Updated frame size: " << frameSize - operandTypes.size();
952 return res;
953}
954
955LogicalResult ValueStack::pushResults(ValueRange results, Location *opLoc) {
956 LDBG() << "Pushing to ValueStack\n"
957 << " Elements(s) to push: " << results.size() << "\n"
958 << " Current stack size: " << values.size();
959 for (Value val : results) {
960 if (!isWasmValueType(val.getType()))
961 return emitError(*opLoc, "invalid value type on stack: ")
962 << val.getType();
963 LDBG() << " PUSH: " << val;
964 values.push_back(val);
965 }
966
967 LDBG() << " Updated stack size: " << values.size();
968 return success();
969}
970
971template <std::byte EndParseByte>
972parsed_inst_t ExpressionParser::parse(OpBuilder &builder,
973 UniqueByte<EndParseByte> endByte) {
974 auto res = parse(builder, ByteSequence<EndParseByte>{});
975 if (failed(res))
976 return failure();
977 return res->opResults;
978}
979
980template <std::byte... ExpressionParseEnd>
981FailureOr<ExpressionParser::ParseResultWithInfo>
982ExpressionParser::parse(OpBuilder &builder,
983 ByteSequence<ExpressionParseEnd...> parsingEndFilters) {
984 SmallVector<Value> res;
985 for (;;) {
986 currentOpLoc = parser.getLocation();
987 FailureOr<std::byte> opCode = parser.consumeByte();
988 if (failed(opCode))
989 return failure();
990 if (isValueOneOf(*opCode, parsingEndFilters))
991 return {{res, *opCode}};
992 parsed_inst_t resParsed;
993 resParsed = dispatchToInstParser(*opCode, builder);
994 if (failed(resParsed))
995 return failure();
996 std::swap(res, *resParsed);
997 if (failed(pushResults(res)))
998 return failure();
999 }
1000}
1001
1002llvm::FailureOr<FunctionType>
1003ExpressionParser::parseBlockFuncType(OpBuilder &builder) {
1004 return getFuncTypeFor(builder, parser.parseBlockType(builder.getContext()));
1005}
1006
1007template <typename OpToCreate>
1008parsed_inst_t
1009ExpressionParser::ExprParserProxy::parseBlockLikeOp(OpBuilder &builder) {
1010 auto opLoc = getCurrentOpLoc();
1011 auto funcType = parseBlockFuncType(builder);
1012 if (failed(funcType))
1013 return failure();
1014
1015 auto inputTypes = funcType->getInputs();
1016 auto inputOps = popOperands(inputTypes);
1017 if (failed(inputOps))
1018 return failure();
1019
1020 Block *curBlock = builder.getBlock();
1021 Region *curRegion = curBlock->getParent();
1022 auto resTypes = funcType->getResults();
1023 llvm::SmallVector<Location> locations{};
1024 locations.resize(resTypes.size(), getCurrentOpLoc());
1025 auto *successor =
1026 builder.createBlock(curRegion, curRegion->end(), resTypes, locations);
1027 builder.setInsertionPointToEnd(curBlock);
1028 auto blockOp =
1029 OpToCreate::create(builder, getCurrentOpLoc(), *inputOps, successor);
1030 auto *blockBody = blockOp.createBlock();
1031 if (failed(parseBlockContent(builder, blockBody, resTypes, opLoc, blockOp)))
1032 return failure();
1033 builder.setInsertionPointToStart(successor);
1034 return {ValueRange{successor->getArguments()}};
1035}
1036
1037parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::block>,
1038 OpBuilder &builder,
1039 ExpressionParser::ExprParserProxy &exprParser) {
1040 return exprParser.parseBlockLikeOp<BlockOp>(builder);
1041}
1042
1043parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::loop>,
1044 OpBuilder &builder,
1045 ExpressionParser::ExprParserProxy &exprParser) {
1046 return exprParser.parseBlockLikeOp<LoopOp>(builder);
1047}
1048
1049parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::ifOpCode>,
1050 OpBuilder &builder,
1051 ExpressionParser::ExprParserProxy &exprParser) {
1052 auto opLoc = exprParser.getCurrentOpLoc();
1053 auto funcType = exprParser.parseBlockFuncType(builder);
1054 if (failed(funcType))
1055 return failure();
1056
1057 LDBG() << "Parsing an if instruction of type " << *funcType;
1058 auto inputTypes = funcType->getInputs();
1059 auto conditionValue = exprParser.popOperands(builder.getI32Type());
1060 if (failed(conditionValue))
1061 return failure();
1062 auto inputOps = exprParser.popOperands(inputTypes);
1063 if (failed(inputOps))
1064 return failure();
1065
1066 Block *curBlock = builder.getBlock();
1067 Region *curRegion = curBlock->getParent();
1068 auto resTypes = funcType->getResults();
1069 llvm::SmallVector<Location> locations{};
1070 locations.resize(resTypes.size(), exprParser.getCurrentOpLoc());
1071 auto *successor =
1072 builder.createBlock(curRegion, curRegion->end(), resTypes, locations);
1073 builder.setInsertionPointToEnd(curBlock);
1074 auto ifOp = IfOp::create(builder, exprParser.getCurrentOpLoc(),
1075 conditionValue->front(), *inputOps, successor);
1076 auto *ifEntryBlock = ifOp.createIfBlock();
1077 constexpr auto ifElseFilter =
1078 ByteSequence<WasmBinaryEncoding::endByte,
1080 auto parseIfRes = exprParser.parseBlockContent(
1081 builder, ifEntryBlock, resTypes, opLoc, ifOp, ifElseFilter);
1082 if (failed(parseIfRes))
1083 return failure();
1084 if (*parseIfRes == WasmBinaryEncoding::OpCode::elseOpCode) {
1085 LDBG() << " else block is present.";
1086 Block *elseEntryBlock = ifOp.createElseBlock();
1087 auto parseElseRes = exprParser.parseBlockContent(builder, elseEntryBlock,
1088 resTypes, opLoc, ifOp);
1089 if (failed(parseElseRes))
1090 return failure();
1091 }
1092 builder.setInsertionPointToStart(successor);
1093 return {ValueRange{successor->getArguments()}};
1094}
1095
1096parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::branchIf>,
1097 OpBuilder &builder,
1098 ExpressionParser::ExprParserProxy &exprParser) {
1099 auto level = exprParser.parser().parseLiteral<uint32_t>();
1100 if (failed(level))
1101 return failure();
1102 Block *curBlock = builder.getBlock();
1103 Region *curRegion = curBlock->getParent();
1104 auto sip = builder.saveInsertionPoint();
1105 Block *elseBlock = builder.createBlock(curRegion, curRegion->end());
1106 auto condition = exprParser.popOperands(builder.getI32Type());
1107 if (failed(condition))
1108 return failure();
1109 builder.restoreInsertionPoint(sip);
1110 auto targetOp =
1111 LabelBranchingOpInterface::getTargetOpFromBlock(curBlock, *level);
1112 if (failed(targetOp))
1113 return failure();
1114 auto inputTypes = targetOp->getLabelTarget()->getArgumentTypes();
1115 auto branchArgs = exprParser.popOperands(inputTypes);
1116 if (failed(branchArgs))
1117 return failure();
1118 BranchIfOp::create(builder, exprParser.getCurrentOpLoc(), condition->front(),
1119 builder.getUI32IntegerAttr(*level), *branchArgs,
1120 elseBlock);
1121 builder.setInsertionPointToStart(elseBlock);
1122 return {*branchArgs};
1123}
1124
1125parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::call>,
1126 OpBuilder &builder,
1127 ExpressionParser::ExprParserProxy &exprParser) {
1128 auto loc = exprParser.getCurrentOpLoc();
1129 auto funcIdx = exprParser.parser().parseLiteral<uint32_t>();
1130 if (failed(funcIdx))
1131 return failure();
1132 if (*funcIdx >= exprParser.symbols().funcSymbols.size())
1133 return emitError(loc, "Invalid function index: ") << *funcIdx;
1134 auto callee = exprParser.symbols().funcSymbols[*funcIdx];
1135 llvm::ArrayRef<Type> inTypes = callee.functionType.getInputs();
1136 llvm::ArrayRef<Type> resTypes = callee.functionType.getResults();
1137 parsed_inst_t inOperands = exprParser.popOperands(inTypes);
1138 if (failed(inOperands))
1139 return failure();
1140 auto callOp =
1141 FuncCallOp::create(builder, loc, resTypes, callee.symbol, *inOperands);
1142 return {callOp.getResults()};
1143}
1144
1145parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::localGet>,
1146 OpBuilder &builder,
1147 ExpressionParser::ExprParserProxy &exprParser) {
1148 FailureOr<uint32_t> id = exprParser.parser().parseLiteral<uint32_t>();
1149 Location instLoc = exprParser.getCurrentOpLoc();
1150 if (failed(id))
1151 return failure();
1152 if (*id >= exprParser.locals().size())
1153 return emitError(instLoc, "invalid local index. function has ")
1154 << exprParser.locals().size()
1155 << " accessible locals, received index " << *id;
1156 return {{LocalGetOp::create(builder, instLoc, exprParser.locals()[*id])
1157 .getResult()}};
1158}
1159
1160parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::globalGet>,
1161 OpBuilder &builder,
1162 ExpressionParser::ExprParserProxy &exprParser) {
1163 FailureOr<uint32_t> id = exprParser.parser().parseLiteral<uint32_t>();
1164 Location instLoc = exprParser.getCurrentOpLoc();
1165 if (failed(id))
1166 return failure();
1167 if (*id >= exprParser.symbols().globalSymbols.size())
1168 return emitError(instLoc, "invalid global index. function has ")
1169 << exprParser.symbols().globalSymbols.size()
1170 << " accessible globals, received index " << *id;
1171 GlobalSymbolRefContainer globalVar = exprParser.symbols().globalSymbols[*id];
1172 auto globalOp = GlobalGetOp::create(builder, instLoc, globalVar.globalType,
1173 globalVar.symbol);
1174
1175 return {{globalOp.getResult()}};
1176}
1177
1178template <typename OpToCreate>
1179parsed_inst_t ExpressionParser::parseSetOrTee(OpBuilder &builder) {
1180 FailureOr<uint32_t> id = parser.parseLiteral<uint32_t>();
1181 if (failed(id))
1182 return failure();
1183 if (*id >= locals.size())
1184 return emitError(*currentOpLoc, "invalid local index. function has ")
1185 << locals.size() << " accessible locals, received index " << *id;
1186 if (valueStack.empty())
1187 return emitError(
1188 *currentOpLoc,
1189 "invalid stack access, trying to access a value on an empty stack");
1190
1191 parsed_inst_t poppedOp = popOperands(locals[*id].getType().getElementType());
1192 if (failed(poppedOp))
1193 return failure();
1194 return {
1195 OpToCreate::create(builder, *currentOpLoc, locals[*id], poppedOp->front())
1196 ->getResults()};
1197}
1198
1199parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::localSet>,
1200 OpBuilder &builder,
1201 ExpressionParser::ExprParserProxy &exprParser) {
1202 return exprParser.parseSetOrTee<LocalSetOp>(builder);
1203}
1204
1205parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::localTee>,
1206 OpBuilder &builder,
1207 ExpressionParser::ExprParserProxy &exprParser) {
1208 return exprParser.parseSetOrTee<LocalTeeOp>(builder);
1209}
1210
1211template <typename T>
1212inline Type buildLiteralType(OpBuilder &);
1213
1214template <>
1215inline Type buildLiteralType<int32_t>(OpBuilder &builder) {
1216 return builder.getI32Type();
1217}
1218
1219template <>
1220inline Type buildLiteralType<int64_t>(OpBuilder &builder) {
1221 return builder.getI64Type();
1222}
1223
1224template <>
1225[[maybe_unused]] inline Type buildLiteralType<uint32_t>(OpBuilder &builder) {
1226 return builder.getI32Type();
1227}
1228
1229template <>
1230[[maybe_unused]] inline Type buildLiteralType<uint64_t>(OpBuilder &builder) {
1231 return builder.getI64Type();
1232}
1233
1234template <>
1235inline Type buildLiteralType<float>(OpBuilder &builder) {
1236 return builder.getF32Type();
1237}
1238
1239template <>
1240inline Type buildLiteralType<double>(OpBuilder &builder) {
1241 return builder.getF64Type();
1242}
1243
1244template <typename ValT,
1245 typename E = std::enable_if_t<std::is_arithmetic_v<ValT>>>
1246struct AttrHolder;
1247
1248template <typename ValT>
1249struct AttrHolder<ValT, std::enable_if_t<std::is_integral_v<ValT>>> {
1250 using type = IntegerAttr;
1251};
1252
1253template <typename ValT>
1254struct AttrHolder<ValT, std::enable_if_t<std::is_floating_point_v<ValT>>> {
1255 using type = FloatAttr;
1256};
1257
1258template <typename ValT>
1259using attr_holder_t = typename AttrHolder<ValT>::type;
1260
1261template <typename ValT,
1262 typename EnableT = std::enable_if_t<std::is_arithmetic_v<ValT>>>
1263attr_holder_t<ValT> buildLiteralAttr(OpBuilder &builder, ValT val) {
1264 return attr_holder_t<ValT>::get(buildLiteralType<ValT>(builder), val);
1265}
1266
1267template <typename valueT>
1268parsed_inst_t ExpressionParser::ExprParserProxy::parseConstInst(
1269 OpBuilder &builder, std::enable_if_t<std::is_arithmetic_v<valueT>> *) {
1270 auto parsedConstant = parser().parseLiteral<valueT>();
1271 if (failed(parsedConstant))
1272 return failure();
1273 auto constOp =
1274 ConstOp::create(builder, getCurrentOpLoc(),
1275 buildLiteralAttr<valueT>(builder, *parsedConstant));
1276 return {{constOp.getResult()}};
1277}
1278
1279parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::constI32>,
1280 OpBuilder &builder,
1281 ExpressionParser::ExprParserProxy &exprParser) {
1282 return exprParser.parseConstInst<int32_t>(builder);
1283}
1284
1285parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::constI64>,
1286 OpBuilder &builder,
1287 ExpressionParser::ExprParserProxy &exprParser) {
1288 return exprParser.parseConstInst<int64_t>(builder);
1289}
1290
1291parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::constFP32>,
1292 OpBuilder &builder,
1293 ExpressionParser::ExprParserProxy &exprParser) {
1294 return exprParser.parseConstInst<float>(builder);
1295}
1296
1297parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::constFP64>,
1298 OpBuilder &builder,
1299 ExpressionParser::ExprParserProxy &exprParser) {
1300 return exprParser.parseConstInst<double>(builder);
1301}
1302
1303template <typename opcode, typename valueType, unsigned int numOperands>
1304inline parsed_inst_t ExpressionParser::ExprParserProxy::buildNumericOp(
1305 OpBuilder &builder, std::enable_if_t<std::is_arithmetic_v<valueType>> *) {
1306 auto ty = buildLiteralType<valueType>(builder);
1307 LDBG() << "*** buildNumericOp: numOperands = " << numOperands
1308 << ", type = " << ty << " ***";
1309 auto tysToPop = SmallVector<Type, numOperands>();
1310 tysToPop.resize(numOperands);
1311 llvm::fill(tysToPop, ty);
1312 auto operands = popOperands(tysToPop);
1313 if (failed(operands))
1314 return failure();
1315 auto op = opcode::create(builder, getCurrentOpLoc(), *operands).getResult();
1316 LDBG() << "Built operation: " << op;
1317 return {{op}};
1318}
1319
1320// Convenience macro for generating numerical operations.
1321#define BUILD_NUMERIC_OP(OP_NAME, N_ARGS, PREFIX, SUFFIX, TYPE) \
1322 inline parsed_inst_t parse( \
1323 OpCode<WasmBinaryEncoding::OpCode::PREFIX##SUFFIX>, OpBuilder &builder, \
1324 ExpressionParser::ExprParserProxy &exprParser) { \
1325 return exprParser.buildNumericOp<OP_NAME, TYPE, N_ARGS>(builder); \
1326 }
1327
1328// Macro to define binops that only support integer types.
1329#define BUILD_NUMERIC_BINOP_INT(OP_NAME, PREFIX) \
1330 BUILD_NUMERIC_OP(OP_NAME, 2, PREFIX, I32, int32_t) \
1331 BUILD_NUMERIC_OP(OP_NAME, 2, PREFIX, I64, int64_t)
1332
1333// Macro to define binops that only support floating point types.
1334#define BUILD_NUMERIC_BINOP_FP(OP_NAME, PREFIX) \
1335 BUILD_NUMERIC_OP(OP_NAME, 2, PREFIX, F32, float) \
1336 BUILD_NUMERIC_OP(OP_NAME, 2, PREFIX, F64, double)
1337
1338// Macro to define binops that support both floating point and integer types.
1339#define BUILD_NUMERIC_BINOP_INTFP(OP_NAME, PREFIX) \
1340 BUILD_NUMERIC_BINOP_INT(OP_NAME, PREFIX) \
1341 BUILD_NUMERIC_BINOP_FP(OP_NAME, PREFIX)
1342
1343// Macro to implement unary ops that only support integers.
1344#define BUILD_NUMERIC_UNARY_OP_INT(OP_NAME, PREFIX) \
1345 BUILD_NUMERIC_OP(OP_NAME, 1, PREFIX, I32, int32_t) \
1346 BUILD_NUMERIC_OP(OP_NAME, 1, PREFIX, I64, int64_t)
1347
1348// Macro to implement unary ops that support integer and floating point types.
1349#define BUILD_NUMERIC_UNARY_OP_FP(OP_NAME, PREFIX) \
1350 BUILD_NUMERIC_OP(OP_NAME, 1, PREFIX, F32, float) \
1351 BUILD_NUMERIC_OP(OP_NAME, 1, PREFIX, F64, double)
1352
1353BUILD_NUMERIC_BINOP_FP(CopySignOp, copysign)
1355BUILD_NUMERIC_BINOP_FP(GeOp, ge)
1356BUILD_NUMERIC_BINOP_FP(GtOp, gt)
1357BUILD_NUMERIC_BINOP_FP(LeOp, le)
1358BUILD_NUMERIC_BINOP_FP(LtOp, lt)
1361BUILD_NUMERIC_BINOP_INT(AndOp, and)
1362BUILD_NUMERIC_BINOP_INT(DivSIOp, divS)
1363BUILD_NUMERIC_BINOP_INT(DivUIOp, divU)
1364BUILD_NUMERIC_BINOP_INT(GeSIOp, geS)
1365BUILD_NUMERIC_BINOP_INT(GeUIOp, geU)
1366BUILD_NUMERIC_BINOP_INT(GtSIOp, gtS)
1367BUILD_NUMERIC_BINOP_INT(GtUIOp, gtU)
1368BUILD_NUMERIC_BINOP_INT(LeSIOp, leS)
1369BUILD_NUMERIC_BINOP_INT(LeUIOp, leU)
1370BUILD_NUMERIC_BINOP_INT(LtSIOp, ltS)
1371BUILD_NUMERIC_BINOP_INT(LtUIOp, ltU)
1373BUILD_NUMERIC_BINOP_INT(RemSIOp, remS)
1374BUILD_NUMERIC_BINOP_INT(RemUIOp, remU)
1375BUILD_NUMERIC_BINOP_INT(RotlOp, rotl)
1376BUILD_NUMERIC_BINOP_INT(RotrOp, rotr)
1377BUILD_NUMERIC_BINOP_INT(ShLOp, shl)
1378BUILD_NUMERIC_BINOP_INT(ShRSOp, shrS)
1379BUILD_NUMERIC_BINOP_INT(ShRUOp, shrU)
1380BUILD_NUMERIC_BINOP_INT(XOrOp, xor)
1385BUILD_NUMERIC_BINOP_INTFP(SubOp, sub)
1386BUILD_NUMERIC_UNARY_OP_FP(AbsOp, abs)
1387BUILD_NUMERIC_UNARY_OP_FP(CeilOp, ceil)
1388BUILD_NUMERIC_UNARY_OP_FP(FloorOp, floor)
1389BUILD_NUMERIC_UNARY_OP_FP(NearestOp, nearest)
1390BUILD_NUMERIC_UNARY_OP_FP(NegOp, neg)
1391BUILD_NUMERIC_UNARY_OP_FP(SqrtOp, sqrt)
1392BUILD_NUMERIC_UNARY_OP_FP(TruncOp, trunc)
1396BUILD_NUMERIC_UNARY_OP_INT(PopCntOp, popcnt)
1397
1398// Don't need these anymore so let's undef them.
1399#undef BUILD_NUMERIC_BINOP_FP
1400#undef BUILD_NUMERIC_BINOP_INT
1401#undef BUILD_NUMERIC_BINOP_INTFP
1402#undef BUILD_NUMERIC_UNARY_OP_FP
1403#undef BUILD_NUMERIC_UNARY_OP_INT
1404#undef BUILD_NUMERIC_OP
1405#undef BUILD_NUMERIC_CAST_OP
1406
1407template <typename opType, typename inputType, typename outputType,
1408 typename... extraArgsT>
1409inline parsed_inst_t
1410ExpressionParser::ExprParserProxy::buildConvertOp(OpBuilder &builder,
1411 extraArgsT... extraArgs) {
1412 static_assert(std::is_arithmetic_v<inputType>,
1413 "InputType should be an arithmetic type");
1414 static_assert(std::is_arithmetic_v<outputType>,
1415 "OutputType should be an arithmetic type");
1416 auto intype = buildLiteralType<inputType>(builder);
1417 auto outType = buildLiteralType<outputType>(builder);
1418 auto operand = popOperands(intype);
1419 if (failed(operand))
1420 return failure();
1421 auto op = opType::create(builder, getCurrentOpLoc(), outType,
1422 operand->front(), extraArgs...);
1423 LDBG() << "Built operation: " << op;
1424 return {{op.getResult()}};
1425}
1426
1427parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::demoteF64ToF32>,
1428 OpBuilder &builder,
1429 ExpressionParser::ExprParserProxy &exprParser) {
1430 return exprParser.buildConvertOp<DemoteOp, double, float>(builder);
1431}
1432
1433parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::wrap>,
1434 OpBuilder &builder,
1435 ExpressionParser::ExprParserProxy &exprParser) {
1436 return exprParser.buildConvertOp<WrapOp, int64_t, int32_t>(builder);
1437}
1438
1439#define BUILD_CONVERSION_OP(IN_T, OUT_T, SOURCE_OP, TARGET_OP) \
1440 inline parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::SOURCE_OP>, \
1441 OpBuilder &builder, \
1442 ExpressionParser::ExprParserProxy &exprParser) { \
1443 return exprParser.buildConvertOp<TARGET_OP, IN_T, OUT_T>(builder); \
1444 }
1445
1446#define BUILD_CONVERT_OP_FOR(DEST_T, WIDTH) \
1447 BUILD_CONVERSION_OP(uint32_t, DEST_T, convertUI32F##WIDTH, ConvertUOp) \
1448 BUILD_CONVERSION_OP(int32_t, DEST_T, convertSI32F##WIDTH, ConvertSOp) \
1449 BUILD_CONVERSION_OP(uint64_t, DEST_T, convertUI64F##WIDTH, ConvertUOp) \
1450 BUILD_CONVERSION_OP(int64_t, DEST_T, convertSI64F##WIDTH, ConvertSOp)
1451
1452BUILD_CONVERT_OP_FOR(float, 32)
1453BUILD_CONVERT_OP_FOR(double, 64)
1454
1455#undef BUILD_CONVERT_OP_FOR
1456
1457#define BUILD_TRUNC_OP_FOR(SRC_T, WIDTH) \
1458 BUILD_CONVERSION_OP(SRC_T, int32_t, truncSI32F##WIDTH, TruncSIOp) \
1459 BUILD_CONVERSION_OP(SRC_T, uint32_t, truncUI32F##WIDTH, TruncUIOp) \
1460 BUILD_CONVERSION_OP(SRC_T, int64_t, truncSI64F##WIDTH, TruncSIOp) \
1461 BUILD_CONVERSION_OP(SRC_T, uint64_t, truncUI64F##WIDTH, TruncUIOp)
1462
1463BUILD_TRUNC_OP_FOR(float, 32)
1464BUILD_TRUNC_OP_FOR(double, 64)
1465
1466#undef BUILD_TRUNC_OP_FOR
1467
1468BUILD_CONVERSION_OP(int32_t, int64_t, extendS, ExtendSI32Op)
1469BUILD_CONVERSION_OP(int32_t, int64_t, extendU, ExtendUI32Op)
1470
1471#undef BUILD_CONVERSION_OP
1472
1473parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::saturatedTruncate>,
1474 OpBuilder &builder,
1475 ExpressionParser::ExprParserProxy &parser,
1476 std::uint32_t subOpCode) {
1477 if (subOpCode > 7)
1478 return emitError(parser.getCurrentOpLoc())
1479 << "invalid sub-opcode for trunc_saturate: " << subOpCode;
1480 LDBG() << "Sub subOpcode for operation: " << subOpCode;
1481 bool isDestUnsigned = (subOpCode & 1) != 0;
1482 bool isSrcF64 = (subOpCode & 2) != 0;
1483 bool isDestI64 = (subOpCode & 4) != 0;
1484
1485 Type srcType = isSrcF64 ? builder.getF64Type() : builder.getF32Type();
1486 Type destType = isDestI64 ? builder.getI64Type() : builder.getI32Type();
1487 auto srcOp = parser.popOperands(srcType);
1488 if (failed(srcOp))
1489 return failure();
1490 Operation *op = isDestUnsigned
1491 ? TruncSatUIOp::create(builder, parser.getCurrentOpLoc(),
1492 destType, srcOp->front())
1493 : TruncSatSIOp::create(builder, parser.getCurrentOpLoc(),
1494 destType, srcOp->front());
1495 LDBG() << "Built operation: " << op;
1496 return {{op->getResult(0)}};
1497}
1498
1499#define BUILD_SLICE_EXTEND_PARSER(IT_WIDTH, EXTRACT_WIDTH) \
1500 parsed_inst_t parse( \
1501 OpCode<WasmBinaryEncoding::OpCode::extendI##IT_WIDTH##EXTRACT_WIDTH##S>, \
1502 OpBuilder &builder, ExpressionParser::ExprParserProxy &exprParser) { \
1503 using inout_t = int##IT_WIDTH##_t; \
1504 auto attr = builder.getUI32IntegerAttr(EXTRACT_WIDTH); \
1505 return exprParser.buildConvertOp<ExtendLowBitsSOp, inout_t, inout_t>( \
1506 builder, attr); \
1507 }
1508
1514
1515#undef BUILD_SLICE_EXTEND_PARSER
1516
1517parsed_inst_t parse(OpCode<WasmBinaryEncoding::OpCode::promoteF32ToF64>,
1518 OpBuilder &builder,
1519 ExpressionParser::ExprParserProxy &exprParser) {
1520 return exprParser.buildConvertOp<PromoteOp, float, double>(builder);
1521}
1522
1523#define BUILD_REINTERPRET_PARSER(WIDTH, FP_TYPE) \
1524 inline parsed_inst_t parse( \
1525 OpCode<WasmBinaryEncoding::OpCode::reinterpretF##WIDTH##AsI##WIDTH>, \
1526 OpBuilder &builder, ExpressionParser::ExprParserProxy &exprParser) { \
1527 return exprParser.buildConvertOp<ReinterpretOp, FP_TYPE, int##WIDTH##_t>( \
1528 builder); \
1529 } \
1530 \
1531 inline parsed_inst_t parse( \
1532 OpCode<WasmBinaryEncoding::OpCode::reinterpretI##WIDTH##AsF##WIDTH>, \
1533 OpBuilder &builder, ExpressionParser::ExprParserProxy &exprParser) { \
1534 return exprParser.buildConvertOp<ReinterpretOp, int##WIDTH##_t, FP_TYPE>( \
1535 builder); \
1536 }
1537
1538BUILD_REINTERPRET_PARSER(32, float)
1539BUILD_REINTERPRET_PARSER(64, double)
1540
1541#undef BUILD_REINTERPRET_PARSER
1542
1543class InstDispatcher {
1544private:
1545 template <std::byte OpCode, typename = void>
1546 struct HasParserRegistered : std::false_type {};
1547
1548 template <std::byte opCode>
1549 struct HasParserRegistered<
1550 opCode, std::void_t<decltype(parse(
1551 std::declval<OpCode<opCode>>(), std::declval<OpBuilder &>(),
1552 std::declval<ExpressionParser::ExprParserProxy &>()))>>
1553 : std::true_type {};
1554
1555 template <std::byte opCode>
1556 static constexpr bool hasParseredRegistered =
1557 HasParserRegistered<opCode>::value;
1558
1559 template <std::byte OpCode, typename = void>
1560 struct HasParserWthSubOpCodeRegistered : std::false_type {};
1561
1562 template <std::byte opCode>
1563 struct HasParserWthSubOpCodeRegistered<
1564 opCode, std::void_t<decltype(parse(
1565 std::declval<OpCode<opCode>>(), std::declval<OpBuilder &>(),
1566 std::declval<ExpressionParser::ExprParserProxy &>(),
1567 std::declval<std::uint32_t>()))>> : std::true_type {
1568 static_assert(!hasParseredRegistered<opCode>,
1569 "plain parser and parser with sub-opcode can't be registered "
1570 "for the same opcode");
1571 };
1572
1573 template <std::byte opCode>
1574 static constexpr bool hasParseredWithSubOpCodeRegistered =
1575 HasParserWthSubOpCodeRegistered<opCode>::value;
1576
1577 using dispatch_t = parsed_inst_t (*)(OpBuilder &,
1578 ExpressionParser::ExprParserProxy &);
1579
1580 static inline parsed_inst_t
1581 unreachableHandler(OpBuilder &,
1582 ExpressionParser::ExprParserProxy &expressionParser) {
1583 llvm_unreachable("Failure in opcode parser dispatch logic.");
1584 return mlir::failure();
1585 }
1586
1587 template <std::byte opCode>
1588 static parsed_inst_t
1589 forwardToParser(OpBuilder &builder,
1590 ExpressionParser::ExprParserProxy &exprParser) {
1591 return parse(OpCode<opCode>{}, builder, exprParser);
1592 }
1593
1594 template <std::byte opCode>
1595 static parsed_inst_t
1596 forwardToParserWithSubOpCode(OpBuilder &builder,
1597 ExpressionParser::ExprParserProxy &exprParser) {
1598 auto loc = exprParser.getCurrentOpLoc();
1599 auto subOpCode = exprParser.parser().parseLiteral<std::uint32_t>();
1600 if (failed(subOpCode))
1601 return emitError(loc) << "expecting sub opcode for opcode "
1602 << static_cast<uint8_t>(opCode);
1603 return parse(OpCode<opCode>{}, builder, exprParser, subOpCode.value());
1604 }
1605
1606 template <std::byte opCode>
1607 static constexpr dispatch_t getHandlerForOpCode() {
1608 if constexpr (hasParseredRegistered<opCode>)
1609 return forwardToParser<opCode>;
1610 else if constexpr (hasParseredWithSubOpCodeRegistered<opCode>)
1611 return forwardToParserWithSubOpCode<opCode>;
1612 else
1613 return unreachableHandler;
1614 }
1615
1616private:
1617 static inline parsed_inst_t
1618 invalidOpcodeDiag(OpBuilder &,
1619 ExpressionParser::ExprParserProxy &expressionParser,
1620 std::byte opCode) {
1621 return emitError(expressionParser.getCurrentOpLoc(),
1622 "unknown instruction opcode: ")
1623 << static_cast<int>(opCode);
1624 }
1625
1626 template <std::byte... opCodes>
1627 static inline parsed_inst_t
1628 dispatchImpl(std::byte opCode, OpBuilder &builder,
1629 ExpressionParser::ExprParserProxy &exprParser,
1630 ByteSequence<opCodes...>) {
1631 static constexpr std::array<bool, 256> opcodeValidityMap{
1632 (hasParseredRegistered<opCodes> ||
1633 hasParseredWithSubOpCodeRegistered<opCodes>)...};
1634 static constexpr std::array<dispatch_t, 256> dispatchTable{
1635 getHandlerForOpCode<opCodes>()...};
1636 if (opcodeValidityMap[static_cast<size_t>(opCode)]) {
1637 return dispatchTable[static_cast<size_t>(opCode)](builder, exprParser);
1638 }
1639 return invalidOpcodeDiag(builder, exprParser, opCode);
1640 }
1641
1642public:
1643 ///
1644 /// @brief dispatch control flow to the sub parser registered for opCode in
1645 /// `ParserRegistry`
1646 ///
1647 /// @param opCode opCode of the instruction to be Parsed
1648 /// @param builder builder that will be passed to the parser
1649 /// @param exprParser the generic parser passed to the sub parser
1650 ///
1651 /// @return the result of the parser or an error if there is no parser
1652 /// registered for the opcode (emits a diagnostic)
1653 static parsed_inst_t dispatch(std::byte opCode, OpBuilder &builder,
1654 ExpressionParser::ExprParserProxy &exprParser) {
1655 return dispatchImpl(opCode, builder, exprParser, all8bitsBytes);
1656 }
1657};
1658
1659inline parsed_inst_t
1660ExpressionParser::dispatchToInstParser(std::byte opCode, OpBuilder &builder) {
1661 ExpressionParser::ExprParserProxy exprParser{*this};
1662 return InstDispatcher::dispatch(opCode, builder, exprParser);
1663}
1664class WasmBinaryParser {
1665private:
1666 struct SectionRegistry {
1667 using section_location_t = StringRef;
1668
1669 std::array<SmallVector<section_location_t>, highestWasmSectionID + 1>
1670 registry;
1671
1672 template <WasmSectionType SecType>
1673 std::conditional_t<sectionShouldBeUnique(SecType),
1674 std::optional<section_location_t>,
1675 ArrayRef<section_location_t>>
1676 getContentForSection() const {
1677 constexpr auto idx = static_cast<size_t>(SecType);
1678 if constexpr (sectionShouldBeUnique(SecType)) {
1679 return registry[idx].empty() ? std::nullopt
1680 : std::make_optional(registry[idx][0]);
1681 } else {
1682 return registry[idx];
1683 }
1684 }
1685
1686 bool hasSection(WasmSectionType secType) const {
1687 return !registry[static_cast<size_t>(secType)].empty();
1688 }
1689
1690 ///
1691 /// @returns success if registration valid, failure in case registration
1692 /// can't be done (if another section of same type already exist and this
1693 /// section type should only be present once)
1694 ///
1695 LogicalResult registerSection(WasmSectionType secType,
1696 section_location_t location, Location loc) {
1697 if (sectionShouldBeUnique(secType) && hasSection(secType))
1698 return emitError(loc,
1699 "trying to add a second instance of unique section");
1700
1701 registry[static_cast<size_t>(secType)].push_back(location);
1702 emitRemark(loc, "Adding section with section ID ")
1703 << static_cast<uint8_t>(secType);
1704 return success();
1705 }
1706
1707 LogicalResult populateFromBody(ParserHead ph) {
1708 while (!ph.end()) {
1709 FileLineColLoc sectionLoc = ph.getLocation();
1710 FailureOr<WasmSectionType> secType = ph.parseWasmSectionType();
1711 if (failed(secType))
1712 return failure();
1713
1714 FailureOr<uint32_t> secSizeParsed = ph.parseLiteral<uint32_t>();
1715 if (failed(secSizeParsed))
1716 return failure();
1717
1718 uint32_t secSize = *secSizeParsed;
1719 FailureOr<StringRef> sectionContent = ph.consumeNBytes(secSize);
1720 if (failed(sectionContent))
1721 return failure();
1722
1723 LogicalResult registration =
1724 registerSection(*secType, *sectionContent, sectionLoc);
1725
1726 if (failed(registration))
1727 return failure();
1728 }
1729 return success();
1730 }
1731 };
1732
1733 auto getLocation(int offset = 0) const {
1734 return FileLineColLoc::get(srcName, 0, offset);
1735 }
1736
1737 template <WasmSectionType>
1738 LogicalResult parseSectionItem(ParserHead &, size_t);
1739
1740 template <WasmSectionType section>
1741 LogicalResult parseSection() {
1742 auto secName = std::string{wasmSectionName<section>};
1743 auto sectionNameAttr =
1744 StringAttr::get(ctx, srcName.strref() + ":" + secName + "-SECTION");
1745 unsigned offset = 0;
1746 auto getLocation = [sectionNameAttr, &offset]() {
1747 return FileLineColLoc::get(sectionNameAttr, 0, offset);
1748 };
1749 auto secContent = registry.getContentForSection<section>();
1750 if (!secContent) {
1751 LDBG() << secName << " section is not present in file.";
1752 return success();
1753 }
1754
1755 auto secSrc = secContent.value();
1756 ParserHead ph{secSrc, sectionNameAttr};
1757 FailureOr<uint32_t> nElemsParsed = ph.parseVectorSize();
1758 if (failed(nElemsParsed))
1759 return failure();
1760 uint32_t nElems = *nElemsParsed;
1761 LDBG() << "starting to parse " << nElems << " items for section "
1762 << secName;
1763 for (size_t i = 0; i < nElems; ++i) {
1764 if (failed(parseSectionItem<section>(ph, i)))
1765 return failure();
1766 }
1767
1768 if (!ph.end())
1769 return emitError(getLocation(), "unparsed garbage at end of section ")
1770 << secName;
1771 return success();
1772 }
1773
1774 /// Handles the registration of a function import
1775 LogicalResult visitImport(Location loc, StringRef moduleName,
1776 StringRef importName, TypeIdxRecord tid) {
1777 using llvm::Twine;
1778 if (tid.id >= symbols.moduleFuncTypes.size())
1779 return emitError(loc, "invalid type id: ")
1780 << tid.id << ". Only " << symbols.moduleFuncTypes.size()
1781 << " type registrations";
1782 FunctionType type = symbols.moduleFuncTypes[tid.id];
1783 std::string symbol = symbols.getNewFuncSymbolName();
1784 auto funcOp = FuncImportOp::create(builder, loc, symbol, moduleName,
1785 importName, type);
1786 symbols.funcSymbols.push_back({{FlatSymbolRefAttr::get(funcOp)}, type});
1787 return funcOp.verify();
1788 }
1789
1790 /// Handles the registration of a memory import
1791 LogicalResult visitImport(Location loc, StringRef moduleName,
1792 StringRef importName, LimitType limitType) {
1793 std::string symbol = symbols.getNewMemorySymbolName();
1794 auto memOp = MemImportOp::create(builder, loc, symbol, moduleName,
1795 importName, limitType);
1796 symbols.memSymbols.push_back({FlatSymbolRefAttr::get(memOp)});
1797 return memOp.verify();
1798 }
1799
1800 /// Handles the registration of a table import
1801 LogicalResult visitImport(Location loc, StringRef moduleName,
1802 StringRef importName, TableType tableType) {
1803 std::string symbol = symbols.getNewTableSymbolName();
1804 auto tableOp = TableImportOp::create(builder, loc, symbol, moduleName,
1805 importName, tableType);
1806 symbols.tableSymbols.push_back({FlatSymbolRefAttr::get(tableOp)});
1807 return tableOp.verify();
1808 }
1809
1810 /// Handles the registration of a global variable import
1811 LogicalResult visitImport(Location loc, StringRef moduleName,
1812 StringRef importName, GlobalTypeRecord globalType) {
1813 std::string symbol = symbols.getNewGlobalSymbolName();
1814 auto giOp =
1815 GlobalImportOp::create(builder, loc, symbol, moduleName, importName,
1816 globalType.type, globalType.isMutable);
1817 symbols.globalSymbols.push_back(
1818 {{FlatSymbolRefAttr::get(giOp)}, giOp.getType()});
1819 return giOp.verify();
1820 }
1821
1822 // Detect occurence of errors
1823 LogicalResult peekDiag(Diagnostic &diag) {
1824 if (diag.getSeverity() == DiagnosticSeverity::Error)
1825 isValid = false;
1826 return failure();
1827 }
1828
1829public:
1830 WasmBinaryParser(llvm::SourceMgr &sourceMgr, MLIRContext *ctx)
1831 : builder{ctx}, ctx{ctx} {
1833 [this](Diagnostic &diag) { return peekDiag(diag); });
1835 if (sourceMgr.getNumBuffers() != 1) {
1836 emitError(UnknownLoc::get(ctx), "one source file should be provided");
1837 return;
1838 }
1839 uint32_t sourceBufId = sourceMgr.getMainFileID();
1840 StringRef source = sourceMgr.getMemoryBuffer(sourceBufId)->getBuffer();
1841 srcName = StringAttr::get(
1842 ctx, sourceMgr.getMemoryBuffer(sourceBufId)->getBufferIdentifier());
1843
1844 auto parser = ParserHead{source, srcName};
1845 auto const wasmHeader = StringRef{"\0asm", 4};
1846 FileLineColLoc magicLoc = parser.getLocation();
1847 FailureOr<StringRef> magic = parser.consumeNBytes(wasmHeader.size());
1848 if (failed(magic) || magic->compare(wasmHeader)) {
1849 emitError(magicLoc, "source file does not contain valid Wasm header");
1850 return;
1851 }
1852 auto const expectedVersionString = StringRef{"\1\0\0\0", 4};
1853 FileLineColLoc versionLoc = parser.getLocation();
1854 FailureOr<StringRef> version =
1855 parser.consumeNBytes(expectedVersionString.size());
1856 if (failed(version))
1857 return;
1858 if (version->compare(expectedVersionString)) {
1859 emitError(versionLoc,
1860 "unsupported Wasm version. only version 1 is supported");
1861 return;
1862 }
1863 LogicalResult fillRegistry = registry.populateFromBody(parser.copy());
1864 if (failed(fillRegistry))
1865 return;
1866
1867 mOp = ModuleOp::create(builder, getLocation());
1868 builder.setInsertionPointToStart(&mOp.getBodyRegion().front());
1869 LogicalResult parsingTypes = parseSection<WasmSectionType::TYPE>();
1870 if (failed(parsingTypes))
1871 return;
1872
1873 LogicalResult parsingImports = parseSection<WasmSectionType::IMPORT>();
1874 if (failed(parsingImports))
1875 return;
1876
1877 firstInternalFuncID = symbols.funcSymbols.size();
1878
1879 LogicalResult parsingFunctions = parseSection<WasmSectionType::FUNCTION>();
1880 if (failed(parsingFunctions))
1881 return;
1882
1883 LogicalResult parsingTables = parseSection<WasmSectionType::TABLE>();
1884 if (failed(parsingTables))
1885 return;
1886
1887 LogicalResult parsingMems = parseSection<WasmSectionType::MEMORY>();
1888 if (failed(parsingMems))
1889 return;
1890
1891 LogicalResult parsingGlobals = parseSection<WasmSectionType::GLOBAL>();
1892 if (failed(parsingGlobals))
1893 return;
1894
1895 LogicalResult parsingCode = parseSection<WasmSectionType::CODE>();
1896 if (failed(parsingCode))
1897 return;
1898
1899 LogicalResult parsingExports = parseSection<WasmSectionType::EXPORT>();
1900 if (failed(parsingExports))
1901 return;
1902
1903 // Copy over sizes of containers into statistics.
1904 LDBG() << "WASM Imports:"
1905 << "\n"
1906 << " - Num functions: " << symbols.funcSymbols.size() << "\n"
1907 << " - Num globals: " << symbols.globalSymbols.size() << "\n"
1908 << " - Num memories: " << symbols.memSymbols.size() << "\n"
1909 << " - Num tables: " << symbols.tableSymbols.size();
1910 }
1911
1912 ModuleOp getModule() {
1913 if (isValid)
1914 return mOp;
1915 if (mOp)
1916 mOp.erase();
1917 return ModuleOp{};
1918 }
1919
1920private:
1921 mlir::StringAttr srcName;
1922 OpBuilder builder;
1923 WasmModuleSymbolTables symbols;
1924 MLIRContext *ctx;
1925 ModuleOp mOp;
1926 SectionRegistry registry;
1927 size_t firstInternalFuncID{0};
1928 bool isValid{true};
1929};
1930
1931template <>
1932LogicalResult
1933WasmBinaryParser::parseSectionItem<WasmSectionType::IMPORT>(ParserHead &ph,
1934 size_t) {
1935 FileLineColLoc importLoc = ph.getLocation();
1936 auto moduleName = ph.parseName();
1937 if (failed(moduleName))
1938 return failure();
1939
1940 auto importName = ph.parseName();
1941 if (failed(importName))
1942 return failure();
1943
1944 FailureOr<ImportDesc> import = ph.parseImportDesc(ctx);
1945 if (failed(import))
1946 return failure();
1947
1948 return std::visit(
1949 [this, importLoc, &moduleName, &importName](auto import) {
1950 return visitImport(importLoc, *moduleName, *importName, import);
1951 },
1952 *import);
1953}
1954
1955template <>
1956LogicalResult
1957WasmBinaryParser::parseSectionItem<WasmSectionType::EXPORT>(ParserHead &ph,
1958 size_t) {
1959 FileLineColLoc exportLoc = ph.getLocation();
1960
1961 auto exportName = ph.parseName();
1962 if (failed(exportName))
1963 return failure();
1964
1965 FailureOr<std::byte> opcode = ph.consumeByte();
1966 if (failed(opcode))
1967 return failure();
1968
1969 FailureOr<uint32_t> idx = ph.parseLiteral<uint32_t>();
1970 if (failed(idx))
1971 return failure();
1972
1973 using SymbolRefDesc = std::variant<SmallVector<SymbolRefContainer>,
1974 SmallVector<GlobalSymbolRefContainer>,
1975 SmallVector<FunctionSymbolRefContainer>>;
1976
1977 SymbolRefDesc currentSymbolList;
1978 std::string symbolType = "";
1979 switch (*opcode) {
1981 symbolType = "function";
1982 currentSymbolList = symbols.funcSymbols;
1983 break;
1985 symbolType = "table";
1986 currentSymbolList = symbols.tableSymbols;
1987 break;
1989 symbolType = "memory";
1990 currentSymbolList = symbols.memSymbols;
1991 break;
1993 symbolType = "global";
1994 currentSymbolList = symbols.globalSymbols;
1995 break;
1996 default:
1997 return emitError(exportLoc, "invalid value for export type: ")
1998 << std::to_integer<unsigned>(*opcode);
1999 }
2000
2001 auto currentSymbol = std::visit(
2002 [&](const auto &list) -> FailureOr<FlatSymbolRefAttr> {
2003 if (*idx > list.size()) {
2004 emitError(
2005 exportLoc,
2006 llvm::formatv(
2007 "trying to export {0} {1} which is undefined in this scope",
2008 symbolType, *idx));
2009 return failure();
2010 }
2011 return list[*idx].symbol;
2012 },
2013 currentSymbolList);
2014
2015 if (failed(currentSymbol))
2016 return failure();
2017
2018 Operation *op = SymbolTable::lookupSymbolIn(mOp, *currentSymbol);
2019 op->setAttr("exported", UnitAttr::get(op->getContext()));
2020 StringAttr symName = SymbolTable::getSymbolName(op);
2021 return SymbolTable{mOp}.rename(symName, *exportName);
2022}
2023
2024template <>
2025LogicalResult
2026WasmBinaryParser::parseSectionItem<WasmSectionType::TABLE>(ParserHead &ph,
2027 size_t) {
2028 FileLineColLoc opLocation = ph.getLocation();
2029 FailureOr<TableType> tableType = ph.parseTableType(ctx);
2030 if (failed(tableType))
2031 return failure();
2032 LDBG() << " Parsed table description: " << *tableType;
2033 StringAttr symbol = builder.getStringAttr(symbols.getNewTableSymbolName());
2034 auto tableOp =
2035 TableOp::create(builder, opLocation, symbol.strref(), *tableType);
2036 symbols.tableSymbols.push_back({SymbolRefAttr::get(tableOp)});
2037 return success();
2038}
2039
2040template <>
2041LogicalResult
2042WasmBinaryParser::parseSectionItem<WasmSectionType::FUNCTION>(ParserHead &ph,
2043 size_t) {
2044 FileLineColLoc opLoc = ph.getLocation();
2045 auto typeIdxParsed = ph.parseLiteral<uint32_t>();
2046 if (failed(typeIdxParsed))
2047 return failure();
2048 uint32_t typeIdx = *typeIdxParsed;
2049 if (typeIdx >= symbols.moduleFuncTypes.size())
2050 return emitError(getLocation(), "invalid type index: ") << typeIdx;
2051 std::string symbol = symbols.getNewFuncSymbolName();
2052 auto funcOp =
2053 FuncOp::create(builder, opLoc, symbol, symbols.moduleFuncTypes[typeIdx]);
2054 Block *block = funcOp.addEntryBlock();
2055 OpBuilder::InsertionGuard guard{builder};
2056 builder.setInsertionPointToEnd(block);
2057 ReturnOp::create(builder, opLoc);
2058 symbols.funcSymbols.push_back(
2059 {{FlatSymbolRefAttr::get(funcOp.getSymNameAttr())},
2060 symbols.moduleFuncTypes[typeIdx]});
2061 return funcOp.verify();
2062}
2063
2064template <>
2065LogicalResult
2066WasmBinaryParser::parseSectionItem<WasmSectionType::TYPE>(ParserHead &ph,
2067 size_t) {
2068 FailureOr<FunctionType> funcType = ph.parseFunctionType(ctx);
2069 if (failed(funcType))
2070 return failure();
2071 LDBG() << "Parsed function type " << *funcType;
2072 symbols.moduleFuncTypes.push_back(*funcType);
2073 return success();
2074}
2075
2076template <>
2077LogicalResult
2078WasmBinaryParser::parseSectionItem<WasmSectionType::MEMORY>(ParserHead &ph,
2079 size_t) {
2080 FileLineColLoc opLocation = ph.getLocation();
2081 FailureOr<LimitType> memory = ph.parseLimit(ctx);
2082 if (failed(memory))
2083 return failure();
2084
2085 LDBG() << " Registering memory " << *memory;
2086 std::string symbol = symbols.getNewMemorySymbolName();
2087 auto memOp = MemOp::create(builder, opLocation, symbol, *memory);
2088 symbols.memSymbols.push_back({SymbolRefAttr::get(memOp)});
2089 return success();
2090}
2091
2092template <>
2093LogicalResult
2094WasmBinaryParser::parseSectionItem<WasmSectionType::GLOBAL>(ParserHead &ph,
2095 size_t) {
2096 FileLineColLoc globalLocation = ph.getLocation();
2097 auto globalTypeParsed = ph.parseGlobalType(ctx);
2098 if (failed(globalTypeParsed))
2099 return failure();
2100
2101 GlobalTypeRecord globalType = *globalTypeParsed;
2102 auto symbol = builder.getStringAttr(symbols.getNewGlobalSymbolName());
2103 auto globalOp = wasmssa::GlobalOp::create(
2104 builder, globalLocation, symbol, globalType.type, globalType.isMutable);
2105 symbols.globalSymbols.push_back(
2106 {{FlatSymbolRefAttr::get(globalOp)}, globalOp.getType()});
2107 OpBuilder::InsertionGuard guard{builder};
2108 Block *block = builder.createBlock(&globalOp.getInitializer());
2109 builder.setInsertionPointToStart(block);
2110 parsed_inst_t expr = ph.parseExpression(builder, symbols);
2111 if (failed(expr))
2112 return failure();
2113 if (block->empty())
2114 return emitError(globalLocation, "global with empty initializer");
2115 if (expr->size() != 1 && (*expr)[0].getType() != globalType.type)
2116 return emitError(
2117 globalLocation,
2118 "initializer result type does not match global declaration type");
2119 ReturnOp::create(builder, globalLocation, *expr);
2120 return success();
2121}
2122
2123template <>
2124LogicalResult WasmBinaryParser::parseSectionItem<WasmSectionType::CODE>(
2125 ParserHead &ph, size_t innerFunctionId) {
2126 unsigned long funcId = innerFunctionId + firstInternalFuncID;
2127 FunctionSymbolRefContainer symRef = symbols.funcSymbols[funcId];
2128 auto funcOp =
2129 dyn_cast<FuncOp>(SymbolTable::lookupSymbolIn(mOp, symRef.symbol));
2130 assert(funcOp);
2131 if (failed(ph.parseCodeFor(funcOp, symbols)))
2132 return failure();
2133 return success();
2134}
2135} // namespace
2136
2137namespace mlir::wasm {
2139 MLIRContext *context) {
2140 WasmBinaryParser wBN{source, context};
2141 ModuleOp mOp = wBN.getModule();
2142 if (mOp)
2143 return {mOp};
2144
2145 return {nullptr};
2146}
2147} // namespace mlir::wasm
return success()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
memberIdxs push_back(ArrayAttr::get(parser.getContext(), values))
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
#define EXPORT
#define BUILD_NUMERIC_BINOP_INTFP(OP_NAME, PREFIX)
#define BUILD_CONVERT_OP_FOR(DEST_T, WIDTH)
#define APPLY_WASM_SEC_TRANSFORM
#define BUILD_REINTERPRET_PARSER(WIDTH, FP_TYPE)
#define BUILD_TRUNC_OP_FOR(SRC_T, WIDTH)
#define BUILD_CONVERSION_OP(IN_T, OUT_T, SOURCE_OP, TARGET_OP)
#define BUILD_SLICE_EXTEND_PARSER(IT_WIDTH, EXTRACT_WIDTH)
#define BUILD_NUMERIC_UNARY_OP_INT(OP_NAME, PREFIX)
#define BUILD_NUMERIC_BINOP_INT(OP_NAME, PREFIX)
#define BUILD_NUMERIC_BINOP_FP(OP_NAME, PREFIX)
#define BUILD_NUMERIC_UNARY_OP_FP(OP_NAME, PREFIX)
#define mul(a, b)
#define add(a, b)
#define div(a, b)
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Definition Block.cpp:154
bool empty()
Definition Block.h:173
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
OpListType & getOperations()
Definition Block.h:162
Operation & back()
Definition Block.h:177
BlockArgListType getArguments()
Definition Block.h:112
FloatType getF32Type()
Definition Builders.cpp:51
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerType getI32Type()
Definition Builders.cpp:71
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
MLIRContext * getContext() const
Definition Builders.h:56
IntegerAttr getUI32IntegerAttr(uint32_t value)
Definition Builders.cpp:220
FloatType getF64Type()
Definition Builders.cpp:53
HandlerID registerHandler(HandlerTy handler)
Register a new handler for diagnostics to the engine.
DiagnosticSeverity getSeverity() const
Returns the severity of this diagnostic.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:161
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
DiagnosticEngine & getDiagEngine()
Returns the diagnostic engine for this context.
void loadAllAvailableDialects()
Load all dialects available in the registry in this context.
This class helps build Operations.
Definition Builders.h:210
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition Builders.h:388
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
Block * getBlock() const
Returns the current block of the builder.
Definition Builders.h:451
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition Builders.h:393
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:636
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
Definition OwningOpRef.h:29
iterator end()
Definition Region.h:56
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
static StringAttr getSymbolName(Operation *symbol)
Returns the name of the given symbol operation, aborting if no symbol is present.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
Type getType() const
Return the type of this value.
Definition Value.h:105
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition Query.cpp:21
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
OwningOpRef< ModuleOp > importWebAssemblyToModule(llvm::SourceMgr &source, MLIRContext *context)
If source contains a valid Wasm binary file, this function returns a a ModuleOp containing the repres...
bool isWasmValueType(::mlir::Type type)
bool isWasmRefType(::mlir::Type type)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
InFlightDiagnostic emitRemark(Location loc)
Utility method to emit a remark message using this location.
static constexpr std::byte memory
static constexpr std::byte table
static constexpr std::byte global
static constexpr std::byte function
static constexpr std::byte memType
static constexpr std::byte typeID
static constexpr std::byte tableType
static constexpr std::byte globalType
static constexpr std::byte elseOpCode
static constexpr std::byte externRef
static constexpr std::byte i32
static constexpr std::byte funcType
static constexpr std::byte i64
static constexpr std::byte emptyBlockType
static constexpr std::byte funcRef
static constexpr std::byte v128
static constexpr std::byte f64
static constexpr std::byte f32
static constexpr std::byte endByte