hydrogen-instructions.cc 131 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

30
#include "double.h"
31
#include "factory.h"
32
#include "hydrogen-infer-representation.h"
33 34 35 36 37 38 39

#if V8_TARGET_ARCH_IA32
#include "ia32/lithium-ia32.h"
#elif V8_TARGET_ARCH_X64
#include "x64/lithium-x64.h"
#elif V8_TARGET_ARCH_ARM
#include "arm/lithium-arm.h"
40 41
#elif V8_TARGET_ARCH_MIPS
#include "mips/lithium-mips.h"
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#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


57 58 59 60 61 62 63 64
int HValue::LoopWeight() const {
  const int w = FLAG_loop_weight;
  static const int weights[] = { 1, w, w*w, w*w*w, w*w*w*w };
  return weights[Min(block()->LoopNestingDepth(),
                     static_cast<int>(ARRAY_SIZE(weights)-1))];
}


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


71 72 73 74 75 76 77 78 79 80
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);
  }
}


81
void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
82 83 84 85 86
  ASSERT(CheckFlag(kFlexibleRepresentation));
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  new_rep = RepresentationFromUses();
  UpdateRepresentation(new_rep, h_infer, "uses");
87 88 89
  if (representation().IsSmi() && HasNonSmiUse()) {
    UpdateRepresentation(
        Representation::Integer32(), h_infer, "use requirements");
90
  }
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
}


Representation HValue::RepresentationFromUses() {
  if (HasNoUses()) return Representation::None();

  // Array of use counts for each representation.
  int use_count[Representation::kNumRepresentations] = { 0 };

  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
    Representation rep = use->observed_input_representation(it.index());
    if (rep.IsNone()) continue;
    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" : ""));
    }
    use_count[rep.kind()] += use->LoopWeight();
  }
  if (IsPhi()) HPhi::cast(this)->AddIndirectUsesTo(&use_count[0]);
  int tagged_count = use_count[Representation::kTagged];
  int double_count = use_count[Representation::kDouble];
  int int32_count = use_count[Representation::kInteger32];
115
  int smi_count = use_count[Representation::kSmi];
116 117 118 119

  if (tagged_count > 0) return Representation::Tagged();
  if (double_count > 0) return Representation::Double();
  if (int32_count > 0) return Representation::Integer32();
120
  if (smi_count > 0) return Representation::Smi();
121 122 123 124 125 126

  return Representation::None();
}


void HValue::UpdateRepresentation(Representation new_rep,
127
                                  HInferRepresentationPhase* h_infer,
128 129 130
                                  const char* reason) {
  Representation r = representation();
  if (new_rep.is_more_general_than(r)) {
131
    if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
132 133 134
    if (FLAG_trace_representation) {
      PrintF("Changing #%d %s representation %s -> %s based on %s\n",
             id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
135 136 137 138 139 140 141
    }
    ChangeRepresentation(new_rep);
    AddDependantsToWorklist(h_infer);
  }
}


142
void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
143 144 145 146 147 148 149 150 151
  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));
  }
}


152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
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;
    }
173
  }
174
  return static_cast<int32_t>(result);
175 176 177
}


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


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


196 197 198 199
static int32_t MulWithoutOverflow(const Representation& r,
                                  int32_t a,
                                  int32_t b,
                                  bool* overflow) {
200
  int64_t result = static_cast<int64_t>(a) * static_cast<int64_t>(b);
201
  return ConvertAndSetOverflow(r, result, overflow);
202 203 204
}


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


218
void Range::AddConstant(int32_t value) {
219
  if (value == 0) return;
220
  bool may_overflow = false;  // Overflow is ignored here.
221 222 223
  Representation r = Representation::Integer32();
  lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
224
#ifdef DEBUG
225
  Verify();
226
#endif
227 228 229
}


230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
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);
}


246 247 248 249 250 251 252 253 254 255 256 257 258 259
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());
}


260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
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);
}


282
bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
283
  bool may_overflow = false;
284 285
  lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
  upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
286
  KeepOrder();
287
#ifdef DEBUG
288
  Verify();
289
#endif
290
  return may_overflow;
291 292 293
}


294
bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
295
  bool may_overflow = false;
296 297
  lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
  upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
298
  KeepOrder();
299
#ifdef DEBUG
300
  Verify();
301
#endif
302
  return may_overflow;
303 304 305 306 307 308 309 310 311 312 313 314
}


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


315
#ifdef DEBUG
316 317 318
void Range::Verify() const {
  ASSERT(lower_ <= upper_);
}
319
#endif
320 321


322
bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
323
  bool may_overflow = false;
324 325 326 327
  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);
328 329
  lower_ = Min(Min(v1, v2), Min(v3, v4));
  upper_ = Max(Max(v1, v2), Max(v3, v4));
330
#ifdef DEBUG
331
  Verify();
332
#endif
333 334 335 336 337
  return may_overflow;
}


const char* HType::ToString() {
338 339
  // Note: The c1visualizer syntax for locals allows only a sequence of the
  // following characters: A-Za-z0-9_-|:
340
  switch (type_) {
341
    case kNone: return "none";
342 343 344 345 346 347 348 349 350 351 352 353
    case kTagged: return "tagged";
    case kTaggedPrimitive: return "primitive";
    case kTaggedNumber: return "number";
    case kSmi: return "smi";
    case kHeapNumber: return "heap-number";
    case kString: return "string";
    case kBoolean: return "boolean";
    case kNonPrimitive: return "non-primitive";
    case kJSArray: return "array";
    case kJSObject: return "object";
  }
  UNREACHABLE();
354
  return "unreachable";
355 356 357
}


358
HType HType::TypeFromValue(Handle<Object> value) {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  HType result = HType::Tagged();
  if (value->IsSmi()) {
    result = HType::Smi();
  } else if (value->IsHeapNumber()) {
    result = HType::HeapNumber();
  } else if (value->IsString()) {
    result = HType::String();
  } else if (value->IsBoolean()) {
    result = HType::Boolean();
  } else if (value->IsJSObject()) {
    result = HType::JSObject();
  } else if (value->IsJSArray()) {
    result = HType::JSArray();
  }
  return result;
}


377 378 379 380 381
bool HValue::IsDefinedAfter(HBasicBlock* other) const {
  return block()->block_id() > other->block_id();
}


382 383 384 385 386 387 388 389 390
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_;
}


391
bool HValue::CheckUsesForFlag(Flag f) const {
392
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
393
    if (it.value()->IsSimulate()) continue;
394 395 396
    if (!it.value()->CheckFlag(f)) return false;
  }
  return true;
397 398 399 400 401 402 403 404 405 406 407 408
}


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;
409 410 411
}


412
bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
413 414 415 416 417 418 419 420 421 422
  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;
}


423 424 425 426 427 428 429 430 431 432 433
HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
  Advance();
}


void HUseIterator::Advance() {
  current_ = next_;
  if (current_ != NULL) {
    next_ = current_->tail();
    value_ = current_->value();
    index_ = current_->index();
434 435 436 437
  }
}


438 439 440 441
int HValue::UseCount() const {
  int count = 0;
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
  return count;
442 443 444
}


445 446 447 448 449 450 451 452 453 454 455
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;
456
    }
457 458 459

    previous = current;
    current = current->tail();
460
  }
461 462 463 464 465

#ifdef DEBUG
  // Do not reuse use list nodes in debug mode, zap them.
  if (current != NULL) {
    HUseListNode* temp =
466 467
        new(block()->zone())
        HUseListNode(current->value(), current->index(), NULL);
468 469 470 471 472
    current->Zap();
    current = temp;
  }
#endif
  return current;
473 474 475
}


476
bool HValue::Equals(HValue* other) {
477 478 479
  if (other->opcode() != opcode()) return false;
  if (!other->representation().Equals(representation())) return false;
  if (!other->type_.Equals(type_)) return false;
480
  if (other->flags() != flags()) return false;
481 482 483 484 485 486 487 488 489 490
  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);
  ASSERT(!result || Hashcode() == other->Hashcode());
  return result;
}


491
intptr_t HValue::Hashcode() {
492 493 494 495 496 497 498 499 500
  intptr_t result = opcode();
  int count = OperandCount();
  for (int i = 0; i < count; ++i) {
    result = result * 19 + OperandAt(i)->id() + (result >> 7);
  }
  return result;
}


501 502 503 504 505 506 507 508 509 510 511
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 "";
  }
}


512 513 514 515 516 517 518 519 520 521 522
bool HValue::CanReplaceWithDummyUses() {
  return FLAG_unreachable_code_elimination &&
      !(block()->IsReachable() ||
        IsBlockEntry() ||
        IsControlInstruction() ||
        IsSimulate() ||
        IsEnterInlined() ||
        IsLeaveInlined());
}


523 524 525 526 527 528 529 530 531 532
bool HValue::IsInteger32Constant() {
  return IsConstant() && HConstant::cast(this)->HasInteger32Value();
}


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


533 534 535 536 537
bool HValue::EqualsInteger32Constant(int32_t value) {
  return IsInteger32Constant() && GetInteger32Constant() == value;
}


538 539 540 541 542 543
void HValue::SetOperandAt(int index, HValue* value) {
  RegisterUse(index, value);
  InternalSetOperandAt(index, value);
}


544 545 546
void HValue::DeleteAndReplaceWith(HValue* other) {
  // We replace all uses first, so Delete can assert that there are none.
  if (other != NULL) ReplaceAllUsesWith(other);
547
  Kill();
548 549 550 551
  DeleteFromGraph();
}


552 553 554 555 556 557 558 559 560
void HValue::ReplaceAllUsesWith(HValue* other) {
  while (use_list_ != NULL) {
    HUseListNode* list_node = use_list_;
    HValue* value = list_node->value();
    ASSERT(!value->block()->IsStartBlock());
    value->InternalSetOperandAt(list_node->index(), other);
    use_list_ = list_node->tail();
    list_node->set_tail(other->use_list_);
    other->use_list_ = list_node;
561 562 563 564
  }
}


565 566 567 568 569
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);
570
  for (int i = 0; i < OperandCount(); ++i) {
571
    HValue* operand = OperandAt(i);
572
    if (operand == NULL) continue;
573
    HUseListNode* first = operand->use_list_;
574
    if (first != NULL && first->value()->CheckFlag(kIsDead)) {
575 576
      operand->use_list_ = first->tail();
    }
577 578 579 580 581 582 583 584 585 586 587 588 589
  }
}


void HValue::SetBlock(HBasicBlock* block) {
  ASSERT(block_ == NULL || block == NULL);
  block_ = block;
  if (id_ == kNoNumber && block != NULL) {
    id_ = block->graph()->GetNextValueID(this);
  }
}


590 591
void HValue::PrintTypeTo(StringStream* stream) {
  if (!representation().IsTagged() || type().Equals(HType::Tagged())) return;
592
  stream->Add(" type:%s", type().ToString());
593 594 595 596 597
}


void HValue::PrintRangeTo(StringStream* stream) {
  if (range() == NULL || range()->IsMostGeneric()) return;
598 599 600
  // Note: The c1visualizer syntax for locals allows only a sequence of the
  // following characters: A-Za-z0-9_-|:
  stream->Add(" range:%d_%d%s",
601 602
              range()->lower(),
              range()->upper(),
603
              range()->CanBeMinusZero() ? "_m0" : "");
604 605 606 607
}


void HValue::PrintChangesTo(StringStream* stream) {
608 609
  GVNFlagSet changes_flags = ChangesFlags();
  if (changes_flags.IsEmpty()) return;
610
  stream->Add(" changes[");
611
  if (changes_flags == AllSideEffectsFlagSet()) {
612 613 614
    stream->Add("*");
  } else {
    bool add_comma = false;
615 616 617 618 619
#define PRINT_DO(type)                            \
    if (changes_flags.Contains(kChanges##type)) { \
      if (add_comma) stream->Add(",");            \
      add_comma = true;                           \
      stream->Add(#type);                         \
620
    }
621 622
    GVN_TRACKED_FLAG_LIST(PRINT_DO);
    GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
623 624 625
#undef PRINT_DO
  }
  stream->Add("]");
626 627 628 629 630 631 632 633
}


void HValue::PrintNameTo(StringStream* stream) {
  stream->Add("%s%d", representation_.Mnemonic(), id());
}


634 635 636 637 638
bool HValue::HasMonomorphicJSObjectType() {
  return !GetMonomorphicJSObjectMap().is_null();
}


639 640 641 642 643 644 645 646 647 648 649
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;
650 651 652 653 654 655

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

656
  if (new_value != NULL) {
657
    if (removed == NULL) {
658 659
      new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
          this, index, new_value->use_list_);
660 661 662 663
    } else {
      removed->set_tail(new_value->use_list_);
      new_value->use_list_ = removed;
    }
664 665 666 667
  }
}


668 669 670
void HValue::AddNewRange(Range* r, Zone* zone) {
  if (!HasRange()) ComputeInitialRange(zone);
  if (!HasRange()) range_ = new(zone) Range();
671 672 673 674 675 676 677 678 679 680 681 682 683
  ASSERT(HasRange());
  r->StackUpon(range_);
  range_ = r;
}


void HValue::RemoveLastAddedRange() {
  ASSERT(HasRange());
  ASSERT(range_->next() != NULL);
  range_ = range_->next();
}


684
void HValue::ComputeInitialRange(Zone* zone) {
685
  ASSERT(!HasRange());
686
  range_ = InferRange(zone);
687 688 689 690
  ASSERT(HasRange());
}


691
void HInstruction::PrintTo(StringStream* stream) {
692
  PrintMnemonicTo(stream);
693
  PrintDataTo(stream);
694 695 696
  PrintRangeTo(stream);
  PrintChangesTo(stream);
  PrintTypeTo(stream);
697 698 699
  if (CheckFlag(HValue::kHasNoObservableSideEffects)) {
    stream->Add(" [noOSE]");
  }
700
}
701 702


703 704 705 706 707 708 709 710
void HInstruction::PrintDataTo(StringStream *stream) {
  for (int i = 0; i < OperandCount(); ++i) {
    if (i > 0) stream->Add(" ");
    OperandAt(i)->PrintNameTo(stream);
  }
}


711
void HInstruction::PrintMnemonicTo(StringStream* stream) {
712
  stream->Add("%s ", Mnemonic());
713 714 715 716 717 718
}


void HInstruction::Unlink() {
  ASSERT(IsLinked());
  ASSERT(!IsControlInstruction());  // Must never move control instructions.
719 720 721 722 723 724 725 726 727
  ASSERT(!IsBlockEntry());  // Doesn't make sense to delete these.
  ASSERT(previous_ != NULL);
  previous_->next_ = next_;
  if (next_ == NULL) {
    ASSERT(block()->last() == this);
    block()->set_last(previous_);
  } else {
    next_->previous_ = previous_;
  }
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
  clear_block();
}


void HInstruction::InsertBefore(HInstruction* next) {
  ASSERT(!IsLinked());
  ASSERT(!next->IsBlockEntry());
  ASSERT(!IsControlInstruction());
  ASSERT(!next->block()->IsStartBlock());
  ASSERT(next->previous_ != NULL);
  HInstruction* prev = next->previous();
  prev->next_ = this;
  next->previous_ = this;
  next_ = next;
  previous_ = prev;
  SetBlock(next->block());
744 745 746 747
  if (position() == RelocInfo::kNoPosition &&
      next->position() != RelocInfo::kNoPosition) {
    set_position(next->position());
  }
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
}


void HInstruction::InsertAfter(HInstruction* previous) {
  ASSERT(!IsLinked());
  ASSERT(!previous->IsControlInstruction());
  ASSERT(!IsControlInstruction() || previous->next_ == NULL);
  HBasicBlock* block = previous->block();
  // Never insert anything except constants into the start block after finishing
  // it.
  if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
    ASSERT(block->end()->SecondSuccessor() == NULL);
    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_;
768
  if (previous->HasObservableSideEffects() && next != NULL) {
769 770 771 772 773 774 775 776 777 778
    ASSERT(next->IsSimulate());
    previous = next;
    next = previous->next_;
  }

  previous_ = previous;
  next_ = next;
  SetBlock(block);
  previous->next_ = this;
  if (next != NULL) next->previous_ = this;
779 780 781
  if (block->last() == previous) {
    block->set_last(this);
  }
782 783 784 785
  if (position() == RelocInfo::kNoPosition &&
      previous->position() != RelocInfo::kNoPosition) {
    set_position(previous->position());
  }
786 787 788 789
}


#ifdef DEBUG
790
void HInstruction::Verify() {
791 792 793 794
  // Verify that input operands are defined before use.
  HBasicBlock* cur_block = block();
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* other_operand = OperandAt(i);
795
    if (other_operand == NULL) continue;
796 797 798
    HBasicBlock* other_block = other_operand->block();
    if (cur_block == other_block) {
      if (!other_operand->IsPhi()) {
799
        HInstruction* cur = this->previous();
800 801
        while (cur != NULL) {
          if (cur == other_operand) break;
802
          cur = cur->previous();
803 804 805 806 807
        }
        // Must reach other operand in the same block!
        ASSERT(cur == other_operand);
      }
    } else {
808 809
      // If the following assert fires, you may have forgotten an
      // AddInstruction.
810 811 812 813 814 815
      ASSERT(other_block->Dominates(cur_block));
    }
  }

  // Verify that instructions that may have side-effects are followed
  // by a simulate instruction.
816
  if (HasObservableSideEffects() && !IsOsrEntry()) {
817 818
    ASSERT(next()->IsSimulate());
  }
819 820 821 822 823

  // 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);
824 825 826 827 828 829 830

  // Verify that all uses are in the graph.
  for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
    if (use.value()->IsInstruction()) {
      ASSERT(HInstruction::cast(use.value())->IsLinked());
    }
  }
831 832 833 834
}
#endif


835 836 837 838 839
void HDummyUse::PrintDataTo(StringStream* stream) {
  value()->PrintNameTo(stream);
}


840 841 842 843 844
void HEnvironmentMarker::PrintDataTo(StringStream* stream) {
  stream->Add("%s var[%d]", kind() == BIND ? "bind" : "lookup", index());
}


845
void HUnaryCall::PrintDataTo(StringStream* stream) {
846 847
  value()->PrintNameTo(stream);
  stream->Add(" ");
848
  stream->Add("#%d", argument_count());
849 850 851
}


852
void HBinaryCall::PrintDataTo(StringStream* stream) {
853 854 855 856
  first()->PrintNameTo(stream);
  stream->Add(" ");
  second()->PrintNameTo(stream);
  stream->Add(" ");
857
  stream->Add("#%d", argument_count());
858 859 860
}


861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
void HBoundsCheck::ApplyIndexChange() {
  if (skip_check()) return;

  DecompositionResult decomposition;
  bool index_is_decomposable = index()->TryDecompose(&decomposition);
  if (index_is_decomposable) {
    ASSERT(decomposition.base() == base());
    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();

880 881
  Zone* zone = block()->graph()->zone();
  HValue* context = block()->graph()->GetInvalidContext();
882
  if (actual_offset != 0) {
883
    HConstant* add_offset = HConstant::New(zone, context, actual_offset);
884
    add_offset->InsertBefore(this);
885 886
    HInstruction* add = HAdd::New(zone, context,
                                  current_index, add_offset);
887 888
    add->InsertBefore(this);
    add->AssumeRepresentation(index()->representation());
889
    add->ClearFlag(kCanOverflow);
890 891 892 893
    current_index = add;
  }

  if (actual_scale != 0) {
894
    HConstant* sar_scale = HConstant::New(zone, context, actual_scale);
895
    sar_scale->InsertBefore(this);
896 897
    HInstruction* sar = HSar::New(zone, context,
                                  current_index, sar_scale);
898 899 900 901 902 903 904 905 906 907
    sar->InsertBefore(this);
    sar->AssumeRepresentation(index()->representation());
    current_index = sar;
  }

  SetOperandAt(0, current_index);

  base_ = NULL;
  offset_ = 0;
  scale_ = 0;
908 909 910
}


911 912 913 914
void HBoundsCheck::PrintDataTo(StringStream* stream) {
  index()->PrintNameTo(stream);
  stream->Add(" ");
  length()->PrintNameTo(stream);
915 916 917 918 919 920 921 922 923
  if (base() != NULL && (offset() != 0 || scale() != 0)) {
    stream->Add(" base: ((");
    if (base() != index()) {
      index()->PrintNameTo(stream);
    } else {
      stream->Add("index");
    }
    stream->Add(" + %d) >> %d)", offset(), scale());
  }
924 925 926
  if (skip_check()) {
    stream->Add(" [DISABLED]");
  }
927 928
}

929

930
void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
931
  ASSERT(CheckFlag(kFlexibleRepresentation));
932
  HValue* actual_index = index()->ActualValue();
933 934
  HValue* actual_length = length()->ActualValue();
  Representation index_rep = actual_index->representation();
935
  Representation length_rep = actual_length->representation();
936 937 938 939 940 941
  if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
    index_rep = Representation::Smi();
  }
  if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
    length_rep = Representation::Smi();
  }
942 943
  Representation r = index_rep.generalize(length_rep);
  if (r.is_more_general_than(Representation::Integer32())) {
944 945 946 947 948 949
    r = Representation::Integer32();
  }
  UpdateRepresentation(r, h_infer, "boundscheck");
}


950 951 952 953 954 955 956 957
void HBoundsCheckBaseIndexInformation::PrintDataTo(StringStream* stream) {
  stream->Add("base: ");
  base_index()->PrintNameTo(stream);
  stream->Add(", check: ");
  base_index()->PrintNameTo(stream);
}


958
void HCallConstantFunction::PrintDataTo(StringStream* stream) {
959 960 961 962
  if (IsApplyFunction()) {
    stream->Add("optimized apply ");
  } else {
    stream->Add("%o ", function()->shared()->DebugName());
963
  }
964
  stream->Add("#%d", argument_count());
965 966 967
}


968
void HCallNamed::PrintDataTo(StringStream* stream) {
969 970 971 972 973
  stream->Add("%o ", *name());
  HUnaryCall::PrintDataTo(stream);
}


974
void HCallGlobal::PrintDataTo(StringStream* stream) {
975 976 977 978 979
  stream->Add("%o ", *name());
  HUnaryCall::PrintDataTo(stream);
}


980
void HCallKnownGlobal::PrintDataTo(StringStream* stream) {
981
  stream->Add("%o ", target()->shared()->DebugName());
982
  stream->Add("#%d", argument_count());
983 984 985
}


986 987 988 989 990 991 992
void HCallNewArray::PrintDataTo(StringStream* stream) {
  stream->Add(ElementsKindToString(elements_kind()));
  stream->Add(" ");
  HBinaryCall::PrintDataTo(stream);
}


993
void HCallRuntime::PrintDataTo(StringStream* stream) {
994
  stream->Add("%o ", *name());
995 996 997
  if (save_doubles() == kSaveFPRegs) {
    stream->Add("[save doubles] ");
  }
998
  stream->Add("#%d", argument_count());
999 1000 1001
}


1002
void HClassOfTestAndBranch::PrintDataTo(StringStream* stream) {
1003
  stream->Add("class_of_test(");
1004
  value()->PrintNameTo(stream);
1005 1006 1007 1008
  stream->Add(", \"%o\")", *class_name());
}


1009 1010 1011 1012 1013 1014 1015
void HWrapReceiver::PrintDataTo(StringStream* stream) {
  receiver()->PrintNameTo(stream);
  stream->Add(" ");
  function()->PrintNameTo(stream);
}


1016
void HAccessArgumentsAt::PrintDataTo(StringStream* stream) {
1017 1018 1019 1020 1021 1022 1023 1024
  arguments()->PrintNameTo(stream);
  stream->Add("[");
  index()->PrintNameTo(stream);
  stream->Add("], length ");
  length()->PrintNameTo(stream);
}


1025
void HControlInstruction::PrintDataTo(StringStream* stream) {
1026 1027 1028 1029 1030
  stream->Add(" goto (");
  bool first_block = true;
  for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
    stream->Add(first_block ? "B%d" : ", B%d", it.Current()->block_id());
    first_block = false;
1031
  }
1032
  stream->Add(")");
1033 1034 1035
}


1036
void HUnaryControlInstruction::PrintDataTo(StringStream* stream) {
1037
  value()->PrintNameTo(stream);
1038
  HControlInstruction::PrintDataTo(stream);
1039 1040 1041
}


1042 1043
void HReturn::PrintDataTo(StringStream* stream) {
  value()->PrintNameTo(stream);
1044 1045 1046
  stream->Add(" (pop ");
  parameter_count()->PrintNameTo(stream);
  stream->Add(" values)");
1047 1048 1049
}


1050 1051 1052 1053
Representation HBranch::observed_input_representation(int index) {
  static const ToBooleanStub::Types tagged_types(
      ToBooleanStub::NULL_TYPE |
      ToBooleanStub::SPEC_OBJECT |
1054 1055
      ToBooleanStub::STRING |
      ToBooleanStub::SYMBOL);
1056 1057
  if (expected_input_types_.ContainsAnyOf(tagged_types)) {
    return Representation::Tagged();
1058 1059 1060 1061 1062 1063 1064 1065
  }
  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)) {
1066
    return Representation::Double();
1067 1068
  }
  if (expected_input_types_.Contains(ToBooleanStub::SMI)) {
1069
    return Representation::Smi();
1070
  }
1071
  return Representation::None();
1072 1073 1074
}


1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
  HValue* value = this->value();
  if (value->EmitAtUses()) {
    ASSERT(value->IsConstant());
    ASSERT(!value->representation().IsDouble());
    *block = HConstant::cast(value)->BooleanValue()
        ? FirstSuccessor()
        : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


1090
void HCompareMap::PrintDataTo(StringStream* stream) {
1091
  value()->PrintNameTo(stream);
1092
  stream->Add(" (%p)", *map().handle());
1093
  HControlInstruction::PrintDataTo(stream);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
}


const char* HUnaryMathOperation::OpName() const {
  switch (op()) {
    case kMathFloor: return "floor";
    case kMathRound: return "round";
    case kMathAbs: return "abs";
    case kMathLog: return "log";
    case kMathSin: return "sin";
    case kMathCos: return "cos";
    case kMathTan: return "tan";
    case kMathExp: return "exp";
    case kMathSqrt: return "sqrt";
1108 1109 1110 1111
    case kMathPowHalf: return "pow-half";
    default:
      UNREACHABLE();
      return NULL;
1112 1113 1114 1115
  }
}


1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
Range* HUnaryMathOperation::InferRange(Zone* zone) {
  Representation r = representation();
  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);
}


1140
void HUnaryMathOperation::PrintDataTo(StringStream* stream) {
1141 1142 1143 1144 1145 1146
  const char* name = OpName();
  stream->Add("%s ", name);
  value()->PrintNameTo(stream);
}


1147
void HUnaryOperation::PrintDataTo(StringStream* stream) {
1148 1149 1150 1151
  value()->PrintNameTo(stream);
}


1152
void HHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) {
1153 1154
  value()->PrintNameTo(stream);
  switch (from_) {
1155
    case FIRST_JS_RECEIVER_TYPE:
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
      if (to_ == LAST_TYPE) stream->Add(" spec_object");
      break;
    case JS_REGEXP_TYPE:
      if (to_ == JS_REGEXP_TYPE) stream->Add(" reg_exp");
      break;
    case JS_ARRAY_TYPE:
      if (to_ == JS_ARRAY_TYPE) stream->Add(" array");
      break;
    case JS_FUNCTION_TYPE:
      if (to_ == JS_FUNCTION_TYPE) stream->Add(" function");
      break;
    default:
      break;
  }
}


1173
void HTypeofIsAndBranch::PrintDataTo(StringStream* stream) {
1174
  value()->PrintNameTo(stream);
1175
  stream->Add(" == %o", *type_literal_);
1176 1177 1178 1179
  HControlInstruction::PrintDataTo(stream);
}


1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
void HCheckMapValue::PrintDataTo(StringStream* stream) {
  value()->PrintNameTo(stream);
  stream->Add(" ");
  map()->PrintNameTo(stream);
}


void HForInPrepareMap::PrintDataTo(StringStream* stream) {
  enumerable()->PrintNameTo(stream);
}


void HForInCacheArray::PrintDataTo(StringStream* stream) {
  enumerable()->PrintNameTo(stream);
  stream->Add(" ");
  map()->PrintNameTo(stream);
  stream->Add("[%d]", idx_);
}


void HLoadFieldByIndex::PrintDataTo(StringStream* stream) {
  object()->PrintNameTo(stream);
  stream->Add(" ");
  index()->PrintNameTo(stream);
}


1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
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);
}


1230
HValue* HBitwise::Canonicalize() {
1231
  if (!representation().IsSmiOrInteger32()) return this;
1232 1233
  // 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;
1234
  if (left()->EqualsInteger32Constant(nop_constant) &&
1235
      !right()->CheckFlag(kUint32)) {
1236 1237
    return right();
  }
1238
  if (right()->EqualsInteger32Constant(nop_constant) &&
1239
      !left()->CheckFlag(kUint32)) {
1240 1241
    return left();
  }
1242 1243 1244 1245
  // Optimize double negation, a common pattern used for ToInt32(x).
  HValue* arg;
  if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
    return arg;
1246 1247 1248 1249 1250
  }
  return this;
}


1251 1252
static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
  return arg1->representation().IsSpecialization() &&
1253
    arg2->EqualsInteger32Constant(identity);
1254 1255 1256
}


1257
HValue* HAdd::Canonicalize() {
1258 1259 1260 1261 1262 1263 1264 1265 1266
  // 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();
  }
1267
  return this;
1268 1269 1270 1271 1272
}


HValue* HSub::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 0)) return left();
1273
  return this;
1274 1275 1276
}


1277 1278 1279
HValue* HMul::Canonicalize() {
  if (IsIdentityOperation(left(), right(), 1)) return left();
  if (IsIdentityOperation(right(), left(), 1)) return right();
1280
  return this;
1281 1282 1283
}


1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
bool HMul::MulMinusOne() {
  if (left()->EqualsInteger32Constant(-1) ||
      right()->EqualsInteger32Constant(-1)) {
    return true;
  }

  return false;
}


1294 1295 1296 1297 1298 1299
HValue* HMod::Canonicalize() {
  return this;
}


HValue* HDiv::Canonicalize() {
1300
  if (IsIdentityOperation(left(), right(), 1)) return left();
1301 1302 1303 1304
  return this;
}


1305 1306 1307 1308 1309
HValue* HChange::Canonicalize() {
  return (from().Equals(to())) ? value() : this;
}


1310 1311 1312 1313 1314 1315 1316 1317 1318
HValue* HWrapReceiver::Canonicalize() {
  if (HasNoUses()) return NULL;
  if (receiver()->type().IsJSObject()) {
    return receiver();
  }
  return this;
}


1319 1320
void HTypeof::PrintDataTo(StringStream* stream) {
  value()->PrintNameTo(stream);
1321 1322 1323
}


1324 1325 1326 1327 1328 1329
void HForceRepresentation::PrintDataTo(StringStream* stream) {
  stream->Add("%s ", representation().Mnemonic());
  value()->PrintNameTo(stream);
}


1330
void HChange::PrintDataTo(StringStream* stream) {
1331
  HUnaryOperation::PrintDataTo(stream);
1332
  stream->Add(" %s to %s", from().Mnemonic(), to().Mnemonic());
1333 1334 1335

  if (CanTruncateToInt32()) stream->Add(" truncating-int32");
  if (CheckFlag(kBailoutOnMinusZero)) stream->Add(" -0?");
1336
  if (CheckFlag(kAllowUndefinedAsNaN)) stream->Add(" allow-undefined-as-nan");
1337 1338 1339
}


1340
static HValue* SimplifiedDividendForMathFloorOfDiv(HValue* dividend) {
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  // A value with an integer representation does not need to be transformed.
  if (dividend->representation().IsInteger32()) {
    return dividend;
  }
  // A change from an integer32 can be replaced by the integer32 value.
  if (dividend->IsChange() &&
      HChange::cast(dividend)->from().IsInteger32()) {
    return HChange::cast(dividend)->value();
  }
  return NULL;
}


1354
HValue* HUnaryMathOperation::Canonicalize() {
1355
  if (op() == kMathRound || op() == kMathFloor) {
1356 1357 1358
    HValue* val = value();
    if (val->IsChange()) val = HChange::cast(val)->value();

1359 1360
    // If the input is smi or integer32 then we replace the instruction with its
    // input.
1361 1362 1363
    if (val->representation().IsSmiOrInteger32()) {
      if (!val->representation().Equals(representation())) {
        HChange* result = new(block()->zone()) HChange(
1364
            val, representation(), false, false);
1365 1366 1367 1368 1369
        result->InsertBefore(this);
        return result;
      }
      return val;
    }
1370 1371
  }

1372
  if (op() == kMathFloor) {
1373 1374 1375 1376
    HValue* val = value();
    if (val->IsChange()) val = HChange::cast(val)->value();
    if (val->IsDiv() && (val->UseCount() == 1)) {
      HDiv* hdiv = HDiv::cast(val);
1377 1378 1379
      HValue* left = hdiv->left();
      HValue* right = hdiv->right();
      // Try to simplify left and right values of the division.
1380 1381 1382
      HValue* new_left = SimplifiedDividendForMathFloorOfDiv(left);
      if (new_left == NULL &&
          hdiv->observed_input_representation(1).IsSmiOrInteger32()) {
1383
        new_left = new(block()->zone()) HChange(
1384
            left, Representation::Integer32(), false, false);
1385 1386
        HChange::cast(new_left)->InsertBefore(this);
      }
1387
      HValue* new_right =
1388 1389
          LChunkBuilder::SimplifiedDivisorForMathFloorOfDiv(right);
      if (new_right == NULL &&
1390
#if V8_TARGET_ARCH_ARM
1391 1392
          CpuFeatures::IsSupported(SUDIV) &&
#endif
1393
          hdiv->observed_input_representation(2).IsSmiOrInteger32()) {
1394
        new_right = new(block()->zone()) HChange(
1395
            right, Representation::Integer32(), false, false);
1396
        HChange::cast(new_right)->InsertBefore(this);
1397
      }
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

      // Return if left or right are not optimizable.
      if ((new_left == NULL) || (new_right == NULL)) return this;

      // Insert the new values in the graph.
      if (new_left->IsInstruction() &&
          !HInstruction::cast(new_left)->IsLinked()) {
        HInstruction::cast(new_left)->InsertBefore(this);
      }
      if (new_right->IsInstruction() &&
          !HInstruction::cast(new_right)->IsLinked()) {
        HInstruction::cast(new_right)->InsertBefore(this);
      }
1411 1412
      HMathFloorOfDiv* instr =
          HMathFloorOfDiv::New(block()->zone(), context(), new_left, new_right);
1413 1414 1415 1416 1417
      // Replace this HMathFloor instruction by the new HMathFloorOfDiv.
      instr->InsertBefore(this);
      ReplaceAllUsesWith(instr);
      Kill();
      // We know the division had no other uses than this HMathFloor. Delete it.
1418 1419
      // Dead code elimination will deal with |left| and |right| if
      // appropriate.
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
      hdiv->DeleteAndReplaceWith(NULL);

      // Return NULL to remove this instruction from the graph.
      return NULL;
    }
  }
  return this;
}


1430
HValue* HCheckInstanceType::Canonicalize() {
1431
  if (check_ == IS_STRING && value()->type().IsString()) {
1432
    return value();
1433
  }
1434

1435
  if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1436 1437 1438
    if (HConstant::cast(value())->HasInternalizedStringValue()) {
      return value();
    }
1439 1440 1441 1442 1443
  }
  return this;
}


1444 1445 1446 1447
void HCheckInstanceType::GetCheckInterval(InstanceType* first,
                                          InstanceType* last) {
  ASSERT(is_interval_check());
  switch (check_) {
1448 1449 1450
    case IS_SPEC_OBJECT:
      *first = FIRST_SPEC_OBJECT_TYPE;
      *last = LAST_SPEC_OBJECT_TYPE;
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
      return;
    case IS_JS_ARRAY:
      *first = *last = JS_ARRAY_TYPE;
      return;
    default:
      UNREACHABLE();
  }
}


void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
  ASSERT(!is_interval_check());
  switch (check_) {
    case IS_STRING:
      *mask = kIsNotStringMask;
      *tag = kStringTag;
      return;
1468
    case IS_INTERNALIZED_STRING:
1469
      *mask = kIsNotInternalizedMask;
1470
      *tag = kInternalizedTag;
1471 1472 1473 1474
      return;
    default:
      UNREACHABLE();
  }
1475 1476 1477
}


1478 1479
void HCheckMaps::HandleSideEffectDominator(GVNFlag side_effect,
                                           HValue* dominator) {
1480 1481 1482 1483
  ASSERT(side_effect == kChangesMaps);
  // TODO(mstarzinger): For now we specialize on HStoreNamedField, but once
  // type information is rich enough we should generalize this to any HType
  // for which the map is known.
1484
  if (HasNoUses() && dominator->IsStoreNamedField()) {
1485
    HStoreNamedField* store = HStoreNamedField::cast(dominator);
1486 1487
    if (!store->has_transition() || store->object() != value()) return;
    HConstant* transition = HConstant::cast(store->transition());
1488 1489 1490
    if (map_set_.Contains(transition->GetUnique())) {
      DeleteAndReplaceWith(NULL);
      return;
1491 1492 1493 1494 1495
    }
  }
}


1496
void HCheckMaps::PrintDataTo(StringStream* stream) {
1497
  value()->PrintNameTo(stream);
1498 1499 1500
  stream->Add(" [%p", *map_set_.at(0).handle());
  for (int i = 1; i < map_set_.size(); ++i) {
    stream->Add(",%p", *map_set_.at(i).handle());
1501
  }
1502
  stream->Add("]%s", CanOmitMapChecks() ? "(omitted)" : "");
1503 1504 1505
}


1506
void HCheckValue::PrintDataTo(StringStream* stream) {
1507
  value()->PrintNameTo(stream);
1508
  stream->Add(" ");
1509
  object().handle()->ShortPrint(stream);
1510 1511 1512
}


1513
HValue* HCheckValue::Canonicalize() {
1514
  return (value()->IsConstant() &&
1515
          HConstant::cast(value())->GetUnique() == object_)
1516 1517 1518 1519 1520
      ? NULL
      : this;
}


1521 1522 1523 1524 1525
const char* HCheckInstanceType::GetCheckName() {
  switch (check_) {
    case IS_SPEC_OBJECT: return "object";
    case IS_JS_ARRAY: return "array";
    case IS_STRING: return "string";
1526
    case IS_INTERNALIZED_STRING: return "internalized_string";
1527 1528 1529 1530 1531
  }
  UNREACHABLE();
  return "";
}

1532

1533 1534 1535 1536 1537 1538
void HCheckInstanceType::PrintDataTo(StringStream* stream) {
  stream->Add("%s ", GetCheckName());
  HUnaryOperation::PrintDataTo(stream);
}


1539
void HCallStub::PrintDataTo(StringStream* stream) {
1540 1541 1542
  stream->Add("%s ",
              CodeStub::MajorName(major_key_, false));
  HUnaryCall::PrintDataTo(stream);
1543 1544 1545
}


1546 1547 1548 1549 1550 1551 1552 1553 1554
void HUnknownOSRValue::PrintDataTo(StringStream *stream) {
  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";
  stream->Add("%s @ %d", type, index_);
}


1555
void HInstanceOf::PrintDataTo(StringStream* stream) {
1556 1557 1558 1559 1560 1561 1562 1563
  left()->PrintNameTo(stream);
  stream->Add(" ");
  right()->PrintNameTo(stream);
  stream->Add(" ");
  context()->PrintNameTo(stream);
}


1564
Range* HValue::InferRange(Zone* zone) {
1565
  Range* result;
1566
  if (representation().IsSmi() || type().IsSmi()) {
1567 1568 1569 1570
    result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
    result->set_can_be_minus_zero(false);
  } else {
    result = new(zone) Range();
1571 1572 1573
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
    // TODO(jkummerow): The range cannot be minus zero when the upper type
    // bound is Integer32.
1574
  }
1575
  return result;
1576 1577 1578
}


1579
Range* HChange::InferRange(Zone* zone) {
1580
  Range* input_range = value()->range();
1581 1582 1583 1584 1585
  if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
      (to().IsSmi() ||
       (to().IsTagged() &&
        input_range != NULL &&
        input_range->IsInSmiRange()))) {
1586
    set_type(HType::Smi());
1587
    ClearGVNFlag(kChangesNewSpacePromotion);
1588 1589
  }
  Range* result = (input_range != NULL)
1590 1591
      ? input_range->Copy(zone)
      : HValue::InferRange(zone);
1592
  result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1593 1594 1595
                                !(CheckFlag(kAllUsesTruncatingToInt32) ||
                                  CheckFlag(kAllUsesTruncatingToSmi)));
  if (to().IsSmi()) result->ClampToSmi();
1596 1597 1598 1599
  return result;
}


1600
Range* HConstant::InferRange(Zone* zone) {
1601
  if (has_int32_value_) {
1602
    Range* result = new(zone) Range(int32_value_, int32_value_);
fschneider@chromium.org's avatar
fschneider@chromium.org committed
1603 1604
    result->set_can_be_minus_zero(false);
    return result;
1605
  }
1606
  return HValue::InferRange(zone);
1607 1608 1609
}


1610 1611 1612 1613 1614
int HPhi::position() const {
  return block()->first()->position();
}


1615
Range* HPhi::InferRange(Zone* zone) {
1616 1617
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1618
    if (block()->IsLoopHeader()) {
1619 1620 1621
      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
1622
      return range;
1623
    } else {
1624
      Range* range = OperandAt(0)->range()->Copy(zone);
1625 1626 1627 1628 1629 1630
      for (int i = 1; i < OperandCount(); ++i) {
        range->Union(OperandAt(i)->range());
      }
      return range;
    }
  } else {
1631
    return HValue::InferRange(zone);
1632 1633 1634 1635
  }
}


1636
Range* HAdd::InferRange(Zone* zone) {
1637 1638
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1639 1640
    Range* a = left()->range();
    Range* b = right()->range();
1641
    Range* res = a->Copy(zone);
1642 1643 1644
    if (!res->AddAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1645 1646
      ClearFlag(kCanOverflow);
    }
1647 1648
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1649
                               a->CanBeMinusZero() && b->CanBeMinusZero());
1650 1651
    return res;
  } else {
1652
    return HValue::InferRange(zone);
1653 1654 1655 1656
  }
}


1657
Range* HSub::InferRange(Zone* zone) {
1658 1659
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1660 1661
    Range* a = left()->range();
    Range* b = right()->range();
1662
    Range* res = a->Copy(zone);
1663 1664 1665
    if (!res->SubAndCheckOverflow(r, b) ||
        (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
        (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1666 1667
      ClearFlag(kCanOverflow);
    }
1668 1669
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1670
                               a->CanBeMinusZero() && b->CanBeZero());
1671 1672
    return res;
  } else {
1673
    return HValue::InferRange(zone);
1674 1675 1676 1677
  }
}


1678
Range* HMul::InferRange(Zone* zone) {
1679 1680
  Representation r = representation();
  if (r.IsSmiOrInteger32()) {
1681 1682
    Range* a = left()->range();
    Range* b = right()->range();
1683
    Range* res = a->Copy(zone);
1684 1685 1686 1687 1688 1689 1690
    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.
1691 1692
      ClearFlag(kCanOverflow);
    }
1693 1694
    res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
                               !CheckFlag(kAllUsesTruncatingToInt32) &&
1695 1696
                               ((a->CanBeZero() && b->CanBeNegative()) ||
                                (a->CanBeNegative() && b->CanBeZero())));
1697 1698
    return res;
  } else {
1699
    return HValue::InferRange(zone);
1700 1701 1702 1703
  }
}


1704
Range* HDiv::InferRange(Zone* zone) {
1705
  if (representation().IsInteger32()) {
1706 1707
    Range* a = left()->range();
    Range* b = right()->range();
1708
    Range* result = new(zone) Range();
1709 1710 1711
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  (a->CanBeMinusZero() ||
                                   (a->CanBeZero() && b->CanBeNegative())));
1712 1713 1714 1715
    if (!a->Includes(kMinInt) ||
        !b->Includes(-1) ||
        CheckFlag(kAllUsesTruncatingToInt32)) {
      // It is safe to clear kCanOverflow when kAllUsesTruncatingToInt32.
1716
      ClearFlag(HValue::kCanOverflow);
1717 1718
    }

1719
    if (!b->CanBeZero()) {
1720 1721 1722 1723
      ClearFlag(HValue::kCanBeDivByZero);
    }
    return result;
  } else {
1724
    return HValue::InferRange(zone);
1725 1726 1727 1728
  }
}


1729
Range* HMod::InferRange(Zone* zone) {
1730 1731
  if (representation().IsInteger32()) {
    Range* a = left()->range();
1732
    Range* b = right()->range();
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

    // The magnitude of the modulus is bounded by the right operand. Note that
    // apart for the cases involving kMinInt, the calculation below is the same
    // as Max(Abs(b->lower()), Abs(b->upper())) - 1.
    int32_t positive_bound = -(Min(NegAbs(b->lower()), NegAbs(b->upper())) + 1);

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

1744 1745
    result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
                                  left_can_be_negative);
1746

1747 1748
    if (!a->Includes(kMinInt) || !b->Includes(-1)) {
      ClearFlag(HValue::kCanOverflow);
1749 1750
    }

1751
    if (!b->CanBeZero()) {
1752 1753 1754 1755
      ClearFlag(HValue::kCanBeDivByZero);
    }
    return result;
  } else {
1756
    return HValue::InferRange(zone);
1757 1758 1759 1760
  }
}


1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
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) {
  ASSERT(limit_validity() != NULL);
  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) {
  ASSERT(first_check_in_block() != NULL);
  HValue* previous_index = first_check_in_block()->index();
  ASSERT(context != NULL);

1888 1889
  Zone* zone = index_base->block()->graph()->zone();
  set_added_constant(HConstant::New(zone, context, mask));
1890 1891 1892 1893 1894 1895 1896 1897
  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());
1898 1899
    HInstruction* new_index =  HBitwise::New(zone, context, token, index_base,
                                             added_constant());
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 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 2088 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 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 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
    ASSERT(new_index->IsBitwise());
    new_index->ClearAllSideEffects();
    new_index->AssumeRepresentation(Representation::Integer32());
    set_added_index(HBitwise::cast(new_index));
    added_index()->InsertBefore(first_check_in_block());
  }
  ASSERT(added_index()->op() == token);

  added_index()->SetOperandAt(1, index_base);
  added_index()->SetOperandAt(2, added_constant());
  first_check_in_block()->SetOperandAt(0, added_index());
  if (previous_index->UseCount() == 0) {
    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) {
  if (!phi_operand->representation().IsInteger32()) return 0;

  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()) {
      return -operation->right()->GetInteger32Constant();
    }
  }

  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) {
  ASSERT(update->updated_variable == this);
  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);
    ASSERT(block == branch->SuccessorAt(1));
  }

  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;
  }
}


2204
Range* HMathMinMax::InferRange(Zone* zone) {
2205
  if (representation().IsSmiOrInteger32()) {
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    Range* a = left()->range();
    Range* b = right()->range();
    Range* res = a->Copy(zone);
    if (operation_ == kMathMax) {
      res->CombinedMax(b);
    } else {
      ASSERT(operation_ == kMathMin);
      res->CombinedMin(b);
    }
    return res;
  } else {
    return HValue::InferRange(zone);
  }
}


2222
void HPhi::PrintTo(StringStream* stream) {
2223 2224 2225 2226 2227 2228 2229
  stream->Add("[");
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* value = OperandAt(i);
    stream->Add(" ");
    value->PrintNameTo(stream);
    stream->Add(" ");
  }
2230
  stream->Add(" uses:%d_%ds_%di_%dd_%dt",
2231
              UseCount(),
2232
              smi_non_phi_uses() + smi_indirect_uses(),
2233 2234 2235
              int32_non_phi_uses() + int32_indirect_uses(),
              double_non_phi_uses() + double_indirect_uses(),
              tagged_non_phi_uses() + tagged_indirect_uses());
2236 2237 2238
  PrintRangeTo(stream);
  PrintTypeTo(stream);
  stream->Add("]");
2239 2240 2241 2242
}


void HPhi::AddInput(HValue* value) {
2243
  inputs_.Add(NULL, value->block()->zone());
2244 2245 2246 2247 2248 2249 2250 2251
  SetOperandAt(OperandCount() - 1, value);
  // Mark phis that may have 'arguments' directly or indirectly as an operand.
  if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
    SetFlag(kIsArguments);
  }
}


2252
bool HPhi::HasRealUses() {
2253 2254
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    if (!it.value()->IsPhi()) return true;
2255 2256 2257 2258 2259
  }
  return false;
}


2260
HValue* HPhi::GetRedundantReplacement() {
2261 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
  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;
  }
  ASSERT(candidate != this);
  return candidate;
}


void HPhi::DeleteFromGraph() {
  ASSERT(block() != NULL);
  block()->RemovePhi(this);
  ASSERT(block() == NULL);
}


void HPhi::InitRealUses(int phi_id) {
  // Initialize real uses.
  phi_id_ = phi_id;
2287 2288 2289
  // Compute a conservative approximation of truncating uses before inferring
  // representations. The proper, exact computation will be done later, when
  // inserting representation changes.
2290
  SetFlag(kTruncatingToSmi);
2291
  SetFlag(kTruncatingToInt32);
2292 2293 2294
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* value = it.value();
    if (!value->IsPhi()) {
2295
      Representation rep = value->observed_input_representation(it.index());
2296
      non_phi_uses_[rep.kind()] += value->LoopWeight();
2297
      if (FLAG_trace_representation) {
2298 2299
        PrintF("#%d Phi is used by real #%d %s as %s\n",
               id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2300
      }
2301 2302 2303 2304 2305 2306 2307
      if (!value->IsSimulate()) {
        if (!value->CheckFlag(kTruncatingToSmi)) {
          ClearFlag(kTruncatingToSmi);
        }
        if (!value->CheckFlag(kTruncatingToInt32)) {
          ClearFlag(kTruncatingToInt32);
        }
2308
      }
2309 2310 2311 2312 2313 2314
    }
  }
}


void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2315
  if (FLAG_trace_representation) {
2316
    PrintF("adding to #%d Phi uses of #%d Phi: s%d i%d d%d t%d\n",
2317
           id(), other->id(),
2318
           other->non_phi_uses_[Representation::kSmi],
2319 2320 2321 2322 2323
           other->non_phi_uses_[Representation::kInteger32],
           other->non_phi_uses_[Representation::kDouble],
           other->non_phi_uses_[Representation::kTagged]);
  }

2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
  for (int i = 0; i < Representation::kNumRepresentations; i++) {
    indirect_uses_[i] += other->non_phi_uses_[i];
  }
}


void HPhi::AddIndirectUsesTo(int* dest) {
  for (int i = 0; i < Representation::kNumRepresentations; i++) {
    dest[i] += indirect_uses_[i];
  }
}


2337 2338 2339 2340 2341 2342
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)) {
2343 2344 2345
        int index = from->GetAssignedIndexAt(i);
        if (HasValueForIndex(index)) continue;
        AddAssignedValue(index, from_values->at(i));
2346
      } else {
2347 2348 2349 2350 2351
        if (pop_count_ > 0) {
          pop_count_--;
        } else {
          AddPushedValue(from_values->at(i));
        }
2352 2353
      }
    }
2354 2355
    pop_count_ += from->pop_count_;
    from->DeleteAndReplaceWith(NULL);
2356
  }
2357 2358 2359
}


2360
void HSimulate::PrintDataTo(StringStream* stream) {
2361
  stream->Add("id=%d", ast_id().ToInt());
2362
  if (pop_count_ > 0) stream->Add(" pop %d", pop_count_);
2363 2364
  if (values_.length() > 0) {
    if (pop_count_ > 0) stream->Add(" /");
2365
    for (int i = values_.length() - 1; i >= 0; --i) {
2366
      if (HasAssignedIndexAt(i)) {
2367
        stream->Add(" var[%d] = ", GetAssignedIndexAt(i));
2368 2369
      } else {
        stream->Add(" push ");
2370 2371
      }
      values_[i]->PrintNameTo(stream);
2372
      if (i > 0) stream->Add(",");
2373 2374 2375 2376 2377
    }
  }
}


2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
void HSimulate::ReplayEnvironment(HEnvironment* env) {
  ASSERT(env != NULL);
  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);
    }
  }
}


2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
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);
      }
    }
  }
}


2408 2409 2410 2411 2412
// 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) {
  ASSERT(env != NULL);
  while (env != NULL) {
2413
    ReplayEnvironmentNested(env->values(), this);
2414 2415 2416 2417 2418
    env = env->outer();
  }
}


2419 2420 2421 2422 2423 2424
void HCapturedObject::PrintDataTo(StringStream* stream) {
  stream->Add("#%d ", capture_id());
  HDematerializedObject::PrintDataTo(stream);
}


2425 2426 2427 2428 2429 2430 2431
void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
                                         Zone* zone) {
  ASSERT(return_target->IsInlineReturnTarget());
  return_targets_.Add(return_target, zone);
}


2432
void HEnterInlined::PrintDataTo(StringStream* stream) {
2433
  SmartArrayPointer<char> name = function()->debug_name()->ToCString();
2434
  stream->Add("%s, id=%d", *name, function()->id().ToInt());
2435 2436 2437
}


2438 2439 2440 2441 2442 2443
static bool IsInteger32(double value) {
  double roundtrip_value = static_cast<double>(static_cast<int32_t>(value));
  return BitCast<int64_t>(roundtrip_value) == BitCast<int64_t>(value);
}


2444
HConstant::HConstant(Handle<Object> handle, Representation r)
2445
  : HTemplateInstruction<0>(HType::TypeFromValue(handle)),
2446
    object_(Unique<Object>::CreateUninitialized(handle)),
2447
    has_smi_value_(false),
2448 2449
    has_int32_value_(false),
    has_double_value_(false),
2450
    has_external_reference_value_(false),
2451
    is_internalized_string_(false),
2452
    is_not_in_new_space_(true),
2453
    is_cell_(false),
2454
    boolean_value_(handle->BooleanValue()) {
2455
  if (handle->IsHeapObject()) {
2456 2457 2458
    Heap* heap = Handle<HeapObject>::cast(handle)->GetHeap();
    is_not_in_new_space_ = !heap->InNewSpace(*handle);
  }
2459 2460
  if (handle->IsNumber()) {
    double n = handle->Number();
2461 2462
    has_int32_value_ = IsInteger32(n);
    int32_value_ = DoubleToInt32(n);
2463
    has_smi_value_ = has_int32_value_ && Smi::IsValid(int32_value_);
2464 2465
    double_value_ = n;
    has_double_value_ = true;
2466
  } else {
2467
    is_internalized_string_ = handle->IsInternalizedString();
2468
  }
2469

2470 2471
  is_cell_ = !handle.is_null() &&
      (handle->IsCell() || handle->IsPropertyCell());
2472
  Initialize(r);
2473 2474 2475
}


2476
HConstant::HConstant(Unique<Object> unique,
2477 2478 2479
                     Representation r,
                     HType type,
                     bool is_internalize_string,
2480
                     bool is_not_in_new_space,
2481
                     bool is_cell,
2482
                     bool boolean_value)
2483
  : HTemplateInstruction<0>(type),
2484
    object_(unique),
2485 2486 2487 2488 2489 2490 2491 2492
    has_smi_value_(false),
    has_int32_value_(false),
    has_double_value_(false),
    has_external_reference_value_(false),
    is_internalized_string_(is_internalize_string),
    is_not_in_new_space_(is_not_in_new_space),
    is_cell_(is_cell),
    boolean_value_(boolean_value) {
2493
  ASSERT(!unique.handle().is_null());
2494 2495 2496 2497 2498 2499 2500
  ASSERT(!type.IsTaggedNumber());
  Initialize(r);
}


HConstant::HConstant(int32_t integer_value,
                     Representation r,
2501
                     bool is_not_in_new_space,
2502 2503
                     Unique<Object> object)
  : object_(object),
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
    has_smi_value_(Smi::IsValid(integer_value)),
    has_int32_value_(true),
    has_double_value_(true),
    has_external_reference_value_(false),
    is_internalized_string_(false),
    is_not_in_new_space_(is_not_in_new_space),
    is_cell_(false),
    boolean_value_(integer_value != 0),
    int32_value_(integer_value),
    double_value_(FastI2D(integer_value)) {
2514
  set_type(has_smi_value_ ? HType::Smi() : HType::TaggedNumber());
2515
  Initialize(r);
2516 2517 2518
}


2519 2520
HConstant::HConstant(double double_value,
                     Representation r,
2521
                     bool is_not_in_new_space,
2522 2523
                     Unique<Object> object)
  : object_(object),
2524 2525 2526 2527 2528 2529 2530 2531 2532
    has_int32_value_(IsInteger32(double_value)),
    has_double_value_(true),
    has_external_reference_value_(false),
    is_internalized_string_(false),
    is_not_in_new_space_(is_not_in_new_space),
    is_cell_(false),
    boolean_value_(double_value != 0 && !std::isnan(double_value)),
    int32_value_(DoubleToInt32(double_value)),
    double_value_(double_value) {
2533
  has_smi_value_ = has_int32_value_ && Smi::IsValid(int32_value_);
2534
  set_type(has_smi_value_ ? HType::Smi() : HType::TaggedNumber());
2535 2536 2537 2538
  Initialize(r);
}


2539
HConstant::HConstant(ExternalReference reference)
2540
  : HTemplateInstruction<0>(HType::None()),
2541
    object_(Unique<Object>(Handle<Object>::null())),
2542
    has_smi_value_(false),
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
    has_int32_value_(false),
    has_double_value_(false),
    has_external_reference_value_(true),
    is_internalized_string_(false),
    is_not_in_new_space_(true),
    is_cell_(false),
    boolean_value_(true),
    external_reference_value_(reference) {
  Initialize(Representation::External());
}


2555
void HConstant::Initialize(Representation r) {
2556
  if (r.IsNone()) {
2557
    if (has_smi_value_ && SmiValuesAre31Bits()) {
2558 2559
      r = Representation::Smi();
    } else if (has_int32_value_) {
2560 2561 2562
      r = Representation::Integer32();
    } else if (has_double_value_) {
      r = Representation::Double();
2563 2564
    } else if (has_external_reference_value_) {
      r = Representation::External();
2565
    } else {
2566 2567 2568 2569 2570 2571 2572 2573
      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);
        }
      }
2574 2575 2576
      r = Representation::Tagged();
    }
  }
2577 2578
  set_representation(r);
  SetFlag(kUseGVN);
2579 2580 2581 2582 2583
}


bool HConstant::EmitAtUses() {
  ASSERT(IsLinked());
2584 2585
  if (block()->graph()->has_osr() &&
      block()->graph()->IsStandardConstant(this)) {
2586
    // TODO(titzer): this seems like a hack that should be fixed by custom OSR.
2587
    return true;
2588
  }
2589
  if (UseCount() == 0) return true;
2590 2591 2592
  if (IsCell()) return false;
  if (representation().IsDouble()) return false;
  return true;
2593 2594 2595
}


2596
HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2597
  if (r.IsSmi() && !has_smi_value_) return NULL;
2598 2599
  if (r.IsInteger32() && !has_int32_value_) return NULL;
  if (r.IsDouble() && !has_double_value_) return NULL;
2600
  if (r.IsExternal() && !has_external_reference_value_) return NULL;
2601
  if (has_int32_value_) {
2602
    return new(zone) HConstant(int32_value_, r, is_not_in_new_space_, object_);
2603 2604
  }
  if (has_double_value_) {
2605
    return new(zone) HConstant(double_value_, r, is_not_in_new_space_, object_);
2606
  }
2607 2608 2609
  if (has_external_reference_value_) {
    return new(zone) HConstant(external_reference_value_);
  }
2610 2611
  ASSERT(!object_.handle().is_null());
  return new(zone) HConstant(object_,
2612
                             r,
2613
                             type_,
2614
                             is_internalized_string_,
2615
                             is_not_in_new_space_,
2616
                             is_cell_,
2617
                             boolean_value_);
2618 2619 2620
}


2621 2622
Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
  HConstant* res = NULL;
2623
  if (has_int32_value_) {
2624 2625 2626
    res = new(zone) HConstant(int32_value_,
                              Representation::Integer32(),
                              is_not_in_new_space_,
2627
                              object_);
2628 2629 2630 2631
  } else if (has_double_value_) {
    res = new(zone) HConstant(DoubleToInt32(double_value_),
                              Representation::Integer32(),
                              is_not_in_new_space_,
2632
                              object_);
2633
  }
2634 2635 2636 2637 2638 2639
  return Maybe<HConstant*>(res != NULL, res);
}


Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Zone* zone) {
  HConstant* res = NULL;
2640 2641 2642
  Handle<Object> handle = this->handle(zone->isolate());
  if (handle->IsBoolean()) {
    res = handle->BooleanValue() ?
2643
      new(zone) HConstant(1) : new(zone) HConstant(0);
2644
  } else if (handle->IsUndefined()) {
2645
    res = new(zone) HConstant(OS::nan_value());
2646
  } else if (handle->IsNull()) {
2647
    res = new(zone) HConstant(0);
2648
  }
2649
  return Maybe<HConstant*>(res != NULL, res);
2650 2651
}

2652

2653
void HConstant::PrintDataTo(StringStream* stream) {
2654 2655 2656
  if (has_int32_value_) {
    stream->Add("%d ", int32_value_);
  } else if (has_double_value_) {
2657
    stream->Add("%f ", FmtElm(double_value_));
2658 2659 2660
  } else if (has_external_reference_value_) {
    stream->Add("%p ", reinterpret_cast<void*>(
            external_reference_value_.address()));
2661
  } else {
2662
    handle(Isolate::Current())->ShortPrint(stream);
2663
  }
2664 2665 2666
}


2667
void HBinaryOperation::PrintDataTo(StringStream* stream) {
2668 2669 2670 2671 2672 2673 2674 2675
  left()->PrintNameTo(stream);
  stream->Add(" ");
  right()->PrintNameTo(stream);
  if (CheckFlag(kCanOverflow)) stream->Add(" !");
  if (CheckFlag(kBailoutOnMinusZero)) stream->Add(" -0?");
}


2676
void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
2677 2678 2679
  ASSERT(CheckFlag(kFlexibleRepresentation));
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
2680 2681 2682 2683 2684 2685

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

2686 2687 2688 2689 2690 2691
  if (observed_output_representation_.IsNone()) {
    new_rep = RepresentationFromUses();
    UpdateRepresentation(new_rep, h_infer, "uses");
  } else {
    new_rep = RepresentationFromOutput();
    UpdateRepresentation(new_rep, h_infer, "output");
2692
  }
2693 2694 2695
}


2696 2697 2698 2699 2700
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) {
2701
    rep = rep.generalize(observed_input_representation(i));
2702 2703 2704 2705 2706
  }
  // 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();
2707 2708
  if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
  if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
2709

2710 2711 2712 2713 2714 2715 2716 2717 2718
  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.
2719
         (!this->IsMul() || HMul::cast(this)->MulMinusOne());
2720 2721 2722 2723 2724
}


Representation HBinaryOperation::RepresentationFromOutput() {
  Representation rep = representation();
2725 2726 2727 2728 2729
  // 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)) {
2730
    return observed_output_representation_;
2731
  }
2732
  return Representation::None();
2733 2734 2735 2736
}


void HBinaryOperation::AssumeRepresentation(Representation r) {
2737 2738
  set_observed_input_representation(1, r);
  set_observed_input_representation(2, r);
2739 2740 2741 2742
  HValue::AssumeRepresentation(r);
}


2743
void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
2744 2745 2746 2747 2748 2749 2750
  ASSERT(CheckFlag(kFlexibleRepresentation));
  Representation new_rep = RepresentationFromInputs();
  UpdateRepresentation(new_rep, h_infer, "inputs");
  // Do not care about uses.
}


2751
Range* HBitwise::InferRange(Zone* zone) {
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
  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));
2780
    }
2781 2782 2783
    Range* result = HValue::InferRange(zone);
    result->set_can_be_minus_zero(false);
    return result;
2784
  }
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
  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;
2795 2796 2797 2798 2799
  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;
2800 2801 2802
}


2803
Range* HSar::InferRange(Zone* zone) {
2804 2805 2806
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
2807
      Range* result = (left()->range() != NULL)
2808 2809
          ? left()->range()->Copy(zone)
          : new(zone) Range();
2810
      result->Sar(c->Integer32Value());
2811 2812 2813
      return result;
    }
  }
2814
  return HValue::InferRange(zone);
2815 2816 2817
}


2818
Range* HShr::InferRange(Zone* zone) {
2819 2820 2821 2822 2823 2824 2825
  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)
2826 2827 2828
            ? new(zone) Range(0,
                              static_cast<uint32_t>(0xffffffff) >> shift_count)
            : new(zone) Range();
2829 2830 2831
      } else {
        // For positive inputs we can use the >> operator.
        Range* result = (left()->range() != NULL)
2832 2833
            ? left()->range()->Copy(zone)
            : new(zone) Range();
2834 2835 2836 2837 2838
        result->Sar(c->Integer32Value());
        return result;
      }
    }
  }
2839
  return HValue::InferRange(zone);
2840 2841 2842
}


2843
Range* HShl::InferRange(Zone* zone) {
2844 2845 2846
  if (right()->IsConstant()) {
    HConstant* c = HConstant::cast(right());
    if (c->HasInteger32Value()) {
2847
      Range* result = (left()->range() != NULL)
2848 2849
          ? left()->range()->Copy(zone)
          : new(zone) Range();
2850
      result->Shl(c->Integer32Value());
2851 2852 2853
      return result;
    }
  }
2854
  return HValue::InferRange(zone);
2855 2856 2857
}


2858
Range* HLoadNamedField::InferRange(Zone* zone) {
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
  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);
2870
  }
2871 2872 2873 2874 2875 2876 2877
  if (access().IsStringLength()) {
    return new(zone) Range(0, String::kMaxLength);
  }
  return HValue::InferRange(zone);
}


2878
Range* HLoadKeyed::InferRange(Zone* zone) {
2879 2880
  switch (elements_kind()) {
    case EXTERNAL_BYTE_ELEMENTS:
2881
      return new(zone) Range(kMinInt8, kMaxInt8);
2882
    case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2883 2884
    case EXTERNAL_PIXEL_ELEMENTS:
      return new(zone) Range(kMinUInt8, kMaxUInt8);
2885
    case EXTERNAL_SHORT_ELEMENTS:
2886
      return new(zone) Range(kMinInt16, kMaxInt16);
2887
    case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2888
      return new(zone) Range(kMinUInt16, kMaxUInt16);
2889
    default:
2890
      return HValue::InferRange(zone);
2891 2892 2893
  }
}

2894

2895
void HCompareGeneric::PrintDataTo(StringStream* stream) {
2896 2897
  stream->Add(Token::Name(token()));
  stream->Add(" ");
2898
  HBinaryOperation::PrintDataTo(stream);
2899 2900 2901
}


2902 2903 2904 2905 2906 2907 2908
void HStringCompareAndBranch::PrintDataTo(StringStream* stream) {
  stream->Add(Token::Name(token()));
  stream->Add(" ");
  HControlInstruction::PrintDataTo(stream);
}


2909
void HCompareNumericAndBranch::PrintDataTo(StringStream* stream) {
2910 2911 2912 2913 2914
  stream->Add(Token::Name(token()));
  stream->Add(" ");
  left()->PrintNameTo(stream);
  stream->Add(" ");
  right()->PrintNameTo(stream);
2915 2916 2917 2918
  HControlInstruction::PrintDataTo(stream);
}


2919 2920 2921 2922 2923 2924 2925 2926
void HCompareObjectEqAndBranch::PrintDataTo(StringStream* stream) {
  left()->PrintNameTo(stream);
  stream->Add(" ");
  right()->PrintNameTo(stream);
  HControlInstruction::PrintDataTo(stream);
}


2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  if (left()->IsConstant() && right()->IsConstant()) {
    bool comparison_result =
        HConstant::cast(left())->Equals(HConstant::cast(right()));
    *block = comparison_result
        ? FirstSuccessor()
        : SecondSuccessor();
    return true;
  }
  *block = NULL;
  return false;
}


2941 2942
void HCompareHoleAndBranch::InferRepresentation(
    HInferRepresentationPhase* h_infer) {
2943
  ChangeRepresentation(value()->representation());
2944 2945 2946
}


2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
bool HCompareMinusZeroAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
  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());
}



2965 2966
void HGoto::PrintDataTo(StringStream* stream) {
  stream->Add("B%d", SuccessorAt(0)->block_id());
2967 2968 2969
}


2970
void HCompareNumericAndBranch::InferRepresentation(
2971
    HInferRepresentationPhase* h_infer) {
2972 2973
  Representation left_rep = left()->representation();
  Representation right_rep = right()->representation();
2974 2975 2976
  Representation observed_left = observed_input_representation(0);
  Representation observed_right = observed_input_representation(1);

2977 2978 2979 2980
  Representation rep = Representation::None();
  rep = rep.generalize(observed_left);
  rep = rep.generalize(observed_right);
  if (rep.IsNone() || rep.IsSmiOrInteger32()) {
2981 2982 2983 2984 2985
    if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
    if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
  } else {
    rep = Representation::Double();
  }
2986 2987

  if (rep.IsDouble()) {
2988 2989 2990 2991
    // 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
2992 2993 2994
    // 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 (<, >, <=,
2995 2996 2997 2998 2999 3000
    // >=). 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
3001 3002
    if (Token::IsOrderedRelationalCompareOp(token_)) {
      SetFlag(kAllowUndefinedAsNaN);
3003
    }
3004
  }
3005
  ChangeRepresentation(rep);
3006 3007 3008
}


3009
void HParameter::PrintDataTo(StringStream* stream) {
3010 3011 3012 3013
  stream->Add("%u", index());
}


3014
void HLoadNamedField::PrintDataTo(StringStream* stream) {
3015
  object()->PrintNameTo(stream);
3016
  access_.PrintTo(stream);
3017 3018 3019
}


3020 3021 3022
HCheckMaps* HCheckMaps::New(Zone* zone,
                            HValue* context,
                            HValue* value,
3023 3024 3025 3026
                            Handle<Map> map,
                            CompilationInfo* info,
                            HValue* typecheck) {
  HCheckMaps* check_map = new(zone) HCheckMaps(value, zone, typecheck);
3027
  check_map->Add(map, zone);
3028 3029
  if (map->CanOmitMapChecks() &&
      value->IsConstant() &&
3030
      HConstant::cast(value)->HasMap(map)) {
3031 3032 3033 3034 3035 3036
    // TODO(titzer): collect dependent map checks into a list.
    check_map->omit_ = true;
    if (map->CanTransition()) {
      map->AddDependentCompilationInfo(
          DependentCode::kPrototypeCheckGroup, info);
    }
3037 3038 3039 3040 3041
  }
  return check_map;
}


3042 3043
void HLoadNamedGeneric::PrintDataTo(StringStream* stream) {
  object()->PrintNameTo(stream);
3044
  stream->Add(".");
3045 3046 3047 3048
  stream->Add(*String::cast(*name())->ToCString());
}


3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
void HLoadKeyed::PrintDataTo(StringStream* stream) {
  if (!is_external()) {
    elements()->PrintNameTo(stream);
  } else {
    ASSERT(elements_kind() >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND);
    elements()->PrintNameTo(stream);
    stream->Add(".");
    stream->Add(ElementsKindToString(elements_kind()));
  }

3060 3061
  stream->Add("[");
  key()->PrintNameTo(stream);
3062
  if (IsDehoisted()) {
3063
    stream->Add(" + %d]", index_offset());
3064
  } else {
3065 3066 3067 3068 3069 3070
    stream->Add("]");
  }

  if (HasDependency()) {
    stream->Add(" ");
    dependency()->PrintNameTo(stream);
3071 3072
  }

3073
  if (RequiresHoleCheck()) {
3074 3075
    stream->Add(" check_hole");
  }
3076 3077 3078
}


3079
bool HLoadKeyed::UsesMustHandleHole() const {
3080
  if (IsFastPackedElementsKind(elements_kind())) {
3081 3082 3083
    return false;
  }

3084 3085 3086 3087
  if (IsExternalArrayElementsKind(elements_kind())) {
    return false;
  }

3088 3089 3090 3091 3092 3093
  if (hole_mode() == ALLOW_RETURN_HOLE) {
    if (IsFastDoubleElementsKind(elements_kind())) {
      return AllUsesCanTreatHoleAsNaN();
    }
    return true;
  }
3094

3095
  if (IsFastDoubleElementsKind(elements_kind())) {
3096
    return false;
3097 3098
  }

3099 3100 3101 3102 3103
  // Holes are only returned as tagged values.
  if (!representation().IsTagged()) {
    return false;
  }

3104 3105
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
3106
    if (!use->IsChange()) return false;
3107
  }
3108

3109 3110 3111 3112
  return true;
}


3113
bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
3114 3115
  return IsFastDoubleElementsKind(elements_kind()) &&
      CheckUsesForFlag(HValue::kAllowUndefinedAsNaN);
3116 3117 3118
}


3119 3120 3121 3122 3123
bool HLoadKeyed::RequiresHoleCheck() const {
  if (IsFastPackedElementsKind(elements_kind())) {
    return false;
  }

3124 3125 3126 3127
  if (IsExternalArrayElementsKind(elements_kind())) {
    return false;
  }

3128
  return !UsesMustHandleHole();
3129 3130 3131
}


3132
void HLoadKeyedGeneric::PrintDataTo(StringStream* stream) {
3133 3134 3135 3136 3137 3138 3139
  object()->PrintNameTo(stream);
  stream->Add("[");
  key()->PrintNameTo(stream);
  stream->Add("]");
}


3140 3141 3142 3143
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.
3144 3145 3146
  if (key()->IsLoadKeyed()) {
    HLoadKeyed* key_load = HLoadKeyed::cast(key());
    if (key_load->elements()->IsForInCacheArray()) {
3147
      HForInCacheArray* names_cache =
3148
          HForInCacheArray::cast(key_load->elements());
3149 3150 3151 3152 3153

      if (names_cache->enumerable() == object()) {
        HForInCacheArray* index_cache =
            names_cache->index_cache();
        HCheckMapValue* map_check =
3154 3155 3156 3157 3158 3159 3160
            HCheckMapValue::New(block()->graph()->zone(),
                                block()->graph()->GetInvalidContext(),
                                object(),
                                names_cache->map());
        HInstruction* index = HLoadKeyed::New(
            block()->graph()->zone(),
            block()->graph()->GetInvalidContext(),
3161
            index_cache,
3162
            key_load->key(),
3163 3164
            key_load->key(),
            key_load->elements_kind());
3165 3166
        map_check->InsertBefore(this);
        index->InsertBefore(this);
3167 3168
        HLoadFieldByIndex* load = new(block()->zone()) HLoadFieldByIndex(
            object(), index);
3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
        load->InsertBefore(this);
        return load;
      }
    }
  }

  return this;
}


3179
void HStoreNamedGeneric::PrintDataTo(StringStream* stream) {
3180 3181 3182 3183 3184 3185 3186 3187 3188
  object()->PrintNameTo(stream);
  stream->Add(".");
  ASSERT(name()->IsString());
  stream->Add(*String::cast(*name())->ToCString());
  stream->Add(" = ");
  value()->PrintNameTo(stream);
}


3189
void HStoreNamedField::PrintDataTo(StringStream* stream) {
3190
  object()->PrintNameTo(stream);
3191
  access_.PrintTo(stream);
3192 3193
  stream->Add(" = ");
  value()->PrintNameTo(stream);
3194 3195 3196
  if (NeedsWriteBarrier()) {
    stream->Add(" (write-barrier)");
  }
3197 3198
  if (has_transition()) {
    stream->Add(" (transition map %p)", *transition_map());
3199 3200 3201 3202
  }
}


3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
void HStoreKeyed::PrintDataTo(StringStream* stream) {
  if (!is_external()) {
    elements()->PrintNameTo(stream);
  } else {
    elements()->PrintNameTo(stream);
    stream->Add(".");
    stream->Add(ElementsKindToString(elements_kind()));
    ASSERT(elements_kind() >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
           elements_kind() <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND);
  }
3213

3214 3215
  stream->Add("[");
  key()->PrintNameTo(stream);
3216 3217 3218 3219 3220 3221
  if (IsDehoisted()) {
    stream->Add(" + %d] = ", index_offset());
  } else {
    stream->Add("] = ");
  }

3222 3223 3224 3225
  value()->PrintNameTo(stream);
}


3226
void HStoreKeyedGeneric::PrintDataTo(StringStream* stream) {
3227 3228 3229 3230 3231 3232 3233 3234
  object()->PrintNameTo(stream);
  stream->Add("[");
  key()->PrintNameTo(stream);
  stream->Add("] = ");
  value()->PrintNameTo(stream);
}


3235 3236
void HTransitionElementsKind::PrintDataTo(StringStream* stream) {
  object()->PrintNameTo(stream);
3237 3238
  ElementsKind from_kind = original_map().handle()->elements_kind();
  ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3239
  stream->Add(" %p [%s] -> %p [%s]",
3240
              *original_map().handle(),
3241
              ElementsAccessor::ForKind(from_kind)->name(),
3242
              *transitioned_map().handle(),
3243
              ElementsAccessor::ForKind(to_kind)->name());
3244
  if (IsSimpleMapChangeTransition(from_kind, to_kind)) stream->Add(" (simple)");
3245 3246 3247
}


3248
void HLoadGlobalCell::PrintDataTo(StringStream* stream) {
3249
  stream->Add("[%p]", *cell().handle());
3250 3251 3252 3253 3254
  if (!details_.IsDontDelete()) stream->Add(" (deleteable)");
  if (details_.IsReadOnly()) stream->Add(" (read-only)");
}


3255
bool HLoadGlobalCell::RequiresHoleCheck() const {
3256 3257 3258 3259 3260 3261
  if (details_.IsDontDelete() && !details_.IsReadOnly()) return false;
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
    HValue* use = it.value();
    if (!use->IsChange()) return true;
  }
  return false;
3262 3263 3264
}


3265 3266 3267 3268 3269
void HLoadGlobalGeneric::PrintDataTo(StringStream* stream) {
  stream->Add("%o ", *name());
}


3270 3271 3272 3273 3274 3275
void HInnerAllocatedObject::PrintDataTo(StringStream* stream) {
  base_object()->PrintNameTo(stream);
  stream->Add(" offset %d", offset());
}


3276
void HStoreGlobalCell::PrintDataTo(StringStream* stream) {
3277
  stream->Add("[%p] = ", *cell().handle());
3278
  value()->PrintNameTo(stream);
3279 3280
  if (!details_.IsDontDelete()) stream->Add(" (deleteable)");
  if (details_.IsReadOnly()) stream->Add(" (read-only)");
3281 3282 3283
}


3284 3285 3286 3287 3288 3289
void HStoreGlobalGeneric::PrintDataTo(StringStream* stream) {
  stream->Add("%o = ", *name());
  value()->PrintNameTo(stream);
}


3290
void HLoadContextSlot::PrintDataTo(StringStream* stream) {
3291 3292 3293 3294 3295
  value()->PrintNameTo(stream);
  stream->Add("[%d]", slot_index());
}


3296
void HStoreContextSlot::PrintDataTo(StringStream* stream) {
3297 3298 3299
  context()->PrintNameTo(stream);
  stream->Add("[%d] = ", slot_index());
  value()->PrintNameTo(stream);
3300 3301 3302
}


3303 3304 3305
// Implementation of type inference and type conversions. Calculates
// the inferred type of this instruction based on the input operands.

3306
HType HValue::CalculateInferredType() {
3307 3308 3309 3310
  return type_;
}


3311
HType HPhi::CalculateInferredType() {
3312 3313 3314
  if (OperandCount() == 0) return HType::Tagged();
  HType result = OperandAt(0)->type();
  for (int i = 1; i < OperandCount(); ++i) {
3315 3316 3317 3318 3319 3320 3321
    HType current = OperandAt(i)->type();
    result = result.Combine(current);
  }
  return result;
}


3322 3323 3324 3325 3326 3327
HType HChange::CalculateInferredType() {
  if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
  return type();
}


3328 3329 3330 3331 3332
Representation HUnaryMathOperation::RepresentationFromInputs() {
  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();
3333 3334 3335
  if (!input_rep.IsTagged()) {
    rep = rep.generalize(input_rep);
  }
3336 3337 3338 3339
  return rep;
}


3340 3341 3342
void HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
                                          HValue* dominator) {
  ASSERT(side_effect == kChangesNewSpacePromotion);
3343
  Zone* zone = block()->zone();
3344
  if (!FLAG_use_allocation_folding) return;
3345

3346
  // Try to fold allocations together with their dominating allocations.
3347 3348 3349 3350 3351
  if (!dominator->IsAllocate()) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s)\n",
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
3352 3353
    return;
  }
3354

3355 3356
  HAllocate* dominator_allocate = HAllocate::cast(dominator);
  HValue* dominator_size = dominator_allocate->size();
3357
  HValue* current_size = size();
3358

3359
  // TODO(hpayer): Add support for non-constant allocation in dominator.
3360
  if (!current_size->IsInteger32Constant() ||
3361
      !dominator_size->IsInteger32Constant()) {
3362
    if (FLAG_trace_allocation_folding) {
3363
      PrintF("#%d (%s) cannot fold into #%d (%s), dynamic allocation size\n",
3364 3365
          id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
    }
3366 3367 3368
    return;
  }

3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
  dominator_allocate = GetFoldableDominator(dominator_allocate);
  if (dominator_allocate == NULL) {
    return;
  }

  ASSERT((IsNewSpaceAllocation() &&
         dominator_allocate->IsNewSpaceAllocation()) ||
         (IsOldDataSpaceAllocation() &&
         dominator_allocate->IsOldDataSpaceAllocation()) ||
         (IsOldPointerSpaceAllocation() &&
         dominator_allocate->IsOldPointerSpaceAllocation()));

3381
  // First update the size of the dominator allocate instruction.
3382
  dominator_size = dominator_allocate->size();
3383
  int32_t original_object_size =
3384
      HConstant::cast(dominator_size)->GetInteger32Constant();
3385
  int32_t dominator_size_constant = original_object_size;
3386 3387
  int32_t current_size_constant =
      HConstant::cast(current_size)->GetInteger32Constant();
3388
  int32_t new_dominator_size = dominator_size_constant + current_size_constant;
3389 3390

  if (MustAllocateDoubleAligned()) {
3391 3392
    if (!dominator_allocate->MustAllocateDoubleAligned()) {
      dominator_allocate->MakeDoubleAligned();
3393 3394 3395 3396 3397 3398 3399
    }
    if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
      dominator_size_constant += kDoubleSize / 2;
      new_dominator_size += kDoubleSize / 2;
    }
  }

3400 3401 3402
  if (new_dominator_size > Page::kMaxNonCodeHeapObjectSize) {
    if (FLAG_trace_allocation_folding) {
      PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3403 3404
          id(), Mnemonic(), dominator_allocate->id(),
          dominator_allocate->Mnemonic(), new_dominator_size);
3405 3406 3407
    }
    return;
  }
3408 3409

  HInstruction* new_dominator_size_constant = HConstant::CreateAndInsertBefore(
3410 3411 3412 3413 3414
      zone,
      context(),
      new_dominator_size,
      Representation::None(),
      dominator_allocate);
3415
  dominator_allocate->UpdateSize(new_dominator_size_constant);
3416

3417
#ifdef VERIFY_HEAP
3418 3419
  if (FLAG_verify_heap && dominator_allocate->IsNewSpaceAllocation()) {
    dominator_allocate->MakePrefillWithFiller();
3420 3421 3422
  } else {
    // TODO(hpayer): This is a short-term hack to make allocation mementos
    // work again in new space.
3423
    dominator_allocate->ClearNextMapWord(original_object_size);
3424
  }
3425 3426 3427
#else
  // TODO(hpayer): This is a short-term hack to make allocation mementos
  // work again in new space.
3428
  dominator_allocate->ClearNextMapWord(original_object_size);
3429 3430
#endif

3431 3432
  dominator_allocate->clear_next_map_word_ = clear_next_map_word_;

3433 3434
  // After that replace the dominated allocate instruction.
  HInstruction* dominated_allocate_instr =
3435 3436
      HInnerAllocatedObject::New(zone,
                                 context(),
3437
                                 dominator_allocate,
3438 3439
                                 dominator_size_constant,
                                 type());
3440 3441 3442 3443
  dominated_allocate_instr->InsertBefore(this);
  DeleteAndReplaceWith(dominated_allocate_instr);
  if (FLAG_trace_allocation_folding) {
    PrintF("#%d (%s) folded into #%d (%s)\n",
3444 3445
        id(), Mnemonic(), dominator_allocate->id(),
        dominator_allocate->Mnemonic());
3446 3447 3448 3449
  }
}


3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
HAllocate* HAllocate::GetFoldableDominator(HAllocate* dominator) {
  if (!IsFoldable(dominator)) {
    // We cannot hoist old space allocations over new space allocations.
    if (IsNewSpaceAllocation() || dominator->IsNewSpaceAllocation()) {
      if (FLAG_trace_allocation_folding) {
        PrintF("#%d (%s) cannot fold into #%d (%s), new space hoisting\n",
            id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
      }
      return NULL;
    }

    HAllocate* dominator_dominator = dominator->dominating_allocate_;

    // We can hoist old data space allocations over an old pointer space
    // allocation and vice versa. For that we have to check the dominator
    // of the dominator allocate instruction.
    if (dominator_dominator == NULL) {
      dominating_allocate_ = dominator;
      if (FLAG_trace_allocation_folding) {
        PrintF("#%d (%s) cannot fold into #%d (%s), different spaces\n",
            id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
      }
      return NULL;
    }

    // We can just fold old space allocations that are in the same basic block,
    // since it is not guaranteed that we fill up the whole allocated old
    // space memory.
    // TODO(hpayer): Remove this limitation and add filler maps for each each
    // allocation as soon as we have store elimination.
    if (block()->block_id() != dominator_dominator->block()->block_id()) {
      if (FLAG_trace_allocation_folding) {
        PrintF("#%d (%s) cannot fold into #%d (%s), different basic blocks\n",
            id(), Mnemonic(), dominator_dominator->id(),
            dominator_dominator->Mnemonic());
      }
      return NULL;
    }

    ASSERT((IsOldDataSpaceAllocation() &&
           dominator_dominator->IsOldDataSpaceAllocation()) ||
           (IsOldPointerSpaceAllocation() &&
           dominator_dominator->IsOldPointerSpaceAllocation()));

    int32_t current_size = HConstant::cast(size())->GetInteger32Constant();
    HStoreNamedField* dominator_free_space_size =
        dominator->filler_free_space_size_;
    if (dominator_free_space_size != NULL) {
      // We already hoisted one old space allocation, i.e., we already installed
      // a filler map. Hence, we just have to update the free space size.
      dominator->UpdateFreeSpaceFiller(current_size);
    } else {
      // This is the first old space allocation that gets hoisted. We have to
      // install a filler map since the follwing allocation may cause a GC.
      dominator->CreateFreeSpaceFiller(current_size);
    }

    // We can hoist the old space allocation over the actual dominator.
    return dominator_dominator;
  }
  return dominator;
}


void HAllocate::UpdateFreeSpaceFiller(int32_t free_space_size) {
  ASSERT(filler_free_space_size_ != NULL);
  Zone* zone = block()->zone();
3517 3518 3519
  // 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.
3520 3521 3522 3523 3524
  HConstant* new_free_space_size = HConstant::CreateAndInsertBefore(
      zone,
      context(),
      filler_free_space_size_->value()->GetInteger32Constant() +
          free_space_size,
3525
      Representation::Smi(),
3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
      filler_free_space_size_);
  filler_free_space_size_->UpdateValue(new_free_space_size);
}


void HAllocate::CreateFreeSpaceFiller(int32_t free_space_size) {
  ASSERT(filler_free_space_size_ == NULL);
  Zone* zone = block()->zone();
  int32_t dominator_size =
      HConstant::cast(dominating_allocate_->size())->GetInteger32Constant();
  HInstruction* free_space_instr =
      HInnerAllocatedObject::New(zone, context(), dominating_allocate_,
      dominator_size, type());
  free_space_instr->InsertBefore(this);
  HConstant* filler_map = HConstant::New(
      zone,
      context(),
3543 3544
      isolate()->factory()->free_space_map());
  filler_map->FinalizeUniqueness();  // TODO(titzer): should be init'd a'ready
3545 3546 3547 3548 3549 3550
  filler_map->InsertAfter(free_space_instr);
  HInstruction* store_map = HStoreNamedField::New(zone, context(),
      free_space_instr, HObjectAccess::ForMap(), filler_map);
  store_map->SetFlag(HValue::kHasNoObservableSideEffects);
  store_map->InsertAfter(filler_map);

3551 3552 3553
  // 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.
3554
  HConstant* filler_size = HConstant::CreateAndInsertAfter(
3555 3556
      zone, context(), free_space_size, Representation::Smi(), store_map);
  // Must force Smi representation for x64 (see comment above).
3557
  HObjectAccess access =
3558 3559
      HObjectAccess::ForJSObjectOffset(FreeSpace::kSizeOffset,
          Representation::Smi());
3560 3561 3562 3563 3564 3565 3566 3567
  HStoreNamedField* store_size = HStoreNamedField::New(zone, context(),
      free_space_instr, access, filler_size);
  store_size->SetFlag(HValue::kHasNoObservableSideEffects);
  store_size->InsertAfter(filler_size);
  filler_free_space_size_ = store_size;
}


3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
void HAllocate::ClearNextMapWord(int offset) {
  if (clear_next_map_word_) {
    Zone* zone = block()->zone();
    HObjectAccess access = HObjectAccess::ForJSObjectOffset(offset);
    HStoreNamedField* clear_next_map =
        HStoreNamedField::New(zone, context(), this, access,
            block()->graph()->GetConstantNull());
    clear_next_map->ClearAllSideEffects();
    clear_next_map->InsertAfter(this);
  }
}


3581 3582
void HAllocate::PrintDataTo(StringStream* stream) {
  size()->PrintNameTo(stream);
3583 3584 3585 3586 3587 3588 3589
  stream->Add(" (");
  if (IsNewSpaceAllocation()) stream->Add("N");
  if (IsOldPointerSpaceAllocation()) stream->Add("P");
  if (IsOldDataSpaceAllocation()) stream->Add("D");
  if (MustAllocateDoubleAligned()) stream->Add("A");
  if (MustPrefillWithFiller()) stream->Add("F");
  stream->Add(")");
3590 3591 3592
}


3593 3594 3595
HValue* HUnaryMathOperation::EnsureAndPropagateNotMinusZero(
    BitVector* visited) {
  visited->Add(id());
3596 3597
  if (representation().IsSmiOrInteger32() &&
      !value()->representation().Equals(representation())) {
3598 3599 3600 3601
    if (value()->range() == NULL || value()->range()->CanBeMinusZero()) {
      SetFlag(kBailoutOnMinusZero);
    }
  }
3602 3603
  if (RequiredInputRepresentation(0).IsSmiOrInteger32() &&
      representation().Equals(RequiredInputRepresentation(0))) {
3604 3605 3606 3607 3608 3609 3610 3611
    return value();
  }
  return NULL;
}


HValue* HChange::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
3612
  if (from().IsSmiOrInteger32()) return NULL;
3613 3614 3615 3616
  if (CanTruncateToInt32()) return NULL;
  if (value()->range() == NULL || value()->range()->CanBeMinusZero()) {
    SetFlag(kBailoutOnMinusZero);
  }
3617
  ASSERT(!from().IsSmiOrInteger32() || !to().IsSmiOrInteger32());
3618 3619 3620 3621
  return NULL;
}


3622 3623 3624 3625 3626 3627 3628
HValue* HForceRepresentation::EnsureAndPropagateNotMinusZero(
    BitVector* visited) {
  visited->Add(id());
  return value();
}


3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
HValue* HMod::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  if (range() == NULL || range()->CanBeMinusZero()) {
    SetFlag(kBailoutOnMinusZero);
    return left();
  }
  return NULL;
}


HValue* HDiv::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  if (range() == NULL || range()->CanBeMinusZero()) {
    SetFlag(kBailoutOnMinusZero);
  }
  return NULL;
}


3648 3649 3650 3651 3652 3653 3654
HValue* HMathFloorOfDiv::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  SetFlag(kBailoutOnMinusZero);
  return NULL;
}


3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
HValue* HMul::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  if (range() == NULL || range()->CanBeMinusZero()) {
    SetFlag(kBailoutOnMinusZero);
  }
  return NULL;
}


HValue* HSub::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  // Propagate to the left argument. If the left argument cannot be -0, then
  // the result of the add operation cannot be either.
  if (range() == NULL || range()->CanBeMinusZero()) {
    return left();
  }
  return NULL;
}


HValue* HAdd::EnsureAndPropagateNotMinusZero(BitVector* visited) {
  visited->Add(id());
  // Propagate to the left argument. If the left argument cannot be -0, then
  // the result of the sub operation cannot be either.
  if (range() == NULL || range()->CanBeMinusZero()) {
    return left();
  }
  return NULL;
}


3686
bool HStoreKeyed::NeedsCanonicalization() {
3687 3688 3689
  // If value is an integer or smi or comes from the result of a keyed load or
  // constant then it is either be a non-hole value or in the case of a constant
  // the hole is only being stored explicitly: no need for canonicalization.
3690 3691 3692 3693 3694
  //
  // The exception to that is keyed loads from external float or double arrays:
  // these can load arbitrary representation of NaN.

  if (value()->IsConstant()) {
3695 3696
    return false;
  }
3697

3698 3699 3700 3701 3702
  if (value()->IsLoadKeyed()) {
    return IsExternalFloatOrDoubleElementsKind(
        HLoadKeyed::cast(value())->elements_kind());
  }

3703
  if (value()->IsChange()) {
3704
    if (HChange::cast(value())->from().IsSmiOrInteger32()) {
3705 3706 3707 3708 3709 3710
      return false;
    }
    if (HChange::cast(value())->value()->type().IsSmi()) {
      return false;
    }
  }
3711 3712 3713 3714
  return true;
}


3715 3716
#define H_CONSTANT_INT(val)                                                    \
HConstant::New(zone, context, static_cast<int32_t>(val))
3717
#define H_CONSTANT_DOUBLE(val)                                                 \
3718
HConstant::New(zone, context, static_cast<double>(val))
3719 3720

#define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op)                       \
3721 3722 3723
HInstruction* HInstr::New(                                                     \
    Zone* zone, HValue* context, HValue* left, HValue* right) {                \
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {      \
3724 3725 3726 3727 3728
    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 (TypeInfo::IsInt32Double(double_res)) {                               \
3729
        return H_CONSTANT_INT(double_res);                                     \
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
      }                                                                        \
      return H_CONSTANT_DOUBLE(double_res);                                    \
    }                                                                          \
  }                                                                            \
  return new(zone) HInstr(context, left, right);                               \
}


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


3745 3746 3747 3748 3749
HInstruction* HStringAdd::New(Zone* zone,
                              HValue* context,
                              HValue* left,
                              HValue* right,
                              StringAddFlags flags) {
3750 3751 3752 3753
  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()) {
3754 3755
      Handle<String> concat = zone->isolate()->factory()->NewFlatConcatString(
          c_left->StringValue(), c_right->StringValue());
3756
      return HConstant::New(zone, context, concat);
3757 3758
    }
  }
3759
  return new(zone) HStringAdd(context, left, right, flags);
3760 3761 3762 3763 3764 3765 3766
}


HInstruction* HStringCharFromCode::New(
    Zone* zone, HValue* context, HValue* char_code) {
  if (FLAG_fold_constants && char_code->IsConstant()) {
    HConstant* c_code = HConstant::cast(char_code);
3767
    Isolate* isolate = zone->isolate();
3768
    if (c_code->HasNumberValue()) {
3769
      if (std::isfinite(c_code->DoubleValue())) {
3770
        uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
3771 3772
        return HConstant::New(zone, context,
            LookupSingleCharacterStringFromCode(isolate, code));
3773
      }
3774
      return HConstant::New(zone, context, isolate->factory()->empty_string());
3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788
    }
  }
  return new(zone) HStringCharFromCode(context, char_code);
}


HInstruction* HUnaryMathOperation::New(
    Zone* zone, HValue* context, HValue* value, BuiltinFunctionId op) {
  do {
    if (!FLAG_fold_constants) break;
    if (!value->IsConstant()) break;
    HConstant* constant = HConstant::cast(value);
    if (!constant->HasNumberValue()) break;
    double d = constant->DoubleValue();
3789
    if (std::isnan(d)) {  // NaN poisons everything.
3790 3791
      return H_CONSTANT_DOUBLE(OS::nan_value());
    }
3792
    if (std::isinf(d)) {  // +Infinity and -Infinity.
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848
      switch (op) {
        case kMathSin:
        case kMathCos:
        case kMathTan:
          return H_CONSTANT_DOUBLE(OS::nan_value());
        case kMathExp:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
        case kMathLog:
        case kMathSqrt:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : OS::nan_value());
        case kMathPowHalf:
        case kMathAbs:
          return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
        case kMathRound:
        case kMathFloor:
          return H_CONSTANT_DOUBLE(d);
        default:
          UNREACHABLE();
          break;
      }
    }
    switch (op) {
      case kMathSin:
        return H_CONSTANT_DOUBLE(fast_sin(d));
      case kMathCos:
        return H_CONSTANT_DOUBLE(fast_cos(d));
      case kMathTan:
        return H_CONSTANT_DOUBLE(fast_tan(d));
      case kMathExp:
        return H_CONSTANT_DOUBLE(fast_exp(d));
      case kMathLog:
        return H_CONSTANT_DOUBLE(fast_log(d));
      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);
        return H_CONSTANT_DOUBLE(floor(d + 0.5));
      case kMathFloor:
        return H_CONSTANT_DOUBLE(floor(d));
      default:
        UNREACHABLE();
        break;
    }
  } while (false);
  return new(zone) HUnaryMathOperation(context, value, op);
}


3849 3850 3851 3852
HInstruction* HPower::New(Zone* zone,
                          HValue* context,
                          HValue* left,
                          HValue* right) {
3853 3854 3855 3856 3857 3858
  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());
3859
      return H_CONSTANT_DOUBLE(std::isnan(result) ?  OS::nan_value() : result);
3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898
    }
  }
  return new(zone) HPower(left, right);
}


HInstruction* HMathMinMax::New(
    Zone* zone, HValue* context, HValue* left, HValue* right, Operation op) {
  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.
      return H_CONSTANT_DOUBLE(OS::nan_value());
    }
  }
  return new(zone) HMathMinMax(context, left, right, op);
}


3899 3900 3901 3902
HInstruction* HMod::New(Zone* zone,
                        HValue* context,
                        HValue* left,
                        HValue* right,
3903
                        Maybe<int> fixed_right_arg) {
3904
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3905 3906 3907 3908 3909
    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();
3910 3911 3912
      if (dividend == kMinInt && divisor == -1) {
        return H_CONSTANT_DOUBLE(-0.0);
      }
3913 3914 3915 3916 3917
      if (divisor != 0) {
        int32_t res = dividend % divisor;
        if ((res == 0) && (dividend < 0)) {
          return H_CONSTANT_DOUBLE(-0.0);
        }
3918
        return H_CONSTANT_INT(res);
3919 3920 3921
      }
    }
  }
3922
  return new(zone) HMod(context, left, right, fixed_right_arg);
3923 3924 3925
}


3926 3927
HInstruction* HDiv::New(
    Zone* zone, HValue* context, HValue* left, HValue* right) {
3928
  // If left and right are constant values, try to return a constant value.
3929
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3930 3931 3932 3933 3934 3935
    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();
        if (TypeInfo::IsInt32Double(double_res)) {
3936
          return H_CONSTANT_INT(double_res);
3937 3938
        }
        return H_CONSTANT_DOUBLE(double_res);
3939 3940 3941 3942
      } else {
        int sign = Double(c_left->DoubleValue()).Sign() *
                   Double(c_right->DoubleValue()).Sign();  // Right could be -0.
        return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
3943 3944 3945 3946 3947 3948 3949
      }
    }
  }
  return new(zone) HDiv(context, left, right);
}


3950
HInstruction* HBitwise::New(
3951
    Zone* zone, HValue* context, Token::Value op, HValue* left, HValue* right) {
3952
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972
    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();
      }
3973
      return H_CONSTANT_INT(result);
3974 3975
    }
  }
3976
  return new(zone) HBitwise(context, op, left, right);
3977 3978 3979 3980
}


#define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result)                             \
3981 3982 3983
HInstruction* HInstr::New(                                                     \
    Zone* zone, HValue* context, HValue* left, HValue* right) {                \
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {      \
3984 3985 3986
    HConstant* c_left = HConstant::cast(left);                                 \
    HConstant* c_right = HConstant::cast(right);                               \
    if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {             \
3987
      return H_CONSTANT_INT(result);                                           \
3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
    }                                                                          \
  }                                                                            \
  return new(zone) HInstr(context, left, right);                               \
}


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


4002 4003 4004
HInstruction* HShr::New(
    Zone* zone, HValue* context, HValue* left, HValue* right) {
  if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4005 4006 4007 4008 4009 4010
    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)) {
4011
        return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
4012
      }
4013
      return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
4014 4015 4016 4017 4018 4019
    }
  }
  return new(zone) HShr(context, left, right);
}


4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
HInstruction* HSeqStringGetChar::New(Zone* zone,
                                     HValue* context,
                                     String::Encoding encoding,
                                     HValue* string,
                                     HValue* index) {
  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();
      ASSERT_LE(0, i);
      ASSERT_LT(i, s->length());
      return H_CONSTANT_INT(s->Get(i));
    }
  }
  return new(zone) HSeqStringGetChar(encoding, string, index);
}


4040
#undef H_CONSTANT_INT
4041 4042 4043
#undef H_CONSTANT_DOUBLE


4044 4045 4046 4047 4048 4049 4050
void HBitwise::PrintDataTo(StringStream* stream) {
  stream->Add(Token::Name(op_));
  stream->Add(" ");
  HBitwiseBinaryOperation::PrintDataTo(stream);
}


4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064
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()) {
      HConstant* integer_input =
4065 4066
          HConstant::New(graph->zone(), graph->GetInvalidContext(),
                         DoubleToInt32(operand->DoubleValue()));
4067 4068
      integer_input->InsertAfter(operand);
      SetOperandAt(i, integer_input);
4069 4070 4071 4072
    } else if (operand->HasBooleanValue()) {
      SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
                                              : graph->GetConstant0());
    } else if (operand->ImmortalImmovable()) {
4073 4074 4075 4076 4077 4078 4079 4080
      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(
4081
          it.index(), Representation::Smi());
4082 4083 4084 4085 4086
    }
  }
}


4087
void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
4088
  ASSERT(CheckFlag(kFlexibleRepresentation));
4089
  Representation new_rep = RepresentationFromInputs();
4090 4091 4092 4093 4094 4095 4096 4097 4098
  UpdateRepresentation(new_rep, h_infer, "inputs");
  new_rep = RepresentationFromUses();
  UpdateRepresentation(new_rep, h_infer, "uses");
  new_rep = RepresentationFromUseRequirements();
  UpdateRepresentation(new_rep, h_infer, "use requirements");
}


Representation HPhi::RepresentationFromInputs() {
4099
  Representation r = Representation::None();
4100
  for (int i = 0; i < OperandCount(); ++i) {
4101
    r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
4102
  }
4103
  return r;
4104 4105 4106
}


4107 4108 4109 4110
// 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();
4111
  for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4112
    // Ignore the use requirement from never run code
4113
    if (it.value()->block()->IsUnreachable()) continue;
4114

4115 4116 4117
    // We check for observed_input_representation elsewhere.
    Representation use_rep =
        it.value()->RequiredInputRepresentation(it.index());
4118 4119
    if (rep.IsNone()) {
      rep = use_rep;
4120 4121
      continue;
    }
4122 4123 4124
    if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
    if (rep.generalize(use_rep).IsInteger32()) {
      rep = Representation::Integer32();
4125 4126
      continue;
    }
4127
    return Representation::None();
4128
  }
4129
  return rep;
4130 4131 4132
}


4133 4134 4135 4136 4137
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());
4138 4139 4140 4141 4142
    if (!use_rep.IsNone() &&
        !use_rep.IsSmi() &&
        !use_rep.IsTagged()) {
      return true;
    }
4143 4144 4145 4146 4147
  }
  return false;
}


4148 4149 4150
// Node-specific verification code is only included in debug mode.
#ifdef DEBUG

4151
void HPhi::Verify() {
4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162
  ASSERT(OperandCount() == block()->predecessors()->length());
  for (int i = 0; i < OperandCount(); ++i) {
    HValue* value = OperandAt(i);
    HBasicBlock* defining_block = value->block();
    HBasicBlock* predecessor_block = block()->predecessors()->at(i);
    ASSERT(defining_block == predecessor_block ||
           defining_block->Dominates(predecessor_block));
  }
}


4163
void HSimulate::Verify() {
4164 4165 4166 4167 4168
  HInstruction::Verify();
  ASSERT(HasAstId());
}


4169
void HCheckHeapObject::Verify() {
4170 4171 4172 4173 4174
  HInstruction::Verify();
  ASSERT(HasNoUses());
}


4175
void HCheckValue::Verify() {
4176 4177 4178 4179 4180 4181
  HInstruction::Verify();
  ASSERT(HasNoUses());
}

#endif

4182 4183 4184 4185 4186 4187 4188 4189 4190

HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
  ASSERT(offset >= 0);
  ASSERT(offset < FixedArray::kHeaderSize);
  if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
  return HObjectAccess(kInobject, offset);
}


4191 4192
HObjectAccess HObjectAccess::ForJSObjectOffset(int offset,
    Representation representation) {
4193 4194 4195 4196 4197 4198 4199 4200
  ASSERT(offset >= 0);
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
4201
  return HObjectAccess(portion, offset, representation);
4202 4203 4204
}


4205 4206 4207 4208 4209 4210 4211 4212 4213
HObjectAccess HObjectAccess::ForContextSlot(int index) {
  ASSERT(index >= 0);
  Portion portion = kInobject;
  int offset = Context::kHeaderSize + index * kPointerSize;
  ASSERT_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
  return HObjectAccess(portion, offset, Representation::Tagged());
}


4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224
HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
  ASSERT(offset >= 0);
  Portion portion = kInobject;

  if (offset == JSObject::kElementsOffset) {
    portion = kElementsPointer;
  } else if (offset == JSArray::kLengthOffset) {
    portion = kArrayLengths;
  } else if (offset == JSObject::kMapOffset) {
    portion = kMaps;
  }
4225
  return HObjectAccess(portion, offset);
4226 4227 4228
}


4229 4230
HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
    Representation representation) {
4231
  ASSERT(offset >= 0);
4232
  return HObjectAccess(kBackingStore, offset, representation);
4233 4234 4235 4236 4237 4238 4239
}


HObjectAccess HObjectAccess::ForField(Handle<Map> map,
    LookupResult *lookup, Handle<String> name) {
  ASSERT(lookup->IsField() || lookup->IsTransitionToField(*map));
  int index;
4240
  Representation representation;
4241 4242
  if (lookup->IsField()) {
    index = lookup->GetLocalFieldIndexFromMap(*map);
4243
    representation = lookup->representation();
4244 4245 4246 4247 4248
  } else {
    Map* transition = lookup->GetTransitionMapFromMap(*map);
    int descriptor = transition->LastAdded();
    index = transition->instance_descriptors()->GetFieldIndex(descriptor) -
        map->inobject_properties();
4249 4250 4251
    PropertyDetails details =
        transition->instance_descriptors()->GetDetails(descriptor);
    representation = details.representation();
4252 4253 4254 4255 4256
  }
  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();
4257
    return HObjectAccess(kInobject, offset, representation);
4258 4259 4260
  } else {
    // Non-negative property indices are in the properties array.
    int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
4261
    return HObjectAccess(kBackingStore, offset, representation, name);
4262 4263 4264 4265
  }
}


4266 4267
HObjectAccess HObjectAccess::ForCellPayload(Isolate* isolate) {
  return HObjectAccess(
4268
      kInobject, Cell::kValueOffset, Representation::Tagged(),
4269 4270 4271 4272
      Handle<String>(isolate->heap()->cell_value_string()));
}


4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
void HObjectAccess::SetGVNFlags(HValue *instr, bool is_store) {
  // set the appropriate GVN flags for a given load or store instruction
  if (is_store) {
    // track dominating allocations in order to eliminate write barriers
    instr->SetGVNFlag(kDependsOnNewSpacePromotion);
    instr->SetFlag(HValue::kTrackSideEffectDominators);
  } else {
    // try to GVN loads, but don't hoist above map changes
    instr->SetFlag(HValue::kUseGVN);
    instr->SetGVNFlag(kDependsOnMaps);
  }

  switch (portion()) {
    case kArrayLengths:
      instr->SetGVNFlag(is_store
          ? kChangesArrayLengths : kDependsOnArrayLengths);
      break;
4290 4291 4292 4293
    case kStringLengths:
      instr->SetGVNFlag(is_store
          ? kChangesStringLengths : kDependsOnStringLengths);
      break;
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313
    case kInobject:
      instr->SetGVNFlag(is_store
          ? kChangesInobjectFields : kDependsOnInobjectFields);
      break;
    case kDouble:
      instr->SetGVNFlag(is_store
          ? kChangesDoubleFields : kDependsOnDoubleFields);
      break;
    case kBackingStore:
      instr->SetGVNFlag(is_store
          ? kChangesBackingStoreFields : kDependsOnBackingStoreFields);
      break;
    case kElementsPointer:
      instr->SetGVNFlag(is_store
          ? kChangesElementsPointer : kDependsOnElementsPointer);
      break;
    case kMaps:
      instr->SetGVNFlag(is_store
          ? kChangesMaps : kDependsOnMaps);
      break;
4314 4315 4316 4317
    case kExternalMemory:
      instr->SetGVNFlag(is_store
          ? kChangesExternalMemory : kDependsOnExternalMemory);
      break;
4318 4319 4320 4321 4322 4323 4324 4325 4326
  }
}


void HObjectAccess::PrintTo(StringStream* stream) {
  stream->Add(".");

  switch (portion()) {
    case kArrayLengths:
4327
    case kStringLengths:
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
      stream->Add("%length");
      break;
    case kElementsPointer:
      stream->Add("%elements");
      break;
    case kMaps:
      stream->Add("%map");
      break;
    case kDouble:  // fall through
    case kInobject:
      if (!name_.is_null()) stream->Add(*String::cast(*name_)->ToCString());
      stream->Add("[in-object]");
      break;
    case kBackingStore:
      if (!name_.is_null()) stream->Add(*String::cast(*name_)->ToCString());
      stream->Add("[backing-store]");
      break;
4345 4346 4347
    case kExternalMemory:
      stream->Add("[external-memory]");
      break;
4348 4349 4350 4351 4352
  }

  stream->Add("@%d", offset());
}

4353
} }  // namespace v8::internal