hydrogen-instructions.cc 147 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 9
#include "src/base/safe_math.h"
#include "src/crankshaft/hydrogen-infer-representation.h"
10
#include "src/double.h"
11
#include "src/elements.h"
12
#include "src/factory.h"
13 14

#if V8_TARGET_ARCH_IA32
15
#include "src/crankshaft/ia32/lithium-ia32.h"  // NOLINT
16
#elif V8_TARGET_ARCH_X64
17
#include "src/crankshaft/x64/lithium-x64.h"  // NOLINT
18
#elif V8_TARGET_ARCH_ARM64
19
#include "src/crankshaft/arm64/lithium-arm64.h"  // NOLINT
20
#elif V8_TARGET_ARCH_ARM
21
#include "src/crankshaft/arm/lithium-arm.h"  // NOLINT
22
#elif V8_TARGET_ARCH_PPC
23
#include "src/crankshaft/ppc/lithium-ppc.h"  // NOLINT
24
#elif V8_TARGET_ARCH_MIPS
25
#include "src/crankshaft/mips/lithium-mips.h"  // NOLINT
26
#elif V8_TARGET_ARCH_MIPS64
27
#include "src/crankshaft/mips64/lithium-mips64.h"  // NOLINT
danno@chromium.org's avatar
danno@chromium.org committed
28
#elif V8_TARGET_ARCH_X87
29
#include "src/crankshaft/x87/lithium-x87.h"  // NOLINT
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#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


45
Isolate* HValue::isolate() const {
46
  DCHECK(block() != NULL);
47
  return block()->isolate();
48 49 50
}


51 52 53 54 55 56 57 58 59 60
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);
  }
}


61
void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
62
  DCHECK(CheckFlag(kFlexibleRepresentation));
63 64 65 66
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  new_rep = RepresentationFromUses();
  UpdateRepresentation(new_rep, h_infer, "uses");
67 68 69
  if (representation().IsSmi() && HasNonSmiUse()) {
    UpdateRepresentation(
        Representation::Integer32(), h_infer, "use requirements");
70
  }
71 72 73 74 75
}


Representation HValue::RepresentationFromUses() {
  if (HasNoUses()) return Representation::None();
76
  Representation result = Representation::None();
77 78 79 80

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

83 84 85 86 87 88
    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" : ""));
    }
  }
89 90 91 92
  if (IsPhi()) {
    result = result.generalize(
        HPhi::cast(this)->representation_from_indirect_uses());
  }
93

94 95
  // External representations are dealt with separately.
  return result.IsExternal() ? Representation::None() : result;
96 97 98 99
}


void HValue::UpdateRepresentation(Representation new_rep,
100
                                  HInferRepresentationPhase* h_infer,
101 102 103
                                  const char* reason) {
  Representation r = representation();
  if (new_rep.is_more_general_than(r)) {
104
    if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
105 106 107
    if (FLAG_trace_representation) {
      PrintF("Changing #%d %s representation %s -> %s based on %s\n",
             id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
108 109 110 111 112 113 114
    }
    ChangeRepresentation(new_rep);
    AddDependantsToWorklist(h_infer);
  }
}


115
void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
116 117 118 119 120 121 122 123 124
  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));
  }
}


125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
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;
    }
146
  }
147
  return static_cast<int32_t>(result);
148 149 150
}


151 152 153 154
static int32_t AddWithoutOverflow(Representation r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
155
  int64_t result = static_cast<int64_t>(a) + static_cast<int64_t>(b);
156
  return ConvertAndSetOverflow(r, result, overflow);
157 158 159
}


160 161 162 163
static int32_t SubWithoutOverflow(Representation r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
164
  int64_t result = static_cast<int64_t>(a) - static_cast<int64_t>(b);
165
  return ConvertAndSetOverflow(r, result, overflow);
166
}
167 168


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


178 179 180 181 182 183 184 185 186 187
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;
188 189 190
}


191
void Range::AddConstant(int32_t value) {
192
  if (value == 0) return;
193
  bool may_overflow = false;  // Overflow is ignored here.
194 195 196
  Representation r = Representation::Integer32();
  lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
197
#ifdef DEBUG
198
  Verify();
199
#endif
200 201 202
}


203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
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);
}


219 220 221 222 223 224 225 226 227 228 229 230 231 232
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());
}


233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
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);
}


255
bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
256
  bool may_overflow = false;
257 258
  lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
259
  KeepOrder();
260
#ifdef DEBUG
261
  Verify();
262
#endif
263
  return may_overflow;
264 265 266
}


267
bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
268
  bool may_overflow = false;
269 270
  lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
  upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
271
  KeepOrder();
272
#ifdef DEBUG
273
  Verify();
274
#endif
275
  return may_overflow;
276 277 278 279 280 281 282 283 284 285 286 287
}


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


288
#ifdef DEBUG
289
void Range::Verify() const {
290
  DCHECK(lower_ <= upper_);
291
}
292
#endif
293 294


295
bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
296
  bool may_overflow = false;
297 298 299 300
  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);
301 302
  lower_ = Min(Min(v1, v2), Min(v3, v4));
  upper_ = Max(Max(v1, v2), Max(v3, v4));
303
#ifdef DEBUG
304
  Verify();
305
#endif
306 307 308 309
  return may_overflow;
}


310 311 312 313 314
bool HValue::IsDefinedAfter(HBasicBlock* other) const {
  return block()->block_id() > other->block_id();
}


315 316 317 318 319 320 321 322 323
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_;
}


324
bool HValue::CheckUsesForFlag(Flag f) const {
325
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
326
    if (it.value()->IsSimulate()) continue;
327 328 329
    if (!it.value()->CheckFlag(f)) return false;
  }
  return true;
330 331 332 333 334 335 336 337 338 339 340 341
}


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;
342 343 344
}


345
bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
346 347 348 349 350 351 352 353 354 355
  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;
}


356 357 358 359 360 361 362 363 364 365 366
HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
  Advance();
}


void HUseIterator::Advance() {
  current_ = next_;
  if (current_ != NULL) {
    next_ = current_->tail();
    value_ = current_->value();
    index_ = current_->index();
367 368 369 370
  }
}


371 372 373 374
int HValue::UseCount() const {
  int count = 0;
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
  return count;
375 376 377
}


378 379 380 381 382 383 384 385 386 387 388
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;
389
    }
390 391 392

    previous = current;
    current = current->tail();
393
  }
394 395 396 397 398

#ifdef DEBUG
  // Do not reuse use list nodes in debug mode, zap them.
  if (current != NULL) {
    HUseListNode* temp =
399 400
        new(block()->zone())
        HUseListNode(current->value(), current->index(), NULL);
401 402 403 404 405
    current->Zap();
    current = temp;
  }
#endif
  return current;
406 407 408
}


409
bool HValue::Equals(HValue* other) {
410 411 412
  if (other->opcode() != opcode()) return false;
  if (!other->representation().Equals(representation())) return false;
  if (!other->type_.Equals(type_)) return false;
413
  if (other->flags() != flags()) return false;
414 415 416 417 418
  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);
419
  DCHECK(!result || Hashcode() == other->Hashcode());
420 421 422 423
  return result;
}


424
intptr_t HValue::Hashcode() {
425 426 427 428 429 430 431 432 433
  intptr_t result = opcode();
  int count = OperandCount();
  for (int i = 0; i < count; ++i) {
    result = result * 19 + OperandAt(i)->id() + (result >> 7);
  }
  return result;
}


434 435 436 437 438 439 440 441 442 443 444
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 "";
  }
}


445 446 447 448 449
bool HValue::CanReplaceWithDummyUses() {
  return FLAG_unreachable_code_elimination &&
      !(block()->IsReachable() ||
        IsBlockEntry() ||
        IsControlInstruction() ||
450
        IsArgumentsObject() ||
451
        IsCapturedObject() ||
452 453 454 455 456 457
        IsSimulate() ||
        IsEnterInlined() ||
        IsLeaveInlined());
}


458
bool HValue::IsInteger32Constant() {
459
  return IsConstant() && HConstant::cast(this)->HasInteger32Value();
460 461 462 463
}


int32_t HValue::GetInteger32Constant() {
464
  return HConstant::cast(this)->Integer32Value();
465 466 467
}


468 469 470 471 472
bool HValue::EqualsInteger32Constant(int32_t value) {
  return IsInteger32Constant() && GetInteger32Constant() == value;
}


473 474 475 476 477 478
void HValue::SetOperandAt(int index, HValue* value) {
  RegisterUse(index, value);
  InternalSetOperandAt(index, value);
}


479 480 481
void HValue::DeleteAndReplaceWith(HValue* other) {
  // We replace all uses first, so Delete can assert that there are none.
  if (other != NULL) ReplaceAllUsesWith(other);
482
  Kill();
483 484 485 486
  DeleteFromGraph();
}


487 488 489 490
void HValue::ReplaceAllUsesWith(HValue* other) {
  while (use_list_ != NULL) {
    HUseListNode* list_node = use_list_;
    HValue* value = list_node->value();
491
    DCHECK(!value->block()->IsStartBlock());
492 493 494 495
    value->InternalSetOperandAt(list_node->index(), other);
    use_list_ = list_node->tail();
    list_node->set_tail(other->use_list_);
    other->use_list_ = list_node;
496 497 498 499
  }
}


500 501 502 503 504
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);
505
  for (int i = 0; i < OperandCount(); ++i) {
506
    HValue* operand = OperandAt(i);
507
    if (operand == NULL) continue;
508
    HUseListNode* first = operand->use_list_;
509
    if (first != NULL && first->value()->CheckFlag(kIsDead)) {
510 511
      operand->use_list_ = first->tail();
    }
512 513 514 515 516
  }
}


void HValue::SetBlock(HBasicBlock* block) {
517
  DCHECK(block_ == NULL || block == NULL);
518 519 520 521 522 523 524
  block_ = block;
  if (id_ == kNoNumber && block != NULL) {
    id_ = block->graph()->GetNextValueID(this);
  }
}


525 526 527
std::ostream& operator<<(std::ostream& os, const HValue& v) {
  return v.PrintTo(os);
}
528 529


530
std::ostream& operator<<(std::ostream& os, const TypeOf& t) {
531 532 533 534
  if (t.value->representation().IsTagged() &&
      !t.value->type().Equals(HType::Tagged()))
    return os;
  return os << " type:" << t.value->type();
535 536 537
}


538
std::ostream& operator<<(std::ostream& os, const ChangesOf& c) {
539 540 541 542 543
  GVNFlagSet changes_flags = c.value->ChangesFlags();
  if (changes_flags.IsEmpty()) return os;
  os << " changes[";
  if (changes_flags == c.value->AllSideEffectsFlagSet()) {
    os << "*";
544 545
  } else {
    bool add_comma = false;
546 547 548 549 550 551
#define PRINT_DO(Type)                   \
  if (changes_flags.Contains(k##Type)) { \
    if (add_comma) os << ",";            \
    add_comma = true;                    \
    os << #Type;                         \
  }
552 553
    GVN_TRACKED_FLAG_LIST(PRINT_DO);
    GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
554 555
#undef PRINT_DO
  }
556
  return os << "]";
557 558 559
}


560 561 562 563 564
bool HValue::HasMonomorphicJSObjectType() {
  return !GetMonomorphicJSObjectMap().is_null();
}


565 566 567 568 569 570 571 572 573 574 575
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;
576 577 578 579 580 581

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

582
  if (new_value != NULL) {
583
    if (removed == NULL) {
584 585
      new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
          this, index, new_value->use_list_);
586 587 588 589
    } else {
      removed->set_tail(new_value->use_list_);
      new_value->use_list_ = removed;
    }
590 591 592 593
  }
}


594 595 596
void HValue::AddNewRange(Range* r, Zone* zone) {
  if (!HasRange()) ComputeInitialRange(zone);
  if (!HasRange()) range_ = new(zone) Range();
597
  DCHECK(HasRange());
598 599 600 601 602 603
  r->StackUpon(range_);
  range_ = r;
}


void HValue::RemoveLastAddedRange() {
604 605
  DCHECK(HasRange());
  DCHECK(range_->next() != NULL);
606 607 608 609
  range_ = range_->next();
}


610
void HValue::ComputeInitialRange(Zone* zone) {
611
  DCHECK(!HasRange());
612
  range_ = InferRange(zone);
613
  DCHECK(HasRange());
614 615 616
}


617
std::ostream& HInstruction::PrintTo(std::ostream& os) const {  // NOLINT
618 619 620 621 622
  os << Mnemonic() << " ";
  PrintDataTo(os) << ChangesOf(this) << TypeOf(this);
  if (CheckFlag(HValue::kHasNoObservableSideEffects)) os << " [noOSE]";
  if (CheckFlag(HValue::kIsDead)) os << " [dead]";
  return os;
623
}
624 625


626
std::ostream& HInstruction::PrintDataTo(std::ostream& os) const {  // NOLINT
627
  for (int i = 0; i < OperandCount(); ++i) {
628 629
    if (i > 0) os << " ";
    os << NameOf(OperandAt(i));
630
  }
631
  return os;
632 633 634 635
}


void HInstruction::Unlink() {
636 637 638 639
  DCHECK(IsLinked());
  DCHECK(!IsControlInstruction());  // Must never move control instructions.
  DCHECK(!IsBlockEntry());  // Doesn't make sense to delete these.
  DCHECK(previous_ != NULL);
640 641
  previous_->next_ = next_;
  if (next_ == NULL) {
642
    DCHECK(block()->last() == this);
643 644 645 646
    block()->set_last(previous_);
  } else {
    next_->previous_ = previous_;
  }
647 648 649 650 651
  clear_block();
}


void HInstruction::InsertBefore(HInstruction* next) {
652 653 654 655 656
  DCHECK(!IsLinked());
  DCHECK(!next->IsBlockEntry());
  DCHECK(!IsControlInstruction());
  DCHECK(!next->block()->IsStartBlock());
  DCHECK(next->previous_ != NULL);
657 658 659 660 661 662
  HInstruction* prev = next->previous();
  prev->next_ = this;
  next->previous_ = this;
  next_ = next;
  previous_ = prev;
  SetBlock(next->block());
663
  if (!has_position() && next->has_position()) {
664 665
    set_position(next->position());
  }
666 667 668 669
}


void HInstruction::InsertAfter(HInstruction* previous) {
670 671 672
  DCHECK(!IsLinked());
  DCHECK(!previous->IsControlInstruction());
  DCHECK(!IsControlInstruction() || previous->next_ == NULL);
673 674 675 676
  HBasicBlock* block = previous->block();
  // Never insert anything except constants into the start block after finishing
  // it.
  if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
677
    DCHECK(block->end()->SecondSuccessor() == NULL);
678 679 680 681 682 683 684 685
    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_;
686
  if (previous->HasObservableSideEffects() && next != NULL) {
687
    DCHECK(next->IsSimulate());
688 689 690 691 692 693 694 695 696
    previous = next;
    next = previous->next_;
  }

  previous_ = previous;
  next_ = next;
  SetBlock(block);
  previous->next_ = this;
  if (next != NULL) next->previous_ = this;
697 698 699
  if (block->last() == previous) {
    block->set_last(this);
  }
700
  if (!has_position() && previous->has_position()) {
701 702
    set_position(previous->position());
  }
703 704 705
}


706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
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;
}


721
#ifdef DEBUG
722
void HInstruction::Verify() {
723 724 725 726
  // Verify that input operands are defined before use.
  HBasicBlock* cur_block = block();
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* other_operand = OperandAt(i);
727
    if (other_operand == NULL) continue;
728 729 730
    HBasicBlock* other_block = other_operand->block();
    if (cur_block == other_block) {
      if (!other_operand->IsPhi()) {
731
        HInstruction* cur = this->previous();
732 733
        while (cur != NULL) {
          if (cur == other_operand) break;
734
          cur = cur->previous();
735 736
        }
        // Must reach other operand in the same block!
737
        DCHECK(cur == other_operand);
738 739
      }
    } else {
740 741
      // If the following assert fires, you may have forgotten an
      // AddInstruction.
742
      DCHECK(other_block->Dominates(cur_block));
743 744 745 746 747
    }
  }

  // Verify that instructions that may have side-effects are followed
  // by a simulate instruction.
748
  if (HasObservableSideEffects() && !IsOsrEntry()) {
749
    DCHECK(next()->IsSimulate());
750
  }
751 752 753 754 755

  // 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);
756 757 758 759

  // Verify that all uses are in the graph.
  for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
    if (use.value()->IsInstruction()) {
760
      DCHECK(HInstruction::cast(use.value())->IsLinked());
761 762
    }
  }
763 764 765 766
}
#endif


767 768 769
bool HInstruction::CanDeoptimize() {
  // TODO(titzer): make this a virtual method?
  switch (opcode()) {
770
    case HValue::kAbnormalExit:
771
    case HValue::kAccessArgumentsAt:
772
    case HValue::kAllocate:
773 774 775
    case HValue::kArgumentsElements:
    case HValue::kArgumentsLength:
    case HValue::kArgumentsObject:
776
    case HValue::kBlockEntry:
777
    case HValue::kBoundsCheckBaseIndexInformation:
778 779 780 781
    case HValue::kCallFunction:
    case HValue::kCallNew:
    case HValue::kCallNewArray:
    case HValue::kCallStub:
782
    case HValue::kCapturedObject:
783 784 785 786 787 788 789
    case HValue::kClassOfTestAndBranch:
    case HValue::kCompareGeneric:
    case HValue::kCompareHoleAndBranch:
    case HValue::kCompareMap:
    case HValue::kCompareMinusZeroAndBranch:
    case HValue::kCompareNumericAndBranch:
    case HValue::kCompareObjectEqAndBranch:
790
    case HValue::kConstant:
791
    case HValue::kConstructDouble:
792 793 794
    case HValue::kContext:
    case HValue::kDebugBreak:
    case HValue::kDeclareGlobals:
795
    case HValue::kDoubleBits:
796 797 798
    case HValue::kDummyUse:
    case HValue::kEnterInlined:
    case HValue::kEnvironmentMarker:
799
    case HValue::kForceRepresentation:
800 801
    case HValue::kGetCachedArrayIndex:
    case HValue::kGoto:
802 803
    case HValue::kHasCachedArrayIndexAndBranch:
    case HValue::kHasInstanceTypeAndBranch:
804 805
    case HValue::kInnerAllocatedObject:
    case HValue::kInstanceOf:
806
    case HValue::kIsConstructCallAndBranch:
807
    case HValue::kHasInPrototypeChainAndBranch:
808 809 810
    case HValue::kIsSmiAndBranch:
    case HValue::kIsStringAndBranch:
    case HValue::kIsUndetectableAndBranch:
811 812 813 814 815 816 817 818 819
    case HValue::kLeaveInlined:
    case HValue::kLoadFieldByIndex:
    case HValue::kLoadGlobalGeneric:
    case HValue::kLoadNamedField:
    case HValue::kLoadNamedGeneric:
    case HValue::kLoadRoot:
    case HValue::kMapEnumLength:
    case HValue::kMathMinMax:
    case HValue::kParameter:
820
    case HValue::kPhi:
821
    case HValue::kPushArguments:
822 823
    case HValue::kRegExpLiteral:
    case HValue::kReturn:
824
    case HValue::kSeqStringGetChar:
825
    case HValue::kStoreCodeEntry:
826
    case HValue::kStoreFrameContext:
827
    case HValue::kStoreKeyed:
828
    case HValue::kStoreNamedField:
829 830 831 832 833 834 835 836 837 838
    case HValue::kStoreNamedGeneric:
    case HValue::kStringCharCodeAt:
    case HValue::kStringCharFromCode:
    case HValue::kThisFunction:
    case HValue::kTypeofIsAndBranch:
    case HValue::kUnknownOSRValue:
    case HValue::kUseConst:
      return false;

    case HValue::kAdd:
839
    case HValue::kAllocateBlockContext:
840 841 842 843
    case HValue::kApplyArguments:
    case HValue::kBitwise:
    case HValue::kBoundsCheck:
    case HValue::kBranch:
844
    case HValue::kCallJSFunction:
845
    case HValue::kCallRuntime:
846
    case HValue::kCallWithDescriptor:
847
    case HValue::kChange:
848
    case HValue::kCheckArrayBufferNotNeutered:
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    case HValue::kCheckHeapObject:
    case HValue::kCheckInstanceType:
    case HValue::kCheckMapValue:
    case HValue::kCheckMaps:
    case HValue::kCheckSmi:
    case HValue::kCheckValue:
    case HValue::kClampToUint8:
    case HValue::kDateField:
    case HValue::kDeoptimize:
    case HValue::kDiv:
    case HValue::kForInCacheArray:
    case HValue::kForInPrepareMap:
    case HValue::kInvokeFunction:
    case HValue::kLoadContextSlot:
    case HValue::kLoadFunctionPrototype:
    case HValue::kLoadKeyed:
    case HValue::kLoadKeyedGeneric:
    case HValue::kMathFloorOfDiv:
867
    case HValue::kMaybeGrowElements:
868 869 870 871
    case HValue::kMod:
    case HValue::kMul:
    case HValue::kOsrEntry:
    case HValue::kPower:
872
    case HValue::kPrologue:
873 874
    case HValue::kRor:
    case HValue::kSar:
875 876 877 878 879 880 881 882
    case HValue::kSeqStringSetChar:
    case HValue::kShl:
    case HValue::kShr:
    case HValue::kSimulate:
    case HValue::kStackCheck:
    case HValue::kStoreContextSlot:
    case HValue::kStoreKeyedGeneric:
    case HValue::kStringAdd:
883
    case HValue::kStringCompareAndBranch:
884 885 886 887 888 889 890 891 892
    case HValue::kSub:
    case HValue::kToFastProperties:
    case HValue::kTransitionElementsKind:
    case HValue::kTrapAllocationMemento:
    case HValue::kTypeof:
    case HValue::kUnaryMathOperation:
    case HValue::kWrapReceiver:
      return true;
  }
893 894
  UNREACHABLE();
  return true;
895 896 897
}


898
std::ostream& operator<<(std::ostream& os, const NameOf& v) {
899 900 901
  return os << v.value->representation().Mnemonic() << v.value->id();
}

902
std::ostream& HDummyUse::PrintDataTo(std::ostream& os) const {  // NOLINT
903
  return os << NameOf(value());
904 905 906
}


907 908
std::ostream& HEnvironmentMarker::PrintDataTo(
    std::ostream& os) const {  // NOLINT
909 910
  return os << (kind() == BIND ? "bind" : "lookup") << " var[" << index()
            << "]";
911 912 913
}


914
std::ostream& HUnaryCall::PrintDataTo(std::ostream& os) const {  // NOLINT
915
  return os << NameOf(value()) << " #" << argument_count();
916 917 918
}


919
std::ostream& HCallJSFunction::PrintDataTo(std::ostream& os) const {  // NOLINT
920
  return os << NameOf(function()) << " #" << argument_count();
921 922 923
}


924 925
HCallJSFunction* HCallJSFunction::New(Isolate* isolate, Zone* zone,
                                      HValue* context, HValue* function,
926
                                      int argument_count) {
927 928 929 930
  bool has_stack_check = false;
  if (function->IsConstant()) {
    HConstant* fun_const = HConstant::cast(function);
    Handle<JSFunction> jsfun =
931
        Handle<JSFunction>::cast(fun_const->handle(isolate));
932 933 934 935 936
    has_stack_check = !jsfun.is_null() &&
        (jsfun->code()->kind() == Code::FUNCTION ||
         jsfun->code()->kind() == Code::OPTIMIZED_FUNCTION);
  }

937
  return new (zone) HCallJSFunction(function, argument_count, has_stack_check);
938 939 940
}


941
std::ostream& HBinaryCall::PrintDataTo(std::ostream& os) const {  // NOLINT
942 943
  return os << NameOf(first()) << " " << NameOf(second()) << " #"
            << argument_count();
944 945 946
}


947 948 949 950 951 952 953 954 955
std::ostream& HCallFunction::PrintDataTo(std::ostream& os) const {  // NOLINT
  os << NameOf(context()) << " " << NameOf(function());
  if (HasVectorAndSlot()) {
    os << " (type-feedback-vector icslot " << slot().ToInt() << ")";
  }
  return os;
}


956 957 958 959 960 961
void HBoundsCheck::ApplyIndexChange() {
  if (skip_check()) return;

  DecompositionResult decomposition;
  bool index_is_decomposable = index()->TryDecompose(&decomposition);
  if (index_is_decomposable) {
962
    DCHECK(decomposition.base() == base());
963 964 965 966 967 968 969 970 971 972 973 974
    if (decomposition.offset() == offset() &&
        decomposition.scale() == scale()) return;
  } else {
    return;
  }

  ReplaceAllUsesWith(index());

  HValue* current_index = decomposition.base();
  int actual_offset = decomposition.offset() + offset();
  int actual_scale = decomposition.scale() + scale();

975 976 977 978
  HGraph* graph = block()->graph();
  Isolate* isolate = graph->isolate();
  Zone* zone = graph->zone();
  HValue* context = graph->GetInvalidContext();
979
  if (actual_offset != 0) {
980 981
    HConstant* add_offset =
        HConstant::New(isolate, zone, context, actual_offset);
982
    add_offset->InsertBefore(this);
983 984
    HInstruction* add =
        HAdd::New(isolate, zone, context, current_index, add_offset);
985 986
    add->InsertBefore(this);
    add->AssumeRepresentation(index()->representation());
987
    add->ClearFlag(kCanOverflow);
988 989 990 991
    current_index = add;
  }

  if (actual_scale != 0) {
992
    HConstant* sar_scale = HConstant::New(isolate, zone, context, actual_scale);
993
    sar_scale->InsertBefore(this);
994 995
    HInstruction* sar =
        HSar::New(isolate, zone, context, current_index, sar_scale);
996 997 998 999 1000 1001 1002 1003 1004 1005
    sar->InsertBefore(this);
    sar->AssumeRepresentation(index()->representation());
    current_index = sar;
  }

  SetOperandAt(0, current_index);

  base_ = NULL;
  offset_ = 0;
  scale_ = 0;
1006 1007 1008
}


1009
std::ostream& HBoundsCheck::PrintDataTo(std::ostream& os) const {  // NOLINT
1010
  os << NameOf(index()) << " " << NameOf(length());
1011
  if (base() != NULL && (offset() != 0 || scale() != 0)) {
1012
    os << " base: ((";
1013
    if (base() != index()) {
1014
      os << NameOf(index());
1015
    } else {
1016
      os << "index";
1017
    }
1018
    os << " + " << offset() << ") >> " << scale() << ")";
1019
  }
1020 1021
  if (skip_check()) os << " [DISABLED]";
  return os;
1022 1023
}

1024

1025
void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
1026
  DCHECK(CheckFlag(kFlexibleRepresentation));
1027
  HValue* actual_index = index()->ActualValue();
1028 1029
  HValue* actual_length = length()->ActualValue();
  Representation index_rep = actual_index->representation();
1030
  Representation length_rep = actual_length->representation();
1031 1032 1033 1034 1035 1036
  if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
    index_rep = Representation::Smi();
  }
  if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
    length_rep = Representation::Smi();
  }
1037 1038
  Representation r = index_rep.generalize(length_rep);
  if (r.is_more_general_than(Representation::Integer32())) {
1039 1040 1041 1042 1043 1044
    r = Representation::Integer32();
  }
  UpdateRepresentation(r, h_infer, "boundscheck");
}


1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
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);
}


1064 1065
std::ostream& HBoundsCheckBaseIndexInformation::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1066 1067 1068
  // TODO(svenpanne) This 2nd base_index() looks wrong...
  return os << "base: " << NameOf(base_index())
            << ", check: " << NameOf(base_index());
1069 1070 1071
}


1072 1073
std::ostream& HCallWithDescriptor::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1074
  for (int i = 0; i < OperandCount(); i++) {
1075
    os << NameOf(OperandAt(i)) << " ";
1076
  }
1077
  return os << "#" << argument_count();
1078 1079 1080
}


1081
std::ostream& HCallNewArray::PrintDataTo(std::ostream& os) const {  // NOLINT
1082 1083
  os << ElementsKindToString(elements_kind()) << " ";
  return HBinaryCall::PrintDataTo(os);
1084 1085 1086
}


1087
std::ostream& HCallRuntime::PrintDataTo(std::ostream& os) const {  // NOLINT
1088
  os << function()->name << " ";
1089 1090
  if (save_doubles() == kSaveFPRegs) os << "[save doubles] ";
  return os << "#" << argument_count();
1091 1092 1093
}


1094 1095
std::ostream& HClassOfTestAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1096 1097
  return os << "class_of_test(" << NameOf(value()) << ", \""
            << class_name()->ToCString().get() << "\")";
1098 1099 1100
}


1101
std::ostream& HWrapReceiver::PrintDataTo(std::ostream& os) const {  // NOLINT
1102
  return os << NameOf(receiver()) << " " << NameOf(function());
1103 1104 1105
}


1106 1107
std::ostream& HAccessArgumentsAt::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1108 1109
  return os << NameOf(arguments()) << "[" << NameOf(index()) << "], length "
            << NameOf(length());
1110 1111 1112
}


1113 1114
std::ostream& HAllocateBlockContext::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1115
  return os << NameOf(context()) << " " << NameOf(function());
1116 1117 1118
}


1119 1120
std::ostream& HControlInstruction::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1121
  os << " goto (";
1122 1123
  bool first_block = true;
  for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
1124 1125
    if (!first_block) os << ", ";
    os << *it.Current();
1126
    first_block = false;
1127
  }
1128
  return os << ")";
1129 1130 1131
}


1132 1133
std::ostream& HUnaryControlInstruction::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1134 1135
  os << NameOf(value());
  return HControlInstruction::PrintDataTo(os);
1136 1137 1138
}


1139
std::ostream& HReturn::PrintDataTo(std::ostream& os) const {  // NOLINT
1140 1141
  return os << NameOf(value()) << " (pop " << NameOf(parameter_count())
            << " values)";
1142 1143 1144
}


1145
Representation HBranch::observed_input_representation(int index) {
1146 1147 1148
  if (expected_input_types_.Contains(ToBooleanStub::NULL_TYPE) ||
      expected_input_types_.Contains(ToBooleanStub::SPEC_OBJECT) ||
      expected_input_types_.Contains(ToBooleanStub::STRING) ||
1149 1150
      expected_input_types_.Contains(ToBooleanStub::SYMBOL) ||
      expected_input_types_.Contains(ToBooleanStub::SIMD_VALUE)) {
1151
    return Representation::Tagged();
1152 1153 1154 1155 1156 1157 1158 1159
  }
  if (expected_input_types_.Contains(ToBooleanStub::UNDEFINED)) {
    if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
      return Representation::Double();
    }
    return Representation::Tagged();
  }
  if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
1160
    return Representation::Double();
1161 1162
  }
  if (expected_input_types_.Contains(ToBooleanStub::SMI)) {
1163
    return Representation::Smi();
1164
  }
1165
  return Representation::None();
1166 1167 1168
}


1169 1170 1171
bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
  HValue* value = this->value();
  if (value->EmitAtUses()) {
1172 1173
    DCHECK(value->IsConstant());
    DCHECK(!value->representation().IsDouble());
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    *block = HConstant::cast(value)->BooleanValue()
        ? FirstSuccessor()
        : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


1184
std::ostream& HBranch::PrintDataTo(std::ostream& os) const {  // NOLINT
1185 1186
  return HUnaryControlInstruction::PrintDataTo(os) << " "
                                                   << expected_input_types();
1187 1188 1189
}


1190
std::ostream& HCompareMap::PrintDataTo(std::ostream& os) const {  // NOLINT
1191 1192
  os << NameOf(value()) << " (" << *map().handle() << ")";
  HControlInstruction::PrintDataTo(os);
1193
  if (known_successor_index() == 0) {
1194
    os << " [true]";
1195
  } else if (known_successor_index() == 1) {
1196
    os << " [false]";
1197
  }
1198
  return os;
1199 1200 1201 1202 1203
}


const char* HUnaryMathOperation::OpName() const {
  switch (op()) {
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    case kMathFloor:
      return "floor";
    case kMathFround:
      return "fround";
    case kMathRound:
      return "round";
    case kMathAbs:
      return "abs";
    case kMathLog:
      return "log";
    case kMathExp:
      return "exp";
    case kMathSqrt:
      return "sqrt";
    case kMathPowHalf:
      return "pow-half";
    case kMathClz32:
      return "clz32";
1222 1223 1224
    default:
      UNREACHABLE();
      return NULL;
1225 1226 1227 1228
  }
}


1229 1230
Range* HUnaryMathOperation::InferRange(Zone* zone) {
  Representation r = representation();
1231
  if (op() == kMathClz32) return new(zone) Range(0, 32);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
  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);
}


1254 1255
std::ostream& HUnaryMathOperation::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1256
  return os << OpName() << " " << NameOf(value());
1257 1258 1259
}


1260
std::ostream& HUnaryOperation::PrintDataTo(std::ostream& os) const {  // NOLINT
1261
  return os << NameOf(value());
1262 1263 1264
}


1265 1266
std::ostream& HHasInstanceTypeAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1267
  os << NameOf(value());
1268
  switch (from_) {
1269
    case FIRST_JS_RECEIVER_TYPE:
1270
      if (to_ == LAST_TYPE) os << " spec_object";
1271 1272
      break;
    case JS_REGEXP_TYPE:
1273
      if (to_ == JS_REGEXP_TYPE) os << " reg_exp";
1274 1275
      break;
    case JS_ARRAY_TYPE:
1276
      if (to_ == JS_ARRAY_TYPE) os << " array";
1277 1278
      break;
    case JS_FUNCTION_TYPE:
1279
      if (to_ == JS_FUNCTION_TYPE) os << " function";
1280 1281 1282 1283
      break;
    default:
      break;
  }
1284
  return os;
1285 1286 1287
}


1288 1289
std::ostream& HTypeofIsAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1290 1291
  os << NameOf(value()) << " == " << type_literal()->ToCString().get();
  return HControlInstruction::PrintDataTo(os);
1292 1293 1294
}


1295 1296 1297
namespace {

String* TypeOfString(HConstant* constant, Isolate* isolate) {
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
  Heap* heap = isolate->heap();
  if (constant->HasNumberValue()) return heap->number_string();
  if (constant->IsUndetectable()) return heap->undefined_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())) {
1310
        return heap->object_string();
1311
      }
1312
      DCHECK(unique.IsKnownGlobal(heap->undefined_value()));
1313
      return heap->undefined_string();
1314
    }
1315 1316
    case SYMBOL_TYPE:
      return heap->symbol_string();
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    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;
    }
1328
    default:
1329
      if (constant->IsCallable()) return heap->function_string();
1330 1331 1332 1333
      return heap->object_string();
  }
}

1334 1335
}  // namespace

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

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();
1348 1349 1350 1351 1352 1353 1354
    return true;
  }
  *block = NULL;
  return false;
}


1355
std::ostream& HCheckMapValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1356
  return os << NameOf(value()) << " " << NameOf(map());
1357 1358 1359
}


1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
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;
}


1371
std::ostream& HForInPrepareMap::PrintDataTo(std::ostream& os) const {  // NOLINT
1372
  return os << NameOf(enumerable());
1373 1374 1375
}


1376
std::ostream& HForInCacheArray::PrintDataTo(std::ostream& os) const {  // NOLINT
1377 1378
  return os << NameOf(enumerable()) << " " << NameOf(map()) << "[" << idx_
            << "]";
1379 1380 1381
}


1382 1383
std::ostream& HLoadFieldByIndex::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1384
  return os << NameOf(object()) << " " << NameOf(index());
1385 1386 1387
}


1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
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);
}


1411
HValue* HBitwise::Canonicalize() {
1412
  if (!representation().IsSmiOrInteger32()) return this;
1413 1414
  // 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;
1415
  if (left()->EqualsInteger32Constant(nop_constant) &&
1416
      !right()->CheckFlag(kUint32)) {
1417 1418
    return right();
  }
1419
  if (right()->EqualsInteger32Constant(nop_constant) &&
1420
      !left()->CheckFlag(kUint32)) {
1421 1422
    return left();
  }
1423 1424 1425 1426
  // Optimize double negation, a common pattern used for ToInt32(x).
  HValue* arg;
  if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
    return arg;
1427 1428 1429 1430 1431
  }
  return this;
}


1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
// static
HInstruction* HAdd::New(Isolate* isolate, Zone* zone, HValue* context,
                        HValue* left, HValue* right, Strength strength,
                        ExternalAddType external_add_type) {
  // For everything else, you should use the other factory method without
  // ExternalAddType.
  DCHECK_EQ(external_add_type, AddOfExternalAndTagged);
  return new (zone) HAdd(context, left, right, strength, external_add_type);
}


1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
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()) {
1456 1457 1458 1459 1460
      if (external_add_type_ == AddOfExternalAndTagged) {
        return Representation::Tagged();
      } else {
        return Representation::Integer32();
      }
1461 1462 1463 1464 1465 1466
    }
  }
  return HArithmeticBinaryOperation::RequiredInputRepresentation(index);
}


1467 1468
static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
  return arg1->representation().IsSpecialization() &&
1469
    arg2->EqualsInteger32Constant(identity);
1470 1471 1472
}


1473
HValue* HAdd::Canonicalize() {
1474 1475 1476 1477 1478 1479 1480 1481 1482
  // 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();
  }
1483
  return this;
1484 1485 1486 1487 1488
}


HValue* HSub::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 0)) return left();
1489
  return this;
1490 1491 1492
}


1493 1494 1495
HValue* HMul::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 1)) return left();
  if (IsIdentityOperation(right(), left(), 1)) return right();
1496
  return this;
1497 1498 1499
}


1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
bool HMul::MulMinusOne() {
  if (left()->EqualsInteger32Constant(-1) ||
      right()->EqualsInteger32Constant(-1)) {
    return true;
  }

  return false;
}


1510 1511 1512 1513 1514 1515
HValue* HMod::Canonicalize() {
  return this;
}


HValue* HDiv::Canonicalize() {
1516
  if (IsIdentityOperation(left(), right(), 1)) return left();
1517 1518 1519 1520
  return this;
}


1521 1522 1523 1524 1525
HValue* HChange::Canonicalize() {
  return (from().Equals(to())) ? value() : this;
}


1526 1527 1528 1529 1530 1531 1532 1533 1534
HValue* HWrapReceiver::Canonicalize() {
  if (HasNoUses()) return NULL;
  if (receiver()->type().IsJSObject()) {
    return receiver();
  }
  return this;
}


1535
std::ostream& HTypeof::PrintDataTo(std::ostream& os) const {  // NOLINT
1536
  return os << NameOf(value());
1537 1538 1539
}


1540 1541 1542
HInstruction* HForceRepresentation::New(Isolate* isolate, Zone* zone,
                                        HValue* context, HValue* value,
                                        Representation representation) {
1543 1544
  if (FLAG_fold_constants && value->IsConstant()) {
    HConstant* c = HConstant::cast(value);
1545 1546
    c = c->CopyToRepresentation(representation, zone);
    if (c != NULL) return c;
1547
  }
1548
  return new(zone) HForceRepresentation(value, representation);
1549 1550 1551
}


1552 1553
std::ostream& HForceRepresentation::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1554
  return os << representation().Mnemonic() << " " << NameOf(value());
1555 1556 1557
}


1558
std::ostream& HChange::PrintDataTo(std::ostream& os) const {  // NOLINT
1559 1560
  HUnaryOperation::PrintDataTo(os);
  os << " " << from().Mnemonic() << " to " << to().Mnemonic();
1561

1562 1563 1564 1565 1566
  if (CanTruncateToSmi()) os << " truncating-smi";
  if (CanTruncateToInt32()) os << " truncating-int32";
  if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
  if (CheckFlag(kAllowUndefinedAsNaN)) os << " allow-undefined-as-nan";
  return os;
1567 1568 1569
}


1570
HValue* HUnaryMathOperation::Canonicalize() {
1571
  if (op() == kMathRound || op() == kMathFloor) {
1572 1573
    HValue* val = value();
    if (val->IsChange()) val = HChange::cast(val)->value();
1574
    if (val->representation().IsSmiOrInteger32()) {
1575 1576 1577
      if (val->representation().Equals(representation())) return val;
      return Prepend(new(block()->zone()) HChange(
          val, representation(), false, false));
1578
    }
1579
  }
1580
  if (op() == kMathFloor && value()->IsDiv() && value()->HasOneUse()) {
1581 1582 1583
    HDiv* hdiv = HDiv::cast(value());

    HValue* left = hdiv->left();
1584
    if (left->representation().IsInteger32() && !left->CheckFlag(kUint32)) {
1585
      // A value with an integer representation does not need to be transformed.
1586 1587
    } else if (left->IsChange() && HChange::cast(left)->from().IsInteger32() &&
               !HChange::cast(left)->value()->CheckFlag(kUint32)) {
1588 1589 1590 1591 1592 1593 1594 1595
      // 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()) {
      left = Prepend(new(block()->zone()) HChange(
          left, Representation::Integer32(), false, false));
    } else {
      return this;
    }
1596

1597 1598 1599 1600
    HValue* right = hdiv->right();
    if (right->IsInteger32Constant()) {
      right = Prepend(HConstant::cast(right)->CopyToRepresentation(
          Representation::Integer32(), right->block()->zone()));
1601 1602
    } else if (right->representation().IsInteger32() &&
               !right->CheckFlag(kUint32)) {
1603 1604
      // A value with an integer representation does not need to be transformed.
    } else if (right->IsChange() &&
1605 1606
               HChange::cast(right)->from().IsInteger32() &&
               !HChange::cast(right)->value()->CheckFlag(kUint32)) {
1607 1608 1609 1610 1611 1612 1613
      // 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()) {
      right = Prepend(new(block()->zone()) HChange(
          right, Representation::Integer32(), false, false));
    } else {
      return this;
1614
    }
1615 1616

    return Prepend(HMathFloorOfDiv::New(
1617
        block()->graph()->isolate(), block()->zone(), context(), left, right));
1618 1619 1620 1621 1622
  }
  return this;
}


1623
HValue* HCheckInstanceType::Canonicalize() {
1624 1625 1626
  if ((check_ == IS_SPEC_OBJECT && value()->type().IsJSObject()) ||
      (check_ == IS_JS_ARRAY && value()->type().IsJSArray()) ||
      (check_ == IS_STRING && value()->type().IsString())) {
1627
    return value();
1628
  }
1629

1630
  if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1631 1632 1633
    if (HConstant::cast(value())->HasInternalizedStringValue()) {
      return value();
    }
1634 1635 1636 1637 1638
  }
  return this;
}


1639 1640
void HCheckInstanceType::GetCheckInterval(InstanceType* first,
                                          InstanceType* last) {
1641
  DCHECK(is_interval_check());
1642
  switch (check_) {
1643 1644 1645
    case IS_SPEC_OBJECT:
      *first = FIRST_SPEC_OBJECT_TYPE;
      *last = LAST_SPEC_OBJECT_TYPE;
1646 1647 1648 1649
      return;
    case IS_JS_ARRAY:
      *first = *last = JS_ARRAY_TYPE;
      return;
1650 1651 1652
    case IS_JS_DATE:
      *first = *last = JS_DATE_TYPE;
      return;
1653 1654 1655 1656 1657 1658 1659
    default:
      UNREACHABLE();
  }
}


void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
1660
  DCHECK(!is_interval_check());
1661 1662 1663 1664 1665
  switch (check_) {
    case IS_STRING:
      *mask = kIsNotStringMask;
      *tag = kStringTag;
      return;
1666
    case IS_INTERNALIZED_STRING:
1667
      *mask = kIsNotStringMask | kIsNotInternalizedMask;
1668
      *tag = kInternalizedTag;
1669 1670 1671 1672
      return;
    default:
      UNREACHABLE();
  }
1673 1674 1675
}


1676
std::ostream& HCheckMaps::PrintDataTo(std::ostream& os) const {  // NOLINT
1677
  os << NameOf(value()) << " [" << *maps()->at(0).handle();
1678
  for (int i = 1; i < maps()->size(); ++i) {
1679
    os << "," << *maps()->at(i).handle();
1680
  }
1681 1682 1683
  os << "]";
  if (IsStabilityCheck()) os << "(stability-check)";
  return os;
1684 1685 1686 1687 1688 1689
}


HValue* HCheckMaps::Canonicalize() {
  if (!IsStabilityCheck() && maps_are_stable() && value()->IsConstant()) {
    HConstant* c_value = HConstant::cast(value());
1690
    if (c_value->HasObjectMap()) {
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
      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;
1704 1705 1706
}


1707
std::ostream& HCheckValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1708
  return os << NameOf(value()) << " " << Brief(*object().handle());
1709 1710 1711
}


1712
HValue* HCheckValue::Canonicalize() {
1713
  return (value()->IsConstant() &&
1714
          HConstant::cast(value())->EqualsUnique(object_)) ? NULL : this;
1715 1716 1717
}


1718
const char* HCheckInstanceType::GetCheckName() const {
1719 1720 1721
  switch (check_) {
    case IS_SPEC_OBJECT: return "object";
    case IS_JS_ARRAY: return "array";
1722 1723
    case IS_JS_DATE:
      return "date";
1724
    case IS_STRING: return "string";
1725
    case IS_INTERNALIZED_STRING: return "internalized_string";
1726 1727 1728 1729 1730
  }
  UNREACHABLE();
  return "";
}

1731

1732 1733
std::ostream& HCheckInstanceType::PrintDataTo(
    std::ostream& os) const {  // NOLINT
1734 1735
  os << GetCheckName() << " ";
  return HUnaryOperation::PrintDataTo(os);
1736 1737 1738
}


1739
std::ostream& HCallStub::PrintDataTo(std::ostream& os) const {  // NOLINT
1740
  os << CodeStub::MajorName(major_key_) << " ";
1741
  return HUnaryCall::PrintDataTo(os);
1742 1743 1744
}


1745
std::ostream& HUnknownOSRValue::PrintDataTo(std::ostream& os) const {  // NOLINT
1746 1747 1748 1749
  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";
1750
  return os << type << " @ " << index_;
1751 1752 1753
}


1754
std::ostream& HInstanceOf::PrintDataTo(std::ostream& os) const {  // NOLINT
1755 1756
  return os << NameOf(left()) << " " << NameOf(right()) << " "
            << NameOf(context());
1757 1758 1759
}


1760
Range* HValue::InferRange(Zone* zone) {
1761
  Range* result;
1762
  if (representation().IsSmi() || type().IsSmi()) {
1763 1764 1765 1766
    result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
    result->set_can_be_minus_zero(false);
  } else {
    result = new(zone) Range();
1767 1768 1769
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
    // TODO(jkummerow): The range cannot be minus zero when the upper type
    // bound is Integer32.
1770
  }
1771
  return result;
1772 1773 1774
}


1775
Range* HChange::InferRange(Zone* zone) {
1776
  Range* input_range = value()->range();
1777 1778 1779 1780 1781
  if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
      (to().IsSmi() ||
       (to().IsTagged() &&
        input_range != NULL &&
        input_range->IsInSmiRange()))) {
1782
    set_type(HType::Smi());
1783
    ClearChangesFlag(kNewSpacePromotion);
1784
  }
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
  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);
  }
1795
  Range* result = (input_range != NULL)
1796 1797
      ? input_range->Copy(zone)
      : HValue::InferRange(zone);
1798
  result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1799 1800 1801
                                !(CheckFlag(kAllUsesTruncatingToInt32) ||
                                  CheckFlag(kAllUsesTruncatingToSmi)));
  if (to().IsSmi()) result->ClampToSmi();
1802 1803 1804 1805
  return result;
}


1806
Range* HConstant::InferRange(Zone* zone) {
1807
  if (HasInteger32Value()) {
1808
    Range* result = new(zone) Range(int32_value_, int32_value_);
fschneider@chromium.org's avatar
fschneider@chromium.org committed
1809 1810
    result->set_can_be_minus_zero(false);
    return result;
1811
  }
1812
  return HValue::InferRange(zone);
1813 1814 1815
}


1816
SourcePosition HPhi::position() const { return block()->first()->position(); }
1817 1818


1819
Range* HPhi::InferRange(Zone* zone) {
1820 1821
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1822
    if (block()->IsLoopHeader()) {
1823 1824 1825
      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
1826
      return range;
1827
    } else {
1828
      Range* range = OperandAt(0)->range()->Copy(zone);
1829 1830 1831 1832 1833 1834
      for (int i = 1; i < OperandCount(); ++i) {
        range->Union(OperandAt(i)->range());
      }
      return range;
    }
  } else {
1835
    return HValue::InferRange(zone);
1836 1837 1838 1839
  }
}


1840
Range* HAdd::InferRange(Zone* zone) {
1841 1842
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1843 1844
    Range* a = left()->range();
    Range* b = right()->range();
1845
    Range* res = a->Copy(zone);
1846 1847 1848
    if (!res->AddAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1849 1850
      ClearFlag(kCanOverflow);
    }
1851 1852
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1853
                               a->CanBeMinusZero() && b->CanBeMinusZero());
1854 1855
    return res;
  } else {
1856
    return HValue::InferRange(zone);
1857 1858 1859 1860
  }
}


1861
Range* HSub::InferRange(Zone* zone) {
1862 1863
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1864 1865
    Range* a = left()->range();
    Range* b = right()->range();
1866
    Range* res = a->Copy(zone);
1867 1868 1869
    if (!res->SubAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1870 1871
      ClearFlag(kCanOverflow);
    }
1872 1873
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1874
                               a->CanBeMinusZero() && b->CanBeZero());
1875 1876
    return res;
  } else {
1877
    return HValue::InferRange(zone);
1878 1879 1880 1881
  }
}


1882
Range* HMul::InferRange(Zone* zone) {
1883 1884
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1885 1886
    Range* a = left()->range();
    Range* b = right()->range();
1887
    Range* res = a->Copy(zone);
1888 1889 1890 1891 1892 1893 1894
    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.
1895 1896
      ClearFlag(kCanOverflow);
    }
1897 1898
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1899 1900
                               ((a->CanBeZero() && b->CanBeNegative()) ||
                                (a->CanBeNegative() && b->CanBeZero())));
1901 1902
    return res;
  } else {
1903
    return HValue::InferRange(zone);
1904 1905 1906 1907
  }
}


1908
Range* HDiv::InferRange(Zone* zone) {
1909
  if (representation().IsInteger32()) {
1910 1911
    Range* a = left()->range();
    Range* b = right()->range();
1912
    Range* result = new(zone) Range();
1913 1914 1915
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  (a->CanBeMinusZero() ||
                                   (a->CanBeZero() && b->CanBeNegative())));
1916
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1917
      ClearFlag(kCanOverflow);
1918 1919
    }

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


1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
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);
    }
1941

1942 1943 1944 1945 1946 1947 1948 1949
    if (!a->CanBeNegative()) {
      ClearFlag(HValue::kLeftCanBeNegative);
    }

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

1950 1951 1952
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
      ClearFlag(kCanOverflow);
    }
1953

1954 1955 1956 1957 1958 1959 1960
    if (!b->CanBeZero()) {
      ClearFlag(kCanBeDivByZero);
    }
    return result;
  } else {
    return HValue::InferRange(zone);
  }
1961 1962 1963
}


1964 1965 1966 1967 1968
// 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); }


1969
Range* HMod::InferRange(Zone* zone) {
1970 1971
  if (representation().IsInteger32()) {
    Range* a = left()->range();
1972
    Range* b = right()->range();
1973

1974 1975
    // The magnitude of the modulus is bounded by the right operand.
    int32_t positive_bound = Max(AbsMinus1(b->lower()), AbsMinus1(b->upper()));
1976 1977 1978 1979 1980 1981

    // 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);

1982 1983
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  left_can_be_negative);
1984

1985 1986 1987 1988
    if (!a->CanBeNegative()) {
      ClearFlag(HValue::kLeftCanBeNegative);
    }

1989 1990
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
      ClearFlag(HValue::kCanOverflow);
1991 1992
    }

1993
    if (!b->CanBeZero()) {
1994 1995 1996 1997
      ClearFlag(HValue::kCanBeDivByZero);
    }
    return result;
  } else {
1998
    return HValue::InferRange(zone);
1999 2000 2001 2002
  }
}


2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
InductionVariableData* InductionVariableData::ExaminePhi(HPhi* phi) {
  if (phi->block()->loop_information() == NULL) return NULL;
  if (phi->OperandCount() != 2) return NULL;
  int32_t candidate_increment;

  candidate_increment = ComputeIncrement(phi, phi->OperandAt(0));
  if (candidate_increment != 0) {
    return new(phi->block()->graph()->zone())
        InductionVariableData(phi, phi->OperandAt(1), candidate_increment);
  }

  candidate_increment = ComputeIncrement(phi, phi->OperandAt(1));
  if (candidate_increment != 0) {
    return new(phi->block()->graph()->zone())
        InductionVariableData(phi, phi->OperandAt(0), candidate_increment);
  }

  return NULL;
}


/*
 * This function tries to match the following patterns (and all the relevant
 * variants related to |, & and + being commutative):
 * base | constant_or_mask
 * base & constant_and_mask
 * (base + constant_offset) & constant_and_mask
 * (base - constant_offset) & constant_and_mask
 */
void InductionVariableData::DecomposeBitwise(
    HValue* value,
    BitwiseDecompositionResult* result) {
  HValue* base = IgnoreOsrValue(value);
  result->base = value;

  if (!base->representation().IsInteger32()) return;

  if (base->IsBitwise()) {
    bool allow_offset = false;
    int32_t mask = 0;

    HBitwise* bitwise = HBitwise::cast(base);
    if (bitwise->right()->IsInteger32Constant()) {
      mask = bitwise->right()->GetInteger32Constant();
      base = bitwise->left();
    } else if (bitwise->left()->IsInteger32Constant()) {
      mask = bitwise->left()->GetInteger32Constant();
      base = bitwise->right();
    } else {
      return;
    }
    if (bitwise->op() == Token::BIT_AND) {
      result->and_mask = mask;
      allow_offset = true;
    } else if (bitwise->op() == Token::BIT_OR) {
      result->or_mask = mask;
    } else {
      return;
    }

    result->context = bitwise->context();

    if (allow_offset) {
      if (base->IsAdd()) {
        HAdd* add = HAdd::cast(base);
        if (add->right()->IsInteger32Constant()) {
          base = add->left();
        } else if (add->left()->IsInteger32Constant()) {
          base = add->right();
        }
      } else if (base->IsSub()) {
        HSub* sub = HSub::cast(base);
        if (sub->right()->IsInteger32Constant()) {
          base = sub->left();
        }
      }
    }

    result->base = base;
  }
}


void InductionVariableData::AddCheck(HBoundsCheck* check,
                                     int32_t upper_limit) {
2088
  DCHECK(limit_validity() != NULL);
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
  if (limit_validity() != check->block() &&
      !limit_validity()->Dominates(check->block())) return;
  if (!phi()->block()->current_loop()->IsNestedInThisLoop(
      check->block()->current_loop())) return;

  ChecksRelatedToLength* length_checks = checks();
  while (length_checks != NULL) {
    if (length_checks->length() == check->length()) break;
    length_checks = length_checks->next();
  }
  if (length_checks == NULL) {
    length_checks = new(check->block()->zone())
        ChecksRelatedToLength(check->length(), checks());
    checks_ = length_checks;
  }

  length_checks->AddCheck(check, upper_limit);
}


void InductionVariableData::ChecksRelatedToLength::CloseCurrentBlock() {
  if (checks() != NULL) {
    InductionVariableCheck* c = checks();
    HBasicBlock* current_block = c->check()->block();
    while (c != NULL && c->check()->block() == current_block) {
      c->set_upper_limit(current_upper_limit_);
      c = c->next();
    }
  }
}


void InductionVariableData::ChecksRelatedToLength::UseNewIndexInCurrentBlock(
    Token::Value token,
    int32_t mask,
    HValue* index_base,
    HValue* context) {
2126
  DCHECK(first_check_in_block() != NULL);
2127
  HValue* previous_index = first_check_in_block()->index();
2128
  DCHECK(context != NULL);
2129

2130
  Zone* zone = index_base->block()->graph()->zone();
2131 2132
  Isolate* isolate = index_base->block()->graph()->isolate();
  set_added_constant(HConstant::New(isolate, zone, context, mask));
2133 2134 2135 2136 2137 2138 2139 2140
  if (added_index() != NULL) {
    added_constant()->InsertBefore(added_index());
  } else {
    added_constant()->InsertBefore(first_check_in_block());
  }

  if (added_index() == NULL) {
    first_check_in_block()->ReplaceAllUsesWith(first_check_in_block()->index());
2141 2142
    HInstruction* new_index = HBitwise::New(isolate, zone, context, token,
                                            index_base, added_constant());
2143
    DCHECK(new_index->IsBitwise());
2144 2145 2146 2147 2148
    new_index->ClearAllSideEffects();
    new_index->AssumeRepresentation(Representation::Integer32());
    set_added_index(HBitwise::cast(new_index));
    added_index()->InsertBefore(first_check_in_block());
  }
2149
  DCHECK(added_index()->op() == token);
2150 2151 2152 2153

  added_index()->SetOperandAt(1, index_base);
  added_index()->SetOperandAt(2, added_constant());
  first_check_in_block()->SetOperandAt(0, added_index());
2154
  if (previous_index->HasNoUses()) {
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 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 2224 2225 2226 2227
    previous_index->DeleteAndReplaceWith(NULL);
  }
}

void InductionVariableData::ChecksRelatedToLength::AddCheck(
    HBoundsCheck* check,
    int32_t upper_limit) {
  BitwiseDecompositionResult decomposition;
  InductionVariableData::DecomposeBitwise(check->index(), &decomposition);

  if (first_check_in_block() == NULL ||
      first_check_in_block()->block() != check->block()) {
    CloseCurrentBlock();

    first_check_in_block_ = check;
    set_added_index(NULL);
    set_added_constant(NULL);
    current_and_mask_in_block_ = decomposition.and_mask;
    current_or_mask_in_block_ = decomposition.or_mask;
    current_upper_limit_ = upper_limit;

    InductionVariableCheck* new_check = new(check->block()->graph()->zone())
        InductionVariableCheck(check, checks_, upper_limit);
    checks_ = new_check;
    return;
  }

  if (upper_limit > current_upper_limit()) {
    current_upper_limit_ = upper_limit;
  }

  if (decomposition.and_mask != 0 &&
      current_or_mask_in_block() == 0) {
    if (current_and_mask_in_block() == 0 ||
        decomposition.and_mask > current_and_mask_in_block()) {
      UseNewIndexInCurrentBlock(Token::BIT_AND,
                                decomposition.and_mask,
                                decomposition.base,
                                decomposition.context);
      current_and_mask_in_block_ = decomposition.and_mask;
    }
    check->set_skip_check();
  }
  if (current_and_mask_in_block() == 0) {
    if (decomposition.or_mask > current_or_mask_in_block()) {
      UseNewIndexInCurrentBlock(Token::BIT_OR,
                                decomposition.or_mask,
                                decomposition.base,
                                decomposition.context);
      current_or_mask_in_block_ = decomposition.or_mask;
    }
    check->set_skip_check();
  }

  if (!check->skip_check()) {
    InductionVariableCheck* new_check = new(check->block()->graph()->zone())
        InductionVariableCheck(check, checks_, upper_limit);
    checks_ = new_check;
  }
}


/*
 * This method detects if phi is an induction variable, with phi_operand as
 * its "incremented" value (the other operand would be the "base" value).
 *
 * It cheks is phi_operand has the form "phi + constant".
 * If yes, the constant is the increment that the induction variable gets at
 * every loop iteration.
 * Otherwise it returns 0.
 */
int32_t InductionVariableData::ComputeIncrement(HPhi* phi,
                                                HValue* phi_operand) {
2228
  if (!phi_operand->representation().IsSmiOrInteger32()) return 0;
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242

  if (phi_operand->IsAdd()) {
    HAdd* operation = HAdd::cast(phi_operand);
    if (operation->left() == phi &&
        operation->right()->IsInteger32Constant()) {
      return operation->right()->GetInteger32Constant();
    } else if (operation->right() == phi &&
               operation->left()->IsInteger32Constant()) {
      return operation->left()->GetInteger32Constant();
    }
  } else if (phi_operand->IsSub()) {
    HSub* operation = HSub::cast(phi_operand);
    if (operation->left() == phi &&
        operation->right()->IsInteger32Constant()) {
2243 2244 2245
      int constant = operation->right()->GetInteger32Constant();
      if (constant == kMinInt) return 0;
      return -constant;
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
    }
  }

  return 0;
}


/*
 * Swaps the information in "update" with the one contained in "this".
 * The swapping is important because this method is used while doing a
 * dominator tree traversal, and "update" will retain the old data that
 * will be restored while backtracking.
 */
void InductionVariableData::UpdateAdditionalLimit(
    InductionVariableLimitUpdate* update) {
2261
  DCHECK(update->updated_variable == this);
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
  if (update->limit_is_upper) {
    swap(&additional_upper_limit_, &update->limit);
    swap(&additional_upper_limit_is_included_, &update->limit_is_included);
  } else {
    swap(&additional_lower_limit_, &update->limit);
    swap(&additional_lower_limit_is_included_, &update->limit_is_included);
  }
}


int32_t InductionVariableData::ComputeUpperLimit(int32_t and_mask,
                                                 int32_t or_mask) {
  // Should be Smi::kMaxValue but it must fit 32 bits; lower is safe anyway.
  const int32_t MAX_LIMIT = 1 << 30;

  int32_t result = MAX_LIMIT;

  if (limit() != NULL &&
      limit()->IsInteger32Constant()) {
    int32_t limit_value = limit()->GetInteger32Constant();
    if (!limit_included()) {
      limit_value--;
    }
    if (limit_value < result) result = limit_value;
  }

  if (additional_upper_limit() != NULL &&
      additional_upper_limit()->IsInteger32Constant()) {
    int32_t limit_value = additional_upper_limit()->GetInteger32Constant();
    if (!additional_upper_limit_is_included()) {
      limit_value--;
    }
    if (limit_value < result) result = limit_value;
  }

  if (and_mask > 0 && and_mask < MAX_LIMIT) {
    if (and_mask < result) result = and_mask;
    return result;
  }

  // Add the effect of the or_mask.
  result |= or_mask;

  return result >= MAX_LIMIT ? kNoLimit : result;
}


HValue* InductionVariableData::IgnoreOsrValue(HValue* v) {
  if (!v->IsPhi()) return v;
  HPhi* phi = HPhi::cast(v);
  if (phi->OperandCount() != 2) return v;
  if (phi->OperandAt(0)->block()->is_osr_entry()) {
    return phi->OperandAt(1);
  } else if (phi->OperandAt(1)->block()->is_osr_entry()) {
    return phi->OperandAt(0);
  } else {
    return v;
  }
}


InductionVariableData* InductionVariableData::GetInductionVariableData(
    HValue* v) {
  v = IgnoreOsrValue(v);
  if (v->IsPhi()) {
    return HPhi::cast(v)->induction_variable_data();
  }
  return NULL;
}


/*
 * Check if a conditional branch to "current_branch" with token "token" is
 * the branch that keeps the induction loop running (and, conversely, will
 * terminate it if the "other_branch" is taken).
 *
 * Three conditions must be met:
 * - "current_branch" must be in the induction loop.
 * - "other_branch" must be out of the induction loop.
 * - "token" and the induction increment must be "compatible": the token should
 *   be a condition that keeps the execution inside the loop until the limit is
 *   reached.
 */
bool InductionVariableData::CheckIfBranchIsLoopGuard(
    Token::Value token,
    HBasicBlock* current_branch,
    HBasicBlock* other_branch) {
  if (!phi()->block()->current_loop()->IsNestedInThisLoop(
      current_branch->current_loop())) {
    return false;
  }

  if (phi()->block()->current_loop()->IsNestedInThisLoop(
      other_branch->current_loop())) {
    return false;
  }

  if (increment() > 0 && (token == Token::LT || token == Token::LTE)) {
    return true;
  }
  if (increment() < 0 && (token == Token::GT || token == Token::GTE)) {
    return true;
  }
  if (Token::IsInequalityOp(token) && (increment() == 1 || increment() == -1)) {
    return true;
  }

  return false;
}


void InductionVariableData::ComputeLimitFromPredecessorBlock(
    HBasicBlock* block,
    LimitFromPredecessorBlock* result) {
  if (block->predecessors()->length() != 1) return;
  HBasicBlock* predecessor = block->predecessors()->at(0);
  HInstruction* end = predecessor->last();

  if (!end->IsCompareNumericAndBranch()) return;
  HCompareNumericAndBranch* branch = HCompareNumericAndBranch::cast(end);

  Token::Value token = branch->token();
  if (!Token::IsArithmeticCompareOp(token)) return;

  HBasicBlock* other_target;
  if (block == branch->SuccessorAt(0)) {
    other_target = branch->SuccessorAt(1);
  } else {
    other_target = branch->SuccessorAt(0);
    token = Token::NegateCompareOp(token);
2392
    DCHECK(block == branch->SuccessorAt(1));
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
  }

  InductionVariableData* data;

  data = GetInductionVariableData(branch->left());
  HValue* limit = branch->right();
  if (data == NULL) {
    data = GetInductionVariableData(branch->right());
    token = Token::ReverseCompareOp(token);
    limit = branch->left();
  }

  if (data != NULL) {
    result->variable = data;
    result->token = token;
    result->limit = limit;
    result->other_target = other_target;
  }
}


/*
 * Compute the limit that is imposed on an induction variable when entering
 * "block" (if any).
 * If the limit is the "proper" induction limit (the one that makes the loop
 * terminate when the induction variable reaches it) it is stored directly in
 * the induction variable data.
 * Otherwise the limit is written in "additional_limit" and the method
 * returns true.
 */
bool InductionVariableData::ComputeInductionVariableLimit(
    HBasicBlock* block,
    InductionVariableLimitUpdate* additional_limit) {
  LimitFromPredecessorBlock limit;
  ComputeLimitFromPredecessorBlock(block, &limit);
  if (!limit.LimitIsValid()) return false;

  if (limit.variable->CheckIfBranchIsLoopGuard(limit.token,
                                               block,
                                               limit.other_target)) {
    limit.variable->limit_ = limit.limit;
    limit.variable->limit_included_ = limit.LimitIsIncluded();
    limit.variable->limit_validity_ = block;
    limit.variable->induction_exit_block_ = block->predecessors()->at(0);
    limit.variable->induction_exit_target_ = limit.other_target;
    return false;
  } else {
    additional_limit->updated_variable = limit.variable;
    additional_limit->limit = limit.limit;
    additional_limit->limit_is_upper = limit.LimitIsUpper();
    additional_limit->limit_is_included = limit.LimitIsIncluded();
    return true;
  }
}


2449
Range* HMathMinMax::InferRange(Zone* zone) {
2450
  if (representation().IsSmiOrInteger32()) {
2451 2452 2453 2454 2455 2456
    Range* a = left()->range();
    Range* b = right()->range();
    Range* res = a->Copy(zone);
    if (operation_ == kMathMax) {
      res->CombinedMax(b);
    } else {
2457
      DCHECK(operation_ == kMathMin);
2458 2459 2460 2461 2462 2463 2464 2465 2466
      res->CombinedMin(b);
    }
    return res;
  } else {
    return HValue::InferRange(zone);
  }
}


2467 2468 2469 2470 2471 2472
void HPushArguments::AddInput(HValue* value) {
  inputs_.Add(NULL, value->block()->zone());
  SetOperandAt(OperandCount() - 1, value);
}


2473
std::ostream& HPhi::PrintTo(std::ostream& os) const {  // NOLINT
2474
  os << "[";
2475
  for (int i = 0; i < OperandCount(); ++i) {
2476
    os << " " << NameOf(OperandAt(i)) << " ";
2477
  }
2478 2479
  return os << " uses" << UseCount()
            << representation_from_indirect_uses().Mnemonic() << " "
2480
            << TypeOf(this) << "]";
2481 2482 2483 2484
}


void HPhi::AddInput(HValue* value) {
2485
  inputs_.Add(NULL, value->block()->zone());
2486 2487 2488 2489 2490 2491 2492 2493
  SetOperandAt(OperandCount() - 1, value);
  // Mark phis that may have 'arguments' directly or indirectly as an operand.
  if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
    SetFlag(kIsArguments);
  }
}


2494
bool HPhi::HasRealUses() {
2495 2496
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    if (!it.value()->IsPhi()) return true;
2497 2498 2499 2500 2501
  }
  return false;
}


2502
HValue* HPhi::GetRedundantReplacement() {
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
  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;
  }
2514
  DCHECK(candidate != this);
2515 2516 2517 2518 2519
  return candidate;
}


void HPhi::DeleteFromGraph() {
2520
  DCHECK(block() != NULL);
2521
  block()->RemovePhi(this);
2522
  DCHECK(block() == NULL);
2523 2524 2525 2526 2527 2528
}


void HPhi::InitRealUses(int phi_id) {
  // Initialize real uses.
  phi_id_ = phi_id;
2529 2530 2531
  // Compute a conservative approximation of truncating uses before inferring
  // representations. The proper, exact computation will be done later, when
  // inserting representation changes.
2532
  SetFlag(kTruncatingToSmi);
2533
  SetFlag(kTruncatingToInt32);
2534 2535 2536
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* value = it.value();
    if (!value->IsPhi()) {
2537
      Representation rep = value->observed_input_representation(it.index());
2538 2539 2540 2541 2542 2543
      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;
      }

2544
      if (FLAG_trace_representation) {
2545 2546
        PrintF("#%d Phi is used by real #%d %s as %s\n",
               id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2547
      }
2548 2549 2550 2551 2552 2553 2554
      if (!value->IsSimulate()) {
        if (!value->CheckFlag(kTruncatingToSmi)) {
          ClearFlag(kTruncatingToSmi);
        }
        if (!value->CheckFlag(kTruncatingToInt32)) {
          ClearFlag(kTruncatingToInt32);
        }
2555
      }
2556 2557 2558 2559 2560 2561
    }
  }
}


void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2562
  if (FLAG_trace_representation) {
2563 2564 2565 2566 2567
    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());
2568 2569
  }

2570 2571 2572
  representation_from_indirect_uses_ =
      representation_from_indirect_uses().generalize(
          other->representation_from_non_phi_uses());
2573 2574 2575
}


2576 2577 2578 2579 2580 2581
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)) {
2582 2583 2584
        int index = from->GetAssignedIndexAt(i);
        if (HasValueForIndex(index)) continue;
        AddAssignedValue(index, from_values->at(i));
2585
      } else {
2586 2587 2588 2589 2590
        if (pop_count_ > 0) {
          pop_count_--;
        } else {
          AddPushedValue(from_values->at(i));
        }
2591 2592
      }
    }
2593 2594
    pop_count_ += from->pop_count_;
    from->DeleteAndReplaceWith(NULL);
2595
  }
2596 2597 2598
}


2599
std::ostream& HSimulate::PrintDataTo(std::ostream& os) const {  // NOLINT
2600 2601
  os << "id=" << ast_id().ToInt();
  if (pop_count_ > 0) os << " pop " << pop_count_;
2602
  if (values_.length() > 0) {
2603
    if (pop_count_ > 0) os << " /";
2604
    for (int i = values_.length() - 1; i >= 0; --i) {
2605
      if (HasAssignedIndexAt(i)) {
2606
        os << " var[" << GetAssignedIndexAt(i) << "] = ";
2607
      } else {
2608
        os << " push ";
2609
      }
2610 2611
      os << NameOf(values_[i]);
      if (i > 0) os << ",";
2612 2613
    }
  }
2614
  return os;
2615 2616 2617
}


2618
void HSimulate::ReplayEnvironment(HEnvironment* env) {
2619
  if (is_done_with_replay()) return;
2620
  DCHECK(env != NULL);
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
  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);
    }
  }
2631
  set_done_with_replay();
2632 2633 2634
}


2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
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);
      }
    }
  }
}


2650 2651 2652
// 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) {
2653
  DCHECK(env != NULL);
2654
  while (env != NULL) {
2655
    ReplayEnvironmentNested(env->values(), this);
2656 2657 2658 2659 2660
    env = env->outer();
  }
}


2661
std::ostream& HCapturedObject::PrintDataTo(std::ostream& os) const {  // NOLINT
2662 2663
  os << "#" << capture_id() << " ";
  return HDematerializedObject::PrintDataTo(os);
2664 2665 2666
}


2667 2668
void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
                                         Zone* zone) {
2669
  DCHECK(return_target->IsInlineReturnTarget());
2670 2671 2672 2673
  return_targets_.Add(return_target, zone);
}


2674
std::ostream& HEnterInlined::PrintDataTo(std::ostream& os) const {  // NOLINT
2675
  return os << function()->debug_name()->ToCString().get();
2676 2677 2678
}


2679
static bool IsInteger32(double value) {
2680 2681 2682 2683 2684 2685
  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;
2686 2687 2688
}


2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
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());
}


2702
HConstant::HConstant(Handle<Object> object, Representation r)
2703 2704 2705
    : HTemplateInstruction<0>(HType::FromValue(object)),
      object_(Unique<Object>::CreateUninitialized(object)),
      object_map_(Handle<Map>::null()),
2706 2707 2708 2709 2710 2711 2712 2713 2714
      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)) {
2715
  if (object->IsHeapObject()) {
2716 2717 2718
    Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
    Isolate* isolate = heap_object->GetIsolate();
    Handle<Map> map(heap_object->map(), isolate);
2719 2720 2721 2722 2723
    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());
2724
    bit_field_ = IsCallableField::update(bit_field_, map->is_callable());
2725
    if (map->is_stable()) object_map_ = Unique<Map>::CreateImmovable(map);
2726 2727 2728
    bit_field_ = HasStableMapValueField::update(
        bit_field_,
        HasMapValue() && Handle<Map>::cast(heap_object)->is_stable());
2729 2730 2731
  }
  if (object->IsNumber()) {
    double n = object->Number();
2732 2733
    bool has_int32_value = IsInteger32(n);
    bit_field_ = HasInt32ValueField::update(bit_field_, has_int32_value);
2734
    int32_value_ = DoubleToInt32(n);
2735 2736
    bit_field_ = HasSmiValueField::update(
        bit_field_, has_int32_value && Smi::IsValid(int32_value_));
2737
    double_value_ = n;
2738
    bit_field_ = HasDoubleValueField::update(bit_field_, true);
2739
    // TODO(titzer): if this heap number is new space, tenure a new one.
2740
  }
2741

2742
  Initialize(r);
2743 2744 2745
}


2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
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)) {
2762 2763
  DCHECK(!object.handle().is_null());
  DCHECK(!type.IsTaggedNumber() || type.IsNone());
2764 2765 2766 2767
  Initialize(r);
}


2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
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)) {
2783 2784 2785
  // 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();
2786
  bool is_smi = HasSmiValue() && !could_be_heapobject;
2787
  set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2788
  Initialize(r);
2789 2790 2791
}


2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
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)),
2805
      int32_value_(DoubleToInt32(double_value)),
2806 2807 2808
      double_value_(double_value) {
  bit_field_ = HasSmiValueField::update(
      bit_field_, HasInteger32Value() && Smi::IsValid(int32_value_));
2809 2810 2811
  // 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();
2812
  bool is_smi = HasSmiValue() && !could_be_heapobject;
2813
  set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2814 2815 2816 2817
  Initialize(r);
}


2818
HConstant::HConstant(ExternalReference reference)
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
    : 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) {
2831 2832 2833 2834
  Initialize(Representation::External());
}


2835
void HConstant::Initialize(Representation r) {
2836
  if (r.IsNone()) {
2837
    if (HasSmiValue() && SmiValuesAre31Bits()) {
2838
      r = Representation::Smi();
2839
    } else if (HasInteger32Value()) {
2840
      r = Representation::Integer32();
2841
    } else if (HasDoubleValue()) {
2842
      r = Representation::Double();
2843
    } else if (HasExternalReferenceValue()) {
2844
      r = Representation::External();
2845
    } else {
2846 2847 2848 2849 2850 2851 2852 2853
      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);
        }
      }
2854 2855 2856
      r = Representation::Tagged();
    }
  }
2857 2858 2859 2860 2861 2862 2863
  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());
  }
2864
  if (r.IsSmiOrInteger32() && object_.handle().is_null()) {
2865 2866 2867
    // If it's not a heap object, it can't be in new space.
    bit_field_ = IsNotInNewSpaceField::update(bit_field_, true);
  }
2868 2869
  set_representation(r);
  SetFlag(kUseGVN);
2870 2871 2872
}


2873
bool HConstant::ImmortalImmovable() const {
2874
  if (HasInteger32Value()) {
2875 2876
    return false;
  }
2877
  if (HasDoubleValue()) {
2878 2879 2880 2881 2882
    if (IsSpecialDouble()) {
      return true;
    }
    return false;
  }
2883
  if (HasExternalReferenceValue()) {
2884 2885 2886
    return false;
  }

2887
  DCHECK(!object_.handle().is_null());
2888
  Heap* heap = isolate()->heap();
2889 2890
  DCHECK(!object_.IsKnownGlobal(heap->minus_zero_value()));
  DCHECK(!object_.IsKnownGlobal(heap->nan_value()));
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
  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;
2905 2906 2907
}


2908
bool HConstant::EmitAtUses() {
2909
  DCHECK(IsLinked());
2910 2911
  if (block()->graph()->has_osr() &&
      block()->graph()->IsStandardConstant(this)) {
2912
    // TODO(titzer): this seems like a hack that should be fixed by custom OSR.
2913
    return true;
2914
  }
2915
  if (HasNoUses()) return true;
2916 2917
  if (IsCell()) return false;
  if (representation().IsDouble()) return false;
2918
  if (representation().IsExternal()) return false;
2919
  return true;
2920 2921 2922
}


2923
HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2924 2925 2926 2927 2928 2929
  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_);
2930
  }
2931 2932
  if (HasDoubleValue()) {
    return new (zone) HConstant(double_value_, r, NotInNewSpace(), object_);
2933
  }
2934
  if (HasExternalReferenceValue()) {
2935 2936
    return new(zone) HConstant(external_reference_value_);
  }
2937
  DCHECK(!object_.handle().is_null());
2938 2939 2940
  return new (zone) HConstant(object_, object_map_, HasStableMapValue(), r,
                              type_, NotInNewSpace(), BooleanValue(),
                              IsUndetectable(), GetInstanceType());
2941 2942 2943
}


2944 2945
Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
  HConstant* res = NULL;
2946 2947 2948 2949 2950 2951 2952
  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_);
2953
  }
2954
  return res != NULL ? Just(res) : Nothing<HConstant*>();
2955 2956 2957
}


2958 2959
Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Isolate* isolate,
                                                   Zone* zone) {
2960
  HConstant* res = NULL;
2961
  Handle<Object> handle = this->handle(isolate);
2962 2963
  if (handle->IsBoolean()) {
    res = handle->BooleanValue() ?
2964
      new(zone) HConstant(1) : new(zone) HConstant(0);
2965
  } else if (handle->IsUndefined()) {
2966
    res = new (zone) HConstant(std::numeric_limits<double>::quiet_NaN());
2967
  } else if (handle->IsNull()) {
2968
    res = new(zone) HConstant(0);
2969
  }
2970
  return res != NULL ? Just(res) : Nothing<HConstant*>();
2971 2972
}

2973

2974
std::ostream& HConstant::PrintDataTo(std::ostream& os) const {  // NOLINT
2975
  if (HasInteger32Value()) {
2976
    os << int32_value_ << " ";
2977
  } else if (HasDoubleValue()) {
2978
    os << double_value_ << " ";
2979
  } else if (HasExternalReferenceValue()) {
2980
    os << reinterpret_cast<void*>(external_reference_value_.address()) << " ";
2981
  } else {
2982
    // The handle() method is silently and lazily mutating the object.
2983
    Handle<Object> h = const_cast<HConstant*>(this)->handle(isolate());
2984 2985 2986
    os << Brief(*h) << " ";
    if (HasStableMapValue()) os << "[stable-map] ";
    if (HasObjectMap()) os << "[map " << *ObjectMap().handle() << "] ";
2987
  }
2988
  if (!NotInNewSpace()) os << "[new space] ";
2989
  return os;
2990 2991 2992
}


2993
std::ostream& HBinaryOperation::PrintDataTo(std::ostream& os) const {  // NOLINT
2994 2995 2996 2997
  os << NameOf(left()) << " " << NameOf(right());
  if (CheckFlag(kCanOverflow)) os << " !";
  if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
  return os;
2998 2999 3000
}


3001
void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
3002
  DCHECK(CheckFlag(kFlexibleRepresentation));
3003 3004
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
3005 3006 3007 3008 3009 3010

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

3011 3012 3013 3014 3015 3016
  if (observed_output_representation_.IsNone()) {
    new_rep = RepresentationFromUses();
    UpdateRepresentation(new_rep, h_infer, "uses");
  } else {
    new_rep = RepresentationFromOutput();
    UpdateRepresentation(new_rep, h_infer, "output");
3017
  }
3018 3019 3020
}


3021 3022 3023 3024 3025
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) {
3026
    rep = rep.generalize(observed_input_representation(i));
3027 3028 3029 3030 3031
  }
  // 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();
3032 3033
  if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
  if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
3034

3035 3036 3037 3038 3039 3040 3041 3042 3043
  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.
3044
         (!this->IsMul() || HMul::cast(this)->MulMinusOne());
3045 3046 3047 3048 3049
}


Representation HBinaryOperation::RepresentationFromOutput() {
  Representation rep = representation();
3050 3051 3052 3053 3054
  // 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)) {
3055
    return observed_output_representation_;
3056
  }
3057
  return Representation::None();
3058 3059 3060 3061
}


void HBinaryOperation::AssumeRepresentation(Representation r) {
3062 3063
  set_observed_input_representation(1, r);
  set_observed_input_representation(2, r);
3064 3065 3066 3067
  HValue::AssumeRepresentation(r);
}


3068
void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
3069
  DCHECK(CheckFlag(kFlexibleRepresentation));
3070 3071 3072 3073 3074 3075
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  // Do not care about uses.
}


3076
Range* HBitwise::InferRange(Zone* zone) {
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
  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));
3105
    }
3106 3107 3108
    Range* result = HValue::InferRange(zone);
    result->set_can_be_minus_zero(false);
    return result;
3109
  }
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
  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;
3120 3121 3122 3123 3124
  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;
3125 3126 3127
}


3128
Range* HSar::InferRange(Zone* zone) {
3129 3130 3131
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
3132
      Range* result = (left()->range() != NULL)
3133 3134
          ? left()->range()->Copy(zone)
          : new(zone) Range();
3135
      result->Sar(c->Integer32Value());
3136 3137 3138
      return result;
    }
  }
3139
  return HValue::InferRange(zone);
3140 3141 3142
}


3143
Range* HShr::InferRange(Zone* zone) {
3144 3145 3146 3147 3148 3149 3150
  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)
3151 3152 3153
            ? new(zone) Range(0,
                              static_cast<uint32_t>(0xffffffff) >> shift_count)
            : new(zone) Range();
3154 3155 3156
      } else {
        // For positive inputs we can use the >> operator.
        Range* result = (left()->range() != NULL)
3157 3158
            ? left()->range()->Copy(zone)
            : new(zone) Range();
3159 3160 3161 3162 3163
        result->Sar(c->Integer32Value());
        return result;
      }
    }
  }
3164
  return HValue::InferRange(zone);
3165 3166 3167
}


3168
Range* HShl::InferRange(Zone* zone) {
3169 3170 3171
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
3172
      Range* result = (left()->range() != NULL)
3173 3174
          ? left()->range()->Copy(zone)
          : new(zone) Range();
3175
      result->Shl(c->Integer32Value());
3176 3177 3178
      return result;
    }
  }
3179
  return HValue::InferRange(zone);
3180 3181 3182
}


3183
Range* HLoadNamedField::InferRange(Zone* zone) {
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
  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);
3195
  }
3196 3197 3198 3199 3200 3201 3202
  if (access().IsStringLength()) {
    return new(zone) Range(0, String::kMaxLength);
  }
  return HValue::InferRange(zone);
}


3203
Range* HLoadKeyed::InferRange(Zone* zone) {
3204
  switch (elements_kind()) {
3205
    case INT8_ELEMENTS:
3206
      return new(zone) Range(kMinInt8, kMaxInt8);
3207 3208
    case UINT8_ELEMENTS:
    case UINT8_CLAMPED_ELEMENTS:
3209
      return new(zone) Range(kMinUInt8, kMaxUInt8);
3210
    case INT16_ELEMENTS:
3211
      return new(zone) Range(kMinInt16, kMaxInt16);
3212
    case UINT16_ELEMENTS:
3213
      return new(zone) Range(kMinUInt16, kMaxUInt16);
3214
    default:
3215
      return HValue::InferRange(zone);
3216 3217 3218
  }
}

3219

3220
std::ostream& HCompareGeneric::PrintDataTo(std::ostream& os) const {  // NOLINT
3221 3222
  os << Token::Name(token()) << " ";
  return HBinaryOperation::PrintDataTo(os);
3223 3224 3225
}


3226 3227
std::ostream& HStringCompareAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3228 3229
  os << Token::Name(token()) << " ";
  return HControlInstruction::PrintDataTo(os);
3230 3231 3232
}


3233 3234
std::ostream& HCompareNumericAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3235 3236
  os << Token::Name(token()) << " " << NameOf(left()) << " " << NameOf(right());
  return HControlInstruction::PrintDataTo(os);
3237 3238 3239
}


3240 3241
std::ostream& HCompareObjectEqAndBranch::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3242 3243
  os << NameOf(left()) << " " << NameOf(right());
  return HControlInstruction::PrintDataTo(os);
3244 3245 3246
}


3247
bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3248 3249 3250 3251
  if (known_successor_index() != kNoKnownSuccessorIndex) {
    *block = SuccessorAt(known_successor_index());
    return true;
  }
3252
  if (FLAG_fold_constants && left()->IsConstant() && right()->IsConstant()) {
3253
    *block = HConstant::cast(left())->DataEquals(HConstant::cast(right()))
3254 3255 3256 3257 3258 3259 3260 3261 3262
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


bool HIsStringAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3263 3264 3265 3266
  if (known_successor_index() != kNoKnownSuccessorIndex) {
    *block = SuccessorAt(known_successor_index());
    return true;
  }
3267 3268 3269 3270 3271
  if (FLAG_fold_constants && value()->IsConstant()) {
    *block = HConstant::cast(value())->HasStringValue()
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
  if (value()->type().IsString()) {
    *block = FirstSuccessor();
    return true;
  }
  if (value()->type().IsSmi() ||
      value()->type().IsNull() ||
      value()->type().IsBoolean() ||
      value()->type().IsUndefined() ||
      value()->type().IsJSObject()) {
    *block = SecondSuccessor();
    return true;
  }
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
  *block = NULL;
  return false;
}


bool HIsUndetectableAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (FLAG_fold_constants && value()->IsConstant()) {
    *block = HConstant::cast(value())->IsUndetectable()
        ? FirstSuccessor() : SecondSuccessor();
    return true;
  }
  *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();
3305 3306 3307 3308 3309 3310 3311
    return true;
  }
  *block = NULL;
  return false;
}


3312 3313
void HCompareHoleAndBranch::InferRepresentation(
    HInferRepresentationPhase* h_infer) {
3314
  ChangeRepresentation(value()->representation());
3315 3316 3317
}


3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
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;
}


3333
bool HCompareMinusZeroAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3334 3335 3336 3337 3338
  if (FLAG_fold_constants && value()->IsConstant()) {
    HConstant* constant = HConstant::cast(value());
    if (constant->HasDoubleValue()) {
      *block = IsMinusZero(constant->DoubleValue())
          ? FirstSuccessor() : SecondSuccessor();
3339
      return true;
3340 3341
    }
  }
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
  if (value()->representation().IsSmiOrInteger32()) {
    // A Smi or Integer32 cannot contain minus zero.
    *block = SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


void HCompareMinusZeroAndBranch::InferRepresentation(
    HInferRepresentationPhase* h_infer) {
  ChangeRepresentation(value()->representation());
}


3358
std::ostream& HGoto::PrintDataTo(std::ostream& os) const {  // NOLINT
3359
  return os << *SuccessorAt(0);
3360 3361 3362
}


3363
void HCompareNumericAndBranch::InferRepresentation(
3364
    HInferRepresentationPhase* h_infer) {
3365 3366
  Representation left_rep = left()->representation();
  Representation right_rep = right()->representation();
3367 3368 3369
  Representation observed_left = observed_input_representation(0);
  Representation observed_right = observed_input_representation(1);

3370 3371 3372 3373
  Representation rep = Representation::None();
  rep = rep.generalize(observed_left);
  rep = rep.generalize(observed_right);
  if (rep.IsNone() || rep.IsSmiOrInteger32()) {
3374 3375 3376 3377 3378
    if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
    if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
  } else {
    rep = Representation::Double();
  }
3379 3380

  if (rep.IsDouble()) {
3381 3382 3383 3384
    // 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
3385 3386 3387
    // 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 (<, >, <=,
3388 3389 3390 3391 3392 3393
    // >=). 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
3394
    if (Token::IsOrderedRelationalCompareOp(token_) && !is_strong(strength())) {
3395
      SetFlag(kAllowUndefinedAsNaN);
3396
    }
3397
  }
3398
  ChangeRepresentation(rep);
3399 3400 3401
}


3402
std::ostream& HParameter::PrintDataTo(std::ostream& os) const {  // NOLINT
3403
  return os << index();
3404 3405 3406
}


3407
std::ostream& HLoadNamedField::PrintDataTo(std::ostream& os) const {  // NOLINT
3408
  os << NameOf(object()) << access_;
3409

3410
  if (maps() != NULL) {
3411
    os << " [" << *maps()->at(0).handle();
3412
    for (int i = 1; i < maps()->size(); ++i) {
3413
      os << "," << *maps()->at(i).handle();
3414
    }
3415
    os << "]";
3416 3417
  }

3418 3419
  if (HasDependency()) os << " " << NameOf(dependency());
  return os;
3420 3421 3422
}


3423 3424
std::ostream& HLoadNamedGeneric::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3425 3426
  Handle<String> n = Handle<String>::cast(name());
  return os << NameOf(object()) << "." << n->ToCString().get();
3427 3428 3429
}


3430
std::ostream& HLoadKeyed::PrintDataTo(std::ostream& os) const {  // NOLINT
3431
  if (!is_fixed_typed_array()) {
3432
    os << NameOf(elements());
3433
  } else {
3434 3435
    DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3436
    os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3437 3438
  }

3439 3440 3441
  os << "[" << NameOf(key());
  if (IsDehoisted()) os << " + " << base_offset();
  os << "]";
3442

3443 3444 3445
  if (HasDependency()) os << " " << NameOf(dependency());
  if (RequiresHoleCheck()) os << " check_hole";
  return os;
3446 3447 3448
}


3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
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;
}


3465
bool HLoadKeyed::UsesMustHandleHole() const {
3466
  if (IsFastPackedElementsKind(elements_kind())) {
3467 3468 3469
    return false;
  }

3470
  if (IsFixedTypedArrayElementsKind(elements_kind())) {
3471 3472 3473
    return false;
  }

3474 3475 3476 3477 3478 3479
  if (hole_mode() == ALLOW_RETURN_HOLE) {
    if (IsFastDoubleElementsKind(elements_kind())) {
      return AllUsesCanTreatHoleAsNaN();
    }
    return true;
  }
3480

3481
  if (IsFastDoubleElementsKind(elements_kind())) {
3482
    return false;
3483 3484
  }

3485 3486 3487 3488 3489
  // Holes are only returned as tagged values.
  if (!representation().IsTagged()) {
    return false;
  }

3490 3491
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
3492
    if (!use->IsChange()) return false;
3493
  }
3494

3495 3496 3497 3498
  return true;
}


3499
bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
3500 3501
  return IsFastDoubleElementsKind(elements_kind()) &&
      CheckUsesForFlag(HValue::kAllowUndefinedAsNaN);
3502 3503 3504
}


3505 3506 3507 3508 3509
bool HLoadKeyed::RequiresHoleCheck() const {
  if (IsFastPackedElementsKind(elements_kind())) {
    return false;
  }

3510
  if (IsFixedTypedArrayElementsKind(elements_kind())) {
3511 3512 3513
    return false;
  }

3514 3515 3516 3517
  if (hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
    return false;
  }

3518
  return !UsesMustHandleHole();
3519 3520 3521
}


3522 3523
std::ostream& HLoadKeyedGeneric::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3524
  return os << NameOf(object()) << "[" << NameOf(key()) << "]";
3525 3526 3527
}


3528 3529 3530 3531
HValue* HLoadKeyedGeneric::Canonicalize() {
  // 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.
3532 3533 3534
  if (key()->IsLoadKeyed()) {
    HLoadKeyed* key_load = HLoadKeyed::cast(key());
    if (key_load->elements()->IsForInCacheArray()) {
3535
      HForInCacheArray* names_cache =
3536
          HForInCacheArray::cast(key_load->elements());
3537 3538 3539 3540

      if (names_cache->enumerable() == object()) {
        HForInCacheArray* index_cache =
            names_cache->index_cache();
3541 3542 3543 3544
        HCheckMapValue* map_check = HCheckMapValue::New(
            block()->graph()->isolate(), block()->graph()->zone(),
            block()->graph()->GetInvalidContext(), object(),
            names_cache->map());
3545
        HInstruction* index = HLoadKeyed::New(
3546 3547 3548
            block()->graph()->isolate(), block()->graph()->zone(),
            block()->graph()->GetInvalidContext(), index_cache, key_load->key(),
            key_load->key(), key_load->elements_kind());
3549 3550
        map_check->InsertBefore(this);
        index->InsertBefore(this);
3551 3552
        return Prepend(new(block()->zone()) HLoadFieldByIndex(
            object(), index));
3553 3554 3555 3556 3557 3558 3559 3560
      }
    }
  }

  return this;
}


3561 3562
std::ostream& HStoreNamedGeneric::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3563 3564 3565
  Handle<String> n = Handle<String>::cast(name());
  return os << NameOf(object()) << "." << n->ToCString().get() << " = "
            << NameOf(value());
3566 3567 3568
}


3569
std::ostream& HStoreNamedField::PrintDataTo(std::ostream& os) const {  // NOLINT
3570 3571 3572 3573
  os << NameOf(object()) << access_ << " = " << NameOf(value());
  if (NeedsWriteBarrier()) os << " (write-barrier)";
  if (has_transition()) os << " (transition map " << *transition_map() << ")";
  return os;
3574 3575 3576
}


3577
std::ostream& HStoreKeyed::PrintDataTo(std::ostream& os) const {  // NOLINT
3578
  if (!is_fixed_typed_array()) {
3579
    os << NameOf(elements());
3580
  } else {
3581 3582
    DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3583
    os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3584
  }
3585

3586 3587 3588
  os << "[" << NameOf(key());
  if (IsDehoisted()) os << " + " << base_offset();
  return os << "] = " << NameOf(value());
3589 3590 3591
}


3592 3593
std::ostream& HStoreKeyedGeneric::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3594 3595
  return os << NameOf(object()) << "[" << NameOf(key())
            << "] = " << NameOf(value());
3596 3597 3598
}


3599 3600
std::ostream& HTransitionElementsKind::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3601
  os << NameOf(object());
3602 3603
  ElementsKind from_kind = original_map().handle()->elements_kind();
  ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3604 3605 3606 3607 3608 3609
  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;
3610 3611 3612
}


3613 3614
std::ostream& HLoadGlobalGeneric::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3615
  return os << name()->ToCString().get() << " ";
3616 3617 3618
}


3619 3620
std::ostream& HInnerAllocatedObject::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3621 3622
  os << NameOf(base_object()) << " offset ";
  return offset()->PrintTo(os);
3623 3624 3625
}


3626
std::ostream& HLoadContextSlot::PrintDataTo(std::ostream& os) const {  // NOLINT
3627
  return os << NameOf(value()) << "[" << slot_index() << "]";
3628 3629 3630
}


3631 3632
std::ostream& HStoreContextSlot::PrintDataTo(
    std::ostream& os) const {  // NOLINT
3633 3634
  return os << NameOf(context()) << "[" << slot_index()
            << "] = " << NameOf(value());
3635 3636 3637
}


3638 3639 3640
// Implementation of type inference and type conversions. Calculates
// the inferred type of this instruction based on the input operands.

3641
HType HValue::CalculateInferredType() {
3642 3643 3644 3645
  return type_;
}


3646
HType HPhi::CalculateInferredType() {
3647 3648 3649
  if (OperandCount() == 0) return HType::Tagged();
  HType result = OperandAt(0)->type();
  for (int i = 1; i < OperandCount(); ++i) {
3650 3651 3652 3653 3654 3655 3656
    HType current = OperandAt(i)->type();
    result = result.Combine(current);
  }
  return result;
}


3657 3658 3659 3660 3661 3662
HType HChange::CalculateInferredType() {
  if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
  return type();
}


3663
Representation HUnaryMathOperation::RepresentationFromInputs() {
3664 3665 3666 3667 3668 3669
  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();
  }
3670 3671 3672 3673
  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();
3674 3675 3676
  if (!input_rep.IsTagged()) {
    rep = rep.generalize(input_rep);
  }
3677 3678 3679 3680
  return rep;
}


3681
bool HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
3682
                                          HValue* dominator) {
3683
  DCHECK(side_effect == kNewSpacePromotion);
3684
  Zone* zone = block()->zone();
3685
  Isolate* isolate = block()->isolate();
3686
  if (!FLAG_use_allocation_folding) return false;
3687

3688
  // Try to fold allocations together with their dominating allocations.
3689 3690 3691 3692
  if (!dominator->IsAllocate()) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s)\n",
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3693 3694 3695 3696 3697 3698 3699 3700 3701
    }
    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());
3702
    }
3703
    return false;
3704
  }
3705

3706
  HAllocate* dominator_allocate = HAllocate::cast(dominator);
3707 3708
  HValue* dominator_size = dominator_allocate->size();
  HValue* current_size = size();
3709

3710 3711
  // TODO(hpayer): Add support for non-constant allocation in dominator.
  if (!dominator_size->IsInteger32Constant()) {
3712 3713
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s), "
3714
             "dynamic allocation size in dominator\n",
3715 3716 3717 3718 3719
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
    return false;
  }

3720 3721 3722 3723 3724 3725

  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());
    }
3726 3727 3728 3729
    return false;
  }

  if (!has_size_upper_bound()) {
3730
    if (FLAG_trace_allocation_folding) {
3731 3732
      PrintF("#%d (%s) cannot fold into #%d (%s), "
             "can't estimate total allocation size\n",
3733 3734 3735 3736 3737
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
    return false;
  }

3738 3739 3740
  if (!current_size->IsInteger32Constant()) {
    // If it's not constant then it is a size_in_bytes calculation graph
    // like this: (const_header_size + const_element_size * size).
3741
    DCHECK(current_size->IsInstruction());
3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754

    HInstruction* current_instr = HInstruction::cast(current_size);
    if (!current_instr->Dominates(dominator_allocate)) {
      if (FLAG_trace_allocation_folding) {
        PrintF("#%d (%s) cannot fold into #%d (%s), dynamic size "
               "value does not dominate target allocation\n",
            id(), Mnemonic(), dominator_allocate->id(),
            dominator_allocate->Mnemonic());
      }
      return false;
    }
  }

3755 3756
  DCHECK(
      (IsNewSpaceAllocation() && dominator_allocate->IsNewSpaceAllocation()) ||
3757
      (IsOldSpaceAllocation() && dominator_allocate->IsOldSpaceAllocation()));
3758

3759 3760 3761 3762 3763
  // 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;
3764 3765

  if (MustAllocateDoubleAligned()) {
3766 3767
    if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
      dominator_size_constant += kDoubleSize / 2;
3768 3769 3770
    }
  }

3771 3772
  int32_t current_size_max_value = size_upper_bound()->GetInteger32Constant();
  int32_t new_dominator_size = dominator_size_constant + current_size_max_value;
3773

3774 3775
  // Since we clear the first word after folded memory, we cannot use the
  // whole Page::kMaxRegularHeapObjectSize memory.
3776
  if (new_dominator_size > Page::kMaxRegularHeapObjectSize - kPointerSize) {
3777 3778
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3779
          id(), Mnemonic(), dominator_allocate->id(),
3780
          dominator_allocate->Mnemonic(), new_dominator_size);
3781
    }
3782
    return false;
3783
  }
3784

3785 3786 3787
  HInstruction* new_dominator_size_value;

  if (current_size->IsInteger32Constant()) {
3788 3789 3790
    new_dominator_size_value = HConstant::CreateAndInsertBefore(
        isolate, zone, context(), new_dominator_size, Representation::None(),
        dominator_allocate);
3791
  } else {
3792 3793 3794
    HValue* new_dominator_size_constant = HConstant::CreateAndInsertBefore(
        isolate, zone, context(), dominator_size_constant,
        Representation::Integer32(), dominator_allocate);
3795

3796
    // Add old and new size together and insert.
3797
    current_size->ChangeRepresentation(Representation::Integer32());
3798

3799 3800
    new_dominator_size_value = HAdd::New(
        isolate, zone, context(), new_dominator_size_constant, current_size);
3801 3802
    new_dominator_size_value->ClearFlag(HValue::kCanOverflow);
    new_dominator_size_value->ChangeRepresentation(Representation::Integer32());
3803

3804
    new_dominator_size_value->InsertBefore(dominator_allocate);
3805 3806
  }

3807
  dominator_allocate->UpdateSize(new_dominator_size_value);
3808 3809 3810 3811 3812 3813

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

3815
  bool keep_new_space_iterable = FLAG_log_gc || FLAG_heap_stats;
3816
#ifdef VERIFY_HEAP
3817 3818 3819 3820
  keep_new_space_iterable = keep_new_space_iterable || FLAG_verify_heap;
#endif

  if (keep_new_space_iterable && dominator_allocate->IsNewSpaceAllocation()) {
3821
    dominator_allocate->MakePrefillWithFiller();
3822 3823 3824
  } else {
    // TODO(hpayer): This is a short-term hack to make allocation mementos
    // work again in new space.
3825
    dominator_allocate->ClearNextMapWord(original_object_size);
3826
  }
3827

3828
  dominator_allocate->UpdateClearNextMapWord(MustClearNextMapWord());
3829

3830
  // After that replace the dominated allocate instruction.
3831
  HInstruction* inner_offset = HConstant::CreateAndInsertBefore(
3832
      isolate, zone, context(), dominator_size_constant, Representation::None(),
3833 3834
      this);

3835 3836
  HInstruction* dominated_allocate_instr = HInnerAllocatedObject::New(
      isolate, zone, context(), dominator_allocate, inner_offset, type());
3837 3838 3839 3840
  dominated_allocate_instr->InsertBefore(this);
  DeleteAndReplaceWith(dominated_allocate_instr);
  if (FLAG_trace_allocation_folding) {
    PrintF("#%d (%s) folded into #%d (%s)\n",
3841 3842
        id(), Mnemonic(), dominator_allocate->id(),
        dominator_allocate->Mnemonic());
3843
  }
3844
  return true;
3845 3846 3847
}


3848
void HAllocate::UpdateFreeSpaceFiller(int32_t free_space_size) {
3849
  DCHECK(filler_free_space_size_ != NULL);
3850
  Zone* zone = block()->zone();
3851 3852 3853
  // We must explicitly force Smi representation here because on x64 we
  // would otherwise automatically choose int32, but the actual store
  // requires a Smi-tagged value.
3854
  HConstant* new_free_space_size = HConstant::CreateAndInsertBefore(
3855
      block()->isolate(), zone, context(),
3856 3857
      filler_free_space_size_->value()->GetInteger32Constant() +
          free_space_size,
3858
      Representation::Smi(), filler_free_space_size_);
3859 3860 3861 3862 3863
  filler_free_space_size_->UpdateValue(new_free_space_size);
}


void HAllocate::CreateFreeSpaceFiller(int32_t free_space_size) {
3864
  DCHECK(filler_free_space_size_ == NULL);
3865
  Isolate* isolate = block()->isolate();
3866 3867
  Zone* zone = block()->zone();
  HInstruction* free_space_instr =
3868 3869
      HInnerAllocatedObject::New(isolate, zone, context(), dominating_allocate_,
                                 dominating_allocate_->size(), type());
3870
  free_space_instr->InsertBefore(this);
3871
  HConstant* filler_map = HConstant::CreateAndInsertAfter(
3872 3873 3874 3875 3876
      zone, Unique<Map>::CreateImmovable(isolate->factory()->free_space_map()),
      true, free_space_instr);
  HInstruction* store_map =
      HStoreNamedField::New(isolate, zone, context(), free_space_instr,
                            HObjectAccess::ForMap(), filler_map);
3877 3878 3879
  store_map->SetFlag(HValue::kHasNoObservableSideEffects);
  store_map->InsertAfter(filler_map);

3880 3881 3882
  // We must explicitly force Smi representation here because on x64 we
  // would otherwise automatically choose int32, but the actual store
  // requires a Smi-tagged value.
3883 3884 3885
  HConstant* filler_size =
      HConstant::CreateAndInsertAfter(isolate, zone, context(), free_space_size,
                                      Representation::Smi(), store_map);
3886
  // Must force Smi representation for x64 (see comment above).
3887 3888 3889 3890 3891
  HObjectAccess access = HObjectAccess::ForMapAndOffset(
      isolate->factory()->free_space_map(), FreeSpace::kSizeOffset,
      Representation::Smi());
  HStoreNamedField* store_size = HStoreNamedField::New(
      isolate, zone, context(), free_space_instr, access, filler_size);
3892 3893 3894 3895 3896 3897
  store_size->SetFlag(HValue::kHasNoObservableSideEffects);
  store_size->InsertAfter(filler_size);
  filler_free_space_size_ = store_size;
}


3898
void HAllocate::ClearNextMapWord(int offset) {
3899
  if (MustClearNextMapWord()) {
3900
    Zone* zone = block()->zone();
3901 3902 3903
    HObjectAccess access =
        HObjectAccess::ForObservableJSObjectOffset(offset);
    HStoreNamedField* clear_next_map =
3904 3905
        HStoreNamedField::New(block()->isolate(), zone, context(), this, access,
                              block()->graph()->GetConstant0());
3906 3907 3908 3909 3910 3911
    clear_next_map->ClearAllSideEffects();
    clear_next_map->InsertAfter(this);
  }
}


3912
std::ostream& HAllocate::PrintDataTo(std::ostream& os) const {  // NOLINT
3913 3914
  os << NameOf(size()) << " (";
  if (IsNewSpaceAllocation()) os << "N";
3915
  if (IsOldSpaceAllocation()) os << "P";
3916 3917 3918
  if (MustAllocateDoubleAligned()) os << "A";
  if (MustPrefillWithFiller()) os << "F";
  return os << ")";
3919 3920 3921
}


3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
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;
}


3935
bool HStoreKeyed::NeedsCanonicalization() {
3936 3937 3938
  switch (value()->opcode()) {
    case kLoadKeyed: {
      ElementsKind load_kind = HLoadKeyed::cast(value())->elements_kind();
3939
      return IsFixedFloatElementsKind(load_kind);
3940 3941 3942 3943 3944
    }
    case kChange: {
      Representation from = HChange::cast(value())->from();
      return from.IsTagged() || from.IsHeapObject();
    }
3945 3946
    case kLoadNamedField:
    case kPhi: {
3947 3948
      // Better safe than sorry...
      return true;
3949
    }
3950
    default:
3951 3952
      return false;
  }
3953 3954 3955
}


3956 3957 3958 3959
#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))
3960

3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
#define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op)                      \
  HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context,    \
                            HValue* left, HValue* right, Strength strength) { \
    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, strength);                 \
3976
  }
3977 3978 3979 3980 3981 3982 3983 3984 3985


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


3986
HInstruction* HStringAdd::New(Isolate* isolate, Zone* zone, HValue* context,
3987
                              HValue* left, HValue* right,
3988 3989 3990
                              PretenureFlag pretenure_flag,
                              StringAddFlags flags,
                              Handle<AllocationSite> allocation_site) {
3991 3992 3993 3994
  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()) {
3995 3996 3997 3998
      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) {
3999
        MaybeHandle<String> concat = isolate->factory()->NewConsString(
4000
            c_left->StringValue(), c_right->StringValue());
4001
        return HConstant::New(isolate, zone, context, concat.ToHandleChecked());
4002
      }
4003 4004
    }
  }
4005 4006
  return new (zone)
      HStringAdd(context, left, right, pretenure_flag, flags, allocation_site);
4007 4008 4009
}


4010
std::ostream& HStringAdd::PrintDataTo(std::ostream& os) const {  // NOLINT
4011
  if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
4012
    os << "_CheckBoth";
4013
  } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_LEFT) {
4014
    os << "_CheckLeft";
4015
  } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_RIGHT) {
4016
    os << "_CheckRight";
4017
  }
4018 4019 4020 4021 4022 4023 4024
  HBinaryOperation::PrintDataTo(os);
  os << " (";
  if (pretenure_flag() == NOT_TENURED)
    os << "N";
  else if (pretenure_flag() == TENURED)
    os << "D";
  return os << ")";
4025 4026 4027
}


4028 4029
HInstruction* HStringCharFromCode::New(Isolate* isolate, Zone* zone,
                                       HValue* context, HValue* char_code) {
4030 4031 4032
  if (FLAG_fold_constants && char_code->IsConstant()) {
    HConstant* c_code = HConstant::cast(char_code);
    if (c_code->HasNumberValue()) {
4033
      if (std::isfinite(c_code->DoubleValue())) {
4034
        uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
4035 4036
        return HConstant::New(
            isolate, zone, context,
4037
            isolate->factory()->LookupSingleCharacterStringFromCode(code));
4038
      }
4039 4040
      return HConstant::New(isolate, zone, context,
                            isolate->factory()->empty_string());
4041 4042 4043 4044 4045 4046
    }
  }
  return new(zone) HStringCharFromCode(context, char_code);
}


4047 4048 4049
HInstruction* HUnaryMathOperation::New(Isolate* isolate, Zone* zone,
                                       HValue* context, HValue* value,
                                       BuiltinFunctionId op) {
4050 4051 4052 4053 4054 4055
  do {
    if (!FLAG_fold_constants) break;
    if (!value->IsConstant()) break;
    HConstant* constant = HConstant::cast(value);
    if (!constant->HasNumberValue()) break;
    double d = constant->DoubleValue();
4056
    if (std::isnan(d)) {  // NaN poisons everything.
4057
      return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
4058
    }
4059
    if (std::isinf(d)) {  // +Infinity and -Infinity.
4060 4061 4062 4063 4064
      switch (op) {
        case kMathExp:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
        case kMathLog:
        case kMathSqrt:
4065 4066
          return H_CONSTANT_DOUBLE(
              (d > 0.0) ? d : std::numeric_limits<double>::quiet_NaN());
4067 4068 4069 4070
        case kMathPowHalf:
        case kMathAbs:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
        case kMathRound:
4071
        case kMathFround:
4072 4073
        case kMathFloor:
          return H_CONSTANT_DOUBLE(d);
4074 4075
        case kMathClz32:
          return H_CONSTANT_INT(32);
4076 4077 4078 4079 4080 4081 4082 4083 4084
        default:
          UNREACHABLE();
          break;
      }
    }
    switch (op) {
      case kMathExp:
        return H_CONSTANT_DOUBLE(fast_exp(d));
      case kMathLog:
4085
        return H_CONSTANT_DOUBLE(std::log(d));
4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
      case kMathSqrt:
        return H_CONSTANT_DOUBLE(fast_sqrt(d));
      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);
4098
        return H_CONSTANT_DOUBLE(Floor(d + 0.5));
4099 4100
      case kMathFround:
        return H_CONSTANT_DOUBLE(static_cast<double>(static_cast<float>(d)));
4101
      case kMathFloor:
4102
        return H_CONSTANT_DOUBLE(Floor(d));
4103
      case kMathClz32: {
4104
        uint32_t i = DoubleToUint32(d);
4105
        return H_CONSTANT_INT(base::bits::CountLeadingZeros32(i));
4106
      }
4107 4108 4109 4110 4111 4112 4113 4114 4115
      default:
        UNREACHABLE();
        break;
    }
  } while (false);
  return new(zone) HUnaryMathOperation(context, value, op);
}


4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152
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();
}


4153 4154
HInstruction* HPower::New(Isolate* isolate, Zone* zone, HValue* context,
                          HValue* left, HValue* right) {
4155 4156 4157 4158 4159 4160
  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 result = power_helper(c_left->DoubleValue(),
                                   c_right->DoubleValue());
4161 4162 4163
      return H_CONSTANT_DOUBLE(std::isnan(result)
                                   ? std::numeric_limits<double>::quiet_NaN()
                                   : result);
4164 4165 4166 4167 4168 4169
    }
  }
  return new(zone) HPower(left, right);
}


4170 4171
HInstruction* HMathMinMax::New(Isolate* isolate, Zone* zone, HValue* context,
                               HValue* left, HValue* right, Operation op) {
4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
  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.
4196
      return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
4197 4198 4199 4200 4201 4202
    }
  }
  return new(zone) HMathMinMax(context, left, right, op);
}


4203
HInstruction* HMod::New(Isolate* isolate, Zone* zone, HValue* context,
4204
                        HValue* left, HValue* right, Strength strength) {
4205
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4206 4207 4208 4209 4210
    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();
4211 4212 4213
      if (dividend == kMinInt && divisor == -1) {
        return H_CONSTANT_DOUBLE(-0.0);
      }
4214 4215 4216 4217 4218
      if (divisor != 0) {
        int32_t res = dividend % divisor;
        if ((res == 0) && (dividend < 0)) {
          return H_CONSTANT_DOUBLE(-0.0);
        }
4219
        return H_CONSTANT_INT(res);
4220 4221 4222
      }
    }
  }
4223
  return new (zone) HMod(context, left, right, strength);
4224 4225 4226
}


4227
HInstruction* HDiv::New(Isolate* isolate, Zone* zone, HValue* context,
4228
                        HValue* left, HValue* right, Strength strength) {
4229
  // If left and right are constant values, try to return a constant value.
4230
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4231 4232 4233 4234 4235
    HConstant* c_left = HConstant::cast(left);
    HConstant* c_right = HConstant::cast(right);
    if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
      if (c_right->DoubleValue() != 0) {
        double double_res = c_left->DoubleValue() / c_right->DoubleValue();
4236
        if (IsInt32Double(double_res)) {
4237
          return H_CONSTANT_INT(double_res);
4238 4239
        }
        return H_CONSTANT_DOUBLE(double_res);
4240 4241 4242
      } else {
        int sign = Double(c_left->DoubleValue()).Sign() *
                   Double(c_right->DoubleValue()).Sign();  // Right could be -0.
4243
        return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
4244 4245 4246
      }
    }
  }
4247
  return new (zone) HDiv(context, left, right, strength);
4248 4249 4250
}


4251
HInstruction* HBitwise::New(Isolate* isolate, Zone* zone, HValue* context,
conradw's avatar
conradw committed
4252
                            Token::Value op, HValue* left, HValue* right,
4253
                            Strength strength) {
4254
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
    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();
      }
4275
      return H_CONSTANT_INT(result);
4276 4277
    }
  }
4278
  return new (zone) HBitwise(context, op, left, right, strength);
4279 4280 4281
}


4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292
#define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result)                            \
  HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context,    \
                            HValue* left, HValue* right, Strength strength) { \
    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, strength);                 \
4293
  }
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303


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


4304
HInstruction* HShr::New(Isolate* isolate, Zone* zone, HValue* context,
4305
                        HValue* left, HValue* right, Strength strength) {
4306
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4307 4308 4309 4310 4311 4312
    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)) {
4313
        return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
4314
      }
4315
      return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
4316 4317
    }
  }
4318
  return new (zone) HShr(context, left, right, strength);
4319 4320 4321
}


4322 4323 4324
HInstruction* HSeqStringGetChar::New(Isolate* isolate, Zone* zone,
                                     HValue* context, String::Encoding encoding,
                                     HValue* string, HValue* index) {
4325 4326 4327 4328 4329 4330
  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();
4331 4332
      DCHECK_LE(0, i);
      DCHECK_LT(i, s->length());
4333 4334 4335 4336 4337 4338 4339
      return H_CONSTANT_INT(s->Get(i));
    }
  }
  return new(zone) HSeqStringGetChar(encoding, string, index);
}


4340
#undef H_CONSTANT_INT
4341 4342 4343
#undef H_CONSTANT_DOUBLE


4344
std::ostream& HBitwise::PrintDataTo(std::ostream& os) const {  // NOLINT
4345 4346
  os << Token::Name(op_) << " ";
  return HBitwiseBinaryOperation::PrintDataTo(os);
4347 4348 4349
}


4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362
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()) {
4363 4364 4365
      HConstant* integer_input = HConstant::New(
          graph->isolate(), graph->zone(), graph->GetInvalidContext(),
          DoubleToInt32(operand->DoubleValue()));
4366 4367
      integer_input->InsertAfter(operand);
      SetOperandAt(i, integer_input);
4368 4369 4370 4371
    } else if (operand->HasBooleanValue()) {
      SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
                                              : graph->GetConstant0());
    } else if (operand->ImmortalImmovable()) {
4372 4373 4374 4375 4376 4377 4378 4379
      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(
4380
          it.index(), Representation::Smi());
4381 4382 4383 4384 4385
    }
  }
}


4386
void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
4387
  DCHECK(CheckFlag(kFlexibleRepresentation));
4388
  Representation new_rep = RepresentationFromUses();
4389
  UpdateRepresentation(new_rep, h_infer, "uses");
4390 4391
  new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
4392 4393 4394 4395 4396 4397
  new_rep = RepresentationFromUseRequirements();
  UpdateRepresentation(new_rep, h_infer, "use requirements");
}


Representation HPhi::RepresentationFromInputs() {
4398
  Representation r = representation();
4399
  for (int i = 0; i < OperandCount(); ++i) {
4400 4401
    // Ignore conservative Tagged assumption of parameters if we have
    // reason to believe that it's too conservative.
4402 4403 4404
    if (has_type_feedback_from_uses() && OperandAt(i)->IsParameter()) {
      continue;
    }
4405

4406
    r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
4407
  }
4408
  return r;
4409 4410 4411
}


4412 4413 4414 4415
// 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();
4416
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4417
    // Ignore the use requirement from never run code
4418
    if (it.value()->block()->IsUnreachable()) continue;
4419

4420 4421 4422
    // We check for observed_input_representation elsewhere.
    Representation use_rep =
        it.value()->RequiredInputRepresentation(it.index());
4423 4424
    if (rep.IsNone()) {
      rep = use_rep;
4425 4426
      continue;
    }
4427 4428 4429
    if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
    if (rep.generalize(use_rep).IsInteger32()) {
      rep = Representation::Integer32();
4430 4431
      continue;
    }
4432
    return Representation::None();
4433
  }
4434
  return rep;
4435 4436 4437
}


4438 4439 4440 4441 4442
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());
4443 4444 4445 4446 4447
    if (!use_rep.IsNone() &&
        !use_rep.IsSmi() &&
        !use_rep.IsTagged()) {
      return true;
    }
4448 4449 4450 4451 4452
  }
  return false;
}


4453 4454 4455
// Node-specific verification code is only included in debug mode.
#ifdef DEBUG

4456
void HPhi::Verify() {
4457
  DCHECK(OperandCount() == block()->predecessors()->length());
4458 4459 4460 4461
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* value = OperandAt(i);
    HBasicBlock* defining_block = value->block();
    HBasicBlock* predecessor_block = block()->predecessors()->at(i);
4462
    DCHECK(defining_block == predecessor_block ||
4463 4464 4465 4466 4467
           defining_block->Dominates(predecessor_block));
  }
}


4468
void HSimulate::Verify() {
4469
  HInstruction::Verify();
4470
  DCHECK(HasAstId() || next()->IsEnterInlined());
4471 4472 4473
}


4474
void HCheckHeapObject::Verify() {
4475
  HInstruction::Verify();
4476
  DCHECK(HasNoUses());
4477 4478 4479
}


4480
void HCheckValue::Verify() {
4481
  HInstruction::Verify();
4482
  DCHECK(HasNoUses());
4483 4484 4485 4486
}

#endif

4487 4488

HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
4489 4490
  DCHECK(offset >= 0);
  DCHECK(offset < FixedArray::kHeaderSize);
4491 4492 4493 4494 4495
  if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
  return HObjectAccess(kInobject, offset);
}


4496
HObjectAccess HObjectAccess::ForMapAndOffset(Handle<Map> map, int offset,
4497
    Representation representation) {
4498
  DCHECK(offset >= 0);
4499 4500 4501 4502 4503 4504 4505
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
4506 4507 4508 4509 4510 4511 4512
  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);
4513 4514 4515
}


4516 4517 4518 4519 4520 4521
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());
4522
    case AllocationSite::kPretenureDataOffset:
4523
      return HObjectAccess(kInobject, offset, Representation::Smi());
4524
    case AllocationSite::kPretenureCreateCountOffset:
4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
      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);
}


4537
HObjectAccess HObjectAccess::ForContextSlot(int index) {
4538
  DCHECK(index >= 0);
4539 4540
  Portion portion = kInobject;
  int offset = Context::kHeaderSize + index * kPointerSize;
4541
  DCHECK_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
4542 4543 4544 4545
  return HObjectAccess(portion, offset, Representation::Tagged());
}


4546
HObjectAccess HObjectAccess::ForScriptContext(int index) {
4547 4548
  DCHECK(index >= 0);
  Portion portion = kInobject;
4549
  int offset = ScriptContextTable::GetContextOffset(index);
4550 4551 4552 4553
  return HObjectAccess(portion, offset, Representation::Tagged());
}


4554
HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
4555
  DCHECK(offset >= 0);
4556 4557 4558 4559 4560 4561 4562 4563 4564
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSArray::kLengthOffset) {
    portion = kArrayLengths;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
4565
  return HObjectAccess(portion, offset);
4566 4567 4568
}


4569 4570
HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
    Representation representation) {
4571
  DCHECK(offset >= 0);
4572 4573
  return HObjectAccess(kBackingStore, offset, representation,
                       Handle<String>::null(), false, false);
4574 4575 4576
}


4577 4578
HObjectAccess HObjectAccess::ForField(Handle<Map> map, int index,
                                      Representation representation,
4579
                                      Handle<Name> name) {
4580 4581 4582 4583
  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();
4584
    return HObjectAccess(kInobject, offset, representation, name, false, true);
4585 4586 4587
  } else {
    // Non-negative property indices are in the properties array.
    int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
4588 4589
    return HObjectAccess(kBackingStore, offset, representation, name,
                         false, false);
4590 4591 4592 4593
  }
}


4594
void HObjectAccess::SetGVNFlags(HValue *instr, PropertyAccessType access_type) {
4595
  // set the appropriate GVN flags for a given load or store instruction
4596
  if (access_type == STORE) {
4597
    // track dominating allocations in order to eliminate write barriers
4598
    instr->SetDependsOnFlag(::v8::internal::kNewSpacePromotion);
4599 4600 4601 4602
    instr->SetFlag(HValue::kTrackSideEffectDominators);
  } else {
    // try to GVN loads, but don't hoist above map changes
    instr->SetFlag(HValue::kUseGVN);
4603
    instr->SetDependsOnFlag(::v8::internal::kMaps);
4604 4605 4606 4607
  }

  switch (portion()) {
    case kArrayLengths:
4608 4609 4610 4611 4612
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kArrayLengths);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kArrayLengths);
      }
4613
      break;
4614
    case kStringLengths:
4615 4616 4617 4618 4619
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kStringLengths);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kStringLengths);
      }
4620
      break;
4621
    case kInobject:
4622 4623 4624 4625 4626
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kInobjectFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kInobjectFields);
      }
4627 4628
      break;
    case kDouble:
4629 4630 4631 4632 4633
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kDoubleFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kDoubleFields);
      }
4634 4635
      break;
    case kBackingStore:
4636 4637 4638 4639 4640
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kBackingStoreFields);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kBackingStoreFields);
      }
4641 4642
      break;
    case kElementsPointer:
4643 4644 4645 4646 4647
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kElementsPointer);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kElementsPointer);
      }
4648 4649
      break;
    case kMaps:
4650 4651 4652 4653 4654
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kMaps);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kMaps);
      }
4655
      break;
4656
    case kExternalMemory:
4657 4658 4659 4660 4661
      if (access_type == STORE) {
        instr->SetChangesFlag(::v8::internal::kExternalMemory);
      } else {
        instr->SetDependsOnFlag(::v8::internal::kExternalMemory);
      }
4662
      break;
4663 4664 4665 4666
  }
}


4667
std::ostream& operator<<(std::ostream& os, const HObjectAccess& access) {
4668
  os << ".";
4669

4670 4671 4672 4673
  switch (access.portion()) {
    case HObjectAccess::kArrayLengths:
    case HObjectAccess::kStringLengths:
      os << "%length";
4674
      break;
4675 4676
    case HObjectAccess::kElementsPointer:
      os << "%elements";
4677
      break;
4678 4679
    case HObjectAccess::kMaps:
      os << "%map";
4680
      break;
4681 4682
    case HObjectAccess::kDouble:  // fall through
    case HObjectAccess::kInobject:
4683
      if (!access.name().is_null() && access.name()->IsString()) {
4684
        os << Handle<String>::cast(access.name())->ToCString().get();
4685
      }
4686
      os << "[in-object]";
4687
      break;
4688
    case HObjectAccess::kBackingStore:
4689
      if (!access.name().is_null() && access.name()->IsString()) {
4690
        os << Handle<String>::cast(access.name())->ToCString().get();
4691
      }
4692
      os << "[backing-store]";
4693
      break;
4694 4695
    case HObjectAccess::kExternalMemory:
      os << "[external-memory]";
4696
      break;
4697 4698
  }

4699
  return os << "@" << access.offset();
4700 4701
}

4702 4703
}  // namespace internal
}  // namespace v8