function-body-decoder-impl.h 85.7 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
#define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_

8 9 10 11
// Do only include this header for implementing new Interface of the
// WasmFullDecoder.

#include "src/bit-vector.h"
12
#include "src/wasm/decoder.h"
13 14 15
#include "src/wasm/function-body-decoder.h"
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-module.h"
16 17 18 19 20 21 22
#include "src/wasm/wasm-opcodes.h"

namespace v8 {
namespace internal {
namespace wasm {

struct WasmGlobal;
23
struct WasmException;
24

25 26 27 28 29
#define TRACE(...)                                    \
  do {                                                \
    if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
  } while (false)

30 31
#define TRACE_INST_FORMAT "  @%-8d #%-20s|"

32 33
// Return the evaluation of `condition` if validate==true, DCHECK that it's
// true and always return true otherwise.
34 35 36 37 38 39
#define VALIDATE(condition)       \
  (validate ? (condition) : [&] { \
    DCHECK(condition);            \
    return true;                  \
  }())

40
#define RET_ON_PROTOTYPE_OPCODE(flag)                                          \
41
  DCHECK(!this->module_ || this->module_->origin == kWasmOrigin);              \
42 43 44 45
  if (!FLAG_experimental_wasm_##flag) {                                        \
    this->error("Invalid opcode (enable with --experimental-wasm-" #flag ")"); \
  }

46
#define CHECK_PROTOTYPE_OPCODE(flag)                                           \
47
  DCHECK(!this->module_ || this->module_->origin == kWasmOrigin);              \
48 49 50 51 52 53 54 55 56
  if (!FLAG_experimental_wasm_##flag) {                                        \
    this->error("Invalid opcode (enable with --experimental-wasm-" #flag ")"); \
    break;                                                                     \
  }

#define OPCODE_ERROR(opcode, message)                                 \
  (this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \
                (message)))

57 58
#define ATOMIC_OP_LIST(V)                \
  V(I32AtomicLoad, Uint32)               \
59
  V(I64AtomicLoad, Uint64)               \
60 61
  V(I32AtomicLoad8U, Uint8)              \
  V(I32AtomicLoad16U, Uint16)            \
62 63 64
  V(I64AtomicLoad8U, Uint8)              \
  V(I64AtomicLoad16U, Uint16)            \
  V(I64AtomicLoad32U, Uint32)            \
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  V(I32AtomicAdd, Uint32)                \
  V(I32AtomicAdd8U, Uint8)               \
  V(I32AtomicAdd16U, Uint16)             \
  V(I64AtomicAdd, Uint64)                \
  V(I64AtomicAdd8U, Uint8)               \
  V(I64AtomicAdd16U, Uint16)             \
  V(I64AtomicAdd32U, Uint32)             \
  V(I32AtomicSub, Uint32)                \
  V(I64AtomicSub, Uint64)                \
  V(I32AtomicSub8U, Uint8)               \
  V(I32AtomicSub16U, Uint16)             \
  V(I64AtomicSub8U, Uint8)               \
  V(I64AtomicSub16U, Uint16)             \
  V(I64AtomicSub32U, Uint32)             \
  V(I32AtomicAnd, Uint32)                \
  V(I64AtomicAnd, Uint64)                \
  V(I32AtomicAnd8U, Uint8)               \
  V(I32AtomicAnd16U, Uint16)             \
  V(I64AtomicAnd8U, Uint8)               \
  V(I64AtomicAnd16U, Uint16)             \
  V(I64AtomicAnd32U, Uint32)             \
  V(I32AtomicOr, Uint32)                 \
  V(I64AtomicOr, Uint64)                 \
  V(I32AtomicOr8U, Uint8)                \
  V(I32AtomicOr16U, Uint16)              \
  V(I64AtomicOr8U, Uint8)                \
  V(I64AtomicOr16U, Uint16)              \
  V(I64AtomicOr32U, Uint32)              \
  V(I32AtomicXor, Uint32)                \
  V(I64AtomicXor, Uint64)                \
  V(I32AtomicXor8U, Uint8)               \
  V(I32AtomicXor16U, Uint16)             \
  V(I64AtomicXor8U, Uint8)               \
  V(I64AtomicXor16U, Uint16)             \
  V(I64AtomicXor32U, Uint32)             \
  V(I32AtomicExchange, Uint32)           \
  V(I64AtomicExchange, Uint64)           \
  V(I32AtomicExchange8U, Uint8)          \
  V(I32AtomicExchange16U, Uint16)        \
  V(I64AtomicExchange8U, Uint8)          \
  V(I64AtomicExchange16U, Uint16)        \
  V(I64AtomicExchange32U, Uint32)        \
  V(I32AtomicCompareExchange, Uint32)    \
  V(I64AtomicCompareExchange, Uint64)    \
  V(I32AtomicCompareExchange8U, Uint8)   \
  V(I32AtomicCompareExchange16U, Uint16) \
  V(I64AtomicCompareExchange8U, Uint8)   \
  V(I64AtomicCompareExchange16U, Uint16) \
  V(I64AtomicCompareExchange32U, Uint32)
114

115 116
#define ATOMIC_STORE_OP_LIST(V) \
  V(I32AtomicStore, Uint32)     \
117
  V(I64AtomicStore, Uint64)     \
118
  V(I32AtomicStore8U, Uint8)    \
119 120 121 122
  V(I32AtomicStore16U, Uint16)  \
  V(I64AtomicStore8U, Uint8)    \
  V(I64AtomicStore16U, Uint16)  \
  V(I64AtomicStore32U, Uint32)
123

124 125
template <typename T, typename Allocator>
Vector<T> vec2vec(std::vector<T, Allocator>& vec) {
126 127 128
  return Vector<T>(vec.data(), vec.size());
}

129
// Helpers for decoding different kinds of immediates which follow bytecodes.
130
template <Decoder::ValidateFlag validate>
131
struct LocalIndexImmediate {
132
  uint32_t index;
133
  ValueType type = kWasmStmt;
134 135
  unsigned length;

136
  inline LocalIndexImmediate(Decoder* decoder, const byte* pc) {
137
    index = decoder->read_u32v<validate>(pc + 1, &length, "local index");
138 139 140
  }
};

141
template <Decoder::ValidateFlag validate>
142
struct ExceptionIndexImmediate {
143 144 145 146
  uint32_t index;
  const WasmException* exception = nullptr;
  unsigned length;

147
  inline ExceptionIndexImmediate(Decoder* decoder, const byte* pc) {
148
    index = decoder->read_u32v<validate>(pc + 1, &length, "exception index");
149 150 151
  }
};

152
template <Decoder::ValidateFlag validate>
153
struct ImmI32Immediate {
154 155
  int32_t value;
  unsigned length;
156
  inline ImmI32Immediate(Decoder* decoder, const byte* pc) {
157
    value = decoder->read_i32v<validate>(pc + 1, &length, "immi32");
158 159 160
  }
};

161
template <Decoder::ValidateFlag validate>
162
struct ImmI64Immediate {
163 164
  int64_t value;
  unsigned length;
165
  inline ImmI64Immediate(Decoder* decoder, const byte* pc) {
166
    value = decoder->read_i64v<validate>(pc + 1, &length, "immi64");
167 168 169
  }
};

170
template <Decoder::ValidateFlag validate>
171
struct ImmF32Immediate {
172
  float value;
173
  unsigned length = 4;
174
  inline ImmF32Immediate(Decoder* decoder, const byte* pc) {
175
    // Avoid bit_cast because it might not preserve the signalling bit of a NaN.
176
    uint32_t tmp = decoder->read_u32<validate>(pc + 1, "immf32");
177 178 179 180
    memcpy(&value, &tmp, sizeof(value));
  }
};

181
template <Decoder::ValidateFlag validate>
182
struct ImmF64Immediate {
183
  double value;
184
  unsigned length = 8;
185
  inline ImmF64Immediate(Decoder* decoder, const byte* pc) {
186
    // Avoid bit_cast because it might not preserve the signalling bit of a NaN.
187
    uint64_t tmp = decoder->read_u64<validate>(pc + 1, "immf64");
188 189 190 191
    memcpy(&value, &tmp, sizeof(value));
  }
};

192
template <Decoder::ValidateFlag validate>
193
struct GlobalIndexImmediate {
194
  uint32_t index;
195 196
  ValueType type = kWasmStmt;
  const WasmGlobal* global = nullptr;
197 198
  unsigned length;

199
  inline GlobalIndexImmediate(Decoder* decoder, const byte* pc) {
200
    index = decoder->read_u32v<validate>(pc + 1, &length, "global index");
201 202 203
  }
};

204
template <Decoder::ValidateFlag validate>
205
struct BlockTypeImmediate {
206
  unsigned length = 1;
207 208 209
  ValueType type = kWasmStmt;
  uint32_t sig_index = 0;
  FunctionSig* sig = nullptr;
210

211
  inline BlockTypeImmediate(Decoder* decoder, const byte* pc) {
212
    uint8_t val = decoder->read_u8<validate>(pc + 1, "block type");
213
    if (!decode_local_type(val, &type)) {
214
      // Handle multi-value blocks.
215
      if (!VALIDATE(FLAG_experimental_wasm_mv)) {
216
        decoder->error(pc + 1, "invalid block type");
217
        return;
218
      }
219 220 221 222 223
      int32_t index =
          decoder->read_i32v<validate>(pc + 1, &length, "block arity");
      if (!VALIDATE(length > 0 && index >= 0)) {
        decoder->error(pc + 1, "invalid block type index");
        return;
224
      }
225
      sig_index = static_cast<uint32_t>(index);
226 227
    }
  }
228

229
  // Decode a byte representing a local type. Return {false} if the encoded
230
  // byte was invalid or the start of a type index.
231
  inline bool decode_local_type(uint8_t val, ValueType* result) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    switch (static_cast<ValueTypeCode>(val)) {
      case kLocalVoid:
        *result = kWasmStmt;
        return true;
      case kLocalI32:
        *result = kWasmI32;
        return true;
      case kLocalI64:
        *result = kWasmI64;
        return true;
      case kLocalF32:
        *result = kWasmF32;
        return true;
      case kLocalF64:
        *result = kWasmF64;
        return true;
      case kLocalS128:
        *result = kWasmS128;
        return true;
251 252 253
      case kLocalAnyRef:
        *result = kWasmAnyRef;
        return true;
254
      default:
255
        *result = kWasmVar;
256 257 258
        return false;
    }
  }
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  uint32_t in_arity() const {
    if (type != kWasmVar) return 0;
    return static_cast<uint32_t>(sig->parameter_count());
  }
  uint32_t out_arity() const {
    if (type == kWasmStmt) return 0;
    if (type != kWasmVar) return 1;
    return static_cast<uint32_t>(sig->return_count());
  }
  ValueType in_type(uint32_t index) {
    DCHECK_EQ(kWasmVar, type);
    return sig->GetParam(index);
  }
  ValueType out_type(uint32_t index) {
    if (type == kWasmVar) return sig->GetReturn(index);
    DCHECK_NE(kWasmStmt, type);
    DCHECK_EQ(0, index);
    return type;
278 279 280
  }
};

281
template <Decoder::ValidateFlag validate>
282
struct BreakDepthImmediate {
283 284
  uint32_t depth;
  unsigned length;
285
  inline BreakDepthImmediate(Decoder* decoder, const byte* pc) {
286
    depth = decoder->read_u32v<validate>(pc + 1, &length, "break depth");
287 288 289
  }
};

290
template <Decoder::ValidateFlag validate>
291
struct CallIndirectImmediate {
292
  uint32_t table_index;
293
  uint32_t sig_index;
294
  FunctionSig* sig = nullptr;
295
  unsigned length = 0;
296
  inline CallIndirectImmediate(Decoder* decoder, const byte* pc) {
297
    unsigned len = 0;
298
    sig_index = decoder->read_u32v<validate>(pc + 1, &len, "signature index");
299
    if (!VALIDATE(decoder->ok())) return;
300
    table_index = decoder->read_u8<validate>(pc + 1 + len, "table index");
301
    if (!VALIDATE(table_index == 0)) {
302 303
      decoder->errorf(pc + 1 + len, "expected table index 0, found %u",
                      table_index);
304 305 306 307 308
    }
    length = 1 + len;
  }
};

309
template <Decoder::ValidateFlag validate>
310
struct CallFunctionImmediate {
311
  uint32_t index;
312
  FunctionSig* sig = nullptr;
313
  unsigned length;
314
  inline CallFunctionImmediate(Decoder* decoder, const byte* pc) {
315
    index = decoder->read_u32v<validate>(pc + 1, &length, "function index");
316 317 318
  }
};

319
template <Decoder::ValidateFlag validate>
320
struct MemoryIndexImmediate {
321
  uint32_t index;
322
  unsigned length = 1;
323
  inline MemoryIndexImmediate(Decoder* decoder, const byte* pc) {
324
    index = decoder->read_u8<validate>(pc + 1, "memory index");
325
    if (!VALIDATE(index == 0)) {
326
      decoder->errorf(pc + 1, "expected memory index 0, found %u", index);
327 328 329 330
    }
  }
};

331
template <Decoder::ValidateFlag validate>
332
struct BranchTableImmediate {
333 334 335
  uint32_t table_count;
  const byte* start;
  const byte* table;
336
  inline BranchTableImmediate(Decoder* decoder, const byte* pc) {
337
    DCHECK_EQ(kExprBrTable, decoder->read_u8<validate>(pc, "opcode"));
338
    start = pc + 1;
339
    unsigned len = 0;
340
    table_count = decoder->read_u32v<validate>(pc + 1, &len, "table count");
341
    table = pc + 1 + len;
342 343 344 345
  }
};

// A helper to iterate over a branch table.
346
template <Decoder::ValidateFlag validate>
347 348 349
class BranchTableIterator {
 public:
  unsigned cur_index() { return index_; }
350
  bool has_next() { return VALIDATE(decoder_->ok()) && index_ <= table_count_; }
351 352 353
  uint32_t next() {
    DCHECK(has_next());
    index_++;
354
    unsigned length;
355
    uint32_t result =
356
        decoder_->read_u32v<validate>(pc_, &length, "branch table entry");
357 358 359
    pc_ += length;
    return result;
  }
360
  // length, including the length of the {BranchTableImmediate}, but not the
361 362 363 364 365 366 367
  // opcode.
  unsigned length() {
    while (has_next()) next();
    return static_cast<unsigned>(pc_ - start_);
  }
  const byte* pc() { return pc_; }

368
  BranchTableIterator(Decoder* decoder,
369
                      const BranchTableImmediate<validate>& imm)
370
      : decoder_(decoder),
371 372 373
        start_(imm.start),
        pc_(imm.table),
        table_count_(imm.table_count) {}
374 375 376 377 378

 private:
  Decoder* decoder_;
  const byte* start_;
  const byte* pc_;
379
  uint32_t index_ = 0;    // the current index.
380 381 382
  uint32_t table_count_;  // the count of entries, not including default.
};

383
template <Decoder::ValidateFlag validate>
384
struct MemoryAccessImmediate {
385 386
  uint32_t alignment;
  uint32_t offset;
387
  unsigned length = 0;
388 389
  inline MemoryAccessImmediate(Decoder* decoder, const byte* pc,
                               uint32_t max_alignment) {
390 391
    unsigned alignment_length;
    alignment =
392
        decoder->read_u32v<validate>(pc + 1, &alignment_length, "alignment");
393
    if (!VALIDATE(alignment <= max_alignment)) {
394 395 396 397
      decoder->errorf(pc + 1,
                      "invalid alignment; expected maximum alignment is %u, "
                      "actual alignment is %u",
                      max_alignment, alignment);
398
    }
399
    if (!VALIDATE(decoder->ok())) return;
400
    unsigned offset_length;
401 402
    offset = decoder->read_u32v<validate>(pc + 1 + alignment_length,
                                          &offset_length, "offset");
403 404 405 406
    length = alignment_length + offset_length;
  }
};

407
// Immediate for SIMD lane operations.
408
template <Decoder::ValidateFlag validate>
409
struct SimdLaneImmediate {
410
  uint8_t lane;
411
  unsigned length = 1;
412

413
  inline SimdLaneImmediate(Decoder* decoder, const byte* pc) {
414
    lane = decoder->read_u8<validate>(pc + 2, "lane");
415 416 417
  }
};

418
// Immediate for SIMD shift operations.
419
template <Decoder::ValidateFlag validate>
420
struct SimdShiftImmediate {
421
  uint8_t shift;
422
  unsigned length = 1;
423

424
  inline SimdShiftImmediate(Decoder* decoder, const byte* pc) {
425
    shift = decoder->read_u8<validate>(pc + 2, "shift");
426 427 428
  }
};

429
// Immediate for SIMD S8x16 shuffle operations.
430
template <Decoder::ValidateFlag validate>
431
struct Simd8x16ShuffleImmediate {
432
  uint8_t shuffle[kSimd128Size] = {0};
433

434
  inline Simd8x16ShuffleImmediate(Decoder* decoder, const byte* pc) {
435
    for (uint32_t i = 0; i < kSimd128Size; ++i) {
436
      shuffle[i] = decoder->read_u8<validate>(pc + 2 + i, "shuffle");
437
      if (!VALIDATE(decoder->ok())) return;
438
    }
439 440 441
  }
};

442
// An entry on the value stack.
443
struct ValueBase {
444 445 446 447
  const byte* pc;
  ValueType type;

  // Named constructors.
448
  static ValueBase Unreachable(const byte* pc) { return {pc, kWasmVar}; }
449

450
  static ValueBase New(const byte* pc, ValueType type) { return {pc, type}; }
451 452
};

453 454
template <typename Value>
struct Merge {
455 456
  uint32_t arity;
  union {
457 458
    Value* array;
    Value first;
459 460
  } vals;  // Either multiple values or a single value.

461 462 463 464 465 466
  // Tracks whether this merge was ever reached. Uses precise reachability, like
  // Reachability::kReachable.
  bool reached;

  Merge(bool reached = false) : reached(reached) {}

467
  Value& operator[](uint32_t i) {
468 469 470 471 472
    DCHECK_GT(arity, i);
    return arity == 1 ? vals.first : vals.array[i];
  }
};

473
enum ControlKind : uint8_t {
474 475 476 477 478 479 480 481
  kControlIf,
  kControlIfElse,
  kControlBlock,
  kControlLoop,
  kControlTry,
  kControlTryCatch
};

482 483 484 485 486 487 488 489 490
enum Reachability : uint8_t {
  // reachable code.
  kReachable,
  // reachable code in unreachable block (implies normal validation).
  kSpecOnlyReachable,
  // code unreachable in its own block (implies polymorphic validation).
  kUnreachable
};

491
// An entry on the control stack (i.e. if, block, loop, or try).
492 493
template <typename Value>
struct ControlBase {
494
  ControlKind kind;
495
  uint32_t stack_depth;  // stack height at the beginning of the construct.
496
  const byte* pc;
497
  Reachability reachability = kReachable;
498

499 500 501
  // Values merged into the start or end of this control construct.
  Merge<Value> start_merge;
  Merge<Value> end_merge;
502

503
  ControlBase() = default;
504 505
  ControlBase(ControlKind kind, uint32_t stack_depth, const byte* pc)
      : kind(kind), stack_depth(stack_depth), pc(pc) {}
506

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
  // Check whether the current block is reachable.
  bool reachable() const { return reachability == kReachable; }

  // Check whether the rest of the block is unreachable.
  // Note that this is different from {!reachable()}, as there is also the
  // "indirect unreachable state", for which both {reachable()} and
  // {unreachable()} return false.
  bool unreachable() const { return reachability == kUnreachable; }

  // Return the reachability of new control structs started in this block.
  Reachability innerReachability() const {
    return reachability == kReachable ? kReachable : kSpecOnlyReachable;
  }

  bool is_if() const { return is_onearmed_if() || is_if_else(); }
  bool is_onearmed_if() const { return kind == kControlIf; }
  bool is_if_else() const { return kind == kControlIfElse; }
  bool is_block() const { return kind == kControlBlock; }
  bool is_loop() const { return kind == kControlLoop; }
  bool is_try() const { return is_incomplete_try() || is_try_catch(); }
  bool is_incomplete_try() const { return kind == kControlTry; }
  bool is_try_catch() const { return kind == kControlTryCatch; }
529

530 531 532 533
  inline Merge<Value>* br_merge() {
    return is_loop() ? &this->start_merge : &this->end_merge;
  }

534
  // Named constructors.
535 536
  static ControlBase Block(const byte* pc, uint32_t stack_depth) {
    return {kControlBlock, stack_depth, pc};
537 538
  }

539 540
  static ControlBase If(const byte* pc, uint32_t stack_depth) {
    return {kControlIf, stack_depth, pc};
541 542
  }

543 544
  static ControlBase Loop(const byte* pc, uint32_t stack_depth) {
    return {kControlLoop, stack_depth, pc};
545 546
  }

547 548
  static ControlBase Try(const byte* pc, uint32_t stack_depth) {
    return {kControlTry, stack_depth, pc};
549 550 551
  }
};

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
#define CONCRETE_NAMED_CONSTRUCTOR(concrete_type, abstract_type, name) \
  template <typename... Args>                                          \
  static concrete_type name(Args&&... args) {                          \
    concrete_type val;                                                 \
    static_cast<abstract_type&>(val) =                                 \
        abstract_type::name(std::forward<Args>(args)...);              \
    return val;                                                        \
  }

// Provide the default named constructors, which default-initialize the
// ConcreteType and the initialize the fields of ValueBase correctly.
// Use like this:
// struct Value : public ValueWithNamedConstructors<Value> { int new_field; };
template <typename ConcreteType>
struct ValueWithNamedConstructors : public ValueBase {
  // Named constructors.
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, Unreachable)
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, New)
};

// Provide the default named constructors, which default-initialize the
// ConcreteType and the initialize the fields of ControlBase correctly.
// Use like this:
// struct Control : public ControlWithNamedConstructors<Control, Value> {
//   int my_uninitialized_field;
//   char* other_field = nullptr;
// };
template <typename ConcreteType, typename Value>
struct ControlWithNamedConstructors : public ControlBase<Value> {
  // Named constructors.
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Block)
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, If)
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Loop)
  CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Try)
};

588 589 590
// This is the list of callback functions that an interface for the
// WasmFullDecoder should implement.
// F(Name, args...)
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
#define INTERFACE_FUNCTIONS(F)                                                \
  /* General: */                                                              \
  F(StartFunction)                                                            \
  F(StartFunctionBody, Control* block)                                        \
  F(FinishFunction)                                                           \
  F(OnFirstError)                                                             \
  F(NextInstruction, WasmOpcode)                                              \
  /* Control: */                                                              \
  F(Block, Control* block)                                                    \
  F(Loop, Control* block)                                                     \
  F(Try, Control* block)                                                      \
  F(If, const Value& cond, Control* if_block)                                 \
  F(FallThruTo, Control* c)                                                   \
  F(PopControl, Control* block)                                               \
  F(EndControl, Control* block)                                               \
  /* Instructions: */                                                         \
  F(UnOp, WasmOpcode opcode, FunctionSig*, const Value& value, Value* result) \
  F(BinOp, WasmOpcode opcode, FunctionSig*, const Value& lhs,                 \
    const Value& rhs, Value* result)                                          \
  F(I32Const, Value* result, int32_t value)                                   \
  F(I64Const, Value* result, int64_t value)                                   \
  F(F32Const, Value* result, float value)                                     \
  F(F64Const, Value* result, double value)                                    \
  F(RefNull, Value* result)                                                   \
  F(Drop, const Value& value)                                                 \
  F(DoReturn, Vector<Value> values, bool implicit)                            \
  F(GetLocal, Value* result, const LocalIndexImmediate<validate>& imm)        \
  F(SetLocal, const Value& value, const LocalIndexImmediate<validate>& imm)   \
  F(TeeLocal, const Value& value, Value* result,                              \
    const LocalIndexImmediate<validate>& imm)                                 \
  F(GetGlobal, Value* result, const GlobalIndexImmediate<validate>& imm)      \
  F(SetGlobal, const Value& value, const GlobalIndexImmediate<validate>& imm) \
  F(Unreachable)                                                              \
  F(Select, const Value& cond, const Value& fval, const Value& tval,          \
    Value* result)                                                            \
  F(Br, Control* target)                                                      \
  F(BrIf, const Value& cond, Control* target)                                 \
  F(BrTable, const BranchTableImmediate<validate>& imm, const Value& key)     \
  F(Else, Control* if_block)                                                  \
  F(LoadMem, LoadType type, const MemoryAccessImmediate<validate>& imm,       \
    const Value& index, Value* result)                                        \
  F(StoreMem, StoreType type, const MemoryAccessImmediate<validate>& imm,     \
    const Value& index, const Value& value)                                   \
  F(CurrentMemoryPages, Value* result)                                        \
  F(GrowMemory, const Value& value, Value* result)                            \
  F(CallDirect, const CallFunctionImmediate<validate>& imm,                   \
    const Value args[], Value returns[])                                      \
  F(CallIndirect, const Value& index,                                         \
    const CallIndirectImmediate<validate>& imm, const Value args[],           \
    Value returns[])                                                          \
  F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result)             \
  F(SimdLaneOp, WasmOpcode opcode, const SimdLaneImmediate<validate>& imm,    \
    const Vector<Value> inputs, Value* result)                                \
  F(SimdShiftOp, WasmOpcode opcode, const SimdShiftImmediate<validate>& imm,  \
    const Value& input, Value* result)                                        \
  F(Simd8x16ShuffleOp, const Simd8x16ShuffleImmediate<validate>& imm,         \
    const Value& input0, const Value& input1, Value* result)                  \
  F(Throw, const ExceptionIndexImmediate<validate>&, Control* block,          \
    const Vector<Value>& args)                                                \
  F(CatchException, const ExceptionIndexImmediate<validate>& imm,             \
    Control* block, Vector<Value> caught_values)                              \
  F(AtomicOp, WasmOpcode opcode, Vector<Value> args,                          \
    const MemoryAccessImmediate<validate>& imm, Value* result)

// Generic Wasm bytecode decoder with utilities for decoding immediates,
656
// lengths, etc.
657
template <Decoder::ValidateFlag validate>
658 659 660 661 662 663 664 665 666 667 668 669 670
class WasmDecoder : public Decoder {
 public:
  WasmDecoder(const WasmModule* module, FunctionSig* sig, const byte* start,
              const byte* end, uint32_t buffer_offset = 0)
      : Decoder(start, end, buffer_offset),
        module_(module),
        sig_(sig),
        local_types_(nullptr) {}
  const WasmModule* module_;
  FunctionSig* sig_;

  ZoneVector<ValueType>* local_types_;

671 672 673 674
  uint32_t total_locals() const {
    return local_types_ == nullptr
               ? 0
               : static_cast<uint32_t>(local_types_->size());
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  }

  static bool DecodeLocals(Decoder* decoder, const FunctionSig* sig,
                           ZoneVector<ValueType>* type_list) {
    DCHECK_NOT_NULL(type_list);
    DCHECK_EQ(0, type_list->size());
    // Initialize from signature.
    if (sig != nullptr) {
      type_list->assign(sig->parameters().begin(), sig->parameters().end());
    }
    // Decode local declarations, if any.
    uint32_t entries = decoder->consume_u32v("local decls count");
    if (decoder->failed()) return false;

    TRACE("local decls count: %u\n", entries);
690
    while (entries-- > 0 && VALIDATE(decoder->ok()) && decoder->more()) {
691 692 693
      uint32_t count = decoder->consume_u32v("local count");
      if (decoder->failed()) return false;

694 695
      DCHECK_LE(type_list->size(), kV8MaxWasmFunctionLocals);
      if (count > kV8MaxWasmFunctionLocals - type_list->size()) {
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        decoder->error(decoder->pc() - 1, "local count too large");
        return false;
      }
      byte code = decoder->consume_u8("local type");
      if (decoder->failed()) return false;

      ValueType type;
      switch (code) {
        case kLocalI32:
          type = kWasmI32;
          break;
        case kLocalI64:
          type = kWasmI64;
          break;
        case kLocalF32:
          type = kWasmF32;
          break;
        case kLocalF64:
          type = kWasmF64;
          break;
716 717 718 719 720 721 722
        case kLocalAnyRef:
          if (FLAG_experimental_wasm_anyref) {
            type = kWasmAnyRef;
            break;
          }
          decoder->error(decoder->pc() - 1, "invalid local type");
          return false;
723
        case kLocalS128:
724 725 726 727
          if (FLAG_experimental_wasm_simd) {
            type = kWasmS128;
            break;
          }
728
          V8_FALLTHROUGH;
729 730 731 732 733 734 735 736 737 738 739
        default:
          decoder->error(decoder->pc() - 1, "invalid local type");
          return false;
      }
      type_list->insert(type_list->end(), count, type);
    }
    DCHECK(decoder->ok());
    return true;
  }

  static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc,
740
                                          uint32_t locals_count, Zone* zone) {
741 742 743
    if (pc >= decoder->end()) return nullptr;
    if (*pc != kExprLoop) return nullptr;

744 745
    // The number of locals_count is augmented by 2 so that 'locals_count - 2'
    // can be used to track mem_size, and 'locals_count - 1' to track mem_start.
746 747 748
    BitVector* assigned = new (zone) BitVector(locals_count, zone);
    int depth = 0;
    // Iteratively process all AST nodes nested inside the loop.
749
    while (pc < decoder->end() && VALIDATE(decoder->ok())) {
750 751 752 753 754 755 756 757 758 759 760 761
      WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
      unsigned length = 1;
      switch (opcode) {
        case kExprLoop:
        case kExprIf:
        case kExprBlock:
        case kExprTry:
          length = OpcodeLength(decoder, pc);
          depth++;
          break;
        case kExprSetLocal:  // fallthru
        case kExprTeeLocal: {
762
          LocalIndexImmediate<Decoder::kValidate> imm(decoder, pc);
763
          if (assigned->length() > 0 &&
764
              imm.index < static_cast<uint32_t>(assigned->length())) {
765
            // Unverified code might have an out-of-bounds index.
766
            assigned->Add(imm.index);
767
          }
768
          length = 1 + imm.length;
769 770
          break;
        }
771 772 773
        case kExprGrowMemory:
        case kExprCallFunction:
        case kExprCallIndirect:
774
          // Add instance cache nodes to the assigned set.
775 776
          // TODO(titzer): make this more clear.
          assigned->Add(locals_count - 1);
777 778
          length = OpcodeLength(decoder, pc);
          break;
779 780 781 782 783 784 785 786 787 788
        case kExprEnd:
          depth--;
          break;
        default:
          length = OpcodeLength(decoder, pc);
          break;
      }
      if (depth <= 0) break;
      pc += length;
    }
789
    return VALIDATE(decoder->ok()) ? assigned : nullptr;
790 791
  }

792
  inline bool Validate(const byte* pc,
793 794 795
                       LocalIndexImmediate<Decoder::kValidate>& imm) {
    if (!VALIDATE(imm.index < total_locals())) {
      errorf(pc + 1, "invalid local index: %u", imm.index);
796
      return false;
797
    }
798
    imm.type = local_types_ ? local_types_->at(imm.index) : kWasmStmt;
799
    return true;
800 801
  }

802
  inline bool Validate(const byte* pc, ExceptionIndexImmediate<validate>& imm) {
803
    if (!VALIDATE(module_ != nullptr &&
804 805
                  imm.index < module_->exceptions.size())) {
      errorf(pc + 1, "Invalid exception index: %u", imm.index);
806
      return false;
807
    }
808
    imm.exception = &module_->exceptions[imm.index];
809
    return true;
810 811
  }

812 813 814
  inline bool Validate(const byte* pc, GlobalIndexImmediate<validate>& imm) {
    if (!VALIDATE(module_ != nullptr && imm.index < module_->globals.size())) {
      errorf(pc + 1, "invalid global index: %u", imm.index);
815
      return false;
816
    }
817 818
    imm.global = &module_->globals[imm.index];
    imm.type = imm.global->type;
819
    return true;
820 821
  }

822
  inline bool Complete(const byte* pc, CallFunctionImmediate<validate>& imm) {
823
    if (!VALIDATE(module_ != nullptr &&
824
                  imm.index < module_->functions.size())) {
825
      return false;
826
    }
827
    imm.sig = module_->functions[imm.index].sig;
828
    return true;
829 830
  }

831 832
  inline bool Validate(const byte* pc, CallFunctionImmediate<validate>& imm) {
    if (Complete(pc, imm)) {
833 834
      return true;
    }
835
    errorf(pc + 1, "invalid function index: %u", imm.index);
836 837 838
    return false;
  }

839
  inline bool Complete(const byte* pc, CallIndirectImmediate<validate>& imm) {
840
    if (!VALIDATE(module_ != nullptr &&
841
                  imm.sig_index < module_->signatures.size())) {
842
      return false;
843
    }
844
    imm.sig = module_->signatures[imm.sig_index];
845
    return true;
846 847
  }

848
  inline bool Validate(const byte* pc, CallIndirectImmediate<validate>& imm) {
849
    if (!VALIDATE(module_ != nullptr && !module_->function_tables.empty())) {
850 851 852
      error("function table has to exist to execute call_indirect");
      return false;
    }
853 854
    if (!Complete(pc, imm)) {
      errorf(pc + 1, "invalid signature index: #%u", imm.sig_index);
855
      return false;
856
    }
857
    return true;
858 859
  }

860
  inline bool Validate(const byte* pc, BreakDepthImmediate<validate>& imm,
861
                       size_t control_depth) {
862 863
    if (!VALIDATE(imm.depth < control_depth)) {
      errorf(pc + 1, "invalid break depth: %u", imm.depth);
864
      return false;
865
    }
866
    return true;
867 868
  }

869
  bool Validate(const byte* pc, BranchTableImmediate<validate>& imm,
870
                size_t block_depth) {
871
    if (!VALIDATE(imm.table_count < kV8MaxWasmFunctionSize)) {
872
      errorf(pc + 1, "invalid table count (> max function size): %u",
873
             imm.table_count);
874 875
      return false;
    }
876
    return checkAvailable(imm.table_count);
877 878 879
  }

  inline bool Validate(const byte* pc, WasmOpcode opcode,
880
                       SimdLaneImmediate<validate>& imm) {
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    uint8_t num_lanes = 0;
    switch (opcode) {
      case kExprF32x4ExtractLane:
      case kExprF32x4ReplaceLane:
      case kExprI32x4ExtractLane:
      case kExprI32x4ReplaceLane:
        num_lanes = 4;
        break;
      case kExprI16x8ExtractLane:
      case kExprI16x8ReplaceLane:
        num_lanes = 8;
        break;
      case kExprI8x16ExtractLane:
      case kExprI8x16ReplaceLane:
        num_lanes = 16;
        break;
      default:
        UNREACHABLE();
        break;
    }
901
    if (!VALIDATE(imm.lane >= 0 && imm.lane < num_lanes)) {
902 903 904 905 906 907 908 909
      error(pc_ + 2, "invalid lane index");
      return false;
    } else {
      return true;
    }
  }

  inline bool Validate(const byte* pc, WasmOpcode opcode,
910
                       SimdShiftImmediate<validate>& imm) {
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    uint8_t max_shift = 0;
    switch (opcode) {
      case kExprI32x4Shl:
      case kExprI32x4ShrS:
      case kExprI32x4ShrU:
        max_shift = 32;
        break;
      case kExprI16x8Shl:
      case kExprI16x8ShrS:
      case kExprI16x8ShrU:
        max_shift = 16;
        break;
      case kExprI8x16Shl:
      case kExprI8x16ShrS:
      case kExprI8x16ShrU:
        max_shift = 8;
        break;
      default:
        UNREACHABLE();
        break;
    }
932
    if (!VALIDATE(imm.shift >= 0 && imm.shift < max_shift)) {
933 934 935 936 937 938 939 940
      error(pc_ + 2, "invalid shift amount");
      return false;
    } else {
      return true;
    }
  }

  inline bool Validate(const byte* pc,
941
                       Simd8x16ShuffleImmediate<validate>& imm) {
942
    uint8_t max_lane = 0;
943
    for (uint32_t i = 0; i < kSimd128Size; ++i) {
944
      max_lane = std::max(max_lane, imm.shuffle[i]);
945
    }
946
    // Shuffle indices must be in [0..31] for a 16 lane shuffle.
947
    if (!VALIDATE(max_lane <= 2 * kSimd128Size)) {
948 949 950
      error(pc_ + 2, "invalid shuffle mask");
      return false;
    }
951
    return true;
952 953
  }

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
  inline bool Complete(BlockTypeImmediate<validate>& imm) {
    if (imm.type != kWasmVar) return true;
    if (!VALIDATE((module_ && imm.sig_index < module_->signatures.size()))) {
      return false;
    }
    imm.sig = module_->signatures[imm.sig_index];
    return true;
  }

  inline bool Validate(BlockTypeImmediate<validate>& imm) {
    if (!Complete(imm)) {
      errorf(pc_, "block type index %u out of bounds (%zu signatures)",
             imm.sig_index, module_ ? module_->signatures.size() : 0);
      return false;
    }
    return true;
  }

972 973 974 975 976 977 978 979
  static unsigned OpcodeLength(Decoder* decoder, const byte* pc) {
    WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
    switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
      FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
      FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
      {
980 981
        MemoryAccessImmediate<validate> imm(decoder, pc, UINT32_MAX);
        return 1 + imm.length;
982 983 984
      }
      case kExprBr:
      case kExprBrIf: {
985 986
        BreakDepthImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
987 988 989
      }
      case kExprSetGlobal:
      case kExprGetGlobal: {
990 991
        GlobalIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
992 993 994
      }

      case kExprCallFunction: {
995 996
        CallFunctionImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
997 998
      }
      case kExprCallIndirect: {
999 1000
        CallIndirectImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1001 1002 1003 1004 1005 1006
      }

      case kExprTry:
      case kExprIf:  // fall through
      case kExprLoop:
      case kExprBlock: {
1007 1008
        BlockTypeImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1009 1010 1011 1012
      }

      case kExprThrow:
      case kExprCatch: {
1013 1014
        ExceptionIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1015 1016 1017 1018 1019
      }

      case kExprSetLocal:
      case kExprTeeLocal:
      case kExprGetLocal: {
1020 1021
        LocalIndexImmediate<Decoder::kValidate> imm(decoder, pc);
        return 1 + imm.length;
1022 1023
      }
      case kExprBrTable: {
1024 1025
        BranchTableImmediate<validate> imm(decoder, pc);
        BranchTableIterator<validate> iterator(decoder, imm);
1026 1027 1028
        return 1 + iterator.length();
      }
      case kExprI32Const: {
1029 1030
        ImmI32Immediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1031 1032
      }
      case kExprI64Const: {
1033 1034
        ImmI64Immediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1035
      }
1036 1037 1038
      case kExprRefNull: {
        return 1;
      }
1039 1040
      case kExprGrowMemory:
      case kExprMemorySize: {
1041 1042
        MemoryIndexImmediate<validate> imm(decoder, pc);
        return 1 + imm.length;
1043 1044 1045 1046 1047
      }
      case kExprF32Const:
        return 5;
      case kExprF64Const:
        return 9;
1048 1049
      case kNumericPrefix:
        return 2;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
      case kSimdPrefix: {
        byte simd_index = decoder->read_u8<validate>(pc + 1, "simd_index");
        WasmOpcode opcode =
            static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index);
        switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          return 2;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          return 3;
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          {
1067 1068
            MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX);
            return 2 + imm.length;
1069 1070 1071 1072 1073 1074 1075 1076 1077
          }
          // Shuffles require a byte per lane, or 16 immediate bytes.
          case kExprS8x16Shuffle:
            return 2 + kSimd128Size;
          default:
            decoder->error(pc, "invalid SIMD opcode");
            return 2;
        }
      }
1078 1079 1080 1081 1082 1083 1084 1085 1086
      case kAtomicPrefix: {
        byte atomic_index = decoder->read_u8<validate>(pc + 1, "atomic_index");
        WasmOpcode opcode =
            static_cast<WasmOpcode>(kAtomicPrefix << 8 | atomic_index);
        switch (opcode) {
#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
          FOREACH_ATOMIC_OPCODE(DECLARE_OPCODE_CASE)
#undef DECLARE_OPCODE_CASE
          {
1087 1088
            MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX);
            return 2 + imm.length;
1089 1090 1091 1092 1093 1094
          }
          default:
            decoder->error(pc, "invalid Atomics opcode");
            return 2;
        }
      }
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
      default:
        return 1;
    }
  }

  std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) {
    WasmOpcode opcode = static_cast<WasmOpcode>(*pc);
    // Handle "simple" opcodes with a fixed signature first.
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
    if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode);
    if (sig) return {sig->parameter_count(), sig->return_count()};

#define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name:
    // clang-format off
    switch (opcode) {
      case kExprSelect:
        return {3, 1};
      FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE)
        return {2, 0};
      FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE)
      case kExprTeeLocal:
      case kExprGrowMemory:
        return {1, 1};
      case kExprSetLocal:
      case kExprSetGlobal:
      case kExprDrop:
      case kExprBrIf:
      case kExprBrTable:
      case kExprIf:
        return {1, 0};
      case kExprGetLocal:
      case kExprGetGlobal:
      case kExprI32Const:
      case kExprI64Const:
      case kExprF32Const:
      case kExprF64Const:
1131
      case kExprRefNull:
1132 1133 1134
      case kExprMemorySize:
        return {0, 1};
      case kExprCallFunction: {
1135 1136 1137
        CallFunctionImmediate<validate> imm(this, pc);
        CHECK(Complete(pc, imm));
        return {imm.sig->parameter_count(), imm.sig->return_count()};
1138 1139
      }
      case kExprCallIndirect: {
1140 1141
        CallIndirectImmediate<validate> imm(this, pc);
        CHECK(Complete(pc, imm));
1142
        // Indirect calls pop an additional argument for the table index.
1143 1144
        return {imm.sig->parameter_count() + 1,
                imm.sig->return_count()};
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
      }
      case kExprBr:
      case kExprBlock:
      case kExprLoop:
      case kExprEnd:
      case kExprElse:
      case kExprNop:
      case kExprReturn:
      case kExprUnreachable:
        return {0, 0};
1155
      case kNumericPrefix:
1156 1157 1158 1159
      case kAtomicPrefix:
      case kSimdPrefix: {
        opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1));
        switch (opcode) {
1160
          FOREACH_SIMD_1_OPERAND_1_PARAM_OPCODE(DECLARE_OPCODE_CASE)
1161
            return {1, 1};
1162 1163
          FOREACH_SIMD_1_OPERAND_2_PARAM_OPCODE(DECLARE_OPCODE_CASE)
            return {2, 1};
1164 1165 1166 1167 1168 1169 1170
          default: {
            sig = WasmOpcodes::Signature(opcode);
            if (sig) {
              return {sig->parameter_count(), sig->return_count()};
            }
          }
        }
1171
        V8_FALLTHROUGH;
1172
      }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
      default:
        V8_Fatal(__FILE__, __LINE__, "unimplemented opcode: %x (%s)", opcode,
                 WasmOpcodes::OpcodeName(opcode));
        return {0, 0};
    }
#undef DECLARE_OPCODE_CASE
    // clang-format on
  }
};

1183
#define CALL_INTERFACE(name, ...) interface_.name(this, ##__VA_ARGS__)
1184 1185 1186 1187 1188 1189
#define CALL_INTERFACE_IF_REACHABLE(name, ...)                 \
  do {                                                         \
    DCHECK(!control_.empty());                                 \
    if (VALIDATE(this->ok()) && control_.back().reachable()) { \
      interface_.name(this, ##__VA_ARGS__);                    \
    }                                                          \
1190
  } while (false)
1191 1192 1193 1194 1195 1196 1197
#define CALL_INTERFACE_IF_PARENT_REACHABLE(name, ...)           \
  do {                                                          \
    DCHECK(!control_.empty());                                  \
    if (VALIDATE(this->ok()) &&                                 \
        (control_.size() == 1 || control_at(1)->reachable())) { \
      interface_.name(this, ##__VA_ARGS__);                     \
    }                                                           \
1198 1199
  } while (false)

1200
template <Decoder::ValidateFlag validate, typename Interface>
1201
class WasmFullDecoder : public WasmDecoder<validate> {
1202 1203 1204
  using Value = typename Interface::Value;
  using Control = typename Interface::Control;
  using MergeValues = Merge<Value>;
1205

1206 1207
  // All Value types should be trivially copyable for performance. We push, pop,
  // and store them in local variables.
1208
  ASSERT_TRIVIALLY_COPYABLE(Value);
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

 public:
  template <typename... InterfaceArgs>
  WasmFullDecoder(Zone* zone, const wasm::WasmModule* module,
                  const FunctionBody& body, InterfaceArgs&&... interface_args)
      : WasmDecoder<validate>(module, body.sig, body.start, body.end,
                              body.offset),
        zone_(zone),
        interface_(std::forward<InterfaceArgs>(interface_args)...),
        local_type_vec_(zone),
        stack_(zone),
        control_(zone),
1221
        args_(zone),
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        last_end_found_(false) {
    this->local_types_ = &local_type_vec_;
  }

  Interface& interface() { return interface_; }

  bool Decode() {
    DCHECK(stack_.empty());
    DCHECK(control_.empty());

    base::ElapsedTimer decode_timer;
    if (FLAG_trace_wasm_decode_time) {
      decode_timer.Start();
    }

    if (this->end_ < this->pc_) {
      this->error("function body end < start");
      return false;
    }

    DCHECK_EQ(0, this->local_types_->size());
    WasmDecoder<validate>::DecodeLocals(this, this->sig_, this->local_types_);
1244
    CALL_INTERFACE(StartFunction);
1245
    DecodeFunctionBody();
1246
    if (!this->failed()) CALL_INTERFACE(FinishFunction);
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267

    if (this->failed()) return this->TraceFailed();

    if (!control_.empty()) {
      // Generate a better error message whether the unterminated control
      // structure is the function body block or an innner structure.
      if (control_.size() > 1) {
        this->error(control_.back().pc, "unterminated control structure");
      } else {
        this->error("function body must end with \"end\" opcode");
      }
      return TraceFailed();
    }

    if (!last_end_found_) {
      this->error("function body must end with \"end\" opcode");
      return false;
    }

    if (FLAG_trace_wasm_decode_time) {
      double ms = decode_timer.Elapsed().InMillisecondsF();
1268 1269
      PrintF("wasm-decode %s (%0.3f ms)\n\n",
             VALIDATE(this->ok()) ? "ok" : "failed", ms);
1270
    } else {
1271
      TRACE("wasm-decode %s\n\n", VALIDATE(this->ok()) ? "ok" : "failed");
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    }

    return true;
  }

  bool TraceFailed() {
    TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_offset_,
          this->GetBufferRelativeOffset(this->error_offset_),
          this->error_msg_.c_str());
    return false;
  }

  const char* SafeOpcodeNameAt(const byte* pc) {
    if (pc >= this->end_) return "<end>";
    return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(*pc));
  }

  inline Zone* zone() const { return zone_; }

  inline uint32_t NumLocals() {
    return static_cast<uint32_t>(local_type_vec_.size());
  }

  inline ValueType GetLocalType(uint32_t index) {
    return local_type_vec_[index];
  }

  inline wasm::WasmCodePosition position() {
    int offset = static_cast<int>(this->pc_ - this->start_);
    DCHECK_EQ(this->pc_ - this->start_, offset);  // overflows cannot happen
    return offset;
  }

  inline uint32_t control_depth() const {
    return static_cast<uint32_t>(control_.size());
  }

  inline Control* control_at(uint32_t depth) {
    DCHECK_GT(control_.size(), depth);
1311
    return &control_.back() - depth;
1312 1313 1314
  }

  inline uint32_t stack_size() const {
1315
    DCHECK_GE(kMaxUInt32, stack_.size());
1316 1317 1318 1319 1320 1321 1322 1323
    return static_cast<uint32_t>(stack_.size());
  }

  inline Value* stack_value(uint32_t depth) {
    DCHECK_GT(stack_.size(), depth);
    return &stack_[stack_.size() - depth - 1];
  }

1324 1325 1326 1327 1328 1329
  inline Value& GetMergeValueFromStack(
      Control* c, Merge<Value>* merge, uint32_t i) {
    DCHECK(merge == &c->start_merge || merge == &c->end_merge);
    DCHECK_GT(merge->arity, i);
    DCHECK_GE(stack_.size(), c->stack_depth + merge->arity);
    return stack_[stack_.size() - merge->arity + i];
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
  }

 private:
  static constexpr size_t kErrorMsgSize = 128;

  Zone* zone_;

  Interface interface_;

  ZoneVector<ValueType> local_type_vec_;  // types of local variables.
  ZoneVector<Value> stack_;               // stack of values.
  ZoneVector<Control> control_;           // stack of blocks, loops, and ifs.
1342
  ZoneVector<Value> args_;                // parameters of current block or call
1343 1344 1345
  bool last_end_found_;

  bool CheckHasMemory() {
1346 1347 1348 1349 1350
    if (!VALIDATE(this->module_->has_memory)) {
      this->error(this->pc_ - 1, "memory instruction with no memory");
      return false;
    }
    return true;
1351 1352
  }

1353 1354 1355 1356 1357 1358 1359 1360
  bool CheckHasSharedMemory() {
    if (!VALIDATE(this->module_->has_shared_memory)) {
      this->error(this->pc_ - 1, "Atomic opcodes used without shared memory");
      return false;
    }
    return true;
  }

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
  class TraceLine {
   public:
    static constexpr int kMaxLen = 512;
    ~TraceLine() {
      if (!FLAG_trace_wasm_decoder) return;
      PrintF("%.*s\n", len_, buffer_);
    }

    // Appends a formatted string.
    PRINTF_FORMAT(2, 3)
    void Append(const char* format, ...) {
      if (!FLAG_trace_wasm_decoder) return;
      va_list va_args;
      va_start(va_args, format);
      size_t remaining_len = kMaxLen - len_;
      Vector<char> remaining_msg_space(buffer_ + len_, remaining_len);
      int len = VSNPrintF(remaining_msg_space, format, va_args);
      va_end(va_args);
      len_ += len < 0 ? remaining_len : len;
    }

   private:
    char buffer_[kMaxLen];
    int len_ = 0;
  };

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
  // Decodes the body of a function.
  void DecodeFunctionBody() {
    TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n",
          reinterpret_cast<const void*>(this->start()),
          reinterpret_cast<const void*>(this->end()), this->pc_offset(),
          static_cast<int>(this->end() - this->start()));

    // Set up initial function block.
    {
      auto* c = PushBlock();
1397
      InitMerge(&c->start_merge, 0, [](uint32_t) -> Value { UNREACHABLE(); });
1398 1399 1400 1401
      InitMerge(&c->end_merge,
                static_cast<uint32_t>(this->sig_->return_count()),
                [&] (uint32_t i) {
                    return Value::New(this->pc_, this->sig_->GetReturn(i)); });
1402
      CALL_INTERFACE(StartFunctionBody, c);
1403 1404 1405 1406 1407
    }

    while (this->pc_ < this->end_) {  // decoding loop.
      unsigned len = 1;
      WasmOpcode opcode = static_cast<WasmOpcode>(*this->pc_);
1408 1409 1410

      CALL_INTERFACE_IF_REACHABLE(NextInstruction, opcode);

1411
#if DEBUG
1412 1413 1414
      TraceLine trace_msg;
#define TRACE_PART(...) trace_msg.Append(__VA_ARGS__)
      if (!WasmOpcodes::IsPrefixOpcode(opcode)) {
1415
        TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
1416
                   WasmOpcodes::OpcodeName(opcode));
1417
      }
1418 1419
#else
#define TRACE_PART(...)
1420 1421
#endif

1422
      FunctionSig* sig = const_cast<FunctionSig*>(kSimpleOpcodeSigs[opcode]);
1423 1424 1425 1426 1427 1428 1429 1430
      if (sig) {
        BuildSimpleOperator(opcode, sig);
      } else {
        // Complex bytecode.
        switch (opcode) {
          case kExprNop:
            break;
          case kExprBlock: {
1431
            BlockTypeImmediate<validate> imm(this, this->pc_);
1432
            if (!this->Validate(imm)) break;
1433
            PopArgs(imm.sig);
1434
            auto* block = PushBlock();
1435
            SetBlockType(block, imm);
1436
            CALL_INTERFACE_IF_REACHABLE(Block, block);
1437
            PushMergeValues(block, &block->start_merge);
1438
            len = 1 + imm.length;
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
            break;
          }
          case kExprRethrow: {
            // TODO(kschimpf): Implement.
            CHECK_PROTOTYPE_OPCODE(eh);
            OPCODE_ERROR(opcode, "not implemented yet");
            break;
          }
          case kExprThrow: {
            CHECK_PROTOTYPE_OPCODE(eh);
1449 1450 1451 1452 1453
            ExceptionIndexImmediate<Decoder::kValidate> imm(this, this->pc_);
            len = 1 + imm.length;
            if (!this->Validate(this->pc_, imm)) break;
            PopArgs(imm.exception->ToFunctionSig());
            CALL_INTERFACE_IF_REACHABLE(Throw, imm, &control_.back(),
1454
                                        vec2vec(args_));
1455
            EndControl();
1456 1457 1458 1459
            break;
          }
          case kExprTry: {
            CHECK_PROTOTYPE_OPCODE(eh);
1460
            BlockTypeImmediate<validate> imm(this, this->pc_);
1461
            if (!this->Validate(imm)) break;
1462
            PopArgs(imm.sig);
1463
            auto* try_block = PushTry();
1464 1465
            SetBlockType(try_block, imm);
            len = 1 + imm.length;
1466
            CALL_INTERFACE_IF_REACHABLE(Try, try_block);
1467
            PushMergeValues(try_block, &try_block->start_merge);
1468 1469 1470 1471 1472
            break;
          }
          case kExprCatch: {
            // TODO(kschimpf): Fix to use type signature of exception.
            CHECK_PROTOTYPE_OPCODE(eh);
1473 1474
            ExceptionIndexImmediate<Decoder::kValidate> imm(this, this->pc_);
            len = 1 + imm.length;
1475

1476
            if (!this->Validate(this->pc_, imm)) break;
1477

1478
            if (!VALIDATE(!control_.empty())) {
1479 1480 1481 1482 1483
              this->error("catch does not match any try");
              break;
            }

            Control* c = &control_.back();
1484
            if (!VALIDATE(c->is_try())) {
1485 1486 1487 1488
              this->error("catch does not match any try");
              break;
            }

1489
            if (!VALIDATE(c->is_incomplete_try())) {
1490 1491 1492 1493 1494 1495
              OPCODE_ERROR(opcode, "multiple catch blocks not implemented");
              break;
            }
            c->kind = kControlTryCatch;
            FallThruTo(c);
            stack_.resize(c->stack_depth);
1496
            const WasmExceptionSig* sig = imm.exception->sig;
1497
            for (size_t i = 0, e = sig->parameter_count(); i < e; ++i) {
1498
              Push(sig->GetParam(i));
1499
            }
1500 1501
            Vector<Value> values(stack_.data() + c->stack_depth,
                                 sig->parameter_count());
1502
            CALL_INTERFACE_IF_PARENT_REACHABLE(CatchException, imm, c, values);
1503
            c->reachability = control_at(1)->innerReachability();
1504 1505 1506 1507 1508 1509 1510 1511 1512
            break;
          }
          case kExprCatchAll: {
            // TODO(kschimpf): Implement.
            CHECK_PROTOTYPE_OPCODE(eh);
            OPCODE_ERROR(opcode, "not implemented yet");
            break;
          }
          case kExprLoop: {
1513
            BlockTypeImmediate<validate> imm(this, this->pc_);
1514
            if (!this->Validate(imm)) break;
1515
            PopArgs(imm.sig);
1516
            auto* block = PushLoop();
1517 1518
            SetBlockType(&control_.back(), imm);
            len = 1 + imm.length;
1519
            CALL_INTERFACE_IF_REACHABLE(Loop, block);
1520
            PushMergeValues(block, &block->start_merge);
1521 1522 1523
            break;
          }
          case kExprIf: {
1524
            BlockTypeImmediate<validate> imm(this, this->pc_);
1525
            if (!this->Validate(imm)) break;
1526
            auto cond = Pop(0, kWasmI32);
1527
            PopArgs(imm.sig);
1528
            if (!VALIDATE(this->ok())) break;
1529
            auto* if_block = PushIf();
1530
            SetBlockType(if_block, imm);
1531
            CALL_INTERFACE_IF_REACHABLE(If, cond, if_block);
1532
            len = 1 + imm.length;
1533
            PushMergeValues(if_block, &if_block->start_merge);
1534 1535 1536
            break;
          }
          case kExprElse: {
1537
            if (!VALIDATE(!control_.empty())) {
1538 1539 1540 1541
              this->error("else does not match any if");
              break;
            }
            Control* c = &control_.back();
1542
            if (!VALIDATE(c->is_if())) {
1543 1544 1545 1546 1547 1548 1549 1550
              this->error(this->pc_, "else does not match an if");
              break;
            }
            if (c->is_if_else()) {
              this->error(this->pc_, "else already present for if");
              break;
            }
            FallThruTo(c);
1551
            c->kind = kControlIfElse;
1552
            CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c);
1553
            PushMergeValues(c, &c->start_merge);
1554
            c->reachability = control_at(1)->innerReachability();
1555 1556 1557
            break;
          }
          case kExprEnd: {
1558
            if (!VALIDATE(!control_.empty())) {
1559 1560 1561 1562
              this->error("end does not match any if, try, or block");
              return;
            }
            Control* c = &control_.back();
1563 1564
            if (!VALIDATE(!c->is_incomplete_try())) {
              this->error(this->pc_, "missing catch in try");
1565 1566 1567
              break;
            }
            if (c->is_onearmed_if()) {
1568 1569
              // Emulate empty else arm.
              FallThruTo(c);
1570
              if (this->failed()) break;
1571 1572 1573
              CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c);
              PushMergeValues(c, &c->start_merge);
              c->reachability = control_at(1)->innerReachability();
1574
            }
1575

1576
            FallThruTo(c);
1577 1578
            // A loop just leaves the values on the stack.
            if (!c->is_loop()) PushMergeValues(c, &c->end_merge);
1579 1580 1581

            if (control_.size() == 1) {
              // If at the last (implicit) control, check we are at end.
1582
              if (!VALIDATE(this->pc_ + 1 == this->end_)) {
1583 1584 1585 1586
                this->error(this->pc_ + 1, "trailing code after function end");
                break;
              }
              last_end_found_ = true;
1587
              // The result of the block is the return value.
1588
              TRACE_PART("\n" TRACE_INST_FORMAT, startrel(this->pc_),
1589
                         "(implicit) return");
1590
              DoReturn(c, true);
1591
            }
1592

1593 1594 1595 1596 1597 1598 1599 1600
            PopControl(c);
            break;
          }
          case kExprSelect: {
            auto cond = Pop(2, kWasmI32);
            auto fval = Pop();
            auto tval = Pop(0, fval.type);
            auto* result = Push(tval.type == kWasmVar ? fval.type : tval.type);
1601
            CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result);
1602 1603 1604
            break;
          }
          case kExprBr: {
1605 1606 1607
            BreakDepthImmediate<validate> imm(this, this->pc_);
            if (!this->Validate(this->pc_, imm, control_.size())) break;
            Control* c = control_at(imm.depth);
1608
            if (!TypeCheckBreak(c)) break;
1609 1610 1611 1612
            if (control_.back().reachable()) {
              CALL_INTERFACE(Br, c);
              c->br_merge()->reached = true;
            }
1613
            len = 1 + imm.length;
1614 1615 1616 1617
            EndControl();
            break;
          }
          case kExprBrIf: {
1618
            BreakDepthImmediate<validate> imm(this, this->pc_);
1619
            auto cond = Pop(0, kWasmI32);
1620
            if (this->failed()) break;
1621 1622
            if (!this->Validate(this->pc_, imm, control_.size())) break;
            Control* c = control_at(imm.depth);
1623
            if (!TypeCheckBreak(c)) break;
1624 1625 1626 1627
            if (control_.back().reachable()) {
              CALL_INTERFACE(BrIf, cond, c);
              c->br_merge()->reached = true;
            }
1628
            len = 1 + imm.length;
1629 1630 1631
            break;
          }
          case kExprBrTable: {
1632 1633
            BranchTableImmediate<validate> imm(this, this->pc_);
            BranchTableIterator<validate> iterator(this, imm);
1634
            auto key = Pop(0, kWasmI32);
1635
            if (this->failed()) break;
1636
            if (!this->Validate(this->pc_, imm, control_.size())) break;
1637
            uint32_t br_arity = 0;
1638
            std::vector<bool> br_targets(control_.size());
1639 1640 1641 1642
            while (iterator.has_next()) {
              const uint32_t i = iterator.cur_index();
              const byte* pos = iterator.pc();
              uint32_t target = iterator.next();
1643
              if (!VALIDATE(target < control_.size())) {
1644 1645 1646
                this->errorf(pos,
                             "improper branch in br_table target %u (depth %u)",
                             i, target);
1647 1648
                break;
              }
1649 1650 1651
              // Avoid redundant break target checks.
              if (br_targets[target]) continue;
              br_targets[target] = true;
1652 1653
              // Check that label types match up.
              Control* c = control_at(target);
1654
              uint32_t arity = c->br_merge()->arity;
1655
              if (i == 0) {
1656 1657
                br_arity = arity;
              } else if (!VALIDATE(br_arity == arity)) {
1658
                this->errorf(pos,
1659
                             "inconsistent arity in br_table target %u"
1660
                             " (previous was %u, this one %u)",
1661
                             i, br_arity, arity);
1662
              }
1663
              if (!TypeCheckBreak(c)) break;
1664
            }
1665
            if (this->failed()) break;
1666

1667
            if (control_.back().reachable()) {
1668
              CALL_INTERFACE(BrTable, imm, key);
1669 1670 1671 1672 1673 1674

              for (uint32_t depth = control_depth(); depth-- > 0;) {
                if (!br_targets[depth]) continue;
                control_at(depth)->br_merge()->reached = true;
              }
            }
1675

1676 1677 1678 1679 1680
            len = 1 + iterator.length();
            EndControl();
            break;
          }
          case kExprReturn: {
1681
            DoReturn(&control_.back(), false);
1682 1683 1684
            break;
          }
          case kExprUnreachable: {
1685
            CALL_INTERFACE_IF_REACHABLE(Unreachable);
1686 1687 1688 1689
            EndControl();
            break;
          }
          case kExprI32Const: {
1690
            ImmI32Immediate<validate> imm(this, this->pc_);
1691
            auto* value = Push(kWasmI32);
1692 1693
            CALL_INTERFACE_IF_REACHABLE(I32Const, value, imm.value);
            len = 1 + imm.length;
1694 1695 1696
            break;
          }
          case kExprI64Const: {
1697
            ImmI64Immediate<validate> imm(this, this->pc_);
1698
            auto* value = Push(kWasmI64);
1699 1700
            CALL_INTERFACE_IF_REACHABLE(I64Const, value, imm.value);
            len = 1 + imm.length;
1701 1702 1703
            break;
          }
          case kExprF32Const: {
1704
            ImmF32Immediate<validate> imm(this, this->pc_);
1705
            auto* value = Push(kWasmF32);
1706 1707
            CALL_INTERFACE_IF_REACHABLE(F32Const, value, imm.value);
            len = 1 + imm.length;
1708 1709 1710
            break;
          }
          case kExprF64Const: {
1711
            ImmF64Immediate<validate> imm(this, this->pc_);
1712
            auto* value = Push(kWasmF64);
1713 1714
            CALL_INTERFACE_IF_REACHABLE(F64Const, value, imm.value);
            len = 1 + imm.length;
1715 1716
            break;
          }
1717 1718 1719 1720 1721 1722 1723
          case kExprRefNull: {
            CHECK_PROTOTYPE_OPCODE(anyref);
            auto* value = Push(kWasmAnyRef);
            CALL_INTERFACE_IF_REACHABLE(RefNull, value);
            len = 1;
            break;
          }
1724
          case kExprGetLocal: {
1725 1726 1727 1728 1729
            LocalIndexImmediate<Decoder::kValidate> imm(this, this->pc_);
            if (!this->Validate(this->pc_, imm)) break;
            auto* value = Push(imm.type);
            CALL_INTERFACE_IF_REACHABLE(GetLocal, value, imm);
            len = 1 + imm.length;
1730 1731 1732
            break;
          }
          case kExprSetLocal: {
1733 1734 1735 1736 1737
            LocalIndexImmediate<Decoder::kValidate> imm(this, this->pc_);
            if (!this->Validate(this->pc_, imm)) break;
            auto value = Pop(0, local_type_vec_[imm.index]);
            CALL_INTERFACE_IF_REACHABLE(SetLocal, value, imm);
            len = 1 + imm.length;
1738 1739 1740
            break;
          }
          case kExprTeeLocal: {
1741 1742 1743
            LocalIndexImmediate<Decoder::kValidate> imm(this, this->pc_);
            if (!this->Validate(this->pc_, imm)) break;
            auto value = Pop(0, local_type_vec_[imm.index]);
1744
            auto* result = Push(value.type);
1745 1746
            CALL_INTERFACE_IF_REACHABLE(TeeLocal, value, result, imm);
            len = 1 + imm.length;
1747 1748 1749
            break;
          }
          case kExprDrop: {
1750
            auto value = Pop();
1751
            CALL_INTERFACE_IF_REACHABLE(Drop, value);
1752 1753 1754
            break;
          }
          case kExprGetGlobal: {
1755 1756 1757 1758 1759
            GlobalIndexImmediate<validate> imm(this, this->pc_);
            len = 1 + imm.length;
            if (!this->Validate(this->pc_, imm)) break;
            auto* result = Push(imm.type);
            CALL_INTERFACE_IF_REACHABLE(GetGlobal, result, imm);
1760 1761 1762
            break;
          }
          case kExprSetGlobal: {
1763 1764 1765 1766
            GlobalIndexImmediate<validate> imm(this, this->pc_);
            len = 1 + imm.length;
            if (!this->Validate(this->pc_, imm)) break;
            if (!VALIDATE(imm.global->mutability)) {
1767
              this->errorf(this->pc_, "immutable global #%u cannot be assigned",
1768
                           imm.index);
1769 1770
              break;
            }
1771 1772
            auto value = Pop(0, imm.type);
            CALL_INTERFACE_IF_REACHABLE(SetGlobal, value, imm);
1773 1774 1775
            break;
          }
          case kExprI32LoadMem8S:
1776
            len = 1 + DecodeLoadMem(LoadType::kI32Load8S);
1777 1778
            break;
          case kExprI32LoadMem8U:
1779
            len = 1 + DecodeLoadMem(LoadType::kI32Load8U);
1780 1781
            break;
          case kExprI32LoadMem16S:
1782
            len = 1 + DecodeLoadMem(LoadType::kI32Load16S);
1783 1784
            break;
          case kExprI32LoadMem16U:
1785
            len = 1 + DecodeLoadMem(LoadType::kI32Load16U);
1786 1787
            break;
          case kExprI32LoadMem:
1788
            len = 1 + DecodeLoadMem(LoadType::kI32Load);
1789 1790
            break;
          case kExprI64LoadMem8S:
1791
            len = 1 + DecodeLoadMem(LoadType::kI64Load8S);
1792 1793
            break;
          case kExprI64LoadMem8U:
1794
            len = 1 + DecodeLoadMem(LoadType::kI64Load8U);
1795 1796
            break;
          case kExprI64LoadMem16S:
1797
            len = 1 + DecodeLoadMem(LoadType::kI64Load16S);
1798 1799
            break;
          case kExprI64LoadMem16U:
1800
            len = 1 + DecodeLoadMem(LoadType::kI64Load16U);
1801 1802
            break;
          case kExprI64LoadMem32S:
1803
            len = 1 + DecodeLoadMem(LoadType::kI64Load32S);
1804 1805
            break;
          case kExprI64LoadMem32U:
1806
            len = 1 + DecodeLoadMem(LoadType::kI64Load32U);
1807 1808
            break;
          case kExprI64LoadMem:
1809
            len = 1 + DecodeLoadMem(LoadType::kI64Load);
1810 1811
            break;
          case kExprF32LoadMem:
1812
            len = 1 + DecodeLoadMem(LoadType::kF32Load);
1813 1814
            break;
          case kExprF64LoadMem:
1815
            len = 1 + DecodeLoadMem(LoadType::kF64Load);
1816 1817
            break;
          case kExprI32StoreMem8:
1818
            len = 1 + DecodeStoreMem(StoreType::kI32Store8);
1819 1820
            break;
          case kExprI32StoreMem16:
1821
            len = 1 + DecodeStoreMem(StoreType::kI32Store16);
1822 1823
            break;
          case kExprI32StoreMem:
1824
            len = 1 + DecodeStoreMem(StoreType::kI32Store);
1825 1826
            break;
          case kExprI64StoreMem8:
1827
            len = 1 + DecodeStoreMem(StoreType::kI64Store8);
1828 1829
            break;
          case kExprI64StoreMem16:
1830
            len = 1 + DecodeStoreMem(StoreType::kI64Store16);
1831 1832
            break;
          case kExprI64StoreMem32:
1833
            len = 1 + DecodeStoreMem(StoreType::kI64Store32);
1834 1835
            break;
          case kExprI64StoreMem:
1836
            len = 1 + DecodeStoreMem(StoreType::kI64Store);
1837 1838
            break;
          case kExprF32StoreMem:
1839
            len = 1 + DecodeStoreMem(StoreType::kF32Store);
1840 1841
            break;
          case kExprF64StoreMem:
1842
            len = 1 + DecodeStoreMem(StoreType::kF64Store);
1843 1844 1845
            break;
          case kExprGrowMemory: {
            if (!CheckHasMemory()) break;
1846 1847
            MemoryIndexImmediate<validate> imm(this, this->pc_);
            len = 1 + imm.length;
1848
            DCHECK_NOT_NULL(this->module_);
1849
            if (!VALIDATE(this->module_->origin == kWasmOrigin)) {
1850 1851 1852 1853 1854
              this->error("grow_memory is not supported for asmjs modules");
              break;
            }
            auto value = Pop(0, kWasmI32);
            auto* result = Push(kWasmI32);
1855
            CALL_INTERFACE_IF_REACHABLE(GrowMemory, value, result);
1856 1857 1858 1859
            break;
          }
          case kExprMemorySize: {
            if (!CheckHasMemory()) break;
1860
            MemoryIndexImmediate<validate> imm(this, this->pc_);
1861
            auto* result = Push(kWasmI32);
1862
            len = 1 + imm.length;
1863
            CALL_INTERFACE_IF_REACHABLE(CurrentMemoryPages, result);
1864 1865 1866
            break;
          }
          case kExprCallFunction: {
1867 1868 1869
            CallFunctionImmediate<validate> imm(this, this->pc_);
            len = 1 + imm.length;
            if (!this->Validate(this->pc_, imm)) break;
1870
            // TODO(clemensh): Better memory management.
1871 1872 1873
            PopArgs(imm.sig);
            auto* returns = PushReturns(imm.sig);
            CALL_INTERFACE_IF_REACHABLE(CallDirect, imm, args_.data(), returns);
1874 1875 1876
            break;
          }
          case kExprCallIndirect: {
1877 1878 1879
            CallIndirectImmediate<validate> imm(this, this->pc_);
            len = 1 + imm.length;
            if (!this->Validate(this->pc_, imm)) break;
1880
            auto index = Pop(0, kWasmI32);
1881 1882 1883 1884
            PopArgs(imm.sig);
            auto* returns = PushReturns(imm.sig);
            CALL_INTERFACE_IF_REACHABLE(CallIndirect, index, imm, args_.data(),
                                        returns);
1885 1886
            break;
          }
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
          case kNumericPrefix: {
            CHECK_PROTOTYPE_OPCODE(sat_f2i_conversions);
            ++len;
            byte numeric_index = this->template read_u8<validate>(
                this->pc_ + 1, "numeric index");
            opcode = static_cast<WasmOpcode>(opcode << 8 | numeric_index);
            TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
                       WasmOpcodes::OpcodeName(opcode));
            sig = WasmOpcodes::Signature(opcode);
            if (sig == nullptr) {
              this->errorf(this->pc_, "Unrecognized numeric opcode: %x\n",
                           opcode);
              return;
            }
            BuildSimpleOperator(opcode, sig);
            break;
          }
1904 1905 1906 1907 1908 1909
          case kSimdPrefix: {
            CHECK_PROTOTYPE_OPCODE(simd);
            len++;
            byte simd_index =
                this->template read_u8<validate>(this->pc_ + 1, "simd index");
            opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index);
1910
            TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
1911
                       WasmOpcodes::OpcodeName(opcode));
1912 1913 1914 1915 1916
            len += DecodeSimdOpcode(opcode);
            break;
          }
          case kAtomicPrefix: {
            CHECK_PROTOTYPE_OPCODE(threads);
1917
            if (!CheckHasSharedMemory()) break;
1918 1919 1920 1921
            len++;
            byte atomic_index =
                this->template read_u8<validate>(this->pc_ + 1, "atomic index");
            opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index);
1922
            TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_),
1923
                       WasmOpcodes::OpcodeName(opcode));
1924
            len += DecodeAtomicOpcode(opcode);
1925 1926
            break;
          }
1927 1928 1929 1930 1931 1932 1933 1934
// Note that prototype opcodes are not handled in the fastpath
// above this switch, to avoid checking a feature flag.
#define SIMPLE_PROTOTYPE_CASE(name, opc, sig) \
  case kExpr##name: /* fallthrough */
            FOREACH_SIMPLE_PROTOTYPE_OPCODE(SIMPLE_PROTOTYPE_CASE)
#undef SIMPLE_PROTOTYPE_CASE
            BuildSimplePrototypeOperator(opcode);
            break;
1935 1936
          default: {
            // Deal with special asmjs opcodes.
1937 1938
            if (this->module_ != nullptr &&
                this->module_->origin == kAsmJsOrigin) {
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
              sig = WasmOpcodes::AsmjsSignature(opcode);
              if (sig) {
                BuildSimpleOperator(opcode, sig);
              }
            } else {
              this->error("Invalid opcode");
              return;
            }
          }
        }
      }

#if DEBUG
      if (FLAG_trace_wasm_decoder) {
1953
        TRACE_PART(" ");
1954 1955
        for (Control& c : control_) {
          switch (c.kind) {
1956
            case kControlIf:
1957
              TRACE_PART("I");
1958 1959
              break;
            case kControlBlock:
1960
              TRACE_PART("B");
1961 1962
              break;
            case kControlLoop:
1963
              TRACE_PART("L");
1964 1965
              break;
            case kControlTry:
1966
              TRACE_PART("T");
1967 1968 1969 1970
              break;
            default:
              break;
          }
1971 1972 1973
          if (c.start_merge.arity) TRACE_PART("%u-", c.start_merge.arity);
          TRACE_PART("%u", c.end_merge.arity);
          if (!c.reachable()) TRACE_PART("%c", c.unreachable() ? '*' : '#');
1974
        }
1975
        TRACE_PART(" | ");
1976 1977 1978 1979 1980 1981
        for (size_t i = 0; i < stack_.size(); ++i) {
          auto& val = stack_[i];
          WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc);
          if (WasmOpcodes::IsPrefixOpcode(opcode)) {
            opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1));
          }
1982
          TRACE_PART(" %c@%d:%s", ValueTypes::ShortNameOf(val.type),
1983 1984
                     static_cast<int>(val.pc - this->start_),
                     WasmOpcodes::OpcodeName(opcode));
1985
          // If the decoder failed, don't try to decode the immediates, as this
1986 1987
          // can trigger a DCHECK failure.
          if (this->failed()) continue;
1988 1989
          switch (opcode) {
            case kExprI32Const: {
1990 1991
              ImmI32Immediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%d]", imm.value);
1992 1993
              break;
            }
1994 1995 1996
            case kExprGetLocal:
            case kExprSetLocal:
            case kExprTeeLocal: {
1997 1998
              LocalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%u]", imm.index);
1999 2000
              break;
            }
2001 2002
            case kExprGetGlobal:
            case kExprSetGlobal: {
2003 2004
              GlobalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc);
              TRACE_PART("[%u]", imm.index);
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
              break;
            }
            default:
              break;
          }
        }
      }
#endif
      this->pc_ += len;
    }  // end decode loop
2015 2016 2017
    if (!VALIDATE(this->pc_ == this->end_) && this->ok()) {
      this->error("Beyond end of code");
    }
2018 2019 2020 2021 2022 2023
  }

  void EndControl() {
    DCHECK(!control_.empty());
    auto* current = &control_.back();
    stack_.resize(current->stack_depth);
2024
    CALL_INTERFACE_IF_REACHABLE(EndControl, current);
2025
    current->reachability = kUnreachable;
2026 2027
  }

2028 2029 2030 2031 2032 2033 2034 2035 2036
  template<typename func>
  void InitMerge(Merge<Value>* merge, uint32_t arity, func get_val) {
    merge->arity = arity;
    if (arity == 1) {
      merge->vals.first = get_val(0);
    } else if (arity > 1) {
      merge->vals.array = zone_->NewArray<Value>(arity);
      for (unsigned i = 0; i < arity; i++) {
        merge->vals.array[i] = get_val(i);
2037 2038 2039 2040
      }
    }
  }

2041 2042
  void SetBlockType(Control* c, BlockTypeImmediate<validate>& imm) {
    DCHECK_EQ(imm.in_arity(), this->args_.size());
2043 2044
    const byte* pc = this->pc_;
    Value* args = this->args_.data();
2045 2046
    InitMerge(&c->end_merge, imm.out_arity(), [pc, &imm](uint32_t i) {
      return Value::New(pc, imm.out_type(i));
2047
    });
2048
    InitMerge(&c->start_merge, imm.in_arity(),
2049
              [args](uint32_t i) { return args[i]; });
2050 2051 2052 2053 2054 2055
  }

  // Pops arguments as required by signature into {args_}.
  V8_INLINE void PopArgs(FunctionSig* sig) {
    int count = sig ? static_cast<int>(sig->parameter_count()) : 0;
    args_.resize(count);
2056
    for (int i = count - 1; i >= 0; --i) {
2057
      args_[i] = Pop(i, sig->GetParam(i));
2058 2059 2060 2061 2062 2063 2064 2065
    }
  }

  ValueType GetReturnType(FunctionSig* sig) {
    DCHECK_GE(1, sig->return_count());
    return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn();
  }

2066 2067 2068 2069 2070 2071
  Control* PushControl(Control&& new_control) {
    Reachability reachability =
        control_.empty() ? kReachable : control_.back().innerReachability();
    control_.emplace_back(std::move(new_control));
    Control* c = &control_.back();
    c->reachability = reachability;
2072
    c->start_merge.reached = c->reachable();
2073
    return c;
2074 2075
  }

2076 2077 2078
  Control* PushBlock() {
    return PushControl(Control::Block(this->pc_, stack_size()));
  }
2079
  Control* PushLoop() {
2080
    return PushControl(Control::Loop(this->pc_, stack_size()));
2081 2082
  }
  Control* PushIf() {
2083
    return PushControl(Control::If(this->pc_, stack_size()));
2084 2085 2086
  }
  Control* PushTry() {
    // current_catch_ = static_cast<int32_t>(control_.size() - 1);
2087
    return PushControl(Control::Try(this->pc_, stack_size()));
2088 2089 2090 2091
  }

  void PopControl(Control* c) {
    DCHECK_EQ(c, &control_.back());
2092
    CALL_INTERFACE_IF_PARENT_REACHABLE(PopControl, c);
2093
    bool reached = c->end_merge.reached;
2094
    control_.pop_back();
2095 2096 2097 2098 2099
    // If the parent block was reachable before, but the popped control does not
    // return to here, this block becomes indirectly unreachable.
    if (!control_.empty() && !reached && control_.back().reachable()) {
      control_.back().reachability = kSpecOnlyReachable;
    }
2100 2101
  }

2102
  int DecodeLoadMem(LoadType type, int prefix_len = 0) {
2103
    if (!CheckHasMemory()) return 0;
2104 2105
    MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len,
                                        type.size_log_2());
2106
    auto index = Pop(0, kWasmI32);
2107
    auto* result = Push(type.value_type());
2108 2109
    CALL_INTERFACE_IF_REACHABLE(LoadMem, type, imm, index, result);
    return imm.length;
2110 2111
  }

2112
  int DecodeStoreMem(StoreType store, int prefix_len = 0) {
2113
    if (!CheckHasMemory()) return 0;
2114 2115
    MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len,
                                        store.size_log_2());
2116
    auto value = Pop(1, store.value_type());
2117
    auto index = Pop(0, kWasmI32);
2118 2119
    CALL_INTERFACE_IF_REACHABLE(StoreMem, store, imm, index, value);
    return imm.length;
2120 2121 2122
  }

  unsigned SimdExtractLane(WasmOpcode opcode, ValueType type) {
2123 2124
    SimdLaneImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2125
      Value inputs[] = {Pop(0, kWasmS128)};
2126
      auto* result = Push(type);
2127 2128
      CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs),
                                  result);
2129
    }
2130
    return imm.length;
2131 2132 2133
  }

  unsigned SimdReplaceLane(WasmOpcode opcode, ValueType type) {
2134 2135
    SimdLaneImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2136 2137
      Value inputs[2];
      inputs[1] = Pop(1, type);
2138 2139
      inputs[0] = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2140 2141
      CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs),
                                  result);
2142
    }
2143
    return imm.length;
2144 2145 2146
  }

  unsigned SimdShiftOp(WasmOpcode opcode) {
2147 2148
    SimdShiftImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, opcode, imm)) {
2149 2150
      auto input = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2151
      CALL_INTERFACE_IF_REACHABLE(SimdShiftOp, opcode, imm, input, result);
2152
    }
2153
    return imm.length;
2154 2155 2156
  }

  unsigned Simd8x16ShuffleOp() {
2157 2158
    Simd8x16ShuffleImmediate<validate> imm(this, this->pc_);
    if (this->Validate(this->pc_, imm)) {
2159 2160 2161
      auto input1 = Pop(1, kWasmS128);
      auto input0 = Pop(0, kWasmS128);
      auto* result = Push(kWasmS128);
2162
      CALL_INTERFACE_IF_REACHABLE(Simd8x16ShuffleOp, imm, input0, input1,
2163
                                  result);
2164 2165 2166 2167 2168 2169 2170 2171
    }
    return 16;
  }

  unsigned DecodeSimdOpcode(WasmOpcode opcode) {
    unsigned len = 0;
    switch (opcode) {
      case kExprF32x4ExtractLane: {
2172
        len = SimdExtractLane(opcode, kWasmF32);
2173 2174 2175 2176 2177
        break;
      }
      case kExprI32x4ExtractLane:
      case kExprI16x8ExtractLane:
      case kExprI8x16ExtractLane: {
2178
        len = SimdExtractLane(opcode, kWasmI32);
2179 2180 2181
        break;
      }
      case kExprF32x4ReplaceLane: {
2182
        len = SimdReplaceLane(opcode, kWasmF32);
2183 2184 2185 2186 2187
        break;
      }
      case kExprI32x4ReplaceLane:
      case kExprI16x8ReplaceLane:
      case kExprI8x16ReplaceLane: {
2188
        len = SimdReplaceLane(opcode, kWasmI32);
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
        break;
      }
      case kExprI32x4Shl:
      case kExprI32x4ShrS:
      case kExprI32x4ShrU:
      case kExprI16x8Shl:
      case kExprI16x8ShrS:
      case kExprI16x8ShrU:
      case kExprI8x16Shl:
      case kExprI8x16ShrS:
      case kExprI8x16ShrU: {
        len = SimdShiftOp(opcode);
        break;
      }
      case kExprS8x16Shuffle: {
        len = Simd8x16ShuffleOp();
        break;
      }
      case kExprS128LoadMem:
2208
        len = DecodeLoadMem(LoadType::kS128Load, 1);
2209 2210
        break;
      case kExprS128StoreMem:
2211
        len = DecodeStoreMem(StoreType::kS128Store, 1);
2212 2213 2214
        break;
      default: {
        FunctionSig* sig = WasmOpcodes::Signature(opcode);
2215
        if (!VALIDATE(sig != nullptr)) {
2216 2217 2218
          this->error("invalid simd opcode");
          break;
        }
2219 2220
        PopArgs(sig);
        auto* results =
2221
            sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig));
2222
        CALL_INTERFACE_IF_REACHABLE(SimdOp, opcode, vec2vec(args_), results);
2223 2224 2225 2226 2227
      }
    }
    return len;
  }

2228
  unsigned DecodeAtomicOpcode(WasmOpcode opcode) {
2229
    unsigned len = 0;
2230
    ValueType ret_type;
2231
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
2232
    if (sig != nullptr) {
2233 2234
      MachineType memtype;
      switch (opcode) {
2235 2236 2237 2238 2239
#define CASE_ATOMIC_STORE_OP(Name, Type) \
  case kExpr##Name: {                    \
    memtype = MachineType::Type();       \
    ret_type = kWasmStmt;                \
    break;                               \
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
  }
        ATOMIC_STORE_OP_LIST(CASE_ATOMIC_STORE_OP)
#undef CASE_ATOMIC_OP
#define CASE_ATOMIC_OP(Name, Type) \
  case kExpr##Name: {              \
    memtype = MachineType::Type(); \
    ret_type = GetReturnType(sig); \
    break;                         \
  }
        ATOMIC_OP_LIST(CASE_ATOMIC_OP)
#undef CASE_ATOMIC_OP
        default:
          this->error("invalid atomic opcode");
2253
          return 0;
2254
      }
2255
      MemoryAccessImmediate<validate> imm(
2256
          this, this->pc_ + 1, ElementSizeLog2Of(memtype.representation()));
2257
      len += imm.length;
2258
      PopArgs(sig);
2259
      auto result = ret_type == kWasmStmt ? nullptr : Push(GetReturnType(sig));
2260
      CALL_INTERFACE_IF_REACHABLE(AtomicOp, opcode, vec2vec(args_), imm,
2261
                                  result);
2262 2263 2264 2265 2266 2267
    } else {
      this->error("invalid atomic opcode");
    }
    return len;
  }

2268
  void DoReturn(Control* c, bool implicit) {
2269
    int return_count = static_cast<int>(this->sig_->return_count());
2270
    args_.resize(return_count);
2271 2272 2273

    // Pop return values off the stack in reverse order.
    for (int i = return_count - 1; i >= 0; --i) {
2274
      args_[i] = Pop(i, this->sig_->GetReturn(i));
2275 2276
    }

2277 2278 2279
    // Simulate that an implicit return morally comes after the current block.
    if (implicit && c->end_merge.reached) c->reachability = kReachable;
    CALL_INTERFACE_IF_REACHABLE(DoReturn, vec2vec(args_), implicit);
2280

2281 2282 2283 2284
    EndControl();
  }

  inline Value* Push(ValueType type) {
2285
    DCHECK_NE(kWasmStmt, type);
2286 2287 2288 2289
    stack_.push_back(Value::New(this->pc_, type));
    return &stack_.back();
  }

2290
  void PushMergeValues(Control* c, Merge<Value>* merge) {
2291
    DCHECK_EQ(c, &control_.back());
2292
    DCHECK(merge == &c->start_merge || merge == &c->end_merge);
2293
    stack_.resize(c->stack_depth);
2294 2295
    if (merge->arity == 1) {
      stack_.push_back(merge->vals.first);
2296
    } else {
2297 2298
      for (unsigned i = 0; i < merge->arity; i++) {
        stack_.push_back(merge->vals.array[i]);
2299 2300
      }
    }
2301
    DCHECK_EQ(c->stack_depth + merge->arity, stack_.size());
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
  }

  Value* PushReturns(FunctionSig* sig) {
    size_t return_count = sig->return_count();
    if (return_count == 0) return nullptr;
    size_t old_size = stack_.size();
    for (size_t i = 0; i < return_count; ++i) {
      Push(sig->GetReturn(i));
    }
    return stack_.data() + old_size;
  }

  Value Pop(int index, ValueType expected) {
    auto val = Pop();
2316 2317
    if (!VALIDATE(val.type == expected || val.type == kWasmVar ||
                  expected == kWasmVar)) {
2318 2319
      this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s",
                   SafeOpcodeNameAt(this->pc_), index,
2320 2321
                   ValueTypes::TypeName(expected), SafeOpcodeNameAt(val.pc),
                   ValueTypes::TypeName(val.type));
2322 2323 2324 2325 2326 2327
    }
    return val;
  }

  Value Pop() {
    DCHECK(!control_.empty());
2328
    uint32_t limit = control_.back().stack_depth;
2329 2330
    if (stack_.size() <= limit) {
      // Popping past the current control start in reachable code.
2331
      if (!VALIDATE(control_.back().unreachable())) {
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
        this->errorf(this->pc_, "%s found empty stack",
                     SafeOpcodeNameAt(this->pc_));
      }
      return Value::Unreachable(this->pc_);
    }
    auto val = stack_.back();
    stack_.pop_back();
    return val;
  }

  int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); }

  void FallThruTo(Control* c) {
    DCHECK_EQ(c, &control_.back());
    if (!TypeCheckFallThru(c)) return;
2347
    if (!c->reachable()) return;
2348

2349 2350
    if (!c->is_loop()) CALL_INTERFACE(FallThruTo, c);
    c->end_merge.reached = true;
2351 2352
  }

2353 2354 2355 2356 2357 2358 2359
  bool TypeCheckMergeValues(Control* c, Merge<Value>* merge) {
    DCHECK(merge == &c->start_merge || merge == &c->end_merge);
    DCHECK_GE(stack_.size(), c->stack_depth + merge->arity);
    // Typecheck the topmost {merge->arity} values on the stack.
    for (uint32_t i = 0; i < merge->arity; ++i) {
      auto& val = GetMergeValueFromStack(c, merge, i);
      auto& old = (*merge)[i];
2360
      if (val.type != old.type) {
2361 2362 2363 2364
        // If {val.type} is polymorphic, which results from unreachable, make
        // it more specific by using the merge value's expected type.
        // If it is not polymorphic, this is a type error.
        if (!VALIDATE(val.type == kWasmVar)) {
2365
          this->errorf(
2366
              this->pc_, "type error in merge[%u] (expected %s, got %s)", i,
2367
              ValueTypes::TypeName(old.type), ValueTypes::TypeName(val.type));
2368 2369
          return false;
        }
2370
        val.type = old.type;
2371 2372 2373 2374 2375 2376 2377 2378 2379
      }
    }

    return true;
  }

  bool TypeCheckFallThru(Control* c) {
    DCHECK_EQ(c, &control_.back());
    if (!validate) return true;
2380
    uint32_t expected = c->end_merge.arity;
2381 2382
    DCHECK_GE(stack_.size(), c->stack_depth);
    uint32_t actual = static_cast<uint32_t>(stack_.size()) - c->stack_depth;
2383 2384
    // Fallthrus must match the arity of the control exactly.
    if (!InsertUnreachablesIfNecessary(expected, actual) || actual > expected) {
2385 2386 2387 2388
      this->errorf(
          this->pc_,
          "expected %u elements on the stack for fallthru to @%d, found %u",
          expected, startrel(c->pc), actual);
2389 2390 2391
      return false;
    }

2392
    return TypeCheckMergeValues(c, &c->end_merge);
2393 2394
  }

2395
  bool TypeCheckBreak(Control* c) {
2396
    // Breaks must have at least the number of values expected; can have more.
2397
    uint32_t expected = c->br_merge()->arity;
2398 2399 2400
    DCHECK_GE(stack_.size(), control_.back().stack_depth);
    uint32_t actual =
        static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth;
2401
    if (!InsertUnreachablesIfNecessary(expected, actual)) {
2402 2403 2404
      this->errorf(this->pc_,
                   "expected %u elements on the stack for br to @%d, found %u",
                   expected, startrel(c->pc), actual);
2405 2406
      return false;
    }
2407
    return TypeCheckMergeValues(c, c->br_merge());
2408 2409
  }

2410 2411
  inline bool InsertUnreachablesIfNecessary(uint32_t expected,
                                            uint32_t actual) {
2412 2413
    if (V8_LIKELY(actual >= expected)) {
      return true;  // enough actual values are there.
2414
    }
2415
    if (!VALIDATE(control_.back().unreachable())) {
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
      // There aren't enough values on the stack.
      return false;
    }
    // A slow path. When the actual number of values on the stack is less
    // than the expected number of values and the current control is
    // unreachable, insert unreachable values below the actual values.
    // This simplifies {TypeCheckMergeValues}.
    auto pos = stack_.begin() + (stack_.size() - actual);
    stack_.insert(pos, (expected - actual), Value::Unreachable(this->pc_));
    return true;
2426 2427
  }

2428 2429 2430
  virtual void onFirstError() {
    this->end_ = this->pc_;  // Terminate decoding loop.
    TRACE(" !%s\n", this->error_msg_.c_str());
2431
    CALL_INTERFACE(OnFirstError);
2432 2433
  }

2434
  void BuildSimplePrototypeOperator(WasmOpcode opcode) {
2435 2436 2437
    if (WasmOpcodes::IsSignExtensionOpcode(opcode)) {
      RET_ON_PROTOTYPE_OPCODE(se);
    }
2438 2439 2440
    if (WasmOpcodes::IsAnyRefOpcode(opcode)) {
      RET_ON_PROTOTYPE_OPCODE(anyref);
    }
2441 2442 2443
    FunctionSig* sig = WasmOpcodes::Signature(opcode);
    BuildSimpleOperator(opcode, sig);
  }
2444

2445
  inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) {
2446 2447 2448 2449 2450
    switch (sig->parameter_count()) {
      case 1: {
        auto val = Pop(0, sig->GetParam(0));
        auto* ret =
            sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
2451
        CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, sig, val, ret);
2452 2453 2454 2455 2456 2457 2458
        break;
      }
      case 2: {
        auto rval = Pop(1, sig->GetParam(1));
        auto lval = Pop(0, sig->GetParam(0));
        auto* ret =
            sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0));
2459
        CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, sig, lval, rval, ret);
2460 2461 2462 2463 2464 2465 2466 2467
        break;
      }
      default:
        UNREACHABLE();
    }
  }
};

2468 2469 2470 2471
#undef CALL_INTERFACE
#undef CALL_INTERFACE_IF_REACHABLE
#undef CALL_INTERFACE_IF_PARENT_REACHABLE

2472
class EmptyInterface {
2473
 public:
2474 2475
  static constexpr wasm::Decoder::ValidateFlag validate =
      wasm::Decoder::kValidate;
2476 2477 2478
  using Value = ValueBase;
  using Control = ControlBase<Value>;
  using Decoder = WasmFullDecoder<validate, EmptyInterface>;
2479 2480 2481 2482 2483 2484 2485

#define DEFINE_EMPTY_CALLBACK(name, ...) \
  void name(Decoder* decoder, ##__VA_ARGS__) {}
  INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK)
#undef DEFINE_EMPTY_CALLBACK
};

2486
#undef TRACE
2487
#undef TRACE_INST_FORMAT
2488 2489
#undef VALIDATE
#undef CHECK_PROTOTYPE_OPCODE
2490
#undef OPCODE_ERROR
2491

2492 2493 2494 2495 2496
}  // namespace wasm
}  // namespace internal
}  // namespace v8

#endif  // V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_