hydrogen-instructions.cc 127 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/crankshaft/hydrogen-instructions.h"
6

7
#include "src/base/bits.h"
8
#include "src/base/ieee754.h"
9
#include "src/base/safe_math.h"
10
#include "src/codegen.h"
11
#include "src/crankshaft/hydrogen-infer-representation.h"
12
#include "src/double.h"
13
#include "src/elements.h"
14
#include "src/factory.h"
15 16

#if V8_TARGET_ARCH_IA32
17
#include "src/crankshaft/ia32/lithium-ia32.h"  // NOLINT
18
#elif V8_TARGET_ARCH_X64
19
#include "src/crankshaft/x64/lithium-x64.h"  // NOLINT
20
#elif V8_TARGET_ARCH_ARM64
21
#include "src/crankshaft/arm64/lithium-arm64.h"  // NOLINT
22
#elif V8_TARGET_ARCH_ARM
23
#include "src/crankshaft/arm/lithium-arm.h"  // NOLINT
24
#elif V8_TARGET_ARCH_PPC
25
#include "src/crankshaft/ppc/lithium-ppc.h"  // NOLINT
26
#elif V8_TARGET_ARCH_MIPS
27
#include "src/crankshaft/mips/lithium-mips.h"  // NOLINT
28
#elif V8_TARGET_ARCH_MIPS64
29
#include "src/crankshaft/mips64/lithium-mips64.h"  // NOLINT
30 31
#elif V8_TARGET_ARCH_S390
#include "src/crankshaft/s390/lithium-s390.h"  // NOLINT
danno@chromium.org's avatar
danno@chromium.org committed
32
#elif V8_TARGET_ARCH_X87
33
#include "src/crankshaft/x87/lithium-x87.h"  // NOLINT
34 35 36 37 38 39 40 41 42 43 44 45 46 47
#else
#error Unsupported target architecture.
#endif

namespace v8 {
namespace internal {

#define DEFINE_COMPILE(type)                                         \
  LInstruction* H##type::CompileToLithium(LChunkBuilder* builder) {  \
    return builder->Do##type(this);                                  \
  }
HYDROGEN_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
#undef DEFINE_COMPILE

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
Representation RepresentationFromMachineType(MachineType type) {
  if (type == MachineType::Int32()) {
    return Representation::Integer32();
  }

  if (type == MachineType::TaggedSigned()) {
    return Representation::Smi();
  }

  if (type == MachineType::Pointer()) {
    return Representation::External();
  }

  return Representation::Tagged();
}
63

64
Isolate* HValue::isolate() const {
65
  DCHECK(block() != NULL);
66
  return block()->isolate();
67 68 69
}


70 71 72 73 74 75 76 77 78 79
void HValue::AssumeRepresentation(Representation r) {
  if (CheckFlag(kFlexibleRepresentation)) {
    ChangeRepresentation(r);
    // The representation of the value is dictated by type feedback and
    // will not be changed later.
    ClearFlag(kFlexibleRepresentation);
  }
}


80
void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
81
  DCHECK(CheckFlag(kFlexibleRepresentation));
82 83 84 85
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  new_rep = RepresentationFromUses();
  UpdateRepresentation(new_rep, h_infer, "uses");
86 87 88
  if (representation().IsSmi() && HasNonSmiUse()) {
    UpdateRepresentation(
        Representation::Integer32(), h_infer, "use requirements");
89
  }
90 91 92 93 94
}


Representation HValue::RepresentationFromUses() {
  if (HasNoUses()) return Representation::None();
95
  Representation result = Representation::None();
96 97 98 99

  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
    Representation rep = use->observed_input_representation(it.index());
100 101
    result = result.generalize(rep);

102 103 104 105 106 107
    if (FLAG_trace_representation) {
      PrintF("#%d %s is used by #%d %s as %s%s\n",
             id(), Mnemonic(), use->id(), use->Mnemonic(), rep.Mnemonic(),
             (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
    }
  }
108 109 110 111
  if (IsPhi()) {
    result = result.generalize(
        HPhi::cast(this)->representation_from_indirect_uses());
  }
112

113 114
  // External representations are dealt with separately.
  return result.IsExternal() ? Representation::None() : result;
115 116 117 118
}


void HValue::UpdateRepresentation(Representation new_rep,
119
                                  HInferRepresentationPhase* h_infer,
120 121 122
                                  const char* reason) {
  Representation r = representation();
  if (new_rep.is_more_general_than(r)) {
123
    if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
124 125 126
    if (FLAG_trace_representation) {
      PrintF("Changing #%d %s representation %s -> %s based on %s\n",
             id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
127 128 129 130 131 132 133
    }
    ChangeRepresentation(new_rep);
    AddDependantsToWorklist(h_infer);
  }
}


134
void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
135 136 137 138 139 140 141 142 143
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    h_infer->AddToWorklist(it.value());
  }
  for (int i = 0; i < OperandCount(); ++i) {
    h_infer->AddToWorklist(OperandAt(i));
  }
}


144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
static int32_t ConvertAndSetOverflow(Representation r,
                                     int64_t result,
                                     bool* overflow) {
  if (r.IsSmi()) {
    if (result > Smi::kMaxValue) {
      *overflow = true;
      return Smi::kMaxValue;
    }
    if (result < Smi::kMinValue) {
      *overflow = true;
      return Smi::kMinValue;
    }
  } else {
    if (result > kMaxInt) {
      *overflow = true;
      return kMaxInt;
    }
    if (result < kMinInt) {
      *overflow = true;
      return kMinInt;
    }
165
  }
166
  return static_cast<int32_t>(result);
167 168 169
}


170 171 172 173
static int32_t AddWithoutOverflow(Representation r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
174
  int64_t result = static_cast<int64_t>(a) + static_cast<int64_t>(b);
175
  return ConvertAndSetOverflow(r, result, overflow);
176 177 178
}


179 180 181 182
static int32_t SubWithoutOverflow(Representation r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
183
  int64_t result = static_cast<int64_t>(a) - static_cast<int64_t>(b);
184
  return ConvertAndSetOverflow(r, result, overflow);
185
}
186 187


188 189 190 191
static int32_t MulWithoutOverflow(const Representation& r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
192
  int64_t result = static_cast<int64_t>(a) * static_cast<int64_t>(b);
193
  return ConvertAndSetOverflow(r, result, overflow);
194 195 196
}


197 198 199 200 201 202 203 204 205 206
int32_t Range::Mask() const {
  if (lower_ == upper_) return lower_;
  if (lower_ >= 0) {
    int32_t res = 1;
    while (res < upper_) {
      res = (res << 1) | 1;
    }
    return res;
  }
  return 0xffffffff;
207 208 209
}


210
void Range::AddConstant(int32_t value) {
211
  if (value == 0) return;
212
  bool may_overflow = false;  // Overflow is ignored here.
213 214 215
  Representation r = Representation::Integer32();
  lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
216
#ifdef DEBUG
217
  Verify();
218
#endif
219 220 221
}


222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
void Range::Intersect(Range* other) {
  upper_ = Min(upper_, other->upper_);
  lower_ = Max(lower_, other->lower_);
  bool b = CanBeMinusZero() && other->CanBeMinusZero();
  set_can_be_minus_zero(b);
}


void Range::Union(Range* other) {
  upper_ = Max(upper_, other->upper_);
  lower_ = Min(lower_, other->lower_);
  bool b = CanBeMinusZero() || other->CanBeMinusZero();
  set_can_be_minus_zero(b);
}


238 239 240 241 242 243 244 245 246 247 248 249 250 251
void Range::CombinedMax(Range* other) {
  upper_ = Max(upper_, other->upper_);
  lower_ = Max(lower_, other->lower_);
  set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
}


void Range::CombinedMin(Range* other) {
  upper_ = Min(upper_, other->upper_);
  lower_ = Min(lower_, other->lower_);
  set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
}


252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
void Range::Sar(int32_t value) {
  int32_t bits = value & 0x1F;
  lower_ = lower_ >> bits;
  upper_ = upper_ >> bits;
  set_can_be_minus_zero(false);
}


void Range::Shl(int32_t value) {
  int32_t bits = value & 0x1F;
  int old_lower = lower_;
  int old_upper = upper_;
  lower_ = lower_ << bits;
  upper_ = upper_ << bits;
  if (old_lower != lower_ >> bits || old_upper != upper_ >> bits) {
    upper_ = kMaxInt;
    lower_ = kMinInt;
  }
  set_can_be_minus_zero(false);
}


274
bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
275
  bool may_overflow = false;
276 277
  lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
278 279 280 281 282
  if (may_overflow) {
    Clear();
  } else {
    KeepOrder();
  }
283
#ifdef DEBUG
284
  Verify();
285
#endif
286
  return may_overflow;
287 288 289
}


290
bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
291
  bool may_overflow = false;
292 293
  lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
  upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
294 295 296 297 298
  if (may_overflow) {
    Clear();
  } else {
    KeepOrder();
  }
299
#ifdef DEBUG
300
  Verify();
301
#endif
302
  return may_overflow;
303 304
}

305 306 307 308
void Range::Clear() {
  lower_ = kMinInt;
  upper_ = kMaxInt;
}
309 310 311 312 313 314 315 316 317 318

void Range::KeepOrder() {
  if (lower_ > upper_) {
    int32_t tmp = lower_;
    lower_ = upper_;
    upper_ = tmp;
  }
}


319
#ifdef DEBUG
320
void Range::Verify() const {
321
  DCHECK(lower_ <= upper_);
322
}
323
#endif
324 325


326
bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
327
  bool may_overflow = false;
328 329 330 331
  int v1 = MulWithoutOverflow(r, lower_, other->lower(), &may_overflow);
  int v2 = MulWithoutOverflow(r, lower_, other->upper(), &may_overflow);
  int v3 = MulWithoutOverflow(r, upper_, other->lower(), &may_overflow);
  int v4 = MulWithoutOverflow(r, upper_, other->upper(), &may_overflow);
332 333 334 335 336 337
  if (may_overflow) {
    Clear();
  } else {
    lower_ = Min(Min(v1, v2), Min(v3, v4));
    upper_ = Max(Max(v1, v2), Max(v3, v4));
  }
338
#ifdef DEBUG
339
  Verify();
340
#endif
341 342 343 344
  return may_overflow;
}


345 346 347 348 349
bool HValue::IsDefinedAfter(HBasicBlock* other) const {
  return block()->block_id() > other->block_id();
}


350 351 352 353 354 355 356 357 358
HUseListNode* HUseListNode::tail() {
  // Skip and remove dead items in the use list.
  while (tail_ != NULL && tail_->value()->CheckFlag(HValue::kIsDead)) {
    tail_ = tail_->tail_;
  }
  return tail_;
}


359
bool HValue::CheckUsesForFlag(Flag f) const {
360
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
361
    if (it.value()->IsSimulate()) continue;
362 363 364
    if (!it.value()->CheckFlag(f)) return false;
  }
  return true;
365 366 367 368 369 370 371 372 373 374 375 376
}


bool HValue::CheckUsesForFlag(Flag f, HValue** value) const {
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    if (it.value()->IsSimulate()) continue;
    if (!it.value()->CheckFlag(f)) {
      *value = it.value();
      return false;
    }
  }
  return true;
377 378 379
}


380
bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
381 382 383 384 385 386 387 388 389 390
  bool return_value = false;
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    if (it.value()->IsSimulate()) continue;
    if (!it.value()->CheckFlag(f)) return false;
    return_value = true;
  }
  return return_value;
}


391 392 393 394 395 396 397 398 399 400 401
HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
  Advance();
}


void HUseIterator::Advance() {
  current_ = next_;
  if (current_ != NULL) {
    next_ = current_->tail();
    value_ = current_->value();
    index_ = current_->index();
402 403 404 405
  }
}


406 407 408 409
int HValue::UseCount() const {
  int count = 0;
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
  return count;
410 411 412
}


413 414 415 416 417 418 419 420 421 422 423
HUseListNode* HValue::RemoveUse(HValue* value, int index) {
  HUseListNode* previous = NULL;
  HUseListNode* current = use_list_;
  while (current != NULL) {
    if (current->value() == value && current->index() == index) {
      if (previous == NULL) {
        use_list_ = current->tail();
      } else {
        previous->set_tail(current->tail());
      }
      break;
424
    }
425 426 427

    previous = current;
    current = current->tail();
428
  }
429 430 431 432 433

#ifdef DEBUG
  // Do not reuse use list nodes in debug mode, zap them.
  if (current != NULL) {
    HUseListNode* temp =
434 435
        new(block()->zone())
        HUseListNode(current->value(), current->index(), NULL);
436 437 438 439 440
    current->Zap();
    current = temp;
  }
#endif
  return current;
441 442 443
}


444
bool HValue::Equals(HValue* other) {
445 446 447
  if (other->opcode() != opcode()) return false;
  if (!other->representation().Equals(representation())) return false;
  if (!other->type_.Equals(type_)) return false;
448
  if (other->flags() != flags()) return false;
449 450 451 452 453
  if (OperandCount() != other->OperandCount()) return false;
  for (int i = 0; i < OperandCount(); ++i) {
    if (OperandAt(i)->id() != other->OperandAt(i)->id()) return false;
  }
  bool result = DataEquals(other);
454
  DCHECK(!result || Hashcode() == other->Hashcode());
455 456 457 458
  return result;
}


459
intptr_t HValue::Hashcode() {
460 461 462 463 464 465 466 467 468
  intptr_t result = opcode();
  int count = OperandCount();
  for (int i = 0; i < count; ++i) {
    result = result * 19 + OperandAt(i)->id() + (result >> 7);
  }
  return result;
}


469 470 471 472 473 474 475 476 477 478 479
const char* HValue::Mnemonic() const {
  switch (opcode()) {
#define MAKE_CASE(type) case k##type: return #type;
    HYDROGEN_CONCRETE_INSTRUCTION_LIST(MAKE_CASE)
#undef MAKE_CASE
    case kPhi: return "Phi";
    default: return "";
  }
}


480 481 482 483 484
bool HValue::CanReplaceWithDummyUses() {
  return FLAG_unreachable_code_elimination &&
      !(block()->IsReachable() ||
        IsBlockEntry() ||
        IsControlInstruction() ||
485
        IsArgumentsObject() ||
486
        IsCapturedObject() ||
487 488 489 490 491 492
        IsSimulate() ||
        IsEnterInlined() ||
        IsLeaveInlined());
}


493
bool HValue::IsInteger32Constant() {
494
  return IsConstant() && HConstant::cast(this)->HasInteger32Value();
495 496 497 498
}


int32_t HValue::GetInteger32Constant() {
499
  return HConstant::cast(this)->Integer32Value();
500 501 502
}


503 504 505 506 507
bool HValue::EqualsInteger32Constant(int32_t value) {
  return IsInteger32Constant() && GetInteger32Constant() == value;
}


508 509 510 511 512 513
void HValue::SetOperandAt(int index, HValue* value) {
  RegisterUse(index, value);
  InternalSetOperandAt(index, value);
}


514 515 516
void HValue::DeleteAndReplaceWith(HValue* other) {
  // We replace all uses first, so Delete can assert that there are none.
  if (other != NULL) ReplaceAllUsesWith(other);
517
  Kill();
518 519 520 521
  DeleteFromGraph();
}


522 523 524 525
void HValue::ReplaceAllUsesWith(HValue* other) {
  while (use_list_ != NULL) {
    HUseListNode* list_node = use_list_;
    HValue* value = list_node->value();
526
    DCHECK(!value->block()->IsStartBlock());
527 528 529 530
    value->InternalSetOperandAt(list_node->index(), other);
    use_list_ = list_node->tail();
    list_node->set_tail(other->use_list_);
    other->use_list_ = list_node;
531 532 533 534
  }
}


535 536 537 538 539
void HValue::Kill() {
  // Instead of going through the entire use list of each operand, we only
  // check the first item in each use list and rely on the tail() method to
  // skip dead items, removing them lazily next time we traverse the list.
  SetFlag(kIsDead);
540
  for (int i = 0; i < OperandCount(); ++i) {
541
    HValue* operand = OperandAt(i);
542
    if (operand == NULL) continue;
543
    HUseListNode* first = operand->use_list_;
544
    if (first != NULL && first->value()->CheckFlag(kIsDead)) {
545 546
      operand->use_list_ = first->tail();
    }
547 548 549 550 551
  }
}


void HValue::SetBlock(HBasicBlock* block) {
552
  DCHECK(block_ == NULL || block == NULL);
553 554 555 556 557 558 559
  block_ = block;
  if (id_ == kNoNumber && block != NULL) {
    id_ = block->graph()->GetNextValueID(this);
  }
}


560 561 562
std::ostream& operator<<(std::ostream& os, const HValue& v) {
  return v.PrintTo(os);
}
563 564


565
std::ostream& operator<<(std::ostream& os, const TypeOf& t) {
566 567 568 569
  if (t.value->representation().IsTagged() &&
      !t.value->type().Equals(HType::Tagged()))
    return os;
  return os << " type:" << t.value->type();
570 571 572
}


573
std::ostream& operator<<(std::ostream& os, const ChangesOf& c) {
574 575 576 577 578
  GVNFlagSet changes_flags = c.value->ChangesFlags();
  if (changes_flags.IsEmpty()) return os;
  os << " changes[";
  if (changes_flags == c.value->AllSideEffectsFlagSet()) {
    os << "*";
579 580
  } else {
    bool add_comma = false;
581 582 583 584 585 586
#define PRINT_DO(Type)                   \
  if (changes_flags.Contains(k##Type)) { \
    if (add_comma) os << ",";            \
    add_comma = true;                    \
    os << #Type;                         \
  }
587 588
    GVN_TRACKED_FLAG_LIST(PRINT_DO);
    GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
589 590
#undef PRINT_DO
  }
591
  return os << "]";
592 593 594
}


595 596 597 598 599
bool HValue::HasMonomorphicJSObjectType() {
  return !GetMonomorphicJSObjectMap().is_null();
}


600 601 602 603 604 605 606 607 608 609 610
bool HValue::UpdateInferredType() {
  HType type = CalculateInferredType();
  bool result = (!type.Equals(type_));
  type_ = type;
  return result;
}


void HValue::RegisterUse(int index, HValue* new_value) {
  HValue* old_value = OperandAt(index);
  if (old_value == new_value) return;
611 612 613 614 615 616

  HUseListNode* removed = NULL;
  if (old_value != NULL) {
    removed = old_value->RemoveUse(this, index);
  }

617
  if (new_value != NULL) {
618
    if (removed == NULL) {
619 620
      new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
          this, index, new_value->use_list_);
621 622 623 624
    } else {
      removed->set_tail(new_value->use_list_);
      new_value->use_list_ = removed;
    }
625 626 627 628
  }
}


629 630 631
void HValue::AddNewRange(Range* r, Zone* zone) {
  if (!HasRange()) ComputeInitialRange(zone);
  if (!HasRange()) range_ = new(zone) Range();
632
  DCHECK(HasRange());
633 634 635 636 637 638
  r->StackUpon(range_);
  range_ = r;
}


void HValue::RemoveLastAddedRange() {
639 640
  DCHECK(HasRange());
  DCHECK(range_->next() != NULL);
641 642 643 644
  range_ = range_->next();
}


645
void HValue::ComputeInitialRange(Zone* zone) {
646
  DCHECK(!HasRange());
647
  range_ = InferRange(zone);
648
  DCHECK(HasRange());
649 650 651
}


652
std::ostream& HInstruction::PrintTo(std::ostream& os) const {  // NOLINT
653 654 655 656 657
  os << Mnemonic() << " ";
  PrintDataTo(os) << ChangesOf(this) << TypeOf(this);
  if (CheckFlag(HValue::kHasNoObservableSideEffects)) os << " [noOSE]";
  if (CheckFlag(HValue::kIsDead)) os << " [dead]";
  return os;
658
}
659 660


661
std::ostream& HInstruction::PrintDataTo(std::ostream& os) const {  // NOLINT
662
  for (int i = 0; i < OperandCount(); ++i) {
663 664
    if (i > 0) os << " ";
    os << NameOf(OperandAt(i));
665
  }
666
  return os;
667 668 669 670
}


void HInstruction::Unlink() {
671 672 673 674
  DCHECK(IsLinked());
  DCHECK(!IsControlInstruction());  // Must never move control instructions.
  DCHECK(!IsBlockEntry());  // Doesn't make sense to delete these.
  DCHECK(previous_ != NULL);
675 676
  previous_->next_ = next_;
  if (next_ == NULL) {
677
    DCHECK(block()->last() == this);
678 679 680 681
    block()->set_last(previous_);
  } else {
    next_->previous_ = previous_;
  }
682 683 684 685 686
  clear_block();
}


void HInstruction::InsertBefore(HInstruction* next) {
687 688 689 690 691
  DCHECK(!IsLinked());
  DCHECK(!next->IsBlockEntry());
  DCHECK(!IsControlInstruction());
  DCHECK(!next->block()->IsStartBlock());
  DCHECK(next->previous_ != NULL);
692 693 694 695 696 697
  HInstruction* prev = next->previous();
  prev->next_ = this;
  next->previous_ = this;
  next_ = next;
  previous_ = prev;
  SetBlock(next->block());
698
  if (!has_position() && next->has_position()) {
699 700
    set_position(next->position());
  }
701 702 703 704
}


void HInstruction::InsertAfter(HInstruction* previous) {
705 706 707
  DCHECK(!IsLinked());
  DCHECK(!previous->IsControlInstruction());
  DCHECK(!IsControlInstruction() || previous->next_ == NULL);
708 709 710 711
  HBasicBlock* block = previous->block();
  // Never insert anything except constants into the start block after finishing
  // it.
  if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
712
    DCHECK(block->end()->SecondSuccessor() == NULL);
713 714 715 716 717 718 719 720
    InsertAfter(block->end()->FirstSuccessor()->first());
    return;
  }

  // If we're inserting after an instruction with side-effects that is
  // followed by a simulate instruction, we need to insert after the
  // simulate instruction instead.
  HInstruction* next = previous->next_;
721
  if (previous->HasObservableSideEffects() && next != NULL) {
722
    DCHECK(next->IsSimulate());
723 724 725 726 727 728 729 730 731
    previous = next;
    next = previous->next_;
  }

  previous_ = previous;
  next_ = next;
  SetBlock(block);
  previous->next_ = this;
  if (next != NULL) next->previous_ = this;
732 733 734
  if (block->last() == previous) {
    block->set_last(this);
  }
735
  if (!has_position() && previous->has_position()) {
736 737
    set_position(previous->position());
  }
738 739 740
}


741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
bool HInstruction::Dominates(HInstruction* other) {
  if (block() != other->block()) {
    return block()->Dominates(other->block());
  }
  // Both instructions are in the same basic block. This instruction
  // should precede the other one in order to dominate it.
  for (HInstruction* instr = next(); instr != NULL; instr = instr->next()) {
    if (instr == other) {
      return true;
    }
  }
  return false;
}


756
#ifdef DEBUG
757
void HInstruction::Verify() {
758 759 760 761
  // Verify that input operands are defined before use.
  HBasicBlock* cur_block = block();
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* other_operand = OperandAt(i);
762
    if (other_operand == NULL) continue;
763 764 765
    HBasicBlock* other_block = other_operand->block();
    if (cur_block == other_block) {
      if (!other_operand->IsPhi()) {
766
        HInstruction* cur = this->previous();
767 768
        while (cur != NULL) {
          if (cur == other_operand) break;
769
          cur = cur->previous();
770 771
        }
        // Must reach other operand in the same block!
772
        DCHECK(cur == other_operand);
773 774
      }
    } else {
775 776
      // If the following assert fires, you may have forgotten an
      // AddInstruction.
777
      DCHECK(other_block->Dominates(cur_block));
778 779 780 781 782
    }
  }

  // Verify that instructions that may have side-effects are followed
  // by a simulate instruction.
783
  if (HasObservableSideEffects() && !IsOsrEntry()) {
784
    DCHECK(next()->IsSimulate());
785
  }
786 787 788 789 790

  // Verify that instructions that can be eliminated by GVN have overridden
  // HValue::DataEquals.  The default implementation is UNREACHABLE.  We
  // don't actually care whether DataEquals returns true or false here.
  if (CheckFlag(kUseGVN)) DataEquals(this);
791 792 793 794

  // Verify that all uses are in the graph.
  for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
    if (use.value()->IsInstruction()) {
795
      DCHECK(HInstruction::cast(use.value())->IsLinked());
796 797
    }
  }
798 799 800 801
}
#endif


802 803
bool HInstruction::CanDeoptimize() {
  switch (opcode()) {
804
    case HValue::kAbnormalExit:
805
    case HValue::kAccessArgumentsAt:
806
    case HValue::kAllocate:
807 808 809
    case HValue::kArgumentsElements:
    case HValue::kArgumentsLength:
    case HValue::kArgumentsObject:
810 811
    case HValue::kBlockEntry:
    case HValue::kCallNewArray:
812
    case HValue::kCapturedObject:
813 814 815 816 817 818
    case HValue::kClassOfTestAndBranch:
    case HValue::kCompareGeneric:
    case HValue::kCompareHoleAndBranch:
    case HValue::kCompareMap:
    case HValue::kCompareNumericAndBranch:
    case HValue::kCompareObjectEqAndBranch:
819 820 821 822 823 824 825
    case HValue::kConstant:
    case HValue::kContext:
    case HValue::kDebugBreak:
    case HValue::kDeclareGlobals:
    case HValue::kDummyUse:
    case HValue::kEnterInlined:
    case HValue::kEnvironmentMarker:
826
    case HValue::kForceRepresentation:
827
    case HValue::kGoto:
828
    case HValue::kHasInstanceTypeAndBranch:
829
    case HValue::kInnerAllocatedObject:
830 831 832
    case HValue::kIsSmiAndBranch:
    case HValue::kIsStringAndBranch:
    case HValue::kIsUndetectableAndBranch:
833 834 835 836 837 838
    case HValue::kLeaveInlined:
    case HValue::kLoadFieldByIndex:
    case HValue::kLoadNamedField:
    case HValue::kLoadRoot:
    case HValue::kMathMinMax:
    case HValue::kParameter:
839
    case HValue::kPhi:
840
    case HValue::kPushArguments:
841
    case HValue::kReturn:
842
    case HValue::kSeqStringGetChar:
843 844
    case HValue::kStoreCodeEntry:
    case HValue::kStoreKeyed:
845
    case HValue::kStoreNamedField:
846 847 848 849 850 851 852 853 854 855 856 857 858 859
    case HValue::kStringCharCodeAt:
    case HValue::kStringCharFromCode:
    case HValue::kThisFunction:
    case HValue::kTypeofIsAndBranch:
    case HValue::kUnknownOSRValue:
    case HValue::kUseConst:
      return false;

    case HValue::kAdd:
    case HValue::kApplyArguments:
    case HValue::kBitwise:
    case HValue::kBoundsCheck:
    case HValue::kBranch:
    case HValue::kCallRuntime:
860
    case HValue::kCallWithDescriptor:
861
    case HValue::kChange:
862
    case HValue::kCheckArrayBufferNotNeutered:
863 864 865 866 867 868 869 870 871 872 873
    case HValue::kCheckHeapObject:
    case HValue::kCheckInstanceType:
    case HValue::kCheckMapValue:
    case HValue::kCheckMaps:
    case HValue::kCheckSmi:
    case HValue::kCheckValue:
    case HValue::kClampToUint8:
    case HValue::kDeoptimize:
    case HValue::kDiv:
    case HValue::kForInCacheArray:
    case HValue::kForInPrepareMap:
874
    case HValue::kHasInPrototypeChainAndBranch:
875 876 877 878 879
    case HValue::kInvokeFunction:
    case HValue::kLoadContextSlot:
    case HValue::kLoadFunctionPrototype:
    case HValue::kLoadKeyed:
    case HValue::kMathFloorOfDiv:
880
    case HValue::kMaybeGrowElements:
881 882 883 884
    case HValue::kMod:
    case HValue::kMul:
    case HValue::kOsrEntry:
    case HValue::kPower:
885
    case HValue::kPrologue:
886 887
    case HValue::kRor:
    case HValue::kSar:
888 889 890 891 892 893 894
    case HValue::kSeqStringSetChar:
    case HValue::kShl:
    case HValue::kShr:
    case HValue::kSimulate:
    case HValue::kStackCheck:
    case HValue::kStoreContextSlot:
    case HValue::kStringAdd:
895
    case HValue::kStringCompareAndBranch:
896 897 898 899 900 901 902 903
    case HValue::kSub:
    case HValue::kTransitionElementsKind:
    case HValue::kTrapAllocationMemento:
    case HValue::kTypeof:
    case HValue::kUnaryMathOperation:
    case HValue::kWrapReceiver:
      return true;
  }
904 905
  UNREACHABLE();
  return true;
906 907 908
}


909
std::ostream& operator<<(std::ostream& os, const NameOf& v) {
910 911 912
  return os << v.value->representation().Mnemonic() << v.value->id();
}

913
std::ostream& HDummyUse::PrintDataTo(std::ostream& os) const {  // NOLINT
914
  return os << NameOf(value());
915 916 917
}


918 919
std::ostream& HEnvironmentMarker::PrintDataTo(
    std::ostream& os) const {  // NOLINT
920 921
  return os << (kind() == BIND ? "bind" : "lookup") << " var[" << index()
            << "]";
922 923 924
}


925
std::ostream& HUnaryCall::PrintDataTo(std::ostream& os) const {  // NOLINT
926
  return os << NameOf(value()) << " #" << argument_count();
927 928 929
}


930
std::ostream& HBinaryCall::PrintDataTo(std::ostream& os) const {  // NOLINT
931 932
  return os << NameOf(first()) << " " << NameOf(second()) << " #"
            << argument_count();
933 934
}

935 936 937 938 939 940 941 942 943 944 945 946
std::ostream& HInvokeFunction::PrintTo(std::ostream& os) const {  // NOLINT
  if (tail_call_mode() == TailCallMode::kAllow) os << "Tail";
  return HBinaryCall::PrintTo(os);
}

std::ostream& HInvokeFunction::PrintDataTo(std::ostream& os) const {  // NOLINT
  HBinaryCall::PrintDataTo(os);
  if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
    os << ", JSTailCall";
  }
  return os;
}
947

948
std::ostream& HBoundsCheck::PrintDataTo(std::ostream& os) const {  // NOLINT
949
  os << NameOf(index()) << " " << NameOf(length());
950
  if (base() != NULL && (offset() != 0 || scale() != 0)) {
951
    os << " base: ((";
952
    if (base() != index()) {
953
      os << NameOf(index());
954
    } else {
955
      os << "index";
956
    }
957
    os << " + " << offset() << ") >> " << scale() << ")";
958
  }
959 960
  if (skip_check()) os << " [DISABLED]";
  return os;
961 962
}

963

964
void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
965
  DCHECK(CheckFlag(kFlexibleRepresentation));
966
  HValue* actual_index = index()->ActualValue();
967 968
  HValue* actual_length = length()->ActualValue();
  Representation index_rep = actual_index->representation();
969
  Representation length_rep = actual_length->representation();
970 971 972 973 974 975
  if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
    index_rep = Representation::Smi();
  }
  if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
    length_rep = Representation::Smi();
  }
976 977
  Representation r = index_rep.generalize(length_rep);
  if (r.is_more_general_than(Representation::Integer32())) {
978 979 980 981 982 983
    r = Representation::Integer32();
  }
  UpdateRepresentation(r, h_infer, "boundscheck");
}


984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
Range* HBoundsCheck::InferRange(Zone* zone) {
  Representation r = representation();
  if (r.IsSmiOrInteger32() && length()->HasRange()) {
    int upper = length()->range()->upper() - (allow_equality() ? 0 : 1);
    int lower = 0;

    Range* result = new(zone) Range(lower, upper);
    if (index()->HasRange()) {
      result->Intersect(index()->range());
    }

    // In case of Smi representation, clamp result to Smi::kMaxValue.
    if (r.IsSmi()) result->ClampToSmi();
    return result;
  }
  return HValue::InferRange(zone);
}


1003 1004
std::ostream& HCallWithDescriptor::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1005
  for (int i = 0; i < OperandCount(); i++) {
1006
    os << NameOf(OperandAt(i)) << " ";
1007
  }
1008 1009 1010 1011 1012
  os << "#" << argument_count();
  if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
    os << ", JSTailCall";
  }
  return os;
1013 1014 1015
}


1016
std::ostream& HCallNewArray::PrintDataTo(std::ostream& os) const {  // NOLINT
1017 1018
  os << ElementsKindToString(elements_kind()) << " ";
  return HBinaryCall::PrintDataTo(os);
1019 1020 1021
}


1022
std::ostream& HCallRuntime::PrintDataTo(std::ostream& os) const {  // NOLINT
1023
  os << function()->name << " ";
1024 1025
  if (save_doubles() == kSaveFPRegs) os << "[save doubles] ";
  return os << "#" << argument_count();
1026 1027 1028
}


1029 1030
std::ostream& HClassOfTestAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1031 1032
  return os << "class_of_test(" << NameOf(value()) << ", \""
            << class_name()->ToCString().get() << "\")";
1033 1034 1035
}


1036
std::ostream& HWrapReceiver::PrintDataTo(std::ostream& os) const {  // NOLINT
1037
  return os << NameOf(receiver()) << " " << NameOf(function());
1038 1039 1040
}


1041 1042
std::ostream& HAccessArgumentsAt::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1043 1044
  return os << NameOf(arguments()) << "[" << NameOf(index()) << "], length "
            << NameOf(length());
1045 1046 1047
}


1048 1049
std::ostream& HControlInstruction::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1050
  os << " goto (";
1051 1052
  bool first_block = true;
  for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
1053 1054
    if (!first_block) os << ", ";
    os << *it.Current();
1055
    first_block = false;
1056
  }
1057
  return os << ")";
1058 1059 1060
}


1061 1062
std::ostream& HUnaryControlInstruction::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1063 1064
  os << NameOf(value());
  return HControlInstruction::PrintDataTo(os);
1065 1066 1067
}


1068
std::ostream& HReturn::PrintDataTo(std::ostream& os) const {  // NOLINT
1069 1070
  return os << NameOf(value()) << " (pop " << NameOf(parameter_count())
            << " values)";
1071 1072 1073
}


1074
Representation HBranch::observed_input_representation(int index) {
1075 1076 1077
  if (expected_input_types_ & (ToBooleanHint::kNull | ToBooleanHint::kReceiver |
                               ToBooleanHint::kString | ToBooleanHint::kSymbol |
                               ToBooleanHint::kSimdValue)) {
1078
    return Representation::Tagged();
1079
  }
1080 1081
  if (expected_input_types_ & ToBooleanHint::kUndefined) {
    if (expected_input_types_ & ToBooleanHint::kHeapNumber) {
1082 1083 1084 1085
      return Representation::Double();
    }
    return Representation::Tagged();
  }
1086
  if (expected_input_types_ & ToBooleanHint::kHeapNumber) {
1087
    return Representation::Double();
1088
  }
1089
  if (expected_input_types_ & ToBooleanHint::kSmallInteger) {
1090
    return Representation::Smi();
1091
  }
1092
  return Representation::None();
1093 1094 1095
}


1096 1097 1098
bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
  HValue* value = this->value();
  if (value->EmitAtUses()) {
1099 1100
    DCHECK(value->IsConstant());
    DCHECK(!value->representation().IsDouble());
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    *block = HConstant::cast(value)->BooleanValue()
        ? FirstSuccessor()
        : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


1111
std::ostream& HBranch::PrintDataTo(std::ostream& os) const {  // NOLINT
1112 1113
  return HUnaryControlInstruction::PrintDataTo(os) << " "
                                                   << expected_input_types();
1114 1115 1116
}


1117
std::ostream& HCompareMap::PrintDataTo(std::ostream& os) const {  // NOLINT
1118 1119
  os << NameOf(value()) << " (" << *map().handle() << ")";
  HControlInstruction::PrintDataTo(os);
1120
  if (known_successor_index() == 0) {
1121
    os << " [true]";
1122
  } else if (known_successor_index() == 1) {
1123
    os << " [false]";
1124
  }
1125
  return os;
1126 1127 1128 1129 1130
}


const char* HUnaryMathOperation::OpName() const {
  switch (op()) {
1131 1132 1133 1134 1135 1136 1137 1138
    case kMathFloor:
      return "floor";
    case kMathFround:
      return "fround";
    case kMathRound:
      return "round";
    case kMathAbs:
      return "abs";
1139 1140
    case kMathCos:
      return "cos";
1141 1142 1143 1144
    case kMathLog:
      return "log";
    case kMathExp:
      return "exp";
1145 1146
    case kMathSin:
      return "sin";
1147 1148 1149 1150 1151 1152
    case kMathSqrt:
      return "sqrt";
    case kMathPowHalf:
      return "pow-half";
    case kMathClz32:
      return "clz32";
1153 1154 1155
    default:
      UNREACHABLE();
      return NULL;
1156 1157 1158 1159
  }
}


1160 1161
Range* HUnaryMathOperation::InferRange(Zone* zone) {
  Representation r = representation();
1162
  if (op() == kMathClz32) return new(zone) Range(0, 32);
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  if (r.IsSmiOrInteger32() && value()->HasRange()) {
    if (op() == kMathAbs) {
      int upper = value()->range()->upper();
      int lower = value()->range()->lower();
      bool spans_zero = value()->range()->CanBeZero();
      // Math.abs(kMinInt) overflows its representation, on which the
      // instruction deopts. Hence clamp it to kMaxInt.
      int abs_upper = upper == kMinInt ? kMaxInt : abs(upper);
      int abs_lower = lower == kMinInt ? kMaxInt : abs(lower);
      Range* result =
          new(zone) Range(spans_zero ? 0 : Min(abs_lower, abs_upper),
                          Max(abs_lower, abs_upper));
      // In case of Smi representation, clamp Math.abs(Smi::kMinValue) to
      // Smi::kMaxValue.
      if (r.IsSmi()) result->ClampToSmi();
      return result;
    }
  }
  return HValue::InferRange(zone);
}


1185 1186
std::ostream& HUnaryMathOperation::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1187
  return os << OpName() << " " << NameOf(value());
1188 1189 1190
}


1191
std::ostream& HUnaryOperation::PrintDataTo(std::ostream& os) const {  // NOLINT
1192
  return os << NameOf(value());
1193 1194 1195
}


1196 1197
std::ostream& HHasInstanceTypeAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1198
  os << NameOf(value());
1199
  switch (from_) {
1200
    case FIRST_JS_RECEIVER_TYPE:
1201
      if (to_ == LAST_TYPE) os << " spec_object";
1202 1203
      break;
    case JS_REGEXP_TYPE:
1204
      if (to_ == JS_REGEXP_TYPE) os << " reg_exp";
1205 1206
      break;
    case JS_ARRAY_TYPE:
1207
      if (to_ == JS_ARRAY_TYPE) os << " array";
1208 1209
      break;
    case JS_FUNCTION_TYPE:
1210
      if (to_ == JS_FUNCTION_TYPE) os << " function";
1211 1212 1213 1214
      break;
    default:
      break;
  }
1215
  return os;
1216 1217 1218
}


1219 1220
std::ostream& HTypeofIsAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1221 1222
  os << NameOf(value()) << " == " << type_literal()->ToCString().get();
  return HControlInstruction::PrintDataTo(os);
1223 1224 1225
}


1226 1227 1228
namespace {

String* TypeOfString(HConstant* constant, Isolate* isolate) {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
  Heap* heap = isolate->heap();
  if (constant->HasNumberValue()) return heap->number_string();
  if (constant->HasStringValue()) return heap->string_string();
  switch (constant->GetInstanceType()) {
    case ODDBALL_TYPE: {
      Unique<Object> unique = constant->GetUnique();
      if (unique.IsKnownGlobal(heap->true_value()) ||
          unique.IsKnownGlobal(heap->false_value())) {
        return heap->boolean_string();
      }
      if (unique.IsKnownGlobal(heap->null_value())) {
1240
        return heap->object_string();
1241
      }
1242
      DCHECK(unique.IsKnownGlobal(heap->undefined_value()));
1243
      return heap->undefined_string();
1244
    }
1245 1246
    case SYMBOL_TYPE:
      return heap->symbol_string();
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    case SIMD128_VALUE_TYPE: {
      Unique<Map> map = constant->ObjectMap();
#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
  if (map.IsKnownGlobal(heap->type##_map())) {                \
    return heap->type##_string();                             \
  }
      SIMD128_TYPES(SIMD128_TYPE)
#undef SIMD128_TYPE
      UNREACHABLE();
      return nullptr;
    }
1258
    default:
1259
      if (constant->IsUndetectable()) return heap->undefined_string();
1260
      if (constant->IsCallable()) return heap->function_string();
1261 1262 1263 1264
      return heap->object_string();
  }
}

1265 1266
}  // namespace

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

bool HTypeofIsAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (FLAG_fold_constants && value()->IsConstant()) {
    HConstant* constant = HConstant::cast(value());
    String* type_string = TypeOfString(constant, isolate());
    bool same_type = type_literal_.IsKnownGlobal(type_string);
    *block = same_type ? FirstSuccessor() : SecondSuccessor();
    return true;
  } else if (value()->representation().IsSpecialization()) {
    bool number_type =
        type_literal_.IsKnownGlobal(isolate()->heap()->number_string());
    *block = number_type ? FirstSuccessor() : SecondSuccessor();
1279 1280 1281 1282 1283 1284 1285
    return true;
  }
  *block = NULL;
  return false;
}


1286
std::ostream& HCheckMapValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1287
  return os << NameOf(value()) << " " << NameOf(map());
1288 1289 1290
}


1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
HValue* HCheckMapValue::Canonicalize() {
  if (map()->IsConstant()) {
    HConstant* c_map = HConstant::cast(map());
    return HCheckMaps::CreateAndInsertAfter(
        block()->graph()->zone(), value(), c_map->MapValue(),
        c_map->HasStableMapValue(), this);
  }
  return this;
}


1302
std::ostream& HForInPrepareMap::PrintDataTo(std::ostream& os) const {  // NOLINT
1303
  return os << NameOf(enumerable());
1304 1305 1306
}


1307
std::ostream& HForInCacheArray::PrintDataTo(std::ostream& os) const {  // NOLINT
1308 1309
  return os << NameOf(enumerable()) << " " << NameOf(map()) << "[" << idx_
            << "]";
1310 1311 1312
}


1313 1314
std::ostream& HLoadFieldByIndex::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1315
  return os << NameOf(object()) << " " << NameOf(index());
1316 1317 1318
}


1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
static bool MatchLeftIsOnes(HValue* l, HValue* r, HValue** negated) {
  if (!l->EqualsInteger32Constant(~0)) return false;
  *negated = r;
  return true;
}


static bool MatchNegationViaXor(HValue* instr, HValue** negated) {
  if (!instr->IsBitwise()) return false;
  HBitwise* b = HBitwise::cast(instr);
  return (b->op() == Token::BIT_XOR) &&
      (MatchLeftIsOnes(b->left(), b->right(), negated) ||
       MatchLeftIsOnes(b->right(), b->left(), negated));
}


static bool MatchDoubleNegation(HValue* instr, HValue** arg) {
  HValue* negated;
  return MatchNegationViaXor(instr, &negated) &&
      MatchNegationViaXor(negated, arg);
}


1342
HValue* HBitwise::Canonicalize() {
1343
  if (!representation().IsSmiOrInteger32()) return this;
1344 1345
  // If x is an int32, then x & -1 == x, x | 0 == x and x ^ 0 == x.
  int32_t nop_constant = (op() == Token::BIT_AND) ? -1 : 0;
1346
  if (left()->EqualsInteger32Constant(nop_constant) &&
1347
      !right()->CheckFlag(kUint32)) {
1348 1349
    return right();
  }
1350
  if (right()->EqualsInteger32Constant(nop_constant) &&
1351
      !left()->CheckFlag(kUint32)) {
1352 1353
    return left();
  }
1354 1355 1356 1357
  // Optimize double negation, a common pattern used for ToInt32(x).
  HValue* arg;
  if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
    return arg;
1358 1359 1360 1361 1362
  }
  return this;
}


1363 1364
// static
HInstruction* HAdd::New(Isolate* isolate, Zone* zone, HValue* context,
1365
                        HValue* left, HValue* right,
1366 1367 1368 1369
                        ExternalAddType external_add_type) {
  // For everything else, you should use the other factory method without
  // ExternalAddType.
  DCHECK_EQ(external_add_type, AddOfExternalAndTagged);
1370
  return new (zone) HAdd(context, left, right, external_add_type);
1371 1372 1373
}


1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
Representation HAdd::RepresentationFromInputs() {
  Representation left_rep = left()->representation();
  if (left_rep.IsExternal()) {
    return Representation::External();
  }
  return HArithmeticBinaryOperation::RepresentationFromInputs();
}


Representation HAdd::RequiredInputRepresentation(int index) {
  if (index == 2) {
    Representation left_rep = left()->representation();
    if (left_rep.IsExternal()) {
1387 1388 1389 1390 1391
      if (external_add_type_ == AddOfExternalAndTagged) {
        return Representation::Tagged();
      } else {
        return Representation::Integer32();
      }
1392 1393 1394 1395 1396 1397
    }
  }
  return HArithmeticBinaryOperation::RequiredInputRepresentation(index);
}


1398 1399
static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
  return arg1->representation().IsSpecialization() &&
1400
    arg2->EqualsInteger32Constant(identity);
1401 1402 1403
}


1404
HValue* HAdd::Canonicalize() {
1405 1406 1407 1408 1409 1410 1411 1412 1413
  // Adding 0 is an identity operation except in case of -0: -0 + 0 = +0
  if (IsIdentityOperation(left(), right(), 0) &&
      !left()->representation().IsDouble()) {  // Left could be -0.
    return left();
  }
  if (IsIdentityOperation(right(), left(), 0) &&
      !left()->representation().IsDouble()) {  // Right could be -0.
    return right();
  }
1414
  return this;
1415 1416 1417 1418 1419
}


HValue* HSub::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 0)) return left();
1420
  return this;
1421 1422 1423
}


1424 1425 1426
HValue* HMul::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 1)) return left();
  if (IsIdentityOperation(right(), left(), 1)) return right();
1427
  return this;
1428 1429 1430
}


1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
bool HMul::MulMinusOne() {
  if (left()->EqualsInteger32Constant(-1) ||
      right()->EqualsInteger32Constant(-1)) {
    return true;
  }

  return false;
}


1441 1442 1443 1444 1445 1446
HValue* HMod::Canonicalize() {
  return this;
}


HValue* HDiv::Canonicalize() {
1447
  if (IsIdentityOperation(left(), right(), 1)) return left();
1448 1449 1450 1451
  return this;
}


1452 1453 1454 1455 1456
HValue* HChange::Canonicalize() {
  return (from().Equals(to())) ? value() : this;
}


1457 1458
HValue* HWrapReceiver::Canonicalize() {
  if (HasNoUses()) return NULL;
1459
  if (receiver()->type().IsJSReceiver()) {
1460 1461 1462 1463 1464 1465
    return receiver();
  }
  return this;
}


1466
std::ostream& HTypeof::PrintDataTo(std::ostream& os) const {  // NOLINT
1467
  return os << NameOf(value());
1468 1469 1470
}


1471 1472 1473
HInstruction* HForceRepresentation::New(Isolate* isolate, Zone* zone,
                                        HValue* context, HValue* value,
                                        Representation representation) {
1474 1475
  if (FLAG_fold_constants && value->IsConstant()) {
    HConstant* c = HConstant::cast(value);
1476 1477
    c = c->CopyToRepresentation(representation, zone);
    if (c != NULL) return c;
1478
  }
1479
  return new(zone) HForceRepresentation(value, representation);
1480 1481 1482
}


1483 1484
std::ostream& HForceRepresentation::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1485
  return os << representation().Mnemonic() << " " << NameOf(value());
1486 1487 1488
}


1489
std::ostream& HChange::PrintDataTo(std::ostream& os) const {  // NOLINT
1490 1491
  HUnaryOperation::PrintDataTo(os);
  os << " " << from().Mnemonic() << " to " << to().Mnemonic();
1492

1493 1494
  if (CanTruncateToSmi()) os << " truncating-smi";
  if (CanTruncateToInt32()) os << " truncating-int32";
1495
  if (CanTruncateToNumber()) os << " truncating-number";
1496 1497
  if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
  return os;
1498 1499 1500
}


1501
HValue* HUnaryMathOperation::Canonicalize() {
1502
  if (op() == kMathRound || op() == kMathFloor) {
1503 1504
    HValue* val = value();
    if (val->IsChange()) val = HChange::cast(val)->value();
1505
    if (val->representation().IsSmiOrInteger32()) {
1506
      if (val->representation().Equals(representation())) return val;
1507 1508
      return Prepend(new (block()->zone())
                         HChange(val, representation(), false, false, true));
1509
    }
1510
  }
1511 1512
  if (op() == kMathFloor && representation().IsSmiOrInteger32() &&
      value()->IsDiv() && value()->HasOneUse()) {
1513 1514 1515
    HDiv* hdiv = HDiv::cast(value());

    HValue* left = hdiv->left();
1516
    if (left->representation().IsInteger32() && !left->CheckFlag(kUint32)) {
1517
      // A value with an integer representation does not need to be transformed.
1518 1519
    } else if (left->IsChange() && HChange::cast(left)->from().IsInteger32() &&
               !HChange::cast(left)->value()->CheckFlag(kUint32)) {
1520 1521 1522
      // A change from an integer32 can be replaced by the integer32 value.
      left = HChange::cast(left)->value();
    } else if (hdiv->observed_input_representation(1).IsSmiOrInteger32()) {
1523 1524
      left = Prepend(new (block()->zone()) HChange(
          left, Representation::Integer32(), false, false, true));
1525 1526 1527
    } else {
      return this;
    }
1528

1529 1530 1531 1532
    HValue* right = hdiv->right();
    if (right->IsInteger32Constant()) {
      right = Prepend(HConstant::cast(right)->CopyToRepresentation(
          Representation::Integer32(), right->block()->zone()));
1533 1534
    } else if (right->representation().IsInteger32() &&
               !right->CheckFlag(kUint32)) {
1535 1536
      // A value with an integer representation does not need to be transformed.
    } else if (right->IsChange() &&
1537 1538
               HChange::cast(right)->from().IsInteger32() &&
               !HChange::cast(right)->value()->CheckFlag(kUint32)) {
1539 1540 1541
      // A change from an integer32 can be replaced by the integer32 value.
      right = HChange::cast(right)->value();
    } else if (hdiv->observed_input_representation(2).IsSmiOrInteger32()) {
1542 1543
      right = Prepend(new (block()->zone()) HChange(
          right, Representation::Integer32(), false, false, true));
1544 1545
    } else {
      return this;
1546
    }
1547 1548

    return Prepend(HMathFloorOfDiv::New(
1549
        block()->graph()->isolate(), block()->zone(), context(), left, right));
1550 1551 1552 1553 1554
  }
  return this;
}


1555
HValue* HCheckInstanceType::Canonicalize() {
1556
  if ((check_ == IS_JS_RECEIVER && value()->type().IsJSReceiver()) ||
1557 1558
      (check_ == IS_JS_ARRAY && value()->type().IsJSArray()) ||
      (check_ == IS_STRING && value()->type().IsString())) {
1559
    return value();
1560
  }
1561

1562
  if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1563 1564 1565
    if (HConstant::cast(value())->HasInternalizedStringValue()) {
      return value();
    }
1566 1567 1568 1569 1570
  }
  return this;
}


1571 1572
void HCheckInstanceType::GetCheckInterval(InstanceType* first,
                                          InstanceType* last) {
1573
  DCHECK(is_interval_check());
1574
  switch (check_) {
1575
    case IS_JS_RECEIVER:
1576 1577
      *first = FIRST_JS_RECEIVER_TYPE;
      *last = LAST_JS_RECEIVER_TYPE;
1578 1579 1580 1581
      return;
    case IS_JS_ARRAY:
      *first = *last = JS_ARRAY_TYPE;
      return;
1582 1583 1584
    case IS_JS_FUNCTION:
      *first = *last = JS_FUNCTION_TYPE;
      return;
1585 1586 1587
    case IS_JS_DATE:
      *first = *last = JS_DATE_TYPE;
      return;
1588 1589 1590 1591 1592 1593 1594
    default:
      UNREACHABLE();
  }
}


void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
1595
  DCHECK(!is_interval_check());
1596 1597 1598 1599 1600
  switch (check_) {
    case IS_STRING:
      *mask = kIsNotStringMask;
      *tag = kStringTag;
      return;
1601
    case IS_INTERNALIZED_STRING:
1602
      *mask = kIsNotStringMask | kIsNotInternalizedMask;
1603
      *tag = kInternalizedTag;
1604 1605 1606 1607
      return;
    default:
      UNREACHABLE();
  }
1608 1609 1610
}


1611
std::ostream& HCheckMaps::PrintDataTo(std::ostream& os) const {  // NOLINT
1612
  os << NameOf(value()) << " [" << *maps()->at(0).handle();
1613
  for (int i = 1; i < maps()->size(); ++i) {
1614
    os << "," << *maps()->at(i).handle();
1615
  }
1616 1617 1618
  os << "]";
  if (IsStabilityCheck()) os << "(stability-check)";
  return os;
1619 1620 1621 1622 1623 1624
}


HValue* HCheckMaps::Canonicalize() {
  if (!IsStabilityCheck() && maps_are_stable() && value()->IsConstant()) {
    HConstant* c_value = HConstant::cast(value());
1625
    if (c_value->HasObjectMap()) {
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
      for (int i = 0; i < maps()->size(); ++i) {
        if (c_value->ObjectMap() == maps()->at(i)) {
          if (maps()->size() > 1) {
            set_maps(new(block()->graph()->zone()) UniqueSet<Map>(
                    maps()->at(i), block()->graph()->zone()));
          }
          MarkAsStabilityCheck();
          break;
        }
      }
    }
  }
  return this;
1639 1640 1641
}


1642
std::ostream& HCheckValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1643
  return os << NameOf(value()) << " " << Brief(*object().handle());
1644 1645 1646
}


1647
HValue* HCheckValue::Canonicalize() {
1648
  return (value()->IsConstant() &&
1649
          HConstant::cast(value())->EqualsUnique(object_)) ? NULL : this;
1650 1651 1652
}


1653
const char* HCheckInstanceType::GetCheckName() const {
1654
  switch (check_) {
1655
    case IS_JS_RECEIVER: return "object";
1656
    case IS_JS_ARRAY: return "array";
1657 1658
    case IS_JS_FUNCTION:
      return "function";
1659 1660
    case IS_JS_DATE:
      return "date";
1661
    case IS_STRING: return "string";
1662
    case IS_INTERNALIZED_STRING: return "internalized_string";
1663 1664 1665 1666 1667
  }
  UNREACHABLE();
  return "";
}

1668

1669 1670
std::ostream& HCheckInstanceType::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1671 1672
  os << GetCheckName() << " ";
  return HUnaryOperation::PrintDataTo(os);
1673 1674 1675
}


1676
std::ostream& HUnknownOSRValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1677 1678 1679 1680
  const char* type = "expression";
  if (environment_->is_local_index(index_)) type = "local";
  if (environment_->is_special_index(index_)) type = "special";
  if (environment_->is_parameter_index(index_)) type = "parameter";
1681
  return os << type << " @ " << index_;
1682 1683 1684
}


1685
Range* HValue::InferRange(Zone* zone) {
1686
  Range* result;
1687
  if (representation().IsSmi() || type().IsSmi()) {
1688 1689 1690 1691
    result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
    result->set_can_be_minus_zero(false);
  } else {
    result = new(zone) Range();
1692 1693 1694
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
    // TODO(jkummerow): The range cannot be minus zero when the upper type
    // bound is Integer32.
1695
  }
1696
  return result;
1697 1698 1699
}


1700
Range* HChange::InferRange(Zone* zone) {
1701
  Range* input_range = value()->range();
1702 1703 1704 1705 1706
  if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
      (to().IsSmi() ||
       (to().IsTagged() &&
        input_range != NULL &&
        input_range->IsInSmiRange()))) {
1707
    set_type(HType::Smi());
1708
    ClearChangesFlag(kNewSpacePromotion);
1709
  }
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
  if (to().IsSmiOrTagged() &&
      input_range != NULL &&
      input_range->IsInSmiRange() &&
      (!SmiValuesAre32Bits() ||
       !value()->CheckFlag(HValue::kUint32) ||
       input_range->upper() != kMaxInt)) {
    // The Range class can't express upper bounds in the (kMaxInt, kMaxUint32]
    // interval, so we treat kMaxInt as a sentinel for this entire interval.
    ClearFlag(kCanOverflow);
  }
1720
  Range* result = (input_range != NULL)
1721 1722
      ? input_range->Copy(zone)
      : HValue::InferRange(zone);
1723
  result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1724 1725 1726
                                !(CheckFlag(kAllUsesTruncatingToInt32) ||
                                  CheckFlag(kAllUsesTruncatingToSmi)));
  if (to().IsSmi()) result->ClampToSmi();
1727 1728 1729 1730
  return result;
}


1731
Range* HConstant::InferRange(Zone* zone) {
1732
  if (HasInteger32Value()) {
1733
    Range* result = new(zone) Range(int32_value_, int32_value_);
fschneider@chromium.org's avatar
fschneider@chromium.org committed
1734 1735
    result->set_can_be_minus_zero(false);
    return result;
1736
  }
1737
  return HValue::InferRange(zone);
1738 1739 1740
}


1741
SourcePosition HPhi::position() const { return block()->first()->position(); }
1742 1743


1744
Range* HPhi::InferRange(Zone* zone) {
1745 1746
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1747
    if (block()->IsLoopHeader()) {
1748 1749 1750
      Range* range = r.IsSmi()
          ? new(zone) Range(Smi::kMinValue, Smi::kMaxValue)
          : new(zone) Range(kMinInt, kMaxInt);
fschneider@chromium.org's avatar
fschneider@chromium.org committed
1751
      return range;
1752
    } else {
1753
      Range* range = OperandAt(0)->range()->Copy(zone);
1754 1755 1756 1757 1758 1759
      for (int i = 1; i < OperandCount(); ++i) {
        range->Union(OperandAt(i)->range());
      }
      return range;
    }
  } else {
1760
    return HValue::InferRange(zone);
1761 1762 1763 1764
  }
}


1765
Range* HAdd::InferRange(Zone* zone) {
1766 1767
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1768 1769
    Range* a = left()->range();
    Range* b = right()->range();
1770
    Range* res = a->Copy(zone);
1771 1772 1773
    if (!res->AddAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1774 1775
      ClearFlag(kCanOverflow);
    }
1776 1777
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1778
                               a->CanBeMinusZero() && b->CanBeMinusZero());
1779 1780
    return res;
  } else {
1781
    return HValue::InferRange(zone);
1782 1783 1784 1785
  }
}


1786
Range* HSub::InferRange(Zone* zone) {
1787 1788
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1789 1790
    Range* a = left()->range();
    Range* b = right()->range();
1791
    Range* res = a->Copy(zone);
1792 1793 1794
    if (!res->SubAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1795 1796
      ClearFlag(kCanOverflow);
    }
1797 1798
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1799
                               a->CanBeMinusZero() && b->CanBeZero());
1800 1801
    return res;
  } else {
1802
    return HValue::InferRange(zone);
1803 1804 1805 1806
  }
}


1807
Range* HMul::InferRange(Zone* zone) {
1808 1809
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1810 1811
    Range* a = left()->range();
    Range* b = right()->range();
1812
    Range* res = a->Copy(zone);
1813 1814 1815 1816 1817 1818 1819
    if (!res->MulAndCheckOverflow(r, b) ||
        (((r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
         (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) &&
         MulMinusOne())) {
      // Truncated int multiplication is too precise and therefore not the
      // same as converting to Double and back.
      // Handle truncated integer multiplication by -1 special.
1820 1821
      ClearFlag(kCanOverflow);
    }
1822 1823
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1824 1825
                               ((a->CanBeZero() && b->CanBeNegative()) ||
                                (a->CanBeNegative() && b->CanBeZero())));
1826 1827
    return res;
  } else {
1828
    return HValue::InferRange(zone);
1829 1830 1831 1832
  }
}


1833
Range* HDiv::InferRange(Zone* zone) {
1834
  if (representation().IsInteger32()) {
1835 1836
    Range* a = left()->range();
    Range* b = right()->range();
1837
    Range* result = new(zone) Range();
1838 1839 1840
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  (a->CanBeMinusZero() ||
                                   (a->CanBeZero() && b->CanBeNegative())));
1841
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1842
      ClearFlag(kCanOverflow);
1843 1844
    }

1845
    if (!b->CanBeZero()) {
1846
      ClearFlag(kCanBeDivByZero);
1847 1848 1849
    }
    return result;
  } else {
1850
    return HValue::InferRange(zone);
1851 1852 1853 1854
  }
}


1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
Range* HMathFloorOfDiv::InferRange(Zone* zone) {
  if (representation().IsInteger32()) {
    Range* a = left()->range();
    Range* b = right()->range();
    Range* result = new(zone) Range();
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  (a->CanBeMinusZero() ||
                                   (a->CanBeZero() && b->CanBeNegative())));
    if (!a->Includes(kMinInt)) {
      ClearFlag(kLeftCanBeMinInt);
    }
1866

1867 1868 1869 1870 1871 1872 1873 1874
    if (!a->CanBeNegative()) {
      ClearFlag(HValue::kLeftCanBeNegative);
    }

    if (!a->CanBePositive()) {
      ClearFlag(HValue::kLeftCanBePositive);
    }

1875 1876 1877
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
      ClearFlag(kCanOverflow);
    }
1878

1879 1880 1881 1882 1883 1884 1885
    if (!b->CanBeZero()) {
      ClearFlag(kCanBeDivByZero);
    }
    return result;
  } else {
    return HValue::InferRange(zone);
  }
1886 1887 1888
}


1889 1890 1891 1892 1893
// Returns the absolute value of its argument minus one, avoiding undefined
// behavior at kMinInt.
static int32_t AbsMinus1(int32_t a) { return a < 0 ? -(a + 1) : (a - 1); }


1894
Range* HMod::InferRange(Zone* zone) {
1895 1896
  if (representation().IsInteger32()) {
    Range* a = left()->range();
1897
    Range* b = right()->range();
1898

1899 1900
    // The magnitude of the modulus is bounded by the right operand.
    int32_t positive_bound = Max(AbsMinus1(b->lower()), AbsMinus1(b->upper()));
1901 1902 1903 1904 1905 1906

    // The result of the modulo operation has the sign of its left operand.
    bool left_can_be_negative = a->CanBeMinusZero() || a->CanBeNegative();
    Range* result = new(zone) Range(left_can_be_negative ? -positive_bound : 0,
                                    a->CanBePositive() ? positive_bound : 0);

1907 1908
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  left_can_be_negative);
1909

1910 1911 1912 1913
    if (!a->CanBeNegative()) {
      ClearFlag(HValue::kLeftCanBeNegative);
    }

1914 1915
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
      ClearFlag(HValue::kCanOverflow);
1916 1917
    }

1918
    if (!b->CanBeZero()) {
1919 1920 1921 1922
      ClearFlag(HValue::kCanBeDivByZero);
    }
    return result;
  } else {
1923
    return HValue::InferRange(zone);
1924 1925 1926 1927
  }
}


1928
Range* HMathMinMax::InferRange(Zone* zone) {
1929
  if (representation().IsSmiOrInteger32()) {
1930 1931 1932 1933 1934 1935
    Range* a = left()->range();
    Range* b = right()->range();
    Range* res = a->Copy(zone);
    if (operation_ == kMathMax) {
      res->CombinedMax(b);
    } else {
1936
      DCHECK(operation_ == kMathMin);
1937 1938 1939 1940 1941 1942 1943 1944 1945
      res->CombinedMin(b);
    }
    return res;
  } else {
    return HValue::InferRange(zone);
  }
}


1946 1947 1948 1949 1950 1951
void HPushArguments::AddInput(HValue* value) {
  inputs_.Add(NULL, value->block()->zone());
  SetOperandAt(OperandCount() - 1, value);
}


1952
std::ostream& HPhi::PrintTo(std::ostream& os) const {  // NOLINT
1953
  os << "[";
1954
  for (int i = 0; i < OperandCount(); ++i) {
1955
    os << " " << NameOf(OperandAt(i)) << " ";
1956
  }
1957 1958
  return os << " uses" << UseCount()
            << representation_from_indirect_uses().Mnemonic() << " "
1959
            << TypeOf(this) << "]";
1960 1961 1962 1963
}


void HPhi::AddInput(HValue* value) {
1964
  inputs_.Add(NULL, value->block()->zone());
1965 1966 1967 1968 1969 1970 1971 1972
  SetOperandAt(OperandCount() - 1, value);
  // Mark phis that may have 'arguments' directly or indirectly as an operand.
  if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
    SetFlag(kIsArguments);
  }
}


1973
bool HPhi::HasRealUses() {
1974 1975
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    if (!it.value()->IsPhi()) return true;
1976 1977 1978 1979 1980
  }
  return false;
}


1981
HValue* HPhi::GetRedundantReplacement() {
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
  HValue* candidate = NULL;
  int count = OperandCount();
  int position = 0;
  while (position < count && candidate == NULL) {
    HValue* current = OperandAt(position++);
    if (current != this) candidate = current;
  }
  while (position < count) {
    HValue* current = OperandAt(position++);
    if (current != this && current != candidate) return NULL;
  }
1993
  DCHECK(candidate != this);
1994 1995 1996 1997 1998
  return candidate;
}


void HPhi::DeleteFromGraph() {
1999
  DCHECK(block() != NULL);
2000
  block()->RemovePhi(this);
2001
  DCHECK(block() == NULL);
2002 2003 2004 2005 2006 2007
}


void HPhi::InitRealUses(int phi_id) {
  // Initialize real uses.
  phi_id_ = phi_id;
2008 2009 2010
  // Compute a conservative approximation of truncating uses before inferring
  // representations. The proper, exact computation will be done later, when
  // inserting representation changes.
2011
  SetFlag(kTruncatingToSmi);
2012
  SetFlag(kTruncatingToInt32);
2013 2014 2015
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* value = it.value();
    if (!value->IsPhi()) {
2016
      Representation rep = value->observed_input_representation(it.index());
2017 2018 2019 2020 2021 2022
      representation_from_non_phi_uses_ =
          representation_from_non_phi_uses().generalize(rep);
      if (rep.IsSmi() || rep.IsInteger32() || rep.IsDouble()) {
        has_type_feedback_from_uses_ = true;
      }

2023
      if (FLAG_trace_representation) {
2024 2025
        PrintF("#%d Phi is used by real #%d %s as %s\n",
               id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2026
      }
2027 2028 2029 2030 2031 2032 2033
      if (!value->IsSimulate()) {
        if (!value->CheckFlag(kTruncatingToSmi)) {
          ClearFlag(kTruncatingToSmi);
        }
        if (!value->CheckFlag(kTruncatingToInt32)) {
          ClearFlag(kTruncatingToInt32);
        }
2034
      }
2035 2036 2037 2038 2039 2040
    }
  }
}


void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2041
  if (FLAG_trace_representation) {
2042 2043 2044 2045 2046
    PrintF(
        "generalizing use representation '%s' of #%d Phi "
        "with uses of #%d Phi '%s'\n",
        representation_from_indirect_uses().Mnemonic(), id(), other->id(),
        other->representation_from_non_phi_uses().Mnemonic());
2047 2048
  }

2049 2050 2051
  representation_from_indirect_uses_ =
      representation_from_indirect_uses().generalize(
          other->representation_from_non_phi_uses());
2052 2053 2054
}


2055 2056 2057 2058 2059 2060
void HSimulate::MergeWith(ZoneList<HSimulate*>* list) {
  while (!list->is_empty()) {
    HSimulate* from = list->RemoveLast();
    ZoneList<HValue*>* from_values = &from->values_;
    for (int i = 0; i < from_values->length(); ++i) {
      if (from->HasAssignedIndexAt(i)) {
2061 2062 2063
        int index = from->GetAssignedIndexAt(i);
        if (HasValueForIndex(index)) continue;
        AddAssignedValue(index, from_values->at(i));
2064
      } else {
2065 2066 2067 2068 2069
        if (pop_count_ > 0) {
          pop_count_--;
        } else {
          AddPushedValue(from_values->at(i));
        }
2070 2071
      }
    }
2072 2073
    pop_count_ += from->pop_count_;
    from->DeleteAndReplaceWith(NULL);
2074
  }
2075 2076 2077
}


2078
std::ostream& HSimulate::PrintDataTo(std::ostream& os) const {  // NOLINT
2079 2080
  os << "id=" << ast_id().ToInt();
  if (pop_count_ > 0) os << " pop " << pop_count_;
2081
  if (values_.length() > 0) {
2082
    if (pop_count_ > 0) os << " /";
2083
    for (int i = values_.length() - 1; i >= 0; --i) {
2084
      if (HasAssignedIndexAt(i)) {
2085
        os << " var[" << GetAssignedIndexAt(i) << "] = ";
2086
      } else {
2087
        os << " push ";
2088
      }
2089 2090
      os << NameOf(values_[i]);
      if (i > 0) os << ",";
2091 2092
    }
  }
2093
  return os;
2094 2095 2096
}


2097
void HSimulate::ReplayEnvironment(HEnvironment* env) {
2098
  if (is_done_with_replay()) return;
2099
  DCHECK(env != NULL);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
  env->set_ast_id(ast_id());
  env->Drop(pop_count());
  for (int i = values()->length() - 1; i >= 0; --i) {
    HValue* value = values()->at(i);
    if (HasAssignedIndexAt(i)) {
      env->Bind(GetAssignedIndexAt(i), value);
    } else {
      env->Push(value);
    }
  }
2110
  set_done_with_replay();
2111 2112 2113
}


2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
static void ReplayEnvironmentNested(const ZoneList<HValue*>* values,
                                    HCapturedObject* other) {
  for (int i = 0; i < values->length(); ++i) {
    HValue* value = values->at(i);
    if (value->IsCapturedObject()) {
      if (HCapturedObject::cast(value)->capture_id() == other->capture_id()) {
        values->at(i) = other;
      } else {
        ReplayEnvironmentNested(HCapturedObject::cast(value)->values(), other);
      }
    }
  }
}


2129 2130 2131
// Replay captured objects by replacing all captured objects with the
// same capture id in the current and all outer environments.
void HCapturedObject::ReplayEnvironment(HEnvironment* env) {
2132
  DCHECK(env != NULL);
2133
  while (env != NULL) {
2134
    ReplayEnvironmentNested(env->values(), this);
2135 2136 2137 2138 2139
    env = env->outer();
  }
}


2140
std::ostream& HCapturedObject::PrintDataTo(std::ostream& os) const {  // NOLINT
2141 2142
  os << "#" << capture_id() << " ";
  return HDematerializedObject::PrintDataTo(os);
2143 2144 2145
}


2146 2147
void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
                                         Zone* zone) {
2148
  DCHECK(return_target->IsInlineReturnTarget());
2149 2150 2151 2152
  return_targets_.Add(return_target, zone);
}


2153
std::ostream& HEnterInlined::PrintDataTo(std::ostream& os) const {  // NOLINT
2154 2155 2156 2157 2158
  os << function()->debug_name()->ToCString().get();
  if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
    os << ", JSTailCall";
  }
  return os;
2159 2160 2161
}


2162
static bool IsInteger32(double value) {
2163 2164 2165 2166 2167 2168
  if (value >= std::numeric_limits<int32_t>::min() &&
      value <= std::numeric_limits<int32_t>::max()) {
    double roundtrip_value = static_cast<double>(static_cast<int32_t>(value));
    return bit_cast<int64_t>(roundtrip_value) == bit_cast<int64_t>(value);
  }
  return false;
2169 2170 2171
}


2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
HConstant::HConstant(Special special)
    : HTemplateInstruction<0>(HType::TaggedNumber()),
      object_(Handle<Object>::null()),
      object_map_(Handle<Map>::null()),
      bit_field_(HasDoubleValueField::encode(true) |
                 InstanceTypeField::encode(kUnknownInstanceType)),
      int32_value_(0) {
  DCHECK_EQ(kHoleNaN, special);
  std::memcpy(&double_value_, &kHoleNanInt64, sizeof(double_value_));
  Initialize(Representation::Double());
}


2185
HConstant::HConstant(Handle<Object> object, Representation r)
2186 2187 2188
    : HTemplateInstruction<0>(HType::FromValue(object)),
      object_(Unique<Object>::CreateUninitialized(object)),
      object_map_(Handle<Map>::null()),
2189 2190 2191 2192 2193 2194 2195 2196 2197
      bit_field_(
          HasStableMapValueField::encode(false) |
          HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
          HasDoubleValueField::encode(false) |
          HasExternalReferenceValueField::encode(false) |
          IsNotInNewSpaceField::encode(true) |
          BooleanValueField::encode(object->BooleanValue()) |
          IsUndetectableField::encode(false) | IsCallableField::encode(false) |
          InstanceTypeField::encode(kUnknownInstanceType)) {
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
  if (object->IsNumber()) {
    double n = object->Number();
    bool has_int32_value = IsInteger32(n);
    bit_field_ = HasInt32ValueField::update(bit_field_, has_int32_value);
    int32_value_ = DoubleToInt32(n);
    bit_field_ = HasSmiValueField::update(
        bit_field_, has_int32_value && Smi::IsValid(int32_value_));
    if (std::isnan(n)) {
      double_value_ = std::numeric_limits<double>::quiet_NaN();
      // Canonicalize object with NaN value.
      DCHECK(object->IsHeapObject());  // NaN can't be a Smi.
      Isolate* isolate = HeapObject::cast(*object)->GetIsolate();
      object = isolate->factory()->nan_value();
      object_ = Unique<Object>::CreateUninitialized(object);
    } else {
      double_value_ = n;
      // Canonicalize object with -0.0 value.
      if (bit_cast<int64_t>(n) == bit_cast<int64_t>(-0.0)) {
        DCHECK(object->IsHeapObject());  // -0.0 can't be a Smi.
        Isolate* isolate = HeapObject::cast(*object)->GetIsolate();
        object = isolate->factory()->minus_zero_value();
        object_ = Unique<Object>::CreateUninitialized(object);
      }
    }
    bit_field_ = HasDoubleValueField::update(bit_field_, true);
  }
2224
  if (object->IsHeapObject()) {
2225 2226 2227
    Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
    Isolate* isolate = heap_object->GetIsolate();
    Handle<Map> map(heap_object->map(), isolate);
2228 2229 2230 2231 2232
    bit_field_ = IsNotInNewSpaceField::update(
        bit_field_, !isolate->heap()->InNewSpace(*object));
    bit_field_ = InstanceTypeField::update(bit_field_, map->instance_type());
    bit_field_ =
        IsUndetectableField::update(bit_field_, map->is_undetectable());
2233
    bit_field_ = IsCallableField::update(bit_field_, map->is_callable());
2234
    if (map->is_stable()) object_map_ = Unique<Map>::CreateImmovable(map);
2235 2236 2237
    bit_field_ = HasStableMapValueField::update(
        bit_field_,
        HasMapValue() && Handle<Map>::cast(heap_object)->is_stable());
2238
  }
2239

2240
  Initialize(r);
2241 2242 2243
}


2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
HConstant::HConstant(Unique<Object> object, Unique<Map> object_map,
                     bool has_stable_map_value, Representation r, HType type,
                     bool is_not_in_new_space, bool boolean_value,
                     bool is_undetectable, InstanceType instance_type)
    : HTemplateInstruction<0>(type),
      object_(object),
      object_map_(object_map),
      bit_field_(HasStableMapValueField::encode(has_stable_map_value) |
                 HasSmiValueField::encode(false) |
                 HasInt32ValueField::encode(false) |
                 HasDoubleValueField::encode(false) |
                 HasExternalReferenceValueField::encode(false) |
                 IsNotInNewSpaceField::encode(is_not_in_new_space) |
                 BooleanValueField::encode(boolean_value) |
                 IsUndetectableField::encode(is_undetectable) |
                 InstanceTypeField::encode(instance_type)) {
2260 2261
  DCHECK(!object.handle().is_null());
  DCHECK(!type.IsTaggedNumber() || type.IsNone());
2262 2263 2264 2265
  Initialize(r);
}


2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
HConstant::HConstant(int32_t integer_value, Representation r,
                     bool is_not_in_new_space, Unique<Object> object)
    : object_(object),
      object_map_(Handle<Map>::null()),
      bit_field_(HasStableMapValueField::encode(false) |
                 HasSmiValueField::encode(Smi::IsValid(integer_value)) |
                 HasInt32ValueField::encode(true) |
                 HasDoubleValueField::encode(true) |
                 HasExternalReferenceValueField::encode(false) |
                 IsNotInNewSpaceField::encode(is_not_in_new_space) |
                 BooleanValueField::encode(integer_value != 0) |
                 IsUndetectableField::encode(false) |
                 InstanceTypeField::encode(kUnknownInstanceType)),
      int32_value_(integer_value),
      double_value_(FastI2D(integer_value)) {
2281 2282 2283
  // It's possible to create a constant with a value in Smi-range but stored
  // in a (pre-existing) HeapNumber. See crbug.com/349878.
  bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2284
  bool is_smi = HasSmiValue() && !could_be_heapobject;
2285
  set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2286
  Initialize(r);
2287 2288
}

2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
HConstant::HConstant(double double_value, Representation r,
                     bool is_not_in_new_space, Unique<Object> object)
    : object_(object),
      object_map_(Handle<Map>::null()),
      bit_field_(HasStableMapValueField::encode(false) |
                 HasInt32ValueField::encode(IsInteger32(double_value)) |
                 HasDoubleValueField::encode(true) |
                 HasExternalReferenceValueField::encode(false) |
                 IsNotInNewSpaceField::encode(is_not_in_new_space) |
                 BooleanValueField::encode(double_value != 0 &&
                                           !std::isnan(double_value)) |
                 IsUndetectableField::encode(false) |
                 InstanceTypeField::encode(kUnknownInstanceType)),
verwaest's avatar
verwaest committed
2302
      int32_value_(DoubleToInt32(double_value)) {
2303 2304
  bit_field_ = HasSmiValueField::update(
      bit_field_, HasInteger32Value() && Smi::IsValid(int32_value_));
2305 2306 2307
  // It's possible to create a constant with a value in Smi-range but stored
  // in a (pre-existing) HeapNumber. See crbug.com/349878.
  bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2308
  bool is_smi = HasSmiValue() && !could_be_heapobject;
2309
  set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
verwaest's avatar
verwaest committed
2310 2311 2312 2313 2314
  if (std::isnan(double_value)) {
    double_value_ = std::numeric_limits<double>::quiet_NaN();
  } else {
    double_value_ = double_value;
  }
2315 2316 2317 2318
  Initialize(r);
}


2319
HConstant::HConstant(ExternalReference reference)
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
    : HTemplateInstruction<0>(HType::Any()),
      object_(Unique<Object>(Handle<Object>::null())),
      object_map_(Handle<Map>::null()),
      bit_field_(
          HasStableMapValueField::encode(false) |
          HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
          HasDoubleValueField::encode(false) |
          HasExternalReferenceValueField::encode(true) |
          IsNotInNewSpaceField::encode(true) | BooleanValueField::encode(true) |
          IsUndetectableField::encode(false) |
          InstanceTypeField::encode(kUnknownInstanceType)),
      external_reference_value_(reference) {
2332 2333 2334 2335
  Initialize(Representation::External());
}


2336
void HConstant::Initialize(Representation r) {
2337
  if (r.IsNone()) {
2338
    if (HasSmiValue() && SmiValuesAre31Bits()) {
2339
      r = Representation::Smi();
2340
    } else if (HasInteger32Value()) {
2341
      r = Representation::Integer32();
2342
    } else if (HasDoubleValue()) {
2343
      r = Representation::Double();
2344
    } else if (HasExternalReferenceValue()) {
2345
      r = Representation::External();
2346
    } else {
2347 2348 2349 2350 2351 2352 2353 2354
      Handle<Object> object = object_.handle();
      if (object->IsJSObject()) {
        // Try to eagerly migrate JSObjects that have deprecated maps.
        Handle<JSObject> js_object = Handle<JSObject>::cast(object);
        if (js_object->map()->is_deprecated()) {
          JSObject::TryMigrateInstance(js_object);
        }
      }
2355 2356 2357
      r = Representation::Tagged();
    }
  }
2358 2359 2360 2361 2362 2363 2364
  if (r.IsSmi()) {
    // If we have an existing handle, zap it, because it might be a heap
    // number which we must not re-use when copying this HConstant to
    // Tagged representation later, because having Smi representation now
    // could cause heap object checks not to get emitted.
    object_ = Unique<Object>(Handle<Object>::null());
  }
2365
  if (r.IsSmiOrInteger32() && object_.handle().is_null()) {
2366 2367 2368
    // If it's not a heap object, it can't be in new space.
    bit_field_ = IsNotInNewSpaceField::update(bit_field_, true);
  }
2369 2370
  set_representation(r);
  SetFlag(kUseGVN);
2371 2372 2373
}


2374
bool HConstant::ImmortalImmovable() const {
2375
  if (HasInteger32Value()) {
2376 2377
    return false;
  }
2378
  if (HasDoubleValue()) {
2379 2380 2381 2382 2383
    if (IsSpecialDouble()) {
      return true;
    }
    return false;
  }
2384
  if (HasExternalReferenceValue()) {
2385 2386 2387
    return false;
  }

2388
  DCHECK(!object_.handle().is_null());
2389
  Heap* heap = isolate()->heap();
2390 2391
  DCHECK(!object_.IsKnownGlobal(heap->minus_zero_value()));
  DCHECK(!object_.IsKnownGlobal(heap->nan_value()));
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
  return
#define IMMORTAL_IMMOVABLE_ROOT(name) \
  object_.IsKnownGlobal(heap->root(Heap::k##name##RootIndex)) ||
      IMMORTAL_IMMOVABLE_ROOT_LIST(IMMORTAL_IMMOVABLE_ROOT)
#undef IMMORTAL_IMMOVABLE_ROOT
#define INTERNALIZED_STRING(name, value) \
      object_.IsKnownGlobal(heap->name()) ||
      INTERNALIZED_STRING_LIST(INTERNALIZED_STRING)
#undef INTERNALIZED_STRING
#define STRING_TYPE(NAME, size, name, Name) \
      object_.IsKnownGlobal(heap->name##_map()) ||
      STRING_TYPE_LIST(STRING_TYPE)
#undef STRING_TYPE
      false;
2406 2407 2408
}


2409
bool HConstant::EmitAtUses() {
2410
  DCHECK(IsLinked());
2411 2412 2413
  if (block()->graph()->has_osr() &&
      block()->graph()->IsStandardConstant(this)) {
    return true;
2414
  }
2415
  if (HasNoUses()) return true;
2416 2417
  if (IsCell()) return false;
  if (representation().IsDouble()) return false;
2418
  if (representation().IsExternal()) return false;
2419
  return true;
2420 2421 2422
}


2423
HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2424 2425 2426 2427 2428 2429
  if (r.IsSmi() && !HasSmiValue()) return NULL;
  if (r.IsInteger32() && !HasInteger32Value()) return NULL;
  if (r.IsDouble() && !HasDoubleValue()) return NULL;
  if (r.IsExternal() && !HasExternalReferenceValue()) return NULL;
  if (HasInteger32Value()) {
    return new (zone) HConstant(int32_value_, r, NotInNewSpace(), object_);
2430
  }
2431 2432
  if (HasDoubleValue()) {
    return new (zone) HConstant(double_value_, r, NotInNewSpace(), object_);
2433
  }
2434
  if (HasExternalReferenceValue()) {
2435 2436
    return new(zone) HConstant(external_reference_value_);
  }
2437
  DCHECK(!object_.handle().is_null());
2438 2439 2440
  return new (zone) HConstant(object_, object_map_, HasStableMapValue(), r,
                              type_, NotInNewSpace(), BooleanValue(),
                              IsUndetectable(), GetInstanceType());
2441 2442 2443
}


2444 2445
Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
  HConstant* res = NULL;
2446 2447 2448 2449 2450 2451 2452
  if (HasInteger32Value()) {
    res = new (zone) HConstant(int32_value_, Representation::Integer32(),
                               NotInNewSpace(), object_);
  } else if (HasDoubleValue()) {
    res = new (zone)
        HConstant(DoubleToInt32(double_value_), Representation::Integer32(),
                  NotInNewSpace(), object_);
2453
  }
2454
  return res != NULL ? Just(res) : Nothing<HConstant*>();
2455 2456 2457
}


2458 2459
Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Isolate* isolate,
                                                   Zone* zone) {
2460
  HConstant* res = NULL;
2461
  Handle<Object> handle = this->handle(isolate);
2462 2463
  if (handle->IsBoolean()) {
    res = handle->BooleanValue() ?
2464
      new(zone) HConstant(1) : new(zone) HConstant(0);
2465
  } else if (handle->IsUndefined(isolate)) {
2466
    res = new (zone) HConstant(std::numeric_limits<double>::quiet_NaN());
2467
  } else if (handle->IsNull(isolate)) {
2468
    res = new(zone) HConstant(0);
2469 2470
  } else if (handle->IsString()) {
    res = new(zone) HConstant(String::ToNumber(Handle<String>::cast(handle)));
2471
  }
2472
  return res != NULL ? Just(res) : Nothing<HConstant*>();
2473 2474
}

2475

2476
std::ostream& HConstant::PrintDataTo(std::ostream& os) const {  // NOLINT
2477
  if (HasInteger32Value()) {
2478
    os << int32_value_ << " ";
2479
  } else if (HasDoubleValue()) {
2480
    os << double_value_ << " ";
2481
  } else if (HasExternalReferenceValue()) {
2482
    os << reinterpret_cast<void*>(external_reference_value_.address()) << " ";
2483
  } else {
2484
    // The handle() method is silently and lazily mutating the object.
2485
    Handle<Object> h = const_cast<HConstant*>(this)->handle(isolate());
2486 2487 2488
    os << Brief(*h) << " ";
    if (HasStableMapValue()) os << "[stable-map] ";
    if (HasObjectMap()) os << "[map " << *ObjectMap().handle() << "] ";
2489
  }
2490
  if (!NotInNewSpace()) os << "[new space] ";
2491
  return os;
2492 2493 2494
}


2495
std::ostream& HBinaryOperation::PrintDataTo(std::ostream& os) const {  // NOLINT
2496 2497 2498 2499
  os << NameOf(left()) << " " << NameOf(right());
  if (CheckFlag(kCanOverflow)) os << " !";
  if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
  return os;
2500 2501 2502
}


2503
void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
2504
  DCHECK(CheckFlag(kFlexibleRepresentation));
2505 2506
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
2507 2508 2509 2510 2511 2512

  if (representation().IsSmi() && HasNonSmiUse()) {
    UpdateRepresentation(
        Representation::Integer32(), h_infer, "use requirements");
  }

2513 2514 2515 2516 2517 2518
  if (observed_output_representation_.IsNone()) {
    new_rep = RepresentationFromUses();
    UpdateRepresentation(new_rep, h_infer, "uses");
  } else {
    new_rep = RepresentationFromOutput();
    UpdateRepresentation(new_rep, h_infer, "output");
2519
  }
2520 2521 2522
}


2523 2524 2525 2526 2527
Representation HBinaryOperation::RepresentationFromInputs() {
  // Determine the worst case of observed input representations and
  // the currently assumed output representation.
  Representation rep = representation();
  for (int i = 1; i <= 2; ++i) {
2528
    rep = rep.generalize(observed_input_representation(i));
2529 2530 2531 2532 2533
  }
  // If any of the actual input representation is more general than what we
  // have so far but not Tagged, use that representation instead.
  Representation left_rep = left()->representation();
  Representation right_rep = right()->representation();
2534 2535
  if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
  if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
2536

2537 2538 2539 2540 2541 2542 2543 2544 2545
  return rep;
}


bool HBinaryOperation::IgnoreObservedOutputRepresentation(
    Representation current_rep) {
  return ((current_rep.IsInteger32() && CheckUsesForFlag(kTruncatingToInt32)) ||
          (current_rep.IsSmi() && CheckUsesForFlag(kTruncatingToSmi))) &&
         // Mul in Integer32 mode would be too precise.
2546
         (!this->IsMul() || HMul::cast(this)->MulMinusOne());
2547 2548 2549 2550 2551
}


Representation HBinaryOperation::RepresentationFromOutput() {
  Representation rep = representation();
2552 2553 2554 2555 2556
  // Consider observed output representation, but ignore it if it's Double,
  // this instruction is not a division, and all its uses are truncating
  // to Integer32.
  if (observed_output_representation_.is_more_general_than(rep) &&
      !IgnoreObservedOutputRepresentation(rep)) {
2557
    return observed_output_representation_;
2558
  }
2559
  return Representation::None();
2560 2561 2562 2563
}


void HBinaryOperation::AssumeRepresentation(Representation r) {
2564 2565
  set_observed_input_representation(1, r);
  set_observed_input_representation(2, r);
2566 2567 2568 2569
  HValue::AssumeRepresentation(r);
}


2570
void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
2571
  DCHECK(CheckFlag(kFlexibleRepresentation));
2572 2573 2574 2575 2576 2577
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  // Do not care about uses.
}


2578
Range* HBitwise::InferRange(Zone* zone) {
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
  if (op() == Token::BIT_XOR) {
    if (left()->HasRange() && right()->HasRange()) {
      // The maximum value has the high bit, and all bits below, set:
      // (1 << high) - 1.
      // If the range can be negative, the minimum int is a negative number with
      // the high bit, and all bits below, unset:
      // -(1 << high).
      // If it cannot be negative, conservatively choose 0 as minimum int.
      int64_t left_upper = left()->range()->upper();
      int64_t left_lower = left()->range()->lower();
      int64_t right_upper = right()->range()->upper();
      int64_t right_lower = right()->range()->lower();

      if (left_upper < 0) left_upper = ~left_upper;
      if (left_lower < 0) left_lower = ~left_lower;
      if (right_upper < 0) right_upper = ~right_upper;
      if (right_lower < 0) right_lower = ~right_lower;

      int high = MostSignificantBit(
          static_cast<uint32_t>(
              left_upper | left_lower | right_upper | right_lower));

      int64_t limit = 1;
      limit <<= high;
      int32_t min = (left()->range()->CanBeNegative() ||
                     right()->range()->CanBeNegative())
                    ? static_cast<int32_t>(-limit) : 0;
      return new(zone) Range(min, static_cast<int32_t>(limit - 1));
2607
    }
2608 2609 2610
    Range* result = HValue::InferRange(zone);
    result->set_can_be_minus_zero(false);
    return result;
2611
  }
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
  const int32_t kDefaultMask = static_cast<int32_t>(0xffffffff);
  int32_t left_mask = (left()->range() != NULL)
      ? left()->range()->Mask()
      : kDefaultMask;
  int32_t right_mask = (right()->range() != NULL)
      ? right()->range()->Mask()
      : kDefaultMask;
  int32_t result_mask = (op() == Token::BIT_AND)
      ? left_mask & right_mask
      : left_mask | right_mask;
2622 2623 2624 2625 2626
  if (result_mask >= 0) return new(zone) Range(0, result_mask);

  Range* result = HValue::InferRange(zone);
  result->set_can_be_minus_zero(false);
  return result;
2627 2628 2629
}


2630
Range* HSar::InferRange(Zone* zone) {
2631 2632 2633
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
2634
      Range* result = (left()->range() != NULL)
2635 2636
          ? left()->range()->Copy(zone)
          : new(zone) Range();
2637
      result->Sar(c->Integer32Value());
2638 2639 2640
      return result;
    }
  }
2641
  return HValue::InferRange(zone);
2642 2643 2644
}


2645
Range* HShr::InferRange(Zone* zone) {
2646 2647 2648 2649 2650 2651 2652
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
      int shift_count = c->Integer32Value() & 0x1f;
      if (left()->range()->CanBeNegative()) {
        // Only compute bounds if the result always fits into an int32.
        return (shift_count >= 1)
2653 2654 2655
            ? new(zone) Range(0,
                              static_cast<uint32_t>(0xffffffff) >> shift_count)
            : new(zone) Range();
2656 2657 2658
      } else {
        // For positive inputs we can use the >> operator.
        Range* result = (left()->range() != NULL)
2659 2660
            ? left()->range()->Copy(zone)
            : new(zone) Range();
2661 2662 2663 2664 2665
        result->Sar(c->Integer32Value());
        return result;
      }
    }
  }
2666
  return HValue::InferRange(zone);
2667 2668 2669
}


2670
Range* HShl::InferRange(Zone* zone) {
2671 2672 2673
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
2674
      Range* result = (left()->range() != NULL)
2675 2676
          ? left()->range()->Copy(zone)
          : new(zone) Range();
2677
      result->Shl(c->Integer32Value());
2678 2679 2680
      return result;
    }
  }
2681
  return HValue::InferRange(zone);
2682 2683 2684
}


2685
Range* HLoadNamedField::InferRange(Zone* zone) {
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
  if (access().representation().IsInteger8()) {
    return new(zone) Range(kMinInt8, kMaxInt8);
  }
  if (access().representation().IsUInteger8()) {
    return new(zone) Range(kMinUInt8, kMaxUInt8);
  }
  if (access().representation().IsInteger16()) {
    return new(zone) Range(kMinInt16, kMaxInt16);
  }
  if (access().representation().IsUInteger16()) {
    return new(zone) Range(kMinUInt16, kMaxUInt16);
2697
  }
2698 2699 2700 2701 2702 2703 2704
  if (access().IsStringLength()) {
    return new(zone) Range(0, String::kMaxLength);
  }
  return HValue::InferRange(zone);
}


2705
Range* HLoadKeyed::InferRange(Zone* zone) {
2706
  switch (elements_kind()) {
2707
    case INT8_ELEMENTS:
2708
      return new(zone) Range(kMinInt8, kMaxInt8);
2709 2710
    case UINT8_ELEMENTS:
    case UINT8_CLAMPED_ELEMENTS:
2711
      return new(zone) Range(kMinUInt8, kMaxUInt8);
2712
    case INT16_ELEMENTS:
2713
      return new(zone) Range(kMinInt16, kMaxInt16);
2714
    case UINT16_ELEMENTS:
2715
      return new(zone) Range(kMinUInt16, kMaxUInt16);
2716
    default:
2717
      return HValue::InferRange(zone);
2718 2719 2720
  }
}

2721

2722
std::ostream& HCompareGeneric::PrintDataTo(std::ostream& os) const {  // NOLINT
2723 2724
  os << Token::Name(token()) << " ";
  return HBinaryOperation::PrintDataTo(os);
2725 2726 2727
}


2728 2729
std::ostream& HStringCompareAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
2730 2731
  os << Token::Name(token()) << " ";
  return HControlInstruction::PrintDataTo(os);
2732 2733 2734
}


2735 2736
std::ostream& HCompareNumericAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
2737 2738
  os << Token::Name(token()) << " " << NameOf(left()) << " " << NameOf(right());
  return HControlInstruction::PrintDataTo(os);
2739 2740 2741
}


2742 2743
std::ostream& HCompareObjectEqAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
2744 2745
  os << NameOf(left()) << " " << NameOf(right());
  return HControlInstruction::PrintDataTo(os);
2746 2747 2748
}


2749
bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2750 2751 2752 2753
  if (known_successor_index() != kNoKnownSuccessorIndex) {
    *block = SuccessorAt(known_successor_index());
    return true;
  }
2754
  if (FLAG_fold_constants && left()->IsConstant() && right()->IsConstant()) {
2755
    *block = HConstant::cast(left())->DataEquals(HConstant::cast(right()))
2756 2757 2758 2759 2760 2761 2762 2763 2764
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


bool HIsStringAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2765 2766 2767 2768
  if (known_successor_index() != kNoKnownSuccessorIndex) {
    *block = SuccessorAt(known_successor_index());
    return true;
  }
2769 2770 2771 2772 2773
  if (FLAG_fold_constants && value()->IsConstant()) {
    *block = HConstant::cast(value())->HasStringValue()
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
2774 2775 2776 2777 2778 2779 2780 2781
  if (value()->type().IsString()) {
    *block = FirstSuccessor();
    return true;
  }
  if (value()->type().IsSmi() ||
      value()->type().IsNull() ||
      value()->type().IsBoolean() ||
      value()->type().IsUndefined() ||
2782
      value()->type().IsJSReceiver()) {
2783 2784 2785
    *block = SecondSuccessor();
    return true;
  }
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
  *block = NULL;
  return false;
}


bool HIsUndetectableAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (FLAG_fold_constants && value()->IsConstant()) {
    *block = HConstant::cast(value())->IsUndetectable()
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
  if (value()->type().IsNull() || value()->type().IsUndefined()) {
    *block = FirstSuccessor();
    return true;
  }
  if (value()->type().IsBoolean() ||
      value()->type().IsSmi() ||
      value()->type().IsString() ||
      value()->type().IsJSReceiver()) {
    *block = SecondSuccessor();
    return true;
  }
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
  *block = NULL;
  return false;
}


bool HHasInstanceTypeAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (FLAG_fold_constants && value()->IsConstant()) {
    InstanceType type = HConstant::cast(value())->GetInstanceType();
    *block = (from_ <= type) && (type <= to_)
        ? FirstSuccessor() : SecondSuccessor();
2818 2819 2820 2821 2822 2823 2824
    return true;
  }
  *block = NULL;
  return false;
}


2825 2826
void HCompareHoleAndBranch::InferRepresentation(
    HInferRepresentationPhase* h_infer) {
2827
  ChangeRepresentation(value()->representation());
2828 2829 2830
}


2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
bool HCompareNumericAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (left() == right() &&
      left()->representation().IsSmiOrInteger32()) {
    *block = (token() == Token::EQ ||
              token() == Token::EQ_STRICT ||
              token() == Token::LTE ||
              token() == Token::GTE)
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


2846
std::ostream& HGoto::PrintDataTo(std::ostream& os) const {  // NOLINT
2847
  return os << *SuccessorAt(0);
2848 2849 2850
}


2851
void HCompareNumericAndBranch::InferRepresentation(
2852
    HInferRepresentationPhase* h_infer) {
2853 2854
  Representation left_rep = left()->representation();
  Representation right_rep = right()->representation();
2855 2856 2857
  Representation observed_left = observed_input_representation(0);
  Representation observed_right = observed_input_representation(1);

2858 2859 2860 2861
  Representation rep = Representation::None();
  rep = rep.generalize(observed_left);
  rep = rep.generalize(observed_right);
  if (rep.IsNone() || rep.IsSmiOrInteger32()) {
2862 2863 2864 2865 2866
    if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
    if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
  } else {
    rep = Representation::Double();
  }
2867 2868

  if (rep.IsDouble()) {
2869 2870 2871 2872
    // According to the ES5 spec (11.9.3, 11.8.5), Equality comparisons (==, ===
    // and !=) have special handling of undefined, e.g. undefined == undefined
    // is 'true'. Relational comparisons have a different semantic, first
    // calling ToPrimitive() on their arguments.  The standard Crankshaft
2873 2874 2875
    // tagged-to-double conversion to ensure the HCompareNumericAndBranch's
    // inputs are doubles caused 'undefined' to be converted to NaN. That's
    // compatible out-of-the box with ordered relational comparisons (<, >, <=,
2876 2877 2878 2879 2880 2881
    // >=). However, for equality comparisons (and for 'in' and 'instanceof'),
    // it is not consistent with the spec. For example, it would cause undefined
    // == undefined (should be true) to be evaluated as NaN == NaN
    // (false). Therefore, any comparisons other than ordered relational
    // comparisons must cause a deopt when one of their arguments is undefined.
    // See also v8:1434
2882
    if (Token::IsOrderedRelationalCompareOp(token_)) {
2883
      SetFlag(kTruncatingToNumber);
2884
    }
2885
  }
2886
  ChangeRepresentation(rep);
2887 2888 2889
}


2890
std::ostream& HParameter::PrintDataTo(std::ostream& os) const {  // NOLINT
2891
  return os << index();
2892 2893 2894
}


2895
std::ostream& HLoadNamedField::PrintDataTo(std::ostream& os) const {  // NOLINT
2896
  os << NameOf(object()) << access_;
2897

2898
  if (maps() != NULL) {
2899
    os << " [" << *maps()->at(0).handle();
2900
    for (int i = 1; i < maps()->size(); ++i) {
2901
      os << "," << *maps()->at(i).handle();
2902
    }
2903
    os << "]";
2904 2905
  }

2906 2907
  if (HasDependency()) os << " " << NameOf(dependency());
  return os;
2908 2909 2910
}


2911
std::ostream& HLoadKeyed::PrintDataTo(std::ostream& os) const {  // NOLINT
2912
  if (!is_fixed_typed_array()) {
2913
    os << NameOf(elements());
2914
  } else {
2915 2916
    DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
2917
    os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
2918 2919
  }

2920 2921 2922
  os << "[" << NameOf(key());
  if (IsDehoisted()) os << " + " << base_offset();
  os << "]";
2923

2924 2925 2926
  if (HasDependency()) os << " " << NameOf(dependency());
  if (RequiresHoleCheck()) os << " check_hole";
  return os;
2927 2928 2929
}


2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
bool HLoadKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
  // The base offset is usually simply the size of the array header, except
  // with dehoisting adds an addition offset due to a array index key
  // manipulation, in which case it becomes (array header size +
  // constant-offset-from-key * kPointerSize)
  uint32_t base_offset = BaseOffsetField::decode(bit_field_);
  v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset;
  addition_result += increase_by_value;
  if (!addition_result.IsValid()) return false;
  base_offset = addition_result.ValueOrDie();
  if (!BaseOffsetField::is_valid(base_offset)) return false;
  bit_field_ = BaseOffsetField::update(bit_field_, base_offset);
  return true;
}


2946
bool HLoadKeyed::UsesMustHandleHole() const {
2947
  if (IsFastPackedElementsKind(elements_kind())) {
2948 2949 2950
    return false;
  }

2951
  if (IsFixedTypedArrayElementsKind(elements_kind())) {
2952 2953 2954
    return false;
  }

2955 2956 2957 2958 2959 2960
  if (hole_mode() == ALLOW_RETURN_HOLE) {
    if (IsFastDoubleElementsKind(elements_kind())) {
      return AllUsesCanTreatHoleAsNaN();
    }
    return true;
  }
2961

2962
  if (IsFastDoubleElementsKind(elements_kind())) {
2963
    return false;
2964 2965
  }

2966 2967 2968 2969 2970
  // Holes are only returned as tagged values.
  if (!representation().IsTagged()) {
    return false;
  }

2971 2972
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
2973
    if (!use->IsChange()) return false;
2974
  }
2975

2976 2977 2978 2979
  return true;
}


2980
bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
2981
  return IsFastDoubleElementsKind(elements_kind()) &&
2982
         CheckUsesForFlag(HValue::kTruncatingToNumber);
2983 2984 2985
}


2986 2987 2988 2989 2990
bool HLoadKeyed::RequiresHoleCheck() const {
  if (IsFastPackedElementsKind(elements_kind())) {
    return false;
  }

2991
  if (IsFixedTypedArrayElementsKind(elements_kind())) {
2992 2993 2994
    return false;
  }

2995 2996 2997 2998
  if (hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
    return false;
  }

2999
  return !UsesMustHandleHole();
3000 3001
}

3002 3003
HValue* HCallWithDescriptor::Canonicalize() {
  if (kind() != Code::KEYED_LOAD_IC) return this;
3004

3005 3006 3007
  // Recognize generic keyed loads that use property name generated
  // by for-in statement as a key and rewrite them into fast property load
  // by index.
3008 3009 3010 3011
  typedef LoadWithVectorDescriptor Descriptor;
  HValue* key = parameter(Descriptor::kName);
  if (key->IsLoadKeyed()) {
    HLoadKeyed* key_load = HLoadKeyed::cast(key);
3012
    if (key_load->elements()->IsForInCacheArray()) {
3013
      HForInCacheArray* names_cache =
3014
          HForInCacheArray::cast(key_load->elements());
3015

3016 3017
      HValue* object = parameter(Descriptor::kReceiver);
      if (names_cache->enumerable() == object) {
3018 3019
        HForInCacheArray* index_cache =
            names_cache->index_cache();
3020 3021
        HCheckMapValue* map_check = HCheckMapValue::New(
            block()->graph()->isolate(), block()->graph()->zone(),
3022
            block()->graph()->GetInvalidContext(), object, names_cache->map());
3023
        HInstruction* index = HLoadKeyed::New(
3024 3025
            block()->graph()->isolate(), block()->graph()->zone(),
            block()->graph()->GetInvalidContext(), index_cache, key_load->key(),
3026
            key_load->key(), nullptr, key_load->elements_kind());
3027 3028
        map_check->InsertBefore(this);
        index->InsertBefore(this);
3029
        return Prepend(new (block()->zone()) HLoadFieldByIndex(object, index));
3030 3031 3032 3033 3034 3035
      }
    }
  }
  return this;
}

3036
std::ostream& HStoreNamedField::PrintDataTo(std::ostream& os) const {  // NOLINT
3037 3038 3039 3040
  os << NameOf(object()) << access_ << " = " << NameOf(value());
  if (NeedsWriteBarrier()) os << " (write-barrier)";
  if (has_transition()) os << " (transition map " << *transition_map() << ")";
  return os;
3041 3042 3043
}


3044
std::ostream& HStoreKeyed::PrintDataTo(std::ostream& os) const {  // NOLINT
3045
  if (!is_fixed_typed_array()) {
3046
    os << NameOf(elements());
3047
  } else {
3048 3049
    DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3050
    os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3051
  }
3052

3053 3054 3055
  os << "[" << NameOf(key());
  if (IsDehoisted()) os << " + " << base_offset();
  return os << "] = " << NameOf(value());
3056 3057 3058
}


3059 3060
std::ostream& HTransitionElementsKind::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3061
  os << NameOf(object());
3062 3063
  ElementsKind from_kind = original_map().handle()->elements_kind();
  ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3064 3065 3066 3067 3068 3069
  os << " " << *original_map().handle() << " ["
     << ElementsAccessor::ForKind(from_kind)->name() << "] -> "
     << *transitioned_map().handle() << " ["
     << ElementsAccessor::ForKind(to_kind)->name() << "]";
  if (IsSimpleMapChangeTransition(from_kind, to_kind)) os << " (simple)";
  return os;
3070 3071 3072
}


3073 3074
std::ostream& HInnerAllocatedObject::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3075 3076
  os << NameOf(base_object()) << " offset ";
  return offset()->PrintTo(os);
3077 3078 3079
}


3080
std::ostream& HLoadContextSlot::PrintDataTo(std::ostream& os) const {  // NOLINT
3081
  return os << NameOf(value()) << "[" << slot_index() << "]";
3082 3083 3084
}


3085 3086
std::ostream& HStoreContextSlot::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3087 3088
  return os << NameOf(context()) << "[" << slot_index()
            << "] = " << NameOf(value());
3089 3090 3091
}


3092 3093 3094
// Implementation of type inference and type conversions. Calculates
// the inferred type of this instruction based on the input operands.

3095
HType HValue::CalculateInferredType() {
3096 3097 3098 3099
  return type_;
}


3100
HType HPhi::CalculateInferredType() {
3101 3102 3103
  if (OperandCount() == 0) return HType::Tagged();
  HType result = OperandAt(0)->type();
  for (int i = 1; i < OperandCount(); ++i) {
3104 3105 3106 3107 3108 3109 3110
    HType current = OperandAt(i)->type();
    result = result.Combine(current);
  }
  return result;
}


3111 3112 3113 3114 3115 3116
HType HChange::CalculateInferredType() {
  if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
  return type();
}


3117
Representation HUnaryMathOperation::RepresentationFromInputs() {
3118 3119 3120 3121 3122 3123
  if (SupportsFlexibleFloorAndRound() &&
      (op_ == kMathFloor || op_ == kMathRound)) {
    // Floor and Round always take a double input. The integral result can be
    // used as an integer or a double. Infer the representation from the uses.
    return Representation::None();
  }
3124 3125 3126 3127
  Representation rep = representation();
  // If any of the actual input representation is more general than what we
  // have so far but not Tagged, use that representation instead.
  Representation input_rep = value()->representation();
3128 3129 3130
  if (!input_rep.IsTagged()) {
    rep = rep.generalize(input_rep);
  }
3131 3132 3133 3134
  return rep;
}


3135
bool HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
3136
                                          HValue* dominator) {
3137
  DCHECK(side_effect == kNewSpacePromotion);
3138
  DCHECK(!IsAllocationFolded());
3139
  Zone* zone = block()->zone();
3140
  Isolate* isolate = block()->isolate();
3141
  if (!FLAG_use_allocation_folding) return false;
3142

3143
  // Try to fold allocations together with their dominating allocations.
3144 3145 3146 3147
  if (!dominator->IsAllocate()) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s)\n",
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3148 3149 3150 3151 3152 3153 3154 3155 3156
    }
    return false;
  }

  // Check whether we are folding within the same block for local folding.
  if (FLAG_use_local_allocation_folding && dominator->block() != block()) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s), crosses basic blocks\n",
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3157
    }
3158
    return false;
3159
  }
3160

3161
  HAllocate* dominator_allocate = HAllocate::cast(dominator);
3162 3163
  HValue* dominator_size = dominator_allocate->size();
  HValue* current_size = size();
3164

3165
  // TODO(hpayer): Add support for non-constant allocation in dominator.
3166 3167
  if (!current_size->IsInteger32Constant() ||
      !dominator_size->IsInteger32Constant()) {
3168 3169
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s), "
3170
             "dynamic allocation size in dominator\n",
3171 3172 3173 3174 3175
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
    return false;
  }

3176 3177 3178 3179 3180 3181 3182
  if (IsAllocationFoldingDominator()) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s), already dominator\n", id(),
             Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
    return false;
  }
3183 3184 3185 3186 3187 3188

  if (!IsFoldable(dominator_allocate)) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s), different spaces\n", id(),
             Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
3189 3190 3191
    return false;
  }

3192 3193
  DCHECK(
      (IsNewSpaceAllocation() && dominator_allocate->IsNewSpaceAllocation()) ||
3194
      (IsOldSpaceAllocation() && dominator_allocate->IsOldSpaceAllocation()));
3195

3196 3197 3198 3199 3200
  // First update the size of the dominator allocate instruction.
  dominator_size = dominator_allocate->size();
  int32_t original_object_size =
      HConstant::cast(dominator_size)->GetInteger32Constant();
  int32_t dominator_size_constant = original_object_size;
3201 3202

  if (MustAllocateDoubleAligned()) {
3203 3204
    if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
      dominator_size_constant += kDoubleSize / 2;
3205 3206 3207
    }
  }

3208
  int32_t current_size_max_value = size()->GetInteger32Constant();
3209
  int32_t new_dominator_size = dominator_size_constant + current_size_max_value;
3210

3211
  // Since we clear the first word after folded memory, we cannot use the
3212 3213
  // whole kMaxRegularHeapObjectSize memory.
  if (new_dominator_size > kMaxRegularHeapObjectSize - kPointerSize) {
3214 3215
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3216
          id(), Mnemonic(), dominator_allocate->id(),
3217
          dominator_allocate->Mnemonic(), new_dominator_size);
3218
    }
3219
    return false;
3220
  }
3221

3222 3223 3224
  HInstruction* new_dominator_size_value = HConstant::CreateAndInsertBefore(
      isolate, zone, context(), new_dominator_size, Representation::None(),
      dominator_allocate);
3225

3226
  dominator_allocate->UpdateSize(new_dominator_size_value);
3227 3228 3229 3230 3231 3232

  if (MustAllocateDoubleAligned()) {
    if (!dominator_allocate->MustAllocateDoubleAligned()) {
      dominator_allocate->MakeDoubleAligned();
    }
  }
3233

3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
  if (!dominator_allocate->IsAllocationFoldingDominator()) {
    HAllocate* first_alloc =
        HAllocate::New(isolate, zone, dominator_allocate->context(),
                       dominator_size, dominator_allocate->type(),
                       IsNewSpaceAllocation() ? NOT_TENURED : TENURED,
                       JS_OBJECT_TYPE, block()->graph()->GetConstant0());
    first_alloc->InsertAfter(dominator_allocate);
    dominator_allocate->ReplaceAllUsesWith(first_alloc);
    dominator_allocate->MakeAllocationFoldingDominator();
    first_alloc->MakeFoldedAllocation(dominator_allocate);
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) inserted for dominator #%d (%s)\n", first_alloc->id(),
             first_alloc->Mnemonic(), dominator_allocate->id(),
             dominator_allocate->Mnemonic());
    }
  }
3250

3251
  MakeFoldedAllocation(dominator_allocate);
3252

3253
  if (FLAG_trace_allocation_folding) {
3254 3255 3256
    PrintF("#%d (%s) folded into #%d (%s), new dominator size: %d\n", id(),
           Mnemonic(), dominator_allocate->id(), dominator_allocate->Mnemonic(),
           new_dominator_size);
3257
  }
3258
  return true;
3259 3260 3261
}


3262
std::ostream& HAllocate::PrintDataTo(std::ostream& os) const {  // NOLINT
3263 3264
  os << NameOf(size()) << " (";
  if (IsNewSpaceAllocation()) os << "N";
3265
  if (IsOldSpaceAllocation()) os << "P";
3266 3267
  if (MustAllocateDoubleAligned()) os << "A";
  if (MustPrefillWithFiller()) os << "F";
3268 3269
  if (IsAllocationFoldingDominator()) os << "d";
  if (IsAllocationFolded()) os << "f";
3270
  return os << ")";
3271 3272 3273
}


3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
bool HStoreKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
  // The base offset is usually simply the size of the array header, except
  // with dehoisting adds an addition offset due to a array index key
  // manipulation, in which case it becomes (array header size +
  // constant-offset-from-key * kPointerSize)
  v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset_;
  addition_result += increase_by_value;
  if (!addition_result.IsValid()) return false;
  base_offset_ = addition_result.ValueOrDie();
  return true;
}


3287
bool HStoreKeyed::NeedsCanonicalization() {
3288 3289 3290
  switch (value()->opcode()) {
    case kLoadKeyed: {
      ElementsKind load_kind = HLoadKeyed::cast(value())->elements_kind();
3291
      return IsFixedFloatElementsKind(load_kind);
3292 3293 3294 3295 3296
    }
    case kChange: {
      Representation from = HChange::cast(value())->from();
      return from.IsTagged() || from.IsHeapObject();
    }
verwaest's avatar
verwaest committed
3297 3298
    case kConstant:
      // Double constants are canonicalized upon construction.
3299
      return false;
verwaest's avatar
verwaest committed
3300 3301
    default:
      return !value()->IsBinaryOperation();
3302
  }
3303 3304 3305
}


3306 3307 3308 3309
#define H_CONSTANT_INT(val) \
  HConstant::New(isolate, zone, context, static_cast<int32_t>(val))
#define H_CONSTANT_DOUBLE(val) \
  HConstant::New(isolate, zone, context, static_cast<double>(val))
3310

3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
#define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op)                     \
  HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context,   \
                            HValue* left, HValue* right) {                   \
    if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {  \
      HConstant* c_left = HConstant::cast(left);                             \
      HConstant* c_right = HConstant::cast(right);                           \
      if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {         \
        double double_res = c_left->DoubleValue() op c_right->DoubleValue(); \
        if (IsInt32Double(double_res)) {                                     \
          return H_CONSTANT_INT(double_res);                                 \
        }                                                                    \
        return H_CONSTANT_DOUBLE(double_res);                                \
      }                                                                      \
    }                                                                        \
    return new (zone) HInstr(context, left, right);                          \
3326
  }
3327 3328 3329 3330 3331 3332 3333 3334

DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HAdd, +)
DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HMul, *)
DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HSub, -)

#undef DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR


3335
HInstruction* HStringAdd::New(Isolate* isolate, Zone* zone, HValue* context,
3336
                              HValue* left, HValue* right,
3337 3338 3339
                              PretenureFlag pretenure_flag,
                              StringAddFlags flags,
                              Handle<AllocationSite> allocation_site) {
3340 3341 3342 3343
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
    HConstant* c_right = HConstant::cast(right);
    HConstant* c_left = HConstant::cast(left);
    if (c_left->HasStringValue() && c_right->HasStringValue()) {
3344 3345 3346 3347
      Handle<String> left_string = c_left->StringValue();
      Handle<String> right_string = c_right->StringValue();
      // Prevent possible exception by invalid string length.
      if (left_string->length() + right_string->length() < String::kMaxLength) {
3348
        MaybeHandle<String> concat = isolate->factory()->NewConsString(
3349
            c_left->StringValue(), c_right->StringValue());
3350
        return HConstant::New(isolate, zone, context, concat.ToHandleChecked());
3351
      }
3352 3353
    }
  }
3354 3355
  return new (zone)
      HStringAdd(context, left, right, pretenure_flag, flags, allocation_site);
3356 3357 3358
}


3359
std::ostream& HStringAdd::PrintDataTo(std::ostream& os) const {  // NOLINT
3360
  if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
3361
    os << "_CheckBoth";
3362
  } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_LEFT) {
3363
    os << "_CheckLeft";
3364
  } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_RIGHT) {
3365
    os << "_CheckRight";
3366
  }
3367 3368 3369 3370 3371 3372 3373
  HBinaryOperation::PrintDataTo(os);
  os << " (";
  if (pretenure_flag() == NOT_TENURED)
    os << "N";
  else if (pretenure_flag() == TENURED)
    os << "D";
  return os << ")";
3374 3375 3376
}


3377 3378
HInstruction* HStringCharFromCode::New(Isolate* isolate, Zone* zone,
                                       HValue* context, HValue* char_code) {
3379 3380 3381
  if (FLAG_fold_constants && char_code->IsConstant()) {
    HConstant* c_code = HConstant::cast(char_code);
    if (c_code->HasNumberValue()) {
3382
      if (std::isfinite(c_code->DoubleValue())) {
3383
        uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
3384 3385
        return HConstant::New(
            isolate, zone, context,
3386
            isolate->factory()->LookupSingleCharacterStringFromCode(code));
3387
      }
3388 3389
      return HConstant::New(isolate, zone, context,
                            isolate->factory()->empty_string());
3390 3391 3392 3393 3394 3395
    }
  }
  return new(zone) HStringCharFromCode(context, char_code);
}


3396 3397 3398
HInstruction* HUnaryMathOperation::New(Isolate* isolate, Zone* zone,
                                       HValue* context, HValue* value,
                                       BuiltinFunctionId op) {
3399 3400 3401 3402 3403 3404
  do {
    if (!FLAG_fold_constants) break;
    if (!value->IsConstant()) break;
    HConstant* constant = HConstant::cast(value);
    if (!constant->HasNumberValue()) break;
    double d = constant->DoubleValue();
3405
    if (std::isnan(d)) {  // NaN poisons everything.
3406
      return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3407
    }
3408
    if (std::isinf(d)) {  // +Infinity and -Infinity.
3409
      switch (op) {
3410 3411 3412
        case kMathCos:
        case kMathSin:
          return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3413 3414 3415 3416
        case kMathExp:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
        case kMathLog:
        case kMathSqrt:
3417 3418
          return H_CONSTANT_DOUBLE(
              (d > 0.0) ? d : std::numeric_limits<double>::quiet_NaN());
3419 3420 3421 3422
        case kMathPowHalf:
        case kMathAbs:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
        case kMathRound:
3423
        case kMathFround:
3424 3425
        case kMathFloor:
          return H_CONSTANT_DOUBLE(d);
3426 3427
        case kMathClz32:
          return H_CONSTANT_INT(32);
3428 3429 3430 3431 3432 3433
        default:
          UNREACHABLE();
          break;
      }
    }
    switch (op) {
3434 3435
      case kMathCos:
        return H_CONSTANT_DOUBLE(base::ieee754::cos(d));
3436
      case kMathExp:
3437
        return H_CONSTANT_DOUBLE(base::ieee754::exp(d));
3438
      case kMathLog:
3439
        return H_CONSTANT_DOUBLE(base::ieee754::log(d));
3440 3441
      case kMathSin:
        return H_CONSTANT_DOUBLE(base::ieee754::sin(d));
3442
      case kMathSqrt:
3443 3444
        lazily_initialize_fast_sqrt(isolate);
        return H_CONSTANT_DOUBLE(fast_sqrt(d, isolate));
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
      case kMathPowHalf:
        return H_CONSTANT_DOUBLE(power_double_double(d, 0.5));
      case kMathAbs:
        return H_CONSTANT_DOUBLE((d >= 0.0) ? d + 0.0 : -d);
      case kMathRound:
        // -0.5 .. -0.0 round to -0.0.
        if ((d >= -0.5 && Double(d).Sign() < 0)) return H_CONSTANT_DOUBLE(-0.0);
        // Doubles are represented as Significant * 2 ^ Exponent. If the
        // Exponent is not negative, the double value is already an integer.
        if (Double(d).Exponent() >= 0) return H_CONSTANT_DOUBLE(d);
3455
        return H_CONSTANT_DOUBLE(Floor(d + 0.5));
3456 3457
      case kMathFround:
        return H_CONSTANT_DOUBLE(static_cast<double>(static_cast<float>(d)));
3458
      case kMathFloor:
3459
        return H_CONSTANT_DOUBLE(Floor(d));
3460
      case kMathClz32: {
3461
        uint32_t i = DoubleToUint32(d);
3462
        return H_CONSTANT_INT(base::bits::CountLeadingZeros32(i));
3463
      }
3464 3465 3466 3467 3468 3469 3470 3471 3472
      default:
        UNREACHABLE();
        break;
    }
  } while (false);
  return new(zone) HUnaryMathOperation(context, value, op);
}


3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
Representation HUnaryMathOperation::RepresentationFromUses() {
  if (op_ != kMathFloor && op_ != kMathRound) {
    return HValue::RepresentationFromUses();
  }

  // The instruction can have an int32 or double output. Prefer a double
  // representation if there are double uses.
  bool use_double = false;

  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
    int use_index = it.index();
    Representation rep_observed = use->observed_input_representation(use_index);
    Representation rep_required = use->RequiredInputRepresentation(use_index);
    use_double |= (rep_observed.IsDouble() || rep_required.IsDouble());
    if (use_double && !FLAG_trace_representation) {
      // Having seen one double is enough.
      break;
    }
    if (FLAG_trace_representation) {
      if (!rep_required.IsDouble() || rep_observed.IsDouble()) {
        PrintF("#%d %s is used by #%d %s as %s%s\n",
               id(), Mnemonic(), use->id(),
               use->Mnemonic(), rep_observed.Mnemonic(),
               (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
      } else {
        PrintF("#%d %s is required by #%d %s as %s%s\n",
               id(), Mnemonic(), use->id(),
               use->Mnemonic(), rep_required.Mnemonic(),
               (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
      }
    }
  }
  return use_double ? Representation::Double() : Representation::Integer32();
}


3510 3511
HInstruction* HPower::New(Isolate* isolate, Zone* zone, HValue* context,
                          HValue* left, HValue* right) {
3512 3513 3514 3515
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
3516 3517
      double result =
          power_helper(isolate, c_left->DoubleValue(), c_right->DoubleValue());
3518 3519 3520
      return H_CONSTANT_DOUBLE(std::isnan(result)
                                   ? std::numeric_limits<double>::quiet_NaN()
                                   : result);
3521 3522 3523 3524 3525 3526
    }
  }
  return new(zone) HPower(left, right);
}


3527 3528
HInstruction* HMathMinMax::New(Isolate* isolate, Zone* zone, HValue* context,
                               HValue* left, HValue* right, Operation op) {
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
      double d_left = c_left->DoubleValue();
      double d_right = c_right->DoubleValue();
      if (op == kMathMin) {
        if (d_left > d_right) return H_CONSTANT_DOUBLE(d_right);
        if (d_left < d_right) return H_CONSTANT_DOUBLE(d_left);
        if (d_left == d_right) {
          // Handle +0 and -0.
          return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_left
                                                                 : d_right);
        }
      } else {
        if (d_left < d_right) return H_CONSTANT_DOUBLE(d_right);
        if (d_left > d_right) return H_CONSTANT_DOUBLE(d_left);
        if (d_left == d_right) {
          // Handle +0 and -0.
          return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_right
                                                                 : d_left);
        }
      }
      // All comparisons failed, must be NaN.
3553
      return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3554 3555 3556 3557 3558
    }
  }
  return new(zone) HMathMinMax(context, left, right, op);
}

3559
HInstruction* HMod::New(Isolate* isolate, Zone* zone, HValue* context,
3560
                        HValue* left, HValue* right) {
3561
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3562 3563 3564 3565 3566
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if (c_left->HasInteger32Value() && c_right->HasInteger32Value()) {
      int32_t dividend = c_left->Integer32Value();
      int32_t divisor = c_right->Integer32Value();
3567 3568 3569
      if (dividend == kMinInt && divisor == -1) {
        return H_CONSTANT_DOUBLE(-0.0);
      }
3570 3571 3572 3573 3574
      if (divisor != 0) {
        int32_t res = dividend % divisor;
        if ((res == 0) && (dividend < 0)) {
          return H_CONSTANT_DOUBLE(-0.0);
        }
3575
        return H_CONSTANT_INT(res);
3576 3577 3578
      }
    }
  }
3579
  return new (zone) HMod(context, left, right);
3580 3581
}

3582
HInstruction* HDiv::New(Isolate* isolate, Zone* zone, HValue* context,
3583
                        HValue* left, HValue* right) {
3584
  // If left and right are constant values, try to return a constant value.
3585
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3586 3587 3588
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
3589 3590 3591 3592
      if (std::isnan(c_left->DoubleValue()) ||
          std::isnan(c_right->DoubleValue())) {
        return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
      } else if (c_right->DoubleValue() != 0) {
3593
        double double_res = c_left->DoubleValue() / c_right->DoubleValue();
3594
        if (IsInt32Double(double_res)) {
3595
          return H_CONSTANT_INT(double_res);
3596 3597
        }
        return H_CONSTANT_DOUBLE(double_res);
3598
      } else if (c_left->DoubleValue() != 0) {
3599 3600
        int sign = Double(c_left->DoubleValue()).Sign() *
                   Double(c_right->DoubleValue()).Sign();  // Right could be -0.
3601
        return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
3602 3603
      } else {
        return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3604 3605 3606
      }
    }
  }
3607
  return new (zone) HDiv(context, left, right);
3608 3609
}

3610
HInstruction* HBitwise::New(Isolate* isolate, Zone* zone, HValue* context,
3611
                            Token::Value op, HValue* left, HValue* right) {
3612
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
      int32_t result;
      int32_t v_left = c_left->NumberValueAsInteger32();
      int32_t v_right = c_right->NumberValueAsInteger32();
      switch (op) {
        case Token::BIT_XOR:
          result = v_left ^ v_right;
          break;
        case Token::BIT_AND:
          result = v_left & v_right;
          break;
        case Token::BIT_OR:
          result = v_left | v_right;
          break;
        default:
          result = 0;  // Please the compiler.
          UNREACHABLE();
      }
3633
      return H_CONSTANT_INT(result);
3634 3635
    }
  }
3636
  return new (zone) HBitwise(context, op, left, right);
3637 3638
}

3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
#define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result)                          \
  HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context,  \
                            HValue* left, HValue* right) {                  \
    if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
      HConstant* c_left = HConstant::cast(left);                            \
      HConstant* c_right = HConstant::cast(right);                          \
      if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {        \
        return H_CONSTANT_INT(result);                                      \
      }                                                                     \
    }                                                                       \
    return new (zone) HInstr(context, left, right);                         \
3650
  }
3651 3652 3653 3654 3655 3656 3657 3658

DEFINE_NEW_H_BITWISE_INSTR(HSar,
c_left->NumberValueAsInteger32() >> (c_right->NumberValueAsInteger32() & 0x1f))
DEFINE_NEW_H_BITWISE_INSTR(HShl,
c_left->NumberValueAsInteger32() << (c_right->NumberValueAsInteger32() & 0x1f))

#undef DEFINE_NEW_H_BITWISE_INSTR

3659
HInstruction* HShr::New(Isolate* isolate, Zone* zone, HValue* context,
3660
                        HValue* left, HValue* right) {
3661
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3662 3663 3664 3665 3666 3667
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
      int32_t left_val = c_left->NumberValueAsInteger32();
      int32_t right_val = c_right->NumberValueAsInteger32() & 0x1f;
      if ((right_val == 0) && (left_val < 0)) {
3668
        return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
3669
      }
3670
      return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
3671 3672
    }
  }
3673
  return new (zone) HShr(context, left, right);
3674 3675 3676
}


3677 3678 3679
HInstruction* HSeqStringGetChar::New(Isolate* isolate, Zone* zone,
                                     HValue* context, String::Encoding encoding,
                                     HValue* string, HValue* index) {
3680 3681 3682 3683 3684 3685
  if (FLAG_fold_constants && string->IsConstant() && index->IsConstant()) {
    HConstant* c_string = HConstant::cast(string);
    HConstant* c_index = HConstant::cast(index);
    if (c_string->HasStringValue() && c_index->HasInteger32Value()) {
      Handle<String> s = c_string->StringValue();
      int32_t i = c_index->Integer32Value();
3686 3687
      DCHECK_LE(0, i);
      DCHECK_LT(i, s->length());
3688 3689 3690 3691 3692 3693 3694
      return H_CONSTANT_INT(s->Get(i));
    }
  }
  return new(zone) HSeqStringGetChar(encoding, string, index);
}


3695
#undef H_CONSTANT_INT
3696 3697 3698
#undef H_CONSTANT_DOUBLE


3699
std::ostream& HBitwise::PrintDataTo(std::ostream& os) const {  // NOLINT
3700 3701
  os << Token::Name(op_) << " ";
  return HBitwiseBinaryOperation::PrintDataTo(os);
3702 3703 3704
}


3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
void HPhi::SimplifyConstantInputs() {
  // Convert constant inputs to integers when all uses are truncating.
  // This must happen before representation inference takes place.
  if (!CheckUsesForFlag(kTruncatingToInt32)) return;
  for (int i = 0; i < OperandCount(); ++i) {
    if (!OperandAt(i)->IsConstant()) return;
  }
  HGraph* graph = block()->graph();
  for (int i = 0; i < OperandCount(); ++i) {
    HConstant* operand = HConstant::cast(OperandAt(i));
    if (operand->HasInteger32Value()) {
      continue;
    } else if (operand->HasDoubleValue()) {
3718 3719 3720
      HConstant* integer_input = HConstant::New(
          graph->isolate(), graph->zone(), graph->GetInvalidContext(),
          DoubleToInt32(operand->DoubleValue()));
3721 3722
      integer_input->InsertAfter(operand);
      SetOperandAt(i, integer_input);
3723 3724 3725 3726
    } else if (operand->HasBooleanValue()) {
      SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
                                              : graph->GetConstant0());
    } else if (operand->ImmortalImmovable()) {
3727 3728 3729 3730 3731 3732 3733 3734
      SetOperandAt(i, graph->GetConstant0());
    }
  }
  // Overwrite observed input representations because they are likely Tagged.
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
    if (use->IsBinaryOperation()) {
      HBinaryOperation::cast(use)->set_observed_input_representation(
3735
          it.index(), Representation::Smi());
3736 3737 3738 3739 3740
    }
  }
}


3741
void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
3742
  DCHECK(CheckFlag(kFlexibleRepresentation));
3743
  Representation new_rep = RepresentationFromUses();
3744
  UpdateRepresentation(new_rep, h_infer, "uses");
3745 3746
  new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
3747 3748 3749 3750 3751 3752
  new_rep = RepresentationFromUseRequirements();
  UpdateRepresentation(new_rep, h_infer, "use requirements");
}


Representation HPhi::RepresentationFromInputs() {
3753
  Representation r = representation();
3754
  for (int i = 0; i < OperandCount(); ++i) {
3755 3756
    // Ignore conservative Tagged assumption of parameters if we have
    // reason to believe that it's too conservative.
3757 3758 3759
    if (has_type_feedback_from_uses() && OperandAt(i)->IsParameter()) {
      continue;
    }
3760

3761
    r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
3762
  }
3763
  return r;
3764 3765 3766
}


3767 3768 3769 3770
// Returns a representation if all uses agree on the same representation.
// Integer32 is also returned when some uses are Smi but others are Integer32.
Representation HValue::RepresentationFromUseRequirements() {
  Representation rep = Representation::None();
3771
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3772
    // Ignore the use requirement from never run code
3773
    if (it.value()->block()->IsUnreachable()) continue;
3774

3775 3776 3777
    // We check for observed_input_representation elsewhere.
    Representation use_rep =
        it.value()->RequiredInputRepresentation(it.index());
3778 3779
    if (rep.IsNone()) {
      rep = use_rep;
3780 3781
      continue;
    }
3782 3783 3784
    if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
    if (rep.generalize(use_rep).IsInteger32()) {
      rep = Representation::Integer32();
3785 3786
      continue;
    }
3787
    return Representation::None();
3788
  }
3789
  return rep;
3790 3791 3792
}


3793 3794 3795 3796 3797
bool HValue::HasNonSmiUse() {
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    // We check for observed_input_representation elsewhere.
    Representation use_rep =
        it.value()->RequiredInputRepresentation(it.index());
3798 3799 3800 3801 3802
    if (!use_rep.IsNone() &&
        !use_rep.IsSmi() &&
        !use_rep.IsTagged()) {
      return true;
    }
3803 3804 3805 3806 3807
  }
  return false;
}


3808 3809 3810
// Node-specific verification code is only included in debug mode.
#ifdef DEBUG

3811
void HPhi::Verify() {
3812
  DCHECK(OperandCount() == block()->predecessors()->length());
3813 3814 3815 3816
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* value = OperandAt(i);
    HBasicBlock* defining_block = value->block();
    HBasicBlock* predecessor_block = block()->predecessors()->at(i);
3817
    DCHECK(defining_block == predecessor_block ||
3818 3819 3820 3821 3822
           defining_block->Dominates(predecessor_block));
  }
}


3823
void HSimulate::Verify() {
3824
  HInstruction::Verify();
3825
  DCHECK(HasAstId() || next()->IsEnterInlined());
3826 3827 3828
}


3829
void HCheckHeapObject::Verify() {
3830
  HInstruction::Verify();
3831
  DCHECK(HasNoUses());
3832 3833 3834
}


3835
void HCheckValue::Verify() {
3836
  HInstruction::Verify();
3837
  DCHECK(HasNoUses());
3838 3839 3840 3841
}

#endif

3842 3843

HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
3844 3845
  DCHECK(offset >= 0);
  DCHECK(offset < FixedArray::kHeaderSize);
3846 3847 3848 3849 3850
  if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
  return HObjectAccess(kInobject, offset);
}


3851
HObjectAccess HObjectAccess::ForMapAndOffset(Handle<Map> map, int offset,
3852
    Representation representation) {
3853
  DCHECK(offset >= 0);
3854 3855 3856 3857 3858 3859 3860
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
3861 3862 3863 3864 3865 3866 3867
  bool existing_inobject_property = true;
  if (!map.is_null()) {
    existing_inobject_property = (offset <
        map->instance_size() - map->unused_property_fields() * kPointerSize);
  }
  return HObjectAccess(portion, offset, representation, Handle<String>::null(),
                       false, existing_inobject_property);
3868 3869 3870
}


3871 3872 3873 3874 3875 3876
HObjectAccess HObjectAccess::ForAllocationSiteOffset(int offset) {
  switch (offset) {
    case AllocationSite::kTransitionInfoOffset:
      return HObjectAccess(kInobject, offset, Representation::Tagged());
    case AllocationSite::kNestedSiteOffset:
      return HObjectAccess(kInobject, offset, Representation::Tagged());
3877
    case AllocationSite::kPretenureDataOffset:
3878
      return HObjectAccess(kInobject, offset, Representation::Smi());
3879
    case AllocationSite::kPretenureCreateCountOffset:
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
      return HObjectAccess(kInobject, offset, Representation::Smi());
    case AllocationSite::kDependentCodeOffset:
      return HObjectAccess(kInobject, offset, Representation::Tagged());
    case AllocationSite::kWeakNextOffset:
      return HObjectAccess(kInobject, offset, Representation::Tagged());
    default:
      UNREACHABLE();
  }
  return HObjectAccess(kInobject, offset);
}


3892
HObjectAccess HObjectAccess::ForContextSlot(int index) {
3893
  DCHECK(index >= 0);
3894 3895
  Portion portion = kInobject;
  int offset = Context::kHeaderSize + index * kPointerSize;
3896
  DCHECK_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
3897 3898 3899 3900
  return HObjectAccess(portion, offset, Representation::Tagged());
}


3901
HObjectAccess HObjectAccess::ForScriptContext(int index) {
3902 3903
  DCHECK(index >= 0);
  Portion portion = kInobject;
3904
  int offset = ScriptContextTable::GetContextOffset(index);
3905 3906 3907 3908
  return HObjectAccess(portion, offset, Representation::Tagged());
}


3909
HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
3910
  DCHECK(offset >= 0);
3911 3912 3913 3914 3915 3916 3917 3918 3919
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSArray::kLengthOffset) {
    portion = kArrayLengths;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
3920
  return HObjectAccess(portion, offset);
3921 3922 3923
}


3924 3925
HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
    Representation representation) {
3926
  DCHECK(offset >= 0);
3927 3928
  return HObjectAccess(kBackingStore, offset, representation,
                       Handle<String>::null(), false, false);
3929 3930 3931
}


3932 3933
HObjectAccess HObjectAccess::ForField(Handle<Map> map, int index,
                                      Representation representation,
3934
                                      Handle<Name> name) {
3935 3936 3937 3938
  if (index < 0) {
    // Negative property indices are in-object properties, indexed
    // from the end of the fixed part of the object.
    int offset = (index * kPointerSize) + map->instance_size();
3939
    return HObjectAccess(kInobject, offset, representation, name, false, true);
3940 3941 3942
  } else {
    // Non-negative property indices are in the properties array.
    int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
3943 3944
    return HObjectAccess(kBackingStore, offset, representation, name,
                         false, false);
3945 3946 3947 3948
  }
}


3949
void HObjectAccess::SetGVNFlags(HValue *instr, PropertyAccessType access_type) {
3950
  // set the appropriate GVN flags for a given load or store instruction
3951
  if (access_type == STORE) {
3952
    // track dominating allocations in order to eliminate write barriers
3953
    instr->SetDependsOnFlag(::v8::internal::kNewSpacePromotion);
3954 3955 3956 3957
    instr->SetFlag(HValue::kTrackSideEffectDominators);
  } else {
    // try to GVN loads, but don't hoist above map changes
    instr->SetFlag(HValue::kUseGVN);
3958
    instr->SetDependsOnFlag(::v8::internal::kMaps);
3959 3960 3961 3962
  }

  switch (portion()) {
    case kArrayLengths:
3963 3964 3965 3966 3967
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kArrayLengths);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kArrayLengths);
      }
3968
      break;
3969
    case kStringLengths:
3970 3971 3972 3973 3974
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kStringLengths);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kStringLengths);
      }
3975
      break;
3976
    case kInobject:
3977 3978 3979 3980 3981
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kInobjectFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kInobjectFields);
      }
3982 3983
      break;
    case kDouble:
3984 3985 3986 3987 3988
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kDoubleFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kDoubleFields);
      }
3989 3990
      break;
    case kBackingStore:
3991 3992 3993 3994 3995
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kBackingStoreFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kBackingStoreFields);
      }
3996 3997
      break;
    case kElementsPointer:
3998 3999 4000 4001 4002
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kElementsPointer);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kElementsPointer);
      }
4003 4004
      break;
    case kMaps:
4005 4006 4007 4008 4009
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kMaps);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kMaps);
      }
4010
      break;
4011
    case kExternalMemory:
4012 4013 4014 4015 4016
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kExternalMemory);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kExternalMemory);
      }
4017
      break;
4018 4019 4020 4021
  }
}


4022
std::ostream& operator<<(std::ostream& os, const HObjectAccess& access) {
4023
  os << ".";
4024

4025 4026 4027 4028
  switch (access.portion()) {
    case HObjectAccess::kArrayLengths:
    case HObjectAccess::kStringLengths:
      os << "%length";
4029
      break;
4030 4031
    case HObjectAccess::kElementsPointer:
      os << "%elements";
4032
      break;
4033 4034
    case HObjectAccess::kMaps:
      os << "%map";
4035
      break;
4036 4037
    case HObjectAccess::kDouble:  // fall through
    case HObjectAccess::kInobject:
4038
      if (!access.name().is_null() && access.name()->IsString()) {
4039
        os << Handle<String>::cast(access.name())->ToCString().get();
4040
      }
4041
      os << "[in-object]";
4042
      break;
4043
    case HObjectAccess::kBackingStore:
4044
      if (!access.name().is_null() && access.name()->IsString()) {
4045
        os << Handle<String>::cast(access.name())->ToCString().get();
4046
      }
4047
      os << "[backing-store]";
4048
      break;
4049 4050
    case HObjectAccess::kExternalMemory:
      os << "[external-memory]";
4051
      break;
4052 4053
  }

4054
  return os << "@" << access.offset();
4055 4056
}

4057 4058
}  // namespace internal
}  // namespace v8