bytecode-graph-builder.cc 139 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 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.

#include "src/compiler/bytecode-graph-builder.h"

7
#include "src/ast/ast.h"
8
#include "src/ast/scopes.h"
9
#include "src/compiler/access-builder.h"
10
#include "src/compiler/compiler-source-position-table.h"
11
#include "src/compiler/linkage.h"
12
#include "src/compiler/node-matchers.h"
13
#include "src/compiler/operator-properties.h"
14
#include "src/compiler/simplified-operator.h"
15
#include "src/interpreter/bytecodes.h"
16
#include "src/objects-inl.h"
17
#include "src/objects/js-array-inl.h"
18
#include "src/objects/js-generator.h"
19
#include "src/objects/literal-objects-inl.h"
20
#include "src/objects/smi.h"
21
#include "src/objects/template-objects-inl.h"
22
#include "src/vector-slot-pair.h"
23 24 25 26 27

namespace v8 {
namespace internal {
namespace compiler {

28 29 30 31 32 33
// The abstract execution environment simulates the content of the interpreter
// register file. The environment performs SSA-renaming of all tracked nodes at
// split and merge points in the control flow.
class BytecodeGraphBuilder::Environment : public ZoneObject {
 public:
  Environment(BytecodeGraphBuilder* builder, int register_count,
34 35 36
              int parameter_count,
              interpreter::Register incoming_new_target_or_generator,
              Node* control_dependency);
37

38 39 40 41 42
  // Specifies whether environment binding methods should attach frame state
  // inputs to nodes representing the value being bound. This is done because
  // the {OutputFrameStateCombine} is closely related to the binding method.
  enum FrameStateAttachmentMode { kAttachFrameState, kDontAttachFrameState };

43 44 45 46 47
  int parameter_count() const { return parameter_count_; }
  int register_count() const { return register_count_; }

  Node* LookupAccumulator() const;
  Node* LookupRegister(interpreter::Register the_register) const;
48
  Node* LookupGeneratorState() const;
49

50 51
  void BindAccumulator(Node* node,
                       FrameStateAttachmentMode mode = kDontAttachFrameState);
52
  void BindRegister(interpreter::Register the_register, Node* node,
53 54 55 56
                    FrameStateAttachmentMode mode = kDontAttachFrameState);
  void BindRegistersToProjections(
      interpreter::Register first_reg, Node* node,
      FrameStateAttachmentMode mode = kDontAttachFrameState);
57
  void BindGeneratorState(Node* node);
58 59
  void RecordAfterState(Node* node,
                        FrameStateAttachmentMode mode = kDontAttachFrameState);
60 61 62 63 64 65 66 67 68

  // Effect dependency tracked by this environment.
  Node* GetEffectDependency() { return effect_dependency_; }
  void UpdateEffectDependency(Node* dependency) {
    effect_dependency_ = dependency;
  }

  // Preserve a checkpoint of the environment for the IR graph. Any
  // further mutation of the environment will not affect checkpoints.
69
  Node* Checkpoint(BailoutId bytecode_offset, OutputFrameStateCombine combine,
70
                   const BytecodeLivenessState* liveness);
71 72 73 74 75 76 77 78 79 80

  // Control dependency tracked by this environment.
  Node* GetControlDependency() const { return control_dependency_; }
  void UpdateControlDependency(Node* dependency) {
    control_dependency_ = dependency;
  }

  Node* Context() const { return context_; }
  void SetContext(Node* new_context) { context_ = new_context; }

81
  Environment* Copy();
82
  void Merge(Environment* other, const BytecodeLivenessState* liveness);
83

84
  void FillWithOsrValues();
85 86
  void PrepareForLoop(const BytecodeLoopAssignments& assignments,
                      const BytecodeLivenessState* liveness);
87
  void PrepareForLoopExit(Node* loop,
88 89
                          const BytecodeLoopAssignments& assignments,
                          const BytecodeLivenessState* liveness);
90

91
 private:
92
  explicit Environment(const Environment* copy);
93

94 95
  bool StateValuesRequireUpdate(Node** state_values, Node** values, int count);
  void UpdateStateValues(Node** state_values, Node** values, int count);
96 97
  Node* GetStateValuesFromCache(Node** values, int count,
                                const BitVector* liveness, int liveness_offset);
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

  int RegisterToValuesIndex(interpreter::Register the_register) const;

  Zone* zone() const { return builder_->local_zone(); }
  Graph* graph() const { return builder_->graph(); }
  CommonOperatorBuilder* common() const { return builder_->common(); }
  BytecodeGraphBuilder* builder() const { return builder_; }
  const NodeVector* values() const { return &values_; }
  NodeVector* values() { return &values_; }
  int register_base() const { return register_base_; }
  int accumulator_base() const { return accumulator_base_; }

  BytecodeGraphBuilder* builder_;
  int register_count_;
  int parameter_count_;
  Node* context_;
  Node* control_dependency_;
  Node* effect_dependency_;
  NodeVector values_;
  Node* parameters_state_values_;
118
  Node* generator_state_;
119 120 121 122
  int register_base_;
  int accumulator_base_;
};

123 124 125 126 127 128 129 130 131 132 133 134
// A helper for creating a temporary sub-environment for simple branches.
struct BytecodeGraphBuilder::SubEnvironment final {
 public:
  explicit SubEnvironment(BytecodeGraphBuilder* builder)
      : builder_(builder), parent_(builder->environment()->Copy()) {}

  ~SubEnvironment() { builder_->set_environment(parent_); }

 private:
  BytecodeGraphBuilder* builder_;
  BytecodeGraphBuilder::Environment* parent_;
};
135

136 137 138
// Issues:
// - Scopes - intimately tied to AST. Need to eval what is needed.
// - Need to resolve closure parameter treatment.
139 140 141 142
BytecodeGraphBuilder::Environment::Environment(
    BytecodeGraphBuilder* builder, int register_count, int parameter_count,
    interpreter::Register incoming_new_target_or_generator,
    Node* control_dependency)
143 144 145 146 147
    : builder_(builder),
      register_count_(register_count),
      parameter_count_(parameter_count),
      control_dependency_(control_dependency),
      effect_dependency_(control_dependency),
148
      values_(builder->local_zone()),
149 150
      parameters_state_values_(nullptr),
      generator_state_(nullptr) {
151 152
  // The layout of values_ is:
  //
153
  // [receiver] [parameters] [registers] [accumulator]
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  //
  // parameter[0] is the receiver (this), parameters 1..N are the
  // parameters supplied to the method (arg0..argN-1). The accumulator
  // is stored separately.

  // Parameters including the receiver
  for (int i = 0; i < parameter_count; i++) {
    const char* debug_name = (i == 0) ? "%this" : nullptr;
    const Operator* op = common()->Parameter(i, debug_name);
    Node* parameter = builder->graph()->NewNode(op, graph()->start());
    values()->push_back(parameter);
  }

  // Registers
  register_base_ = static_cast<int>(values()->size());
  Node* undefined_constant = builder->jsgraph()->UndefinedConstant();
  values()->insert(values()->end(), register_count, undefined_constant);

  // Accumulator
173 174
  accumulator_base_ = static_cast<int>(values()->size());
  values()->push_back(undefined_constant);
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

  // Context
  int context_index = Linkage::GetJSCallContextParamIndex(parameter_count);
  const Operator* op = common()->Parameter(context_index, "%context");
  context_ = builder->graph()->NewNode(op, graph()->start());

  // Incoming new.target or generator register
  if (incoming_new_target_or_generator.is_valid()) {
    int new_target_index =
        Linkage::GetJSCallNewTargetParamIndex(parameter_count);
    const Operator* op = common()->Parameter(new_target_index, "%new.target");
    Node* new_target_node = builder->graph()->NewNode(op, graph()->start());

    int values_index = RegisterToValuesIndex(incoming_new_target_or_generator);
    values()->at(values_index) = new_target_node;
  }
191 192
}

193
BytecodeGraphBuilder::Environment::Environment(
194
    const BytecodeGraphBuilder::Environment* other)
195 196 197 198 199 200 201
    : builder_(other->builder_),
      register_count_(other->register_count_),
      parameter_count_(other->parameter_count_),
      context_(other->context_),
      control_dependency_(other->control_dependency_),
      effect_dependency_(other->effect_dependency_),
      values_(other->zone()),
202
      parameters_state_values_(other->parameters_state_values_),
203
      generator_state_(other->generator_state_),
204
      register_base_(other->register_base_),
205
      accumulator_base_(other->accumulator_base_) {
206 207 208 209
  values_ = other->values_;
}


210 211 212 213 214 215 216 217 218
int BytecodeGraphBuilder::Environment::RegisterToValuesIndex(
    interpreter::Register the_register) const {
  if (the_register.is_parameter()) {
    return the_register.ToParameterIndex(parameter_count());
  } else {
    return the_register.index() + register_base();
  }
}

219 220
Node* BytecodeGraphBuilder::Environment::LookupAccumulator() const {
  return values()->at(accumulator_base_);
221 222
}

223 224 225 226
Node* BytecodeGraphBuilder::Environment::LookupGeneratorState() const {
  DCHECK_NOT_NULL(generator_state_);
  return generator_state_;
}
227 228 229

Node* BytecodeGraphBuilder::Environment::LookupRegister(
    interpreter::Register the_register) const {
230 231
  if (the_register.is_current_context()) {
    return Context();
232 233 234 235 236 237
  } else if (the_register.is_function_closure()) {
    return builder()->GetFunctionClosure();
  } else {
    int values_index = RegisterToValuesIndex(the_register);
    return values()->at(values_index);
  }
238 239
}

240
void BytecodeGraphBuilder::Environment::BindAccumulator(
241 242 243
    Node* node, FrameStateAttachmentMode mode) {
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(0));
244 245 246 247
  }
  values()->at(accumulator_base_) = node;
}

248 249 250 251
void BytecodeGraphBuilder::Environment::BindGeneratorState(Node* node) {
  generator_state_ = node;
}

252 253
void BytecodeGraphBuilder::Environment::BindRegister(
    interpreter::Register the_register, Node* node,
254
    FrameStateAttachmentMode mode) {
255
  int values_index = RegisterToValuesIndex(the_register);
256 257 258
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(
                                           accumulator_base_ - values_index));
259 260
  }
  values()->at(values_index) = node;
261 262
}

263 264
void BytecodeGraphBuilder::Environment::BindRegistersToProjections(
    interpreter::Register first_reg, Node* node,
265
    FrameStateAttachmentMode mode) {
266
  int values_index = RegisterToValuesIndex(first_reg);
267 268 269
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::PokeAt(
                                           accumulator_base_ - values_index));
270 271 272 273 274
  }
  for (int i = 0; i < node->op()->ValueOutputCount(); i++) {
    values()->at(values_index + i) =
        builder()->NewNode(common()->Projection(i), node);
  }
275 276
}

277
void BytecodeGraphBuilder::Environment::RecordAfterState(
278 279 280 281
    Node* node, FrameStateAttachmentMode mode) {
  if (mode == FrameStateAttachmentMode::kAttachFrameState) {
    builder()->PrepareFrameState(node, OutputFrameStateCombine::Ignore());
  }
282 283
}

284
BytecodeGraphBuilder::Environment* BytecodeGraphBuilder::Environment::Copy() {
285
  return new (zone()) Environment(this);
286 287 288
}

void BytecodeGraphBuilder::Environment::Merge(
289 290
    BytecodeGraphBuilder::Environment* other,
    const BytecodeLivenessState* liveness) {
291 292 293 294 295 296 297 298 299 300 301 302
  // Create a merge of the control dependencies of both environments and update
  // the current environment's control dependency accordingly.
  Node* control = builder()->MergeControl(GetControlDependency(),
                                          other->GetControlDependency());
  UpdateControlDependency(control);

  // Create a merge of the effect dependencies of both environments and update
  // the current environment's effect dependency accordingly.
  Node* effect = builder()->MergeEffect(GetEffectDependency(),
                                        other->GetEffectDependency(), control);
  UpdateEffectDependency(effect);

303 304
  // Introduce Phi nodes for values that are live and have differing inputs at
  // the merge point, potentially extending an existing Phi node if possible.
305
  context_ = builder()->MergeValue(context_, other->context_, control);
306
  for (int i = 0; i < parameter_count(); i++) {
307 308
    values_[i] = builder()->MergeValue(values_[i], other->values_[i], control);
  }
309 310 311
  for (int i = 0; i < register_count(); i++) {
    int index = register_base() + i;
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
312 313 314 315 316 317 318 319 320 321 322 323
#if DEBUG
      // We only do these DCHECKs when we are not in the resume path of a
      // generator -- this is, when either there is no generator state at all,
      // or the generator state is not the constant "executing" value.
      if (generator_state_ == nullptr ||
          NumberMatcher(generator_state_)
              .Is(JSGeneratorObject::kGeneratorExecuting)) {
        DCHECK_NE(values_[index], builder()->jsgraph()->OptimizedOutConstant());
        DCHECK_NE(other->values_[index],
                  builder()->jsgraph()->OptimizedOutConstant());
      }
#endif
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

      values_[index] =
          builder()->MergeValue(values_[index], other->values_[index], control);

    } else {
      values_[index] = builder()->jsgraph()->OptimizedOutConstant();
    }
  }

  if (liveness == nullptr || liveness->AccumulatorIsLive()) {
    DCHECK_NE(values_[accumulator_base()],
              builder()->jsgraph()->OptimizedOutConstant());
    DCHECK_NE(other->values_[accumulator_base()],
              builder()->jsgraph()->OptimizedOutConstant());

    values_[accumulator_base()] =
        builder()->MergeValue(values_[accumulator_base()],
                              other->values_[accumulator_base()], control);
  } else {
    values_[accumulator_base()] = builder()->jsgraph()->OptimizedOutConstant();
  }
345 346 347 348 349 350

  if (generator_state_ != nullptr) {
    DCHECK_NOT_NULL(other->generator_state_);
    generator_state_ = builder()->MergeValue(generator_state_,
                                             other->generator_state_, control);
  }
351 352
}

353
void BytecodeGraphBuilder::Environment::PrepareForLoop(
354 355
    const BytecodeLoopAssignments& assignments,
    const BytecodeLivenessState* liveness) {
356 357 358 359 360 361 362
  // Create a control node for the loop header.
  Node* control = builder()->NewLoop();

  // Create a Phi for external effects.
  Node* effect = builder()->NewEffectPhi(1, GetEffectDependency(), control);
  UpdateEffectDependency(effect);

363 364
  // Create Phis for any values that are live on entry to the loop and may be
  // updated by the end of the loop.
365
  context_ = builder()->NewPhi(1, context_, control);
366 367 368 369 370 371
  for (int i = 0; i < parameter_count(); i++) {
    if (assignments.ContainsParameter(i)) {
      values_[i] = builder()->NewPhi(1, values_[i], control);
    }
  }
  for (int i = 0; i < register_count(); i++) {
372 373
    if (assignments.ContainsLocal(i) &&
        (liveness == nullptr || liveness->RegisterIsLive(i))) {
374 375 376 377
      int index = register_base() + i;
      values_[index] = builder()->NewPhi(1, values_[index], control);
    }
  }
378 379
  // The accumulator should not be live on entry.
  DCHECK_IMPLIES(liveness != nullptr, !liveness->AccumulatorIsLive());
380

381 382 383 384
  if (generator_state_ != nullptr) {
    generator_state_ = builder()->NewPhi(1, generator_state_, control);
  }

385 386 387 388 389 390
  // Connect to the loop end.
  Node* terminate = builder()->graph()->NewNode(
      builder()->common()->Terminate(), effect, control);
  builder()->exit_controls_.push_back(terminate);
}

391
void BytecodeGraphBuilder::Environment::FillWithOsrValues() {
392 393
  Node* start = graph()->start();

394 395
  // Create OSR values for each environment value.
  SetContext(graph()->NewNode(
396
      common()->OsrValue(Linkage::kOsrContextSpillSlotIndex), start));
397 398 399 400 401
  int size = static_cast<int>(values()->size());
  for (int i = 0; i < size; i++) {
    int idx = i;  // Indexing scheme follows {StandardFrame}, adapt accordingly.
    if (i >= register_base()) idx += InterpreterFrameConstants::kExtraSlotCount;
    if (i >= accumulator_base()) idx = Linkage::kOsrAccumulatorRegisterIndex;
402
    values()->at(i) = graph()->NewNode(common()->OsrValue(idx), start);
403 404
  }
}
405

406
bool BytecodeGraphBuilder::Environment::StateValuesRequireUpdate(
407
    Node** state_values, Node** values, int count) {
408 409
  if (*state_values == nullptr) {
    return true;
410
  }
411
  Node::Inputs inputs = (*state_values)->inputs();
412
  if (inputs.count() != count) return true;
413
  for (int i = 0; i < count; i++) {
414
    if (inputs[i] != values[i]) {
415
      return true;
416 417 418 419 420
    }
  }
  return false;
}

421
void BytecodeGraphBuilder::Environment::PrepareForLoopExit(
422 423
    Node* loop, const BytecodeLoopAssignments& assignments,
    const BytecodeLivenessState* liveness) {
424 425 426 427 428 429 430 431 432 433 434 435 436
  DCHECK_EQ(loop->opcode(), IrOpcode::kLoop);

  Node* control = GetControlDependency();

  // Create the loop exit node.
  Node* loop_exit = graph()->NewNode(common()->LoopExit(), control, loop);
  UpdateControlDependency(loop_exit);

  // Rename the effect.
  Node* effect_rename = graph()->NewNode(common()->LoopExitEffect(),
                                         GetEffectDependency(), loop_exit);
  UpdateEffectDependency(effect_rename);

437
  // TODO(jarin) We should also rename context here. However, unconditional
438 439
  // renaming confuses global object and native context specialization.
  // We should only rename if the context is assigned in the loop.
440

441 442
  // Rename the environment values if they were assigned in the loop and are
  // live after exiting the loop.
443 444 445 446 447 448 449 450
  for (int i = 0; i < parameter_count(); i++) {
    if (assignments.ContainsParameter(i)) {
      Node* rename =
          graph()->NewNode(common()->LoopExitValue(), values_[i], loop_exit);
      values_[i] = rename;
    }
  }
  for (int i = 0; i < register_count(); i++) {
451 452
    if (assignments.ContainsLocal(i) &&
        (liveness == nullptr || liveness->RegisterIsLive(i))) {
453 454 455 456 457
      Node* rename = graph()->NewNode(common()->LoopExitValue(),
                                      values_[register_base() + i], loop_exit);
      values_[register_base() + i] = rename;
    }
  }
458 459 460 461 462
  if (liveness == nullptr || liveness->AccumulatorIsLive()) {
    Node* rename = graph()->NewNode(common()->LoopExitValue(),
                                    values_[accumulator_base()], loop_exit);
    values_[accumulator_base()] = rename;
  }
463 464 465 466 467

  if (generator_state_ != nullptr) {
    generator_state_ = graph()->NewNode(common()->LoopExitValue(),
                                        generator_state_, loop_exit);
  }
468
}
469 470

void BytecodeGraphBuilder::Environment::UpdateStateValues(Node** state_values,
471
                                                          Node** values,
472
                                                          int count) {
473
  if (StateValuesRequireUpdate(state_values, values, count)) {
474
    const Operator* op = common()->StateValues(count, SparseInputMask::Dense());
475
    (*state_values) = graph()->NewNode(op, count, values);
476 477 478
  }
}

479 480 481
Node* BytecodeGraphBuilder::Environment::GetStateValuesFromCache(
    Node** values, int count, const BitVector* liveness, int liveness_offset) {
  return builder_->state_values_cache_.GetNodeForValues(
482
      values, static_cast<size_t>(count), liveness, liveness_offset);
483 484
}

485
Node* BytecodeGraphBuilder::Environment::Checkpoint(
486
    BailoutId bailout_id, OutputFrameStateCombine combine,
487
    const BytecodeLivenessState* liveness) {
488 489 490
  if (parameter_count() == register_count()) {
    // Re-use the state-value cache if the number of local registers happens
    // to match the parameter count.
491 492
    parameters_state_values_ = GetStateValuesFromCache(
        &values()->at(0), parameter_count(), nullptr, 0);
493 494 495 496
  } else {
    UpdateStateValues(&parameters_state_values_, &values()->at(0),
                      parameter_count());
  }
497

498 499 500
  Node* registers_state_values =
      GetStateValuesFromCache(&values()->at(register_base()), register_count(),
                              liveness ? &liveness->bit_vector() : nullptr, 0);
501 502

  bool accumulator_is_live = !liveness || liveness->AccumulatorIsLive();
503
  Node* accumulator_state_value =
504 505 506
      accumulator_is_live && combine != OutputFrameStateCombine::PokeAt(0)
          ? values()->at(accumulator_base())
          : builder()->jsgraph()->OptimizedOutConstant();
507 508 509 510

  const Operator* op = common()->FrameState(
      bailout_id, combine, builder()->frame_state_function_info());
  Node* result = graph()->NewNode(
511
      op, parameters_state_values_, registers_state_values,
512
      accumulator_state_value, Context(), builder()->GetFunctionClosure(),
513 514 515 516 517
      builder()->graph()->start());

  return result;
}

518
BytecodeGraphBuilder::BytecodeGraphBuilder(
519 520
    Zone* local_zone, Handle<BytecodeArray> bytecode_array,
    Handle<SharedFunctionInfo> shared_info,
521
    Handle<FeedbackVector> feedback_vector, BailoutId osr_offset,
522
    JSGraph* jsgraph, CallFrequency& invocation_frequency,
523
    SourcePositionTable* source_positions, Handle<Context> native_context,
524 525
    int inlining_id, JSTypeHintLowering::Flags flags, bool stack_check,
    bool analyze_environment_liveness)
526 527
    : local_zone_(local_zone),
      jsgraph_(jsgraph),
528
      invocation_frequency_(invocation_frequency),
529
      bytecode_array_(bytecode_array),
530
      feedback_vector_(feedback_vector),
531
      type_hint_lowering_(jsgraph, feedback_vector, flags),
532 533
      frame_state_function_info_(common()->CreateFrameStateFunctionInfo(
          FrameStateType::kInterpretedFunction,
534 535
          bytecode_array->parameter_count(), bytecode_array->register_count(),
          shared_info)),
536 537 538
      bytecode_iterator_(nullptr),
      bytecode_analysis_(nullptr),
      environment_(nullptr),
539
      osr_offset_(osr_offset),
540 541
      currently_peeled_loop_offset_(-1),
      stack_check_(stack_check),
542
      analyze_environment_liveness_(analyze_environment_liveness),
543
      merge_environments_(local_zone),
544
      generator_merge_environments_(local_zone),
545 546
      exception_handlers_(local_zone),
      current_exception_handler_(0),
547 548
      input_buffer_size_(0),
      input_buffer_(nullptr),
549
      needs_eager_checkpoint_(true),
550 551
      exit_controls_(local_zone),
      state_values_cache_(jsgraph),
552
      source_positions_(source_positions),
553
      start_position_(shared_info->StartPosition(), inlining_id),
554
      shared_info_(shared_info),
555
      native_context_(native_context) {}
556

557 558
Node* BytecodeGraphBuilder::GetFunctionClosure() {
  if (!function_closure_.is_set()) {
559 560
    int index = Linkage::kJSCallClosureParamIndex;
    const Operator* op = common()->Parameter(index, "%closure");
561 562 563 564 565 566
    Node* node = NewNode(op, graph()->start());
    function_closure_.set(node);
  }
  return function_closure_.get();
}

567
Node* BytecodeGraphBuilder::BuildLoadNativeContextField(int index) {
568 569
  const Operator* op =
      javascript()->LoadContext(0, Context::NATIVE_CONTEXT_INDEX, true);
570 571 572 573
  Node* native_context = NewNode(op);
  Node* result = NewNode(javascript()->LoadContext(0, index, true));
  NodeProperties::ReplaceContextInput(result, native_context);
  return result;
574 575
}

576
VectorSlotPair BytecodeGraphBuilder::CreateVectorSlotPair(int slot_id) {
577 578 579
  FeedbackSlot slot = FeedbackVector::ToSlot(slot_id);
  FeedbackNexus nexus(feedback_vector(), slot);
  return VectorSlotPair(feedback_vector(), slot, nexus.ic_state());
580 581
}

582
void BytecodeGraphBuilder::CreateGraph() {
583 584
  SourcePositionTable::Scope pos_scope(source_positions_, start_position_);

585
  // Set up the basic structure of the graph. Outputs for {Start} are the formal
586 587 588
  // parameters (including the receiver) plus new target, number of arguments,
  // context and closure.
  int actual_parameter_count = bytecode_array()->parameter_count() + 4;
589 590 591
  graph()->SetStart(graph()->NewNode(common()->Start(actual_parameter_count)));

  Environment env(this, bytecode_array()->register_count(),
592 593 594
                  bytecode_array()->parameter_count(),
                  bytecode_array()->incoming_new_target_or_generator_register(),
                  graph()->start());
595 596
  set_environment(&env);

597
  VisitBytecodes();
598 599 600 601 602 603 604 605 606

  // Finish the basic structure of the graph.
  DCHECK_NE(0u, exit_controls_.size());
  int const input_count = static_cast<int>(exit_controls_.size());
  Node** const inputs = &exit_controls_.front();
  Node* end = graph()->NewNode(common()->End(input_count), input_count, inputs);
  graph()->SetEnd(end);
}

607
void BytecodeGraphBuilder::PrepareEagerCheckpoint() {
608
  if (needs_eager_checkpoint()) {
609 610
    // Create an explicit checkpoint node for before the operation. This only
    // needs to happen if we aren't effect-dominated by a {Checkpoint} already.
611
    mark_as_needing_eager_checkpoint(false);
612 613 614 615
    Node* node = NewNode(common()->Checkpoint());
    DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
    DCHECK_EQ(IrOpcode::kDead,
              NodeProperties::GetFrameStateInput(node)->opcode());
616
    BailoutId bailout_id(bytecode_iterator().current_offset());
617

618 619 620
    const BytecodeLivenessState* liveness_before =
        bytecode_analysis()->GetInLivenessFor(
            bytecode_iterator().current_offset());
621

622
    Node* frame_state_before = environment()->Checkpoint(
623
        bailout_id, OutputFrameStateCombine::Ignore(), liveness_before);
624
    NodeProperties::ReplaceFrameStateInput(node, frame_state_before);
625 626 627 628 629 630 631 632 633 634 635 636 637
#ifdef DEBUG
  } else {
    // In case we skipped checkpoint creation above, we must be able to find an
    // existing checkpoint that effect-dominates the nodes about to be created.
    // Starting a search from the current effect-dependency has to succeed.
    Node* effect = environment()->GetEffectDependency();
    while (effect->opcode() != IrOpcode::kCheckpoint) {
      DCHECK(effect->op()->HasProperty(Operator::kNoWrite));
      DCHECK_EQ(1, effect->op()->EffectInputCount());
      effect = NodeProperties::GetEffectInput(effect);
    }
  }
#else
638
  }
639
#endif  // DEBUG
640 641 642 643 644 645 646 647 648 649
}

void BytecodeGraphBuilder::PrepareFrameState(Node* node,
                                             OutputFrameStateCombine combine) {
  if (OperatorProperties::HasFrameStateInput(node->op())) {
    // Add the frame state for after the operation. The node in question has
    // already been created and had a {Dead} frame state input up until now.
    DCHECK_EQ(1, OperatorProperties::GetFrameStateInputCount(node->op()));
    DCHECK_EQ(IrOpcode::kDead,
              NodeProperties::GetFrameStateInput(node)->opcode());
650
    BailoutId bailout_id(bytecode_iterator().current_offset());
651

652 653 654
    const BytecodeLivenessState* liveness_after =
        bytecode_analysis()->GetOutLivenessFor(
            bytecode_iterator().current_offset());
655

656 657
    Node* frame_state_after =
        environment()->Checkpoint(bailout_id, combine, liveness_after);
658
    NodeProperties::ReplaceFrameStateInput(node, frame_state_after);
659 660 661
  }
}

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
// Stores the state of the SourcePosition iterator, and the index to the
// current exception handlers stack. We need, during the OSR graph generation,
// to backup the states of these iterators at the LoopHeader offset of each
// outer loop which contains the OSR loop. The iterators are then restored when
// peeling the loops, so that both exception handling and synchronisation with
// the source position can be achieved.
class BytecodeGraphBuilder::OsrIteratorState {
 public:
  OsrIteratorState(interpreter::BytecodeArrayIterator* iterator,
                   SourcePositionTableIterator* source_position_iterator,
                   BytecodeGraphBuilder* graph_builder)
      : iterator_(iterator),
        source_position_iterator_(source_position_iterator),
        graph_builder_(graph_builder),
        saved_states_(graph_builder->local_zone()) {}

  void ProcessOsrPrelude() {
    ZoneVector<int> outer_loop_offsets(graph_builder_->local_zone());

    const BytecodeAnalysis& bytecode_analysis =
        *(graph_builder_->bytecode_analysis());
    int osr_offset = bytecode_analysis.osr_entry_point();

    // We find here the outermost loop which contains the OSR loop.
    int outermost_loop_offset = osr_offset;
    while ((outermost_loop_offset =
                bytecode_analysis.GetLoopInfoFor(outermost_loop_offset)
                    .parent_offset()) != -1) {
      outer_loop_offsets.push_back(outermost_loop_offset);
    }
    outermost_loop_offset =
        outer_loop_offsets.empty() ? osr_offset : outer_loop_offsets.back();

    // We will not processs any bytecode before the outermost_loop_offset, but
    // the source_position_iterator needs to be advanced step by step through
    // the bytecode.
    for (; iterator_->current_offset() != outermost_loop_offset;
         iterator_->Advance()) {
      graph_builder_->UpdateSourcePosition(source_position_iterator_,
                                           iterator_->current_offset());
    }

    // We save some iterators states at the offsets of the loop headers of the
    // outer loops (the ones containing the OSR loop). They will be used for
    // jumping back in the bytecode.
    for (ZoneVector<int>::const_reverse_iterator it =
             outer_loop_offsets.crbegin();
         it != outer_loop_offsets.crend(); ++it) {
      int next_loop_offset = *it;
      for (; iterator_->current_offset() != next_loop_offset;
           iterator_->Advance()) {
        graph_builder_->UpdateSourcePosition(source_position_iterator_,
                                             iterator_->current_offset());
      }
      graph_builder_->ExitThenEnterExceptionHandlers(
          iterator_->current_offset());
      saved_states_.push(
          IteratorsStates(graph_builder_->current_exception_handler(),
                          source_position_iterator_->GetState()));
    }

    // Finishing by advancing to the OSR entry
    for (; iterator_->current_offset() != osr_offset; iterator_->Advance()) {
      graph_builder_->UpdateSourcePosition(source_position_iterator_,
                                           iterator_->current_offset());
    }

    // Enters all remaining exception handler which end before the OSR loop
    // so that on next call of VisitSingleBytecode they will get popped from
    // the exception handlers stack.
    graph_builder_->ExitThenEnterExceptionHandlers(osr_offset);
    graph_builder_->set_currently_peeled_loop_offset(
        bytecode_analysis.GetLoopInfoFor(osr_offset).parent_offset());
  }

  void RestoreState(int target_offset, int new_parent_offset) {
    iterator_->SetOffset(target_offset);
    // In case of a return, we must not build loop exits for
    // not-yet-built outer loops.
    graph_builder_->set_currently_peeled_loop_offset(new_parent_offset);
    IteratorsStates saved_state = saved_states_.top();
    source_position_iterator_->RestoreState(saved_state.source_iterator_state_);
    graph_builder_->set_current_exception_handler(
        saved_state.exception_handler_index_);
    saved_states_.pop();
  }

 private:
  struct IteratorsStates {
    int exception_handler_index_;
752
    SourcePositionTableIterator::IndexAndPositionState source_iterator_state_;
753

754 755 756
    IteratorsStates(int exception_handler_index,
                    SourcePositionTableIterator::IndexAndPositionState
                        source_iterator_state)
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
        : exception_handler_index_(exception_handler_index),
          source_iterator_state_(source_iterator_state) {}
  };

  interpreter::BytecodeArrayIterator* iterator_;
  SourcePositionTableIterator* source_position_iterator_;
  BytecodeGraphBuilder* graph_builder_;
  ZoneStack<IteratorsStates> saved_states_;
};

void BytecodeGraphBuilder::RemoveMergeEnvironmentsBeforeOffset(
    int limit_offset) {
  if (!merge_environments_.empty()) {
    ZoneMap<int, Environment*>::iterator it = merge_environments_.begin();
    ZoneMap<int, Environment*>::iterator stop_it = merge_environments_.end();
    while (it != stop_it && it->first <= limit_offset) {
      it = merge_environments_.erase(it);
    }
  }
}

// We will iterate through the OSR loop, then its parent, and so on
// until we have reached the outmost loop containing the OSR loop. We do
// not generate nodes for anything before the outermost loop.
void BytecodeGraphBuilder::AdvanceToOsrEntryAndPeelLoops(
    interpreter::BytecodeArrayIterator* iterator,
    SourcePositionTableIterator* source_position_iterator) {
  const BytecodeAnalysis& analysis = *(bytecode_analysis());
  int osr_offset = analysis.osr_entry_point();
  OsrIteratorState iterator_states(iterator, source_position_iterator, this);

  iterator_states.ProcessOsrPrelude();
  DCHECK_EQ(iterator->current_offset(), osr_offset);

  environment()->FillWithOsrValues();

  // Suppose we have n nested loops, loop_0 being the outermost one, and
  // loop_n being the OSR loop. We start iterating the bytecode at the header
  // of loop_n (the OSR loop), and then we peel the part of the the body of
  // loop_{n-1} following the end of loop_n. We then rewind the iterator to
  // the header of loop_{n-1}, and so on until we have partly peeled loop 0.
  // The full loop_0 body will be generating with the rest of the function,
  // outside the OSR generation.

  // To do so, if we are visiting a loop, we continue to visit what's left
  // of its parent, and then when reaching the parent's JumpLoop, we do not
  // create any jump for that but rewind the bytecode iterator to visit the
  // parent loop entirely, and so on.

  int current_parent_offset =
      analysis.GetLoopInfoFor(osr_offset).parent_offset();
  while (current_parent_offset != -1) {
809
    const LoopInfo& current_parent_loop =
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
        analysis.GetLoopInfoFor(current_parent_offset);
    // We iterate until the back edge of the parent loop, which we detect by
    // the offset that the JumpLoop targets.
    for (; !iterator->done(); iterator->Advance()) {
      if (iterator->current_bytecode() == interpreter::Bytecode::kJumpLoop &&
          iterator->GetJumpTargetOffset() == current_parent_offset) {
        // Reached the end of the current parent loop.
        break;
      }
      VisitSingleBytecode(source_position_iterator);
    }
    DCHECK(!iterator->done());  // Should have found the loop's jump target.

    // We also need to take care of the merge environments and exceptions
    // handlers here because the omitted JumpLoop bytecode can still be the
    // target of jumps or the first bytecode after a try block.
    ExitThenEnterExceptionHandlers(iterator->current_offset());
    SwitchToMergeEnvironment(iterator->current_offset());

    // This jump is the jump of our parent loop, which is not yet created.
    // So we do not build the jump nodes, but restore the bytecode and the
    // SourcePosition iterators to the values they had when we were visiting
    // the offset pointed at by the JumpLoop we've just reached.
    // We have already built nodes for inner loops, but now we will
    // iterate again over them and build new nodes corresponding to the same
    // bytecode offsets. Any jump or reference to this inner loops must now
    // point to the new nodes we will build, hence we clear the relevant part
    // of the environment.
    // Completely clearing the environment is not possible because merge
    // environments for forward jumps out of the loop need to be preserved
    // (e.g. a return or a labeled break in the middle of a loop).
    RemoveMergeEnvironmentsBeforeOffset(iterator->current_offset());
    iterator_states.RestoreState(current_parent_offset,
                                 current_parent_loop.parent_offset());
    current_parent_offset = current_parent_loop.parent_offset();
  }
}

void BytecodeGraphBuilder::VisitSingleBytecode(
    SourcePositionTableIterator* source_position_iterator) {
  const interpreter::BytecodeArrayIterator& iterator = bytecode_iterator();
  int current_offset = iterator.current_offset();
  UpdateSourcePosition(source_position_iterator, current_offset);
  ExitThenEnterExceptionHandlers(current_offset);
  DCHECK_GE(exception_handlers_.empty() ? current_offset
                                        : exception_handlers_.top().end_offset_,
            current_offset);
  SwitchToMergeEnvironment(current_offset);

  if (environment() != nullptr) {
    BuildLoopHeaderEnvironment(current_offset);

    // Skip the first stack check if stack_check is false
    if (!stack_check() &&
        iterator.current_bytecode() == interpreter::Bytecode::kStackCheck) {
      set_stack_check(true);
      return;
    }

    switch (iterator.current_bytecode()) {
#define BYTECODE_CASE(name, ...)       \
  case interpreter::Bytecode::k##name: \
    Visit##name();                     \
    break;
      BYTECODE_LIST(BYTECODE_CASE)
875
#undef BYTECODE_CASE
876 877 878 879 880
    }
  }
}

void BytecodeGraphBuilder::VisitBytecodes() {
881
  BytecodeAnalysis bytecode_analysis(bytecode_array(), local_zone(),
882
                                     analyze_environment_liveness());
883
  bytecode_analysis.Analyze(osr_offset_);
884
  set_bytecode_analysis(&bytecode_analysis);
885

886
  interpreter::BytecodeArrayIterator iterator(bytecode_array());
887
  set_bytecode_iterator(&iterator);
888
  SourcePositionTableIterator source_position_iterator(
889
      handle(bytecode_array()->SourcePositionTable(), isolate()));
890

891
  if (analyze_environment_liveness() && FLAG_trace_environment_liveness) {
892
    StdoutStream of;
893 894 895
    bytecode_analysis.PrintLivenessTo(of);
  }

896 897 898 899 900
  if (!bytecode_analysis.resume_jump_targets().empty()) {
    environment()->BindGeneratorState(
        jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
  }

901 902 903 904 905 906 907
  if (bytecode_analysis.HasOsrEntryPoint()) {
    // We peel the OSR loop and any outer loop containing it except that we
    // leave the nodes corresponding to the whole outermost loop (including
    // the last copies of the loops it contains) to be generated by the normal
    // bytecode iteration below.
    AdvanceToOsrEntryAndPeelLoops(&iterator, &source_position_iterator);
  }
908

909
  bool has_one_shot_bytecode = false;
910
  for (; !iterator.done(); iterator.Advance()) {
911 912 913 914
    if (interpreter::Bytecodes::IsOneShotBytecode(
            iterator.current_bytecode())) {
      has_one_shot_bytecode = true;
    }
915
    VisitSingleBytecode(&source_position_iterator);
916
  }
917 918 919 920 921 922

  if (has_one_shot_bytecode) {
    isolate()->CountUsage(
        v8::Isolate::UseCounterFeature::kOptimizedFunctionWithOneShotBytecode);
  }

923
  set_bytecode_analysis(nullptr);
924
  set_bytecode_iterator(nullptr);
925
  DCHECK(exception_handlers_.empty());
926 927
}

928
void BytecodeGraphBuilder::VisitLdaZero() {
929 930 931 932
  Node* node = jsgraph()->ZeroConstant();
  environment()->BindAccumulator(node);
}

933
void BytecodeGraphBuilder::VisitLdaSmi() {
934
  Node* node = jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
935 936 937
  environment()->BindAccumulator(node);
}

938
void BytecodeGraphBuilder::VisitLdaConstant() {
939 940
  Node* node = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
941 942 943
  environment()->BindAccumulator(node);
}

944
void BytecodeGraphBuilder::VisitLdaUndefined() {
945 946 947 948
  Node* node = jsgraph()->UndefinedConstant();
  environment()->BindAccumulator(node);
}

949
void BytecodeGraphBuilder::VisitLdaNull() {
950 951 952 953
  Node* node = jsgraph()->NullConstant();
  environment()->BindAccumulator(node);
}

954
void BytecodeGraphBuilder::VisitLdaTheHole() {
955 956 957 958
  Node* node = jsgraph()->TheHoleConstant();
  environment()->BindAccumulator(node);
}

959
void BytecodeGraphBuilder::VisitLdaTrue() {
960 961 962 963
  Node* node = jsgraph()->TrueConstant();
  environment()->BindAccumulator(node);
}

964
void BytecodeGraphBuilder::VisitLdaFalse() {
965 966 967 968
  Node* node = jsgraph()->FalseConstant();
  environment()->BindAccumulator(node);
}

969 970 971
void BytecodeGraphBuilder::VisitLdar() {
  Node* value =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
972 973 974
  environment()->BindAccumulator(value);
}

975
void BytecodeGraphBuilder::VisitStar() {
976
  Node* value = environment()->LookupAccumulator();
977
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), value);
978 979
}

980 981 982 983
void BytecodeGraphBuilder::VisitMov() {
  Node* value =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(1), value);
984 985
}

986 987
Node* BytecodeGraphBuilder::BuildLoadGlobal(Handle<Name> name,
                                            uint32_t feedback_slot_index,
988 989
                                            TypeofMode typeof_mode) {
  VectorSlotPair feedback = CreateVectorSlotPair(feedback_slot_index);
990
  DCHECK(IsLoadGlobalICKind(feedback_vector()->GetKind(feedback.slot())));
991
  const Operator* op = javascript()->LoadGlobal(name, feedback, typeof_mode);
992
  return NewNode(op);
993 994
}

995
void BytecodeGraphBuilder::VisitLdaGlobal() {
996
  PrepareEagerCheckpoint();
997 998
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
999 1000 1001
  uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
  Node* node =
      BuildLoadGlobal(name, feedback_slot_index, TypeofMode::NOT_INSIDE_TYPEOF);
1002
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1003 1004
}

1005
void BytecodeGraphBuilder::VisitLdaGlobalInsideTypeof() {
1006
  PrepareEagerCheckpoint();
1007 1008
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
1009 1010 1011
  uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
  Node* node =
      BuildLoadGlobal(name, feedback_slot_index, TypeofMode::INSIDE_TYPEOF);
1012
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1013 1014
}

1015
void BytecodeGraphBuilder::VisitStaGlobal() {
1016
  PrepareEagerCheckpoint();
1017 1018
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)), isolate());
1019 1020
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(1));
1021 1022
  Node* value = environment()->LookupAccumulator();

1023 1024
  LanguageMode language_mode =
      feedback.vector()->GetLanguageMode(feedback.slot());
1025
  const Operator* op = javascript()->StoreGlobal(language_mode, name, feedback);
1026
  Node* node = NewNode(op, value);
1027
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1028 1029
}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
void BytecodeGraphBuilder::VisitStaInArrayLiteral() {
  PrepareEagerCheckpoint();
  Node* value = environment()->LookupAccumulator();
  Node* array =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
  const Operator* op = javascript()->StoreInArrayLiteral(feedback);

  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreKeyed(op, array, index, value, feedback.slot());
  if (lowering.IsExit()) return;

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(op, array, index, value);
  }

  environment()->RecordAfterState(node, Environment::kAttachFrameState);
}

1056
void BytecodeGraphBuilder::VisitStaDataPropertyInLiteral() {
1057 1058
  PrepareEagerCheckpoint();

1059 1060 1061 1062
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* name =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
1063 1064 1065 1066
  Node* value = environment()->LookupAccumulator();
  int flags = bytecode_iterator().GetFlagOperand(2);
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(3));
1067

1068
  const Operator* op = javascript()->StoreDataPropertyInLiteral(feedback);
1069
  Node* node = NewNode(op, object, name, value, jsgraph()->Constant(flags));
1070
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1071 1072 1073 1074 1075
}

void BytecodeGraphBuilder::VisitCollectTypeProfile() {
  PrepareEagerCheckpoint();

1076 1077
  Node* position =
      jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
1078 1079 1080 1081 1082
  Node* value = environment()->LookupAccumulator();
  Node* vector = jsgraph()->Constant(feedback_vector());

  const Operator* op = javascript()->CallRuntime(Runtime::kCollectTypeProfile);

1083
  Node* node = NewNode(op, position, value, vector);
1084
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1085 1086
}

1087
void BytecodeGraphBuilder::VisitLdaContextSlot() {
1088 1089 1090
  const Operator* op = javascript()->LoadContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1), false);
1091
  Node* node = NewNode(op);
1092 1093
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1094
  NodeProperties::ReplaceContextInput(node, context);
1095
  environment()->BindAccumulator(node);
1096 1097
}

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
void BytecodeGraphBuilder::VisitLdaImmutableContextSlot() {
  const Operator* op = javascript()->LoadContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1), true);
  Node* node = NewNode(op);
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  NodeProperties::ReplaceContextInput(node, context);
  environment()->BindAccumulator(node);
}

1109
void BytecodeGraphBuilder::VisitLdaCurrentContextSlot() {
1110 1111
  const Operator* op = javascript()->LoadContext(
      0, bytecode_iterator().GetIndexOperand(0), false);
1112
  Node* node = NewNode(op);
1113
  environment()->BindAccumulator(node);
1114 1115
}

1116 1117 1118 1119 1120 1121 1122
void BytecodeGraphBuilder::VisitLdaImmutableCurrentContextSlot() {
  const Operator* op = javascript()->LoadContext(
      0, bytecode_iterator().GetIndexOperand(0), true);
  Node* node = NewNode(op);
  environment()->BindAccumulator(node);
}

1123
void BytecodeGraphBuilder::VisitStaContextSlot() {
1124 1125 1126
  const Operator* op = javascript()->StoreContext(
      bytecode_iterator().GetUnsignedImmediateOperand(2),
      bytecode_iterator().GetIndexOperand(1));
1127 1128
  Node* value = environment()->LookupAccumulator();
  Node* node = NewNode(op, value);
1129 1130
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1131
  NodeProperties::ReplaceContextInput(node, context);
1132 1133
}

1134 1135 1136 1137
void BytecodeGraphBuilder::VisitStaCurrentContextSlot() {
  const Operator* op =
      javascript()->StoreContext(0, bytecode_iterator().GetIndexOperand(0));
  Node* value = environment()->LookupAccumulator();
1138
  NewNode(op, value);
1139 1140
}

1141
void BytecodeGraphBuilder::BuildLdaLookupSlot(TypeofMode typeof_mode) {
1142
  PrepareEagerCheckpoint();
1143 1144
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1145 1146 1147 1148 1149
  const Operator* op =
      javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                    ? Runtime::kLoadLookupSlot
                                    : Runtime::kLoadLookupSlotInsideTypeof);
  Node* value = NewNode(op, name);
1150
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
1151 1152
}

1153 1154
void BytecodeGraphBuilder::VisitLdaLookupSlot() {
  BuildLdaLookupSlot(TypeofMode::NOT_INSIDE_TYPEOF);
1155 1156
}

1157 1158
void BytecodeGraphBuilder::VisitLdaLookupSlotInsideTypeof() {
  BuildLdaLookupSlot(TypeofMode::INSIDE_TYPEOF);
1159 1160
}

1161 1162 1163
BytecodeGraphBuilder::Environment* BytecodeGraphBuilder::CheckContextExtensions(
    uint32_t depth) {
  // Output environment where the context has an extension
1164 1165
  Environment* slow_environment = nullptr;

1166 1167
  // We only need to check up to the last-but-one depth, because the an eval
  // in the same scope as the variable itself has no way of shadowing it.
1168 1169
  for (uint32_t d = 0; d < depth; d++) {
    Node* extension_slot =
1170
        NewNode(javascript()->LoadContext(d, Context::EXTENSION_INDEX, false));
1171 1172

    Node* check_no_extension =
1173 1174
        NewNode(simplified()->ReferenceEqual(), extension_slot,
                jsgraph()->TheHoleConstant());
1175 1176 1177 1178

    NewBranch(check_no_extension);

    {
1179 1180
      SubEnvironment sub_environment(this);

1181 1182 1183
      NewIfFalse();
      // If there is an extension, merge into the slow path.
      if (slow_environment == nullptr) {
1184
        slow_environment = environment();
1185 1186
        NewMerge();
      } else {
1187 1188 1189
        slow_environment->Merge(environment(),
                                bytecode_analysis()->GetInLivenessFor(
                                    bytecode_iterator().current_offset()));
1190 1191 1192
      }
    }

1193 1194 1195
    NewIfTrue();
    // Do nothing on if there is no extension, eventually falling through to
    // the fast path.
1196 1197
  }

1198 1199
  // The depth can be zero, in which case no slow-path checks are built, and
  // the slow path environment can be null.
1200
  DCHECK(depth == 0 || slow_environment != nullptr);
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

  return slow_environment;
}

void BytecodeGraphBuilder::BuildLdaLookupContextSlot(TypeofMode typeof_mode) {
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(2);

  // Check if any context in the depth has an extension.
  Environment* slow_environment = CheckContextExtensions(depth);

1211 1212 1213 1214 1215
  // Fast path, do a context load.
  {
    uint32_t slot_index = bytecode_iterator().GetIndexOperand(1);

    const Operator* op = javascript()->LoadContext(depth, slot_index, false);
1216
    environment()->BindAccumulator(NewNode(op));
1217
  }
1218

1219 1220 1221 1222 1223
  // Only build the slow path if there were any slow-path checks.
  if (slow_environment != nullptr) {
    // Add a merge to the fast environment.
    NewMerge();
    Environment* fast_environment = environment();
1224

1225 1226 1227 1228
    // Slow path, do a runtime load lookup.
    set_environment(slow_environment);
    {
      Node* name = jsgraph()->Constant(
1229
          handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1230 1231 1232 1233 1234 1235

      const Operator* op =
          javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                        ? Runtime::kLoadLookupSlot
                                        : Runtime::kLoadLookupSlotInsideTypeof);
      Node* value = NewNode(op, name);
1236
      environment()->BindAccumulator(value, Environment::kAttachFrameState);
1237
    }
1238

1239 1240 1241
    fast_environment->Merge(environment(),
                            bytecode_analysis()->GetOutLivenessFor(
                                bytecode_iterator().current_offset()));
1242
    set_environment(fast_environment);
1243
    mark_as_needing_eager_checkpoint(true);
1244
  }
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
}

void BytecodeGraphBuilder::VisitLdaLookupContextSlot() {
  BuildLdaLookupContextSlot(TypeofMode::NOT_INSIDE_TYPEOF);
}

void BytecodeGraphBuilder::VisitLdaLookupContextSlotInsideTypeof() {
  BuildLdaLookupContextSlot(TypeofMode::INSIDE_TYPEOF);
}

1255
void BytecodeGraphBuilder::BuildLdaLookupGlobalSlot(TypeofMode typeof_mode) {
1256 1257 1258 1259 1260 1261 1262
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(2);

  // Check if any context in the depth has an extension.
  Environment* slow_environment = CheckContextExtensions(depth);

  // Fast path, do a global load.
  {
1263
    PrepareEagerCheckpoint();
1264 1265 1266
    Handle<Name> name(
        Name::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
        isolate());
1267 1268
    uint32_t feedback_slot_index = bytecode_iterator().GetIndexOperand(1);
    Node* node = BuildLoadGlobal(name, feedback_slot_index, typeof_mode);
1269
    environment()->BindAccumulator(node, Environment::kAttachFrameState);
1270
  }
1271

1272 1273 1274
  // Only build the slow path if there were any slow-path checks.
  if (slow_environment != nullptr) {
    // Add a merge to the fast environment.
1275
    NewMerge();
1276
    Environment* fast_environment = environment();
1277

1278 1279 1280 1281
    // Slow path, do a runtime load lookup.
    set_environment(slow_environment);
    {
      Node* name = jsgraph()->Constant(
1282
          handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1283

1284 1285 1286 1287 1288
      const Operator* op =
          javascript()->CallRuntime(typeof_mode == TypeofMode::NOT_INSIDE_TYPEOF
                                        ? Runtime::kLoadLookupSlot
                                        : Runtime::kLoadLookupSlotInsideTypeof);
      Node* value = NewNode(op, name);
1289
      environment()->BindAccumulator(value, Environment::kAttachFrameState);
1290
    }
1291

1292 1293 1294
    fast_environment->Merge(environment(),
                            bytecode_analysis()->GetOutLivenessFor(
                                bytecode_iterator().current_offset()));
1295
    set_environment(fast_environment);
1296
    mark_as_needing_eager_checkpoint(true);
1297
  }
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
}

void BytecodeGraphBuilder::VisitLdaLookupGlobalSlot() {
  BuildLdaLookupGlobalSlot(TypeofMode::NOT_INSIDE_TYPEOF);
}

void BytecodeGraphBuilder::VisitLdaLookupGlobalSlotInsideTypeof() {
  BuildLdaLookupGlobalSlot(TypeofMode::INSIDE_TYPEOF);
}

1308
void BytecodeGraphBuilder::VisitStaLookupSlot() {
1309
  PrepareEagerCheckpoint();
1310
  Node* value = environment()->LookupAccumulator();
1311 1312
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
1313 1314 1315 1316 1317 1318 1319 1320 1321
  int bytecode_flags = bytecode_iterator().GetFlagOperand(1);
  LanguageMode language_mode = static_cast<LanguageMode>(
      interpreter::StoreLookupSlotFlags::LanguageModeBit::decode(
          bytecode_flags));
  LookupHoistingMode lookup_hoisting_mode = static_cast<LookupHoistingMode>(
      interpreter::StoreLookupSlotFlags::LookupHoistingModeBit::decode(
          bytecode_flags));
  DCHECK_IMPLIES(lookup_hoisting_mode == LookupHoistingMode::kLegacySloppy,
                 is_sloppy(language_mode));
1322
  const Operator* op = javascript()->CallRuntime(
1323 1324 1325 1326 1327
      is_strict(language_mode)
          ? Runtime::kStoreLookupSlot_Strict
          : lookup_hoisting_mode == LookupHoistingMode::kLegacySloppy
                ? Runtime::kStoreLookupSlot_SloppyHoisting
                : Runtime::kStoreLookupSlot_Sloppy);
1328
  Node* store = NewNode(op, name, value);
1329
  environment()->BindAccumulator(store, Environment::kAttachFrameState);
1330 1331
}

1332 1333
void BytecodeGraphBuilder::VisitLdaNamedProperty() {
  PrepareEagerCheckpoint();
1334 1335
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1336 1337
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
1338 1339
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1340
  const Operator* op = javascript()->LoadNamed(name, feedback);
1341

1342 1343 1344 1345
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedLoadNamed(op, object, feedback.slot());
  if (lowering.IsExit()) return;

1346
  Node* node = nullptr;
1347 1348
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1349
  } else {
1350
    DCHECK(!lowering.Changed());
1351 1352
    node = NewNode(op, object);
  }
1353
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1354
}
1355

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
void BytecodeGraphBuilder::VisitLdaNamedPropertyNoFeedback() {
  PrepareEagerCheckpoint();
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
  const Operator* op = javascript()->LoadNamed(name, VectorSlotPair());
  Node* node = NewNode(op, object);
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

1367
void BytecodeGraphBuilder::VisitLdaKeyedProperty() {
1368
  PrepareEagerCheckpoint();
1369
  Node* key = environment()->LookupAccumulator();
1370 1371 1372 1373
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(1));
1374
  const Operator* op = javascript()->LoadProperty(feedback);
1375

1376 1377 1378 1379
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedLoadKeyed(op, object, key, feedback.slot());
  if (lowering.IsExit()) return;

1380
  Node* node = nullptr;
1381 1382
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1383
  } else {
1384
    DCHECK(!lowering.Changed());
1385 1386
    node = NewNode(op, object, key);
  }
1387
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1388 1389
}

1390
void BytecodeGraphBuilder::BuildNamedStore(StoreMode store_mode) {
1391
  PrepareEagerCheckpoint();
1392
  Node* value = environment()->LookupAccumulator();
1393 1394
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1395 1396
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
1397 1398
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1399

1400 1401 1402 1403 1404 1405
  const Operator* op;
  if (store_mode == StoreMode::kOwn) {
    DCHECK_EQ(FeedbackSlotKind::kStoreOwnNamed,
              feedback.vector()->GetKind(feedback.slot()));
    op = javascript()->StoreNamedOwn(name, feedback);
  } else {
1406
    DCHECK_EQ(StoreMode::kNormal, store_mode);
1407 1408
    LanguageMode language_mode =
        feedback.vector()->GetLanguageMode(feedback.slot());
1409 1410
    op = javascript()->StoreNamed(language_mode, name, feedback);
  }
1411

1412 1413 1414 1415
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreNamed(op, object, value, feedback.slot());
  if (lowering.IsExit()) return;

1416
  Node* node = nullptr;
1417 1418
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1419
  } else {
1420
    DCHECK(!lowering.Changed());
1421 1422
    node = NewNode(op, object, value);
  }
1423
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1424 1425
}

1426 1427
void BytecodeGraphBuilder::VisitStaNamedProperty() {
  BuildNamedStore(StoreMode::kNormal);
1428 1429
}

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
void BytecodeGraphBuilder::VisitStaNamedPropertyNoFeedback() {
  PrepareEagerCheckpoint();
  Node* value = environment()->LookupAccumulator();
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Handle<Name> name(
      Name::cast(bytecode_iterator().GetConstantForIndexOperand(1)), isolate());
  LanguageMode language_mode =
      static_cast<LanguageMode>(bytecode_iterator().GetFlagOperand(2));
  const Operator* op =
      javascript()->StoreNamed(language_mode, name, VectorSlotPair());
  Node* node = NewNode(op, object, value);
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
}

1445
void BytecodeGraphBuilder::VisitStaNamedOwnProperty() {
1446
  BuildNamedStore(StoreMode::kOwn);
1447 1448
}

1449
void BytecodeGraphBuilder::VisitStaKeyedProperty() {
1450
  PrepareEagerCheckpoint();
1451
  Node* value = environment()->LookupAccumulator();
1452 1453 1454 1455 1456 1457
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* key =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  VectorSlotPair feedback =
      CreateVectorSlotPair(bytecode_iterator().GetIndexOperand(2));
1458 1459
  LanguageMode language_mode =
      feedback.vector()->GetLanguageMode(feedback.slot());
1460
  const Operator* op = javascript()->StoreProperty(language_mode, feedback);
1461

1462 1463 1464 1465
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedStoreKeyed(op, object, key, value, feedback.slot());
  if (lowering.IsExit()) return;

1466
  Node* node = nullptr;
1467 1468
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1469
  } else {
1470
    DCHECK(!lowering.Changed());
1471 1472 1473
    node = NewNode(op, object, key, value);
  }

1474
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
1475 1476
}

1477
void BytecodeGraphBuilder::VisitLdaModuleVariable() {
1478 1479
  int32_t cell_index = bytecode_iterator().GetImmediateOperand(0);
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(1);
1480 1481
  Node* module =
      NewNode(javascript()->LoadContext(depth, Context::EXTENSION_INDEX, true));
1482 1483
  Node* value = NewNode(javascript()->LoadModule(cell_index), module);
  environment()->BindAccumulator(value);
1484 1485 1486
}

void BytecodeGraphBuilder::VisitStaModuleVariable() {
1487 1488
  int32_t cell_index = bytecode_iterator().GetImmediateOperand(0);
  uint32_t depth = bytecode_iterator().GetUnsignedImmediateOperand(1);
1489 1490
  Node* module =
      NewNode(javascript()->LoadContext(depth, Context::EXTENSION_INDEX, true));
1491
  Node* value = environment()->LookupAccumulator();
1492
  NewNode(javascript()->StoreModule(cell_index), module, value);
1493 1494
}

1495
void BytecodeGraphBuilder::VisitPushContext() {
1496
  Node* new_context = environment()->LookupAccumulator();
1497
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0),
1498 1499
                              environment()->Context());
  environment()->SetContext(new_context);
1500 1501
}

1502 1503 1504
void BytecodeGraphBuilder::VisitPopContext() {
  Node* context =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1505
  environment()->SetContext(context);
1506 1507
}

1508
void BytecodeGraphBuilder::VisitCreateClosure() {
1509 1510 1511 1512
  Handle<SharedFunctionInfo> shared_info(
      SharedFunctionInfo::cast(
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1513 1514
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
  FeedbackNexus nexus(feedback_vector(), slot);
1515
  PretenureFlag tenured =
1516
      interpreter::CreateClosureFlags::PretenuredBit::decode(
1517
          bytecode_iterator().GetFlagOperand(2))
1518 1519
          ? TENURED
          : NOT_TENURED;
1520 1521
  const Operator* op = javascript()->CreateClosure(
      shared_info, nexus.GetFeedbackCell(),
1522 1523
      handle(jsgraph()->isolate()->builtins()->builtin(Builtins::kCompileLazy),
             isolate()),
1524
      tenured);
1525 1526 1527 1528
  Node* closure = NewNode(op);
  environment()->BindAccumulator(closure);
}

1529
void BytecodeGraphBuilder::VisitCreateBlockContext() {
1530 1531 1532
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1533 1534

  const Operator* op = javascript()->CreateBlockContext(scope_info);
1535
  Node* context = NewNode(op);
1536 1537 1538
  environment()->BindAccumulator(context);
}

1539
void BytecodeGraphBuilder::VisitCreateFunctionContext() {
1540 1541 1542
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1543
  uint32_t slots = bytecode_iterator().GetUnsignedImmediateOperand(1);
1544
  const Operator* op =
1545 1546
      javascript()->CreateFunctionContext(scope_info, slots, FUNCTION_SCOPE);
  Node* context = NewNode(op);
1547 1548 1549 1550
  environment()->BindAccumulator(context);
}

void BytecodeGraphBuilder::VisitCreateEvalContext() {
1551 1552 1553
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1554 1555 1556 1557
  uint32_t slots = bytecode_iterator().GetUnsignedImmediateOperand(1);
  const Operator* op =
      javascript()->CreateFunctionContext(scope_info, slots, EVAL_SCOPE);
  Node* context = NewNode(op);
1558 1559 1560
  environment()->BindAccumulator(context);
}

1561 1562 1563
void BytecodeGraphBuilder::VisitCreateCatchContext() {
  interpreter::Register reg = bytecode_iterator().GetRegisterOperand(0);
  Node* exception = environment()->LookupRegister(reg);
1564 1565 1566
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(1)),
      isolate());
1567

1568
  const Operator* op = javascript()->CreateCatchContext(scope_info);
1569
  Node* context = NewNode(op, exception);
1570 1571 1572
  environment()->BindAccumulator(context);
}

1573 1574 1575
void BytecodeGraphBuilder::VisitCreateWithContext() {
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1576 1577 1578
  Handle<ScopeInfo> scope_info(
      ScopeInfo::cast(bytecode_iterator().GetConstantForIndexOperand(1)),
      isolate());
1579

1580
  const Operator* op = javascript()->CreateWithContext(scope_info);
1581
  Node* context = NewNode(op, object);
1582 1583 1584
  environment()->BindAccumulator(context);
}

1585 1586
void BytecodeGraphBuilder::BuildCreateArguments(CreateArgumentsType type) {
  const Operator* op = javascript()->CreateArguments(type);
1587
  Node* object = NewNode(op, GetFunctionClosure());
1588
  environment()->BindAccumulator(object, Environment::kAttachFrameState);
1589 1590
}

1591
void BytecodeGraphBuilder::VisitCreateMappedArguments() {
1592
  BuildCreateArguments(CreateArgumentsType::kMappedArguments);
1593 1594
}

1595
void BytecodeGraphBuilder::VisitCreateUnmappedArguments() {
1596
  BuildCreateArguments(CreateArgumentsType::kUnmappedArguments);
1597 1598
}

1599 1600
void BytecodeGraphBuilder::VisitCreateRestParameter() {
  BuildCreateArguments(CreateArgumentsType::kRestParameter);
1601 1602
}

1603
void BytecodeGraphBuilder::VisitCreateRegExpLiteral() {
1604 1605 1606
  Handle<String> constant_pattern(
      String::cast(bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1607 1608
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
1609
  int literal_flags = bytecode_iterator().GetFlagOperand(2);
1610 1611
  Node* literal = NewNode(
      javascript()->CreateLiteralRegExp(constant_pattern, pair, literal_flags));
1612
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
1613 1614
}

1615
void BytecodeGraphBuilder::VisitCreateArrayLiteral() {
1616 1617
  Handle<ArrayBoilerplateDescription> array_boilerplate_description(
      ArrayBoilerplateDescription::cast(
1618 1619
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1620 1621
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
1622 1623 1624
  int bytecode_flags = bytecode_iterator().GetFlagOperand(2);
  int literal_flags =
      interpreter::CreateArrayLiteralFlags::FlagsBits::decode(bytecode_flags);
1625 1626 1627 1628 1629
  // Disable allocation site mementos. Only unoptimized code will collect
  // feedback about allocation site. Once the code is optimized we expect the
  // data to converge. So, we disable allocation site mementos in optimized
  // code. We can revisit this when we have data to the contrary.
  literal_flags |= ArrayLiteral::kDisableMementos;
1630 1631
  // TODO(mstarzinger): Thread through number of elements. The below number is
  // only an estimate and does not match {ArrayLiteral::values::length}.
1632 1633
  int number_of_elements =
      array_boilerplate_description->constant_elements()->length();
1634
  Node* literal = NewNode(javascript()->CreateLiteralArray(
1635
      array_boilerplate_description, pair, literal_flags, number_of_elements));
1636
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
1637 1638
}

1639
void BytecodeGraphBuilder::VisitCreateEmptyArrayLiteral() {
1640 1641 1642
  int const slot_id = bytecode_iterator().GetIndexOperand(0);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
  Node* literal = NewNode(javascript()->CreateEmptyLiteralArray(pair));
1643 1644 1645
  environment()->BindAccumulator(literal);
}

1646 1647 1648 1649 1650 1651
void BytecodeGraphBuilder::VisitCreateArrayFromIterable() {
  Node* iterable = NewNode(javascript()->CreateArrayFromIterable(),
                           environment()->LookupAccumulator());
  environment()->BindAccumulator(iterable, Environment::kAttachFrameState);
}

1652
void BytecodeGraphBuilder::VisitCreateObjectLiteral() {
1653 1654
  Handle<ObjectBoilerplateDescription> constant_properties(
      ObjectBoilerplateDescription::cast(
1655 1656
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1657 1658
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
  VectorSlotPair pair = CreateVectorSlotPair(slot_id);
1659 1660 1661
  int bytecode_flags = bytecode_iterator().GetFlagOperand(2);
  int literal_flags =
      interpreter::CreateObjectLiteralFlags::FlagsBits::decode(bytecode_flags);
1662 1663
  // TODO(mstarzinger): Thread through number of properties. The below number is
  // only an estimate and does not match {ObjectLiteral::properties_count}.
1664
  int number_of_properties = constant_properties->size();
1665 1666
  Node* literal = NewNode(javascript()->CreateLiteralObject(
      constant_properties, pair, literal_flags, number_of_properties));
1667
  environment()->BindAccumulator(literal, Environment::kAttachFrameState);
1668 1669
}

1670
void BytecodeGraphBuilder::VisitCreateEmptyObjectLiteral() {
1671 1672
  Node* literal =
      NewNode(javascript()->CreateEmptyLiteralObject(), GetFunctionClosure());
1673 1674 1675
  environment()->BindAccumulator(literal);
}

1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
void BytecodeGraphBuilder::VisitCloneObject() {
  PrepareEagerCheckpoint();
  Node* source =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  int flags = bytecode_iterator().GetFlagOperand(1);
  int slot = bytecode_iterator().GetIndexOperand(2);
  const Operator* op =
      javascript()->CloneObject(CreateVectorSlotPair(slot), flags);
  Node* value = NewNode(op, source);
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
}

1688
void BytecodeGraphBuilder::VisitGetTemplateObject() {
1689 1690 1691 1692
  Handle<TemplateObjectDescription> description(
      TemplateObjectDescription::cast(
          bytecode_iterator().GetConstantForIndexOperand(0)),
      isolate());
1693 1694 1695 1696
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
  FeedbackNexus nexus(feedback_vector(), slot);

  Handle<JSArray> cached_value;
1697
  if (nexus.GetFeedback() == MaybeObject::FromSmi(Smi::zero())) {
1698 1699 1700
    // It's not observable when the template object is created, so we
    // can just create it eagerly during graph building and bake in
    // the JSArray constant here.
1701 1702
    cached_value = TemplateObjectDescription::GetTemplateObject(
        isolate(), native_context(), description, shared_info(), slot.ToInt());
1703 1704
    nexus.vector()->Set(slot, *cached_value);
  } else {
1705 1706 1707
    cached_value =
        handle(JSArray::cast(nexus.GetFeedback()->GetHeapObjectAssumeStrong()),
               isolate());
1708 1709 1710
  }

  Node* template_object = jsgraph()->HeapConstant(cached_value);
1711 1712 1713
  environment()->BindAccumulator(template_object);
}

1714
Node* const* BytecodeGraphBuilder::GetCallArgumentsFromRegisters(
1715 1716 1717 1718 1719 1720 1721 1722
    Node* callee, Node* receiver, interpreter::Register first_arg,
    int arg_count) {
  // The arity of the Call node -- includes the callee, receiver and function
  // arguments.
  int arity = 2 + arg_count;

  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));

1723
  all[0] = callee;
1724 1725 1726 1727 1728 1729 1730
  all[1] = receiver;

  // The function arguments are in consecutive registers.
  int arg_base = first_arg.index();
  for (int i = 0; i < arg_count; ++i) {
    all[2 + i] =
        environment()->LookupRegister(interpreter::Register(arg_base + i));
1731
  }
1732

1733 1734 1735 1736 1737
  return all;
}

Node* BytecodeGraphBuilder::ProcessCallArguments(const Operator* call_op,
                                                 Node* const* args,
1738 1739
                                                 int arg_count) {
  return MakeNode(call_op, arg_count, args, false);
1740 1741 1742 1743 1744
}

Node* BytecodeGraphBuilder::ProcessCallArguments(const Operator* call_op,
                                                 Node* callee,
                                                 interpreter::Register receiver,
1745 1746 1747 1748 1749 1750 1751
                                                 size_t reg_count) {
  Node* receiver_node = environment()->LookupRegister(receiver);
  // The receiver is followed by the arguments in the consecutive registers.
  DCHECK_GE(reg_count, 1);
  interpreter::Register first_arg = interpreter::Register(receiver.index() + 1);
  int arg_count = static_cast<int>(reg_count) - 1;

1752 1753
  Node* const* call_args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                         first_arg, arg_count);
1754
  return ProcessCallArguments(call_op, call_args, 2 + arg_count);
1755 1756
}

1757
void BytecodeGraphBuilder::BuildCall(ConvertReceiverMode receiver_mode,
1758 1759
                                     Node* const* args, size_t arg_count,
                                     int slot_id) {
1760 1761 1762
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            receiver_mode);
1763
  PrepareEagerCheckpoint();
1764

1765
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
1766

1767
  CallFrequency frequency = ComputeCallFrequency(slot_id);
1768
  const Operator* op =
1769 1770
      javascript()->Call(arg_count, frequency, feedback, receiver_mode,
                         GetSpeculationMode(slot_id));
1771 1772 1773 1774
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedCall(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

1775
  Node* node = nullptr;
1776 1777
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1778
  } else {
1779
    DCHECK(!lowering.Changed());
1780 1781 1782
    node = ProcessCallArguments(op, args, static_cast<int>(arg_count));
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1783 1784
}

1785 1786 1787 1788
Node* const* BytecodeGraphBuilder::ProcessCallVarArgs(
    ConvertReceiverMode receiver_mode, Node* callee,
    interpreter::Register first_reg, int arg_count) {
  DCHECK_GE(arg_count, 0);
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
  Node* receiver_node;
  interpreter::Register first_arg;

  if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
    // The receiver is implicit (and undefined), the arguments are in
    // consecutive registers.
    receiver_node = jsgraph()->UndefinedConstant();
    first_arg = first_reg;
  } else {
    // The receiver is the first register, followed by the arguments in the
    // consecutive registers.
    receiver_node = environment()->LookupRegister(first_reg);
    first_arg = interpreter::Register(first_reg.index() + 1);
  }

1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
  Node* const* call_args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                         first_arg, arg_count);
  return call_args;
}

void BytecodeGraphBuilder::BuildCallVarArgs(ConvertReceiverMode receiver_mode) {
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            receiver_mode);
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
  int const slot_id = bytecode_iterator().GetIndexOperand(3);

  int arg_count = receiver_mode == ConvertReceiverMode::kNullOrUndefined
                      ? static_cast<int>(reg_count)
                      : static_cast<int>(reg_count) - 1;
1822
  Node* const* call_args =
1823
      ProcessCallVarArgs(receiver_mode, callee, first_reg, arg_count);
1824 1825
  BuildCall(receiver_mode, call_args, static_cast<size_t>(2 + arg_count),
            slot_id);
1826 1827
}

1828
void BytecodeGraphBuilder::VisitCallAnyReceiver() {
1829
  BuildCallVarArgs(ConvertReceiverMode::kAny);
1830 1831
}

1832
void BytecodeGraphBuilder::VisitCallNoFeedback() {
1833 1834 1835 1836
  DCHECK_EQ(interpreter::Bytecodes::GetReceiverMode(
                bytecode_iterator().current_bytecode()),
            ConvertReceiverMode::kAny);

1837
  PrepareEagerCheckpoint();
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));

  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);

  // The receiver is the first register, followed by the arguments in the
  // consecutive registers.
  int arg_count = static_cast<int>(reg_count) - 1;
  // The arity of the Call node -- includes the callee, receiver and function
  // arguments.
  int arity = 2 + arg_count;

  // Setting call frequency to a value less than min_inlining frequency to
  // prevent inlining of one-shot call node.
  DCHECK(CallFrequency::kNoFeedbackCallFrequency < FLAG_min_inlining_frequency);
  const Operator* call = javascript()->Call(
      arity, CallFrequency(CallFrequency::kNoFeedbackCallFrequency));
  Node* const* call_args = ProcessCallVarArgs(ConvertReceiverMode::kAny, callee,
                                              first_reg, arg_count);
  Node* value = ProcessCallArguments(call, call_args, arity);
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
1860 1861
}

1862
void BytecodeGraphBuilder::VisitCallProperty() {
1863
  BuildCallVarArgs(ConvertReceiverMode::kNotNullOrUndefined);
1864 1865 1866
}

void BytecodeGraphBuilder::VisitCallProperty0() {
1867 1868 1869 1870 1871
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int const slot_id = bytecode_iterator().GetIndexOperand(2);
1872 1873
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined, {callee, receiver},
            slot_id);
1874 1875
}

1876
void BytecodeGraphBuilder::VisitCallProperty1() {
1877 1878 1879 1880 1881 1882 1883
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  Node* arg0 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
1884 1885
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined, {callee, receiver, arg0},
            slot_id);
1886 1887
}

1888
void BytecodeGraphBuilder::VisitCallProperty2() {
1889 1890 1891 1892 1893 1894 1895 1896 1897
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  Node* arg0 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  Node* arg1 =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(3));
  int const slot_id = bytecode_iterator().GetIndexOperand(4);
1898
  BuildCall(ConvertReceiverMode::kNotNullOrUndefined,
1899 1900 1901
            {callee, receiver, arg0, arg1}, slot_id);
}

1902
void BytecodeGraphBuilder::VisitCallUndefinedReceiver() {
1903
  BuildCallVarArgs(ConvertReceiverMode::kNullOrUndefined);
1904 1905
}

1906
void BytecodeGraphBuilder::VisitCallUndefinedReceiver0() {
1907 1908
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1909 1910
  Node* receiver = jsgraph()->UndefinedConstant();
  int const slot_id = bytecode_iterator().GetIndexOperand(1);
1911
  BuildCall(ConvertReceiverMode::kNullOrUndefined, {callee, receiver}, slot_id);
1912 1913
}

1914
void BytecodeGraphBuilder::VisitCallUndefinedReceiver1() {
1915 1916
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1917
  Node* receiver = jsgraph()->UndefinedConstant();
1918
  Node* arg0 =
1919 1920
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int const slot_id = bytecode_iterator().GetIndexOperand(2);
1921 1922
  BuildCall(ConvertReceiverMode::kNullOrUndefined, {callee, receiver, arg0},
            slot_id);
1923 1924
}

1925
void BytecodeGraphBuilder::VisitCallUndefinedReceiver2() {
1926 1927
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
1928
  Node* receiver = jsgraph()->UndefinedConstant();
1929
  Node* arg0 =
1930
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
1931
  Node* arg1 =
1932 1933
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(2));
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
1934
  BuildCall(ConvertReceiverMode::kNullOrUndefined,
1935
            {callee, receiver, arg0, arg1}, slot_id);
1936 1937
}

1938 1939
void BytecodeGraphBuilder::VisitCallWithSpread() {
  PrepareEagerCheckpoint();
1940 1941 1942
  Node* callee =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
1943
  Node* receiver_node = environment()->LookupRegister(receiver);
1944
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
1945 1946
  interpreter::Register first_arg = interpreter::Register(receiver.index() + 1);
  int arg_count = static_cast<int>(reg_count) - 1;
1947 1948
  Node* const* args = GetCallArgumentsFromRegisters(callee, receiver_node,
                                                    first_arg, arg_count);
1949 1950
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
1951

1952 1953 1954
  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->CallWithSpread(
      static_cast<int>(reg_count + 1), frequency, feedback);
1955 1956 1957 1958 1959

  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedCall(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

1960
  Node* node = nullptr;
1961 1962
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
1963
  } else {
1964
    DCHECK(!lowering.Changed());
1965 1966 1967
    node = ProcessCallArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
1968 1969
}

1970
void BytecodeGraphBuilder::VisitCallJSRuntime() {
1971
  PrepareEagerCheckpoint();
1972 1973
  Node* callee = BuildLoadNativeContextField(
      bytecode_iterator().GetNativeContextIndexOperand(0));
1974
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
1975
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
1976
  int arg_count = static_cast<int>(reg_count);
1977

1978 1979 1980 1981
  const Operator* call = javascript()->Call(2 + arg_count);
  Node* const* call_args = ProcessCallVarArgs(
      ConvertReceiverMode::kNullOrUndefined, callee, first_reg, arg_count);
  Node* value = ProcessCallArguments(call, call_args, 2 + arg_count);
1982
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
1983 1984
}

1985
Node* BytecodeGraphBuilder::ProcessCallRuntimeArguments(
1986 1987 1988 1989 1990 1991 1992 1993
    const Operator* call_runtime_op, interpreter::Register receiver,
    size_t reg_count) {
  int arg_count = static_cast<int>(reg_count);
  // arity is args.
  int arity = arg_count;
  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));
  int first_arg_index = receiver.index();
  for (int i = 0; i < static_cast<int>(reg_count); ++i) {
1994 1995 1996
    all[i] = environment()->LookupRegister(
        interpreter::Register(first_arg_index + i));
  }
1997
  Node* value = MakeNode(call_runtime_op, arity, all, false);
1998 1999 2000
  return value;
}

2001
void BytecodeGraphBuilder::VisitCallRuntime() {
2002
  PrepareEagerCheckpoint();
2003
  Runtime::FunctionId function_id = bytecode_iterator().GetRuntimeIdOperand(0);
2004 2005
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2006 2007

  // Create node to perform the runtime call.
2008
  const Operator* call = javascript()->CallRuntime(function_id, reg_count);
2009
  Node* value = ProcessCallRuntimeArguments(call, receiver, reg_count);
2010
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2011 2012 2013

  // Connect to the end if {function_id} is non-returning.
  if (Runtime::IsNonReturning(function_id)) {
2014
    // TODO(7099): Investigate if we need LoopExit node here.
2015 2016 2017
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }
2018 2019
}

2020
void BytecodeGraphBuilder::VisitCallRuntimeForPair() {
2021
  PrepareEagerCheckpoint();
2022
  Runtime::FunctionId functionId = bytecode_iterator().GetRuntimeIdOperand(0);
2023 2024
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2025 2026
  interpreter::Register first_return =
      bytecode_iterator().GetRegisterOperand(3);
2027 2028

  // Create node to perform the runtime call.
2029 2030
  const Operator* call = javascript()->CallRuntime(functionId, reg_count);
  Node* return_pair = ProcessCallRuntimeArguments(call, receiver, reg_count);
2031 2032
  environment()->BindRegistersToProjections(first_return, return_pair,
                                            Environment::kAttachFrameState);
2033 2034
}

2035 2036 2037
Node* const* BytecodeGraphBuilder::GetConstructArgumentsFromRegister(
    Node* target, Node* new_target, interpreter::Register first_arg,
    int arg_count) {
2038 2039 2040
  // arity is args + callee and new target.
  int arity = arg_count + 2;
  Node** all = local_zone()->NewArray<Node*>(static_cast<size_t>(arity));
2041 2042
  all[0] = target;
  int first_arg_index = first_arg.index();
2043 2044 2045
  for (int i = 0; i < arg_count; ++i) {
    all[1 + i] = environment()->LookupRegister(
        interpreter::Register(first_arg_index + i));
2046 2047
  }
  all[arity - 1] = new_target;
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
  return all;
}

Node* BytecodeGraphBuilder::ProcessConstructArguments(const Operator* op,
                                                      Node* const* args,
                                                      int arg_count) {
  return MakeNode(op, arg_count, args, false);
}

void BytecodeGraphBuilder::VisitConstruct() {
  PrepareEagerCheckpoint();
  interpreter::Register callee_reg = bytecode_iterator().GetRegisterOperand(0);
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);

  Node* new_target = environment()->LookupAccumulator();
  Node* callee = environment()->LookupRegister(callee_reg);

  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->Construct(
      static_cast<uint32_t>(reg_count + 2), frequency, feedback);
  int arg_count = static_cast<int>(reg_count);
  Node* const* args = GetConstructArgumentsFromRegister(callee, new_target,
                                                        first_reg, arg_count);
2074 2075 2076 2077
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedConstruct(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2078
  Node* node = nullptr;
2079 2080
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2081
  } else {
2082
    DCHECK(!lowering.Changed());
2083 2084 2085
    node = ProcessConstructArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2086 2087
}

2088
void BytecodeGraphBuilder::VisitConstructWithSpread() {
2089
  PrepareEagerCheckpoint();
2090
  interpreter::Register callee_reg = bytecode_iterator().GetRegisterOperand(0);
2091
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
2092
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2093 2094
  int const slot_id = bytecode_iterator().GetIndexOperand(3);
  VectorSlotPair feedback = CreateVectorSlotPair(slot_id);
2095 2096 2097

  Node* new_target = environment()->LookupAccumulator();
  Node* callee = environment()->LookupRegister(callee_reg);
2098

2099 2100 2101
  CallFrequency frequency = ComputeCallFrequency(slot_id);
  const Operator* op = javascript()->ConstructWithSpread(
      static_cast<uint32_t>(reg_count + 2), frequency, feedback);
2102 2103 2104
  int arg_count = static_cast<int>(reg_count);
  Node* const* args = GetConstructArgumentsFromRegister(callee, new_target,
                                                        first_reg, arg_count);
2105 2106 2107 2108
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedConstruct(
      op, args, static_cast<int>(arg_count), feedback.slot());
  if (lowering.IsExit()) return;

2109
  Node* node = nullptr;
2110 2111
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2112
  } else {
2113
    DCHECK(!lowering.Changed());
2114 2115 2116
    node = ProcessConstructArguments(op, args, 2 + arg_count);
  }
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2117 2118
}

2119
void BytecodeGraphBuilder::VisitInvokeIntrinsic() {
2120
  PrepareEagerCheckpoint();
2121
  Runtime::FunctionId functionId = bytecode_iterator().GetIntrinsicIdOperand(0);
2122 2123
  interpreter::Register receiver = bytecode_iterator().GetRegisterOperand(1);
  size_t reg_count = bytecode_iterator().GetRegisterCountOperand(2);
2124 2125 2126

  // Create node to perform the runtime call. Turbofan will take care of the
  // lowering.
2127 2128
  const Operator* call = javascript()->CallRuntime(functionId, reg_count);
  Node* value = ProcessCallRuntimeArguments(call, receiver, reg_count);
2129
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
2130 2131
}

2132
void BytecodeGraphBuilder::VisitThrow() {
2133
  BuildLoopExitsForFunctionExit(bytecode_analysis()->GetInLivenessFor(
2134
      bytecode_iterator().current_offset()));
2135
  Node* value = environment()->LookupAccumulator();
2136
  Node* call = NewNode(javascript()->CallRuntime(Runtime::kThrow), value);
2137
  environment()->BindAccumulator(call, Environment::kAttachFrameState);
2138
  Node* control = NewNode(common()->Throw());
2139
  MergeControlToLeaveFunction(control);
2140 2141
}

2142
void BytecodeGraphBuilder::VisitAbort() {
2143
  BuildLoopExitsForFunctionExit(bytecode_analysis()->GetInLivenessFor(
2144
      bytecode_iterator().current_offset()));
2145 2146
  AbortReason reason =
      static_cast<AbortReason>(bytecode_iterator().GetIndexOperand(0));
2147 2148 2149 2150 2151
  NewNode(simplified()->RuntimeAbort(reason));
  Node* control = NewNode(common()->Throw());
  MergeControlToLeaveFunction(control);
}

2152
void BytecodeGraphBuilder::VisitReThrow() {
2153
  BuildLoopExitsForFunctionExit(bytecode_analysis()->GetInLivenessFor(
2154
      bytecode_iterator().current_offset()));
2155
  Node* value = environment()->LookupAccumulator();
2156 2157
  NewNode(javascript()->CallRuntime(Runtime::kReThrow), value);
  Node* control = NewNode(common()->Throw());
2158
  MergeControlToLeaveFunction(control);
2159 2160
}

2161 2162 2163 2164 2165 2166 2167 2168
void BytecodeGraphBuilder::BuildHoleCheckAndThrow(
    Node* condition, Runtime::FunctionId runtime_id, Node* name) {
  Node* accumulator = environment()->LookupAccumulator();
  NewBranch(condition, BranchHint::kFalse);
  {
    SubEnvironment sub_environment(this);

    NewIfTrue();
2169 2170
    BuildLoopExitsForFunctionExit(bytecode_analysis()->GetInLivenessFor(
        bytecode_iterator().current_offset()));
2171 2172
    Node* node;
    const Operator* op = javascript()->CallRuntime(runtime_id);
2173
    if (runtime_id == Runtime::kThrowAccessedUninitializedVariable) {
2174
      DCHECK_NOT_NULL(name);
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
      node = NewNode(op, name);
    } else {
      DCHECK(runtime_id == Runtime::kThrowSuperAlreadyCalledError ||
             runtime_id == Runtime::kThrowSuperNotCalled);
      node = NewNode(op);
    }
    environment()->RecordAfterState(node, Environment::kAttachFrameState);
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }
  NewIfFalse();
  environment()->BindAccumulator(accumulator);
}

void BytecodeGraphBuilder::VisitThrowReferenceErrorIfHole() {
2190 2191 2192
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
2193 2194
  Node* name = jsgraph()->Constant(
      handle(bytecode_iterator().GetConstantForIndexOperand(0), isolate()));
2195 2196
  BuildHoleCheckAndThrow(check_for_hole,
                         Runtime::kThrowAccessedUninitializedVariable, name);
2197 2198 2199
}

void BytecodeGraphBuilder::VisitThrowSuperNotCalledIfHole() {
2200 2201 2202 2203
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
  BuildHoleCheckAndThrow(check_for_hole, Runtime::kThrowSuperNotCalled);
2204 2205 2206
}

void BytecodeGraphBuilder::VisitThrowSuperAlreadyCalledIfNotHole() {
2207 2208 2209 2210 2211 2212 2213
  Node* accumulator = environment()->LookupAccumulator();
  Node* check_for_hole = NewNode(simplified()->ReferenceEqual(), accumulator,
                                 jsgraph()->TheHoleConstant());
  Node* check_for_not_hole =
      NewNode(simplified()->BooleanNot(), check_for_hole);
  BuildHoleCheckAndThrow(check_for_not_hole,
                         Runtime::kThrowSuperAlreadyCalledError);
2214 2215
}

2216 2217 2218 2219
void BytecodeGraphBuilder::BuildUnaryOp(const Operator* op) {
  PrepareEagerCheckpoint();
  Node* operand = environment()->LookupAccumulator();

2220 2221
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kUnaryOperationHintIndex);
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedUnaryOp(op, operand, slot);
  if (lowering.IsExit()) return;

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(op, operand);
  }

  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

2237
void BytecodeGraphBuilder::BuildBinaryOp(const Operator* op) {
2238
  PrepareEagerCheckpoint();
2239 2240
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2241
  Node* right = environment()->LookupAccumulator();
2242

2243 2244
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kBinaryOperationHintIndex);
2245 2246
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2247
  if (lowering.IsExit()) return;
2248 2249 2250 2251

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2252
  } else {
2253
    DCHECK(!lowering.Changed());
2254 2255 2256
    node = NewNode(op, left, right);
  }

2257
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2258 2259
}

2260 2261
// Helper function to create binary operation hint from the recorded type
// feedback.
2262 2263
BinaryOperationHint BytecodeGraphBuilder::GetBinaryOperationHint(
    int operand_index) {
2264 2265
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(operand_index);
  FeedbackNexus nexus(feedback_vector(), slot);
2266
  return nexus.GetBinaryOperationFeedback();
2267 2268
}

2269 2270 2271
// Helper function to create compare operation hint from the recorded type
// feedback.
CompareOperationHint BytecodeGraphBuilder::GetCompareOperationHint() {
2272 2273
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
  FeedbackNexus nexus(feedback_vector(), slot);
2274
  return nexus.GetCompareOperationFeedback();
2275 2276
}

2277 2278
// Helper function to create for-in mode from the recorded type feedback.
ForInMode BytecodeGraphBuilder::GetForInMode(int operand_index) {
2279 2280
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(operand_index);
  FeedbackNexus nexus(feedback_vector(), slot);
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
  switch (nexus.GetForInFeedback()) {
    case ForInHint::kNone:
    case ForInHint::kEnumCacheKeysAndIndices:
      return ForInMode::kUseEnumCacheKeysAndIndices;
    case ForInHint::kEnumCacheKeys:
      return ForInMode::kUseEnumCacheKeys;
    case ForInHint::kAny:
      return ForInMode::kGeneric;
  }
  UNREACHABLE();
}

2293 2294
CallFrequency BytecodeGraphBuilder::ComputeCallFrequency(int slot_id) const {
  if (invocation_frequency_.IsUnknown()) return CallFrequency();
2295
  FeedbackNexus nexus(feedback_vector(), FeedbackVector::ToSlot(slot_id));
2296 2297 2298 2299 2300 2301 2302
  float feedback_frequency = nexus.ComputeCallFrequency();
  if (feedback_frequency == 0.0f) {
    // This is to prevent multiplying zero and infinity.
    return CallFrequency(0.0f);
  } else {
    return CallFrequency(feedback_frequency * invocation_frequency_.value());
  }
2303 2304
}

2305
SpeculationMode BytecodeGraphBuilder::GetSpeculationMode(int slot_id) const {
2306
  FeedbackNexus nexus(feedback_vector(), FeedbackVector::ToSlot(slot_id));
2307 2308 2309
  return nexus.GetSpeculationMode();
}

2310
void BytecodeGraphBuilder::VisitBitwiseNot() {
2311 2312
  BuildUnaryOp(javascript()->BitwiseNot());
}
2313

2314 2315 2316
void BytecodeGraphBuilder::VisitDec() {
  BuildUnaryOp(javascript()->Decrement());
}
2317

2318 2319
void BytecodeGraphBuilder::VisitInc() {
  BuildUnaryOp(javascript()->Increment());
2320 2321
}

2322
void BytecodeGraphBuilder::VisitNegate() {
2323
  BuildUnaryOp(javascript()->Negate());
2324 2325
}

2326
void BytecodeGraphBuilder::VisitAdd() {
2327 2328
  BuildBinaryOp(
      javascript()->Add(GetBinaryOperationHint(kBinaryOperationHintIndex)));
2329 2330
}

2331
void BytecodeGraphBuilder::VisitSub() {
2332
  BuildBinaryOp(javascript()->Subtract());
2333 2334
}

2335
void BytecodeGraphBuilder::VisitMul() {
2336
  BuildBinaryOp(javascript()->Multiply());
2337 2338
}

2339
void BytecodeGraphBuilder::VisitDiv() { BuildBinaryOp(javascript()->Divide()); }
2340

2341
void BytecodeGraphBuilder::VisitMod() {
2342
  BuildBinaryOp(javascript()->Modulus());
2343 2344
}

2345 2346 2347 2348
void BytecodeGraphBuilder::VisitExp() {
  BuildBinaryOp(javascript()->Exponentiate());
}

2349
void BytecodeGraphBuilder::VisitBitwiseOr() {
2350
  BuildBinaryOp(javascript()->BitwiseOr());
2351 2352
}

2353
void BytecodeGraphBuilder::VisitBitwiseXor() {
2354
  BuildBinaryOp(javascript()->BitwiseXor());
2355 2356
}

2357
void BytecodeGraphBuilder::VisitBitwiseAnd() {
2358
  BuildBinaryOp(javascript()->BitwiseAnd());
2359 2360
}

2361
void BytecodeGraphBuilder::VisitShiftLeft() {
2362
  BuildBinaryOp(javascript()->ShiftLeft());
2363 2364
}

2365
void BytecodeGraphBuilder::VisitShiftRight() {
2366
  BuildBinaryOp(javascript()->ShiftRight());
2367 2368
}

2369
void BytecodeGraphBuilder::VisitShiftRightLogical() {
2370
  BuildBinaryOp(javascript()->ShiftRightLogical());
2371 2372
}

2373
void BytecodeGraphBuilder::BuildBinaryOpWithImmediate(const Operator* op) {
2374
  PrepareEagerCheckpoint();
2375
  Node* left = environment()->LookupAccumulator();
2376
  Node* right = jsgraph()->Constant(bytecode_iterator().GetImmediateOperand(0));
2377

2378 2379
  FeedbackSlot slot =
      bytecode_iterator().GetSlotOperand(kBinaryOperationSmiHintIndex);
2380 2381
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2382 2383
  if (lowering.IsExit()) return;

2384 2385 2386
  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2387
  } else {
2388
    DCHECK(!lowering.Changed());
2389 2390
    node = NewNode(op, left, right);
  }
2391
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2392 2393 2394
}

void BytecodeGraphBuilder::VisitAddSmi() {
2395 2396
  BuildBinaryOpWithImmediate(
      javascript()->Add(GetBinaryOperationHint(kBinaryOperationSmiHintIndex)));
2397 2398 2399
}

void BytecodeGraphBuilder::VisitSubSmi() {
2400
  BuildBinaryOpWithImmediate(javascript()->Subtract());
2401 2402
}

2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
void BytecodeGraphBuilder::VisitMulSmi() {
  BuildBinaryOpWithImmediate(javascript()->Multiply());
}

void BytecodeGraphBuilder::VisitDivSmi() {
  BuildBinaryOpWithImmediate(javascript()->Divide());
}

void BytecodeGraphBuilder::VisitModSmi() {
  BuildBinaryOpWithImmediate(javascript()->Modulus());
}

2415 2416 2417 2418
void BytecodeGraphBuilder::VisitExpSmi() {
  BuildBinaryOpWithImmediate(javascript()->Exponentiate());
}

2419
void BytecodeGraphBuilder::VisitBitwiseOrSmi() {
2420
  BuildBinaryOpWithImmediate(javascript()->BitwiseOr());
2421 2422
}

2423 2424 2425 2426
void BytecodeGraphBuilder::VisitBitwiseXorSmi() {
  BuildBinaryOpWithImmediate(javascript()->BitwiseXor());
}

2427
void BytecodeGraphBuilder::VisitBitwiseAndSmi() {
2428
  BuildBinaryOpWithImmediate(javascript()->BitwiseAnd());
2429 2430 2431
}

void BytecodeGraphBuilder::VisitShiftLeftSmi() {
2432
  BuildBinaryOpWithImmediate(javascript()->ShiftLeft());
2433 2434 2435
}

void BytecodeGraphBuilder::VisitShiftRightSmi() {
2436
  BuildBinaryOpWithImmediate(javascript()->ShiftRight());
2437 2438
}

2439 2440 2441 2442
void BytecodeGraphBuilder::VisitShiftRightLogicalSmi() {
  BuildBinaryOpWithImmediate(javascript()->ShiftRightLogical());
}

2443
void BytecodeGraphBuilder::VisitLogicalNot() {
2444
  Node* value = environment()->LookupAccumulator();
2445
  Node* node = NewNode(simplified()->BooleanNot(), value);
2446 2447 2448 2449
  environment()->BindAccumulator(node);
}

void BytecodeGraphBuilder::VisitToBooleanLogicalNot() {
2450 2451
  Node* value =
      NewNode(simplified()->ToBoolean(), environment()->LookupAccumulator());
2452
  Node* node = NewNode(simplified()->BooleanNot(), value);
2453
  environment()->BindAccumulator(node);
2454 2455
}

2456
void BytecodeGraphBuilder::VisitTypeOf() {
2457
  Node* node =
2458
      NewNode(simplified()->TypeOf(), environment()->LookupAccumulator());
2459 2460 2461
  environment()->BindAccumulator(node);
}

2462
void BytecodeGraphBuilder::BuildDelete(LanguageMode language_mode) {
2463
  PrepareEagerCheckpoint();
2464
  Node* key = environment()->LookupAccumulator();
2465 2466
  Node* object =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2467 2468
  Node* mode = jsgraph()->Constant(static_cast<int32_t>(language_mode));
  Node* node = NewNode(javascript()->DeleteProperty(), object, key, mode);
2469
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2470 2471
}

2472
void BytecodeGraphBuilder::VisitDeletePropertyStrict() {
2473
  BuildDelete(LanguageMode::kStrict);
2474 2475
}

2476
void BytecodeGraphBuilder::VisitDeletePropertySloppy() {
2477
  BuildDelete(LanguageMode::kSloppy);
2478 2479
}

2480 2481 2482 2483 2484 2485 2486
void BytecodeGraphBuilder::VisitGetSuperConstructor() {
  Node* node = NewNode(javascript()->GetSuperConstructor(),
                       environment()->LookupAccumulator());
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), node,
                              Environment::kAttachFrameState);
}

2487
void BytecodeGraphBuilder::BuildCompareOp(const Operator* op) {
2488
  PrepareEagerCheckpoint();
2489 2490
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2491
  Node* right = environment()->LookupAccumulator();
2492

2493
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
2494 2495
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedBinaryOp(op, left, right, slot);
2496 2497
  if (lowering.IsExit()) return;

2498
  Node* node = nullptr;
2499 2500
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2501
  } else {
2502
    DCHECK(!lowering.Changed());
2503 2504
    node = NewNode(op, left, right);
  }
2505
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2506 2507
}

2508
void BytecodeGraphBuilder::VisitTestEqual() {
2509
  BuildCompareOp(javascript()->Equal(GetCompareOperationHint()));
2510 2511
}

2512
void BytecodeGraphBuilder::VisitTestEqualStrict() {
2513
  BuildCompareOp(javascript()->StrictEqual(GetCompareOperationHint()));
2514 2515
}

2516
void BytecodeGraphBuilder::VisitTestLessThan() {
2517
  BuildCompareOp(javascript()->LessThan(GetCompareOperationHint()));
2518 2519
}

2520
void BytecodeGraphBuilder::VisitTestGreaterThan() {
2521
  BuildCompareOp(javascript()->GreaterThan(GetCompareOperationHint()));
2522 2523
}

2524
void BytecodeGraphBuilder::VisitTestLessThanOrEqual() {
2525
  BuildCompareOp(javascript()->LessThanOrEqual(GetCompareOperationHint()));
2526 2527
}

2528
void BytecodeGraphBuilder::VisitTestGreaterThanOrEqual() {
2529
  BuildCompareOp(javascript()->GreaterThanOrEqual(GetCompareOperationHint()));
2530 2531
}

2532
void BytecodeGraphBuilder::VisitTestReferenceEqual() {
2533 2534 2535
  Node* left =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* right = environment()->LookupAccumulator();
2536 2537
  Node* result = NewNode(simplified()->ReferenceEqual(), left, right);
  environment()->BindAccumulator(result);
2538 2539
}

2540
void BytecodeGraphBuilder::VisitTestIn() {
2541
  PrepareEagerCheckpoint();
2542 2543
  Node* object = environment()->LookupAccumulator();
  Node* key =
2544
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2545
  Node* node = NewNode(javascript()->HasProperty(), object, key);
2546 2547 2548
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
}

2549
void BytecodeGraphBuilder::VisitTestInstanceOf() {
2550 2551
  int const slot_index = bytecode_iterator().GetIndexOperand(1);
  BuildCompareOp(javascript()->InstanceOf(CreateVectorSlotPair(slot_index)));
2552 2553
}

2554
void BytecodeGraphBuilder::VisitTestUndetectable() {
2555
  Node* object = environment()->LookupAccumulator();
2556 2557 2558 2559
  Node* node = NewNode(jsgraph()->simplified()->ObjectIsUndetectable(), object);
  environment()->BindAccumulator(node);
}

2560
void BytecodeGraphBuilder::VisitTestNull() {
2561
  Node* object = environment()->LookupAccumulator();
2562 2563
  Node* result = NewNode(simplified()->ReferenceEqual(), object,
                         jsgraph()->NullConstant());
2564 2565 2566 2567
  environment()->BindAccumulator(result);
}

void BytecodeGraphBuilder::VisitTestUndefined() {
2568
  Node* object = environment()->LookupAccumulator();
2569 2570
  Node* result = NewNode(simplified()->ReferenceEqual(), object,
                         jsgraph()->UndefinedConstant());
2571 2572 2573
  environment()->BindAccumulator(result);
}

2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
void BytecodeGraphBuilder::VisitTestTypeOf() {
  Node* object = environment()->LookupAccumulator();
  auto literal_flag = interpreter::TestTypeOfFlags::Decode(
      bytecode_iterator().GetFlagOperand(0));
  Node* result;
  switch (literal_flag) {
    case interpreter::TestTypeOfFlags::LiteralFlag::kNumber:
      result = NewNode(simplified()->ObjectIsNumber(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kString:
      result = NewNode(simplified()->ObjectIsString(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kSymbol:
      result = NewNode(simplified()->ObjectIsSymbol(), object);
      break;
2589 2590 2591
    case interpreter::TestTypeOfFlags::LiteralFlag::kBigInt:
      result = NewNode(simplified()->ObjectIsBigInt(), object);
      break;
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
    case interpreter::TestTypeOfFlags::LiteralFlag::kBoolean:
      result = NewNode(common()->Select(MachineRepresentation::kTagged),
                       NewNode(simplified()->ReferenceEqual(), object,
                               jsgraph()->TrueConstant()),
                       jsgraph()->TrueConstant(),
                       NewNode(simplified()->ReferenceEqual(), object,
                               jsgraph()->FalseConstant()));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kUndefined:
      result = graph()->NewNode(
          common()->Select(MachineRepresentation::kTagged),
          graph()->NewNode(simplified()->ReferenceEqual(), object,
                           jsgraph()->NullConstant()),
          jsgraph()->FalseConstant(),
          graph()->NewNode(simplified()->ObjectIsUndetectable(), object));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kFunction:
      result =
          graph()->NewNode(simplified()->ObjectIsDetectableCallable(), object);
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kObject:
      result = graph()->NewNode(
          common()->Select(MachineRepresentation::kTagged),
          graph()->NewNode(simplified()->ObjectIsNonCallable(), object),
          jsgraph()->TrueConstant(),
          graph()->NewNode(simplified()->ReferenceEqual(), object,
                           jsgraph()->NullConstant()));
      break;
    case interpreter::TestTypeOfFlags::LiteralFlag::kOther:
      UNREACHABLE();  // Should never be emitted.
      break;
  }
  environment()->BindAccumulator(result);
}

2627 2628
void BytecodeGraphBuilder::BuildCastOperator(const Operator* js_op) {
  Node* value = NewNode(js_op, environment()->LookupAccumulator());
2629
  environment()->BindRegister(bytecode_iterator().GetRegisterOperand(0), value,
2630
                              Environment::kAttachFrameState);
2631 2632
}

2633 2634 2635 2636
void BytecodeGraphBuilder::VisitToName() {
  BuildCastOperator(javascript()->ToName());
}

2637
void BytecodeGraphBuilder::VisitToObject() {
2638
  BuildCastOperator(javascript()->ToObject());
2639 2640
}

2641 2642 2643 2644 2645 2646
void BytecodeGraphBuilder::VisitToString() {
  Node* value =
      NewNode(javascript()->ToString(), environment()->LookupAccumulator());
  environment()->BindAccumulator(value, Environment::kAttachFrameState);
}

2647
void BytecodeGraphBuilder::VisitToNumber() {
2648 2649 2650
  PrepareEagerCheckpoint();
  Node* object = environment()->LookupAccumulator();

2651
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(0);
2652 2653 2654 2655 2656 2657
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedToNumber(object, slot);

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
2658
  } else {
2659
    DCHECK(!lowering.Changed());
2660 2661 2662
    node = NewNode(javascript()->ToNumber(), object);
  }

2663
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2664 2665
}

2666
void BytecodeGraphBuilder::VisitToNumeric() {
2667 2668 2669 2670 2671
  PrepareEagerCheckpoint();
  Node* object = environment()->LookupAccumulator();

  // If we have some kind of Number feedback, we do the same lowering as for
  // ToNumber.
2672
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(0);
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedToNumber(object, slot);

  Node* node = nullptr;
  if (lowering.IsSideEffectFree()) {
    node = lowering.value();
  } else {
    DCHECK(!lowering.Changed());
    node = NewNode(javascript()->ToNumeric(), object);
  }

  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2685 2686
}

2687
void BytecodeGraphBuilder::VisitJump() { BuildJump(); }
2688

2689
void BytecodeGraphBuilder::VisitJumpConstant() { BuildJump(); }
2690

2691
void BytecodeGraphBuilder::VisitJumpIfTrue() { BuildJumpIfTrue(); }
2692

2693
void BytecodeGraphBuilder::VisitJumpIfTrueConstant() { BuildJumpIfTrue(); }
2694

2695
void BytecodeGraphBuilder::VisitJumpIfFalse() { BuildJumpIfFalse(); }
2696

2697
void BytecodeGraphBuilder::VisitJumpIfFalseConstant() { BuildJumpIfFalse(); }
2698

2699
void BytecodeGraphBuilder::VisitJumpIfToBooleanTrue() {
2700
  BuildJumpIfToBooleanTrue();
2701 2702
}

2703
void BytecodeGraphBuilder::VisitJumpIfToBooleanTrueConstant() {
2704
  BuildJumpIfToBooleanTrue();
2705 2706
}

2707
void BytecodeGraphBuilder::VisitJumpIfToBooleanFalse() {
2708
  BuildJumpIfToBooleanFalse();
2709 2710
}

2711
void BytecodeGraphBuilder::VisitJumpIfToBooleanFalseConstant() {
2712
  BuildJumpIfToBooleanFalse();
2713
}
2714

2715 2716 2717 2718 2719 2720
void BytecodeGraphBuilder::VisitJumpIfJSReceiver() { BuildJumpIfJSReceiver(); }

void BytecodeGraphBuilder::VisitJumpIfJSReceiverConstant() {
  BuildJumpIfJSReceiver();
}

2721
void BytecodeGraphBuilder::VisitJumpIfNull() {
2722
  BuildJumpIfEqual(jsgraph()->NullConstant());
2723 2724
}

2725
void BytecodeGraphBuilder::VisitJumpIfNullConstant() {
2726 2727 2728
  BuildJumpIfEqual(jsgraph()->NullConstant());
}

2729 2730 2731 2732 2733 2734 2735 2736
void BytecodeGraphBuilder::VisitJumpIfNotNull() {
  BuildJumpIfNotEqual(jsgraph()->NullConstant());
}

void BytecodeGraphBuilder::VisitJumpIfNotNullConstant() {
  BuildJumpIfNotEqual(jsgraph()->NullConstant());
}

2737
void BytecodeGraphBuilder::VisitJumpIfUndefined() {
2738
  BuildJumpIfEqual(jsgraph()->UndefinedConstant());
2739 2740
}

2741
void BytecodeGraphBuilder::VisitJumpIfUndefinedConstant() {
2742 2743 2744
  BuildJumpIfEqual(jsgraph()->UndefinedConstant());
}

2745 2746 2747 2748 2749 2750 2751 2752
void BytecodeGraphBuilder::VisitJumpIfNotUndefined() {
  BuildJumpIfNotEqual(jsgraph()->UndefinedConstant());
}

void BytecodeGraphBuilder::VisitJumpIfNotUndefinedConstant() {
  BuildJumpIfNotEqual(jsgraph()->UndefinedConstant());
}

2753 2754
void BytecodeGraphBuilder::VisitJumpLoop() { BuildJump(); }

2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
void BytecodeGraphBuilder::BuildSwitchOnSmi(Node* condition) {
  interpreter::JumpTableTargetOffsets offsets =
      bytecode_iterator().GetJumpTableTargetOffsets();

  NewSwitch(condition, offsets.size() + 1);
  for (const auto& entry : offsets) {
    SubEnvironment sub_environment(this);
    NewIfValue(entry.case_value);
    MergeIntoSuccessorEnvironment(entry.target_offset);
  }
  NewIfDefault();
}

2768 2769 2770 2771
void BytecodeGraphBuilder::VisitSwitchOnSmiNoFeedback() {
  PrepareEagerCheckpoint();

  Node* acc = environment()->LookupAccumulator();
2772
  Node* acc_smi = NewNode(simplified()->CheckSmi(VectorSlotPair()), acc);
2773
  BuildSwitchOnSmi(acc_smi);
2774 2775
}

2776
void BytecodeGraphBuilder::VisitStackCheck() {
2777
  PrepareEagerCheckpoint();
2778
  Node* node = NewNode(javascript()->StackCheck());
2779
  environment()->RecordAfterState(node, Environment::kAttachFrameState);
2780 2781
}

2782 2783 2784 2785 2786 2787
void BytecodeGraphBuilder::VisitSetPendingMessage() {
  Node* previous_message = NewNode(javascript()->LoadMessage());
  NewNode(javascript()->StoreMessage(), environment()->LookupAccumulator());
  environment()->BindAccumulator(previous_message);
}

2788 2789
void BytecodeGraphBuilder::BuildReturn(const BytecodeLivenessState* liveness) {
  BuildLoopExitsForFunctionExit(liveness);
2790
  Node* pop_node = jsgraph()->ZeroConstant();
2791
  Node* control =
2792
      NewNode(common()->Return(), pop_node, environment()->LookupAccumulator());
2793
  MergeControlToLeaveFunction(control);
2794 2795
}

2796 2797 2798 2799 2800
void BytecodeGraphBuilder::VisitReturn() {
  BuildReturn(bytecode_analysis()->GetInLivenessFor(
      bytecode_iterator().current_offset()));
}

2801
void BytecodeGraphBuilder::VisitDebugger() {
2802
  PrepareEagerCheckpoint();
2803 2804
  Node* call = NewNode(javascript()->Debugger());
  environment()->RecordAfterState(call, Environment::kAttachFrameState);
2805 2806
}

2807 2808 2809
// We cannot create a graph from the debugger copy of the bytecode array.
#define DEBUG_BREAK(Name, ...) \
  void BytecodeGraphBuilder::Visit##Name() { UNREACHABLE(); }
2810
DEBUG_BREAK_BYTECODE_LIST(DEBUG_BREAK)
2811 2812
#undef DEBUG_BREAK

2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
void BytecodeGraphBuilder::VisitIncBlockCounter() {
  Node* closure = GetFunctionClosure();
  Node* coverage_array_slot =
      jsgraph()->Constant(bytecode_iterator().GetIndexOperand(0));

  const Operator* op = javascript()->CallRuntime(Runtime::kIncBlockCounter);

  NewNode(op, closure, coverage_array_slot);
}

2823
void BytecodeGraphBuilder::VisitForInEnumerate() {
2824 2825
  Node* receiver =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2826 2827 2828 2829 2830 2831 2832 2833
  Node* enumerator = NewNode(javascript()->ForInEnumerate(), receiver);
  environment()->BindAccumulator(enumerator, Environment::kAttachFrameState);
}

void BytecodeGraphBuilder::VisitForInPrepare() {
  PrepareEagerCheckpoint();
  Node* enumerator = environment()->LookupAccumulator();

2834
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(1);
2835 2836 2837 2838 2839
  JSTypeHintLowering::LoweringResult lowering =
      TryBuildSimplifiedForInPrepare(enumerator, slot);
  if (lowering.IsExit()) return;
  DCHECK(!lowering.Changed());
  Node* node = NewNode(javascript()->ForInPrepare(GetForInMode(1)), enumerator);
2840
  environment()->BindRegistersToProjections(
2841
      bytecode_iterator().GetRegisterOperand(0), node);
2842 2843
}

2844
void BytecodeGraphBuilder::VisitForInContinue() {
2845
  PrepareEagerCheckpoint();
2846 2847
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2848
  Node* cache_length =
2849
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
2850 2851 2852
  Node* exit_cond = NewNode(simplified()->SpeculativeNumberLessThan(
                                NumberOperationHint::kSignedSmall),
                            index, cache_length);
2853
  environment()->BindAccumulator(exit_cond);
2854 2855
}

2856
void BytecodeGraphBuilder::VisitForInNext() {
2857
  PrepareEagerCheckpoint();
2858
  Node* receiver =
2859 2860 2861 2862
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(1));
  int catch_reg_pair_index = bytecode_iterator().GetRegisterOperand(2).index();
2863 2864 2865 2866 2867
  Node* cache_type = environment()->LookupRegister(
      interpreter::Register(catch_reg_pair_index));
  Node* cache_array = environment()->LookupRegister(
      interpreter::Register(catch_reg_pair_index + 1));

2868 2869 2870
  // We need to rename the {index} here, as in case of OSR we loose the
  // information that the {index} is always a valid unsigned Smi value.
  index = graph()->NewNode(common()->TypeGuard(Type::UnsignedSmall()), index,
2871
                           environment()->GetEffectDependency(),
2872
                           environment()->GetControlDependency());
2873
  environment()->UpdateEffectDependency(index);
2874

2875
  FeedbackSlot slot = bytecode_iterator().GetSlotOperand(3);
2876 2877 2878 2879
  JSTypeHintLowering::LoweringResult lowering = TryBuildSimplifiedForInNext(
      receiver, cache_array, cache_type, index, slot);
  if (lowering.IsExit()) return;

2880 2881 2882
  DCHECK(!lowering.Changed());
  Node* node = NewNode(javascript()->ForInNext(GetForInMode(3)), receiver,
                       cache_array, cache_type, index);
2883
  environment()->BindAccumulator(node, Environment::kAttachFrameState);
2884 2885
}

2886
void BytecodeGraphBuilder::VisitForInStep() {
2887
  PrepareEagerCheckpoint();
2888 2889
  Node* index =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
2890 2891 2892
  index = NewNode(simplified()->SpeculativeSafeIntegerAdd(
                      NumberOperationHint::kSignedSmall),
                  index, jsgraph()->OneConstant());
2893
  environment()->BindAccumulator(index, Environment::kAttachFrameState);
2894 2895
}

2896
void BytecodeGraphBuilder::VisitSuspendGenerator() {
2897 2898
  Node* generator = environment()->LookupRegister(
      bytecode_iterator().GetRegisterOperand(0));
2899 2900 2901 2902 2903
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
  // We assume we are storing a range starting from index 0.
  CHECK_EQ(0, first_reg.index());
  int register_count =
      static_cast<int>(bytecode_iterator().GetRegisterCountOperand(2));
2904 2905 2906
  int parameter_count_without_receiver =
      bytecode_array()->parameter_count() - 1;

2907 2908
  Node* suspend_id = jsgraph()->SmiConstant(
      bytecode_iterator().GetUnsignedImmediateOperand(3));
2909

2910 2911 2912 2913 2914
  // The offsets used by the bytecode iterator are relative to a different base
  // than what is used in the interpreter, hence the addition.
  Node* offset =
      jsgraph()->Constant(bytecode_iterator().current_offset() +
                          (BytecodeArray::kHeaderSize - kHeapObjectTag));
2915

2916 2917 2918 2919 2920 2921 2922
  const BytecodeLivenessState* liveness = bytecode_analysis()->GetInLivenessFor(
      bytecode_iterator().current_offset());

  // Maybe overallocate the value list since we don't know how many registers
  // are live.
  // TODO(leszeks): We could get this count from liveness rather than the
  // register list.
2923
  int value_input_count = 3 + parameter_count_without_receiver + register_count;
2924 2925 2926

  Node** value_inputs = local_zone()->NewArray<Node*>(value_input_count);
  value_inputs[0] = generator;
2927
  value_inputs[1] = suspend_id;
2928
  value_inputs[2] = offset;
2929 2930

  int count_written = 0;
2931 2932 2933 2934 2935 2936 2937 2938
  // Store the parameters.
  for (int i = 0; i < parameter_count_without_receiver; i++) {
    value_inputs[3 + count_written++] =
        environment()->LookupRegister(interpreter::Register::FromParameterIndex(
            i, parameter_count_without_receiver));
  }

  // Store the registers.
2939
  for (int i = 0; i < register_count; ++i) {
2940
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
2941 2942 2943
      int index_in_parameters_and_registers =
          parameter_count_without_receiver + i;
      while (count_written < index_in_parameters_and_registers) {
2944 2945 2946 2947
        value_inputs[3 + count_written++] = jsgraph()->OptimizedOutConstant();
      }
      value_inputs[3 + count_written++] =
          environment()->LookupRegister(interpreter::Register(i));
2948
      DCHECK_EQ(count_written, index_in_parameters_and_registers + 1);
2949
    }
2950 2951
  }

2952 2953 2954
  // Use the actual written count rather than the register count to create the
  // node.
  MakeNode(javascript()->GeneratorStore(count_written), 3 + count_written,
2955
           value_inputs, false);
2956 2957 2958 2959 2960

  // TODO(leszeks): This over-approximates the liveness at exit, only the
  // accumulator should be live by this point.
  BuildReturn(bytecode_analysis()->GetInLivenessFor(
      bytecode_iterator().current_offset()));
2961 2962
}

2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
void BytecodeGraphBuilder::BuildSwitchOnGeneratorState(
    const ZoneVector<ResumeJumpTarget>& resume_jump_targets,
    bool allow_fallthrough_on_executing) {
  Node* generator_state = environment()->LookupGeneratorState();

  int extra_cases = allow_fallthrough_on_executing ? 2 : 1;
  NewSwitch(generator_state,
            static_cast<int>(resume_jump_targets.size() + extra_cases));
  for (const ResumeJumpTarget& target : resume_jump_targets) {
    SubEnvironment sub_environment(this);
    NewIfValue(target.suspend_id());
    if (target.is_leaf()) {
      // Mark that we are resuming executing.
      environment()->BindGeneratorState(
          jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
    }
    // Jump to the target offset, whether it's a loop header or the resume.
    MergeIntoSuccessorEnvironment(target.target_offset());
  }

  {
    SubEnvironment sub_environment(this);
    // We should never hit the default case (assuming generator state cannot be
    // corrupted), so abort if we do.
    // TODO(leszeks): Maybe only check this in debug mode, and otherwise use
    // the default to represent one of the cases above/fallthrough below?
    NewIfDefault();
    NewNode(simplified()->RuntimeAbort(AbortReason::kInvalidJumpTableIndex));
2991
    // TODO(7099): Investigate if we need LoopExit here.
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
    Node* control = NewNode(common()->Throw());
    MergeControlToLeaveFunction(control);
  }

  if (allow_fallthrough_on_executing) {
    // If we are executing (rather than resuming), and we allow it, just fall
    // through to the actual loop body.
    NewIfValue(JSGeneratorObject::kGeneratorExecuting);
  } else {
    // Otherwise, this environment is dead.
    set_environment(nullptr);
  }
}

void BytecodeGraphBuilder::VisitSwitchOnGeneratorState() {
  Node* generator =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3009

3010 3011 3012
  Node* generator_is_undefined =
      NewNode(simplified()->ReferenceEqual(), generator,
              jsgraph()->UndefinedConstant());
3013

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
  NewBranch(generator_is_undefined);
  {
    SubEnvironment resume_env(this);
    NewIfFalse();

    Node* generator_state =
        NewNode(javascript()->GeneratorRestoreContinuation(), generator);
    environment()->BindGeneratorState(generator_state);

    Node* generator_context =
        NewNode(javascript()->GeneratorRestoreContext(), generator);
    environment()->SetContext(generator_context);

    BuildSwitchOnGeneratorState(bytecode_analysis()->resume_jump_targets(),
                                false);
  }
3030

3031 3032
  // Fallthrough for the first-call case.
  NewIfTrue();
3033 3034
}

3035
void BytecodeGraphBuilder::VisitResumeGenerator() {
3036 3037
  Node* generator =
      environment()->LookupRegister(bytecode_iterator().GetRegisterOperand(0));
3038
  interpreter::Register first_reg = bytecode_iterator().GetRegisterOperand(1);
3039 3040
  // We assume we are restoring registers starting fromm index 0.
  CHECK_EQ(0, first_reg.index());
3041 3042 3043 3044

  const BytecodeLivenessState* liveness =
      bytecode_analysis()->GetOutLivenessFor(
          bytecode_iterator().current_offset());
3045

3046 3047 3048 3049 3050
  int parameter_count_without_receiver =
      bytecode_array()->parameter_count() - 1;

  // Mapping between registers and array indices must match that used in
  // InterpreterAssembler::ExportParametersAndRegisterFile.
3051 3052
  for (int i = 0; i < environment()->register_count(); ++i) {
    if (liveness == nullptr || liveness->RegisterIsLive(i)) {
3053 3054 3055
      Node* value = NewNode(javascript()->GeneratorRestoreRegister(
                                parameter_count_without_receiver + i),
                            generator);
3056 3057
      environment()->BindRegister(interpreter::Register(i), value);
    }
3058
  }
3059 3060 3061 3062 3063

  // Update the accumulator with the generator's input_or_debug_pos.
  Node* input_or_debug_pos =
      NewNode(javascript()->GeneratorRestoreInputOrDebugPos(), generator);
  environment()->BindAccumulator(input_or_debug_pos);
3064 3065
}

3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
void BytecodeGraphBuilder::VisitWide() {
  // Consumed by the BytecodeArrayIterator.
  UNREACHABLE();
}

void BytecodeGraphBuilder::VisitExtraWide() {
  // Consumed by the BytecodeArrayIterator.
  UNREACHABLE();
}

void BytecodeGraphBuilder::VisitIllegal() {
3077 3078
  // Not emitted in valid bytecode.
  UNREACHABLE();
3079 3080
}

3081
void BytecodeGraphBuilder::SwitchToMergeEnvironment(int current_offset) {
3082 3083
  auto it = merge_environments_.find(current_offset);
  if (it != merge_environments_.end()) {
3084
    mark_as_needing_eager_checkpoint(true);
3085
    if (environment() != nullptr) {
3086 3087
      it->second->Merge(environment(),
                        bytecode_analysis()->GetInLivenessFor(current_offset));
3088
    }
3089
    set_environment(it->second);
3090 3091 3092
  }
}

3093
void BytecodeGraphBuilder::BuildLoopHeaderEnvironment(int current_offset) {
3094
  if (bytecode_analysis()->IsLoopHeader(current_offset)) {
3095
    mark_as_needing_eager_checkpoint(true);
3096 3097
    const LoopInfo& loop_info =
        bytecode_analysis()->GetLoopInfoFor(current_offset);
3098 3099
    const BytecodeLivenessState* liveness =
        bytecode_analysis()->GetInLivenessFor(current_offset);
3100

3101 3102 3103
    const auto& resume_jump_targets = loop_info.resume_jump_targets();
    bool generate_suspend_switch = !resume_jump_targets.empty();

3104
    // Add loop header.
3105
    environment()->PrepareForLoop(loop_info.assignments(), liveness);
3106 3107 3108 3109

    // Store a copy of the environment so we can connect merged back edge inputs
    // to the loop header.
    merge_environments_[current_offset] = environment()->Copy();
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123

    // If this loop contains resumes, create a new switch just after the loop
    // for those resumes.
    if (generate_suspend_switch) {
      BuildSwitchOnGeneratorState(loop_info.resume_jump_targets(), true);

      // TODO(leszeks): At this point we know we are executing rather than
      // resuming, so we should be able to prune off the phis in the environment
      // related to the resume path.

      // Set the generator state to a known constant.
      environment()->BindGeneratorState(
          jsgraph()->SmiConstant(JSGeneratorObject::kGeneratorExecuting));
    }
3124 3125 3126
  }
}

3127
void BytecodeGraphBuilder::MergeIntoSuccessorEnvironment(int target_offset) {
3128
  BuildLoopExitsForBranch(target_offset);
3129
  Environment*& merge_environment = merge_environments_[target_offset];
3130

3131
  if (merge_environment == nullptr) {
3132 3133 3134 3135 3136
    // Append merge nodes to the environment. We may merge here with another
    // environment. So add a place holder for merge nodes. We may add redundant
    // but will be eliminated in a later pass.
    // TODO(mstarzinger): Be smarter about this!
    NewMerge();
3137
    merge_environment = environment();
3138
  } else {
3139 3140 3141
    // Merge any values which are live coming into the successor.
    merge_environment->Merge(
        environment(), bytecode_analysis()->GetInLivenessFor(target_offset));
3142 3143 3144 3145
  }
  set_environment(nullptr);
}

3146 3147 3148 3149
void BytecodeGraphBuilder::MergeControlToLeaveFunction(Node* exit) {
  exit_controls_.push_back(exit);
  set_environment(nullptr);
}
3150

3151 3152 3153 3154
void BytecodeGraphBuilder::BuildLoopExitsForBranch(int target_offset) {
  int origin_offset = bytecode_iterator().current_offset();
  // Only build loop exits for forward edges.
  if (target_offset > origin_offset) {
3155
    BuildLoopExitsUntilLoop(
3156 3157
        bytecode_analysis()->GetLoopOffsetFor(target_offset),
        bytecode_analysis()->GetInLivenessFor(target_offset));
3158 3159 3160
  }
}

3161 3162
void BytecodeGraphBuilder::BuildLoopExitsUntilLoop(
    int loop_offset, const BytecodeLivenessState* liveness) {
3163
  int origin_offset = bytecode_iterator().current_offset();
3164
  int current_loop = bytecode_analysis()->GetLoopOffsetFor(origin_offset);
3165 3166 3167 3168
  // The limit_offset is the stop offset for building loop exists, used for OSR.
  // It prevents the creations of loopexits for loops which do not exist.
  loop_offset = std::max(loop_offset, currently_peeled_loop_offset_);

3169 3170
  while (loop_offset < current_loop) {
    Node* loop_node = merge_environments_[current_loop]->GetControlDependency();
3171 3172
    const LoopInfo& loop_info =
        bytecode_analysis()->GetLoopInfoFor(current_loop);
3173 3174
    environment()->PrepareForLoopExit(loop_node, loop_info.assignments(),
                                      liveness);
3175
    current_loop = loop_info.parent_offset();
3176 3177 3178
  }
}

3179 3180 3181
void BytecodeGraphBuilder::BuildLoopExitsForFunctionExit(
    const BytecodeLivenessState* liveness) {
  BuildLoopExitsUntilLoop(-1, liveness);
3182 3183
}

3184
void BytecodeGraphBuilder::BuildJump() {
3185
  MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
3186 3187
}

3188
void BytecodeGraphBuilder::BuildJumpIf(Node* condition) {
3189
  NewBranch(condition, BranchHint::kNone, IsSafetyCheck::kNoSafetyCheck);
3190 3191 3192 3193 3194
  {
    SubEnvironment sub_environment(this);
    NewIfTrue();
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
3195 3196 3197
  NewIfFalse();
}

3198
void BytecodeGraphBuilder::BuildJumpIfNot(Node* condition) {
3199
  NewBranch(condition, BranchHint::kNone, IsSafetyCheck::kNoSafetyCheck);
3200 3201 3202 3203 3204
  {
    SubEnvironment sub_environment(this);
    NewIfFalse();
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
3205 3206
  NewIfTrue();
}
3207

3208
void BytecodeGraphBuilder::BuildJumpIfEqual(Node* comperand) {
3209
  Node* accumulator = environment()->LookupAccumulator();
3210
  Node* condition =
3211
      NewNode(simplified()->ReferenceEqual(), accumulator, comperand);
3212
  BuildJumpIf(condition);
3213 3214
}

3215 3216 3217 3218 3219 3220 3221
void BytecodeGraphBuilder::BuildJumpIfNotEqual(Node* comperand) {
  Node* accumulator = environment()->LookupAccumulator();
  Node* condition =
      NewNode(simplified()->ReferenceEqual(), accumulator, comperand);
  BuildJumpIfNot(condition);
}

3222
void BytecodeGraphBuilder::BuildJumpIfFalse() {
3223
  NewBranch(environment()->LookupAccumulator(), BranchHint::kNone,
3224
            IsSafetyCheck::kNoSafetyCheck);
3225 3226 3227 3228 3229 3230 3231 3232
  {
    SubEnvironment sub_environment(this);
    NewIfFalse();
    environment()->BindAccumulator(jsgraph()->FalseConstant());
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
  NewIfTrue();
  environment()->BindAccumulator(jsgraph()->TrueConstant());
3233
}
3234

3235
void BytecodeGraphBuilder::BuildJumpIfTrue() {
3236
  NewBranch(environment()->LookupAccumulator(), BranchHint::kNone,
3237
            IsSafetyCheck::kNoSafetyCheck);
3238 3239 3240 3241 3242 3243 3244 3245
  {
    SubEnvironment sub_environment(this);
    NewIfTrue();
    environment()->BindAccumulator(jsgraph()->TrueConstant());
    MergeIntoSuccessorEnvironment(bytecode_iterator().GetJumpTargetOffset());
  }
  NewIfFalse();
  environment()->BindAccumulator(jsgraph()->FalseConstant());
3246 3247 3248
}

void BytecodeGraphBuilder::BuildJumpIfToBooleanTrue() {
3249
  Node* accumulator = environment()->LookupAccumulator();
3250
  Node* condition = NewNode(simplified()->ToBoolean(), accumulator);
3251 3252 3253 3254 3255
  BuildJumpIf(condition);
}

void BytecodeGraphBuilder::BuildJumpIfToBooleanFalse() {
  Node* accumulator = environment()->LookupAccumulator();
3256
  Node* condition = NewNode(simplified()->ToBoolean(), accumulator);
3257
  BuildJumpIfNot(condition);
3258 3259
}

3260 3261
void BytecodeGraphBuilder::BuildJumpIfNotHole() {
  Node* accumulator = environment()->LookupAccumulator();
3262 3263
  Node* condition = NewNode(simplified()->ReferenceEqual(), accumulator,
                            jsgraph()->TheHoleConstant());
3264
  BuildJumpIfNot(condition);
3265
}
3266

3267 3268 3269 3270 3271 3272
void BytecodeGraphBuilder::BuildJumpIfJSReceiver() {
  Node* accumulator = environment()->LookupAccumulator();
  Node* condition = NewNode(simplified()->ObjectIsReceiver(), accumulator);
  BuildJumpIf(condition);
}

3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedUnaryOp(const Operator* op,
                                                Node* operand,
                                                FeedbackSlot slot) {
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceUnaryOperation(op, operand, effect, control,
                                                slot);
  ApplyEarlyReduction(result);
  return result;
}

3286 3287 3288 3289
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedBinaryOp(const Operator* op, Node* left,
                                                 Node* right,
                                                 FeedbackSlot slot) {
3290 3291
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3292 3293 3294 3295 3296
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceBinaryOperation(op, left, right, effect,
                                                 control, slot);
  ApplyEarlyReduction(result);
  return result;
3297 3298
}

3299 3300 3301 3302 3303
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedForInNext(Node* receiver,
                                                  Node* cache_array,
                                                  Node* cache_type, Node* index,
                                                  FeedbackSlot slot) {
3304 3305
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3306 3307 3308
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceForInNextOperation(
          receiver, cache_array, cache_type, index, effect, control, slot);
3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
  ApplyEarlyReduction(result);
  return result;
}

JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedForInPrepare(Node* enumerator,
                                                     FeedbackSlot slot) {
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceForInPrepareOperation(enumerator, effect,
                                                       control, slot);
3321 3322
  ApplyEarlyReduction(result);
  return result;
3323 3324
}

3325 3326 3327
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedToNumber(Node* value,
                                                 FeedbackSlot slot) {
3328 3329
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3330 3331 3332 3333 3334
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceToNumberOperation(value, effect, control,
                                                   slot);
  ApplyEarlyReduction(result);
  return result;
3335 3336
}

3337 3338
JSTypeHintLowering::LoweringResult BytecodeGraphBuilder::TryBuildSimplifiedCall(
    const Operator* op, Node* const* args, int arg_count, FeedbackSlot slot) {
3339 3340
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3341 3342 3343 3344 3345
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceCallOperation(op, args, arg_count, effect,
                                               control, slot);
  ApplyEarlyReduction(result);
  return result;
3346 3347
}

3348 3349 3350 3351 3352
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedConstruct(const Operator* op,
                                                  Node* const* args,
                                                  int arg_count,
                                                  FeedbackSlot slot) {
3353 3354
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3355 3356 3357 3358 3359
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceConstructOperation(op, args, arg_count, effect,
                                                    control, slot);
  ApplyEarlyReduction(result);
  return result;
3360 3361
}

3362 3363 3364 3365
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedLoadNamed(const Operator* op,
                                                  Node* receiver,
                                                  FeedbackSlot slot) {
3366 3367
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3368 3369 3370 3371 3372
  JSTypeHintLowering::LoweringResult early_reduction =
      type_hint_lowering().ReduceLoadNamedOperation(op, receiver, effect,
                                                    control, slot);
  ApplyEarlyReduction(early_reduction);
  return early_reduction;
3373 3374
}

3375 3376 3377 3378
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedLoadKeyed(const Operator* op,
                                                  Node* receiver, Node* key,
                                                  FeedbackSlot slot) {
3379 3380
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3381 3382 3383 3384 3385
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceLoadKeyedOperation(op, receiver, key, effect,
                                                    control, slot);
  ApplyEarlyReduction(result);
  return result;
3386 3387
}

3388 3389 3390 3391
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedStoreNamed(const Operator* op,
                                                   Node* receiver, Node* value,
                                                   FeedbackSlot slot) {
3392 3393
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3394 3395 3396 3397 3398
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceStoreNamedOperation(op, receiver, value,
                                                     effect, control, slot);
  ApplyEarlyReduction(result);
  return result;
3399 3400
}

3401 3402 3403 3404 3405
JSTypeHintLowering::LoweringResult
BytecodeGraphBuilder::TryBuildSimplifiedStoreKeyed(const Operator* op,
                                                   Node* receiver, Node* key,
                                                   Node* value,
                                                   FeedbackSlot slot) {
3406 3407
  Node* effect = environment()->GetEffectDependency();
  Node* control = environment()->GetControlDependency();
3408 3409 3410 3411 3412
  JSTypeHintLowering::LoweringResult result =
      type_hint_lowering().ReduceStoreKeyedOperation(op, receiver, key, value,
                                                     effect, control, slot);
  ApplyEarlyReduction(result);
  return result;
3413 3414
}

3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
void BytecodeGraphBuilder::ApplyEarlyReduction(
    JSTypeHintLowering::LoweringResult reduction) {
  if (reduction.IsExit()) {
    MergeControlToLeaveFunction(reduction.control());
  } else if (reduction.IsSideEffectFree()) {
    environment()->UpdateEffectDependency(reduction.effect());
    environment()->UpdateControlDependency(reduction.control());
  } else {
    DCHECK(!reduction.Changed());
    // At the moment, we assume side-effect free reduction. To support
    // side-effects, we would have to invalidate the eager checkpoint,
    // so that deoptimization does not repeat the side effect.
3427 3428 3429
  }
}

3430 3431 3432 3433 3434 3435 3436 3437 3438
Node** BytecodeGraphBuilder::EnsureInputBufferSize(int size) {
  if (size > input_buffer_size_) {
    size = size + kInputBufferSizeIncrement + input_buffer_size_;
    input_buffer_ = local_zone()->NewArray<Node*>(size);
    input_buffer_size_ = size;
  }
  return input_buffer_;
}

3439
void BytecodeGraphBuilder::ExitThenEnterExceptionHandlers(int current_offset) {
3440
  HandlerTable table(*bytecode_array());
3441 3442 3443 3444 3445 3446 3447 3448 3449

  // Potentially exit exception handlers.
  while (!exception_handlers_.empty()) {
    int current_end = exception_handlers_.top().end_offset_;
    if (current_offset < current_end) break;  // Still covered by range.
    exception_handlers_.pop();
  }

  // Potentially enter exception handlers.
3450
  int num_entries = table.NumberOfRangeEntries();
3451
  while (current_exception_handler_ < num_entries) {
3452
    int next_start = table.GetRangeStart(current_exception_handler_);
3453
    if (current_offset < next_start) break;  // Not yet covered by range.
3454 3455 3456
    int next_end = table.GetRangeEnd(current_exception_handler_);
    int next_handler = table.GetRangeHandler(current_exception_handler_);
    int context_register = table.GetRangeData(current_exception_handler_);
3457
    exception_handlers_.push(
3458
        {next_start, next_end, next_handler, context_register});
3459 3460 3461
    current_exception_handler_++;
  }
}
3462 3463

Node* BytecodeGraphBuilder::MakeNode(const Operator* op, int value_input_count,
3464 3465
                                     Node* const* value_inputs,
                                     bool incomplete) {
3466 3467 3468
  DCHECK_EQ(op->ValueInputCount(), value_input_count);

  bool has_context = OperatorProperties::HasContextInput(op);
3469
  bool has_frame_state = OperatorProperties::HasFrameStateInput(op);
3470 3471 3472 3473 3474 3475
  bool has_control = op->ControlInputCount() == 1;
  bool has_effect = op->EffectInputCount() == 1;

  DCHECK_LT(op->ControlInputCount(), 2);
  DCHECK_LT(op->EffectInputCount(), 2);

3476
  Node* result = nullptr;
3477
  if (!has_context && !has_frame_state && !has_control && !has_effect) {
3478 3479
    result = graph()->NewNode(op, value_input_count, value_inputs, incomplete);
  } else {
3480
    bool inside_handler = !exception_handlers_.empty();
3481 3482
    int input_count_with_deps = value_input_count;
    if (has_context) ++input_count_with_deps;
3483
    if (has_frame_state) ++input_count_with_deps;
3484 3485 3486
    if (has_control) ++input_count_with_deps;
    if (has_effect) ++input_count_with_deps;
    Node** buffer = EnsureInputBufferSize(input_count_with_deps);
3487 3488 3489
    if (value_input_count > 0) {
      memcpy(buffer, value_inputs, kSystemPointerSize * value_input_count);
    }
3490 3491
    Node** current_input = buffer + value_input_count;
    if (has_context) {
3492 3493 3494
      *current_input++ = OperatorProperties::NeedsExactContext(op)
                             ? environment()->Context()
                             : jsgraph()->HeapConstant(native_context());
3495
    }
3496
    if (has_frame_state) {
3497 3498 3499
      // The frame state will be inserted later. Here we misuse the {Dead} node
      // as a sentinel to be later overwritten with the real frame state by the
      // calls to {PrepareFrameState} within individual visitor methods.
3500
      *current_input++ = jsgraph()->Dead();
3501 3502 3503 3504 3505 3506 3507 3508
    }
    if (has_effect) {
      *current_input++ = environment()->GetEffectDependency();
    }
    if (has_control) {
      *current_input++ = environment()->GetControlDependency();
    }
    result = graph()->NewNode(op, input_count_with_deps, buffer, incomplete);
3509
    // Update the current control dependency for control-producing nodes.
3510
    if (result->op()->ControlOutputCount() > 0) {
3511 3512 3513 3514 3515 3516 3517 3518 3519
      environment()->UpdateControlDependency(result);
    }
    // Update the current effect dependency for effect-producing nodes.
    if (result->op()->EffectOutputCount() > 0) {
      environment()->UpdateEffectDependency(result);
    }
    // Add implicit exception continuation for throwing nodes.
    if (!result->op()->HasProperty(Operator::kNoThrow) && inside_handler) {
      int handler_offset = exception_handlers_.top().handler_offset_;
3520 3521
      int context_index = exception_handlers_.top().context_register_;
      interpreter::Register context_register(context_index);
3522
      Environment* success_env = environment()->Copy();
3523
      const Operator* op = common()->IfException();
3524 3525
      Node* effect = environment()->GetEffectDependency();
      Node* on_exception = graph()->NewNode(op, effect, result);
3526
      Node* context = environment()->LookupRegister(context_register);
3527 3528 3529
      environment()->UpdateControlDependency(on_exception);
      environment()->UpdateEffectDependency(on_exception);
      environment()->BindAccumulator(on_exception);
3530
      environment()->SetContext(context);
3531 3532 3533 3534
      MergeIntoSuccessorEnvironment(handler_offset);
      set_environment(success_env);
    }
    // Add implicit success continuation for throwing nodes.
3535
    if (!result->op()->HasProperty(Operator::kNoThrow) && inside_handler) {
3536 3537 3538
      const Operator* if_success = common()->IfSuccess();
      Node* on_success = graph()->NewNode(if_success, result);
      environment()->UpdateControlDependency(on_success);
3539
    }
3540 3541 3542 3543
    // Ensure checkpoints are created after operations with side-effects.
    if (has_effect && !result->op()->HasProperty(Operator::kNoWrite)) {
      mark_as_needing_eager_checkpoint(true);
    }
3544 3545 3546 3547 3548 3549
  }

  return result;
}


3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
Node* BytecodeGraphBuilder::NewPhi(int count, Node* input, Node* control) {
  const Operator* phi_op = common()->Phi(MachineRepresentation::kTagged, count);
  Node** buffer = EnsureInputBufferSize(count + 1);
  MemsetPointer(buffer, input, count);
  buffer[count] = control;
  return graph()->NewNode(phi_op, count + 1, buffer, true);
}

Node* BytecodeGraphBuilder::NewEffectPhi(int count, Node* input,
                                         Node* control) {
  const Operator* phi_op = common()->EffectPhi(count);
  Node** buffer = EnsureInputBufferSize(count + 1);
  MemsetPointer(buffer, input, count);
  buffer[count] = control;
  return graph()->NewNode(phi_op, count + 1, buffer, true);
}


3568 3569 3570 3571 3572 3573
Node* BytecodeGraphBuilder::MergeControl(Node* control, Node* other) {
  int inputs = control->op()->ControlInputCount() + 1;
  if (control->opcode() == IrOpcode::kLoop) {
    // Control node for loop exists, add input.
    const Operator* op = common()->Loop(inputs);
    control->AppendInput(graph_zone(), other);
3574
    NodeProperties::ChangeOp(control, op);
3575 3576 3577 3578
  } else if (control->opcode() == IrOpcode::kMerge) {
    // Control node for merge exists, add input.
    const Operator* op = common()->Merge(inputs);
    control->AppendInput(graph_zone(), other);
3579
    NodeProperties::ChangeOp(control, op);
3580 3581 3582
  } else {
    // Control node is a singleton, introduce a merge.
    const Operator* op = common()->Merge(inputs);
3583 3584
    Node* merge_inputs[] = {control, other};
    control = graph()->NewNode(op, arraysize(merge_inputs), merge_inputs, true);
3585 3586 3587 3588
  }
  return control;
}

3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
Node* BytecodeGraphBuilder::MergeEffect(Node* value, Node* other,
                                        Node* control) {
  int inputs = control->op()->ControlInputCount();
  if (value->opcode() == IrOpcode::kEffectPhi &&
      NodeProperties::GetControlInput(value) == control) {
    // Phi already exists, add input.
    value->InsertInput(graph_zone(), inputs - 1, other);
    NodeProperties::ChangeOp(value, common()->EffectPhi(inputs));
  } else if (value != other) {
    // Phi does not exist yet, introduce one.
    value = NewEffectPhi(inputs, value, control);
    value->ReplaceInput(inputs - 1, other);
  }
  return value;
}

Node* BytecodeGraphBuilder::MergeValue(Node* value, Node* other,
                                       Node* control) {
  int inputs = control->op()->ControlInputCount();
  if (value->opcode() == IrOpcode::kPhi &&
      NodeProperties::GetControlInput(value) == control) {
    // Phi already exists, add input.
    value->InsertInput(graph_zone(), inputs - 1, other);
    NodeProperties::ChangeOp(
        value, common()->Phi(MachineRepresentation::kTagged, inputs));
  } else if (value != other) {
    // Phi does not exist yet, introduce one.
    value = NewPhi(inputs, value, control);
    value->ReplaceInput(inputs - 1, other);
  }
  return value;
}

3622 3623
void BytecodeGraphBuilder::UpdateSourcePosition(SourcePositionTableIterator* it,
                                                int offset) {
3624 3625
  if (it->done()) return;
  if (it->code_offset() == offset) {
3626 3627
    source_positions_->SetCurrentPosition(SourcePosition(
        it->source_position().ScriptOffset(), start_position_.InliningId()));
3628 3629 3630 3631 3632 3633
    it->Advance();
  } else {
    DCHECK_GT(it->code_offset(), offset);
  }
}

3634 3635 3636
}  // namespace compiler
}  // namespace internal
}  // namespace v8