js-native-context-specialization.cc 142 KB
Newer Older
1 2 3 4
// 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.

5
#include "src/compiler/js-native-context-specialization.h"
6

7
#include "src/api/api-inl.h"
8
#include "src/builtins/accessors.h"
9 10
#include "src/codegen/code-factory.h"
#include "src/codegen/string-constants.h"
11
#include "src/compiler/access-builder.h"
12
#include "src/compiler/access-info.h"
13
#include "src/compiler/allocation-builder.h"
14
#include "src/compiler/compilation-dependencies.h"
15 16
#include "src/compiler/js-graph.h"
#include "src/compiler/js-operator.h"
17
#include "src/compiler/linkage.h"
18
#include "src/compiler/map-inference.h"
19
#include "src/compiler/node-matchers.h"
20
#include "src/compiler/property-access-builder.h"
21
#include "src/compiler/type-cache.h"
22
#include "src/execution/isolate-inl.h"
23
#include "src/numbers/dtoa.h"
24
#include "src/objects/feedback-vector.h"
25
#include "src/objects/field-index-inl.h"
26
#include "src/objects/heap-number.h"
27
#include "src/objects/js-array-buffer-inl.h"
28
#include "src/objects/js-array-inl.h"
29
#include "src/objects/templates.h"
30 31 32 33 34

namespace v8 {
namespace internal {
namespace compiler {

35 36
namespace {

37
bool HasNumberMaps(JSHeapBroker* broker, ZoneVector<Handle<Map>> const& maps) {
38
  for (auto map : maps) {
39 40
    MapRef map_ref(broker, map);
    if (map_ref.IsHeapNumberMap()) return true;
41 42 43 44
  }
  return false;
}

45 46
bool HasOnlyJSArrayMaps(JSHeapBroker* broker,
                        ZoneVector<Handle<Map>> const& maps) {
47
  for (auto map : maps) {
48 49
    MapRef map_ref(broker, map);
    if (!map_ref.IsJSArrayMap()) return false;
50 51 52 53 54 55
  }
  return true;
}

}  // namespace

56 57 58 59
bool JSNativeContextSpecialization::should_disallow_heap_access() const {
  return broker()->is_concurrent_inlining();
}

60
JSNativeContextSpecialization::JSNativeContextSpecialization(
61
    Editor* editor, JSGraph* jsgraph, JSHeapBroker* broker, Flags flags,
62
    CompilationDependencies* dependencies, Zone* zone, Zone* shared_zone)
63 64
    : AdvancedReducer(editor),
      jsgraph_(jsgraph),
65
      broker_(broker),
66
      flags_(flags),
67 68 69
      global_object_(broker->target_native_context().global_object().object()),
      global_proxy_(
          broker->target_native_context().global_proxy_object().object()),
70
      dependencies_(dependencies),
71
      zone_(zone),
72
      shared_zone_(shared_zone),
73
      type_cache_(TypeCache::Get()) {}
74

75
Reduction JSNativeContextSpecialization::Reduce(Node* node) {
76
  DisallowHeapAccessIf disallow_heap_access(should_disallow_heap_access());
77

78
  switch (node->opcode()) {
79 80
    case IrOpcode::kJSAdd:
      return ReduceJSAdd(node);
81 82 83 84 85 86
    case IrOpcode::kJSAsyncFunctionEnter:
      return ReduceJSAsyncFunctionEnter(node);
    case IrOpcode::kJSAsyncFunctionReject:
      return ReduceJSAsyncFunctionReject(node);
    case IrOpcode::kJSAsyncFunctionResolve:
      return ReduceJSAsyncFunctionResolve(node);
87 88
    case IrOpcode::kJSGetSuperConstructor:
      return ReduceJSGetSuperConstructor(node);
89 90
    case IrOpcode::kJSInstanceOf:
      return ReduceJSInstanceOf(node);
91 92
    case IrOpcode::kJSHasInPrototypeChain:
      return ReduceJSHasInPrototypeChain(node);
93 94
    case IrOpcode::kJSOrdinaryHasInstance:
      return ReduceJSOrdinaryHasInstance(node);
95 96 97 98
    case IrOpcode::kJSPromiseResolve:
      return ReduceJSPromiseResolve(node);
    case IrOpcode::kJSResolvePromise:
      return ReduceJSResolvePromise(node);
99 100 101 102
    case IrOpcode::kJSLoadGlobal:
      return ReduceJSLoadGlobal(node);
    case IrOpcode::kJSStoreGlobal:
      return ReduceJSStoreGlobal(node);
103 104
    case IrOpcode::kJSLoadNamed:
      return ReduceJSLoadNamed(node);
105 106
    case IrOpcode::kJSStoreNamed:
      return ReduceJSStoreNamed(node);
107 108
    case IrOpcode::kJSHasProperty:
      return ReduceJSHasProperty(node);
109 110 111 112
    case IrOpcode::kJSLoadProperty:
      return ReduceJSLoadProperty(node);
    case IrOpcode::kJSStoreProperty:
      return ReduceJSStoreProperty(node);
113 114
    case IrOpcode::kJSStoreNamedOwn:
      return ReduceJSStoreNamedOwn(node);
115 116
    case IrOpcode::kJSStoreDataPropertyInLiteral:
      return ReduceJSStoreDataPropertyInLiteral(node);
117 118
    case IrOpcode::kJSStoreInArrayLiteral:
      return ReduceJSStoreInArrayLiteral(node);
119 120
    case IrOpcode::kJSToObject:
      return ReduceJSToObject(node);
121 122
    case IrOpcode::kJSToString:
      return ReduceJSToString(node);
123 124
    case IrOpcode::kJSGetIterator:
      return ReduceJSGetIterator(node);
125 126 127 128 129 130
    default:
      break;
  }
  return NoChange();
}

131 132
// static
base::Optional<size_t> JSNativeContextSpecialization::GetMaxStringLength(
133
    JSHeapBroker* broker, Node* node) {
134 135 136 137 138
  if (node->opcode() == IrOpcode::kDelayedStringConstant) {
    return StringConstantBaseOf(node->op())->GetMaxStringConstantLength();
  }

  HeapObjectMatcher matcher(node);
139 140 141
  if (matcher.HasValue() && matcher.Ref(broker).IsString()) {
    StringRef input = matcher.Ref(broker).AsString();
    return input.length();
142 143 144 145 146 147 148 149 150 151 152 153
  }

  NumberMatcher number_matcher(node);
  if (number_matcher.HasValue()) {
    return kBase10MaximalLength + 1;
  }

  // We don't support objects with possibly monkey-patched prototype.toString
  // as it might have side-effects, so we shouldn't attempt lowering them.
  return base::nullopt;
}

154 155 156 157 158 159
Reduction JSNativeContextSpecialization::ReduceJSToString(Node* node) {
  DCHECK_EQ(IrOpcode::kJSToString, node->opcode());
  Node* const input = node->InputAt(0);
  Reduction reduction;

  HeapObjectMatcher matcher(input);
160
  if (matcher.HasValue() && matcher.Ref(broker()).IsString()) {
161 162 163 164 165 166 167 168 169 170 171
    reduction = Changed(input);  // JSToString(x:string) => x
    ReplaceWithValue(node, reduction.replacement());
    return reduction;
  }

  // TODO(turbofan): This optimization is weaker than what we used to have
  // in js-typed-lowering for OrderedNumbers. We don't have types here though,
  // so alternative approach should be designed if this causes performance
  // regressions and the stronger optimization should be re-implemented.
  NumberMatcher number_matcher(input);
  if (number_matcher.HasValue()) {
172 173 174 175
    const StringConstantBase* base =
        new (shared_zone()) NumberToStringConstant(number_matcher.Value());
    reduction =
        Replace(graph()->NewNode(common()->DelayedStringConstant(base)));
176 177 178 179 180 181 182
    ReplaceWithValue(node, reduction.replacement());
    return reduction;
  }

  return NoChange();
}

183 184 185 186 187 188 189 190 191 192
const StringConstantBase*
JSNativeContextSpecialization::CreateDelayedStringConstant(Node* node) {
  if (node->opcode() == IrOpcode::kDelayedStringConstant) {
    return StringConstantBaseOf(node->op());
  } else {
    NumberMatcher number_matcher(node);
    if (number_matcher.HasValue()) {
      return new (shared_zone()) NumberToStringConstant(number_matcher.Value());
    } else {
      HeapObjectMatcher matcher(node);
193 194
      if (matcher.HasValue() && matcher.Ref(broker()).IsString()) {
        StringRef s = matcher.Ref(broker()).AsString();
195
        return new (shared_zone())
196
            StringLiteral(s.object(), static_cast<size_t>(s.length()));
197 198 199 200 201 202 203
      } else {
        UNREACHABLE();
      }
    }
  }
}

204 205
namespace {
bool IsStringConstant(JSHeapBroker* broker, Node* node) {
206 207 208 209 210
  if (node->opcode() == IrOpcode::kDelayedStringConstant) {
    return true;
  }

  HeapObjectMatcher matcher(node);
211 212
  return matcher.HasValue() && matcher.Ref(broker).IsString();
}
213
}  // namespace
214

215 216 217 218 219 220
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionEnter(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSAsyncFunctionEnter, node->opcode());
  Node* closure = NodeProperties::GetValueInput(node, 0);
  Node* receiver = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
221
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
222 223 224
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

225
  if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
226

227 228 229 230 231 232
  // Create the promise for the async function.
  Node* promise = effect =
      graph()->NewNode(javascript()->CreatePromise(), context, effect);

  // Create the JSAsyncFunctionObject based on the SharedFunctionInfo
  // extracted from the top-most frame in {frame_state}.
233 234 235 236 237 238
  SharedFunctionInfoRef shared(
      broker(),
      FrameStateInfoOf(frame_state->op()).shared_info().ToHandleChecked());
  DCHECK(shared.is_compiled());
  int register_count = shared.internal_formal_parameter_count() +
                       shared.GetBytecodeArray().register_count();
239 240 241 242 243
  Node* value = effect =
      graph()->NewNode(javascript()->CreateAsyncFunctionObject(register_count),
                       closure, receiver, promise, context, effect, control);
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
244 245 246 247 248
}

Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionReject(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSAsyncFunctionReject, node->opcode());
249
  Node* async_function_object = NodeProperties::GetValueInput(node, 0);
250 251 252 253 254 255
  Node* reason = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

256
  if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
257

258 259 260 261 262
  // Load the promise from the {async_function_object}.
  Node* promise = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
      async_function_object, effect, control);

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  // Create a nested frame state inside the current method's most-recent
  // {frame_state} that will ensure that lazy deoptimizations at this
  // point will still return the {promise} instead of the result of the
  // JSRejectPromise operation (which yields undefined).
  Node* parameters[] = {promise};
  frame_state = CreateStubBuiltinContinuationFrameState(
      jsgraph(), Builtins::kAsyncFunctionLazyDeoptContinuation, context,
      parameters, arraysize(parameters), frame_state,
      ContinuationFrameStateMode::LAZY);

  // Disable the additional debug event for the rejection since a
  // debug event already happend for the exception that got us here.
  Node* debug_event = jsgraph()->FalseConstant();
  effect = graph()->NewNode(javascript()->RejectPromise(), promise, reason,
                            debug_event, context, frame_state, effect, control);
  ReplaceWithValue(node, promise, effect, control);
  return Replace(promise);
}

Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionResolve(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSAsyncFunctionResolve, node->opcode());
285
  Node* async_function_object = NodeProperties::GetValueInput(node, 0);
286 287 288 289 290 291
  Node* value = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

292
  if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
293 294 295 296 297

  // Load the promise from the {async_function_object}.
  Node* promise = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
      async_function_object, effect, control);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

  // Create a nested frame state inside the current method's most-recent
  // {frame_state} that will ensure that lazy deoptimizations at this
  // point will still return the {promise} instead of the result of the
  // JSResolvePromise operation (which yields undefined).
  Node* parameters[] = {promise};
  frame_state = CreateStubBuiltinContinuationFrameState(
      jsgraph(), Builtins::kAsyncFunctionLazyDeoptContinuation, context,
      parameters, arraysize(parameters), frame_state,
      ContinuationFrameStateMode::LAZY);

  effect = graph()->NewNode(javascript()->ResolvePromise(), promise, value,
                            context, frame_state, effect, control);
  ReplaceWithValue(node, promise, effect, control);
  return Replace(promise);
}

315 316 317 318 319 320 321
Reduction JSNativeContextSpecialization::ReduceJSAdd(Node* node) {
  // TODO(turbofan): This has to run together with the inlining and
  // native context specialization to be able to leverage the string
  // constant-folding for optimizing property access, but we should
  // nevertheless find a better home for this at some point.
  DCHECK_EQ(IrOpcode::kJSAdd, node->opcode());

322 323 324
  Node* const lhs = node->InputAt(0);
  Node* const rhs = node->InputAt(1);

325 326
  base::Optional<size_t> lhs_len = GetMaxStringLength(broker(), lhs);
  base::Optional<size_t> rhs_len = GetMaxStringLength(broker(), rhs);
327 328
  if (!lhs_len || !rhs_len) {
    return NoChange();
329
  }
330 331 332 333

  // Fold into DelayedStringConstant if at least one of the parameters is a
  // string constant and the addition won't throw due to too long result.
  if (*lhs_len + *rhs_len <= String::kMaxLength &&
334
      (IsStringConstant(broker(), lhs) || IsStringConstant(broker(), rhs))) {
335 336 337 338 339 340 341 342 343 344
    const StringConstantBase* left = CreateDelayedStringConstant(lhs);
    const StringConstantBase* right = CreateDelayedStringConstant(rhs);
    const StringConstantBase* cons =
        new (shared_zone()) StringCons(left, right);

    Node* reduced = graph()->NewNode(common()->DelayedStringConstant(cons));
    ReplaceWithValue(node, reduced);
    return Replace(reduced);
  }

345 346 347
  return NoChange();
}

348 349 350 351 352 353 354 355
Reduction JSNativeContextSpecialization::ReduceJSGetSuperConstructor(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSGetSuperConstructor, node->opcode());
  Node* constructor = NodeProperties::GetValueInput(node, 0);

  // Check if the input is a known JSFunction.
  HeapObjectMatcher m(constructor);
  if (!m.HasValue()) return NoChange();
356
  JSFunctionRef function = m.Ref(broker()).AsJSFunction();
357
  MapRef function_map = function.map();
358
  if (should_disallow_heap_access() && !function_map.serialized_prototype()) {
359
    TRACE_BROKER_MISSING(broker(), "data for map " << function_map);
360 361
    return NoChange();
  }
362
  ObjectRef function_prototype = function_map.prototype();
363 364 365 366

  // We can constant-fold the super constructor access if the
  // {function}s map is stable, i.e. we can use a code dependency
  // to guard against [[Prototype]] changes of {function}.
367 368 369
  if (function_map.is_stable() && function_prototype.IsHeapObject() &&
      function_prototype.AsHeapObject().map().is_constructor()) {
    dependencies()->DependOnStableMap(function_map);
370 371 372
    Node* value = jsgraph()->Constant(function_prototype);
    ReplaceWithValue(node, value);
    return Replace(value);
373 374 375 376 377
  }

  return NoChange();
}

378 379
Reduction JSNativeContextSpecialization::ReduceJSInstanceOf(Node* node) {
  DCHECK_EQ(IrOpcode::kJSInstanceOf, node->opcode());
380
  FeedbackParameter const& p = FeedbackParameterOf(node->op());
381 382 383 384
  Node* object = NodeProperties::GetValueInput(node, 0);
  Node* constructor = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
385
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
386 387
  Node* control = NodeProperties::GetControlInput(node);

388 389 390
  // Check if the right hand side is a known {receiver}, or
  // we have feedback from the InstanceOfIC.
  Handle<JSObject> receiver;
391
  HeapObjectMatcher m(constructor);
392 393
  if (m.HasValue() && m.Ref(broker()).IsJSObject()) {
    receiver = m.Ref(broker()).AsJSObject().object();
394
  } else if (p.feedback().IsValid()) {
395 396 397 398 399 400 401
    ProcessedFeedback const& feedback =
        broker()->GetFeedbackForInstanceOf(FeedbackSource(p.feedback()));
    if (feedback.IsInsufficient()) return NoChange();
    base::Optional<JSObjectRef> maybe_receiver =
        feedback.AsInstanceOf().value();
    if (!maybe_receiver.has_value()) return NoChange();
    receiver = maybe_receiver->object();
402 403 404
  } else {
    return NoChange();
  }
405 406 407 408 409

  JSObjectRef receiver_ref(broker(), receiver);
  MapRef receiver_map = receiver_ref.map();

  PropertyAccessInfo access_info = PropertyAccessInfo::Invalid(graph()->zone());
410
  if (should_disallow_heap_access()) {
411 412 413 414
    access_info = broker()->GetPropertyAccessInfo(
        receiver_map,
        NameRef(broker(), isolate()->factory()->has_instance_symbol()),
        AccessMode::kLoad);
415 416 417 418 419 420 421 422
  } else {
    AccessInfoFactory access_info_factory(broker(), dependencies(),
                                          graph()->zone());
    access_info = access_info_factory.ComputePropertyAccessInfo(
        receiver_map.object(), factory()->has_instance_symbol(),
        AccessMode::kLoad);
  }

423
  if (access_info.IsInvalid()) return NoChange();
424
  access_info.RecordDependencies(dependencies());
425

426
  PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
427

428 429
  if (access_info.IsNotFound()) {
    // If there's no @@hasInstance handler, the OrdinaryHasInstance operation
430
    // takes over, but that requires the constructor to be callable.
431
    if (!receiver_map.is_callable()) return NoChange();
432

433 434
    dependencies()->DependOnStablePrototypeChains(access_info.receiver_maps(),
                                                  kStartAtPrototype);
435 436 437 438 439 440 441 442 443 444

    // Monomorphic property access.
    access_builder.BuildCheckMaps(constructor, &effect, control,
                                  access_info.receiver_maps());

    // Lower to OrdinaryHasInstance(C, O).
    NodeProperties::ReplaceValueInput(node, constructor, 0);
    NodeProperties::ReplaceValueInput(node, object, 1);
    NodeProperties::ReplaceEffectInput(node, effect);
    NodeProperties::ChangeOp(node, javascript()->OrdinaryHasInstance());
445
    return Changed(node).FollowedBy(ReduceJSOrdinaryHasInstance(node));
446 447
  }

448
  if (access_info.IsDataConstant()) {
449
    Handle<JSObject> holder;
450
    bool found_on_proto = access_info.holder().ToHandle(&holder);
451 452 453 454 455 456
    JSObjectRef holder_ref =
        found_on_proto ? JSObjectRef(broker(), holder) : receiver_ref;
    base::Optional<ObjectRef> constant = holder_ref.GetOwnDataProperty(
        access_info.field_representation(), access_info.field_index());
    if (!constant.has_value() || !constant->IsHeapObject() ||
        !constant->AsHeapObject().map().is_callable())
457
      return NoChange();
458 459 460

    if (found_on_proto) {
      dependencies()->DependOnStablePrototypeChains(
461 462
          access_info.receiver_maps(), kStartAtPrototype,
          JSObjectRef(broker(), holder));
463
    }
464

465 466 467 468
    // Check that {constructor} is actually {receiver}.
    constructor =
        access_builder.BuildCheckValue(constructor, &effect, control, receiver);

469
    // Monomorphic property access.
470 471
    access_builder.BuildCheckMaps(constructor, &effect, control,
                                  access_info.receiver_maps());
472

473 474 475 476 477 478 479 480 481 482
    // Create a nested frame state inside the current method's most-recent frame
    // state that will ensure that deopts that happen after this point will not
    // fallback to the last Checkpoint--which would completely re-execute the
    // instanceof logic--but rather create an activation of a version of the
    // ToBoolean stub that finishes the remaining work of instanceof and returns
    // to the caller without duplicating side-effects upon a lazy deopt.
    Node* continuation_frame_state = CreateStubBuiltinContinuationFrameState(
        jsgraph(), Builtins::kToBooleanLazyDeoptContinuation, context, nullptr,
        0, frame_state, ContinuationFrameStateMode::LAZY);

483
    // Call the @@hasInstance handler.
484
    Node* target = jsgraph()->Constant(*constant);
485 486 487
    node->InsertInput(graph()->zone(), 0, target);
    node->ReplaceInput(1, constructor);
    node->ReplaceInput(2, object);
488
    node->ReplaceInput(4, continuation_frame_state);
489
    node->ReplaceInput(5, effect);
490
    NodeProperties::ChangeOp(
491
        node, javascript()->Call(3, CallFrequency(), FeedbackSource(),
492
                                 ConvertReceiverMode::kNotNullOrUndefined));
493 494

    // Rewire the value uses of {node} to ToBoolean conversion of the result.
495
    Node* value = graph()->NewNode(simplified()->ToBoolean(), node);
496 497 498 499 500 501 502 503 504 505 506 507
    for (Edge edge : node->use_edges()) {
      if (NodeProperties::IsValueEdge(edge) && edge.from() != value) {
        edge.UpdateTo(value);
        Revisit(edge.from());
      }
    }
    return Changed(node);
  }

  return NoChange();
}

508 509
JSNativeContextSpecialization::InferHasInPrototypeChainResult
JSNativeContextSpecialization::InferHasInPrototypeChain(
510
    Node* receiver, Node* effect, HeapObjectRef const& prototype) {
511 512
  ZoneHandleSet<Map> receiver_maps;
  NodeProperties::InferReceiverMapsResult result =
513 514
      NodeProperties::InferReceiverMapsUnsafe(broker(), receiver, effect,
                                              &receiver_maps);
515 516
  if (result == NodeProperties::kNoReceiverMaps) return kMayBeInPrototypeChain;

517 518 519
  // Try to determine either that all of the {receiver_maps} have the given
  // {prototype} in their chain, or that none do. If we can't tell, return
  // kMayBeInPrototypeChain.
520 521 522
  bool all = true;
  bool none = true;
  for (size_t i = 0; i < receiver_maps.size(); ++i) {
523
    MapRef map(broker(), receiver_maps[i]);
524 525 526
    if (result == NodeProperties::kUnreliableReceiverMaps && !map.is_stable()) {
      return kMayBeInPrototypeChain;
    }
527 528 529 530 531
    while (true) {
      if (IsSpecialReceiverInstanceType(map.instance_type())) {
        return kMayBeInPrototypeChain;
      }
      if (!map.IsJSObjectMap()) {
532 533 534
        all = false;
        break;
      }
535
      if (should_disallow_heap_access() && !map.serialized_prototype()) {
536 537 538 539
        TRACE_BROKER_MISSING(broker(), "prototype data for map " << map);
        return kMayBeInPrototypeChain;
      }
      if (map.prototype().equals(prototype)) {
540 541 542
        none = false;
        break;
      }
543
      map = map.prototype().map();
544
      if (!map.is_stable()) return kMayBeInPrototypeChain;
545 546 547
      if (map.oddball_type() == OddballType::kNull) {
        all = false;
        break;
548 549 550 551
      }
    }
  }
  DCHECK_IMPLIES(all, !none);
552 553 554 555 556
  if (!all && !none) return kMayBeInPrototypeChain;

  {
    base::Optional<JSObjectRef> last_prototype;
    if (all) {
557 558 559 560 561 562
      // We don't need to protect the full chain if we found the prototype, we
      // can stop at {prototype}.  In fact we could stop at the one before
      // {prototype} but since we're dealing with multiple receiver maps this
      // might be a different object each time, so it's much simpler to include
      // {prototype}. That does, however, mean that we must check {prototype}'s
      // map stability.
563 564
      if (!prototype.map().is_stable()) return kMayBeInPrototypeChain;
      last_prototype = prototype.AsJSObject();
565 566 567 568 569 570 571
    }
    WhereToStart start = result == NodeProperties::kUnreliableReceiverMaps
                             ? kStartAtReceiver
                             : kStartAtPrototype;
    dependencies()->DependOnStablePrototypeChains(receiver_maps, start,
                                                  last_prototype);
  }
572

573 574
  DCHECK_EQ(all, !none);
  return all ? kIsInPrototypeChain : kIsNotInPrototypeChain;
575 576 577 578 579 580 581 582 583 584 585 586 587 588
}

Reduction JSNativeContextSpecialization::ReduceJSHasInPrototypeChain(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSHasInPrototypeChain, node->opcode());
  Node* value = NodeProperties::GetValueInput(node, 0);
  Node* prototype = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);

  // Check if we can constant-fold the prototype chain walk
  // for the given {value} and the {prototype}.
  HeapObjectMatcher m(prototype);
  if (m.HasValue()) {
    InferHasInPrototypeChainResult result =
589
        InferHasInPrototypeChain(value, effect, m.Ref(broker()));
590 591 592 593 594 595 596 597 598 599
    if (result != kMayBeInPrototypeChain) {
      Node* value = jsgraph()->BooleanConstant(result == kIsInPrototypeChain);
      ReplaceWithValue(node, value);
      return Replace(value);
    }
  }

  return NoChange();
}

600 601 602 603 604 605
Reduction JSNativeContextSpecialization::ReduceJSOrdinaryHasInstance(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSOrdinaryHasInstance, node->opcode());
  Node* constructor = NodeProperties::GetValueInput(node, 0);
  Node* object = NodeProperties::GetValueInput(node, 1);

606
  // Check if the {constructor} is known at compile time.
607
  HeapObjectMatcher m(constructor);
608 609
  if (!m.HasValue()) return NoChange();

610 611 612 613
  if (m.Ref(broker()).IsJSBoundFunction()) {
    // OrdinaryHasInstance on bound functions turns into a recursive invocation
    // of the instanceof operator again.
    JSBoundFunctionRef function = m.Ref(broker()).AsJSBoundFunction();
614
    if (should_disallow_heap_access() && !function.serialized()) {
615
      TRACE_BROKER_MISSING(broker(), "data for JSBoundFunction " << function);
616 617 618 619 620
      return NoChange();
    }

    JSReceiverRef bound_target_function = function.bound_target_function();

621 622
    NodeProperties::ReplaceValueInput(node, object, 0);
    NodeProperties::ReplaceValueInput(
623
        node, jsgraph()->Constant(bound_target_function), 1);
624
    NodeProperties::ChangeOp(node, javascript()->InstanceOf(FeedbackSource()));
625
    return Changed(node).FollowedBy(ReduceJSInstanceOf(node));
626 627
  }

628 629 630
  if (m.Ref(broker()).IsJSFunction()) {
    // Optimize if we currently know the "prototype" property.

631
    JSFunctionRef function = m.Ref(broker()).AsJSFunction();
632
    if (should_disallow_heap_access() && !function.serialized()) {
633
      TRACE_BROKER_MISSING(broker(), "data for JSFunction " << function);
634 635 636
      return NoChange();
    }

637 638 639 640 641
    // TODO(neis): Remove the has_prototype_slot condition once the broker is
    // always enabled.
    if (!function.map().has_prototype_slot() || !function.has_prototype() ||
        function.PrototypeRequiresRuntimeLookup()) {
      return NoChange();
642
    }
643

644 645 646 647 648 649 650
    ObjectRef prototype = dependencies()->DependOnPrototypeProperty(function);
    Node* prototype_constant = jsgraph()->Constant(prototype);

    // Lower the {node} to JSHasInPrototypeChain.
    NodeProperties::ReplaceValueInput(node, object, 0);
    NodeProperties::ReplaceValueInput(node, prototype_constant, 1);
    NodeProperties::ChangeOp(node, javascript()->HasInPrototypeChain());
651
    return Changed(node).FollowedBy(ReduceJSHasInPrototypeChain(node));
652 653
  }

654 655 656
  return NoChange();
}

657 658 659 660 661 662 663 664 665 666 667 668
// ES section #sec-promise-resolve
Reduction JSNativeContextSpecialization::ReduceJSPromiseResolve(Node* node) {
  DCHECK_EQ(IrOpcode::kJSPromiseResolve, node->opcode());
  Node* constructor = NodeProperties::GetValueInput(node, 0);
  Node* value = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Check if the {constructor} is the %Promise% function.
  HeapObjectMatcher m(constructor);
669
  if (!m.HasValue() ||
670
      !m.Ref(broker()).equals(native_context().promise_function())) {
671
    return NoChange();
672
  }
673

674 675 676 677 678
  // Only optimize if {value} cannot be a JSPromise.
  MapInference inference(broker(), value, effect);
  if (!inference.HaveMaps() ||
      inference.AnyOfInstanceTypesAre(JS_PROMISE_TYPE)) {
    return NoChange();
679 680
  }

681
  if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
  // Create a %Promise% instance and resolve it with {value}.
  Node* promise = effect =
      graph()->NewNode(javascript()->CreatePromise(), context, effect);
  effect = graph()->NewNode(javascript()->ResolvePromise(), promise, value,
                            context, frame_state, effect, control);
  ReplaceWithValue(node, promise, effect, control);
  return Replace(promise);
}

// ES section #sec-promise-resolve-functions
Reduction JSNativeContextSpecialization::ReduceJSResolvePromise(Node* node) {
  DCHECK_EQ(IrOpcode::kJSResolvePromise, node->opcode());
  Node* promise = NodeProperties::GetValueInput(node, 0);
  Node* resolution = NodeProperties::GetValueInput(node, 1);
  Node* context = NodeProperties::GetContextInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Check if we know something about the {resolution}.
702 703 704
  MapInference inference(broker(), resolution, effect);
  if (!inference.HaveMaps()) return NoChange();
  MapHandles const& resolution_maps = inference.GetMaps();
705

706
  // Compute property access info for "then" on {resolution}.
707 708 709
  ZoneVector<PropertyAccessInfo> access_infos(graph()->zone());
  AccessInfoFactory access_info_factory(broker(), dependencies(),
                                        graph()->zone());
710
  if (!should_disallow_heap_access()) {
711 712 713 714 715 716 717
    access_info_factory.ComputePropertyAccessInfos(
        resolution_maps, factory()->then_string(), AccessMode::kLoad,
        &access_infos);
  } else {
    // Obtain pre-computed access infos from the broker.
    for (auto map : resolution_maps) {
      MapRef map_ref(broker(), map);
718 719 720
      access_infos.push_back(broker()->GetPropertyAccessInfo(
          map_ref, NameRef(broker(), isolate()->factory()->then_string()),
          AccessMode::kLoad));
721 722
    }
  }
723 724 725
  PropertyAccessInfo access_info =
      access_info_factory.FinalizePropertyAccessInfosAsOne(access_infos,
                                                           AccessMode::kLoad);
726 727 728 729
  if (access_info.IsInvalid()) return inference.NoChange();

  // Only optimize when {resolution} definitely doesn't have a "then" property.
  if (!access_info.IsNotFound()) return inference.NoChange();
730

731 732 733
  if (!inference.RelyOnMapsViaStability(dependencies())) {
    return inference.NoChange();
  }
734

735 736
  dependencies()->DependOnStablePrototypeChains(access_info.receiver_maps(),
                                                kStartAtPrototype);
737

738 739 740 741 742 743 744 745
  // Simply fulfill the {promise} with the {resolution}.
  Node* value = effect =
      graph()->NewNode(javascript()->FulfillPromise(), promise, resolution,
                       context, effect, control);
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
}

746 747 748
namespace {

FieldAccess ForPropertyCellValue(MachineRepresentation representation,
749
                                 Type type, MaybeHandle<Map> map,
750
                                 NameRef const& name) {
751
  WriteBarrierKind kind = kFullWriteBarrier;
752
  if (representation == MachineRepresentation::kTaggedSigned) {
753
    kind = kNoWriteBarrier;
754
  } else if (representation == MachineRepresentation::kTaggedPointer) {
755 756 757 758
    kind = kPointerWriteBarrier;
  }
  MachineType r = MachineType::TypeForRepresentation(representation);
  FieldAccess access = {
759 760
      kTaggedBase, PropertyCell::kValueOffset, name.object(), map, type, r,
      kind};
761 762 763 764 765 766
  return access;
}

}  // namespace

Reduction JSNativeContextSpecialization::ReduceGlobalAccess(
767
    Node* node, Node* receiver, Node* value, NameRef const& name,
768
    AccessMode access_mode, Node* key) {
769
  base::Optional<PropertyCellRef> cell =
770
      native_context().global_object().GetPropertyCell(name);
771
  return cell.has_value() ? ReduceGlobalAccess(node, receiver, value, name,
772
                                               access_mode, key, *cell)
773
                          : NoChange();
774 775
}

776 777 778
// TODO(neis): Try to merge this with ReduceNamedAccess by introducing a new
// PropertyAccessInfo kind for global accesses and using the existing mechanism
// for building loads/stores.
779
Reduction JSNativeContextSpecialization::ReduceGlobalAccess(
780
    Node* node, Node* receiver, Node* value, NameRef const& name,
781
    AccessMode access_mode, Node* key, PropertyCellRef const& property_cell) {
782 783 784
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

785 786 787 788
  ObjectRef property_cell_value = property_cell.value();
  if (property_cell_value.IsHeapObject() &&
      property_cell_value.AsHeapObject().map().oddball_type() ==
          OddballType::kHole) {
789 790 791 792
    // The property cell is no longer valid.
    return NoChange();
  }

793
  PropertyDetails property_details = property_cell.property_details();
794
  PropertyCellType property_cell_type = property_details.cell_type();
795
  DCHECK_EQ(kData, property_details.kind());
796 797 798 799 800 801 802 803 804 805 806 807

  // We have additional constraints for stores.
  if (access_mode == AccessMode::kStore) {
    if (property_details.IsReadOnly()) {
      // Don't even bother trying to lower stores to read-only data properties.
      return NoChange();
    } else if (property_cell_type == PropertyCellType::kUndefined) {
      // There's no fast-path for dealing with undefined property cells.
      return NoChange();
    } else if (property_cell_type == PropertyCellType::kConstantType) {
      // There's also no fast-path to store to a global cell which pretended
      // to be stable, but is no longer stable now.
808 809
      if (property_cell_value.IsHeapObject() &&
          !property_cell_value.AsHeapObject().map().is_stable()) {
810 811 812
        return NoChange();
      }
    }
813 814 815 816 817 818 819
  } else if (access_mode == AccessMode::kHas) {
    // has checks cannot follow the fast-path used by loads when these
    // conditions hold.
    if ((property_details.IsConfigurable() || !property_details.IsReadOnly()) &&
        property_details.cell_type() != PropertyCellType::kConstant &&
        property_details.cell_type() != PropertyCellType::kUndefined)
      return NoChange();
820 821
  }

822 823 824
  // Ensure that {key} matches the specified {name} (if {key} is given).
  if (key != nullptr) {
    effect = BuildCheckEqualsName(name, key, effect, control);
825 826
  }

827 828 829
  // If we have a {receiver} to validate, we do so by checking that its map is
  // the (target) global proxy's map. This guarantees that in fact the receiver
  // is the global proxy.
830
  if (receiver != nullptr) {
831
    effect = graph()->NewNode(
832 833 834 835 836
        simplified()->CheckMaps(
            CheckMapsFlag::kNone,
            ZoneHandleSet<Map>(
                HeapObjectRef(broker(), global_proxy()).map().object())),
        receiver, effect, control);
837 838
  }

839
  if (access_mode == AccessMode::kLoad || access_mode == AccessMode::kHas) {
840 841 842
    // Load from non-configurable, read-only data property on the global
    // object can be constant-folded, even without deoptimization support.
    if (!property_details.IsConfigurable() && property_details.IsReadOnly()) {
843 844 845
      value = access_mode == AccessMode::kHas
                  ? jsgraph()->TrueConstant()
                  : jsgraph()->Constant(property_cell_value);
846 847 848 849 850 851
    } else {
      // Record a code dependency on the cell if we can benefit from the
      // additional feedback, or the global property is configurable (i.e.
      // can be deleted or reconfigured to an accessor property).
      if (property_details.cell_type() != PropertyCellType::kMutable ||
          property_details.IsConfigurable()) {
852
        dependencies()->DependOnGlobalProperty(property_cell);
853 854 855 856 857
      }

      // Load from constant/undefined global property can be constant-folded.
      if (property_details.cell_type() == PropertyCellType::kConstant ||
          property_details.cell_type() == PropertyCellType::kUndefined) {
858 859 860
        value = access_mode == AccessMode::kHas
                    ? jsgraph()->TrueConstant()
                    : jsgraph()->Constant(property_cell_value);
861 862 863
        DCHECK(!property_cell_value.IsHeapObject() ||
               property_cell_value.AsHeapObject().map().oddball_type() !=
                   OddballType::kHole);
864
      } else {
865 866
        DCHECK_NE(AccessMode::kHas, access_mode);

867 868
        // Load from constant type cell can benefit from type feedback.
        MaybeHandle<Map> map;
869
        Type property_cell_value_type = Type::NonInternal();
870
        MachineRepresentation representation = MachineRepresentation::kTagged;
871 872
        if (property_details.cell_type() == PropertyCellType::kConstantType) {
          // Compute proper type based on the current value in the cell.
873
          if (property_cell_value.IsSmi()) {
874
            property_cell_value_type = Type::SignedSmall();
875
            representation = MachineRepresentation::kTaggedSigned;
876
          } else if (property_cell_value.IsHeapNumber()) {
877
            property_cell_value_type = Type::Number();
878
            representation = MachineRepresentation::kTaggedPointer;
879
          } else {
880 881
            MapRef property_cell_value_map =
                property_cell_value.AsHeapObject().map();
882
            property_cell_value_type = Type::For(property_cell_value_map);
883
            representation = MachineRepresentation::kTaggedPointer;
884 885 886 887

            // We can only use the property cell value map for map check
            // elimination if it's stable, i.e. the HeapObject wasn't
            // mutated without the cell state being updated.
888 889
            if (property_cell_value_map.is_stable()) {
              dependencies()->DependOnStableMap(property_cell_value_map);
890
              map = property_cell_value_map.object();
891 892 893 894 895 896
            }
          }
        }
        value = effect = graph()->NewNode(
            simplified()->LoadField(ForPropertyCellValue(
                representation, property_cell_value_type, map, name)),
897
            jsgraph()->Constant(property_cell), effect, control);
898 899 900 901 902 903 904 905 906 907 908 909 910
      }
    }
  } else {
    DCHECK_EQ(AccessMode::kStore, access_mode);
    DCHECK(!property_details.IsReadOnly());
    switch (property_details.cell_type()) {
      case PropertyCellType::kUndefined: {
        UNREACHABLE();
        break;
      }
      case PropertyCellType::kConstant: {
        // Record a code dependency on the cell, and just deoptimize if the new
        // value doesn't match the previous value stored inside the cell.
911
        dependencies()->DependOnGlobalProperty(property_cell);
912 913 914
        Node* check =
            graph()->NewNode(simplified()->ReferenceEqual(), value,
                             jsgraph()->Constant(property_cell_value));
915 916 917
        effect = graph()->NewNode(
            simplified()->CheckIf(DeoptimizeReason::kValueMismatch), check,
            effect, control);
918 919 920 921 922 923
        break;
      }
      case PropertyCellType::kConstantType: {
        // Record a code dependency on the cell, and just deoptimize if the new
        // values' type doesn't match the type of the previous value in the
        // cell.
924
        dependencies()->DependOnGlobalProperty(property_cell);
925
        Type property_cell_value_type;
926
        MachineRepresentation representation = MachineRepresentation::kTagged;
927
        if (property_cell_value.IsHeapObject()) {
928 929
          // We cannot do anything if the {property_cell_value}s map is no
          // longer stable.
930 931 932
          MapRef property_cell_value_map =
              property_cell_value.AsHeapObject().map();
          dependencies()->DependOnStableMap(property_cell_value_map);
933 934 935 936 937

          // Check that the {value} is a HeapObject.
          value = effect = graph()->NewNode(simplified()->CheckHeapObject(),
                                            value, effect, control);

938
          // Check {value} map against the {property_cell} map.
939 940 941 942 943
          effect = graph()->NewNode(
              simplified()->CheckMaps(
                  CheckMapsFlag::kNone,
                  ZoneHandleSet<Map>(property_cell_value_map.object())),
              value, effect, control);
944
          property_cell_value_type = Type::OtherInternal();
945
          representation = MachineRepresentation::kTaggedPointer;
946 947
        } else {
          // Check that the {value} is a Smi.
948
          value = effect = graph()->NewNode(
949
              simplified()->CheckSmi(FeedbackSource()), value, effect, control);
950
          property_cell_value_type = Type::SignedSmall();
951
          representation = MachineRepresentation::kTaggedSigned;
952 953 954 955
        }
        effect = graph()->NewNode(simplified()->StoreField(ForPropertyCellValue(
                                      representation, property_cell_value_type,
                                      MaybeHandle<Map>(), name)),
956
                                  jsgraph()->Constant(property_cell), value,
957 958 959 960 961 962
                                  effect, control);
        break;
      }
      case PropertyCellType::kMutable: {
        // Record a code dependency on the cell, and just deoptimize if the
        // property ever becomes read-only.
963
        dependencies()->DependOnGlobalProperty(property_cell);
964 965
        effect = graph()->NewNode(
            simplified()->StoreField(ForPropertyCellValue(
966
                MachineRepresentation::kTagged, Type::NonInternal(),
967
                MaybeHandle<Map>(), name)),
968
            jsgraph()->Constant(property_cell), value, effect, control);
969 970 971 972 973 974 975 976 977 978
        break;
      }
    }
  }

  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
}

Reduction JSNativeContextSpecialization::ReduceJSLoadGlobal(Node* node) {
979
  DCHECK_EQ(IrOpcode::kJSLoadGlobal, node->opcode());
980 981
  LoadGlobalParameters const& p = LoadGlobalParametersOf(node->op());
  if (!p.feedback().IsValid()) return NoChange();
982

983 984 985
  ProcessedFeedback const& processed =
      broker()->GetFeedbackForGlobalAccess(FeedbackSource(p.feedback()));
  if (processed.IsInsufficient()) return NoChange();
986

987 988
  GlobalAccessFeedback const& feedback = processed.AsGlobalAccess();
  if (feedback.IsScriptContextSlot()) {
989
    Node* effect = NodeProperties::GetEffectInput(node);
990
    Node* script_context = jsgraph()->Constant(feedback.script_context());
991
    Node* value = effect =
992 993
        graph()->NewNode(javascript()->LoadContext(0, feedback.slot_index(),
                                                   feedback.immutable()),
994
                         script_context, effect);
995 996
    ReplaceWithValue(node, value, effect);
    return Replace(value);
997 998 999 1000 1001 1002 1003
  } else if (feedback.IsPropertyCell()) {
    return ReduceGlobalAccess(node, nullptr, nullptr,
                              NameRef(broker(), p.name()), AccessMode::kLoad,
                              nullptr, feedback.property_cell());
  } else {
    DCHECK(feedback.IsMegamorphic());
    return NoChange();
1004 1005 1006 1007
  }
}

Reduction JSNativeContextSpecialization::ReduceJSStoreGlobal(Node* node) {
1008
  DCHECK_EQ(IrOpcode::kJSStoreGlobal, node->opcode());
1009
  Node* value = NodeProperties::GetValueInput(node, 0);
1010 1011
  StoreGlobalParameters const& p = StoreGlobalParametersOf(node->op());
  if (!p.feedback().IsValid()) return NoChange();
1012

1013 1014 1015
  ProcessedFeedback const& processed =
      broker()->GetFeedbackForGlobalAccess(FeedbackSource(p.feedback()));
  if (processed.IsInsufficient()) return NoChange();
1016

1017 1018 1019
  GlobalAccessFeedback const& feedback = processed.AsGlobalAccess();
  if (feedback.IsScriptContextSlot()) {
    if (feedback.immutable()) return NoChange();
1020 1021
    Node* effect = NodeProperties::GetEffectInput(node);
    Node* control = NodeProperties::GetControlInput(node);
1022
    Node* script_context = jsgraph()->Constant(feedback.script_context());
1023
    effect =
1024
        graph()->NewNode(javascript()->StoreContext(0, feedback.slot_index()),
1025
                         value, script_context, effect, control);
1026 1027
    ReplaceWithValue(node, value, effect, control);
    return Replace(value);
1028
  } else if (feedback.IsPropertyCell()) {
1029 1030
    return ReduceGlobalAccess(node, nullptr, value, NameRef(broker(), p.name()),
                              AccessMode::kStore, nullptr,
1031 1032 1033 1034
                              feedback.property_cell());
  } else {
    DCHECK(feedback.IsMegamorphic());
    return NoChange();
1035
  }
1036
}
1037

1038
Reduction JSNativeContextSpecialization::ReduceNamedAccess(
1039 1040
    Node* node, Node* value, NamedAccessFeedback const& feedback,
    AccessMode access_mode, Node* key) {
1041
  DCHECK(node->opcode() == IrOpcode::kJSLoadNamed ||
1042 1043
         node->opcode() == IrOpcode::kJSStoreNamed ||
         node->opcode() == IrOpcode::kJSLoadProperty ||
1044
         node->opcode() == IrOpcode::kJSStoreProperty ||
1045
         node->opcode() == IrOpcode::kJSStoreNamedOwn ||
1046
         node->opcode() == IrOpcode::kJSStoreDataPropertyInLiteral ||
1047
         node->opcode() == IrOpcode::kJSHasProperty);
1048
  Node* receiver = NodeProperties::GetValueInput(node, 0);
1049
  Node* context = NodeProperties::GetContextInput(node);
1050
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
1051 1052 1053
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

1054 1055 1056 1057
  // Either infer maps from the graph or use the feedback.
  ZoneVector<Handle<Map>> receiver_maps(zone());
  if (!InferReceiverMaps(receiver, effect, &receiver_maps)) {
    receiver_maps = feedback.maps();
1058
  }
1059
  RemoveImpossibleReceiverMaps(receiver, &receiver_maps);
1060

1061 1062 1063 1064 1065
  // Check if we have an access o.x or o.x=v where o is the target native
  // contexts' global proxy, and turn that into a direct access to the
  // corresponding global object instead.
  if (receiver_maps.size() == 1) {
    MapRef receiver_map(broker(), receiver_maps[0]);
1066 1067 1068
    if (receiver_map.equals(
            broker()->target_native_context().global_proxy_object().map()) &&
        !broker()->target_native_context().global_object().IsDetached()) {
1069 1070
      return ReduceGlobalAccess(node, receiver, value, feedback.name(),
                                access_mode, key);
1071 1072 1073
    }
  }

1074 1075 1076 1077 1078 1079 1080 1081
  ZoneVector<PropertyAccessInfo> access_infos(zone());
  {
    ZoneVector<PropertyAccessInfo> access_infos_for_feedback(zone());
    for (Handle<Map> map_handle : receiver_maps) {
      MapRef map(broker(), map_handle);
      if (map.is_deprecated()) continue;
      PropertyAccessInfo access_info = broker()->GetPropertyAccessInfo(
          map, feedback.name(), access_mode, dependencies(),
1082 1083 1084
          should_disallow_heap_access()
              ? SerializationPolicy::kAssumeSerialized
              : SerializationPolicy::kSerializeIfNeeded);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
      access_infos_for_feedback.push_back(access_info);
    }

    AccessInfoFactory access_info_factory(broker(), dependencies(),
                                          graph()->zone());
    if (!access_info_factory.FinalizePropertyAccessInfos(
            access_infos_for_feedback, access_mode, &access_infos)) {
      return NoChange();
    }
  }

1096
  // Ensure that {key} matches the specified name (if {key} is given).
1097
  if (key != nullptr) {
1098
    effect = BuildCheckEqualsName(feedback.name(), key, effect, control);
1099 1100
  }

1101 1102 1103 1104 1105 1106 1107 1108
  // Collect call nodes to rewire exception edges.
  ZoneVector<Node*> if_exception_nodes(zone());
  ZoneVector<Node*>* if_exceptions = nullptr;
  Node* if_exception = nullptr;
  if (NodeProperties::IsExceptionalCall(node, &if_exception)) {
    if_exceptions = &if_exception_nodes;
  }

1109
  PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
1110

1111
  // Check for the monomorphic cases.
1112 1113
  if (access_infos.size() == 1) {
    PropertyAccessInfo access_info = access_infos.front();
1114 1115
    // Try to build string check or number check if possible.
    // Otherwise build a map check.
1116 1117
    if (!access_builder.TryBuildStringCheck(broker(),
                                            access_info.receiver_maps(),
1118
                                            &receiver, &effect, control) &&
1119 1120
        !access_builder.TryBuildNumberCheck(broker(),
                                            access_info.receiver_maps(),
1121
                                            &receiver, &effect, control)) {
1122
      if (HasNumberMaps(broker(), access_info.receiver_maps())) {
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        // We need to also let Smi {receiver}s through in this case, so
        // we construct a diamond, guarded by the Sminess of the {receiver}
        // and if {receiver} is not a Smi just emit a sequence of map checks.
        Node* check = graph()->NewNode(simplified()->ObjectIsSmi(), receiver);
        Node* branch = graph()->NewNode(common()->Branch(), check, control);

        Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
        Node* etrue = effect;

        Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
        Node* efalse = effect;
        {
          access_builder.BuildCheckMaps(receiver, &efalse, if_false,
                                        access_info.receiver_maps());
        }

        control = graph()->NewNode(common()->Merge(2), if_true, if_false);
        effect =
            graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
      } else {
        access_builder.BuildCheckMaps(receiver, &effect, control,
                                      access_info.receiver_maps());
      }
1146
    }
1147

1148
    // Generate the actual property access.
1149
    ValueEffectControl continuation = BuildPropertyAccess(
1150
        receiver, value, context, frame_state, effect, control, feedback.name(),
1151
        if_exceptions, access_info, access_mode);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    value = continuation.value();
    effect = continuation.effect();
    control = continuation.control();
  } else {
    // The final states for every polymorphic branch. We join them with
    // Merge+Phi+EffectPhi at the bottom.
    ZoneVector<Node*> values(zone());
    ZoneVector<Node*> effects(zone());
    ZoneVector<Node*> controls(zone());

    // Check if {receiver} may be a number.
    bool receiverissmi_possible = false;
    for (PropertyAccessInfo const& access_info : access_infos) {
1165
      if (HasNumberMaps(broker(), access_info.receiver_maps())) {
1166 1167
        receiverissmi_possible = true;
        break;
1168
      }
1169 1170
    }

1171
    // Handle the case that {receiver} may be a number.
1172 1173 1174 1175 1176 1177 1178 1179
    Node* receiverissmi_control = nullptr;
    Node* receiverissmi_effect = effect;
    if (receiverissmi_possible) {
      Node* check = graph()->NewNode(simplified()->ObjectIsSmi(), receiver);
      Node* branch = graph()->NewNode(common()->Branch(), check, control);
      control = graph()->NewNode(common()->IfFalse(), branch);
      receiverissmi_control = graph()->NewNode(common()->IfTrue(), branch);
      receiverissmi_effect = effect;
1180 1181
    }

1182 1183 1184 1185 1186 1187 1188
    // Generate code for the various different property access patterns.
    Node* fallthrough_control = control;
    for (size_t j = 0; j < access_infos.size(); ++j) {
      PropertyAccessInfo const& access_info = access_infos[j];
      Node* this_value = value;
      Node* this_receiver = receiver;
      Node* this_effect = effect;
1189
      Node* this_control = fallthrough_control;
1190 1191

      // Perform map check on {receiver}.
1192 1193
      ZoneVector<Handle<Map>> const& receiver_maps =
          access_info.receiver_maps();
1194
      {
1195 1196 1197 1198
        // Whether to insert a dedicated MapGuard node into the
        // effect to be able to learn from the control flow.
        bool insert_map_guard = true;

1199
        // Check maps for the {receiver}s.
1200 1201 1202
        if (j == access_infos.size() - 1) {
          // Last map check on the fallthrough control path, do a
          // conditional eager deoptimization exit here.
1203 1204
          access_builder.BuildCheckMaps(receiver, &this_effect, this_control,
                                        receiver_maps);
1205
          fallthrough_control = nullptr;
1206 1207 1208 1209 1210

          // Don't insert a MapGuard in this case, as the CheckMaps
          // node already gives you all the information you need
          // along the effect chain.
          insert_map_guard = false;
1211
        } else {
1212 1213 1214 1215
          // Explicitly branch on the {receiver_maps}.
          ZoneHandleSet<Map> maps;
          for (Handle<Map> map : receiver_maps) {
            maps.insert(map, graph()->zone());
1216
          }
1217 1218 1219 1220 1221 1222 1223
          Node* check = this_effect =
              graph()->NewNode(simplified()->CompareMaps(maps), receiver,
                               this_effect, this_control);
          Node* branch =
              graph()->NewNode(common()->Branch(), check, this_control);
          fallthrough_control = graph()->NewNode(common()->IfFalse(), branch);
          this_control = graph()->NewNode(common()->IfTrue(), branch);
1224
        }
1225 1226

        // The Number case requires special treatment to also deal with Smis.
1227
        if (HasNumberMaps(broker(), receiver_maps)) {
1228 1229 1230
          // Join this check with the "receiver is smi" check above.
          DCHECK_NOT_NULL(receiverissmi_effect);
          DCHECK_NOT_NULL(receiverissmi_control);
1231 1232 1233 1234
          this_control = graph()->NewNode(common()->Merge(2), this_control,
                                          receiverissmi_control);
          this_effect = graph()->NewNode(common()->EffectPhi(2), this_effect,
                                         receiverissmi_effect, this_control);
1235
          receiverissmi_effect = receiverissmi_control = nullptr;
1236 1237 1238 1239

          // The {receiver} can also be a Smi in this case, so
          // a MapGuard doesn't make sense for this at all.
          insert_map_guard = false;
1240
        }
1241

1242 1243 1244 1245 1246 1247
        // Introduce a MapGuard to learn from this on the effect chain.
        if (insert_map_guard) {
          ZoneHandleSet<Map> maps;
          for (auto receiver_map : receiver_maps) {
            maps.insert(receiver_map, graph()->zone());
          }
1248
          this_effect = graph()->NewNode(simplified()->MapGuard(maps), receiver,
1249 1250
                                         this_effect, this_control);
        }
1251 1252 1253 1254 1255

        // If all {receiver_maps} are Strings we also need to rename the
        // {receiver} here to make sure that TurboFan knows that along this
        // path the {this_receiver} is a String. This is because we want
        // strict checking of types, for example for StringLength operators.
1256
        if (HasOnlyStringMaps(broker(), receiver_maps)) {
1257 1258 1259 1260
          this_receiver = this_effect =
              graph()->NewNode(common()->TypeGuard(Type::String()), receiver,
                               this_effect, this_control);
        }
1261 1262
      }

1263
      // Generate the actual property access.
1264 1265 1266 1267
      ValueEffectControl continuation =
          BuildPropertyAccess(this_receiver, this_value, context, frame_state,
                              this_effect, this_control, feedback.name(),
                              if_exceptions, access_info, access_mode);
1268 1269 1270 1271
      values.push_back(continuation.value());
      effects.push_back(continuation.effect());
      controls.push_back(continuation.control());
    }
1272

1273
    DCHECK_NULL(fallthrough_control);
1274

1275 1276 1277
    // Generate the final merge point for all (polymorphic) branches.
    int const control_count = static_cast<int>(controls.size());
    if (control_count == 0) {
1278
      value = effect = control = jsgraph()->Dead();
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    } else if (control_count == 1) {
      value = values.front();
      effect = effects.front();
      control = controls.front();
    } else {
      control = graph()->NewNode(common()->Merge(control_count), control_count,
                                 &controls.front());
      values.push_back(control);
      value = graph()->NewNode(
          common()->Phi(MachineRepresentation::kTagged, control_count),
          control_count + 1, &values.front());
      effects.push_back(control);
      effect = graph()->NewNode(common()->EffectPhi(control_count),
                                control_count + 1, &effects.front());
    }
1294
  }
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

  // Properly rewire IfException edges if {node} is inside a try-block.
  if (!if_exception_nodes.empty()) {
    DCHECK_NOT_NULL(if_exception);
    DCHECK_EQ(if_exceptions, &if_exception_nodes);
    int const if_exception_count = static_cast<int>(if_exceptions->size());
    Node* merge = graph()->NewNode(common()->Merge(if_exception_count),
                                   if_exception_count, &if_exceptions->front());
    if_exceptions->push_back(merge);
    Node* ephi =
        graph()->NewNode(common()->EffectPhi(if_exception_count),
                         if_exception_count + 1, &if_exceptions->front());
    Node* phi = graph()->NewNode(
        common()->Phi(MachineRepresentation::kTagged, if_exception_count),
        if_exception_count + 1, &if_exceptions->front());
    ReplaceWithValue(if_exception, phi, ephi, merge);
  }

1313 1314
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
1315 1316
}

1317 1318
Reduction JSNativeContextSpecialization::ReduceJSLoadNamed(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadNamed, node->opcode());
1319
  NamedAccess const& p = NamedAccessOf(node->op());
1320
  Node* const receiver = NodeProperties::GetValueInput(node, 0);
1321
  NameRef name(broker(), p.name());
1322

1323 1324 1325
  // Check if we have a constant receiver.
  HeapObjectMatcher m(receiver);
  if (m.HasValue()) {
1326 1327 1328
    ObjectRef object = m.Ref(broker());
    if (object.IsJSFunction() &&
        name.equals(ObjectRef(broker(), factory()->prototype_string()))) {
1329
      // Optimize "prototype" property of functions.
1330
      JSFunctionRef function = object.AsJSFunction();
1331
      if (should_disallow_heap_access() && !function.serialized()) {
1332
        TRACE_BROKER_MISSING(broker(), "data for function " << function);
1333 1334
        return NoChange();
      }
1335 1336 1337 1338
      // TODO(neis): Remove the has_prototype_slot condition once the broker is
      // always enabled.
      if (!function.map().has_prototype_slot() || !function.has_prototype() ||
          function.PrototypeRequiresRuntimeLookup()) {
1339 1340
        return NoChange();
      }
1341 1342 1343 1344
      ObjectRef prototype = dependencies()->DependOnPrototypeProperty(function);
      Node* value = jsgraph()->Constant(prototype);
      ReplaceWithValue(node, value);
      return Replace(value);
1345 1346
    } else if (object.IsString() &&
               name.equals(ObjectRef(broker(), factory()->length_string()))) {
1347
      // Constant-fold "length" property on constant strings.
1348
      Node* value = jsgraph()->Constant(object.AsString().length());
1349 1350
      ReplaceWithValue(node, value);
      return Replace(value);
1351 1352 1353
    }
  }

1354
  if (!p.feedback().IsValid()) return NoChange();
1355 1356
  return ReducePropertyAccess(node, nullptr, name, jsgraph()->Dead(),
                              FeedbackSource(p.feedback()), AccessMode::kLoad);
1357
}
1358

1359 1360
Reduction JSNativeContextSpecialization::ReduceJSGetIterator(Node* node) {
  DCHECK_EQ(IrOpcode::kJSGetIterator, node->opcode());
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  GetIteratorParameters const& p = GetIteratorParametersOf(node->op());

  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* context = NodeProperties::GetContextInput(node);
  Node* frame_state = NodeProperties::GetFrameStateInput(node);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Load iterator property operator
  Handle<Name> iterator_symbol = factory()->iterator_symbol();
  const Operator* load_op =
      javascript()->LoadNamed(iterator_symbol, p.loadFeedback());

  // Lazy deopt of the load iterator property
1375
  // TODO(v8:10047): Use TaggedIndexConstant here once deoptimizer supports it.
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
  Node* call_slot = jsgraph()->SmiConstant(p.callFeedback().slot.ToInt());
  Node* call_feedback = jsgraph()->HeapConstant(p.callFeedback().vector);
  Node* lazy_deopt_parameters[] = {receiver, call_slot, call_feedback};
  Node* lazy_deopt_frame_state = CreateStubBuiltinContinuationFrameState(
      jsgraph(), Builtins::kGetIteratorWithFeedbackLazyDeoptContinuation,
      context, lazy_deopt_parameters, arraysize(lazy_deopt_parameters),
      frame_state, ContinuationFrameStateMode::LAZY);
  Node* load_property = graph()->NewNode(
      load_op, receiver, context, lazy_deopt_frame_state, effect, control);
  effect = load_property;
  control = load_property;

  // Handle exception path for the load named property
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
  Node* iterator_exception_node = nullptr;
  if (NodeProperties::IsExceptionalCall(node, &iterator_exception_node)) {
    // If there exists an exception node for the given iterator_node, create a
    // pair of IfException/IfSuccess nodes on the current control path. The uses
    // of new exception node are merged with the original exception node. The
    // IfSuccess node is returned as a control path for further reduction.
    Node* exception_node =
        graph()->NewNode(common()->IfException(), effect, control);
    Node* if_success = graph()->NewNode(common()->IfSuccess(), control);

    // Use dead_node as a placeholder for the original exception node until
    // its uses are rewired to the nodes merging the exceptions
    Node* dead_node = jsgraph()->Dead();
    Node* merge_node =
        graph()->NewNode(common()->Merge(2), dead_node, exception_node);
    Node* effect_phi = graph()->NewNode(common()->EffectPhi(2), dead_node,
                                        exception_node, merge_node);
    Node* phi =
        graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                         dead_node, exception_node, merge_node);
    ReplaceWithValue(iterator_exception_node, phi, effect_phi, merge_node);
    phi->ReplaceInput(0, iterator_exception_node);
    effect_phi->ReplaceInput(0, iterator_exception_node);
    merge_node->ReplaceInput(0, iterator_exception_node);
    control = if_success;
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  }

  // Eager deopt of call iterator property
  Node* parameters[] = {receiver, load_property, call_slot, call_feedback};
  Node* eager_deopt_frame_state = CreateStubBuiltinContinuationFrameState(
      jsgraph(), Builtins::kCallIteratorWithFeedback, context, parameters,
      arraysize(parameters), frame_state, ContinuationFrameStateMode::EAGER);
  Node* deopt_checkpoint = graph()->NewNode(
      common()->Checkpoint(), eager_deopt_frame_state, effect, control);
  effect = deopt_checkpoint;
1424

1425 1426 1427 1428 1429 1430 1431 1432
  // Call iterator property operator
  ProcessedFeedback const& feedback =
      broker()->GetFeedbackForCall(p.callFeedback());
  SpeculationMode mode = feedback.IsInsufficient()
                             ? SpeculationMode::kDisallowSpeculation
                             : feedback.AsCall().speculation_mode();
  const Operator* call_op =
      javascript()->Call(2, CallFrequency(), p.callFeedback(),
1433 1434
                         ConvertReceiverMode::kNotNullOrUndefined, mode,
                         CallFeedbackRelation::kRelated);
1435 1436 1437
  Node* call_property = graph()->NewNode(call_op, load_property, receiver,
                                         context, frame_state, effect, control);

1438
  return Replace(call_property);
1439 1440
}

1441 1442 1443 1444
Reduction JSNativeContextSpecialization::ReduceJSStoreNamed(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreNamed, node->opcode());
  NamedAccess const& p = NamedAccessOf(node->op());
  Node* const value = NodeProperties::GetValueInput(node, 1);
1445

1446
  if (!p.feedback().IsValid()) return NoChange();
1447 1448
  return ReducePropertyAccess(node, nullptr, NameRef(broker(), p.name()), value,
                              FeedbackSource(p.feedback()), AccessMode::kStore);
1449 1450
}

1451 1452 1453 1454 1455 1456
Reduction JSNativeContextSpecialization::ReduceJSStoreNamedOwn(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreNamedOwn, node->opcode());
  StoreNamedOwnParameters const& p = StoreNamedOwnParametersOf(node->op());
  Node* const value = NodeProperties::GetValueInput(node, 1);

  if (!p.feedback().IsValid()) return NoChange();
1457 1458 1459
  return ReducePropertyAccess(node, nullptr, NameRef(broker(), p.name()), value,
                              FeedbackSource(p.feedback()),
                              AccessMode::kStoreInLiteral);
1460
}
1461

1462
Reduction JSNativeContextSpecialization::ReduceElementAccessOnString(
1463
    Node* node, Node* index, Node* value, KeyedAccessMode const& keyed_mode) {
1464 1465 1466 1467 1468
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

  // Strings are immutable in JavaScript.
1469
  if (keyed_mode.access_mode() == AccessMode::kStore) return NoChange();
1470

1471
  // `in` cannot be used on strings.
1472
  if (keyed_mode.access_mode() == AccessMode::kHas) return NoChange();
1473

1474 1475
  // Ensure that the {receiver} is actually a String.
  receiver = effect = graph()->NewNode(
1476
      simplified()->CheckString(FeedbackSource()), receiver, effect, control);
1477 1478 1479 1480 1481 1482 1483

  // Determine the {receiver} length.
  Node* length = graph()->NewNode(simplified()->StringLength(), receiver);

  // Load the single character string from {receiver} or yield undefined
  // if the {index} is out of bounds (depending on the {load_mode}).
  value = BuildIndexedStringLoad(receiver, index, length, &effect, &control,
1484
                                 keyed_mode.load_mode());
1485 1486 1487 1488 1489

  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
}

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
namespace {
base::Optional<JSTypedArrayRef> GetTypedArrayConstant(JSHeapBroker* broker,
                                                      Node* receiver) {
  HeapObjectMatcher m(receiver);
  if (!m.HasValue()) return base::nullopt;
  ObjectRef object = m.Ref(broker);
  if (!object.IsJSTypedArray()) return base::nullopt;
  JSTypedArrayRef typed_array = object.AsJSTypedArray();
  if (typed_array.is_on_heap()) return base::nullopt;
  return typed_array;
}
}  // namespace

1503 1504
void JSNativeContextSpecialization::RemoveImpossibleReceiverMaps(
    Node* receiver, ZoneVector<Handle<Map>>* receiver_maps) const {
1505 1506
  base::Optional<MapRef> root_map = InferReceiverRootMap(receiver);
  if (root_map.has_value()) {
1507 1508 1509
    DCHECK(!root_map->is_abandoned_prototype_map());
    receiver_maps->erase(
        std::remove_if(receiver_maps->begin(), receiver_maps->end(),
1510 1511 1512 1513 1514
                       [root_map, this](Handle<Map> map) {
                         MapRef map_ref(broker(), map);
                         return map_ref.is_abandoned_prototype_map() ||
                                (map_ref.FindRootMap().has_value() &&
                                 !map_ref.FindRootMap()->equals(*root_map));
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
                       }),
        receiver_maps->end());
  }
}

// Possibly refine the feedback using inferred map information from the graph.
ElementAccessFeedback const&
JSNativeContextSpecialization::TryRefineElementAccessFeedback(
    ElementAccessFeedback const& feedback, Node* receiver, Node* effect) const {
  AccessMode access_mode = feedback.keyed_mode().access_mode();
  bool use_inference =
      access_mode == AccessMode::kLoad || access_mode == AccessMode::kHas;
  if (!use_inference) return feedback;

  ZoneVector<Handle<Map>> inferred_maps(zone());
  if (!InferReceiverMaps(receiver, effect, &inferred_maps)) return feedback;

  RemoveImpossibleReceiverMaps(receiver, &inferred_maps);
  // TODO(neis): After Refine, the resulting feedback can still contain
  // impossible maps when a target is kept only because more than one of its
  // sources was inferred. Think of a way to completely rule out impossible
  // maps.
  return feedback.Refine(inferred_maps, zone());
}

1540
Reduction JSNativeContextSpecialization::ReduceElementAccess(
1541
    Node* node, Node* index, Node* value,
1542
    ElementAccessFeedback const& feedback) {
1543
  DCHECK(node->opcode() == IrOpcode::kJSLoadProperty ||
1544
         node->opcode() == IrOpcode::kJSStoreProperty ||
1545
         node->opcode() == IrOpcode::kJSStoreInArrayLiteral ||
1546
         node->opcode() == IrOpcode::kJSStoreDataPropertyInLiteral ||
1547
         node->opcode() == IrOpcode::kJSHasProperty);
1548

1549 1550 1551
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
1552 1553
  Node* frame_state =
      NodeProperties::FindFrameStateBefore(node, jsgraph()->Dead());
1554

1555 1556 1557 1558 1559 1560 1561 1562
  // TODO(neis): It's odd that we do optimizations below that don't really care
  // about the feedback, but we don't do them when the feedback is megamorphic.
  if (feedback.transition_groups().empty()) return NoChange();

  ElementAccessFeedback const& refined_feedback =
      TryRefineElementAccessFeedback(feedback, receiver, effect);

  AccessMode access_mode = refined_feedback.keyed_mode().access_mode();
1563 1564
  if ((access_mode == AccessMode::kLoad || access_mode == AccessMode::kHas) &&
      receiver->opcode() == IrOpcode::kHeapConstant) {
1565
    Reduction reduction = ReduceElementLoadFromHeapConstant(
1566
        node, index, access_mode, refined_feedback.keyed_mode().load_mode());
1567 1568 1569
    if (reduction.Changed()) return reduction;
  }

1570 1571
  if (!refined_feedback.transition_groups().empty() &&
      refined_feedback.HasOnlyStringMaps(broker())) {
1572
    return ReduceElementAccessOnString(node, index, value,
1573
                                       refined_feedback.keyed_mode());
1574
  }
1575

1576 1577
  AccessInfoFactory access_info_factory(broker(), dependencies(),
                                        graph()->zone());
1578
  ZoneVector<ElementAccessInfo> access_infos(zone());
1579 1580 1581
  if (!access_info_factory.ComputeElementAccessInfos(refined_feedback,
                                                     &access_infos) ||
      access_infos.empty()) {
1582 1583
    return NoChange();
  }
1584

1585 1586 1587 1588 1589 1590 1591
  // For holey stores or growing stores, we need to check that the prototype
  // chain contains no setters for elements, and we need to guard those checks
  // via code dependencies on the relevant prototype maps.
  if (access_mode == AccessMode::kStore) {
    // TODO(turbofan): We could have a fast path here, that checks for the
    // common case of Array or Object prototype only and therefore avoids
    // the zone allocation of this vector.
1592
    ZoneVector<MapRef> prototype_maps(zone());
1593
    for (ElementAccessInfo const& access_info : access_infos) {
1594 1595
      for (Handle<Map> map : access_info.receiver_maps()) {
        MapRef receiver_map(broker(), map);
1596 1597 1598 1599
        // If the {receiver_map} has a prototype and its elements backing
        // store is either holey, or we have a potentially growing store,
        // then we need to check that all prototypes have stable maps with
        // fast elements (and we need to guard against changes to that below).
1600
        if ((IsHoleyOrDictionaryElementsKind(receiver_map.elements_kind()) ||
1601
             IsGrowStoreMode(feedback.keyed_mode().store_mode())) &&
1602 1603 1604
            !receiver_map.HasOnlyStablePrototypesWithFastElements(
                &prototype_maps)) {
          return NoChange();
1605 1606
        }
      }
1607
    }
1608 1609
    for (MapRef const& prototype_map : prototype_maps) {
      dependencies()->DependOnStableMap(prototype_map);
1610
    }
1611 1612 1613 1614 1615
  } else if (access_mode == AccessMode::kHas) {
    // If we have any fast arrays, we need to check and depend on
    // NoElementsProtector.
    for (ElementAccessInfo const& access_info : access_infos) {
      if (IsFastElementsKind(access_info.elements_kind())) {
1616
        if (!dependencies()->DependOnNoElementsProtector()) return NoChange();
1617 1618 1619
        break;
      }
    }
1620
  }
1621

1622 1623
  // Check if we have the necessary data for building element accesses.
  for (ElementAccessInfo const& access_info : access_infos) {
1624
    if (!IsTypedArrayElementsKind(access_info.elements_kind())) continue;
1625 1626 1627
    base::Optional<JSTypedArrayRef> typed_array =
        GetTypedArrayConstant(broker(), receiver);
    if (typed_array.has_value()) {
1628
      if (should_disallow_heap_access() && !typed_array->serialized()) {
1629
        TRACE_BROKER_MISSING(broker(), "data for typed array " << *typed_array);
1630 1631 1632 1633 1634
        return NoChange();
      }
    }
  }

1635
  // Check for the monomorphic case.
1636
  PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
1637 1638 1639 1640
  if (access_infos.size() == 1) {
    ElementAccessInfo access_info = access_infos.front();

    // Perform possible elements kind transitions.
1641 1642
    MapRef transition_target(broker(), access_info.receiver_maps().front());
    for (auto source : access_info.transition_sources()) {
1643
      DCHECK_EQ(access_info.receiver_maps().size(), 1);
1644
      MapRef transition_source(broker(), source);
1645 1646
      effect = graph()->NewNode(
          simplified()->TransitionElementsKind(ElementsTransition(
1647 1648
              IsSimpleMapChangeTransition(transition_source.elements_kind(),
                                          transition_target.elements_kind())
1649 1650
                  ? ElementsTransition::kFastTransition
                  : ElementsTransition::kSlowTransition,
1651
              transition_source.object(), transition_target.object())),
1652
          receiver, effect, control);
1653 1654
    }

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    // TODO(turbofan): The effect/control linearization will not find a
    // FrameState after the StoreField or Call that is generated for the
    // elements kind transition above. This is because those operators
    // don't have the kNoWrite flag on it, even though they are not
    // observable by JavaScript.
    effect =
        graph()->NewNode(common()->Checkpoint(), frame_state, effect, control);

    // Perform map check on the {receiver}.
    access_builder.BuildCheckMaps(receiver, &effect, control,
                                  access_info.receiver_maps());

    // Access the actual element.
    ValueEffectControl continuation =
        BuildElementAccess(receiver, index, value, effect, control, access_info,
1670
                           feedback.keyed_mode());
1671 1672 1673 1674 1675 1676 1677 1678 1679
    value = continuation.value();
    effect = continuation.effect();
    control = continuation.control();
  } else {
    // The final states for every polymorphic branch. We join them with
    // Merge+Phi+EffectPhi at the bottom.
    ZoneVector<Node*> values(zone());
    ZoneVector<Node*> effects(zone());
    ZoneVector<Node*> controls(zone());
1680

1681 1682 1683 1684 1685 1686 1687 1688 1689
    // Generate code for the various different element access patterns.
    Node* fallthrough_control = control;
    for (size_t j = 0; j < access_infos.size(); ++j) {
      ElementAccessInfo const& access_info = access_infos[j];
      Node* this_receiver = receiver;
      Node* this_value = value;
      Node* this_index = index;
      Node* this_effect = effect;
      Node* this_control = fallthrough_control;
1690 1691

      // Perform possible elements kind transitions.
1692 1693 1694
      MapRef transition_target(broker(), access_info.receiver_maps().front());
      for (auto source : access_info.transition_sources()) {
        MapRef transition_source(broker(), source);
1695
        DCHECK_EQ(access_info.receiver_maps().size(), 1);
1696
        this_effect = graph()->NewNode(
1697
            simplified()->TransitionElementsKind(ElementsTransition(
1698 1699
                IsSimpleMapChangeTransition(transition_source.elements_kind(),
                                            transition_target.elements_kind())
1700
                    ? ElementsTransition::kFastTransition
1701
                    : ElementsTransition::kSlowTransition,
1702
                transition_source.object(), transition_target.object())),
1703
            receiver, this_effect, this_control);
1704 1705
      }

1706
      // Perform map check(s) on {receiver}.
1707 1708
      ZoneVector<Handle<Map>> const& receiver_maps =
          access_info.receiver_maps();
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
      if (j == access_infos.size() - 1) {
        // Last map check on the fallthrough control path, do a
        // conditional eager deoptimization exit here.
        access_builder.BuildCheckMaps(receiver, &this_effect, this_control,
                                      receiver_maps);
        fallthrough_control = nullptr;
      } else {
        // Explicitly branch on the {receiver_maps}.
        ZoneHandleSet<Map> maps;
        for (Handle<Map> map : receiver_maps) {
          maps.insert(map, graph()->zone());
1720
        }
1721 1722 1723 1724 1725 1726 1727
        Node* check = this_effect =
            graph()->NewNode(simplified()->CompareMaps(maps), receiver,
                             this_effect, fallthrough_control);
        Node* branch =
            graph()->NewNode(common()->Branch(), check, fallthrough_control);
        fallthrough_control = graph()->NewNode(common()->IfFalse(), branch);
        this_control = graph()->NewNode(common()->IfTrue(), branch);
1728

1729 1730 1731
        // Introduce a MapGuard to learn from this on the effect chain.
        this_effect = graph()->NewNode(simplified()->MapGuard(maps), receiver,
                                       this_effect, this_control);
1732
      }
1733

1734
      // Access the actual element.
1735 1736
      ValueEffectControl continuation =
          BuildElementAccess(this_receiver, this_index, this_value, this_effect,
1737
                             this_control, access_info, feedback.keyed_mode());
1738 1739 1740 1741
      values.push_back(continuation.value());
      effects.push_back(continuation.effect());
      controls.push_back(continuation.control());
    }
1742

1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
    DCHECK_NULL(fallthrough_control);

    // Generate the final merge point for all (polymorphic) branches.
    int const control_count = static_cast<int>(controls.size());
    if (control_count == 0) {
      value = effect = control = jsgraph()->Dead();
    } else if (control_count == 1) {
      value = values.front();
      effect = effects.front();
      control = controls.front();
    } else {
      control = graph()->NewNode(common()->Merge(control_count), control_count,
                                 &controls.front());
      values.push_back(control);
      value = graph()->NewNode(
          common()->Phi(MachineRepresentation::kTagged, control_count),
          control_count + 1, &values.front());
      effects.push_back(control);
      effect = graph()->NewNode(common()->EffectPhi(control_count),
                                control_count + 1, &effects.front());
1763
    }
1764
  }
1765

1766 1767
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
1768 1769
}

1770
Reduction JSNativeContextSpecialization::ReduceElementLoadFromHeapConstant(
1771
    Node* node, Node* key, AccessMode access_mode,
1772
    KeyedAccessLoadMode load_mode) {
1773 1774
  DCHECK(node->opcode() == IrOpcode::kJSLoadProperty ||
         node->opcode() == IrOpcode::kJSHasProperty);
1775 1776 1777 1778
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);

1779
  HeapObjectMatcher mreceiver(receiver);
1780
  HeapObjectRef receiver_ref = mreceiver.Ref(broker());
1781 1782
  if (receiver_ref.map().oddball_type() == OddballType::kHole ||
      receiver_ref.map().oddball_type() == OddballType::kNull ||
1783
      receiver_ref.map().oddball_type() == OddballType::kUndefined ||
1784
      // The 'in' operator throws a TypeError on primitive values.
1785
      (receiver_ref.IsString() && access_mode == AccessMode::kHas)) {
1786 1787
    return NoChange();
  }
1788

1789 1790
  // Check whether we're accessing a known element on the {receiver} and can
  // constant-fold the load.
1791 1792 1793
  NumberMatcher mkey(key);
  if (mkey.IsInteger() && mkey.IsInRange(0.0, kMaxUInt32 - 1.0)) {
    uint32_t index = static_cast<uint32_t>(mkey.Value());
1794
    base::Optional<ObjectRef> element =
1795
        receiver_ref.GetOwnConstantElement(index);
1796 1797 1798 1799
    if (!element.has_value() && receiver_ref.IsJSArray()) {
      // We didn't find a constant element, but if the receiver is a cow-array
      // we can exploit the fact that any future write to the element will
      // replace the whole elements storage.
1800
      element = receiver_ref.AsJSArray().GetOwnCowElement(index);
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
      if (element.has_value()) {
        Node* elements = effect = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForJSObjectElements()),
            receiver, effect, control);
        FixedArrayRef array_elements =
            receiver_ref.AsJSArray().elements().AsFixedArray();
        Node* check = graph()->NewNode(simplified()->ReferenceEqual(), elements,
                                       jsgraph()->Constant(array_elements));
        effect = graph()->NewNode(
            simplified()->CheckIf(DeoptimizeReason::kCowArrayElementsChanged),
            check, effect, control);
1812
      }
1813
    }
1814 1815 1816 1817 1818 1819 1820
    if (element.has_value()) {
      Node* value = access_mode == AccessMode::kHas
                        ? jsgraph()->TrueConstant()
                        : jsgraph()->Constant(*element);
      ReplaceWithValue(node, value, effect, control);
      return Replace(value);
    }
1821
  }
1822

1823 1824
  // For constant Strings we can eagerly strength-reduce the keyed
  // accesses using the known length, which doesn't change.
1825 1826
  if (receiver_ref.IsString()) {
    DCHECK_NE(access_mode, AccessMode::kHas);
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    // Ensure that {key} is less than {receiver} length.
    Node* length = jsgraph()->Constant(receiver_ref.AsString().length());

    // Load the single character string from {receiver} or yield
    // undefined if the {key} is out of bounds (depending on the
    // {load_mode}).
    Node* value = BuildIndexedStringLoad(receiver, key, length, &effect,
                                         &control, load_mode);
    ReplaceWithValue(node, value, effect, control);
    return Replace(value);
1837 1838 1839 1840 1841
  }

  return NoChange();
}

1842
Reduction JSNativeContextSpecialization::ReducePropertyAccess(
1843
    Node* node, Node* key, base::Optional<NameRef> static_name, Node* value,
1844
    FeedbackSource const& source, AccessMode access_mode) {
1845
  DisallowHeapAccessIf disallow_heap_access(should_disallow_heap_access());
1846

1847 1848
  DCHECK_EQ(key == nullptr, static_name.has_value());
  DCHECK(node->opcode() == IrOpcode::kJSLoadProperty ||
1849
         node->opcode() == IrOpcode::kJSStoreProperty ||
1850
         node->opcode() == IrOpcode::kJSStoreInArrayLiteral ||
1851
         node->opcode() == IrOpcode::kJSStoreDataPropertyInLiteral ||
1852 1853 1854
         node->opcode() == IrOpcode::kJSHasProperty ||
         node->opcode() == IrOpcode::kJSLoadNamed ||
         node->opcode() == IrOpcode::kJSStoreNamed ||
1855
         node->opcode() == IrOpcode::kJSStoreNamedOwn);
1856
  DCHECK_GE(node->op()->ControlOutputCount(), 1);
1857

1858 1859 1860
  ProcessedFeedback const& feedback =
      broker()->GetFeedbackForPropertyAccess(source, access_mode, static_name);
  switch (feedback.kind()) {
1861 1862 1863 1864 1865
    case ProcessedFeedback::kInsufficient:
      return ReduceSoftDeoptimize(
          node,
          DeoptimizeReason::kInsufficientTypeFeedbackForGenericNamedAccess);
    case ProcessedFeedback::kNamedAccess:
1866
      return ReduceNamedAccess(node, value, feedback.AsNamedAccess(),
1867 1868
                               access_mode, key);
    case ProcessedFeedback::kElementAccess:
1869 1870 1871 1872
      DCHECK_EQ(feedback.AsElementAccess().keyed_mode().access_mode(),
                access_mode);
      return ReduceElementAccess(node, key, value, feedback.AsElementAccess());
    default:
1873
      UNREACHABLE();
1874 1875 1876
  }
}

1877 1878
Reduction JSNativeContextSpecialization::ReduceSoftDeoptimize(
    Node* node, DeoptimizeReason reason) {
1879 1880 1881 1882 1883 1884 1885
  if (!(flags() & kBailoutOnUninitialized)) return NoChange();

  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
  Node* frame_state =
      NodeProperties::FindFrameStateBefore(node, jsgraph()->Dead());
  Node* deoptimize = graph()->NewNode(
1886
      common()->Deoptimize(DeoptimizeKind::kSoft, reason, FeedbackSource()),
1887 1888 1889 1890 1891 1892 1893
      frame_state, effect, control);
  // TODO(bmeurer): This should be on the AdvancedReducer somehow.
  NodeProperties::MergeControlToEnd(graph(), common(), deoptimize);
  Revisit(graph()->end());
  node->TrimInputCount(0);
  NodeProperties::ChangeOp(node, common()->Dead());
  return Changed(node);
1894 1895
}

1896 1897 1898
Reduction JSNativeContextSpecialization::ReduceJSHasProperty(Node* node) {
  DCHECK_EQ(IrOpcode::kJSHasProperty, node->opcode());
  PropertyAccess const& p = PropertyAccessOf(node->op());
1899
  Node* key = NodeProperties::GetValueInput(node, 1);
1900 1901 1902
  Node* value = jsgraph()->Dead();

  if (!p.feedback().IsValid()) return NoChange();
1903 1904
  return ReducePropertyAccess(node, key, base::nullopt, value,
                              FeedbackSource(p.feedback()), AccessMode::kHas);
1905 1906
}

1907 1908 1909
Reduction JSNativeContextSpecialization::ReduceJSLoadPropertyWithEnumeratedKey(
    Node* node) {
  // We can optimize a property load if it's being used inside a for..in:
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
  //   for (name in receiver) {
  //     value = receiver[name];
  //     ...
  //   }
  //
  // If the for..in is in fast-mode, we know that the {receiver} has {name}
  // as own property, otherwise the enumeration wouldn't include it. The graph
  // constructed by the BytecodeGraphBuilder in this case looks like this:

  // receiver
  //  ^    ^
  //  |    |
  //  |    +-+
  //  |      |
  //  |   JSToObject
  //  |      ^
  //  |      |
  //  |      |
  //  |  JSForInNext
  //  |      ^
  //  |      |
  //  +----+ |
  //       | |
  //       | |
  //   JSLoadProperty

  // If the for..in has only seen maps with enum cache consisting of keys
  // and indices so far, we can turn the {JSLoadProperty} into a map check
  // on the {receiver} and then just load the field value dynamically via
1939 1940 1941
  // the {LoadFieldByIndex} operator. The map check is only necessary when
  // TurboFan cannot prove that there is no observable side effect between
  // the {JSForInNext} and the {JSLoadProperty} node.
1942 1943 1944 1945
  //
  // Also note that it's safe to look through the {JSToObject}, since the
  // [[Get]] operation does an implicit ToObject anyway, and these operations
  // are not observable.
1946

1947 1948 1949 1950 1951 1952
  DCHECK_EQ(IrOpcode::kJSLoadProperty, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* name = NodeProperties::GetValueInput(node, 1);
  DCHECK_EQ(IrOpcode::kJSForInNext, name->opcode());
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
1953

1954 1955 1956 1957 1958 1959
  if (ForInModeOf(name->op()) != ForInMode::kUseEnumCacheKeysAndIndices) {
    return NoChange();
  }

  Node* object = NodeProperties::GetValueInput(name, 0);
  Node* enumerator = NodeProperties::GetValueInput(name, 2);
1960
  Node* key = NodeProperties::GetValueInput(name, 3);
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
  if (object->opcode() == IrOpcode::kJSToObject) {
    object = NodeProperties::GetValueInput(object, 0);
  }
  if (object != receiver) return NoChange();

  // No need to repeat the map check if we can prove that there's no
  // observable side effect between {effect} and {name].
  if (!NodeProperties::NoObservableSideEffectBetween(effect, name)) {
    // Check that the {receiver} map is still valid.
    Node* receiver_map = effect =
        graph()->NewNode(simplified()->LoadField(AccessBuilder::ForMap()),
                         receiver, effect, control);
    Node* check = graph()->NewNode(simplified()->ReferenceEqual(), receiver_map,
                                   enumerator);
    effect =
        graph()->NewNode(simplified()->CheckIf(DeoptimizeReason::kWrongMap),
                         check, effect, control);
  }

  // Load the enum cache indices from the {cache_type}.
  Node* descriptor_array = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForMapDescriptors()), enumerator,
      effect, control);
  Node* enum_cache = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForDescriptorArrayEnumCache()),
      descriptor_array, effect, control);
  Node* enum_indices = effect = graph()->NewNode(
      simplified()->LoadField(AccessBuilder::ForEnumCacheIndices()), enum_cache,
      effect, control);

  // Ensure that the {enum_indices} are valid.
  Node* check = graph()->NewNode(
      simplified()->BooleanNot(),
      graph()->NewNode(simplified()->ReferenceEqual(), enum_indices,
                       jsgraph()->EmptyFixedArrayConstant()));
  effect = graph()->NewNode(
      simplified()->CheckIf(DeoptimizeReason::kWrongEnumIndices), check, effect,
      control);

2000 2001
  // Determine the key from the {enum_indices}.
  key = effect = graph()->NewNode(
2002 2003
      simplified()->LoadElement(
          AccessBuilder::ForFixedArrayElement(PACKED_SMI_ELEMENTS)),
2004
      enum_indices, key, effect, control);
2005 2006 2007

  // Load the actual field value.
  Node* value = effect = graph()->NewNode(simplified()->LoadFieldByIndex(),
2008
                                          receiver, key, effect, control);
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
  ReplaceWithValue(node, value, effect, control);
  return Replace(value);
}

Reduction JSNativeContextSpecialization::ReduceJSLoadProperty(Node* node) {
  DCHECK_EQ(IrOpcode::kJSLoadProperty, node->opcode());
  PropertyAccess const& p = PropertyAccessOf(node->op());
  Node* name = NodeProperties::GetValueInput(node, 1);

  if (name->opcode() == IrOpcode::kJSForInNext) {
    Reduction reduction = ReduceJSLoadPropertyWithEnumeratedKey(node);
    if (reduction.Changed()) return reduction;
2021
  }
2022 2023

  if (!p.feedback().IsValid()) return NoChange();
2024
  Node* value = jsgraph()->Dead();
2025 2026
  return ReducePropertyAccess(node, name, base::nullopt, value,
                              FeedbackSource(p.feedback()), AccessMode::kLoad);
2027 2028 2029 2030 2031
}

Reduction JSNativeContextSpecialization::ReduceJSStoreProperty(Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreProperty, node->opcode());
  PropertyAccess const& p = PropertyAccessOf(node->op());
2032
  Node* const key = NodeProperties::GetValueInput(node, 1);
2033 2034 2035
  Node* const value = NodeProperties::GetValueInput(node, 2);

  if (!p.feedback().IsValid()) return NoChange();
2036 2037
  return ReducePropertyAccess(node, key, base::nullopt, value,
                              FeedbackSource(p.feedback()), AccessMode::kStore);
2038 2039
}

2040 2041 2042 2043
Node* JSNativeContextSpecialization::InlinePropertyGetterCall(
    Node* receiver, Node* context, Node* frame_state, Node** effect,
    Node** control, ZoneVector<Node*>* if_exceptions,
    PropertyAccessInfo const& access_info) {
2044 2045
  ObjectRef constant(broker(), access_info.constant());
  Node* target = jsgraph()->Constant(constant);
2046
  FrameStateInfo const& frame_info = FrameStateInfoOf(frame_state->op());
2047 2048
  // Introduce the call to the getter function.
  Node* value;
2049
  if (constant.IsJSFunction()) {
2050
    value = *effect = *control = graph()->NewNode(
2051
        jsgraph()->javascript()->Call(2, CallFrequency(), FeedbackSource(),
2052
                                      ConvertReceiverMode::kNotNullOrUndefined),
2053
        target, receiver, context, frame_state, *effect, *control);
2054
  } else {
2055 2056 2057 2058
    Node* holder = access_info.holder().is_null()
                       ? receiver
                       : jsgraph()->Constant(ObjectRef(
                             broker(), access_info.holder().ToHandleChecked()));
2059 2060
    SharedFunctionInfoRef shared_info(
        broker(), frame_info.shared_info().ToHandleChecked());
2061

2062 2063 2064
    value =
        InlineApiCall(receiver, holder, frame_state, nullptr, effect, control,
                      shared_info, constant.AsFunctionTemplateInfo());
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
  }
  // Remember to rewire the IfException edge if this is inside a try-block.
  if (if_exceptions != nullptr) {
    // Create the appropriate IfException/IfSuccess projections.
    Node* const if_exception =
        graph()->NewNode(common()->IfException(), *control, *effect);
    Node* const if_success = graph()->NewNode(common()->IfSuccess(), *control);
    if_exceptions->push_back(if_exception);
    *control = if_success;
  }
  return value;
}

2078
void JSNativeContextSpecialization::InlinePropertySetterCall(
2079 2080 2081
    Node* receiver, Node* value, Node* context, Node* frame_state,
    Node** effect, Node** control, ZoneVector<Node*>* if_exceptions,
    PropertyAccessInfo const& access_info) {
2082 2083
  ObjectRef constant(broker(), access_info.constant());
  Node* target = jsgraph()->Constant(constant);
2084
  FrameStateInfo const& frame_info = FrameStateInfoOf(frame_state->op());
2085
  // Introduce the call to the setter function.
2086
  if (constant.IsJSFunction()) {
2087
    *effect = *control = graph()->NewNode(
2088
        jsgraph()->javascript()->Call(3, CallFrequency(), FeedbackSource(),
2089
                                      ConvertReceiverMode::kNotNullOrUndefined),
2090
        target, receiver, value, context, frame_state, *effect, *control);
2091
  } else {
2092 2093 2094 2095
    Node* holder = access_info.holder().is_null()
                       ? receiver
                       : jsgraph()->Constant(ObjectRef(
                             broker(), access_info.holder().ToHandleChecked()));
2096 2097
    SharedFunctionInfoRef shared_info(
        broker(), frame_info.shared_info().ToHandleChecked());
2098
    InlineApiCall(receiver, holder, frame_state, value, effect, control,
2099
                  shared_info, constant.AsFunctionTemplateInfo());
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
  }
  // Remember to rewire the IfException edge if this is inside a try-block.
  if (if_exceptions != nullptr) {
    // Create the appropriate IfException/IfSuccess projections.
    Node* const if_exception =
        graph()->NewNode(common()->IfException(), *control, *effect);
    Node* const if_success = graph()->NewNode(common()->IfSuccess(), *control);
    if_exceptions->push_back(if_exception);
    *control = if_success;
  }
}

Node* JSNativeContextSpecialization::InlineApiCall(
2113
    Node* receiver, Node* holder, Node* frame_state, Node* value, Node** effect,
2114 2115
    Node** control, SharedFunctionInfoRef const& shared_info,
    FunctionTemplateInfoRef const& function_template_info) {
2116 2117 2118 2119
  if (!function_template_info.has_call_code()) {
    return nullptr;
  }

2120 2121 2122 2123 2124
  if (!function_template_info.call_code().has_value()) {
    TRACE_BROKER_MISSING(broker(), "call code for function template info "
                                       << function_template_info);
    return nullptr;
  }
2125
  CallHandlerInfoRef call_handler_info = *function_template_info.call_code();
2126 2127 2128 2129

  // Only setters have a value.
  int const argc = value == nullptr ? 0 : 1;
  // The stub always expects the receiver as the first param on the stack.
2130
  Callable call_api_callback = CodeFactory::CallApiCallback(isolate());
2131
  CallInterfaceDescriptor call_interface_descriptor =
2132
      call_api_callback.descriptor();
2133
  auto call_descriptor = Linkage::GetStubCallDescriptor(
2134
      graph()->zone(), call_interface_descriptor,
2135
      call_interface_descriptor.GetStackParameterCount() + argc +
2136
          1 /* implicit receiver */,
2137
      CallDescriptor::kNeedsFrameState);
2138

2139 2140
  Node* data = jsgraph()->Constant(call_handler_info.data());
  ApiFunction function(call_handler_info.callback());
2141
  Node* function_reference =
2142 2143
      graph()->NewNode(common()->ExternalConstant(ExternalReference::Create(
          &function, ExternalReference::DIRECT_API_CALL)));
2144
  Node* code = jsgraph()->HeapConstant(call_api_callback.code());
2145 2146

  // Add CallApiCallbackStub's register argument as well.
2147
  Node* context = jsgraph()->Constant(native_context());
2148
  Node* inputs[11] = {
2149 2150 2151 2152
      code,    function_reference, jsgraph()->Constant(argc), data, holder,
      receiver};
  int index = 6 + argc;
  inputs[index++] = context;
2153 2154 2155 2156 2157 2158
  inputs[index++] = frame_state;
  inputs[index++] = *effect;
  inputs[index++] = *control;
  // This needs to stay here because of the edge case described in
  // http://crbug.com/675648.
  if (value != nullptr) {
2159
    inputs[6] = value;
2160 2161 2162 2163 2164 2165 2166 2167 2168
  }

  return *effect = *control =
             graph()->NewNode(common()->Call(call_descriptor), index, inputs);
}

JSNativeContextSpecialization::ValueEffectControl
JSNativeContextSpecialization::BuildPropertyLoad(
    Node* receiver, Node* context, Node* frame_state, Node* effect,
2169
    Node* control, NameRef const& name, ZoneVector<Node*>* if_exceptions,
2170
    PropertyAccessInfo const& access_info) {
2171 2172 2173
  // Determine actual holder and perform prototype chain checks.
  Handle<JSObject> holder;
  if (access_info.holder().ToHandle(&holder)) {
2174
    dependencies()->DependOnStablePrototypeChains(
2175 2176
        access_info.receiver_maps(), kStartAtPrototype,
        JSObjectRef(broker(), holder));
2177 2178 2179 2180 2181 2182 2183 2184 2185
  }

  // Generate the actual property access.
  Node* value;
  if (access_info.IsNotFound()) {
    value = jsgraph()->UndefinedConstant();
  } else if (access_info.IsAccessorConstant()) {
    value = InlinePropertyGetterCall(receiver, context, frame_state, &effect,
                                     &control, if_exceptions, access_info);
2186
  } else if (access_info.IsModuleExport()) {
2187 2188
    Node* cell = jsgraph()->Constant(
        ObjectRef(broker(), access_info.constant()).AsCell());
2189 2190 2191
    value = effect =
        graph()->NewNode(simplified()->LoadField(AccessBuilder::ForCellValue()),
                         cell, effect, control);
2192 2193
  } else if (access_info.IsStringLength()) {
    value = graph()->NewNode(simplified()->StringLength(), receiver);
2194
  } else {
2195
    DCHECK(access_info.IsDataField() || access_info.IsDataConstant());
2196
    PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
2197 2198 2199 2200 2201 2202 2203
    value = access_builder.BuildLoadDataField(name, access_info, receiver,
                                              &effect, &control);
  }

  return ValueEffectControl(value, effect, control);
}

2204 2205 2206 2207 2208 2209 2210
JSNativeContextSpecialization::ValueEffectControl
JSNativeContextSpecialization::BuildPropertyTest(
    Node* effect, Node* control, PropertyAccessInfo const& access_info) {
  // Determine actual holder and perform prototype chain checks.
  Handle<JSObject> holder;
  if (access_info.holder().ToHandle(&holder)) {
    dependencies()->DependOnStablePrototypeChains(
2211 2212
        access_info.receiver_maps(), kStartAtPrototype,
        JSObjectRef(broker(), holder));
2213 2214 2215 2216 2217 2218 2219
  }

  Node* value = access_info.IsNotFound() ? jsgraph()->FalseConstant()
                                         : jsgraph()->TrueConstant();
  return ValueEffectControl(value, effect, control);
}

2220 2221
JSNativeContextSpecialization::ValueEffectControl
JSNativeContextSpecialization::BuildPropertyAccess(
2222
    Node* receiver, Node* value, Node* context, Node* frame_state, Node* effect,
2223
    Node* control, NameRef const& name, ZoneVector<Node*>* if_exceptions,
2224
    PropertyAccessInfo const& access_info, AccessMode access_mode) {
2225 2226 2227
  switch (access_mode) {
    case AccessMode::kLoad:
      return BuildPropertyLoad(receiver, context, frame_state, effect, control,
2228
                               name, if_exceptions, access_info);
2229 2230 2231 2232
    case AccessMode::kStore:
    case AccessMode::kStoreInLiteral:
      return BuildPropertyStore(receiver, value, context, frame_state, effect,
                                control, name, if_exceptions, access_info,
2233
                                access_mode);
2234 2235
    case AccessMode::kHas:
      return BuildPropertyTest(effect, control, access_info);
2236 2237 2238 2239 2240 2241 2242
  }
  UNREACHABLE();
}

JSNativeContextSpecialization::ValueEffectControl
JSNativeContextSpecialization::BuildPropertyStore(
    Node* receiver, Node* value, Node* context, Node* frame_state, Node* effect,
2243
    Node* control, NameRef const& name, ZoneVector<Node*>* if_exceptions,
2244
    PropertyAccessInfo const& access_info, AccessMode access_mode) {
2245 2246
  // Determine actual holder and perform prototype chain checks.
  Handle<JSObject> holder;
2247
  PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
2248
  if (access_info.holder().ToHandle(&holder)) {
2249
    DCHECK_NE(AccessMode::kStoreInLiteral, access_mode);
2250
    dependencies()->DependOnStablePrototypeChains(
2251 2252
        access_info.receiver_maps(), kStartAtPrototype,
        JSObjectRef(broker(), holder));
2253 2254
  }

2255 2256
  DCHECK(!access_info.IsNotFound());

2257
  // Generate the actual property access.
2258
  if (access_info.IsAccessorConstant()) {
2259 2260
    InlinePropertySetterCall(receiver, value, context, frame_state, &effect,
                             &control, if_exceptions, access_info);
2261
  } else {
2262
    DCHECK(access_info.IsDataField() || access_info.IsDataConstant());
2263 2264
    DCHECK(access_mode == AccessMode::kStore ||
           access_mode == AccessMode::kStoreInLiteral);
2265
    FieldIndex const field_index = access_info.field_index();
2266
    Type const field_type = access_info.field_type();
2267
    MachineRepresentation const field_representation =
2268 2269
        PropertyAccessBuilder::ConvertRepresentation(
            access_info.field_representation());
2270 2271 2272
    Node* storage = receiver;
    if (!field_index.is_inobject()) {
      storage = effect = graph()->NewNode(
2273 2274
          simplified()->LoadField(
              AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer()),
2275 2276
          storage, effect, control);
    }
2277 2278 2279
    bool store_to_existing_constant_field = access_info.IsDataConstant() &&
                                            access_mode == AccessMode::kStore &&
                                            !access_info.HasTransitionMap();
2280
    FieldAccess field_access = {
2281 2282
        kTaggedBase,
        field_index.offset(),
2283
        name.object(),
2284
        MaybeHandle<Map>(),
2285 2286
        field_type,
        MachineType::TypeForRepresentation(field_representation),
2287 2288
        kFullWriteBarrier,
        LoadSensitivity::kUnsafe,
2289 2290
        access_info.GetConstFieldInfo(),
        access_mode == AccessMode::kStoreInLiteral};
2291 2292 2293

    switch (field_representation) {
      case MachineRepresentation::kFloat64: {
2294
        value = effect =
2295
            graph()->NewNode(simplified()->CheckNumber(FeedbackSource()), value,
2296
                             effect, control);
2297
        if (!field_index.is_inobject() || !FLAG_unbox_double_fields) {
2298
          if (access_info.HasTransitionMap()) {
2299
            // Allocate a HeapNumber for the new property.
2300
            AllocationBuilder a(jsgraph(), effect, control);
2301 2302
            a.Allocate(HeapNumber::kSize, AllocationType::kYoung,
                       Type::OtherInternal());
2303 2304
            a.Store(AccessBuilder::ForMap(),
                    MapRef(broker(), factory()->heap_number_map()));
2305 2306
            FieldAccess value_field_access =
                AccessBuilder::ForHeapNumberValue();
2307
            value_field_access.const_field_info = field_access.const_field_info;
2308
            a.Store(value_field_access, value);
2309
            value = effect = a.Finish();
2310 2311

            field_access.type = Type::Any();
2312
            field_access.machine_type = MachineType::TaggedPointer();
2313 2314
            field_access.write_barrier_kind = kPointerWriteBarrier;
          } else {
2315
            // We just store directly to the HeapNumber.
2316
            FieldAccess const storage_access = {
2317 2318 2319 2320 2321
                kTaggedBase,
                field_index.offset(),
                name.object(),
                MaybeHandle<Map>(),
                Type::OtherInternal(),
2322
                MachineType::TaggedPointer(),
2323 2324
                kPointerWriteBarrier,
                LoadSensitivity::kUnsafe,
2325 2326
                access_info.GetConstFieldInfo(),
                access_mode == AccessMode::kStoreInLiteral};
2327 2328 2329 2330 2331 2332
            storage = effect =
                graph()->NewNode(simplified()->LoadField(storage_access),
                                 storage, effect, control);
            field_access.offset = HeapNumber::kValueOffset;
            field_access.name = MaybeHandle<Name>();
            field_access.machine_type = MachineType::Float64();
2333 2334
          }
        }
2335
        if (store_to_existing_constant_field) {
2336 2337 2338 2339 2340 2341
          DCHECK(!access_info.HasTransitionMap());
          // If the field is constant check that the value we are going
          // to store matches current value.
          Node* current_value = effect = graph()->NewNode(
              simplified()->LoadField(field_access), storage, effect, control);

2342 2343
          Node* check =
              graph()->NewNode(simplified()->SameValue(), current_value, value);
2344
          effect = graph()->NewNode(
2345 2346
              simplified()->CheckIf(DeoptimizeReason::kWrongValue), check,
              effect, control);
2347 2348 2349
          return ValueEffectControl(value, effect, control);
        }
        break;
2350
      }
2351 2352 2353
      case MachineRepresentation::kTaggedSigned:
      case MachineRepresentation::kTaggedPointer:
      case MachineRepresentation::kTagged:
2354
        if (store_to_existing_constant_field) {
2355 2356 2357 2358 2359 2360
          DCHECK(!access_info.HasTransitionMap());
          // If the field is constant check that the value we are going
          // to store matches current value.
          Node* current_value = effect = graph()->NewNode(
              simplified()->LoadField(field_access), storage, effect, control);

2361
          Node* check = graph()->NewNode(simplified()->SameValueNumbersOnly(),
2362
                                         current_value, value);
2363
          effect = graph()->NewNode(
2364 2365
              simplified()->CheckIf(DeoptimizeReason::kWrongValue), check,
              effect, control);
2366
          return ValueEffectControl(value, effect, control);
2367
        }
2368

2369
        if (field_representation == MachineRepresentation::kTaggedSigned) {
2370
          value = effect = graph()->NewNode(
2371
              simplified()->CheckSmi(FeedbackSource()), value, effect, control);
2372 2373 2374
          field_access.write_barrier_kind = kNoWriteBarrier;

        } else if (field_representation ==
2375
                   MachineRepresentation::kTaggedPointer) {
2376 2377 2378 2379 2380 2381 2382
          Handle<Map> field_map;
          if (access_info.field_map().ToHandle(&field_map)) {
            // Emit a map check for the value.
            effect = graph()->NewNode(
                simplified()->CheckMaps(CheckMapsFlag::kNone,
                                        ZoneHandleSet<Map>(field_map)),
                value, effect, control);
2383 2384 2385 2386
          } else {
            // Ensure that {value} is a HeapObject.
            value = effect = graph()->NewNode(simplified()->CheckHeapObject(),
                                              value, effect, control);
2387
          }
2388 2389 2390
          field_access.write_barrier_kind = kPointerWriteBarrier;

        } else {
2391
          DCHECK(field_representation == MachineRepresentation::kTagged);
2392
        }
2393 2394 2395
        break;
      case MachineRepresentation::kNone:
      case MachineRepresentation::kBit:
2396 2397
      case MachineRepresentation::kCompressedPointer:
      case MachineRepresentation::kCompressed:
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
      case MachineRepresentation::kWord8:
      case MachineRepresentation::kWord16:
      case MachineRepresentation::kWord32:
      case MachineRepresentation::kWord64:
      case MachineRepresentation::kFloat32:
      case MachineRepresentation::kSimd128:
        UNREACHABLE();
        break;
    }
    // Check if we need to perform a transitioning store.
    Handle<Map> transition_map;
    if (access_info.transition_map().ToHandle(&transition_map)) {
      // Check if we need to grow the properties backing store
      // with this transitioning store.
2412 2413 2414
      MapRef transition_map_ref(broker(), transition_map);
      MapRef original_map = transition_map_ref.GetBackPointer().AsMap();
      if (original_map.UnusedPropertyFields() == 0) {
2415 2416 2417 2418
        DCHECK(!field_index.is_inobject());

        // Reallocate the properties {storage}.
        storage = effect = BuildExtendPropertiesBackingStore(
2419
            original_map, storage, effect, control);
2420 2421

        // Perform the actual store.
2422 2423
        effect = graph()->NewNode(simplified()->StoreField(field_access),
                                  storage, value, effect, control);
2424 2425

        // Atomically switch to the new properties below.
2426
        field_access = AccessBuilder::ForJSObjectPropertiesOrHashKnownPointer();
2427 2428
        value = storage;
        storage = receiver;
2429
      }
2430 2431 2432 2433
      effect = graph()->NewNode(
          common()->BeginRegion(RegionObservability::kObservable), effect);
      effect = graph()->NewNode(
          simplified()->StoreField(AccessBuilder::ForMap()), receiver,
2434
          jsgraph()->Constant(transition_map_ref), effect, control);
2435 2436 2437 2438 2439 2440 2441 2442
      effect = graph()->NewNode(simplified()->StoreField(field_access), storage,
                                value, effect, control);
      effect = graph()->NewNode(common()->FinishRegion(),
                                jsgraph()->UndefinedConstant(), effect);
    } else {
      // Regular non-transitioning field store.
      effect = graph()->NewNode(simplified()->StoreField(field_access), storage,
                                value, effect, control);
2443 2444 2445 2446 2447 2448
    }
  }

  return ValueEffectControl(value, effect, control);
}

2449 2450
Reduction JSNativeContextSpecialization::ReduceJSStoreDataPropertyInLiteral(
    Node* node) {
2451
  DCHECK_EQ(IrOpcode::kJSStoreDataPropertyInLiteral, node->opcode());
2452
  FeedbackParameter const& p = FeedbackParameterOf(node->op());
2453 2454
  Node* const key = NodeProperties::GetValueInput(node, 1);
  Node* const value = NodeProperties::GetValueInput(node, 2);
2455
  Node* const flags = NodeProperties::GetValueInput(node, 3);
2456 2457

  if (!p.feedback().IsValid()) return NoChange();
2458 2459 2460 2461 2462 2463 2464

  NumberMatcher mflags(flags);
  CHECK(mflags.HasValue());
  DataPropertyInLiteralFlags cflags(mflags.Value());
  DCHECK(!(cflags & DataPropertyInLiteralFlag::kDontEnum));
  if (cflags & DataPropertyInLiteralFlag::kSetFunctionName) return NoChange();

2465 2466 2467
  return ReducePropertyAccess(node, key, base::nullopt, value,
                              FeedbackSource(p.feedback()),
                              AccessMode::kStoreInLiteral);
2468 2469
}

2470 2471 2472 2473 2474 2475 2476 2477
Reduction JSNativeContextSpecialization::ReduceJSStoreInArrayLiteral(
    Node* node) {
  DCHECK_EQ(IrOpcode::kJSStoreInArrayLiteral, node->opcode());
  FeedbackParameter const& p = FeedbackParameterOf(node->op());
  Node* const index = NodeProperties::GetValueInput(node, 1);
  Node* const value = NodeProperties::GetValueInput(node, 2);

  if (!p.feedback().IsValid()) return NoChange();
2478 2479 2480
  return ReducePropertyAccess(node, index, base::nullopt, value,
                              FeedbackSource(p.feedback()),
                              AccessMode::kStoreInLiteral);
2481 2482
}

2483 2484 2485 2486 2487
Reduction JSNativeContextSpecialization::ReduceJSToObject(Node* node) {
  DCHECK_EQ(IrOpcode::kJSToObject, node->opcode());
  Node* receiver = NodeProperties::GetValueInput(node, 0);
  Node* effect = NodeProperties::GetEffectInput(node);

2488 2489 2490
  MapInference inference(broker(), receiver, effect);
  if (!inference.HaveMaps() || !inference.AllOfInstanceTypesAreJSReceiver()) {
    return NoChange();
2491 2492 2493 2494 2495 2496
  }

  ReplaceWithValue(node, receiver, effect);
  return Replace(receiver);
}

2497 2498 2499 2500
namespace {

ExternalArrayType GetArrayTypeFromElementsKind(ElementsKind kind) {
  switch (kind) {
2501 2502
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
  case TYPE##_ELEMENTS:                           \
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
    return kExternal##Type##Array;
    TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
    default:
      break;
  }
  UNREACHABLE();
}

}  // namespace

2514 2515 2516
JSNativeContextSpecialization::ValueEffectControl
JSNativeContextSpecialization::BuildElementAccess(
    Node* receiver, Node* index, Node* value, Node* effect, Node* control,
2517
    ElementAccessInfo const& access_info, KeyedAccessMode const& keyed_mode) {
2518 2519 2520
  // TODO(bmeurer): We currently specialize based on elements kind. We should
  // also be able to properly support strings and other JSObjects here.
  ElementsKind elements_kind = access_info.elements_kind();
2521
  ZoneVector<Handle<Map>> const& receiver_maps = access_info.receiver_maps();
2522

2523 2524
  if (IsTypedArrayElementsKind(elements_kind)) {
    Node* buffer_or_receiver = receiver;
2525 2526 2527 2528
    Node* length;
    Node* base_pointer;
    Node* external_pointer;

2529
    // Check if we can constant-fold information about the {receiver} (e.g.
2530
    // for asm.js-like code patterns).
2531
    base::Optional<JSTypedArrayRef> typed_array =
2532
        GetTypedArrayConstant(broker(), receiver);
2533
    if (typed_array.has_value()) {
2534
      length = jsgraph()->Constant(static_cast<double>(typed_array->length()));
2535

2536 2537 2538 2539 2540 2541
      DCHECK(!typed_array->is_on_heap());
      // Load the (known) data pointer for the {receiver} and set {base_pointer}
      // and {external_pointer} to the values that will allow to generate typed
      // element accesses using the known data pointer.
      // The data pointer might be invalid if the {buffer} was detached,
      // so we need to make sure that any access is properly guarded.
2542
      base_pointer = jsgraph()->ZeroConstant();
2543
      external_pointer = jsgraph()->PointerConstant(typed_array->data_ptr());
2544 2545 2546 2547 2548 2549
    } else {
      // Load the {receiver}s length.
      length = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForJSTypedArrayLength()),
          receiver, effect, control);

2550 2551 2552 2553 2554
      // Load the base pointer for the {receiver}. This will always be Smi
      // zero unless we allow on-heap TypedArrays, which is only the case
      // for Chrome. Node and Electron both set this limit to 0. Setting
      // the base to Smi zero here allows the EffectControlLinearizer to
      // optimize away the tricky part of the access later.
2555
      if (JSTypedArray::kMaxSizeInHeap == 0) {
2556 2557
        base_pointer = jsgraph()->ZeroConstant();
      } else {
2558 2559 2560 2561
        base_pointer = effect =
            graph()->NewNode(simplified()->LoadField(
                                 AccessBuilder::ForJSTypedArrayBasePointer()),
                             receiver, effect, control);
2562 2563
      }

2564 2565 2566 2567 2568
      // Load the external pointer for the {receiver}.
      external_pointer = effect =
          graph()->NewNode(simplified()->LoadField(
                               AccessBuilder::ForJSTypedArrayExternalPointer()),
                           receiver, effect, control);
2569
    }
2570

2571
    // See if we can skip the detaching check.
2572
    if (!dependencies()->DependOnArrayBufferDetachingProtector()) {
2573 2574 2575 2576 2577 2578 2579 2580 2581
      // Load the buffer for the {receiver}.
      Node* buffer =
          typed_array.has_value()
              ? jsgraph()->Constant(typed_array->buffer())
              : (effect = graph()->NewNode(
                     simplified()->LoadField(
                         AccessBuilder::ForJSArrayBufferViewBuffer()),
                     receiver, effect, control));

2582 2583
      // Deopt if the {buffer} was detached.
      // Note: A detached buffer leads to megamorphic feedback.
2584 2585 2586 2587 2588 2589 2590
      Node* buffer_bit_field = effect = graph()->NewNode(
          simplified()->LoadField(AccessBuilder::ForJSArrayBufferBitField()),
          buffer, effect, control);
      Node* check = graph()->NewNode(
          simplified()->NumberEqual(),
          graph()->NewNode(
              simplified()->NumberBitwiseAnd(), buffer_bit_field,
2591
              jsgraph()->Constant(JSArrayBuffer::WasDetachedBit::kMask)),
2592 2593
          jsgraph()->ZeroConstant());
      effect = graph()->NewNode(
2594
          simplified()->CheckIf(DeoptimizeReason::kArrayBufferWasDetached),
2595
          check, effect, control);
2596 2597 2598

      // Retain the {buffer} instead of {receiver} to reduce live ranges.
      buffer_or_receiver = buffer;
2599
    }
2600

2601 2602
    enum Situation { kBoundsCheckDone, kHandleOOB_SmiCheckDone };
    Situation situation;
2603 2604 2605 2606
    if ((keyed_mode.IsLoad() &&
         keyed_mode.load_mode() == LOAD_IGNORE_OUT_OF_BOUNDS) ||
        (keyed_mode.IsStore() &&
         keyed_mode.store_mode() == STORE_IGNORE_OUT_OF_BOUNDS)) {
2607
      // Only check that the {index} is in SignedSmall range. We do the actual
2608
      // bounds check below and just skip the property access if it's out of
2609
      // bounds for the {receiver}.
2610
      index = effect = graph()->NewNode(
2611
          simplified()->CheckSmi(FeedbackSource()), index, effect, control);
2612 2613 2614 2615 2616

      // Cast the {index} to Unsigned32 range, so that the bounds checks
      // below are performed on unsigned values, which means that all the
      // Negative32 values are treated as out-of-bounds.
      index = graph()->NewNode(simplified()->NumberToUint32(), index);
2617
      situation = kHandleOOB_SmiCheckDone;
2618
    } else {
2619
      // Check that the {index} is in the valid range for the {receiver}.
2620 2621 2622 2623
      index = effect = graph()->NewNode(
          simplified()->CheckBounds(
              FeedbackSource(), CheckBoundsFlag::kConvertStringAndMinusZero),
          index, length, effect, control);
2624
      situation = kBoundsCheckDone;
2625
    }
2626 2627 2628 2629

    // Access the actual element.
    ExternalArrayType external_array_type =
        GetArrayTypeFromElementsKind(elements_kind);
2630
    switch (keyed_mode.access_mode()) {
2631
      case AccessMode::kLoad: {
2632
        // Check if we can return undefined for out-of-bounds loads.
2633
        if (situation == kHandleOOB_SmiCheckDone) {
2634 2635
          Node* check =
              graph()->NewNode(simplified()->NumberLessThan(), index, length);
2636 2637 2638 2639
          Node* branch = graph()->NewNode(
              common()->Branch(BranchHint::kTrue,
                               IsSafetyCheck::kCriticalSafetyCheck),
              check, control);
2640 2641 2642 2643 2644

          Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
          Node* etrue = effect;
          Node* vtrue;
          {
2645 2646 2647 2648 2649 2650
            // Do a real bounds check against {length}. This is in order to
            // protect against a potential typer bug leading to the elimination
            // of the NumberLessThan above.
            index = etrue = graph()->NewNode(
                simplified()->CheckBounds(
                    FeedbackSource(),
2651 2652
                    CheckBoundsFlag::kConvertStringAndMinusZero |
                        CheckBoundsFlag::kAbortOnOutOfBounds),
2653 2654
                index, length, etrue, if_true);

2655 2656
            // Perform the actual load
            vtrue = etrue = graph()->NewNode(
2657 2658 2659
                simplified()->LoadTypedElement(external_array_type),
                buffer_or_receiver, base_pointer, external_pointer, index,
                etrue, if_true);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
          }

          Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
          Node* efalse = effect;
          Node* vfalse;
          {
            // Materialize undefined for out-of-bounds loads.
            vfalse = jsgraph()->UndefinedConstant();
          }

          control = graph()->NewNode(common()->Merge(2), if_true, if_false);
          effect =
              graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
          value =
              graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                               vtrue, vfalse, control);
        } else {
          // Perform the actual load.
2678
          DCHECK_EQ(kBoundsCheckDone, situation);
2679
          value = effect = graph()->NewNode(
2680 2681 2682
              simplified()->LoadTypedElement(external_array_type),
              buffer_or_receiver, base_pointer, external_pointer, index, effect,
              control);
2683
        }
2684
        break;
2685
      }
2686 2687 2688
      case AccessMode::kStoreInLiteral:
        UNREACHABLE();
        break;
2689
      case AccessMode::kStore: {
2690 2691
        // Ensure that the {value} is actually a Number or an Oddball,
        // and truncate it to a Number appropriately.
2692 2693
        value = effect = graph()->NewNode(
            simplified()->SpeculativeToNumber(
2694
                NumberOperationHint::kNumberOrOddball, FeedbackSource()),
2695
            value, effect, control);
2696

2697 2698 2699 2700 2701 2702 2703 2704
        // Introduce the appropriate truncation for {value}. Currently we
        // only need to do this for ClamedUint8Array {receiver}s, as the
        // other truncations are implicit in the StoreTypedElement, but we
        // might want to change that at some point.
        if (external_array_type == kExternalUint8ClampedArray) {
          value = graph()->NewNode(simplified()->NumberToUint8Clamped(), value);
        }

2705 2706 2707
        if (situation == kHandleOOB_SmiCheckDone) {
          // We have to detect OOB stores and handle them without deopt (by
          // simply not performing them).
2708 2709 2710 2711 2712 2713 2714 2715
          Node* check =
              graph()->NewNode(simplified()->NumberLessThan(), index, length);
          Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue),
                                          check, control);

          Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
          Node* etrue = effect;
          {
2716 2717 2718 2719 2720 2721
            // Do a real bounds check against {length}. This is in order to
            // protect against a potential typer bug leading to the elimination
            // of the NumberLessThan above.
            index = etrue = graph()->NewNode(
                simplified()->CheckBounds(
                    FeedbackSource(),
2722 2723
                    CheckBoundsFlag::kConvertStringAndMinusZero |
                        CheckBoundsFlag::kAbortOnOutOfBounds),
2724 2725
                index, length, etrue, if_true);

2726 2727
            // Perform the actual store.
            etrue = graph()->NewNode(
2728 2729 2730
                simplified()->StoreTypedElement(external_array_type),
                buffer_or_receiver, base_pointer, external_pointer, index,
                value, etrue, if_true);
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
          }

          Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
          Node* efalse = effect;
          {
            // Just ignore the out-of-bounds write.
          }

          control = graph()->NewNode(common()->Merge(2), if_true, if_false);
          effect =
              graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
        } else {
          // Perform the actual store
2744
          DCHECK_EQ(kBoundsCheckDone, situation);
2745
          effect = graph()->NewNode(
2746 2747 2748
              simplified()->StoreTypedElement(external_array_type),
              buffer_or_receiver, base_pointer, external_pointer, index, value,
              effect, control);
2749
        }
2750
        break;
2751
      }
2752
      case AccessMode::kHas:
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
        if (situation == kHandleOOB_SmiCheckDone) {
          value = effect =
              graph()->NewNode(simplified()->SpeculativeNumberLessThan(
                                   NumberOperationHint::kSignedSmall),
                               index, length, effect, control);
        } else {
          DCHECK_EQ(kBoundsCheckDone, situation);
          // For has-property on a typed array, all we need is a bounds check.
          value = jsgraph()->TrueConstant();
        }
2763
        break;
2764 2765
    }
  } else {
2766 2767 2768 2769 2770
    // Load the elements for the {receiver}.
    Node* elements = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForJSObjectElements()), receiver,
        effect, control);

2771 2772
    // Don't try to store to a copy-on-write backing store (unless supported by
    // the store mode).
2773
    if (keyed_mode.access_mode() == AccessMode::kStore &&
2774
        IsSmiOrObjectElementsKind(elements_kind) &&
2775
        !IsCOWHandlingStoreMode(keyed_mode.store_mode())) {
2776 2777 2778 2779 2780
      effect = graph()->NewNode(
          simplified()->CheckMaps(
              CheckMapsFlag::kNone,
              ZoneHandleSet<Map>(factory()->fixed_array_map())),
          elements, effect, control);
2781 2782
    }

2783
    // Check if the {receiver} is a JSArray.
2784
    bool receiver_is_jsarray = HasOnlyJSArrayMaps(broker(), receiver_maps);
2785

2786 2787
    // Load the length of the {receiver}.
    Node* length = effect =
2788
        receiver_is_jsarray
2789 2790 2791 2792 2793 2794 2795 2796
            ? graph()->NewNode(
                  simplified()->LoadField(
                      AccessBuilder::ForJSArrayLength(elements_kind)),
                  receiver, effect, control)
            : graph()->NewNode(
                  simplified()->LoadField(AccessBuilder::ForFixedArrayLength()),
                  elements, effect, control);

2797
    // Check if we might need to grow the {elements} backing store.
2798
    if (keyed_mode.IsStore() && IsGrowStoreMode(keyed_mode.store_mode())) {
2799
      // For growing stores we validate the {index} below.
2800 2801
    } else if (keyed_mode.IsLoad() &&
               keyed_mode.load_mode() == LOAD_IGNORE_OUT_OF_BOUNDS &&
2802
               CanTreatHoleAsUndefined(receiver_maps)) {
2803 2804 2805
      // Check that the {index} is a valid array index, we do the actual
      // bounds check below and just skip the store below if it's out of
      // bounds for the {receiver}.
2806
      index = effect = graph()->NewNode(
2807 2808 2809
          simplified()->CheckBounds(
              FeedbackSource(), CheckBoundsFlag::kConvertStringAndMinusZero),
          index, jsgraph()->Constant(Smi::kMaxValue), effect, control);
2810
    } else {
2811
      // Check that the {index} is in the valid range for the {receiver}.
2812 2813 2814 2815
      index = effect = graph()->NewNode(
          simplified()->CheckBounds(
              FeedbackSource(), CheckBoundsFlag::kConvertStringAndMinusZero),
          index, length, effect, control);
2816
    }
2817 2818

    // Compute the element access.
2819
    Type element_type = Type::NonInternal();
2820
    MachineType element_machine_type = MachineType::AnyTagged();
2821
    if (IsDoubleElementsKind(elements_kind)) {
2822 2823
      element_type = Type::Number();
      element_machine_type = MachineType::Float64();
2824
    } else if (IsSmiElementsKind(elements_kind)) {
2825
      element_type = Type::SignedSmall();
2826
      element_machine_type = MachineType::TaggedSigned();
2827
    }
2828 2829 2830 2831
    ElementAccess element_access = {
        kTaggedBase,       FixedArray::kHeaderSize,
        element_type,      element_machine_type,
        kFullWriteBarrier, LoadSensitivity::kCritical};
2832 2833

    // Access the actual element.
2834
    if (keyed_mode.access_mode() == AccessMode::kLoad) {
2835 2836
      // Compute the real element access type, which includes the hole in case
      // of holey backing stores.
2837
      if (IsHoleyElementsKind(elements_kind)) {
2838 2839
        element_access.type =
            Type::Union(element_type, Type::Hole(), graph()->zone());
2840
      }
2841 2842
      if (elements_kind == HOLEY_ELEMENTS ||
          elements_kind == HOLEY_SMI_ELEMENTS) {
2843
        element_access.machine_type = MachineType::AnyTagged();
2844
      }
2845 2846

      // Check if we can return undefined for out-of-bounds loads.
2847
      if (keyed_mode.load_mode() == LOAD_IGNORE_OUT_OF_BOUNDS &&
2848 2849 2850
          CanTreatHoleAsUndefined(receiver_maps)) {
        Node* check =
            graph()->NewNode(simplified()->NumberLessThan(), index, length);
2851 2852 2853 2854
        Node* branch = graph()->NewNode(
            common()->Branch(BranchHint::kTrue,
                             IsSafetyCheck::kCriticalSafetyCheck),
            check, control);
2855 2856 2857 2858 2859

        Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
        Node* etrue = effect;
        Node* vtrue;
        {
2860 2861 2862
          // Do a real bounds check against {length}. This is in order to
          // protect against a potential typer bug leading to the elimination of
          // the NumberLessThan above.
2863 2864 2865 2866 2867 2868
          index = etrue =
              graph()->NewNode(simplified()->CheckBounds(
                                   FeedbackSource(),
                                   CheckBoundsFlag::kConvertStringAndMinusZero |
                                       CheckBoundsFlag::kAbortOnOutOfBounds),
                               index, length, etrue, if_true);
2869

2870 2871 2872
          // Perform the actual load
          vtrue = etrue =
              graph()->NewNode(simplified()->LoadElement(element_access),
2873
                               elements, index, etrue, if_true);
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885

          // Handle loading from holey backing stores correctly, by either
          // mapping the hole to undefined if possible, or deoptimizing
          // otherwise.
          if (elements_kind == HOLEY_ELEMENTS ||
              elements_kind == HOLEY_SMI_ELEMENTS) {
            // Turn the hole into undefined.
            vtrue = graph()->NewNode(
                simplified()->ConvertTaggedHoleToUndefined(), vtrue);
          } else if (elements_kind == HOLEY_DOUBLE_ELEMENTS) {
            // Return the signaling NaN hole directly if all uses are
            // truncating.
2886 2887
            vtrue = etrue = graph()->NewNode(
                simplified()->CheckFloat64Hole(
2888
                    CheckFloat64HoleMode::kAllowReturnHole, FeedbackSource()),
2889
                vtrue, etrue, if_true);
2890 2891 2892 2893 2894 2895 2896 2897 2898
          }
        }

        Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
        Node* efalse = effect;
        Node* vfalse;
        {
          // Materialize undefined for out-of-bounds loads.
          vfalse = jsgraph()->UndefinedConstant();
2899
        }
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910

        control = graph()->NewNode(common()->Merge(2), if_true, if_false);
        effect =
            graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
        value =
            graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                             vtrue, vfalse, control);
      } else {
        // Perform the actual load.
        value = effect =
            graph()->NewNode(simplified()->LoadElement(element_access),
2911
                             elements, index, effect, control);
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936

        // Handle loading from holey backing stores correctly, by either mapping
        // the hole to undefined if possible, or deoptimizing otherwise.
        if (elements_kind == HOLEY_ELEMENTS ||
            elements_kind == HOLEY_SMI_ELEMENTS) {
          // Check if we are allowed to turn the hole into undefined.
          if (CanTreatHoleAsUndefined(receiver_maps)) {
            // Turn the hole into undefined.
            value = graph()->NewNode(
                simplified()->ConvertTaggedHoleToUndefined(), value);
          } else {
            // Bailout if we see the hole.
            value = effect = graph()->NewNode(
                simplified()->CheckNotTaggedHole(), value, effect, control);
          }
        } else if (elements_kind == HOLEY_DOUBLE_ELEMENTS) {
          // Perform the hole check on the result.
          CheckFloat64HoleMode mode = CheckFloat64HoleMode::kNeverReturnHole;
          // Check if we are allowed to return the hole directly.
          if (CanTreatHoleAsUndefined(receiver_maps)) {
            // Return the signaling NaN hole directly if all uses are
            // truncating.
            mode = CheckFloat64HoleMode::kAllowReturnHole;
          }
          value = effect = graph()->NewNode(
2937
              simplified()->CheckFloat64Hole(mode, FeedbackSource()), value,
2938
              effect, control);
2939 2940
        }
      }
2941
    } else if (keyed_mode.access_mode() == AccessMode::kHas) {
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
      // For packed arrays with NoElementsProctector valid, a bound check
      // is equivalent to HasProperty.
      value = effect = graph()->NewNode(simplified()->SpeculativeNumberLessThan(
                                            NumberOperationHint::kSignedSmall),
                                        index, length, effect, control);
      if (IsHoleyElementsKind(elements_kind)) {
        // If the index is in bounds, do a load and hole check.

        Node* branch = graph()->NewNode(common()->Branch(), value, control);

        Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
        Node* efalse = effect;
        Node* vfalse = jsgraph()->FalseConstant();

        element_access.type =
            Type::Union(element_type, Type::Hole(), graph()->zone());

        if (elements_kind == HOLEY_ELEMENTS ||
            elements_kind == HOLEY_SMI_ELEMENTS) {
2961
          element_access.machine_type = MachineType::AnyTagged();
2962 2963 2964 2965 2966
        }

        Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
        Node* etrue = effect;

2967 2968 2969 2970
        Node* checked = etrue = graph()->NewNode(
            simplified()->CheckBounds(
                FeedbackSource(), CheckBoundsFlag::kConvertStringAndMinusZero),
            index, length, etrue, if_true);
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999

        Node* element = etrue =
            graph()->NewNode(simplified()->LoadElement(element_access),
                             elements, checked, etrue, if_true);

        Node* vtrue;
        if (CanTreatHoleAsUndefined(receiver_maps)) {
          if (elements_kind == HOLEY_ELEMENTS ||
              elements_kind == HOLEY_SMI_ELEMENTS) {
            // Check if we are allowed to turn the hole into undefined.
            // Turn the hole into undefined.
            vtrue = graph()->NewNode(simplified()->ReferenceEqual(), element,
                                     jsgraph()->TheHoleConstant());
          } else {
            vtrue =
                graph()->NewNode(simplified()->NumberIsFloat64Hole(), element);
          }

          // has == !IsHole
          vtrue = graph()->NewNode(simplified()->BooleanNot(), vtrue);
        } else {
          if (elements_kind == HOLEY_ELEMENTS ||
              elements_kind == HOLEY_SMI_ELEMENTS) {
            // Bailout if we see the hole.
            etrue = graph()->NewNode(simplified()->CheckNotTaggedHole(),
                                     element, etrue, if_true);
          } else {
            etrue = graph()->NewNode(
                simplified()->CheckFloat64Hole(
3000
                    CheckFloat64HoleMode::kNeverReturnHole, FeedbackSource()),
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
                element, etrue, if_true);
          }

          vtrue = jsgraph()->TrueConstant();
        }

        control = graph()->NewNode(common()->Merge(2), if_true, if_false);
        effect =
            graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
        value =
            graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                             vtrue, vfalse, control);
      }
3014
    } else {
3015 3016 3017
      DCHECK(keyed_mode.access_mode() == AccessMode::kStore ||
             keyed_mode.access_mode() == AccessMode::kStoreInLiteral);

3018
      if (IsSmiElementsKind(elements_kind)) {
3019
        value = effect = graph()->NewNode(
3020
            simplified()->CheckSmi(FeedbackSource()), value, effect, control);
3021
      } else if (IsDoubleElementsKind(elements_kind)) {
3022
        value = effect =
3023
            graph()->NewNode(simplified()->CheckNumber(FeedbackSource()), value,
3024
                             effect, control);
3025 3026 3027
        // Make sure we do not store signalling NaNs into double arrays.
        value = graph()->NewNode(simplified()->NumberSilenceNaN(), value);
      }
3028 3029

      // Ensure that copy-on-write backing store is writable.
3030
      if (IsSmiOrObjectElementsKind(elements_kind) &&
3031
          keyed_mode.store_mode() == STORE_HANDLE_COW) {
3032 3033 3034
        elements = effect =
            graph()->NewNode(simplified()->EnsureWritableFastElements(),
                             receiver, elements, effect, control);
3035
      } else if (IsGrowStoreMode(keyed_mode.store_mode())) {
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
        // Determine the length of the {elements} backing store.
        Node* elements_length = effect = graph()->NewNode(
            simplified()->LoadField(AccessBuilder::ForFixedArrayLength()),
            elements, effect, control);

        // Validate the {index} depending on holeyness:
        //
        // For HOLEY_*_ELEMENTS the {index} must not exceed the {elements}
        // backing store capacity plus the maximum allowed gap, as otherwise
        // the (potential) backing store growth would normalize and thus
        // the elements kind of the {receiver} would change to slow mode.
        //
        // For PACKED_*_ELEMENTS the {index} must be within the range
        // [0,length+1[ to be valid. In case {index} equals {length},
        // the {receiver} will be extended, but kept packed.
        Node* limit =
            IsHoleyElementsKind(elements_kind)
                ? graph()->NewNode(simplified()->NumberAdd(), elements_length,
                                   jsgraph()->Constant(JSObject::kMaxGap))
                : graph()->NewNode(simplified()->NumberAdd(), length,
                                   jsgraph()->OneConstant());
3057 3058 3059 3060
        index = effect = graph()->NewNode(
            simplified()->CheckBounds(
                FeedbackSource(), CheckBoundsFlag::kConvertStringAndMinusZero),
            index, limit, effect, control);
3061 3062 3063 3064 3065 3066 3067

        // Grow {elements} backing store if necessary.
        GrowFastElementsMode mode =
            IsDoubleElementsKind(elements_kind)
                ? GrowFastElementsMode::kDoubleElements
                : GrowFastElementsMode::kSmiOrObjectElements;
        elements = effect = graph()->NewNode(
3068
            simplified()->MaybeGrowFastElements(mode, FeedbackSource()),
3069
            receiver, elements, index, elements_length, effect, control);
3070

3071 3072 3073
        // If we didn't grow {elements}, it might still be COW, in which case we
        // copy it now.
        if (IsSmiOrObjectElementsKind(elements_kind) &&
3074
            keyed_mode.store_mode() == STORE_AND_GROW_HANDLE_COW) {
3075 3076 3077 3078 3079
          elements = effect =
              graph()->NewNode(simplified()->EnsureWritableFastElements(),
                               receiver, elements, effect, control);
        }

3080
        // Also update the "length" property if {receiver} is a JSArray.
3081
        if (receiver_is_jsarray) {
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
          Node* check =
              graph()->NewNode(simplified()->NumberLessThan(), index, length);
          Node* branch = graph()->NewNode(common()->Branch(), check, control);

          Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
          Node* etrue = effect;
          {
            // We don't need to do anything, the {index} is within
            // the valid bounds for the JSArray {receiver}.
          }

          Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
          Node* efalse = effect;
          {
            // Update the JSArray::length field. Since this is observable,
            // there must be no other check after this.
            Node* new_length = graph()->NewNode(
                simplified()->NumberAdd(), index, jsgraph()->OneConstant());
            efalse = graph()->NewNode(
                simplified()->StoreField(
                    AccessBuilder::ForJSArrayLength(elements_kind)),
                receiver, new_length, efalse, if_false);
          }

          control = graph()->NewNode(common()->Merge(2), if_true, if_false);
          effect =
              graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control);
3109
        }
3110 3111 3112
      }

      // Perform the actual element access.
3113 3114
      effect = graph()->NewNode(simplified()->StoreElement(element_access),
                                elements, index, value, effect, control);
3115 3116 3117 3118 3119
    }
  }

  return ValueEffectControl(value, effect, control);
}
3120

3121 3122 3123 3124
Node* JSNativeContextSpecialization::BuildIndexedStringLoad(
    Node* receiver, Node* index, Node* length, Node** effect, Node** control,
    KeyedAccessLoadMode load_mode) {
  if (load_mode == LOAD_IGNORE_OUT_OF_BOUNDS &&
3125
      dependencies()->DependOnNoElementsProtector()) {
3126
    // Ensure that the {index} is a valid String length.
3127
    index = *effect = graph()->NewNode(
3128 3129 3130
        simplified()->CheckBounds(FeedbackSource(),
                                  CheckBoundsFlag::kConvertStringAndMinusZero),
        index, jsgraph()->Constant(String::kMaxLength), *effect, *control);
3131 3132 3133 3134 3135 3136

    // Load the single character string from {receiver} or yield
    // undefined if the {index} is not within the valid bounds.
    Node* check =
        graph()->NewNode(simplified()->NumberLessThan(), index, length);
    Node* branch =
3137 3138 3139
        graph()->NewNode(common()->Branch(BranchHint::kTrue,
                                          IsSafetyCheck::kCriticalSafetyCheck),
                         check, *control);
3140 3141

    Node* if_true = graph()->NewNode(common()->IfTrue(), branch);
3142 3143 3144 3145 3146
    // Do a real bounds check against {length}. This is in order to protect
    // against a potential typer bug leading to the elimination of the
    // NumberLessThan above.
    Node* etrue = index = graph()->NewNode(
        simplified()->CheckBounds(FeedbackSource(),
3147 3148
                                  CheckBoundsFlag::kConvertStringAndMinusZero |
                                      CheckBoundsFlag::kAbortOnOutOfBounds),
3149 3150
        index, length, *effect, if_true);
    Node* masked_index = graph()->NewNode(simplified()->PoisonIndex(), index);
3151 3152
    Node* vtrue = etrue =
        graph()->NewNode(simplified()->StringCharCodeAt(), receiver,
3153
                         masked_index, etrue, if_true);
3154
    vtrue = graph()->NewNode(simplified()->StringFromSingleCharCode(), vtrue);
3155 3156 3157 3158 3159

    Node* if_false = graph()->NewNode(common()->IfFalse(), branch);
    Node* vfalse = jsgraph()->UndefinedConstant();

    *control = graph()->NewNode(common()->Merge(2), if_true, if_false);
3160 3161
    *effect =
        graph()->NewNode(common()->EffectPhi(2), etrue, *effect, *control);
3162 3163 3164 3165
    return graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2),
                            vtrue, vfalse, *control);
  } else {
    // Ensure that {index} is less than {receiver} length.
3166 3167 3168 3169
    index = *effect = graph()->NewNode(
        simplified()->CheckBounds(FeedbackSource(),
                                  CheckBoundsFlag::kConvertStringAndMinusZero),
        index, length, *effect, *control);
3170

3171
    Node* masked_index = graph()->NewNode(simplified()->PoisonIndex(), index);
3172

3173
    // Return the character from the {receiver} as single character string.
3174
    Node* value = *effect =
3175 3176
        graph()->NewNode(simplified()->StringCharCodeAt(), receiver,
                         masked_index, *effect, *control);
3177
    value = graph()->NewNode(simplified()->StringFromSingleCharCode(), value);
3178
    return value;
3179 3180 3181
  }
}

3182
Node* JSNativeContextSpecialization::BuildExtendPropertiesBackingStore(
3183
    const MapRef& map, Node* properties, Node* effect, Node* control) {
3184 3185 3186 3187 3188 3189 3190 3191 3192
  // TODO(bmeurer/jkummerow): Property deletions can undo map transitions
  // while keeping the backing store around, meaning that even though the
  // map might believe that objects have no unused property fields, there
  // might actually be some. It would be nice to not create a new backing
  // store in that case (i.e. when properties->length() >= new_length).
  // However, introducing branches and Phi nodes here would make it more
  // difficult for escape analysis to get rid of the backing stores used
  // for intermediate states of chains of property additions. That makes
  // it unclear what the best approach is here.
3193
  DCHECK_EQ(0, map.UnusedPropertyFields());
3194
  // Compute the length of the old {properties} and the new properties.
3195
  int length = map.NextFreePropertyIndex() - map.GetInObjectProperties();
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209
  int new_length = length + JSObject::kFieldsAdded;
  // Collect the field values from the {properties}.
  ZoneVector<Node*> values(zone());
  values.reserve(new_length);
  for (int i = 0; i < length; ++i) {
    Node* value = effect = graph()->NewNode(
        simplified()->LoadField(AccessBuilder::ForFixedArraySlot(i)),
        properties, effect, control);
    values.push_back(value);
  }
  // Initialize the new fields to undefined.
  for (int i = 0; i < JSObject::kFieldsAdded; ++i) {
    values.push_back(jsgraph()->UndefinedConstant());
  }
3210

3211
  // Compute new length and hash.
3212 3213 3214 3215 3216 3217
  Node* hash;
  if (length == 0) {
    hash = graph()->NewNode(
        common()->Select(MachineRepresentation::kTaggedSigned),
        graph()->NewNode(simplified()->ObjectIsSmi(), properties), properties,
        jsgraph()->SmiConstant(PropertyArray::kNoHashSentinel));
3218 3219
    hash = effect = graph()->NewNode(common()->TypeGuard(Type::SignedSmall()),
                                     hash, effect, control);
3220 3221 3222
    hash =
        graph()->NewNode(simplified()->NumberShiftLeft(), hash,
                         jsgraph()->Constant(PropertyArray::HashField::kShift));
3223 3224
  } else {
    hash = effect = graph()->NewNode(
3225
        simplified()->LoadField(AccessBuilder::ForPropertyArrayLengthAndHash()),
3226
        properties, effect, control);
3227 3228 3229
    hash =
        graph()->NewNode(simplified()->NumberBitwiseAnd(), hash,
                         jsgraph()->Constant(PropertyArray::HashField::kMask));
3230 3231 3232
  }
  Node* new_length_and_hash = graph()->NewNode(
      simplified()->NumberBitwiseOr(), jsgraph()->Constant(new_length), hash);
3233 3234 3235 3236
  // TDOO(jarin): Fix the typer to infer tighter bound for NumberBitwiseOr.
  new_length_and_hash = effect =
      graph()->NewNode(common()->TypeGuard(Type::SignedSmall()),
                       new_length_and_hash, effect, control);
3237 3238

  // Allocate and initialize the new properties.
3239
  AllocationBuilder a(jsgraph(), effect, control);
3240
  a.Allocate(PropertyArray::SizeFor(new_length), AllocationType::kYoung,
3241 3242 3243
             Type::OtherInternal());
  a.Store(AccessBuilder::ForMap(), jsgraph()->PropertyArrayMapConstant());
  a.Store(AccessBuilder::ForPropertyArrayLengthAndHash(), new_length_and_hash);
3244
  for (int i = 0; i < new_length; ++i) {
3245
    a.Store(AccessBuilder::ForFixedArraySlot(i), values[i]);
3246
  }
3247
  return a.Finish();
3248 3249
}

3250
Node* JSNativeContextSpecialization::BuildCheckEqualsName(NameRef const& name,
3251 3252 3253
                                                          Node* value,
                                                          Node* effect,
                                                          Node* control) {
3254
  DCHECK(name.IsUniqueName());
3255
  Operator const* const op =
3256 3257 3258
      name.IsSymbol() ? simplified()->CheckEqualsSymbol()
                      : simplified()->CheckEqualsInternalizedString();
  return graph()->NewNode(op, jsgraph()->Constant(name), value, effect,
3259 3260 3261
                          control);
}

3262
bool JSNativeContextSpecialization::CanTreatHoleAsUndefined(
3263
    ZoneVector<Handle<Map>> const& receiver_maps) {
3264
  // Check if all {receiver_maps} have one of the initial Array.prototype
3265 3266
  // or Object.prototype objects as their prototype (in any of the current
  // native contexts, as the global Array protector works isolate-wide).
3267
  for (Handle<Map> map : receiver_maps) {
3268
    MapRef receiver_map(broker(), map);
3269 3270
    ObjectRef receiver_prototype = receiver_map.prototype();
    if (!receiver_prototype.IsJSObject() ||
3271
        !broker()->IsArrayOrObjectPrototype(receiver_prototype.AsJSObject())) {
3272 3273 3274 3275
      return false;
    }
  }

3276
  // Check if the array prototype chain is intact.
3277
  return dependencies()->DependOnNoElementsProtector();
3278 3279
}

3280
bool JSNativeContextSpecialization::InferReceiverMaps(
3281 3282
    Node* receiver, Node* effect,
    ZoneVector<Handle<Map>>* receiver_maps) const {
3283
  ZoneHandleSet<Map> maps;
3284
  NodeProperties::InferReceiverMapsResult result =
3285 3286
      NodeProperties::InferReceiverMapsUnsafe(broker(), receiver, effect,
                                              &maps);
3287 3288
  if (result == NodeProperties::kReliableReceiverMaps) {
    for (size_t i = 0; i < maps.size(); ++i) {
3289
      receiver_maps->push_back(maps[i]);
3290 3291 3292 3293 3294 3295
    }
    return true;
  } else if (result == NodeProperties::kUnreliableReceiverMaps) {
    // For untrusted receiver maps, we can still use the information
    // if the maps are stable.
    for (size_t i = 0; i < maps.size(); ++i) {
3296 3297
      MapRef map(broker(), maps[i]);
      if (!map.is_stable()) return false;
3298
    }
3299
    for (size_t i = 0; i < maps.size(); ++i) {
3300
      receiver_maps->push_back(maps[i]);
3301
    }
3302
    return true;
3303
  }
3304
  return false;
3305 3306
}

3307
base::Optional<MapRef> JSNativeContextSpecialization::InferReceiverRootMap(
3308
    Node* receiver) const {
3309 3310
  HeapObjectMatcher m(receiver);
  if (m.HasValue()) {
3311 3312
    MapRef map = m.Ref(broker()).map();
    return map.FindRootMap();
3313
  } else if (m.IsJSCreate()) {
3314 3315 3316
    base::Optional<MapRef> initial_map =
        NodeProperties::GetJSCreateMap(broker(), receiver);
    if (initial_map.has_value()) {
3317 3318 3319 3320 3321
      if (!initial_map->FindRootMap().has_value()) {
        return base::nullopt;
      }
      DCHECK(initial_map->equals(*initial_map->FindRootMap()));
      return *initial_map;
3322 3323
    }
  }
3324
  return base::nullopt;
3325
}
3326

3327 3328 3329
Graph* JSNativeContextSpecialization::graph() const {
  return jsgraph()->graph();
}
3330

3331
Isolate* JSNativeContextSpecialization::isolate() const {
3332 3333 3334
  return jsgraph()->isolate();
}

3335 3336 3337 3338
Factory* JSNativeContextSpecialization::factory() const {
  return isolate()->factory();
}

3339
CommonOperatorBuilder* JSNativeContextSpecialization::common() const {
3340 3341 3342
  return jsgraph()->common();
}

3343
JSOperatorBuilder* JSNativeContextSpecialization::javascript() const {
3344 3345 3346
  return jsgraph()->javascript();
}

3347
SimplifiedOperatorBuilder* JSNativeContextSpecialization::simplified() const {
3348 3349 3350
  return jsgraph()->simplified();
}

3351 3352 3353
}  // namespace compiler
}  // namespace internal
}  // namespace v8