wasm-interpreter.cc 127 KB
Newer Older
1 2 3 4
// Copyright 2016 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.

5
#include <atomic>
6 7
#include <type_traits>

8
#include "src/wasm/wasm-interpreter.h"
9

10
#include "src/assembler-inl.h"
11
#include "src/boxed-float.h"
12
#include "src/compiler/wasm-compiler.h"
13
#include "src/conversions.h"
14
#include "src/identity-map.h"
15
#include "src/objects-inl.h"
16
#include "src/trap-handler/trap-handler.h"
17
#include "src/utils.h"
18
#include "src/wasm/decoder.h"
19
#include "src/wasm/function-body-decoder-impl.h"
20
#include "src/wasm/function-body-decoder.h"
21
#include "src/wasm/memory-tracing.h"
22
#include "src/wasm/wasm-engine.h"
23
#include "src/wasm/wasm-external-refs.h"
24
#include "src/wasm/wasm-limits.h"
25
#include "src/wasm/wasm-module.h"
26
#include "src/wasm/wasm-objects-inl.h"
27

28 29
#include "src/zone/accounting-allocator.h"
#include "src/zone/zone-containers.h"
30 31 32 33 34 35 36 37 38 39

namespace v8 {
namespace internal {
namespace wasm {

#define TRACE(...)                                        \
  do {                                                    \
    if (FLAG_trace_wasm_interpreter) PrintF(__VA_ARGS__); \
  } while (false)

40 41 42 43 44 45
#if V8_TARGET_BIG_ENDIAN
#define LANE(i, type) ((sizeof(type.val) / sizeof(type.val[0])) - (i)-1)
#else
#define LANE(i, type) (i)
#endif

46 47
#define FOREACH_INTERNAL_OPCODE(V) V(Breakpoint, 0xFF)

48
#define WASM_CTYPES(V) \
49
  V(I32, int32_t) V(I64, int64_t) V(F32, float) V(F64, double) V(S128, Simd128)
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#define FOREACH_SIMPLE_BINOP(V) \
  V(I32Add, uint32_t, +)        \
  V(I32Sub, uint32_t, -)        \
  V(I32Mul, uint32_t, *)        \
  V(I32And, uint32_t, &)        \
  V(I32Ior, uint32_t, |)        \
  V(I32Xor, uint32_t, ^)        \
  V(I32Eq, uint32_t, ==)        \
  V(I32Ne, uint32_t, !=)        \
  V(I32LtU, uint32_t, <)        \
  V(I32LeU, uint32_t, <=)       \
  V(I32GtU, uint32_t, >)        \
  V(I32GeU, uint32_t, >=)       \
  V(I32LtS, int32_t, <)         \
  V(I32LeS, int32_t, <=)        \
  V(I32GtS, int32_t, >)         \
  V(I32GeS, int32_t, >=)        \
  V(I64Add, uint64_t, +)        \
  V(I64Sub, uint64_t, -)        \
  V(I64Mul, uint64_t, *)        \
  V(I64And, uint64_t, &)        \
  V(I64Ior, uint64_t, |)        \
  V(I64Xor, uint64_t, ^)        \
  V(I64Eq, uint64_t, ==)        \
  V(I64Ne, uint64_t, !=)        \
  V(I64LtU, uint64_t, <)        \
  V(I64LeU, uint64_t, <=)       \
  V(I64GtU, uint64_t, >)        \
  V(I64GeU, uint64_t, >=)       \
  V(I64LtS, int64_t, <)         \
  V(I64LeS, int64_t, <=)        \
  V(I64GtS, int64_t, >)         \
  V(I64GeS, int64_t, >=)        \
  V(F32Add, float, +)           \
85
  V(F32Sub, float, -)           \
86 87 88 89 90 91 92
  V(F32Eq, float, ==)           \
  V(F32Ne, float, !=)           \
  V(F32Lt, float, <)            \
  V(F32Le, float, <=)           \
  V(F32Gt, float, >)            \
  V(F32Ge, float, >=)           \
  V(F64Add, double, +)          \
93
  V(F64Sub, double, -)          \
94 95 96 97 98
  V(F64Eq, double, ==)          \
  V(F64Ne, double, !=)          \
  V(F64Lt, double, <)           \
  V(F64Le, double, <=)          \
  V(F64Gt, double, >)           \
99 100 101 102
  V(F64Ge, double, >=)          \
  V(F32Mul, float, *)           \
  V(F64Mul, double, *)          \
  V(F32Div, float, /)           \
103 104
  V(F64Div, double, /)

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
#define FOREACH_OTHER_BINOP(V) \
  V(I32DivS, int32_t)          \
  V(I32DivU, uint32_t)         \
  V(I32RemS, int32_t)          \
  V(I32RemU, uint32_t)         \
  V(I32Shl, uint32_t)          \
  V(I32ShrU, uint32_t)         \
  V(I32ShrS, int32_t)          \
  V(I64DivS, int64_t)          \
  V(I64DivU, uint64_t)         \
  V(I64RemS, int64_t)          \
  V(I64RemU, uint64_t)         \
  V(I64Shl, uint64_t)          \
  V(I64ShrU, uint64_t)         \
  V(I64ShrS, int64_t)          \
  V(I32Ror, int32_t)           \
  V(I32Rol, int32_t)           \
  V(I64Ror, int64_t)           \
  V(I64Rol, int64_t)           \
  V(F32Min, float)             \
  V(F32Max, float)             \
  V(F64Min, double)            \
  V(F64Max, double)            \
  V(I32AsmjsDivS, int32_t)     \
  V(I32AsmjsDivU, uint32_t)    \
  V(I32AsmjsRemS, int32_t)     \
131 132 133
  V(I32AsmjsRemU, uint32_t)    \
  V(F32CopySign, Float32)      \
  V(F64CopySign, Float64)
134

135 136 137 138 139 140
#define FOREACH_I32CONV_FLOATOP(V)   \
  V(I32SConvertF32, int32_t, float)  \
  V(I32SConvertF64, int32_t, double) \
  V(I32UConvertF32, uint32_t, float) \
  V(I32UConvertF64, uint32_t, double)

141 142 143 144 145 146 147 148 149
#define FOREACH_OTHER_UNOP(V)    \
  V(I32Clz, uint32_t)            \
  V(I32Ctz, uint32_t)            \
  V(I32Popcnt, uint32_t)         \
  V(I32Eqz, uint32_t)            \
  V(I64Clz, uint64_t)            \
  V(I64Ctz, uint64_t)            \
  V(I64Popcnt, uint64_t)         \
  V(I64Eqz, uint64_t)            \
150 151
  V(F32Abs, Float32)             \
  V(F32Neg, Float32)             \
152 153 154 155
  V(F32Ceil, float)              \
  V(F32Floor, float)             \
  V(F32Trunc, float)             \
  V(F32NearestInt, float)        \
156 157
  V(F64Abs, Float64)             \
  V(F64Neg, Float64)             \
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  V(F64Ceil, double)             \
  V(F64Floor, double)            \
  V(F64Trunc, double)            \
  V(F64NearestInt, double)       \
  V(I32ConvertI64, int64_t)      \
  V(I64SConvertF32, float)       \
  V(I64SConvertF64, double)      \
  V(I64UConvertF32, float)       \
  V(I64UConvertF64, double)      \
  V(I64SConvertI32, int32_t)     \
  V(I64UConvertI32, uint32_t)    \
  V(F32SConvertI32, int32_t)     \
  V(F32UConvertI32, uint32_t)    \
  V(F32SConvertI64, int64_t)     \
  V(F32UConvertI64, uint64_t)    \
  V(F32ConvertF64, double)       \
  V(F32ReinterpretI32, int32_t)  \
  V(F64SConvertI32, int32_t)     \
  V(F64UConvertI32, uint32_t)    \
  V(F64SConvertI64, int64_t)     \
  V(F64UConvertI64, uint64_t)    \
  V(F64ConvertF32, float)        \
  V(F64ReinterpretI64, int64_t)  \
  V(I32AsmjsSConvertF32, float)  \
  V(I32AsmjsUConvertF32, float)  \
  V(I32AsmjsSConvertF64, double) \
184 185
  V(I32AsmjsUConvertF64, double) \
  V(F32Sqrt, float)              \
186 187
  V(F64Sqrt, double)

188 189
namespace {

190 191 192
constexpr uint32_t kFloat32SignBitMask = uint32_t{1} << 31;
constexpr uint64_t kFloat64SignBitMask = uint64_t{1} << 63;

193
inline int32_t ExecuteI32DivS(int32_t a, int32_t b, TrapReason* trap) {
194 195 196 197 198 199 200 201 202 203 204
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  if (b == -1 && a == std::numeric_limits<int32_t>::min()) {
    *trap = kTrapDivUnrepresentable;
    return 0;
  }
  return a / b;
}

205
inline uint32_t ExecuteI32DivU(uint32_t a, uint32_t b, TrapReason* trap) {
206 207 208 209 210 211 212
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  return a / b;
}

213
inline int32_t ExecuteI32RemS(int32_t a, int32_t b, TrapReason* trap) {
214 215 216 217 218 219 220 221
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  if (b == -1) return 0;
  return a % b;
}

222
inline uint32_t ExecuteI32RemU(uint32_t a, uint32_t b, TrapReason* trap) {
223 224 225 226 227 228 229
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  return a % b;
}

230
inline uint32_t ExecuteI32Shl(uint32_t a, uint32_t b, TrapReason* trap) {
231
  return a << (b & 0x1F);
232 233
}

234
inline uint32_t ExecuteI32ShrU(uint32_t a, uint32_t b, TrapReason* trap) {
235
  return a >> (b & 0x1F);
236 237
}

238
inline int32_t ExecuteI32ShrS(int32_t a, int32_t b, TrapReason* trap) {
239
  return a >> (b & 0x1F);
240 241
}

242
inline int64_t ExecuteI64DivS(int64_t a, int64_t b, TrapReason* trap) {
243 244 245 246 247 248 249 250 251 252 253
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  if (b == -1 && a == std::numeric_limits<int64_t>::min()) {
    *trap = kTrapDivUnrepresentable;
    return 0;
  }
  return a / b;
}

254
inline uint64_t ExecuteI64DivU(uint64_t a, uint64_t b, TrapReason* trap) {
255 256 257 258 259 260 261
  if (b == 0) {
    *trap = kTrapDivByZero;
    return 0;
  }
  return a / b;
}

262
inline int64_t ExecuteI64RemS(int64_t a, int64_t b, TrapReason* trap) {
263 264 265 266 267 268 269 270
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  if (b == -1) return 0;
  return a % b;
}

271
inline uint64_t ExecuteI64RemU(uint64_t a, uint64_t b, TrapReason* trap) {
272 273 274 275 276 277 278
  if (b == 0) {
    *trap = kTrapRemByZero;
    return 0;
  }
  return a % b;
}

279
inline uint64_t ExecuteI64Shl(uint64_t a, uint64_t b, TrapReason* trap) {
280
  return a << (b & 0x3F);
281 282
}

283
inline uint64_t ExecuteI64ShrU(uint64_t a, uint64_t b, TrapReason* trap) {
284
  return a >> (b & 0x3F);
285 286
}

287
inline int64_t ExecuteI64ShrS(int64_t a, int64_t b, TrapReason* trap) {
288
  return a >> (b & 0x3F);
289 290
}

291
inline uint32_t ExecuteI32Ror(uint32_t a, uint32_t b, TrapReason* trap) {
292
  uint32_t shift = (b & 0x1F);
293 294 295
  return (a >> shift) | (a << (32 - shift));
}

296
inline uint32_t ExecuteI32Rol(uint32_t a, uint32_t b, TrapReason* trap) {
297
  uint32_t shift = (b & 0x1F);
298 299 300
  return (a << shift) | (a >> (32 - shift));
}

301
inline uint64_t ExecuteI64Ror(uint64_t a, uint64_t b, TrapReason* trap) {
302
  uint32_t shift = (b & 0x3F);
303 304 305
  return (a >> shift) | (a << (64 - shift));
}

306
inline uint64_t ExecuteI64Rol(uint64_t a, uint64_t b, TrapReason* trap) {
307
  uint32_t shift = (b & 0x3F);
308 309 310
  return (a << shift) | (a >> (64 - shift));
}

311
inline float ExecuteF32Min(float a, float b, TrapReason* trap) {
312
  return JSMin(a, b);
313 314
}

315
inline float ExecuteF32Max(float a, float b, TrapReason* trap) {
316
  return JSMax(a, b);
317 318
}

319 320 321
inline Float32 ExecuteF32CopySign(Float32 a, Float32 b, TrapReason* trap) {
  return Float32::FromBits((a.get_bits() & ~kFloat32SignBitMask) |
                           (b.get_bits() & kFloat32SignBitMask));
322 323
}

324
inline double ExecuteF64Min(double a, double b, TrapReason* trap) {
325
  return JSMin(a, b);
326 327
}

328
inline double ExecuteF64Max(double a, double b, TrapReason* trap) {
329
  return JSMax(a, b);
330 331
}

332 333 334
inline Float64 ExecuteF64CopySign(Float64 a, Float64 b, TrapReason* trap) {
  return Float64::FromBits((a.get_bits() & ~kFloat64SignBitMask) |
                           (b.get_bits() & kFloat64SignBitMask));
335 336
}

337
inline int32_t ExecuteI32AsmjsDivS(int32_t a, int32_t b, TrapReason* trap) {
338 339 340 341 342 343 344
  if (b == 0) return 0;
  if (b == -1 && a == std::numeric_limits<int32_t>::min()) {
    return std::numeric_limits<int32_t>::min();
  }
  return a / b;
}

345
inline uint32_t ExecuteI32AsmjsDivU(uint32_t a, uint32_t b, TrapReason* trap) {
346 347 348 349
  if (b == 0) return 0;
  return a / b;
}

350
inline int32_t ExecuteI32AsmjsRemS(int32_t a, int32_t b, TrapReason* trap) {
351 352 353 354 355
  if (b == 0) return 0;
  if (b == -1) return 0;
  return a % b;
}

356
inline uint32_t ExecuteI32AsmjsRemU(uint32_t a, uint32_t b, TrapReason* trap) {
357 358 359 360
  if (b == 0) return 0;
  return a % b;
}

361
inline int32_t ExecuteI32AsmjsSConvertF32(float a, TrapReason* trap) {
362 363 364
  return DoubleToInt32(a);
}

365
inline uint32_t ExecuteI32AsmjsUConvertF32(float a, TrapReason* trap) {
366 367 368
  return DoubleToUint32(a);
}

369
inline int32_t ExecuteI32AsmjsSConvertF64(double a, TrapReason* trap) {
370 371 372
  return DoubleToInt32(a);
}

373
inline uint32_t ExecuteI32AsmjsUConvertF64(double a, TrapReason* trap) {
374 375 376
  return DoubleToUint32(a);
}

377
int32_t ExecuteI32Clz(uint32_t val, TrapReason* trap) {
378
  return base::bits::CountLeadingZeros(val);
379 380
}

381
uint32_t ExecuteI32Ctz(uint32_t val, TrapReason* trap) {
382
  return base::bits::CountTrailingZeros(val);
383 384
}

385
uint32_t ExecuteI32Popcnt(uint32_t val, TrapReason* trap) {
386
  return base::bits::CountPopulation(val);
387 388
}

389
inline uint32_t ExecuteI32Eqz(uint32_t val, TrapReason* trap) {
390 391 392
  return val == 0 ? 1 : 0;
}

393
int64_t ExecuteI64Clz(uint64_t val, TrapReason* trap) {
394
  return base::bits::CountLeadingZeros(val);
395 396
}

397
inline uint64_t ExecuteI64Ctz(uint64_t val, TrapReason* trap) {
398
  return base::bits::CountTrailingZeros(val);
399 400
}

401
inline int64_t ExecuteI64Popcnt(uint64_t val, TrapReason* trap) {
402
  return base::bits::CountPopulation(val);
403 404
}

405
inline int32_t ExecuteI64Eqz(uint64_t val, TrapReason* trap) {
406 407 408
  return val == 0 ? 1 : 0;
}

409
inline Float32 ExecuteF32Abs(Float32 a, TrapReason* trap) {
410
  return Float32::FromBits(a.get_bits() & ~kFloat32SignBitMask);
411 412
}

413
inline Float32 ExecuteF32Neg(Float32 a, TrapReason* trap) {
414
  return Float32::FromBits(a.get_bits() ^ kFloat32SignBitMask);
415 416
}

417
inline float ExecuteF32Ceil(float a, TrapReason* trap) { return ceilf(a); }
418

419
inline float ExecuteF32Floor(float a, TrapReason* trap) { return floorf(a); }
420

421
inline float ExecuteF32Trunc(float a, TrapReason* trap) { return truncf(a); }
422

423
inline float ExecuteF32NearestInt(float a, TrapReason* trap) {
424 425 426
  return nearbyintf(a);
}

427
inline float ExecuteF32Sqrt(float a, TrapReason* trap) {
428 429
  float result = sqrtf(a);
  return result;
430 431
}

432
inline Float64 ExecuteF64Abs(Float64 a, TrapReason* trap) {
433
  return Float64::FromBits(a.get_bits() & ~kFloat64SignBitMask);
434 435
}

436
inline Float64 ExecuteF64Neg(Float64 a, TrapReason* trap) {
437
  return Float64::FromBits(a.get_bits() ^ kFloat64SignBitMask);
438 439
}

440
inline double ExecuteF64Ceil(double a, TrapReason* trap) { return ceil(a); }
441

442
inline double ExecuteF64Floor(double a, TrapReason* trap) { return floor(a); }
443

444
inline double ExecuteF64Trunc(double a, TrapReason* trap) { return trunc(a); }
445

446
inline double ExecuteF64NearestInt(double a, TrapReason* trap) {
447 448 449
  return nearbyint(a);
}

450
inline double ExecuteF64Sqrt(double a, TrapReason* trap) { return sqrt(a); }
451

452 453 454 455
template <typename int_type, typename float_type>
int_type ExecuteConvert(float_type a, TrapReason* trap) {
  if (is_inbounds<int_type>(a)) {
    return static_cast<int_type>(a);
456 457 458 459 460
  }
  *trap = kTrapFloatUnrepresentable;
  return 0;
}

461 462
template <typename int_type, typename float_type>
int_type ExecuteConvertSaturate(float_type a) {
463
  TrapReason base_trap = kTrapCount;
464
  int32_t val = ExecuteConvert<int_type>(a, &base_trap);
465 466 467 468
  if (base_trap == kTrapCount) {
    return val;
  }
  return std::isnan(a) ? 0
469 470 471
                       : (a < static_cast<float_type>(0.0)
                              ? std::numeric_limits<int_type>::min()
                              : std::numeric_limits<int_type>::max());
472 473
}

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
template <typename dst_type, typename src_type, void (*fn)(Address)>
inline dst_type CallExternalIntToFloatFunction(src_type input) {
  uint8_t data[std::max(sizeof(dst_type), sizeof(src_type))];
  Address data_addr = reinterpret_cast<Address>(data);
  WriteUnalignedValue<src_type>(data_addr, input);
  fn(data_addr);
  return ReadUnalignedValue<dst_type>(data_addr);
}

template <typename dst_type, typename src_type, int32_t (*fn)(Address)>
inline dst_type CallExternalFloatToIntFunction(src_type input,
                                               TrapReason* trap) {
  uint8_t data[std::max(sizeof(dst_type), sizeof(src_type))];
  Address data_addr = reinterpret_cast<Address>(data);
  WriteUnalignedValue<src_type>(data_addr, input);
  if (!fn(data_addr)) *trap = kTrapFloatUnrepresentable;
  return ReadUnalignedValue<dst_type>(data_addr);
}

493
inline uint32_t ExecuteI32ConvertI64(int64_t a, TrapReason* trap) {
494 495 496
  return static_cast<uint32_t>(a & 0xFFFFFFFF);
}

497
int64_t ExecuteI64SConvertF32(float a, TrapReason* trap) {
498 499
  return CallExternalFloatToIntFunction<int64_t, float,
                                        float32_to_int64_wrapper>(a, trap);
500 501
}

502 503 504 505 506 507 508 509 510 511 512
int64_t ExecuteI64SConvertSatF32(float a) {
  TrapReason base_trap = kTrapCount;
  int64_t val = ExecuteI64SConvertF32(a, &base_trap);
  if (base_trap == kTrapCount) {
    return val;
  }
  return std::isnan(a) ? 0
                       : (a < 0.0 ? std::numeric_limits<int64_t>::min()
                                  : std::numeric_limits<int64_t>::max());
}

513
int64_t ExecuteI64SConvertF64(double a, TrapReason* trap) {
514 515
  return CallExternalFloatToIntFunction<int64_t, double,
                                        float64_to_int64_wrapper>(a, trap);
516 517
}

518 519 520 521 522 523 524 525 526 527 528
int64_t ExecuteI64SConvertSatF64(double a) {
  TrapReason base_trap = kTrapCount;
  int64_t val = ExecuteI64SConvertF64(a, &base_trap);
  if (base_trap == kTrapCount) {
    return val;
  }
  return std::isnan(a) ? 0
                       : (a < 0.0 ? std::numeric_limits<int64_t>::min()
                                  : std::numeric_limits<int64_t>::max());
}

529
uint64_t ExecuteI64UConvertF32(float a, TrapReason* trap) {
530 531
  return CallExternalFloatToIntFunction<uint64_t, float,
                                        float32_to_uint64_wrapper>(a, trap);
532 533
}

534 535 536 537 538 539 540 541 542 543 544
uint64_t ExecuteI64UConvertSatF32(float a) {
  TrapReason base_trap = kTrapCount;
  uint64_t val = ExecuteI64UConvertF32(a, &base_trap);
  if (base_trap == kTrapCount) {
    return val;
  }
  return std::isnan(a) ? 0
                       : (a < 0.0 ? std::numeric_limits<uint64_t>::min()
                                  : std::numeric_limits<uint64_t>::max());
}

545
uint64_t ExecuteI64UConvertF64(double a, TrapReason* trap) {
546 547
  return CallExternalFloatToIntFunction<uint64_t, double,
                                        float64_to_uint64_wrapper>(a, trap);
548 549
}

550 551 552 553 554 555 556 557 558 559 560
uint64_t ExecuteI64UConvertSatF64(double a) {
  TrapReason base_trap = kTrapCount;
  int64_t val = ExecuteI64UConvertF64(a, &base_trap);
  if (base_trap == kTrapCount) {
    return val;
  }
  return std::isnan(a) ? 0
                       : (a < 0.0 ? std::numeric_limits<uint64_t>::min()
                                  : std::numeric_limits<uint64_t>::max());
}

561
inline int64_t ExecuteI64SConvertI32(int32_t a, TrapReason* trap) {
562 563 564
  return static_cast<int64_t>(a);
}

565
inline int64_t ExecuteI64UConvertI32(uint32_t a, TrapReason* trap) {
566 567 568
  return static_cast<uint64_t>(a);
}

569
inline float ExecuteF32SConvertI32(int32_t a, TrapReason* trap) {
570 571 572
  return static_cast<float>(a);
}

573
inline float ExecuteF32UConvertI32(uint32_t a, TrapReason* trap) {
574 575 576
  return static_cast<float>(a);
}

577
inline float ExecuteF32SConvertI64(int64_t a, TrapReason* trap) {
578
  return static_cast<float>(a);
579 580
}

581
inline float ExecuteF32UConvertI64(uint64_t a, TrapReason* trap) {
582 583
  return CallExternalIntToFloatFunction<float, uint64_t,
                                        uint64_to_float32_wrapper>(a);
584 585
}

586
inline float ExecuteF32ConvertF64(double a, TrapReason* trap) {
587 588 589
  return static_cast<float>(a);
}

590 591
inline Float32 ExecuteF32ReinterpretI32(int32_t a, TrapReason* trap) {
  return Float32::FromBits(a);
592 593
}

594
inline double ExecuteF64SConvertI32(int32_t a, TrapReason* trap) {
595 596 597
  return static_cast<double>(a);
}

598
inline double ExecuteF64UConvertI32(uint32_t a, TrapReason* trap) {
599 600 601
  return static_cast<double>(a);
}

602
inline double ExecuteF64SConvertI64(int64_t a, TrapReason* trap) {
603
  return static_cast<double>(a);
604 605
}

606
inline double ExecuteF64UConvertI64(uint64_t a, TrapReason* trap) {
607 608
  return CallExternalIntToFloatFunction<double, uint64_t,
                                        uint64_to_float64_wrapper>(a);
609 610
}

611
inline double ExecuteF64ConvertF32(float a, TrapReason* trap) {
612 613 614
  return static_cast<double>(a);
}

615 616
inline Float64 ExecuteF64ReinterpretI64(int64_t a, TrapReason* trap) {
  return Float64::FromBits(a);
617 618
}

619
inline int32_t ExecuteI32ReinterpretF32(WasmValue a) {
620
  return a.to_f32_boxed().get_bits();
621 622
}

623
inline int64_t ExecuteI64ReinterpretF64(WasmValue a) {
624
  return a.to_f64_boxed().get_bits();
625 626 627 628 629 630 631 632
}

enum InternalOpcode {
#define DECL_INTERNAL_ENUM(name, value) kInternal##name = value,
  FOREACH_INTERNAL_OPCODE(DECL_INTERNAL_ENUM)
#undef DECL_INTERNAL_ENUM
};

633
const char* OpcodeName(uint32_t val) {
634 635 636 637 638 639 640 641 642 643
  switch (val) {
#define DECL_INTERNAL_CASE(name, value) \
  case kInternal##name:                 \
    return "Internal" #name;
    FOREACH_INTERNAL_OPCODE(DECL_INTERNAL_CASE)
#undef DECL_INTERNAL_CASE
  }
  return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(val));
}

644 645
}  // namespace

646
class SideTable;
647 648 649 650 651 652 653 654 655

// Code and metadata needed to execute a function.
struct InterpreterCode {
  const WasmFunction* function;  // wasm function
  BodyLocalDecls locals;         // local declarations
  const byte* orig_start;        // start of original code
  const byte* orig_end;          // end of original code
  byte* start;                   // start of (maybe altered) code
  byte* end;                     // end of (maybe altered) code
656
  SideTable* side_table;         // precomputed side table for control flow.
657 658 659 660

  const byte* at(pc_t pc) { return start + pc; }
};

661 662 663
// A helper class to compute the control transfers for each bytecode offset.
// Control transfers allow Br, BrIf, BrTable, If, Else, and End bytecodes to
// be directly executed without the need to dynamically track blocks.
664
class SideTable : public ZoneObject {
665 666
 public:
  ControlTransferMap map_;
667
  uint32_t max_stack_height_ = 0;
668

669
  SideTable(Zone* zone, const WasmModule* module, InterpreterCode* code)
670
      : map_(zone) {
671 672 673
    // Create a zone for all temporary objects.
    Zone control_transfer_zone(zone->allocator(), ZONE_NAME);

674
    // Represents a control flow label.
675 676
    class CLabel : public ZoneObject {
      explicit CLabel(Zone* zone, uint32_t target_stack_height, uint32_t arity)
677
          : target_stack_height(target_stack_height),
678 679 680 681 682 683 684 685
            arity(arity),
            refs(zone) {}

     public:
      struct Ref {
        const byte* from_pc;
        const uint32_t stack_height;
      };
686
      const byte* target = nullptr;
687
      uint32_t target_stack_height;
688
      // Arity when branching to this label.
689 690
      const uint32_t arity;
      ZoneVector<Ref> refs;
691

692 693 694
      static CLabel* New(Zone* zone, uint32_t stack_height, uint32_t arity) {
        return new (zone) CLabel(zone, stack_height, arity);
      }
695 696

      // Bind this label to the given PC.
697
      void Bind(const byte* pc) {
698 699 700 701 702
        DCHECK_NULL(target);
        target = pc;
      }

      // Reference this label from the given location.
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
      void Ref(const byte* from_pc, uint32_t stack_height) {
        // Target being bound before a reference means this is a loop.
        DCHECK_IMPLIES(target, *target == kExprLoop);
        refs.push_back({from_pc, stack_height});
      }

      void Finish(ControlTransferMap* map, const byte* start) {
        DCHECK_NOT_NULL(target);
        for (auto ref : refs) {
          size_t offset = static_cast<size_t>(ref.from_pc - start);
          auto pcdiff = static_cast<pcdiff_t>(target - ref.from_pc);
          DCHECK_GE(ref.stack_height, target_stack_height);
          spdiff_t spdiff =
              static_cast<spdiff_t>(ref.stack_height - target_stack_height);
          TRACE("control transfer @%zu: Δpc %d, stack %u->%u = -%u\n", offset,
                pcdiff, ref.stack_height, target_stack_height, spdiff);
          ControlTransferEntry& entry = (*map)[offset];
          entry.pc_diff = pcdiff;
          entry.sp_diff = spdiff;
          entry.target_arity = arity;
723 724 725 726 727 728 729 730 731
        }
      }
    };

    // An entry in the control stack.
    struct Control {
      const byte* pc;
      CLabel* end_label;
      CLabel* else_label;
732 733 734
      // Arity (number of values on the stack) when exiting this control
      // structure via |end|.
      uint32_t exit_arity;
735 736 737
      // Track whether this block was already left, i.e. all further
      // instructions are unreachable.
      bool unreachable = false;
738 739 740 741 742 743 744 745 746

      Control(const byte* pc, CLabel* end_label, CLabel* else_label,
              uint32_t exit_arity)
          : pc(pc),
            end_label(end_label),
            else_label(else_label),
            exit_arity(exit_arity) {}
      Control(const byte* pc, CLabel* end_label, uint32_t exit_arity)
          : Control(pc, end_label, nullptr, exit_arity) {}
747

748 749 750
      void Finish(ControlTransferMap* map, const byte* start) {
        end_label->Finish(map, start);
        if (else_label) else_label->Finish(map, start);
751 752 753 754
      }
    };

    // Compute the ControlTransfer map.
755
    // This algorithm maintains a stack of control constructs similar to the
756 757 758
    // AST decoder. The {control_stack} allows matching {br,br_if,br_table}
    // bytecodes with their target, as well as determining whether the current
    // bytecodes are within the true or false block of an else.
759 760 761 762 763 764
    ZoneVector<Control> control_stack(&control_transfer_zone);
    uint32_t stack_height = 0;
    uint32_t func_arity =
        static_cast<uint32_t>(code->function->sig->return_count());
    CLabel* func_label =
        CLabel::New(&control_transfer_zone, stack_height, func_arity);
765
    control_stack.emplace_back(code->orig_start, func_label, func_arity);
766 767 768 769 770 771 772
    auto control_parent = [&]() -> Control& {
      DCHECK_LE(2, control_stack.size());
      return control_stack[control_stack.size() - 2];
    };
    auto copy_unreachable = [&] {
      control_stack.back().unreachable = control_parent().unreachable;
    };
773 774
    for (BytecodeIterator i(code->orig_start, code->orig_end, &code->locals);
         i.has_next(); i.next()) {
775
      WasmOpcode opcode = i.current();
776
      if (WasmOpcodes::IsPrefixOpcode(opcode)) opcode = i.prefixed_opcode();
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
      bool unreachable = control_stack.back().unreachable;
      if (unreachable) {
        TRACE("@%u: %s (is unreachable)\n", i.pc_offset(),
              WasmOpcodes::OpcodeName(opcode));
      } else {
        auto stack_effect =
            StackEffect(module, code->function->sig, i.pc(), i.end());
        TRACE("@%u: %s (sp %d - %d + %d)\n", i.pc_offset(),
              WasmOpcodes::OpcodeName(opcode), stack_height, stack_effect.first,
              stack_effect.second);
        DCHECK_GE(stack_height, stack_effect.first);
        DCHECK_GE(kMaxUInt32, static_cast<uint64_t>(stack_height) -
                                  stack_effect.first + stack_effect.second);
        stack_height = stack_height - stack_effect.first + stack_effect.second;
        if (stack_height > max_stack_height_) max_stack_height_ = stack_height;
      }
793
      switch (opcode) {
794
        case kExprBlock:
795
        case kExprLoop: {
796
          bool is_loop = opcode == kExprLoop;
797 798
          BlockTypeImmediate<Decoder::kNoValidate> imm(kAllWasmFeatures, &i,
                                                       i.pc());
799 800
          if (imm.type == kWasmVar) {
            imm.sig = module->signatures[imm.sig_index];
801 802
          }
          TRACE("control @%u: %s, arity %d->%d\n", i.pc_offset(),
803 804 805 806 807
                is_loop ? "Loop" : "Block", imm.in_arity(), imm.out_arity());
          CLabel* label =
              CLabel::New(&control_transfer_zone, stack_height,
                          is_loop ? imm.in_arity() : imm.out_arity());
          control_stack.emplace_back(i.pc(), label, imm.out_arity());
808
          copy_unreachable();
809
          if (is_loop) label->Bind(i.pc());
810 811 812
          break;
        }
        case kExprIf: {
813 814
          BlockTypeImmediate<Decoder::kNoValidate> imm(kAllWasmFeatures, &i,
                                                       i.pc());
815 816
          if (imm.type == kWasmVar) {
            imm.sig = module->signatures[imm.sig_index];
817 818
          }
          TRACE("control @%u: If, arity %d->%d\n", i.pc_offset(),
819 820 821
                imm.in_arity(), imm.out_arity());
          CLabel* end_label = CLabel::New(&control_transfer_zone, stack_height,
                                          imm.out_arity());
822 823
          CLabel* else_label =
              CLabel::New(&control_transfer_zone, stack_height, 0);
824
          control_stack.emplace_back(i.pc(), end_label, else_label,
825
                                     imm.out_arity());
826 827
          copy_unreachable();
          if (!unreachable) else_label->Ref(i.pc(), stack_height);
828 829 830 831
          break;
        }
        case kExprElse: {
          Control* c = &control_stack.back();
832
          copy_unreachable();
833
          TRACE("control @%u: Else\n", i.pc_offset());
834 835 836
          if (!control_parent().unreachable) {
            c->end_label->Ref(i.pc(), stack_height);
          }
837
          DCHECK_NOT_NULL(c->else_label);
838 839
          c->else_label->Bind(i.pc() + 1);
          c->else_label->Finish(&map_, code->orig_start);
840
          c->else_label = nullptr;
841 842
          DCHECK_GE(stack_height, c->end_label->target_stack_height);
          stack_height = c->end_label->target_stack_height;
843 844 845 846
          break;
        }
        case kExprEnd: {
          Control* c = &control_stack.back();
847
          TRACE("control @%u: End\n", i.pc_offset());
848 849 850 851 852
          // Only loops have bound labels.
          DCHECK_IMPLIES(c->end_label->target, *c->pc == kExprLoop);
          if (!c->end_label->target) {
            if (c->else_label) c->else_label->Bind(i.pc());
            c->end_label->Bind(i.pc() + 1);
853
          }
854 855
          c->Finish(&map_, code->orig_start);
          DCHECK_GE(stack_height, c->end_label->target_stack_height);
856
          stack_height = c->end_label->target_stack_height + c->exit_arity;
857 858 859 860
          control_stack.pop_back();
          break;
        }
        case kExprBr: {
861 862 863
          BreakDepthImmediate<Decoder::kNoValidate> imm(&i, i.pc());
          TRACE("control @%u: Br[depth=%u]\n", i.pc_offset(), imm.depth);
          Control* c = &control_stack[control_stack.size() - imm.depth - 1];
864
          if (!unreachable) c->end_label->Ref(i.pc(), stack_height);
865 866 867
          break;
        }
        case kExprBrIf: {
868 869 870
          BreakDepthImmediate<Decoder::kNoValidate> imm(&i, i.pc());
          TRACE("control @%u: BrIf[depth=%u]\n", i.pc_offset(), imm.depth);
          Control* c = &control_stack[control_stack.size() - imm.depth - 1];
871
          if (!unreachable) c->end_label->Ref(i.pc(), stack_height);
872 873 874
          break;
        }
        case kExprBrTable: {
875 876
          BranchTableImmediate<Decoder::kNoValidate> imm(&i, i.pc());
          BranchTableIterator<Decoder::kNoValidate> iterator(&i, imm);
877
          TRACE("control @%u: BrTable[count=%u]\n", i.pc_offset(),
878
                imm.table_count);
879 880 881 882 883 884 885
          if (!unreachable) {
            while (iterator.has_next()) {
              uint32_t j = iterator.cur_index();
              uint32_t target = iterator.next();
              Control* c = &control_stack[control_stack.size() - target - 1];
              c->end_label->Ref(i.pc() + j, stack_height);
            }
886 887 888
          }
          break;
        }
889
        default:
890
          break;
891 892 893
      }
      if (WasmOpcodes::IsUnconditionalJump(opcode)) {
        control_stack.back().unreachable = true;
894 895
      }
    }
896 897
    DCHECK_EQ(0, control_stack.size());
    DCHECK_EQ(func_arity, stack_height);
898 899
  }

900
  ControlTransferEntry& Lookup(pc_t from) {
901
    auto result = map_.find(from);
902
    DCHECK(result != map_.end());
903 904 905 906 907 908 909 910 911 912
    return result->second;
  }
};

// The main storage for interpreter code. It maps {WasmFunction} to the
// metadata needed to execute each function.
class CodeMap {
  Zone* zone_;
  const WasmModule* module_;
  ZoneVector<InterpreterCode> interpreter_code_;
913 914 915
  // TODO(wasm): Remove this testing wart. It is needed because interpreter
  // entry stubs are not generated in testing the interpreter in cctests.
  bool call_indirect_through_module_ = false;
916

917
 public:
918
  CodeMap(const WasmModule* module, const uint8_t* module_start, Zone* zone)
919
      : zone_(zone), module_(module), interpreter_code_(zone) {
920
    if (module == nullptr) return;
921 922 923
    interpreter_code_.reserve(module->functions.size());
    for (const WasmFunction& function : module->functions) {
      if (function.imported) {
924
        DCHECK(!function.code.is_set());
925 926
        AddFunction(&function, nullptr, nullptr);
      } else {
927 928
        AddFunction(&function, module_start + function.code.offset(),
                    module_start + function.code.end_offset());
929
      }
930
    }
931 932
  }

933 934 935 936 937 938
  bool call_indirect_through_module() { return call_indirect_through_module_; }

  void set_call_indirect_through_module(bool val) {
    call_indirect_through_module_ = val;
  }

939
  const WasmModule* module() const { return module_; }
940

941 942 943 944
  InterpreterCode* GetCode(const WasmFunction* function) {
    InterpreterCode* code = GetCode(function->func_index);
    DCHECK_EQ(function, code->function);
    return code;
945 946 947
  }

  InterpreterCode* GetCode(uint32_t function_index) {
948
    DCHECK_LT(function_index, interpreter_code_.size());
949 950 951
    return Preprocess(&interpreter_code_[function_index]);
  }

952
  InterpreterCode* GetIndirectCode(uint32_t table_index, uint32_t entry_index) {
953 954
    uint32_t saved_index;
    USE(saved_index);
955
    if (table_index >= module_->tables.size()) return nullptr;
956 957
    // Mask table index for SSCA mitigation.
    saved_index = table_index;
958 959 960
    table_index &= static_cast<int32_t>((table_index - module_->tables.size()) &
                                        ~static_cast<int32_t>(table_index)) >>
                   31;
961
    DCHECK_EQ(table_index, saved_index);
962
    const WasmTable* table = &module_->tables[table_index];
963
    if (entry_index >= table->values.size()) return nullptr;
964 965 966 967 968 969
    // Mask entry_index for SSCA mitigation.
    saved_index = entry_index;
    entry_index &= static_cast<int32_t>((entry_index - table->values.size()) &
                                        ~static_cast<int32_t>(entry_index)) >>
                   31;
    DCHECK_EQ(entry_index, saved_index);
970
    uint32_t index = table->values[entry_index];
971
    if (index >= interpreter_code_.size()) return nullptr;
972 973 974 975 976 977 978
    // Mask index for SSCA mitigation.
    saved_index = index;
    index &= static_cast<int32_t>((index - interpreter_code_.size()) &
                                  ~static_cast<int32_t>(index)) >>
             31;
    DCHECK_EQ(index, saved_index);

979 980 981 982
    return GetCode(index);
  }

  InterpreterCode* Preprocess(InterpreterCode* code) {
983
    DCHECK_EQ(code->function->imported, code->start == nullptr);
984
    if (!code->side_table && code->start) {
985
      // Compute the control targets map and the local declarations.
986
      code->side_table = new (zone_) SideTable(zone_, module_, code);
987 988 989 990
    }
    return code;
  }

991 992
  void AddFunction(const WasmFunction* function, const byte* code_start,
                   const byte* code_end) {
993
    InterpreterCode code = {
994
        function, BodyLocalDecls(zone_),         code_start,
995 996 997 998 999 1000 1001
        code_end, const_cast<byte*>(code_start), const_cast<byte*>(code_end),
        nullptr};

    DCHECK_EQ(interpreter_code_.size(), function->func_index);
    interpreter_code_.push_back(code);
  }

1002
  void SetFunctionCode(const WasmFunction* function, const byte* start,
1003
                       const byte* end) {
1004 1005 1006
    DCHECK_LT(function->func_index, interpreter_code_.size());
    InterpreterCode* code = &interpreter_code_[function->func_index];
    DCHECK_EQ(function, code->function);
1007 1008 1009 1010
    code->orig_start = start;
    code->orig_end = end;
    code->start = const_cast<byte*>(start);
    code->end = const_cast<byte*>(end);
1011
    code->side_table = nullptr;
1012 1013
    Preprocess(code);
  }
1014
};
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
namespace {

struct ExternalCallResult {
  enum Type {
    // The function should be executed inside this interpreter.
    INTERNAL,
    // For indirect calls: Table or function does not exist.
    INVALID_FUNC,
    // For indirect calls: Signature does not match expected signature.
    SIGNATURE_MISMATCH,
    // The function was executed and returned normally.
    EXTERNAL_RETURNED,
    // The function was executed, threw an exception, and the stack was unwound.
    EXTERNAL_UNWOUND
  };
  Type type;
  // If type is INTERNAL, this field holds the function to call internally.
  InterpreterCode* interpreter_code;

  ExternalCallResult(Type type) : type(type) {  // NOLINT
    DCHECK_NE(INTERNAL, type);
  }
  ExternalCallResult(Type type, InterpreterCode* code)
      : type(type), interpreter_code(code) {
    DCHECK_EQ(INTERNAL, type);
  }
};

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
// Like a static_cast from src to dst, but specialized for boxed floats.
template <typename dst, typename src>
struct converter {
  dst operator()(src val) const { return static_cast<dst>(val); }
};
template <>
struct converter<Float64, uint64_t> {
  Float64 operator()(uint64_t val) const { return Float64::FromBits(val); }
};
template <>
struct converter<Float32, uint32_t> {
  Float32 operator()(uint32_t val) const { return Float32::FromBits(val); }
};
template <>
struct converter<uint64_t, Float64> {
  uint64_t operator()(Float64 val) const { return val.get_bits(); }
};
template <>
struct converter<uint32_t, Float32> {
  uint32_t operator()(Float32 val) const { return val.get_bits(); }
};

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
template <typename T>
V8_INLINE bool has_nondeterminism(T val) {
  static_assert(!std::is_floating_point<T>::value, "missing specialization");
  return false;
}
template <>
V8_INLINE bool has_nondeterminism<float>(float val) {
  return std::isnan(val);
}
template <>
V8_INLINE bool has_nondeterminism<double>(double val) {
  return std::isnan(val);
}

1080 1081
}  // namespace

1082
// Responsible for executing code directly.
1083
class ThreadImpl {
1084 1085
  struct Activation {
    uint32_t fp;
1086 1087
    sp_t sp;
    Activation(uint32_t fp, sp_t sp) : fp(fp), sp(sp) {}
1088 1089
  };

1090
 public:
1091 1092
  ThreadImpl(Zone* zone, CodeMap* codemap,
             Handle<WasmInstanceObject> instance_object)
1093
      : codemap_(codemap),
1094
        instance_object_(instance_object),
1095
        frames_(zone),
1096
        activations_(zone) {}
1097 1098 1099 1100 1101

  //==========================================================================
  // Implementation of public interface for WasmInterpreter::Thread.
  //==========================================================================

1102
  WasmInterpreter::State state() { return state_; }
1103

1104
  void InitFrame(const WasmFunction* function, WasmValue* args) {
1105
    DCHECK_EQ(current_activation().fp, frames_.size());
1106
    InterpreterCode* code = codemap()->GetCode(function);
1107 1108 1109
    size_t num_params = function->sig->parameter_count();
    EnsureStackSpace(num_params);
    Push(args, num_params);
1110
    PushFrame(code);
1111 1112
  }

1113
  WasmInterpreter::State Run(int num_steps = -1) {
1114 1115
    DCHECK(state_ == WasmInterpreter::STOPPED ||
           state_ == WasmInterpreter::PAUSED);
1116 1117
    DCHECK(num_steps == -1 || num_steps > 0);
    if (num_steps == -1) {
1118
      TRACE("  => Run()\n");
1119 1120 1121 1122 1123 1124 1125
    } else if (num_steps == 1) {
      TRACE("  => Step()\n");
    } else {
      TRACE("  => Run(%d)\n", num_steps);
    }
    state_ = WasmInterpreter::RUNNING;
    Execute(frames_.back().code, frames_.back().pc, num_steps);
1126 1127 1128
    // If state_ is STOPPED, the current activation must be fully unwound.
    DCHECK_IMPLIES(state_ == WasmInterpreter::STOPPED,
                   current_activation().fp == frames_.size());
1129 1130 1131
    return state_;
  }

1132
  void Pause() { UNIMPLEMENTED(); }
1133

1134
  void Reset() {
1135
    TRACE("----- RESET -----\n");
1136
    sp_ = stack_.get();
1137 1138 1139
    frames_.clear();
    state_ = WasmInterpreter::STOPPED;
    trap_reason_ = kTrapCount;
1140
    possible_nondeterminism_ = false;
1141 1142
  }

1143 1144 1145
  int GetFrameCount() {
    DCHECK_GE(kMaxInt, frames_.size());
    return static_cast<int>(frames_.size());
1146 1147
  }

1148
  WasmValue GetReturnValue(uint32_t index) {
1149
    if (state_ == WasmInterpreter::TRAPPED) return WasmValue(0xDEADBEEF);
1150 1151 1152 1153
    DCHECK_EQ(WasmInterpreter::FINISHED, state_);
    Activation act = current_activation();
    // Current activation must be finished.
    DCHECK_EQ(act.fp, frames_.size());
1154 1155 1156
    return GetStackValue(act.sp + index);
  }

1157
  WasmValue GetStackValue(sp_t index) {
1158
    DCHECK_GT(StackHeight(), index);
1159
    return stack_[index];
1160 1161
  }

1162
  void SetStackValue(sp_t index, WasmValue value) {
1163
    DCHECK_GT(StackHeight(), index);
1164
    stack_[index] = value;
1165 1166
  }

1167 1168
  TrapReason GetTrapReason() { return trap_reason_; }

1169
  pc_t GetBreakpointPc() { return break_pc_; }
1170

1171
  bool PossibleNondeterminism() { return possible_nondeterminism_; }
1172

1173 1174
  uint64_t NumInterpretedCalls() { return num_interpreted_calls_; }

1175 1176 1177 1178
  void AddBreakFlags(uint8_t flags) { break_flags_ |= flags; }

  void ClearBreakFlags() { break_flags_ = WasmInterpreter::BreakFlag::None; }

1179 1180 1181 1182 1183 1184 1185 1186
  uint32_t NumActivations() {
    return static_cast<uint32_t>(activations_.size());
  }

  uint32_t StartActivation() {
    TRACE("----- START ACTIVATION %zu -----\n", activations_.size());
    // If you use activations, use them consistently:
    DCHECK_IMPLIES(activations_.empty(), frames_.empty());
1187
    DCHECK_IMPLIES(activations_.empty(), StackHeight() == 0);
1188 1189
    uint32_t activation_id = static_cast<uint32_t>(activations_.size());
    activations_.emplace_back(static_cast<uint32_t>(frames_.size()),
1190
                              StackHeight());
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    state_ = WasmInterpreter::STOPPED;
    return activation_id;
  }

  void FinishActivation(uint32_t id) {
    TRACE("----- FINISH ACTIVATION %zu -----\n", activations_.size() - 1);
    DCHECK_LT(0, activations_.size());
    DCHECK_EQ(activations_.size() - 1, id);
    // Stack height must match the start of this activation (otherwise unwind
    // first).
    DCHECK_EQ(activations_.back().fp, frames_.size());
1202
    DCHECK_LE(activations_.back().sp, StackHeight());
1203
    sp_ = stack_.get() + activations_.back().sp;
1204 1205 1206 1207 1208 1209 1210 1211
    activations_.pop_back();
  }

  uint32_t ActivationFrameBase(uint32_t id) {
    DCHECK_GT(activations_.size(), id);
    return activations_[id].fp;
  }

1212
  // Handle a thrown exception. Returns whether the exception was handled inside
1213
  // the current activation. Unwinds the interpreted stack accordingly.
1214 1215 1216
  WasmInterpreter::Thread::ExceptionHandlingResult HandleException(
      Isolate* isolate) {
    DCHECK(isolate->has_pending_exception());
1217
    // TODO(wasm): Add wasm exception handling (would return HANDLED).
1218 1219
    USE(isolate->pending_exception());
    TRACE("----- UNWIND -----\n");
1220 1221 1222 1223
    DCHECK_LT(0, activations_.size());
    Activation& act = activations_.back();
    DCHECK_LE(act.fp, frames_.size());
    frames_.resize(act.fp);
1224
    DCHECK_LE(act.sp, StackHeight());
1225
    sp_ = stack_.get() + act.sp;
1226 1227 1228 1229
    state_ = WasmInterpreter::STOPPED;
    return WasmInterpreter::Thread::UNWOUND;
  }

1230 1231 1232 1233
 private:
  // Entries on the stack of functions being evaluated.
  struct Frame {
    InterpreterCode* code;
1234
    pc_t pc;
1235 1236 1237 1238 1239
    sp_t sp;

    // Limit of parameters.
    sp_t plimit() { return sp + code->function->sig->parameter_count(); }
    // Limit of locals.
1240
    sp_t llimit() { return plimit() + code->locals.type_list.size(); }
1241 1242
  };

1243 1244 1245 1246 1247 1248 1249
  struct Block {
    pc_t pc;
    sp_t sp;
    size_t fp;
    unsigned arity;
  };

1250 1251
  friend class InterpretedFrameImpl;

1252
  CodeMap* codemap_;
1253
  Handle<WasmInstanceObject> instance_object_;
1254
  std::unique_ptr<WasmValue[]> stack_;
1255 1256
  WasmValue* stack_limit_ = nullptr;  // End of allocated stack space.
  WasmValue* sp_ = nullptr;           // Current stack pointer.
1257
  ZoneVector<Frame> frames_;
1258 1259 1260 1261 1262
  WasmInterpreter::State state_ = WasmInterpreter::STOPPED;
  pc_t break_pc_ = kInvalidPc;
  TrapReason trap_reason_ = kTrapCount;
  bool possible_nondeterminism_ = false;
  uint8_t break_flags_ = 0;  // a combination of WasmInterpreter::BreakFlag
1263
  uint64_t num_interpreted_calls_ = 0;
1264 1265 1266
  // Store the stack height of each activation (for unwind and frame
  // inspection).
  ZoneVector<Activation> activations_;
1267

1268 1269
  CodeMap* codemap() const { return codemap_; }
  const WasmModule* module() const { return codemap_->module(); }
1270 1271

  void DoTrap(TrapReason trap, pc_t pc) {
1272
    TRACE("TRAP: %s\n", WasmOpcodes::TrapReasonMessage(trap));
1273 1274 1275 1276 1277 1278
    state_ = WasmInterpreter::TRAPPED;
    trap_reason_ = trap;
    CommitPc(pc);
  }

  // Push a frame with arguments already on the stack.
1279 1280
  void PushFrame(InterpreterCode* code) {
    DCHECK_NOT_NULL(code);
1281 1282 1283 1284
    DCHECK_NOT_NULL(code->side_table);
    EnsureStackSpace(code->side_table->max_stack_height_ +
                     code->locals.type_list.size());

1285
    ++num_interpreted_calls_;
1286 1287
    size_t arity = code->function->sig->parameter_count();
    // The parameters will overlap the arguments already on the stack.
1288 1289
    DCHECK_GE(StackHeight(), arity);
    frames_.push_back({code, 0, StackHeight() - arity});
1290
    frames_.back().pc = InitLocals(code);
1291 1292
    TRACE("  => PushFrame #%zu (#%u @%zu)\n", frames_.size() - 1,
          code->function->func_index, frames_.back().pc);
1293 1294 1295
  }

  pc_t InitLocals(InterpreterCode* code) {
1296
    for (auto p : code->locals.type_list) {
1297
      WasmValue val;
1298
      switch (p) {
1299 1300 1301
#define CASE_TYPE(wasm, ctype) \
  case kWasm##wasm:            \
    val = WasmValue(ctype{});  \
1302 1303 1304
    break;
        WASM_CTYPES(CASE_TYPE)
#undef CASE_TYPE
1305 1306 1307 1308
        default:
          UNREACHABLE();
          break;
      }
1309
      Push(val);
1310
    }
1311
    return code->locals.encoded_size;
1312 1313 1314
  }

  void CommitPc(pc_t pc) {
1315 1316
    DCHECK(!frames_.empty());
    frames_.back().pc = pc;
1317 1318 1319
  }

  bool SkipBreakpoint(InterpreterCode* code, pc_t pc) {
1320
    if (pc == break_pc_) {
1321
      // Skip the previously hit breakpoint when resuming.
1322 1323 1324
      break_pc_ = kInvalidPc;
      return true;
    }
1325 1326 1327
    return false;
  }

1328
  int LookupTargetDelta(InterpreterCode* code, pc_t pc) {
1329
    return static_cast<int>(code->side_table->Lookup(pc).pc_diff);
1330 1331 1332
  }

  int DoBreak(InterpreterCode* code, pc_t pc, size_t depth) {
1333 1334
    ControlTransferEntry& control_transfer_entry = code->side_table->Lookup(pc);
    DoStackTransfer(sp_ - control_transfer_entry.sp_diff,
1335 1336
                    control_transfer_entry.target_arity);
    return control_transfer_entry.pc_diff;
1337 1338
  }

1339 1340 1341
  pc_t ReturnPc(Decoder* decoder, InterpreterCode* code, pc_t pc) {
    switch (code->orig_start[pc]) {
      case kExprCallFunction: {
1342 1343
        CallFunctionImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc));
        return pc + 1 + imm.length;
1344 1345
      }
      case kExprCallIndirect: {
1346 1347
        CallIndirectImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc));
        return pc + 1 + imm.length;
1348 1349 1350 1351 1352 1353 1354 1355
      }
      default:
        UNREACHABLE();
    }
  }

  bool DoReturn(Decoder* decoder, InterpreterCode** code, pc_t* pc, pc_t* limit,
                size_t arity) {
1356
    DCHECK_GT(frames_.size(), 0);
1357
    WasmValue* sp_dest = stack_.get() + frames_.back().sp;
1358
    frames_.pop_back();
1359
    if (frames_.size() == current_activation().fp) {
1360
      // A return from the last frame terminates the execution.
1361
      state_ = WasmInterpreter::FINISHED;
1362
      DoStackTransfer(sp_dest, arity);
1363 1364 1365 1366 1367 1368
      TRACE("  => finish\n");
      return false;
    } else {
      // Return to caller frame.
      Frame* top = &frames_.back();
      *code = top->code;
1369 1370
      decoder->Reset((*code)->start, (*code)->end);
      *pc = ReturnPc(decoder, *code, top->pc);
1371
      *limit = top->code->end - top->code->start;
1372 1373
      TRACE("  => Return to #%zu (#%u @%zu)\n", frames_.size() - 1,
            (*code)->function->func_index, *pc);
1374
      DoStackTransfer(sp_dest, arity);
1375 1376 1377 1378
      return true;
    }
  }

1379 1380 1381
  // Returns true if the call was successful, false if the stack check failed
  // and the current activation was fully unwound.
  bool DoCall(Decoder* decoder, InterpreterCode* target, pc_t* pc,
1382
              pc_t* limit) V8_WARN_UNUSED_RESULT {
1383 1384
    frames_.back().pc = *pc;
    PushFrame(target);
1385
    if (!DoStackCheck()) return false;
1386
    *pc = frames_.back().pc;
1387
    *limit = target->end - target->start;
1388
    decoder->Reset(target->start, target->end);
1389
    return true;
1390 1391
  }

1392 1393
  // Copies {arity} values on the top of the stack down the stack to {dest},
  // dropping the values in-between.
1394
  void DoStackTransfer(WasmValue* dest, size_t arity) {
1395
    // before: |---------------| pop_count | arity |
1396
    //         ^ 0             ^ dest              ^ sp_
1397 1398
    //
    // after:  |---------------| arity |
1399 1400 1401
    //         ^ 0                     ^ sp_
    DCHECK_LE(dest, sp_);
    DCHECK_LE(dest + arity, sp_);
1402
    if (arity) memmove(dest, sp_ - arity, arity * sizeof(*sp_));
1403
    sp_ = dest + arity;
1404 1405
  }

1406
  template <typename mtype>
1407
  inline Address BoundsCheckMem(uint32_t offset, uint32_t index) {
1408
    size_t mem_size = instance_object_->memory_size();
1409 1410 1411
    if (sizeof(mtype) > mem_size) return kNullAddress;
    if (offset > (mem_size - sizeof(mtype))) return kNullAddress;
    if (index > (mem_size - sizeof(mtype) - offset)) return kNullAddress;
1412 1413
    // Compute the effective address of the access, making sure to condition
    // the index even in the in-bounds case.
1414 1415
    return reinterpret_cast<Address>(instance_object_->memory_start()) +
           offset + (index & instance_object_->memory_mask());
1416 1417
  }

1418
  template <typename ctype, typename mtype>
1419 1420
  bool ExecuteLoad(Decoder* decoder, InterpreterCode* code, pc_t pc, int& len,
                   MachineRepresentation rep) {
1421 1422
    MemoryAccessImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc),
                                                    sizeof(ctype));
1423
    uint32_t index = Pop().to<uint32_t>();
1424
    Address addr = BoundsCheckMem<mtype>(imm.offset, index);
1425
    if (!addr) {
1426 1427 1428
      DoTrap(kTrapMemOutOfBounds, pc);
      return false;
    }
1429 1430
    WasmValue result(
        converter<ctype, mtype>{}(ReadLittleEndianValue<mtype>(addr)));
1431

1432
    Push(result);
1433
    len = 1 + imm.length;
1434

1435
    if (FLAG_trace_wasm_memory) {
1436
      MemoryTracingInfo info(imm.offset + index, false, rep);
1437
      TraceMemoryOperation(ExecutionTier::kInterpreter, &info,
1438
                           code->function->func_index, static_cast<int>(pc),
1439
                           instance_object_->memory_start());
1440 1441
    }

1442 1443 1444 1445
    return true;
  }

  template <typename ctype, typename mtype>
1446 1447
  bool ExecuteStore(Decoder* decoder, InterpreterCode* code, pc_t pc, int& len,
                    MachineRepresentation rep) {
1448 1449
    MemoryAccessImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc),
                                                    sizeof(ctype));
1450
    ctype val = Pop().to<ctype>();
1451 1452

    uint32_t index = Pop().to<uint32_t>();
1453
    Address addr = BoundsCheckMem<mtype>(imm.offset, index);
1454
    if (!addr) {
1455 1456 1457
      DoTrap(kTrapMemOutOfBounds, pc);
      return false;
    }
1458
    WriteLittleEndianValue<mtype>(addr, converter<mtype, ctype>{}(val));
1459
    len = 1 + imm.length;
1460

1461
    if (FLAG_trace_wasm_memory) {
1462
      MemoryTracingInfo info(imm.offset + index, true, rep);
1463
      TraceMemoryOperation(ExecutionTier::kInterpreter, &info,
1464
                           code->function->func_index, static_cast<int>(pc),
1465
                           instance_object_->memory_start());
1466 1467
    }

1468 1469 1470
    return true;
  }

1471
  template <typename type, typename op_type>
1472 1473
  bool ExtractAtomicOpParams(Decoder* decoder, InterpreterCode* code,
                             Address& address, pc_t pc, int& len,
1474
                             type* val = nullptr, type* val2 = nullptr) {
1475 1476
    MemoryAccessImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc + 1),
                                                    sizeof(type));
1477 1478
    if (val2) *val2 = static_cast<type>(Pop().to<op_type>());
    if (val) *val = static_cast<type>(Pop().to<op_type>());
1479
    uint32_t index = Pop().to<uint32_t>();
1480
    address = BoundsCheckMem<type>(imm.offset, index);
1481
    if (!address) {
1482 1483 1484
      DoTrap(kTrapMemOutOfBounds, pc);
      return false;
    }
1485
    len = 2 + imm.length;
1486 1487 1488
    return true;
  }

1489 1490 1491
  bool ExecuteNumericOp(WasmOpcode opcode, Decoder* decoder,
                        InterpreterCode* code, pc_t pc, int& len) {
    switch (opcode) {
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
      case kExprI32SConvertSatF32:
        Push(WasmValue(ExecuteConvertSaturate<int32_t>(Pop().to<float>())));
        return true;
      case kExprI32UConvertSatF32:
        Push(WasmValue(ExecuteConvertSaturate<uint32_t>(Pop().to<float>())));
        return true;
      case kExprI32SConvertSatF64:
        Push(WasmValue(ExecuteConvertSaturate<int32_t>(Pop().to<double>())));
        return true;
      case kExprI32UConvertSatF64:
        Push(WasmValue(ExecuteConvertSaturate<uint32_t>(Pop().to<double>())));
1503
        return true;
1504
      case kExprI64SConvertSatF32:
1505 1506
        Push(WasmValue(ExecuteI64SConvertSatF32(Pop().to<float>())));
        return true;
1507 1508 1509 1510 1511 1512 1513 1514 1515
      case kExprI64UConvertSatF32:
        Push(WasmValue(ExecuteI64UConvertSatF32(Pop().to<float>())));
        return true;
      case kExprI64SConvertSatF64:
        Push(WasmValue(ExecuteI64SConvertSatF64(Pop().to<double>())));
        return true;
      case kExprI64UConvertSatF64:
        Push(WasmValue(ExecuteI64UConvertSatF64(Pop().to<double>())));
        return true;
1516
      default:
1517 1518
        FATAL("Unknown or unimplemented opcode #%d:%s", code->start[pc],
              OpcodeName(code->start[pc]));
1519 1520 1521 1522 1523
        UNREACHABLE();
    }
    return false;
  }

1524 1525 1526 1527
  bool ExecuteAtomicOp(WasmOpcode opcode, Decoder* decoder,
                       InterpreterCode* code, pc_t pc, int& len) {
    WasmValue result;
    switch (opcode) {
1528 1529 1530 1531
// Disabling on Mips as 32 bit atomics are not correctly laid out for load/store
// on big endian and 64 bit atomics fail to compile.
#if !(V8_TARGET_ARCH_MIPS && V8_TARGET_BIG_ENDIAN)
#define ATOMIC_BINOP_CASE(name, type, op_type, operation)                   \
1532 1533 1534
  case kExpr##name: {                                                       \
    type val;                                                               \
    Address addr;                                                           \
1535 1536
    if (!ExtractAtomicOpParams<type, op_type>(decoder, code, addr, pc, len, \
                                              &val)) {                      \
1537 1538 1539 1540 1541
      return false;                                                         \
    }                                                                       \
    static_assert(sizeof(std::atomic<type>) == sizeof(type),                \
                  "Size mismatch for types std::atomic<" #type              \
                  ">, and " #type);                                         \
1542 1543
    result = WasmValue(static_cast<op_type>(                                \
        std::operation(reinterpret_cast<std::atomic<type>*>(addr), val)));  \
1544 1545
    Push(result);                                                           \
    break;                                                                  \
1546
  }
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
      ATOMIC_BINOP_CASE(I32AtomicAdd, uint32_t, uint32_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I32AtomicAdd8U, uint8_t, uint32_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I32AtomicAdd16U, uint16_t, uint32_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I32AtomicSub, uint32_t, uint32_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I32AtomicSub8U, uint8_t, uint32_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I32AtomicSub16U, uint16_t, uint32_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I32AtomicAnd, uint32_t, uint32_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I32AtomicAnd8U, uint8_t, uint32_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I32AtomicAnd16U, uint16_t, uint32_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I32AtomicOr, uint32_t, uint32_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I32AtomicOr8U, uint8_t, uint32_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I32AtomicOr16U, uint16_t, uint32_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I32AtomicXor, uint32_t, uint32_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I32AtomicXor8U, uint8_t, uint32_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I32AtomicXor16U, uint16_t, uint32_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I32AtomicExchange, uint32_t, uint32_t, atomic_exchange);
      ATOMIC_BINOP_CASE(I32AtomicExchange8U, uint8_t, uint32_t,
                        atomic_exchange);
      ATOMIC_BINOP_CASE(I32AtomicExchange16U, uint16_t, uint32_t,
                        atomic_exchange);
      ATOMIC_BINOP_CASE(I64AtomicAdd, uint64_t, uint64_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I64AtomicAdd8U, uint8_t, uint64_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I64AtomicAdd16U, uint16_t, uint64_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I64AtomicAdd32U, uint32_t, uint64_t, atomic_fetch_add);
      ATOMIC_BINOP_CASE(I64AtomicSub, uint64_t, uint64_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I64AtomicSub8U, uint8_t, uint64_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I64AtomicSub16U, uint16_t, uint64_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I64AtomicSub32U, uint32_t, uint64_t, atomic_fetch_sub);
      ATOMIC_BINOP_CASE(I64AtomicAnd, uint64_t, uint64_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I64AtomicAnd8U, uint8_t, uint64_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I64AtomicAnd16U, uint16_t, uint64_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I64AtomicAnd32U, uint32_t, uint64_t, atomic_fetch_and);
      ATOMIC_BINOP_CASE(I64AtomicOr, uint64_t, uint64_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I64AtomicOr8U, uint8_t, uint64_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I64AtomicOr16U, uint16_t, uint64_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I64AtomicOr32U, uint32_t, uint64_t, atomic_fetch_or);
      ATOMIC_BINOP_CASE(I64AtomicXor, uint64_t, uint64_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I64AtomicXor8U, uint8_t, uint64_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I64AtomicXor16U, uint16_t, uint64_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I64AtomicXor32U, uint32_t, uint64_t, atomic_fetch_xor);
      ATOMIC_BINOP_CASE(I64AtomicExchange, uint64_t, uint64_t, atomic_exchange);
      ATOMIC_BINOP_CASE(I64AtomicExchange8U, uint8_t, uint64_t,
                        atomic_exchange);
      ATOMIC_BINOP_CASE(I64AtomicExchange16U, uint16_t, uint64_t,
                        atomic_exchange);
      ATOMIC_BINOP_CASE(I64AtomicExchange32U, uint32_t, uint64_t,
                        atomic_exchange);
1594
#undef ATOMIC_BINOP_CASE
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
#define ATOMIC_COMPARE_EXCHANGE_CASE(name, type, op_type)                   \
  case kExpr##name: {                                                       \
    type val;                                                               \
    type val2;                                                              \
    Address addr;                                                           \
    if (!ExtractAtomicOpParams<type, op_type>(decoder, code, addr, pc, len, \
                                              &val, &val2)) {               \
      return false;                                                         \
    }                                                                       \
    static_assert(sizeof(std::atomic<type>) == sizeof(type),                \
                  "Size mismatch for types std::atomic<" #type              \
                  ">, and " #type);                                         \
    std::atomic_compare_exchange_strong(                                    \
        reinterpret_cast<std::atomic<type>*>(addr), &val, val2);            \
    Push(WasmValue(static_cast<op_type>(val)));                             \
    break;                                                                  \
  }
      ATOMIC_COMPARE_EXCHANGE_CASE(I32AtomicCompareExchange, uint32_t,
                                   uint32_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I32AtomicCompareExchange8U, uint8_t,
                                   uint32_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I32AtomicCompareExchange16U, uint16_t,
                                   uint32_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I64AtomicCompareExchange, uint64_t,
                                   uint64_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I64AtomicCompareExchange8U, uint8_t,
                                   uint64_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I64AtomicCompareExchange16U, uint16_t,
                                   uint64_t);
      ATOMIC_COMPARE_EXCHANGE_CASE(I64AtomicCompareExchange32U, uint32_t,
                                   uint64_t);
1626
#undef ATOMIC_COMPARE_EXCHANGE_CASE
1627
#define ATOMIC_LOAD_CASE(name, type, op_type, operation)                       \
1628 1629
  case kExpr##name: {                                                          \
    Address addr;                                                              \
1630
    if (!ExtractAtomicOpParams<type, op_type>(decoder, code, addr, pc, len)) { \
1631 1632 1633 1634 1635
      return false;                                                            \
    }                                                                          \
    static_assert(sizeof(std::atomic<type>) == sizeof(type),                   \
                  "Size mismatch for types std::atomic<" #type                 \
                  ">, and " #type);                                            \
1636 1637
    result = WasmValue(static_cast<op_type>(                                   \
        std::operation(reinterpret_cast<std::atomic<type>*>(addr))));          \
1638 1639 1640
    Push(result);                                                              \
    break;                                                                     \
  }
1641 1642 1643 1644 1645 1646 1647
      ATOMIC_LOAD_CASE(I32AtomicLoad, uint32_t, uint32_t, atomic_load);
      ATOMIC_LOAD_CASE(I32AtomicLoad8U, uint8_t, uint32_t, atomic_load);
      ATOMIC_LOAD_CASE(I32AtomicLoad16U, uint16_t, uint32_t, atomic_load);
      ATOMIC_LOAD_CASE(I64AtomicLoad, uint64_t, uint64_t, atomic_load);
      ATOMIC_LOAD_CASE(I64AtomicLoad8U, uint8_t, uint64_t, atomic_load);
      ATOMIC_LOAD_CASE(I64AtomicLoad16U, uint16_t, uint64_t, atomic_load);
      ATOMIC_LOAD_CASE(I64AtomicLoad32U, uint32_t, uint64_t, atomic_load);
1648
#undef ATOMIC_LOAD_CASE
1649
#define ATOMIC_STORE_CASE(name, type, op_type, operation)                   \
1650 1651 1652
  case kExpr##name: {                                                       \
    type val;                                                               \
    Address addr;                                                           \
1653 1654
    if (!ExtractAtomicOpParams<type, op_type>(decoder, code, addr, pc, len, \
                                              &val)) {                      \
1655 1656 1657 1658 1659 1660 1661 1662
      return false;                                                         \
    }                                                                       \
    static_assert(sizeof(std::atomic<type>) == sizeof(type),                \
                  "Size mismatch for types std::atomic<" #type              \
                  ">, and " #type);                                         \
    std::operation(reinterpret_cast<std::atomic<type>*>(addr), val);        \
    break;                                                                  \
  }
1663 1664 1665 1666 1667 1668 1669
      ATOMIC_STORE_CASE(I32AtomicStore, uint32_t, uint32_t, atomic_store);
      ATOMIC_STORE_CASE(I32AtomicStore8U, uint8_t, uint32_t, atomic_store);
      ATOMIC_STORE_CASE(I32AtomicStore16U, uint16_t, uint32_t, atomic_store);
      ATOMIC_STORE_CASE(I64AtomicStore, uint64_t, uint64_t, atomic_store);
      ATOMIC_STORE_CASE(I64AtomicStore8U, uint8_t, uint64_t, atomic_store);
      ATOMIC_STORE_CASE(I64AtomicStore16U, uint16_t, uint64_t, atomic_store);
      ATOMIC_STORE_CASE(I64AtomicStore32U, uint32_t, uint64_t, atomic_store);
1670
#undef ATOMIC_STORE_CASE
1671
#endif  // !(V8_TARGET_ARCH_MIPS && V8_TARGET_BIG_ENDIAN)
1672
      default:
1673
        UNREACHABLE();
1674 1675 1676 1677 1678
        return false;
    }
    return true;
  }

1679 1680 1681 1682 1683 1684 1685 1686 1687
  byte* GetGlobalPtr(const WasmGlobal* global) {
    if (global->mutability && global->imported) {
      return reinterpret_cast<byte*>(
          instance_object_->imported_mutable_globals()[global->index]);
    } else {
      return instance_object_->globals_start() + global->offset;
    }
  }

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  bool ExecuteSimdOp(WasmOpcode opcode, Decoder* decoder, InterpreterCode* code,
                     pc_t pc, int& len) {
    switch (opcode) {
#define SPLAT_CASE(format, sType, valType, num) \
  case kExpr##format##Splat: {                  \
    WasmValue val = Pop();                      \
    valType v = val.to<valType>();              \
    sType s;                                    \
    for (int i = 0; i < num; i++) s.val[i] = v; \
    Push(WasmValue(Simd128(s)));                \
    return true;                                \
  }
      SPLAT_CASE(I32x4, int4, int32_t, 4)
      SPLAT_CASE(F32x4, float4, float, 4)
      SPLAT_CASE(I16x8, int8, int32_t, 8)
      SPLAT_CASE(I8x16, int16, int32_t, 16)
#undef SPLAT_CASE
#define EXTRACT_LANE_CASE(format, name)                                 \
  case kExpr##format##ExtractLane: {                                    \
    SimdLaneImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc)); \
    ++len;                                                              \
    WasmValue val = Pop();                                              \
    Simd128 s = val.to_s128();                                          \
1711 1712
    auto ss = s.to_##name();                                            \
    Push(WasmValue(ss.val[LANE(imm.lane, ss)]));                        \
1713 1714 1715 1716 1717 1718 1719
    return true;                                                        \
  }
      EXTRACT_LANE_CASE(I32x4, i32x4)
      EXTRACT_LANE_CASE(F32x4, f32x4)
      EXTRACT_LANE_CASE(I16x8, i16x8)
      EXTRACT_LANE_CASE(I8x16, i8x16)
#undef EXTRACT_LANE_CASE
1720 1721 1722 1723 1724 1725 1726 1727
#define BINOP_CASE(op, name, stype, count, expr) \
  case kExpr##op: {                              \
    WasmValue v2 = Pop();                        \
    WasmValue v1 = Pop();                        \
    stype s1 = v1.to_s128().to_##name();         \
    stype s2 = v2.to_s128().to_##name();         \
    stype res;                                   \
    for (size_t i = 0; i < count; ++i) {         \
1728 1729 1730
      auto a = s1.val[LANE(i, s1)];              \
      auto b = s2.val[LANE(i, s1)];              \
      res.val[LANE(i, s1)] = expr;               \
1731 1732 1733 1734 1735 1736 1737 1738 1739
    }                                            \
    Push(WasmValue(Simd128(res)));               \
    return true;                                 \
  }
      BINOP_CASE(F32x4Add, f32x4, float4, 4, a + b)
      BINOP_CASE(F32x4Sub, f32x4, float4, 4, a - b)
      BINOP_CASE(F32x4Mul, f32x4, float4, 4, a * b)
      BINOP_CASE(F32x4Min, f32x4, float4, 4, a < b ? a : b)
      BINOP_CASE(F32x4Max, f32x4, float4, 4, a > b ? a : b)
1740 1741 1742 1743
      BINOP_CASE(I32x4Add, i32x4, int4, 4, a + b)
      BINOP_CASE(I32x4Sub, i32x4, int4, 4, a - b)
      BINOP_CASE(I32x4Mul, i32x4, int4, 4, a * b)
      BINOP_CASE(I32x4MinS, i32x4, int4, 4, a < b ? a : b)
1744 1745
      BINOP_CASE(I32x4MinU, i32x4, int4, 4,
                 static_cast<uint32_t>(a) < static_cast<uint32_t>(b) ? a : b)
1746
      BINOP_CASE(I32x4MaxS, i32x4, int4, 4, a > b ? a : b)
1747 1748
      BINOP_CASE(I32x4MaxU, i32x4, int4, 4,
                 static_cast<uint32_t>(a) > static_cast<uint32_t>(b) ? a : b)
1749 1750 1751
      BINOP_CASE(S128And, i32x4, int4, 4, a & b)
      BINOP_CASE(S128Or, i32x4, int4, 4, a | b)
      BINOP_CASE(S128Xor, i32x4, int4, 4, a ^ b)
1752 1753 1754 1755
      BINOP_CASE(I16x8Add, i16x8, int8, 8, a + b)
      BINOP_CASE(I16x8Sub, i16x8, int8, 8, a - b)
      BINOP_CASE(I16x8Mul, i16x8, int8, 8, a * b)
      BINOP_CASE(I16x8MinS, i16x8, int8, 8, a < b ? a : b)
1756 1757
      BINOP_CASE(I16x8MinU, i16x8, int8, 8,
                 static_cast<uint16_t>(a) < static_cast<uint16_t>(b) ? a : b)
1758
      BINOP_CASE(I16x8MaxS, i16x8, int8, 8, a > b ? a : b)
1759 1760
      BINOP_CASE(I16x8MaxU, i16x8, int8, 8,
                 static_cast<uint16_t>(a) > static_cast<uint16_t>(b) ? a : b)
1761
      BINOP_CASE(I16x8AddSaturateS, i16x8, int8, 8, SaturateAdd<int16_t>(a, b))
1762
      BINOP_CASE(I16x8AddSaturateU, i16x8, int8, 8, SaturateAdd<uint16_t>(a, b))
1763
      BINOP_CASE(I16x8SubSaturateS, i16x8, int8, 8, SaturateSub<int16_t>(a, b))
1764 1765 1766 1767 1768
      BINOP_CASE(I16x8SubSaturateU, i16x8, int8, 8, SaturateSub<uint16_t>(a, b))
      BINOP_CASE(I8x16Add, i8x16, int16, 16, a + b)
      BINOP_CASE(I8x16Sub, i8x16, int16, 16, a - b)
      BINOP_CASE(I8x16Mul, i8x16, int16, 16, a * b)
      BINOP_CASE(I8x16MinS, i8x16, int16, 16, a < b ? a : b)
1769 1770
      BINOP_CASE(I8x16MinU, i8x16, int16, 16,
                 static_cast<uint8_t>(a) < static_cast<uint8_t>(b) ? a : b)
1771
      BINOP_CASE(I8x16MaxS, i8x16, int16, 16, a > b ? a : b)
1772 1773
      BINOP_CASE(I8x16MaxU, i8x16, int16, 16,
                 static_cast<uint8_t>(a) > static_cast<uint8_t>(b) ? a : b)
1774
      BINOP_CASE(I8x16AddSaturateS, i8x16, int16, 16, SaturateAdd<int8_t>(a, b))
1775
      BINOP_CASE(I8x16AddSaturateU, i8x16, int16, 16,
1776 1777
                 SaturateAdd<uint8_t>(a, b))
      BINOP_CASE(I8x16SubSaturateS, i8x16, int16, 16, SaturateSub<int8_t>(a, b))
1778
      BINOP_CASE(I8x16SubSaturateU, i8x16, int16, 16,
1779 1780
                 SaturateSub<uint8_t>(a, b))
#undef BINOP_CASE
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
#define UNOP_CASE(op, name, stype, count, expr) \
  case kExpr##op: {                             \
    WasmValue v = Pop();                        \
    stype s = v.to_s128().to_##name();          \
    stype res;                                  \
    for (size_t i = 0; i < count; ++i) {        \
      auto a = s.val[i];                        \
      res.val[i] = expr;                        \
    }                                           \
    Push(WasmValue(Simd128(res)));              \
    return true;                                \
  }
      UNOP_CASE(F32x4Abs, f32x4, float4, 4, std::abs(a))
      UNOP_CASE(F32x4Neg, f32x4, float4, 4, -a)
      UNOP_CASE(F32x4RecipApprox, f32x4, float4, 4, 1.0f / a)
      UNOP_CASE(F32x4RecipSqrtApprox, f32x4, float4, 4, 1.0f / std::sqrt(a))
1797
      UNOP_CASE(I32x4Neg, i32x4, int4, 4, -a)
1798
      UNOP_CASE(S128Not, i32x4, int4, 4, ~a)
1799 1800
      UNOP_CASE(I16x8Neg, i16x8, int8, 8, -a)
      UNOP_CASE(I8x16Neg, i8x16, int16, 16, -a)
1801
#undef UNOP_CASE
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
#define CMPOP_CASE(op, name, stype, out_stype, count, expr) \
  case kExpr##op: {                                         \
    WasmValue v2 = Pop();                                   \
    WasmValue v1 = Pop();                                   \
    stype s1 = v1.to_s128().to_##name();                    \
    stype s2 = v2.to_s128().to_##name();                    \
    out_stype res;                                          \
    for (size_t i = 0; i < count; ++i) {                    \
      auto a = s1.val[i];                                   \
      auto b = s2.val[i];                                   \
      res.val[i] = expr ? -1 : 0;                           \
    }                                                       \
    Push(WasmValue(Simd128(res)));                          \
    return true;                                            \
  }
      CMPOP_CASE(F32x4Eq, f32x4, float4, int4, 4, a == b)
      CMPOP_CASE(F32x4Ne, f32x4, float4, int4, 4, a != b)
      CMPOP_CASE(F32x4Gt, f32x4, float4, int4, 4, a > b)
      CMPOP_CASE(F32x4Ge, f32x4, float4, int4, 4, a >= b)
      CMPOP_CASE(F32x4Lt, f32x4, float4, int4, 4, a < b)
      CMPOP_CASE(F32x4Le, f32x4, float4, int4, 4, a <= b)
      CMPOP_CASE(I32x4Eq, i32x4, int4, int4, 4, a == b)
      CMPOP_CASE(I32x4Ne, i32x4, int4, int4, 4, a != b)
      CMPOP_CASE(I32x4GtS, i32x4, int4, int4, 4, a > b)
      CMPOP_CASE(I32x4GeS, i32x4, int4, int4, 4, a >= b)
      CMPOP_CASE(I32x4LtS, i32x4, int4, int4, 4, a < b)
      CMPOP_CASE(I32x4LeS, i32x4, int4, int4, 4, a <= b)
1829 1830 1831 1832 1833 1834 1835 1836
      CMPOP_CASE(I32x4GtU, i32x4, int4, int4, 4,
                 static_cast<uint32_t>(a) > static_cast<uint32_t>(b))
      CMPOP_CASE(I32x4GeU, i32x4, int4, int4, 4,
                 static_cast<uint32_t>(a) >= static_cast<uint32_t>(b))
      CMPOP_CASE(I32x4LtU, i32x4, int4, int4, 4,
                 static_cast<uint32_t>(a) < static_cast<uint32_t>(b))
      CMPOP_CASE(I32x4LeU, i32x4, int4, int4, 4,
                 static_cast<uint32_t>(a) <= static_cast<uint32_t>(b))
1837 1838 1839 1840 1841 1842
      CMPOP_CASE(I16x8Eq, i16x8, int8, int8, 8, a == b)
      CMPOP_CASE(I16x8Ne, i16x8, int8, int8, 8, a != b)
      CMPOP_CASE(I16x8GtS, i16x8, int8, int8, 8, a > b)
      CMPOP_CASE(I16x8GeS, i16x8, int8, int8, 8, a >= b)
      CMPOP_CASE(I16x8LtS, i16x8, int8, int8, 8, a < b)
      CMPOP_CASE(I16x8LeS, i16x8, int8, int8, 8, a <= b)
1843 1844 1845 1846 1847 1848 1849 1850
      CMPOP_CASE(I16x8GtU, i16x8, int8, int8, 8,
                 static_cast<uint16_t>(a) > static_cast<uint16_t>(b))
      CMPOP_CASE(I16x8GeU, i16x8, int8, int8, 8,
                 static_cast<uint16_t>(a) >= static_cast<uint16_t>(b))
      CMPOP_CASE(I16x8LtU, i16x8, int8, int8, 8,
                 static_cast<uint16_t>(a) < static_cast<uint16_t>(b))
      CMPOP_CASE(I16x8LeU, i16x8, int8, int8, 8,
                 static_cast<uint16_t>(a) <= static_cast<uint16_t>(b))
1851 1852 1853 1854 1855 1856
      CMPOP_CASE(I8x16Eq, i8x16, int16, int16, 16, a == b)
      CMPOP_CASE(I8x16Ne, i8x16, int16, int16, 16, a != b)
      CMPOP_CASE(I8x16GtS, i8x16, int16, int16, 16, a > b)
      CMPOP_CASE(I8x16GeS, i8x16, int16, int16, 16, a >= b)
      CMPOP_CASE(I8x16LtS, i8x16, int16, int16, 16, a < b)
      CMPOP_CASE(I8x16LeS, i8x16, int16, int16, 16, a <= b)
1857 1858 1859 1860 1861 1862 1863 1864
      CMPOP_CASE(I8x16GtU, i8x16, int16, int16, 16,
                 static_cast<uint8_t>(a) > static_cast<uint8_t>(b))
      CMPOP_CASE(I8x16GeU, i8x16, int16, int16, 16,
                 static_cast<uint8_t>(a) >= static_cast<uint8_t>(b))
      CMPOP_CASE(I8x16LtU, i8x16, int16, int16, 16,
                 static_cast<uint8_t>(a) < static_cast<uint8_t>(b))
      CMPOP_CASE(I8x16LeU, i8x16, int16, int16, 16,
                 static_cast<uint8_t>(a) <= static_cast<uint8_t>(b))
1865
#undef CMPOP_CASE
1866 1867 1868 1869 1870 1871 1872
#define REPLACE_LANE_CASE(format, name, stype, ctype)                   \
  case kExpr##format##ReplaceLane: {                                    \
    SimdLaneImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc)); \
    ++len;                                                              \
    WasmValue new_val = Pop();                                          \
    WasmValue simd_val = Pop();                                         \
    stype s = simd_val.to_s128().to_##name();                           \
1873
    s.val[LANE(imm.lane, s)] = new_val.to<ctype>();                     \
1874 1875 1876 1877 1878 1879 1880 1881
    Push(WasmValue(Simd128(s)));                                        \
    return true;                                                        \
  }
      REPLACE_LANE_CASE(F32x4, f32x4, float4, float)
      REPLACE_LANE_CASE(I32x4, i32x4, int4, int32_t)
      REPLACE_LANE_CASE(I16x8, i16x8, int8, int32_t)
      REPLACE_LANE_CASE(I8x16, i8x16, int16, int32_t)
#undef REPLACE_LANE_CASE
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
      case kExprS128LoadMem:
        return ExecuteLoad<Simd128, Simd128>(decoder, code, pc, len,
                                             MachineRepresentation::kSimd128);
      case kExprS128StoreMem:
        return ExecuteStore<Simd128, Simd128>(decoder, code, pc, len,
                                              MachineRepresentation::kSimd128);
#define SHIFT_CASE(op, name, stype, count, expr)                         \
  case kExpr##op: {                                                      \
    SimdShiftImmediate<Decoder::kNoValidate> imm(decoder, code->at(pc)); \
    ++len;                                                               \
    WasmValue v = Pop();                                                 \
    stype s = v.to_s128().to_##name();                                   \
    stype res;                                                           \
    for (size_t i = 0; i < count; ++i) {                                 \
      auto a = s.val[i];                                                 \
      res.val[i] = expr;                                                 \
    }                                                                    \
    Push(WasmValue(Simd128(res)));                                       \
    return true;                                                         \
  }
        SHIFT_CASE(I32x4Shl, i32x4, int4, 4, a << imm.shift)
        SHIFT_CASE(I32x4ShrS, i32x4, int4, 4, a >> imm.shift)
        SHIFT_CASE(I32x4ShrU, i32x4, int4, 4,
                   static_cast<uint32_t>(a) >> imm.shift)
        SHIFT_CASE(I16x8Shl, i16x8, int8, 8, a << imm.shift)
        SHIFT_CASE(I16x8ShrS, i16x8, int8, 8, a >> imm.shift)
        SHIFT_CASE(I16x8ShrU, i16x8, int8, 8,
                   static_cast<uint16_t>(a) >> imm.shift)
        SHIFT_CASE(I8x16Shl, i8x16, int16, 16, a << imm.shift)
        SHIFT_CASE(I8x16ShrS, i8x16, int16, 16, a >> imm.shift)
        SHIFT_CASE(I8x16ShrU, i8x16, int16, 16,
                   static_cast<uint8_t>(a) >> imm.shift)
#undef SHIFT_CASE
1915 1916 1917 1918 1919 1920 1921
#define CONVERT_CASE(op, src_type, name, dst_type, count, start_index, ctype, \
                     expr)                                                    \
  case kExpr##op: {                                                           \
    WasmValue v = Pop();                                                      \
    src_type s = v.to_s128().to_##name();                                     \
    dst_type res;                                                             \
    for (size_t i = 0; i < count; ++i) {                                      \
1922 1923
      ctype a = s.val[LANE(start_index + i, s)];                              \
      res.val[LANE(i, res)] = expr;                                           \
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    }                                                                         \
    Push(WasmValue(Simd128(res)));                                            \
    return true;                                                              \
  }
        CONVERT_CASE(F32x4SConvertI32x4, int4, i32x4, float4, 4, 0, int32_t,
                     static_cast<float>(a))
        CONVERT_CASE(F32x4UConvertI32x4, int4, i32x4, float4, 4, 0, uint32_t,
                     static_cast<float>(a))
        CONVERT_CASE(I32x4SConvertF32x4, float4, f32x4, int4, 4, 0, double,
                     std::isnan(a) ? 0
                                   : a<kMinInt ? kMinInt : a> kMaxInt
                                         ? kMaxInt
                                         : static_cast<int32_t>(a))
        CONVERT_CASE(I32x4UConvertF32x4, float4, f32x4, int4, 4, 0, double,
                     std::isnan(a)
                         ? 0
                         : a<0 ? 0 : a> kMaxUInt32 ? kMaxUInt32
                                                   : static_cast<uint32_t>(a))
        CONVERT_CASE(I32x4SConvertI16x8High, int8, i16x8, int4, 4, 4, int16_t,
                     a)
        CONVERT_CASE(I32x4UConvertI16x8High, int8, i16x8, int4, 4, 4, uint16_t,
                     a)
        CONVERT_CASE(I32x4SConvertI16x8Low, int8, i16x8, int4, 4, 0, int16_t, a)
        CONVERT_CASE(I32x4UConvertI16x8Low, int8, i16x8, int4, 4, 0, uint16_t,
                     a)
        CONVERT_CASE(I16x8SConvertI8x16High, int16, i8x16, int8, 8, 8, int8_t,
                     a)
        CONVERT_CASE(I16x8UConvertI8x16High, int16, i8x16, int8, 8, 8, uint8_t,
                     a)
        CONVERT_CASE(I16x8SConvertI8x16Low, int16, i8x16, int8, 8, 0, int8_t, a)
        CONVERT_CASE(I16x8UConvertI8x16Low, int16, i8x16, int8, 8, 0, uint8_t,
                     a)
#undef CONVERT_CASE
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
#define PACK_CASE(op, src_type, name, dst_type, count, ctype, dst_ctype,   \
                  is_unsigned)                                             \
  case kExpr##op: {                                                        \
    WasmValue v2 = Pop();                                                  \
    WasmValue v1 = Pop();                                                  \
    src_type s1 = v1.to_s128().to_##name();                                \
    src_type s2 = v2.to_s128().to_##name();                                \
    dst_type res;                                                          \
    int64_t min = std::numeric_limits<ctype>::min();                       \
    int64_t max = std::numeric_limits<ctype>::max();                       \
    for (size_t i = 0; i < count; ++i) {                                   \
      int32_t v = i < count / 2 ? s1.val[LANE(i, s1)]                      \
                                : s2.val[LANE(i - count / 2, s2)];         \
      int64_t a = is_unsigned ? static_cast<int64_t>(v & 0xFFFFFFFFu) : v; \
      res.val[LANE(i, res)] =                                              \
          static_cast<dst_ctype>(std::max(min, std::min(max, a)));         \
    }                                                                      \
    Push(WasmValue(Simd128(res)));                                         \
    return true;                                                           \
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
  }
        PACK_CASE(I16x8SConvertI32x4, int4, i32x4, int8, 8, int16_t, int16_t,
                  false)
        PACK_CASE(I16x8UConvertI32x4, int4, i32x4, int8, 8, uint16_t, int16_t,
                  true)
        PACK_CASE(I8x16SConvertI16x8, int8, i16x8, int16, 16, int8_t, int8_t,
                  false)
        PACK_CASE(I8x16UConvertI16x8, int8, i16x8, int16, 16, uint8_t, int8_t,
                  true)
#undef PACK_CASE
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
      case kExprS128Select: {
        int4 v2 = Pop().to_s128().to_i32x4();
        int4 v1 = Pop().to_s128().to_i32x4();
        int4 bool_val = Pop().to_s128().to_i32x4();
        int4 res;
        for (size_t i = 0; i < 4; ++i) {
          res.val[i] = v2.val[i] ^ ((v1.val[i] ^ v2.val[i]) & bool_val.val[i]);
        }
        Push(WasmValue(Simd128(res)));
        return true;
      }
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
#define ADD_HORIZ_CASE(op, name, stype, count)                   \
  case kExpr##op: {                                              \
    WasmValue v2 = Pop();                                        \
    WasmValue v1 = Pop();                                        \
    stype s1 = v1.to_s128().to_##name();                         \
    stype s2 = v2.to_s128().to_##name();                         \
    stype res;                                                   \
    for (size_t i = 0; i < count / 2; ++i) {                     \
      res.val[LANE(i, s1)] =                                     \
          s1.val[LANE(i * 2, s1)] + s1.val[LANE(i * 2 + 1, s1)]; \
      res.val[LANE(i + count / 2, s1)] =                         \
          s2.val[LANE(i * 2, s1)] + s2.val[LANE(i * 2 + 1, s1)]; \
    }                                                            \
    Push(WasmValue(Simd128(res)));                               \
    return true;                                                 \
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
  }
        ADD_HORIZ_CASE(I32x4AddHoriz, i32x4, int4, 4)
        ADD_HORIZ_CASE(F32x4AddHoriz, f32x4, float4, 4)
        ADD_HORIZ_CASE(I16x8AddHoriz, i16x8, int8, 8)
#undef ADD_HORIZ_CASE
      case kExprS8x16Shuffle: {
        Simd8x16ShuffleImmediate<Decoder::kNoValidate> imm(decoder,
                                                           code->at(pc));
        len += 16;
        int16 v2 = Pop().to_s128().to_i8x16();
        int16 v1 = Pop().to_s128().to_i8x16();
        int16 res;
        for (size_t i = 0; i < kSimd128Size; ++i) {
          int lane = imm.shuffle[i];
2026 2027 2028
          res.val[LANE(i, v1)] = lane < kSimd128Size
                                     ? v1.val[LANE(lane, v1)]
                                     : v2.val[LANE(lane - kSimd128Size, v1)];
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
        }
        Push(WasmValue(Simd128(res)));
        return true;
      }
#define REDUCTION_CASE(op, name, stype, count, operation) \
  case kExpr##op: {                                       \
    stype s = Pop().to_s128().to_##name();                \
    int32_t res = s.val[0];                               \
    for (size_t i = 1; i < count; ++i) {                  \
      res = res operation static_cast<int32_t>(s.val[i]); \
    }                                                     \
    Push(WasmValue(res));                                 \
    return true;                                          \
  }
        REDUCTION_CASE(S1x4AnyTrue, i32x4, int4, 4, |)
        REDUCTION_CASE(S1x4AllTrue, i32x4, int4, 4, &)
        REDUCTION_CASE(S1x8AnyTrue, i16x8, int8, 8, |)
        REDUCTION_CASE(S1x8AllTrue, i16x8, int8, 8, &)
        REDUCTION_CASE(S1x16AnyTrue, i8x16, int16, 16, |)
        REDUCTION_CASE(S1x16AllTrue, i8x16, int16, 16, &)
#undef REDUCTION_CASE
2050 2051 2052 2053 2054
      default:
        return false;
    }
  }

2055 2056 2057 2058 2059 2060
  // Check if our control stack (frames_) exceeds the limit. Trigger stack
  // overflow if it does, and unwinding the current frame.
  // Returns true if execution can continue, false if the current activation was
  // fully unwound.
  // Do call this function immediately *after* pushing a new frame. The pc of
  // the top frame will be reset to 0 if the stack check fails.
2061
  bool DoStackCheck() V8_WARN_UNUSED_RESULT {
2062 2063 2064 2065 2066 2067 2068
    // The goal of this stack check is not to prevent actual stack overflows,
    // but to simulate stack overflows during the execution of compiled code.
    // That is why this function uses FLAG_stack_size, even though the value
    // stack actually lies in zone memory.
    const size_t stack_size_limit = FLAG_stack_size * KB;
    // Sum up the value stack size and the control stack size.
    const size_t current_stack_size =
2069
        (sp_ - stack_.get()) + frames_.size() * sizeof(Frame);
2070
    if (V8_LIKELY(current_stack_size <= stack_size_limit)) {
2071 2072 2073 2074 2075
      return true;
    }
    // The pc of the top frame is initialized to the first instruction. We reset
    // it to 0 here such that we report the same position as in compiled code.
    frames_.back().pc = 0;
2076
    Isolate* isolate = instance_object_->GetIsolate();
2077 2078 2079 2080 2081
    HandleScope handle_scope(isolate);
    isolate->StackOverflow();
    return HandleException(isolate) == WasmInterpreter::Thread::HANDLED;
  }

2082
  void Execute(InterpreterCode* code, pc_t pc, int max) {
2083 2084 2085 2086 2087 2088 2089
    DCHECK_NOT_NULL(code->side_table);
    DCHECK(!frames_.empty());
    // There must be enough space on the stack to hold the arguments, locals,
    // and the value stack.
    DCHECK_LE(code->function->sig->parameter_count() +
                  code->locals.type_list.size() +
                  code->side_table->max_stack_height_,
2090
              stack_limit_ - stack_.get() - frames_.back().sp);
2091

2092 2093
    Decoder decoder(code->start, code->end);
    pc_t limit = code->end - code->start;
2094 2095 2096 2097 2098 2099 2100 2101
    bool hit_break = false;

    while (true) {
#define PAUSE_IF_BREAK_FLAG(flag)                                     \
  if (V8_UNLIKELY(break_flags_ & WasmInterpreter::BreakFlag::flag)) { \
    hit_break = true;                                                 \
    max = 0;                                                          \
  }
2102

2103
      DCHECK_GT(limit, pc);
2104
      DCHECK_NOT_NULL(code->start);
2105

2106
      // Do first check for a breakpoint, in order to set hit_break correctly.
2107
      const char* skip = "        ";
2108
      int len = 1;
2109 2110 2111 2112 2113 2114
      byte orig = code->start[pc];
      WasmOpcode opcode = static_cast<WasmOpcode>(orig);
      if (WasmOpcodes::IsPrefixOpcode(opcode)) {
        opcode = static_cast<WasmOpcode>(opcode << 8 | code->start[pc + 1]);
      }
      if (V8_UNLIKELY(orig == kInternalBreakpoint)) {
2115
        orig = code->orig_start[pc];
2116 2117 2118 2119
        if (WasmOpcodes::IsPrefixOpcode(static_cast<WasmOpcode>(orig))) {
          opcode =
              static_cast<WasmOpcode>(orig << 8 | code->orig_start[pc + 1]);
        }
2120 2121
        if (SkipBreakpoint(code, pc)) {
          // skip breakpoint by switching on original code.
2122
          skip = "[skip]  ";
2123
        } else {
2124
          TRACE("@%-3zu: [break] %-24s:", pc, WasmOpcodes::OpcodeName(opcode));
2125 2126
          TraceValueStack();
          TRACE("\n");
2127
          hit_break = true;
2128
          break;
2129 2130 2131
        }
      }

2132 2133 2134
      // If max is 0, break. If max is positive (a limit is set), decrement it.
      if (max == 0) break;
      if (max > 0) --max;
2135

2136
      USE(skip);
2137
      TRACE("@%-3zu: %s%-24s:", pc, skip, WasmOpcodes::OpcodeName(opcode));
2138 2139 2140
      TraceValueStack();
      TRACE("\n");

2141 2142 2143
#ifdef DEBUG
      // Compute the stack effect of this opcode, and verify later that the
      // stack was modified accordingly.
2144 2145 2146
      std::pair<uint32_t, uint32_t> stack_effect =
          StackEffect(codemap_->module(), frames_.back().code->function->sig,
                      code->orig_start + pc, code->orig_end);
2147 2148
      sp_t expected_new_stack_height =
          StackHeight() - stack_effect.first + stack_effect.second;
2149 2150
#endif

2151 2152 2153
      switch (orig) {
        case kExprNop:
          break;
2154
        case kExprBlock: {
2155 2156
          BlockTypeImmediate<Decoder::kNoValidate> imm(kAllWasmFeatures,
                                                       &decoder, code->at(pc));
2157
          len = 1 + imm.length;
2158 2159
          break;
        }
2160
        case kExprLoop: {
2161 2162
          BlockTypeImmediate<Decoder::kNoValidate> imm(kAllWasmFeatures,
                                                       &decoder, code->at(pc));
2163
          len = 1 + imm.length;
2164 2165 2166
          break;
        }
        case kExprIf: {
2167 2168
          BlockTypeImmediate<Decoder::kNoValidate> imm(kAllWasmFeatures,
                                                       &decoder, code->at(pc));
2169
          WasmValue cond = Pop();
2170 2171 2172
          bool is_true = cond.to<uint32_t>() != 0;
          if (is_true) {
            // fall through to the true block.
2173
            len = 1 + imm.length;
2174 2175
            TRACE("  true => fallthrough\n");
          } else {
2176
            len = LookupTargetDelta(code, pc);
2177 2178 2179 2180 2181
            TRACE("  false => @%zu\n", pc + len);
          }
          break;
        }
        case kExprElse: {
2182
          len = LookupTargetDelta(code, pc);
2183 2184 2185 2186
          TRACE("  end => @%zu\n", pc + len);
          break;
        }
        case kExprSelect: {
2187 2188 2189
          WasmValue cond = Pop();
          WasmValue fval = Pop();
          WasmValue tval = Pop();
2190
          Push(cond.to<int32_t>() != 0 ? tval : fval);
2191 2192 2193
          break;
        }
        case kExprBr: {
2194 2195
          BreakDepthImmediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          len = DoBreak(code, pc, imm.depth);
2196 2197 2198 2199
          TRACE("  br => @%zu\n", pc + len);
          break;
        }
        case kExprBrIf: {
2200
          BreakDepthImmediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
2201
          WasmValue cond = Pop();
2202 2203
          bool is_true = cond.to<uint32_t>() != 0;
          if (is_true) {
2204
            len = DoBreak(code, pc, imm.depth);
2205 2206 2207
            TRACE("  br_if => @%zu\n", pc + len);
          } else {
            TRACE("  false => fallthrough\n");
2208
            len = 1 + imm.length;
2209 2210 2211 2212
          }
          break;
        }
        case kExprBrTable: {
2213 2214 2215
          BranchTableImmediate<Decoder::kNoValidate> imm(&decoder,
                                                         code->at(pc));
          BranchTableIterator<Decoder::kNoValidate> iterator(&decoder, imm);
2216
          uint32_t key = Pop().to<uint32_t>();
2217
          uint32_t depth = 0;
2218
          if (key >= imm.table_count) key = imm.table_count;
2219 2220 2221 2222 2223
          for (uint32_t i = 0; i <= key; i++) {
            DCHECK(iterator.has_next());
            depth = iterator.next();
          }
          len = key + DoBreak(code, pc + key, static_cast<size_t>(depth));
2224
          TRACE("  br[%u] => @%zu\n", key, pc + key + len);
2225 2226 2227
          break;
        }
        case kExprReturn: {
2228
          size_t arity = code->function->sig->return_count();
2229
          if (!DoReturn(&decoder, &code, &pc, &limit, arity)) return;
2230
          PAUSE_IF_BREAK_FLAG(AfterReturn);
2231 2232 2233
          continue;
        }
        case kExprUnreachable: {
2234
          return DoTrap(kTrapUnreachable, pc);
2235 2236 2237 2238 2239
        }
        case kExprEnd: {
          break;
        }
        case kExprI32Const: {
2240 2241 2242
          ImmI32Immediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          Push(WasmValue(imm.value));
          len = 1 + imm.length;
2243 2244 2245
          break;
        }
        case kExprI64Const: {
2246 2247 2248
          ImmI64Immediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          Push(WasmValue(imm.value));
          len = 1 + imm.length;
2249 2250 2251
          break;
        }
        case kExprF32Const: {
2252 2253 2254
          ImmF32Immediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          Push(WasmValue(imm.value));
          len = 1 + imm.length;
2255 2256 2257
          break;
        }
        case kExprF64Const: {
2258 2259 2260
          ImmF64Immediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          Push(WasmValue(imm.value));
          len = 1 + imm.length;
2261 2262 2263
          break;
        }
        case kExprGetLocal: {
2264 2265 2266
          LocalIndexImmediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
          Push(GetStackValue(frames_.back().sp + imm.index));
          len = 1 + imm.length;
2267 2268 2269
          break;
        }
        case kExprSetLocal: {
2270
          LocalIndexImmediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
2271
          WasmValue val = Pop();
2272 2273
          SetStackValue(frames_.back().sp + imm.index, val);
          len = 1 + imm.length;
2274 2275 2276
          break;
        }
        case kExprTeeLocal: {
2277
          LocalIndexImmediate<Decoder::kNoValidate> imm(&decoder, code->at(pc));
2278
          WasmValue val = Pop();
2279
          SetStackValue(frames_.back().sp + imm.index, val);
2280
          Push(val);
2281
          len = 1 + imm.length;
2282 2283
          break;
        }
2284 2285 2286 2287
        case kExprDrop: {
          Pop();
          break;
        }
2288
        case kExprCallFunction: {
2289 2290 2291
          CallFunctionImmediate<Decoder::kNoValidate> imm(&decoder,
                                                          code->at(pc));
          InterpreterCode* target = codemap()->GetCode(imm.index);
2292 2293
          if (target->function->imported) {
            CommitPc(pc);
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
            ExternalCallResult result =
                CallImportedFunction(target->function->func_index);
            switch (result.type) {
              case ExternalCallResult::INTERNAL:
                // The import is a function of this instance. Call it directly.
                target = result.interpreter_code;
                DCHECK(!target->function->imported);
                break;
              case ExternalCallResult::INVALID_FUNC:
              case ExternalCallResult::SIGNATURE_MISMATCH:
                // Direct calls are checked statically.
                UNREACHABLE();
              case ExternalCallResult::EXTERNAL_RETURNED:
                PAUSE_IF_BREAK_FLAG(AfterCall);
2308
                len = 1 + imm.length;
2309 2310 2311 2312 2313
                break;
              case ExternalCallResult::EXTERNAL_UNWOUND:
                return;
            }
            if (result.type != ExternalCallResult::INTERNAL) break;
2314
          }
2315
          // Execute an internal call.
2316
          if (!DoCall(&decoder, target, &pc, &limit)) return;
2317
          code = target;
2318
          PAUSE_IF_BREAK_FLAG(AfterCall);
2319
          continue;  // don't bump pc
2320
        } break;
2321
        case kExprCallIndirect: {
2322 2323
          CallIndirectImmediate<Decoder::kNoValidate> imm(&decoder,
                                                          code->at(pc));
2324
          uint32_t entry_index = Pop().to<uint32_t>();
2325
          // Assume only one table for now.
2326
          DCHECK_LE(module()->tables.size(), 1u);
2327
          CommitPc(pc);  // TODO(wasm): Be more disciplined about committing PC.
2328
          ExternalCallResult result =
2329
              CallIndirectFunction(0, entry_index, imm.sig_index);
2330 2331 2332
          switch (result.type) {
            case ExternalCallResult::INTERNAL:
              // The import is a function of this instance. Call it directly.
2333 2334
              if (!DoCall(&decoder, result.interpreter_code, &pc, &limit))
                return;
2335 2336 2337 2338 2339 2340
              code = result.interpreter_code;
              PAUSE_IF_BREAK_FLAG(AfterCall);
              continue;  // don't bump pc
            case ExternalCallResult::INVALID_FUNC:
              return DoTrap(kTrapFuncInvalid, pc);
            case ExternalCallResult::SIGNATURE_MISMATCH:
2341
              return DoTrap(kTrapFuncSigMismatch, pc);
2342 2343
            case ExternalCallResult::EXTERNAL_RETURNED:
              PAUSE_IF_BREAK_FLAG(AfterCall);
2344
              len = 1 + imm.length;
2345 2346 2347
              break;
            case ExternalCallResult::EXTERNAL_UNWOUND:
              return;
2348
          }
2349
        } break;
2350
        case kExprGetGlobal: {
2351 2352 2353
          GlobalIndexImmediate<Decoder::kNoValidate> imm(&decoder,
                                                         code->at(pc));
          const WasmGlobal* global = &module()->globals[imm.index];
2354
          byte* ptr = GetGlobalPtr(global);
2355
          WasmValue val;
2356
          switch (global->type) {
2357 2358 2359 2360
#define CASE_TYPE(wasm, ctype)                                         \
  case kWasm##wasm:                                                    \
    val = WasmValue(                                                   \
        ReadLittleEndianValue<ctype>(reinterpret_cast<Address>(ptr))); \
2361 2362 2363 2364 2365
    break;
            WASM_CTYPES(CASE_TYPE)
#undef CASE_TYPE
            default:
              UNREACHABLE();
2366
          }
2367
          Push(val);
2368
          len = 1 + imm.length;
2369 2370
          break;
        }
2371
        case kExprSetGlobal: {
2372 2373 2374
          GlobalIndexImmediate<Decoder::kNoValidate> imm(&decoder,
                                                         code->at(pc));
          const WasmGlobal* global = &module()->globals[imm.index];
2375
          byte* ptr = GetGlobalPtr(global);
2376
          WasmValue val = Pop();
2377
          switch (global->type) {
2378 2379 2380 2381
#define CASE_TYPE(wasm, ctype)                                    \
  case kWasm##wasm:                                               \
    WriteLittleEndianValue<ctype>(reinterpret_cast<Address>(ptr), \
                                  val.to<ctype>());               \
2382 2383 2384 2385 2386
    break;
            WASM_CTYPES(CASE_TYPE)
#undef CASE_TYPE
            default:
              UNREACHABLE();
2387
          }
2388
          len = 1 + imm.length;
2389 2390 2391
          break;
        }

2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
#define LOAD_CASE(name, ctype, mtype, rep)                      \
  case kExpr##name: {                                           \
    if (!ExecuteLoad<ctype, mtype>(&decoder, code, pc, len,     \
                                   MachineRepresentation::rep)) \
      return;                                                   \
    break;                                                      \
  }

          LOAD_CASE(I32LoadMem8S, int32_t, int8_t, kWord8);
          LOAD_CASE(I32LoadMem8U, int32_t, uint8_t, kWord8);
          LOAD_CASE(I32LoadMem16S, int32_t, int16_t, kWord16);
          LOAD_CASE(I32LoadMem16U, int32_t, uint16_t, kWord16);
          LOAD_CASE(I64LoadMem8S, int64_t, int8_t, kWord8);
          LOAD_CASE(I64LoadMem8U, int64_t, uint8_t, kWord16);
          LOAD_CASE(I64LoadMem16S, int64_t, int16_t, kWord16);
          LOAD_CASE(I64LoadMem16U, int64_t, uint16_t, kWord16);
          LOAD_CASE(I64LoadMem32S, int64_t, int32_t, kWord32);
          LOAD_CASE(I64LoadMem32U, int64_t, uint32_t, kWord32);
          LOAD_CASE(I32LoadMem, int32_t, int32_t, kWord32);
          LOAD_CASE(I64LoadMem, int64_t, int64_t, kWord64);
2412 2413
          LOAD_CASE(F32LoadMem, Float32, uint32_t, kFloat32);
          LOAD_CASE(F64LoadMem, Float64, uint64_t, kFloat64);
2414 2415
#undef LOAD_CASE

2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
#define STORE_CASE(name, ctype, mtype, rep)                      \
  case kExpr##name: {                                            \
    if (!ExecuteStore<ctype, mtype>(&decoder, code, pc, len,     \
                                    MachineRepresentation::rep)) \
      return;                                                    \
    break;                                                       \
  }

          STORE_CASE(I32StoreMem8, int32_t, int8_t, kWord8);
          STORE_CASE(I32StoreMem16, int32_t, int16_t, kWord16);
          STORE_CASE(I64StoreMem8, int64_t, int8_t, kWord8);
          STORE_CASE(I64StoreMem16, int64_t, int16_t, kWord16);
          STORE_CASE(I64StoreMem32, int64_t, int32_t, kWord32);
          STORE_CASE(I32StoreMem, int32_t, int32_t, kWord32);
          STORE_CASE(I64StoreMem, int64_t, int64_t, kWord64);
2431 2432
          STORE_CASE(F32StoreMem, Float32, uint32_t, kFloat32);
          STORE_CASE(F64StoreMem, Float64, uint64_t, kFloat64);
2433 2434
#undef STORE_CASE

2435 2436 2437 2438
#define ASMJS_LOAD_CASE(name, ctype, mtype, defval)                 \
  case kExpr##name: {                                               \
    uint32_t index = Pop().to<uint32_t>();                          \
    ctype result;                                                   \
2439
    Address addr = BoundsCheckMem<mtype>(0, index);                 \
2440
    if (!addr) {                                                    \
2441 2442 2443 2444 2445 2446 2447
      result = defval;                                              \
    } else {                                                        \
      /* TODO(titzer): alignment for asmjs load mem? */             \
      result = static_cast<ctype>(*reinterpret_cast<mtype*>(addr)); \
    }                                                               \
    Push(WasmValue(result));                                        \
    break;                                                          \
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
  }
          ASMJS_LOAD_CASE(I32AsmjsLoadMem8S, int32_t, int8_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem8U, int32_t, uint8_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem16S, int32_t, int16_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem16U, int32_t, uint16_t, 0);
          ASMJS_LOAD_CASE(I32AsmjsLoadMem, int32_t, int32_t, 0);
          ASMJS_LOAD_CASE(F32AsmjsLoadMem, float, float,
                          std::numeric_limits<float>::quiet_NaN());
          ASMJS_LOAD_CASE(F64AsmjsLoadMem, double, double,
                          std::numeric_limits<double>::quiet_NaN());
#undef ASMJS_LOAD_CASE

#define ASMJS_STORE_CASE(name, ctype, mtype)                                   \
  case kExpr##name: {                                                          \
2462
    WasmValue val = Pop();                                                     \
2463
    uint32_t index = Pop().to<uint32_t>();                                     \
2464
    Address addr = BoundsCheckMem<mtype>(0, index);                            \
2465
    if (addr) {                                                                \
2466 2467
      *(reinterpret_cast<mtype*>(addr)) = static_cast<mtype>(val.to<ctype>()); \
    }                                                                          \
2468
    Push(val);                                                                 \
2469 2470 2471 2472 2473 2474 2475 2476 2477
    break;                                                                     \
  }

          ASMJS_STORE_CASE(I32AsmjsStoreMem8, int32_t, int8_t);
          ASMJS_STORE_CASE(I32AsmjsStoreMem16, int32_t, int16_t);
          ASMJS_STORE_CASE(I32AsmjsStoreMem, int32_t, int32_t);
          ASMJS_STORE_CASE(F32AsmjsStoreMem, float, float);
          ASMJS_STORE_CASE(F64AsmjsStoreMem, double, double);
#undef ASMJS_STORE_CASE
2478
        case kExprGrowMemory: {
2479 2480
          MemoryIndexImmediate<Decoder::kNoValidate> imm(&decoder,
                                                         code->at(pc));
2481
          uint32_t delta_pages = Pop().to<uint32_t>();
2482 2483
          Handle<WasmMemoryObject> memory(instance_object_->memory_object(),
                                          instance_object_->GetIsolate());
2484 2485
          Isolate* isolate = memory->GetIsolate();
          int32_t result = WasmMemoryObject::Grow(isolate, memory, delta_pages);
2486
          Push(WasmValue(result));
2487
          len = 1 + imm.length;
2488 2489 2490
          // Treat one grow_memory instruction like 1000 other instructions,
          // because it is a really expensive operation.
          if (max > 0) max = std::max(0, max - 1000);
2491 2492
          break;
        }
2493
        case kExprMemorySize: {
2494 2495
          MemoryIndexImmediate<Decoder::kNoValidate> imm(&decoder,
                                                         code->at(pc));
2496 2497
          Push(WasmValue(static_cast<uint32_t>(instance_object_->memory_size() /
                                               kWasmPageSize)));
2498
          len = 1 + imm.length;
2499 2500
          break;
        }
2501 2502 2503 2504
        // We need to treat kExprI32ReinterpretF32 and kExprI64ReinterpretF64
        // specially to guarantee that the quiet bit of a NaN is preserved on
        // ia32 by the reinterpret casts.
        case kExprI32ReinterpretF32: {
2505 2506
          WasmValue val = Pop();
          Push(WasmValue(ExecuteI32ReinterpretF32(val)));
2507 2508 2509
          break;
        }
        case kExprI64ReinterpretF64: {
2510 2511
          WasmValue val = Pop();
          Push(WasmValue(ExecuteI64ReinterpretF64(val)));
2512
          break;
2513
        }
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
#define SIGN_EXTENSION_CASE(name, wtype, ntype)        \
  case kExpr##name: {                                  \
    ntype val = static_cast<ntype>(Pop().to<wtype>()); \
    Push(WasmValue(static_cast<wtype>(val)));          \
    break;                                             \
  }
          SIGN_EXTENSION_CASE(I32SExtendI8, int32_t, int8_t);
          SIGN_EXTENSION_CASE(I32SExtendI16, int32_t, int16_t);
          SIGN_EXTENSION_CASE(I64SExtendI8, int64_t, int8_t);
          SIGN_EXTENSION_CASE(I64SExtendI16, int64_t, int16_t);
          SIGN_EXTENSION_CASE(I64SExtendI32, int64_t, int32_t);
#undef SIGN_EXTENSION_CASE
2526 2527 2528 2529
        case kNumericPrefix: {
          ++len;
          if (!ExecuteNumericOp(opcode, &decoder, code, pc, len)) return;
          break;
2530
        }
2531 2532 2533 2534
        case kAtomicPrefix: {
          if (!ExecuteAtomicOp(opcode, &decoder, code, pc, len)) return;
          break;
        }
2535 2536 2537 2538 2539
        case kSimdPrefix: {
          ++len;
          if (!ExecuteSimdOp(opcode, &decoder, code, pc, len)) return;
          break;
        }
2540

2541 2542 2543 2544
#define EXECUTE_SIMPLE_BINOP(name, ctype, op)               \
  case kExpr##name: {                                       \
    WasmValue rval = Pop();                                 \
    WasmValue lval = Pop();                                 \
2545 2546 2547
    auto result = lval.to<ctype>() op rval.to<ctype>();     \
    possible_nondeterminism_ |= has_nondeterminism(result); \
    Push(WasmValue(result));                                \
2548
    break;                                                  \
2549 2550 2551 2552
  }
          FOREACH_SIMPLE_BINOP(EXECUTE_SIMPLE_BINOP)
#undef EXECUTE_SIMPLE_BINOP

2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
#define EXECUTE_OTHER_BINOP(name, ctype)                    \
  case kExpr##name: {                                       \
    TrapReason trap = kTrapCount;                           \
    ctype rval = Pop().to<ctype>();                         \
    ctype lval = Pop().to<ctype>();                         \
    auto result = Execute##name(lval, rval, &trap);         \
    possible_nondeterminism_ |= has_nondeterminism(result); \
    if (trap != kTrapCount) return DoTrap(trap, pc);        \
    Push(WasmValue(result));                                \
    break;                                                  \
2563 2564 2565 2566
  }
          FOREACH_OTHER_BINOP(EXECUTE_OTHER_BINOP)
#undef EXECUTE_OTHER_BINOP

2567
#define EXECUTE_UNOP(name, ctype, exec_fn)                  \
2568 2569 2570
  case kExpr##name: {                                       \
    TrapReason trap = kTrapCount;                           \
    ctype val = Pop().to<ctype>();                          \
2571
    auto result = exec_fn(val, &trap);                      \
2572 2573 2574 2575
    possible_nondeterminism_ |= has_nondeterminism(result); \
    if (trap != kTrapCount) return DoTrap(trap, pc);        \
    Push(WasmValue(result));                                \
    break;                                                  \
2576
  }
2577 2578

#define EXECUTE_OTHER_UNOP(name, ctype) EXECUTE_UNOP(name, ctype, Execute##name)
2579 2580 2581
          FOREACH_OTHER_UNOP(EXECUTE_OTHER_UNOP)
#undef EXECUTE_OTHER_UNOP

2582 2583 2584 2585 2586 2587
#define EXECUTE_I32CONV_FLOATOP(name, out_type, in_type) \
  EXECUTE_UNOP(name, in_type, ExecuteConvert<out_type>)
          FOREACH_I32CONV_FLOATOP(EXECUTE_I32CONV_FLOATOP)
#undef EXECUTE_I32CONV_FLOATOP
#undef EXECUTE_UNOP

2588
        default:
2589 2590
          FATAL("Unknown or unimplemented opcode #%d:%s", code->start[pc],
                OpcodeName(code->start[pc]));
2591 2592 2593
          UNREACHABLE();
      }

2594
#ifdef DEBUG
2595
      if (!WasmOpcodes::IsControlOpcode(opcode)) {
2596
        DCHECK_EQ(expected_new_stack_height, StackHeight());
2597 2598 2599
      }
#endif

2600
      pc += len;
2601 2602 2603
      if (pc == limit) {
        // Fell off end of code; do an implicit return.
        TRACE("@%-3zu: ImplicitReturn\n", pc);
2604 2605
        if (!DoReturn(&decoder, &code, &pc, &limit,
                      code->function->sig->return_count()))
2606 2607 2608
          return;
        PAUSE_IF_BREAK_FLAG(AfterReturn);
      }
2609
#undef PAUSE_IF_BREAK_FLAG
2610
    }
2611

2612
    state_ = WasmInterpreter::PAUSED;
2613
    break_pc_ = hit_break ? pc : kInvalidPc;
2614
    CommitPc(pc);
2615 2616
  }

2617
  WasmValue Pop() {
2618
    DCHECK_GT(frames_.size(), 0);
2619 2620
    DCHECK_GT(StackHeight(), frames_.back().llimit());  // can't pop into locals
    return *--sp_;
2621 2622 2623
  }

  void PopN(int n) {
2624
    DCHECK_GE(StackHeight(), n);
2625
    DCHECK_GT(frames_.size(), 0);
2626 2627 2628
    // Check that we don't pop into locals.
    DCHECK_GE(StackHeight() - n, frames_.back().llimit());
    sp_ -= n;
2629 2630
  }

2631 2632
  WasmValue PopArity(size_t arity) {
    if (arity == 0) return WasmValue();
2633
    CHECK_EQ(1, arity);
2634 2635 2636
    return Pop();
  }

2637 2638
  void Push(WasmValue val) {
    DCHECK_NE(kWasmStmt, val.type());
2639 2640 2641 2642
    DCHECK_LE(1, stack_limit_ - sp_);
    *sp_++ = val;
  }

2643
  void Push(WasmValue* vals, size_t arity) {
2644
    DCHECK_LE(arity, stack_limit_ - sp_);
2645 2646
    for (WasmValue *val = vals, *end = vals + arity; val != end; ++val) {
      DCHECK_NE(kWasmStmt, val->type());
2647 2648 2649 2650 2651 2652 2653
    }
    memcpy(sp_, vals, arity * sizeof(*sp_));
    sp_ += arity;
  }

  void EnsureStackSpace(size_t size) {
    if (V8_LIKELY(static_cast<size_t>(stack_limit_ - sp_) >= size)) return;
2654
    size_t old_size = stack_limit_ - stack_.get();
2655
    size_t requested_size =
2656
        base::bits::RoundUpToPowerOfTwo64((sp_ - stack_.get()) + size);
2657
    size_t new_size = Max(size_t{8}, Max(2 * old_size, requested_size));
2658 2659 2660 2661 2662
    std::unique_ptr<WasmValue[]> new_stack(new WasmValue[new_size]);
    memcpy(new_stack.get(), stack_.get(), old_size * sizeof(*sp_));
    sp_ = new_stack.get() + (sp_ - stack_.get());
    stack_ = std::move(new_stack);
    stack_limit_ = stack_.get() + new_size;
2663 2664
  }

2665
  sp_t StackHeight() { return sp_ - stack_.get(); }
2666

2667
  void TraceValueStack() {
2668
#ifdef DEBUG
2669
    if (!FLAG_trace_wasm_interpreter) return;
2670 2671 2672 2673
    Frame* top = frames_.size() > 0 ? &frames_.back() : nullptr;
    sp_t sp = top ? top->sp : 0;
    sp_t plimit = top ? top->plimit() : 0;
    sp_t llimit = top ? top->llimit() : 0;
2674 2675 2676 2677 2678 2679 2680
    for (size_t i = sp; i < StackHeight(); ++i) {
      if (i < plimit)
        PrintF(" p%zu:", i);
      else if (i < llimit)
        PrintF(" l%zu:", i);
      else
        PrintF(" s%zu:", i);
2681 2682
      WasmValue val = GetStackValue(i);
      switch (val.type()) {
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
        case kWasmI32:
          PrintF("i32:%d", val.to<int32_t>());
          break;
        case kWasmI64:
          PrintF("i64:%" PRId64 "", val.to<int64_t>());
          break;
        case kWasmF32:
          PrintF("f32:%f", val.to<float>());
          break;
        case kWasmF64:
          PrintF("f64:%lf", val.to<double>());
          break;
        case kWasmStmt:
          PrintF("void");
          break;
        default:
          UNREACHABLE();
          break;
2701 2702
      }
    }
2703
#endif  // DEBUG
2704
  }
2705

2706 2707 2708
  ExternalCallResult TryHandleException(Isolate* isolate) {
    if (HandleException(isolate) == WasmInterpreter::Thread::UNWOUND) {
      return {ExternalCallResult::EXTERNAL_UNWOUND};
2709
    }
2710 2711 2712
    return {ExternalCallResult::EXTERNAL_RETURNED};
  }

2713 2714 2715 2716
  ExternalCallResult CallExternalWasmFunction(Isolate* isolate,
                                              Handle<Object> object_ref,
                                              const WasmCode* code,
                                              FunctionSig* sig) {
2717
    if (code->kind() == WasmCode::kWasmToJsWrapper &&
2718
        !IsJSCompatibleSignature(sig)) {
2719 2720 2721
      isolate->Throw(*isolate->factory()->NewTypeError(
          MessageTemplate::kWasmTrapTypeError));
      return TryHandleException(isolate);
2722
    }
2723

2724
    Handle<WasmDebugInfo> debug_info(instance_object_->debug_info(), isolate);
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
    Handle<JSFunction> wasm_entry =
        WasmDebugInfo::GetCWasmEntry(debug_info, sig);

    TRACE("  => Calling external wasm function\n");

    // Copy the arguments to one buffer.
    // TODO(clemensh): Introduce a helper for all argument buffer
    // con-/destruction.
    int num_args = static_cast<int>(sig->parameter_count());
    std::vector<uint8_t> arg_buffer(num_args * 8);
    size_t offset = 0;
    WasmValue* wasm_args = sp_ - num_args;
    for (int i = 0; i < num_args; ++i) {
2738
      int param_size = ValueTypes::ElementSizeInBytes(sig->GetParam(i));
2739 2740 2741
      if (arg_buffer.size() < offset + param_size) {
        arg_buffer.resize(std::max(2 * arg_buffer.size(), offset + param_size));
      }
2742
      Address address = reinterpret_cast<Address>(arg_buffer.data()) + offset;
2743 2744
      switch (sig->GetParam(i)) {
        case kWasmI32:
2745
          WriteUnalignedValue(address, wasm_args[i].to<uint32_t>());
2746 2747
          break;
        case kWasmI64:
2748
          WriteUnalignedValue(address, wasm_args[i].to<uint64_t>());
2749 2750
          break;
        case kWasmF32:
2751
          WriteUnalignedValue(address, wasm_args[i].to<float>());
2752 2753
          break;
        case kWasmF64:
2754
          WriteUnalignedValue(address, wasm_args[i].to<double>());
2755 2756 2757 2758 2759 2760 2761
          break;
        default:
          UNIMPLEMENTED();
      }
      offset += param_size;
    }

2762 2763
    // Ensure that there is enough space in the arg_buffer to hold the return
    // value(s).
2764
    size_t return_size = 0;
2765
    for (ValueType t : sig->returns()) {
2766
      return_size += ValueTypes::ElementSizeInBytes(t);
2767 2768 2769 2770 2771
    }
    if (arg_buffer.size() < return_size) {
      arg_buffer.resize(return_size);
    }

2772 2773
    // Wrap the arg_buffer and the code target data pointers in handles. As
    // these are aligned pointers, to the GC it will look like Smis.
2774 2775 2776
    Handle<Object> arg_buffer_obj(reinterpret_cast<Object*>(arg_buffer.data()),
                                  isolate);
    DCHECK(!arg_buffer_obj->IsHeapObject());
2777 2778 2779
    Handle<Object> code_entry_obj(
        reinterpret_cast<Object*>(code->instruction_start()), isolate);
    DCHECK(!code_entry_obj->IsHeapObject());
2780

2781 2782
    static_assert(compiler::CWasmEntryParameters::kNumParameters == 3,
                  "code below needs adaption");
2783
    Handle<Object> args[compiler::CWasmEntryParameters::kNumParameters];
2784
    args[compiler::CWasmEntryParameters::kCodeEntry] = code_entry_obj;
2785
    args[compiler::CWasmEntryParameters::kObjectRef] = object_ref;
2786 2787 2788
    args[compiler::CWasmEntryParameters::kArgumentsBuffer] = arg_buffer_obj;

    Handle<Object> receiver = isolate->factory()->undefined_value();
2789
    trap_handler::SetThreadInWasm();
2790 2791
    MaybeHandle<Object> maybe_retval =
        Execution::Call(isolate, wasm_entry, receiver, arraysize(args), args);
2792 2793 2794 2795
    TRACE("  => External wasm function returned%s\n",
          maybe_retval.is_null() ? " with exception" : "");

    if (maybe_retval.is_null()) {
2796 2797 2798 2799 2800 2801
      // JSEntryStub may through a stack overflow before we actually get to wasm
      // code or back to the interpreter, meaning the thread-in-wasm flag won't
      // be cleared.
      if (trap_handler::IsThreadInWasm()) {
        trap_handler::ClearThreadInWasm();
      }
2802 2803 2804 2805
      return TryHandleException(isolate);
    }

    trap_handler::ClearThreadInWasm();
2806 2807 2808 2809 2810 2811 2812

    // Pop arguments off the stack.
    sp_ -= num_args;
    // Push return values.
    if (sig->return_count() > 0) {
      // TODO(wasm): Handle multiple returns.
      DCHECK_EQ(1, sig->return_count());
2813
      Address address = reinterpret_cast<Address>(arg_buffer.data());
2814 2815
      switch (sig->GetReturn()) {
        case kWasmI32:
2816
          Push(WasmValue(ReadUnalignedValue<uint32_t>(address)));
2817 2818
          break;
        case kWasmI64:
2819
          Push(WasmValue(ReadUnalignedValue<uint64_t>(address)));
2820 2821
          break;
        case kWasmF32:
2822
          Push(WasmValue(ReadUnalignedValue<float>(address)));
2823 2824
          break;
        case kWasmF64:
2825
          Push(WasmValue(ReadUnalignedValue<double>(address)));
2826 2827 2828 2829 2830 2831 2832 2833
          break;
        default:
          UNIMPLEMENTED();
      }
    }
    return {ExternalCallResult::EXTERNAL_RETURNED};
  }

2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
  static WasmCode* GetTargetCode(WasmCodeManager* code_manager,
                                 Address target) {
    NativeModule* native_module = code_manager->LookupNativeModule(target);
    if (native_module->is_jump_table_slot(target)) {
      uint32_t func_index =
          native_module->GetFunctionIndexFromJumpTableSlot(target);
      return native_module->code(func_index);
    }
    WasmCode* code = native_module->Lookup(target);
    DCHECK_EQ(code->instruction_start(), target);
    return code;
  }

2847
  ExternalCallResult CallImportedFunction(uint32_t function_index) {
2848
    DCHECK_GT(module()->num_imported_functions, function_index);
2849 2850
    // Use a new HandleScope to avoid leaking / accumulating handles in the
    // outer scope.
2851
    Isolate* isolate = instance_object_->GetIsolate();
2852 2853
    HandleScope handle_scope(isolate);

2854
    ImportedFunctionEntry entry(instance_object_, function_index);
2855
    Handle<Object> object_ref(entry.object_ref(), isolate);
2856 2857
    WasmCode* code =
        GetTargetCode(isolate->wasm_engine()->code_manager(), entry.target());
2858 2859
    FunctionSig* sig = module()->functions[function_index].sig;
    return CallExternalWasmFunction(isolate, object_ref, code, sig);
2860 2861 2862 2863 2864
  }

  ExternalCallResult CallIndirectFunction(uint32_t table_index,
                                          uint32_t entry_index,
                                          uint32_t sig_index) {
2865 2866
    if (codemap()->call_indirect_through_module()) {
      // Rely on the information stored in the WasmModule.
2867 2868 2869 2870 2871
      InterpreterCode* code =
          codemap()->GetIndirectCode(table_index, entry_index);
      if (!code) return {ExternalCallResult::INVALID_FUNC};
      if (code->function->sig_index != sig_index) {
        // If not an exact match, we have to do a canonical check.
2872 2873 2874 2875
        int function_canonical_id =
            module()->signature_ids[code->function->sig_index];
        int expected_canonical_id = module()->signature_ids[sig_index];
        DCHECK_EQ(function_canonical_id,
2876
                  module()->signature_map.Find(*code->function->sig));
2877
        if (function_canonical_id != expected_canonical_id) {
2878 2879 2880 2881 2882 2883
          return {ExternalCallResult::SIGNATURE_MISMATCH};
        }
      }
      return {ExternalCallResult::INTERNAL, code};
    }

2884 2885 2886
    Isolate* isolate = instance_object_->GetIsolate();
    uint32_t expected_sig_id = module()->signature_ids[sig_index];
    DCHECK_EQ(expected_sig_id,
2887
              module()->signature_map.Find(*module()->signatures[sig_index]));
2888 2889 2890 2891 2892 2893 2894

    // The function table is stored in the instance.
    // TODO(wasm): the wasm interpreter currently supports only one table.
    CHECK_EQ(0, table_index);
    // Bounds check against table size.
    if (entry_index >= instance_object_->indirect_function_table_size()) {
      return {ExternalCallResult::INVALID_FUNC};
2895 2896
    }

2897 2898 2899 2900 2901
    IndirectFunctionTableEntry entry(instance_object_, entry_index);
    // Signature check.
    if (entry.sig_id() != static_cast<int32_t>(expected_sig_id)) {
      return {ExternalCallResult::SIGNATURE_MISMATCH};
    }
2902

2903
    HandleScope scope(isolate);
2904
    FunctionSig* signature = module()->signatures[sig_index];
2905 2906 2907
    Handle<Object> object_ref = handle(entry.object_ref(), isolate);
    WasmCode* code =
        GetTargetCode(isolate->wasm_engine()->code_manager(), entry.target());
2908

2909 2910 2911
    if (!object_ref->IsWasmInstanceObject() || /* call to an import */
        !instance_object_.is_identical_to(object_ref) /* cross-instance */) {
      return CallExternalWasmFunction(isolate, object_ref, code, signature);
2912 2913
    }

2914 2915 2916
    DCHECK(code->kind() == WasmCode::kInterpreterEntry ||
           code->kind() == WasmCode::kFunction);
    return {ExternalCallResult::INTERNAL, codemap()->GetCode(code->index())};
2917
  }
2918 2919 2920 2921

  inline Activation current_activation() {
    return activations_.empty() ? Activation(0, 0) : activations_.back();
  }
2922 2923
};

2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
class InterpretedFrameImpl {
 public:
  InterpretedFrameImpl(ThreadImpl* thread, int index)
      : thread_(thread), index_(index) {
    DCHECK_LE(0, index);
  }

  const WasmFunction* function() const { return frame()->code->function; }

  int pc() const {
    DCHECK_LE(0, frame()->pc);
    DCHECK_GE(kMaxInt, frame()->pc);
    return static_cast<int>(frame()->pc);
  }

  int GetParameterCount() const {
    DCHECK_GE(kMaxInt, function()->sig->parameter_count());
    return static_cast<int>(function()->sig->parameter_count());
  }

  int GetLocalCount() const {
    size_t num_locals = function()->sig->parameter_count() +
                        frame()->code->locals.type_list.size();
    DCHECK_GE(kMaxInt, num_locals);
    return static_cast<int>(num_locals);
  }

  int GetStackHeight() const {
    bool is_top_frame =
        static_cast<size_t>(index_) + 1 == thread_->frames_.size();
    size_t stack_limit =
2955
        is_top_frame ? thread_->StackHeight() : thread_->frames_[index_ + 1].sp;
2956 2957 2958 2959
    DCHECK_LE(frame()->sp, stack_limit);
    size_t frame_size = stack_limit - frame()->sp;
    DCHECK_LE(GetLocalCount(), frame_size);
    return static_cast<int>(frame_size) - GetLocalCount();
2960 2961
  }

2962
  WasmValue GetLocalValue(int index) const {
2963 2964 2965 2966 2967
    DCHECK_LE(0, index);
    DCHECK_GT(GetLocalCount(), index);
    return thread_->GetStackValue(static_cast<int>(frame()->sp) + index);
  }

2968
  WasmValue GetStackValue(int index) const {
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
    DCHECK_LE(0, index);
    // Index must be within the number of stack values of this frame.
    DCHECK_GT(GetStackHeight(), index);
    return thread_->GetStackValue(static_cast<int>(frame()->sp) +
                                  GetLocalCount() + index);
  }

 private:
  ThreadImpl* thread_;
  int index_;

  ThreadImpl::Frame* frame() const {
    DCHECK_GT(thread_->frames_.size(), index_);
    return &thread_->frames_[index_];
  }
};

2986 2987
namespace {

2988 2989 2990 2991 2992 2993 2994
// Converters between WasmInterpreter::Thread and WasmInterpreter::ThreadImpl.
// Thread* is the public interface, without knowledge of the object layout.
// This cast is potentially risky, but as long as we always cast it back before
// accessing any data, it should be fine. UBSan is not complaining.
WasmInterpreter::Thread* ToThread(ThreadImpl* impl) {
  return reinterpret_cast<WasmInterpreter::Thread*>(impl);
}
2995
ThreadImpl* ToImpl(WasmInterpreter::Thread* thread) {
2996 2997
  return reinterpret_cast<ThreadImpl*>(thread);
}
2998

2999 3000 3001 3002 3003 3004 3005 3006
// Same conversion for InterpretedFrame and InterpretedFrameImpl.
InterpretedFrame* ToFrame(InterpretedFrameImpl* impl) {
  return reinterpret_cast<InterpretedFrame*>(impl);
}
const InterpretedFrameImpl* ToImpl(const InterpretedFrame* frame) {
  return reinterpret_cast<const InterpretedFrameImpl*>(frame);
}

3007 3008
}  // namespace

3009
//============================================================================
3010 3011 3012 3013
// Implementation of the pimpl idiom for WasmInterpreter::Thread.
// Instead of placing a pointer to the ThreadImpl inside of the Thread object,
// we just reinterpret_cast them. ThreadImpls are only allocated inside this
// translation unit anyway.
3014 3015
//============================================================================
WasmInterpreter::State WasmInterpreter::Thread::state() {
3016
  return ToImpl(this)->state();
3017
}
3018
void WasmInterpreter::Thread::InitFrame(const WasmFunction* function,
3019
                                        WasmValue* args) {
3020
  ToImpl(this)->InitFrame(function, args);
3021
}
3022 3023
WasmInterpreter::State WasmInterpreter::Thread::Run(int num_steps) {
  return ToImpl(this)->Run(num_steps);
3024 3025 3026
}
void WasmInterpreter::Thread::Pause() { return ToImpl(this)->Pause(); }
void WasmInterpreter::Thread::Reset() { return ToImpl(this)->Reset(); }
3027 3028 3029 3030
WasmInterpreter::Thread::ExceptionHandlingResult
WasmInterpreter::Thread::HandleException(Isolate* isolate) {
  return ToImpl(this)->HandleException(isolate);
}
3031
pc_t WasmInterpreter::Thread::GetBreakpointPc() {
3032 3033 3034 3035
  return ToImpl(this)->GetBreakpointPc();
}
int WasmInterpreter::Thread::GetFrameCount() {
  return ToImpl(this)->GetFrameCount();
3036
}
3037
WasmInterpreter::FramePtr WasmInterpreter::Thread::GetFrame(int index) {
3038 3039
  DCHECK_LE(0, index);
  DCHECK_GT(GetFrameCount(), index);
3040
  return FramePtr(ToFrame(new InterpretedFrameImpl(ToImpl(this), index)));
3041
}
3042
WasmValue WasmInterpreter::Thread::GetReturnValue(int index) {
3043
  return ToImpl(this)->GetReturnValue(index);
3044
}
3045 3046 3047
TrapReason WasmInterpreter::Thread::GetTrapReason() {
  return ToImpl(this)->GetTrapReason();
}
3048
bool WasmInterpreter::Thread::PossibleNondeterminism() {
3049
  return ToImpl(this)->PossibleNondeterminism();
3050
}
3051 3052 3053
uint64_t WasmInterpreter::Thread::NumInterpretedCalls() {
  return ToImpl(this)->NumInterpretedCalls();
}
3054 3055 3056 3057 3058 3059
void WasmInterpreter::Thread::AddBreakFlags(uint8_t flags) {
  ToImpl(this)->AddBreakFlags(flags);
}
void WasmInterpreter::Thread::ClearBreakFlags() {
  ToImpl(this)->ClearBreakFlags();
}
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
uint32_t WasmInterpreter::Thread::NumActivations() {
  return ToImpl(this)->NumActivations();
}
uint32_t WasmInterpreter::Thread::StartActivation() {
  return ToImpl(this)->StartActivation();
}
void WasmInterpreter::Thread::FinishActivation(uint32_t id) {
  ToImpl(this)->FinishActivation(id);
}
uint32_t WasmInterpreter::Thread::ActivationFrameBase(uint32_t id) {
  return ToImpl(this)->ActivationFrameBase(id);
}
3072

3073 3074 3075 3076 3077
//============================================================================
// The implementation details of the interpreter.
//============================================================================
class WasmInterpreterInternals : public ZoneObject {
 public:
3078 3079 3080
  // Create a copy of the module bytes for the interpreter, since the passed
  // pointer might be invalidated after constructing the interpreter.
  const ZoneVector<uint8_t> module_bytes_;
3081
  CodeMap codemap_;
3082
  ZoneVector<ThreadImpl> threads_;
3083

3084
  WasmInterpreterInternals(Zone* zone, const WasmModule* module,
3085
                           const ModuleWireBytes& wire_bytes,
3086
                           Handle<WasmInstanceObject> instance_object)
3087
      : module_bytes_(wire_bytes.start(), wire_bytes.end(), zone),
3088
        codemap_(module, module_bytes_.data(), zone),
3089
        threads_(zone) {
3090
    threads_.emplace_back(zone, &codemap_, instance_object);
3091
  }
3092 3093
};

3094
namespace {
3095 3096 3097 3098
void NopFinalizer(const v8::WeakCallbackInfo<void>& data) {
  Object** global_handle_location =
      reinterpret_cast<Object**>(data.GetParameter());
  GlobalHandles::Destroy(global_handle_location);
3099 3100 3101 3102
}

Handle<WasmInstanceObject> MakeWeak(
    Isolate* isolate, Handle<WasmInstanceObject> instance_object) {
3103 3104 3105 3106 3107 3108 3109
  Handle<WasmInstanceObject> weak_instance =
      isolate->global_handles()->Create<WasmInstanceObject>(*instance_object);
  Object** global_handle_location =
      Handle<Object>::cast(weak_instance).location();
  GlobalHandles::MakeWeak(global_handle_location, global_handle_location,
                          &NopFinalizer, v8::WeakCallbackType::kParameter);
  return weak_instance;
3110 3111 3112
}
}  // namespace

3113 3114 3115
//============================================================================
// Implementation of the public interface of the interpreter.
//============================================================================
3116 3117
WasmInterpreter::WasmInterpreter(Isolate* isolate, const WasmModule* module,
                                 const ModuleWireBytes& wire_bytes,
3118
                                 Handle<WasmInstanceObject> instance_object)
3119
    : zone_(isolate->allocator(), ZONE_NAME),
3120
      internals_(new (&zone_) WasmInterpreterInternals(
3121
          &zone_, module, wire_bytes, MakeWeak(isolate, instance_object))) {}
3122

3123
WasmInterpreter::~WasmInterpreter() { internals_->~WasmInterpreterInternals(); }
3124

3125
void WasmInterpreter::Run() { internals_->threads_[0].Run(); }
3126

3127
void WasmInterpreter::Pause() { internals_->threads_[0].Pause(); }
3128

3129
bool WasmInterpreter::SetBreakpoint(const WasmFunction* function, pc_t pc,
3130
                                    bool enabled) {
3131
  InterpreterCode* code = internals_->codemap_.GetCode(function);
3132
  size_t size = static_cast<size_t>(code->end - code->start);
3133
  // Check bounds for {pc}.
3134
  if (pc < code->locals.encoded_size || pc >= size) return false;
3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
  // Make a copy of the code before enabling a breakpoint.
  if (enabled && code->orig_start == code->start) {
    code->start = reinterpret_cast<byte*>(zone_.New(size));
    memcpy(code->start, code->orig_start, size);
    code->end = code->start + size;
  }
  bool prev = code->start[pc] == kInternalBreakpoint;
  if (enabled) {
    code->start[pc] = kInternalBreakpoint;
  } else {
    code->start[pc] = code->orig_start[pc];
  }
  return prev;
}

3150
bool WasmInterpreter::GetBreakpoint(const WasmFunction* function, pc_t pc) {
3151
  InterpreterCode* code = internals_->codemap_.GetCode(function);
3152
  size_t size = static_cast<size_t>(code->end - code->start);
3153
  // Check bounds for {pc}.
3154
  if (pc < code->locals.encoded_size || pc >= size) return false;
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167
  // Check if a breakpoint is present at that place in the code.
  return code->start[pc] == kInternalBreakpoint;
}

bool WasmInterpreter::SetTracing(const WasmFunction* function, bool enabled) {
  UNIMPLEMENTED();
  return false;
}

int WasmInterpreter::GetThreadCount() {
  return 1;  // only one thread for now.
}

3168
WasmInterpreter::Thread* WasmInterpreter::GetThread(int id) {
3169
  CHECK_EQ(0, id);  // only one thread for now.
3170
  return ToThread(&internals_->threads_[id]);
3171 3172
}

3173 3174
void WasmInterpreter::AddFunctionForTesting(const WasmFunction* function) {
  internals_->codemap_.AddFunction(function, nullptr, nullptr);
3175 3176
}

3177
void WasmInterpreter::SetFunctionCodeForTesting(const WasmFunction* function,
3178 3179
                                                const byte* start,
                                                const byte* end) {
3180
  internals_->codemap_.SetFunctionCode(function, start, end);
3181 3182
}

3183 3184 3185 3186
void WasmInterpreter::SetCallIndirectTestMode() {
  internals_->codemap_.set_call_indirect_through_module(true);
}

3187
ControlTransferMap WasmInterpreter::ComputeControlTransfersForTesting(
3188 3189 3190 3191
    Zone* zone, const WasmModule* module, const byte* start, const byte* end) {
  // Create some dummy structures, to avoid special-casing the implementation
  // just for testing.
  FunctionSig sig(0, 0, nullptr);
3192
  WasmFunction function{&sig, 0, 0, {0, 0}, false, false};
3193 3194 3195 3196
  InterpreterCode code{
      &function, BodyLocalDecls(zone), start, end, nullptr, nullptr, nullptr};

  // Now compute and return the control transfers.
3197 3198
  SideTable side_table(zone, module, &code);
  return side_table.map_;
3199 3200
}

3201 3202 3203
//============================================================================
// Implementation of the frame inspection interface.
//============================================================================
3204 3205 3206 3207
const WasmFunction* InterpretedFrame::function() const {
  return ToImpl(this)->function();
}
int InterpretedFrame::pc() const { return ToImpl(this)->pc(); }
3208
int InterpretedFrame::GetParameterCount() const {
3209
  return ToImpl(this)->GetParameterCount();
3210
}
3211 3212
int InterpretedFrame::GetLocalCount() const {
  return ToImpl(this)->GetLocalCount();
3213
}
3214 3215 3216
int InterpretedFrame::GetStackHeight() const {
  return ToImpl(this)->GetStackHeight();
}
3217
WasmValue InterpretedFrame::GetLocalValue(int index) const {
3218 3219
  return ToImpl(this)->GetLocalValue(index);
}
3220
WasmValue InterpretedFrame::GetStackValue(int index) const {
3221
  return ToImpl(this)->GetStackValue(index);
3222
}
Marja Hölttä's avatar
Marja Hölttä committed
3223
void InterpretedFrameDeleter::operator()(InterpretedFrame* ptr) {
3224 3225
  delete ToImpl(ptr);
}
3226

3227
#undef TRACE
3228
#undef LANE
3229 3230 3231 3232
#undef FOREACH_INTERNAL_OPCODE
#undef WASM_CTYPES
#undef FOREACH_SIMPLE_BINOP
#undef FOREACH_OTHER_BINOP
3233
#undef FOREACH_I32CONV_FLOATOP
3234
#undef FOREACH_OTHER_UNOP
3235

3236 3237 3238
}  // namespace wasm
}  // namespace internal
}  // namespace v8