blob: 7de8b5d4a297186ac44c4ff8dd194742755136c3 [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/crankshaft/hydrogen-instructions.h"
6
7#include "src/base/bits.h"
8#include "src/base/safe_math.h"
9#include "src/crankshaft/hydrogen-infer-representation.h"
10#include "src/double.h"
11#include "src/elements.h"
12#include "src/factory.h"
13
14#if V8_TARGET_ARCH_IA32
15#include "src/crankshaft/ia32/lithium-ia32.h" // NOLINT
16#elif V8_TARGET_ARCH_X64
17#include "src/crankshaft/x64/lithium-x64.h" // NOLINT
18#elif V8_TARGET_ARCH_ARM64
19#include "src/crankshaft/arm64/lithium-arm64.h" // NOLINT
20#elif V8_TARGET_ARCH_ARM
21#include "src/crankshaft/arm/lithium-arm.h" // NOLINT
22#elif V8_TARGET_ARCH_PPC
23#include "src/crankshaft/ppc/lithium-ppc.h" // NOLINT
24#elif V8_TARGET_ARCH_MIPS
25#include "src/crankshaft/mips/lithium-mips.h" // NOLINT
26#elif V8_TARGET_ARCH_MIPS64
27#include "src/crankshaft/mips64/lithium-mips64.h" // NOLINT
Ben Murdochda12d292016-06-02 14:46:10 +010028#elif V8_TARGET_ARCH_S390
29#include "src/crankshaft/s390/lithium-s390.h" // NOLINT
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000030#elif V8_TARGET_ARCH_X87
31#include "src/crankshaft/x87/lithium-x87.h" // NOLINT
32#else
33#error Unsupported target architecture.
34#endif
35
36namespace v8 {
37namespace internal {
38
39#define DEFINE_COMPILE(type) \
40 LInstruction* H##type::CompileToLithium(LChunkBuilder* builder) { \
41 return builder->Do##type(this); \
42 }
43HYDROGEN_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
44#undef DEFINE_COMPILE
45
46
47Isolate* HValue::isolate() const {
48 DCHECK(block() != NULL);
49 return block()->isolate();
50}
51
52
53void HValue::AssumeRepresentation(Representation r) {
54 if (CheckFlag(kFlexibleRepresentation)) {
55 ChangeRepresentation(r);
56 // The representation of the value is dictated by type feedback and
57 // will not be changed later.
58 ClearFlag(kFlexibleRepresentation);
59 }
60}
61
62
63void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
64 DCHECK(CheckFlag(kFlexibleRepresentation));
65 Representation new_rep = RepresentationFromInputs();
66 UpdateRepresentation(new_rep, h_infer, "inputs");
67 new_rep = RepresentationFromUses();
68 UpdateRepresentation(new_rep, h_infer, "uses");
69 if (representation().IsSmi() && HasNonSmiUse()) {
70 UpdateRepresentation(
71 Representation::Integer32(), h_infer, "use requirements");
72 }
73}
74
75
76Representation HValue::RepresentationFromUses() {
77 if (HasNoUses()) return Representation::None();
78 Representation result = Representation::None();
79
80 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
81 HValue* use = it.value();
82 Representation rep = use->observed_input_representation(it.index());
83 result = result.generalize(rep);
84
85 if (FLAG_trace_representation) {
86 PrintF("#%d %s is used by #%d %s as %s%s\n",
87 id(), Mnemonic(), use->id(), use->Mnemonic(), rep.Mnemonic(),
88 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
89 }
90 }
91 if (IsPhi()) {
92 result = result.generalize(
93 HPhi::cast(this)->representation_from_indirect_uses());
94 }
95
96 // External representations are dealt with separately.
97 return result.IsExternal() ? Representation::None() : result;
98}
99
100
101void HValue::UpdateRepresentation(Representation new_rep,
102 HInferRepresentationPhase* h_infer,
103 const char* reason) {
104 Representation r = representation();
105 if (new_rep.is_more_general_than(r)) {
106 if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
107 if (FLAG_trace_representation) {
108 PrintF("Changing #%d %s representation %s -> %s based on %s\n",
109 id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
110 }
111 ChangeRepresentation(new_rep);
112 AddDependantsToWorklist(h_infer);
113 }
114}
115
116
117void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
118 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
119 h_infer->AddToWorklist(it.value());
120 }
121 for (int i = 0; i < OperandCount(); ++i) {
122 h_infer->AddToWorklist(OperandAt(i));
123 }
124}
125
126
127static int32_t ConvertAndSetOverflow(Representation r,
128 int64_t result,
129 bool* overflow) {
130 if (r.IsSmi()) {
131 if (result > Smi::kMaxValue) {
132 *overflow = true;
133 return Smi::kMaxValue;
134 }
135 if (result < Smi::kMinValue) {
136 *overflow = true;
137 return Smi::kMinValue;
138 }
139 } else {
140 if (result > kMaxInt) {
141 *overflow = true;
142 return kMaxInt;
143 }
144 if (result < kMinInt) {
145 *overflow = true;
146 return kMinInt;
147 }
148 }
149 return static_cast<int32_t>(result);
150}
151
152
153static int32_t AddWithoutOverflow(Representation r,
154 int32_t a,
155 int32_t b,
156 bool* overflow) {
157 int64_t result = static_cast<int64_t>(a) + static_cast<int64_t>(b);
158 return ConvertAndSetOverflow(r, result, overflow);
159}
160
161
162static int32_t SubWithoutOverflow(Representation r,
163 int32_t a,
164 int32_t b,
165 bool* overflow) {
166 int64_t result = static_cast<int64_t>(a) - static_cast<int64_t>(b);
167 return ConvertAndSetOverflow(r, result, overflow);
168}
169
170
171static int32_t MulWithoutOverflow(const Representation& r,
172 int32_t a,
173 int32_t b,
174 bool* overflow) {
175 int64_t result = static_cast<int64_t>(a) * static_cast<int64_t>(b);
176 return ConvertAndSetOverflow(r, result, overflow);
177}
178
179
180int32_t Range::Mask() const {
181 if (lower_ == upper_) return lower_;
182 if (lower_ >= 0) {
183 int32_t res = 1;
184 while (res < upper_) {
185 res = (res << 1) | 1;
186 }
187 return res;
188 }
189 return 0xffffffff;
190}
191
192
193void Range::AddConstant(int32_t value) {
194 if (value == 0) return;
195 bool may_overflow = false; // Overflow is ignored here.
196 Representation r = Representation::Integer32();
197 lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
198 upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
199#ifdef DEBUG
200 Verify();
201#endif
202}
203
204
205void Range::Intersect(Range* other) {
206 upper_ = Min(upper_, other->upper_);
207 lower_ = Max(lower_, other->lower_);
208 bool b = CanBeMinusZero() && other->CanBeMinusZero();
209 set_can_be_minus_zero(b);
210}
211
212
213void Range::Union(Range* other) {
214 upper_ = Max(upper_, other->upper_);
215 lower_ = Min(lower_, other->lower_);
216 bool b = CanBeMinusZero() || other->CanBeMinusZero();
217 set_can_be_minus_zero(b);
218}
219
220
221void Range::CombinedMax(Range* other) {
222 upper_ = Max(upper_, other->upper_);
223 lower_ = Max(lower_, other->lower_);
224 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
225}
226
227
228void Range::CombinedMin(Range* other) {
229 upper_ = Min(upper_, other->upper_);
230 lower_ = Min(lower_, other->lower_);
231 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
232}
233
234
235void Range::Sar(int32_t value) {
236 int32_t bits = value & 0x1F;
237 lower_ = lower_ >> bits;
238 upper_ = upper_ >> bits;
239 set_can_be_minus_zero(false);
240}
241
242
243void Range::Shl(int32_t value) {
244 int32_t bits = value & 0x1F;
245 int old_lower = lower_;
246 int old_upper = upper_;
247 lower_ = lower_ << bits;
248 upper_ = upper_ << bits;
249 if (old_lower != lower_ >> bits || old_upper != upper_ >> bits) {
250 upper_ = kMaxInt;
251 lower_ = kMinInt;
252 }
253 set_can_be_minus_zero(false);
254}
255
256
257bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
258 bool may_overflow = false;
259 lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
260 upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
261 KeepOrder();
262#ifdef DEBUG
263 Verify();
264#endif
265 return may_overflow;
266}
267
268
269bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
270 bool may_overflow = false;
271 lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
272 upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
273 KeepOrder();
274#ifdef DEBUG
275 Verify();
276#endif
277 return may_overflow;
278}
279
280
281void Range::KeepOrder() {
282 if (lower_ > upper_) {
283 int32_t tmp = lower_;
284 lower_ = upper_;
285 upper_ = tmp;
286 }
287}
288
289
290#ifdef DEBUG
291void Range::Verify() const {
292 DCHECK(lower_ <= upper_);
293}
294#endif
295
296
297bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
298 bool may_overflow = false;
299 int v1 = MulWithoutOverflow(r, lower_, other->lower(), &may_overflow);
300 int v2 = MulWithoutOverflow(r, lower_, other->upper(), &may_overflow);
301 int v3 = MulWithoutOverflow(r, upper_, other->lower(), &may_overflow);
302 int v4 = MulWithoutOverflow(r, upper_, other->upper(), &may_overflow);
303 lower_ = Min(Min(v1, v2), Min(v3, v4));
304 upper_ = Max(Max(v1, v2), Max(v3, v4));
305#ifdef DEBUG
306 Verify();
307#endif
308 return may_overflow;
309}
310
311
312bool HValue::IsDefinedAfter(HBasicBlock* other) const {
313 return block()->block_id() > other->block_id();
314}
315
316
317HUseListNode* HUseListNode::tail() {
318 // Skip and remove dead items in the use list.
319 while (tail_ != NULL && tail_->value()->CheckFlag(HValue::kIsDead)) {
320 tail_ = tail_->tail_;
321 }
322 return tail_;
323}
324
325
326bool HValue::CheckUsesForFlag(Flag f) const {
327 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
328 if (it.value()->IsSimulate()) continue;
329 if (!it.value()->CheckFlag(f)) return false;
330 }
331 return true;
332}
333
334
335bool HValue::CheckUsesForFlag(Flag f, HValue** value) const {
336 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
337 if (it.value()->IsSimulate()) continue;
338 if (!it.value()->CheckFlag(f)) {
339 *value = it.value();
340 return false;
341 }
342 }
343 return true;
344}
345
346
347bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
348 bool return_value = false;
349 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
350 if (it.value()->IsSimulate()) continue;
351 if (!it.value()->CheckFlag(f)) return false;
352 return_value = true;
353 }
354 return return_value;
355}
356
357
358HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
359 Advance();
360}
361
362
363void HUseIterator::Advance() {
364 current_ = next_;
365 if (current_ != NULL) {
366 next_ = current_->tail();
367 value_ = current_->value();
368 index_ = current_->index();
369 }
370}
371
372
373int HValue::UseCount() const {
374 int count = 0;
375 for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
376 return count;
377}
378
379
380HUseListNode* HValue::RemoveUse(HValue* value, int index) {
381 HUseListNode* previous = NULL;
382 HUseListNode* current = use_list_;
383 while (current != NULL) {
384 if (current->value() == value && current->index() == index) {
385 if (previous == NULL) {
386 use_list_ = current->tail();
387 } else {
388 previous->set_tail(current->tail());
389 }
390 break;
391 }
392
393 previous = current;
394 current = current->tail();
395 }
396
397#ifdef DEBUG
398 // Do not reuse use list nodes in debug mode, zap them.
399 if (current != NULL) {
400 HUseListNode* temp =
401 new(block()->zone())
402 HUseListNode(current->value(), current->index(), NULL);
403 current->Zap();
404 current = temp;
405 }
406#endif
407 return current;
408}
409
410
411bool HValue::Equals(HValue* other) {
412 if (other->opcode() != opcode()) return false;
413 if (!other->representation().Equals(representation())) return false;
414 if (!other->type_.Equals(type_)) return false;
415 if (other->flags() != flags()) return false;
416 if (OperandCount() != other->OperandCount()) return false;
417 for (int i = 0; i < OperandCount(); ++i) {
418 if (OperandAt(i)->id() != other->OperandAt(i)->id()) return false;
419 }
420 bool result = DataEquals(other);
421 DCHECK(!result || Hashcode() == other->Hashcode());
422 return result;
423}
424
425
426intptr_t HValue::Hashcode() {
427 intptr_t result = opcode();
428 int count = OperandCount();
429 for (int i = 0; i < count; ++i) {
430 result = result * 19 + OperandAt(i)->id() + (result >> 7);
431 }
432 return result;
433}
434
435
436const char* HValue::Mnemonic() const {
437 switch (opcode()) {
438#define MAKE_CASE(type) case k##type: return #type;
439 HYDROGEN_CONCRETE_INSTRUCTION_LIST(MAKE_CASE)
440#undef MAKE_CASE
441 case kPhi: return "Phi";
442 default: return "";
443 }
444}
445
446
447bool HValue::CanReplaceWithDummyUses() {
448 return FLAG_unreachable_code_elimination &&
449 !(block()->IsReachable() ||
450 IsBlockEntry() ||
451 IsControlInstruction() ||
452 IsArgumentsObject() ||
453 IsCapturedObject() ||
454 IsSimulate() ||
455 IsEnterInlined() ||
456 IsLeaveInlined());
457}
458
459
460bool HValue::IsInteger32Constant() {
461 return IsConstant() && HConstant::cast(this)->HasInteger32Value();
462}
463
464
465int32_t HValue::GetInteger32Constant() {
466 return HConstant::cast(this)->Integer32Value();
467}
468
469
470bool HValue::EqualsInteger32Constant(int32_t value) {
471 return IsInteger32Constant() && GetInteger32Constant() == value;
472}
473
474
475void HValue::SetOperandAt(int index, HValue* value) {
476 RegisterUse(index, value);
477 InternalSetOperandAt(index, value);
478}
479
480
481void HValue::DeleteAndReplaceWith(HValue* other) {
482 // We replace all uses first, so Delete can assert that there are none.
483 if (other != NULL) ReplaceAllUsesWith(other);
484 Kill();
485 DeleteFromGraph();
486}
487
488
489void HValue::ReplaceAllUsesWith(HValue* other) {
490 while (use_list_ != NULL) {
491 HUseListNode* list_node = use_list_;
492 HValue* value = list_node->value();
493 DCHECK(!value->block()->IsStartBlock());
494 value->InternalSetOperandAt(list_node->index(), other);
495 use_list_ = list_node->tail();
496 list_node->set_tail(other->use_list_);
497 other->use_list_ = list_node;
498 }
499}
500
501
502void HValue::Kill() {
503 // Instead of going through the entire use list of each operand, we only
504 // check the first item in each use list and rely on the tail() method to
505 // skip dead items, removing them lazily next time we traverse the list.
506 SetFlag(kIsDead);
507 for (int i = 0; i < OperandCount(); ++i) {
508 HValue* operand = OperandAt(i);
509 if (operand == NULL) continue;
510 HUseListNode* first = operand->use_list_;
511 if (first != NULL && first->value()->CheckFlag(kIsDead)) {
512 operand->use_list_ = first->tail();
513 }
514 }
515}
516
517
518void HValue::SetBlock(HBasicBlock* block) {
519 DCHECK(block_ == NULL || block == NULL);
520 block_ = block;
521 if (id_ == kNoNumber && block != NULL) {
522 id_ = block->graph()->GetNextValueID(this);
523 }
524}
525
526
527std::ostream& operator<<(std::ostream& os, const HValue& v) {
528 return v.PrintTo(os);
529}
530
531
532std::ostream& operator<<(std::ostream& os, const TypeOf& t) {
533 if (t.value->representation().IsTagged() &&
534 !t.value->type().Equals(HType::Tagged()))
535 return os;
536 return os << " type:" << t.value->type();
537}
538
539
540std::ostream& operator<<(std::ostream& os, const ChangesOf& c) {
541 GVNFlagSet changes_flags = c.value->ChangesFlags();
542 if (changes_flags.IsEmpty()) return os;
543 os << " changes[";
544 if (changes_flags == c.value->AllSideEffectsFlagSet()) {
545 os << "*";
546 } else {
547 bool add_comma = false;
548#define PRINT_DO(Type) \
549 if (changes_flags.Contains(k##Type)) { \
550 if (add_comma) os << ","; \
551 add_comma = true; \
552 os << #Type; \
553 }
554 GVN_TRACKED_FLAG_LIST(PRINT_DO);
555 GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
556#undef PRINT_DO
557 }
558 return os << "]";
559}
560
561
562bool HValue::HasMonomorphicJSObjectType() {
563 return !GetMonomorphicJSObjectMap().is_null();
564}
565
566
567bool HValue::UpdateInferredType() {
568 HType type = CalculateInferredType();
569 bool result = (!type.Equals(type_));
570 type_ = type;
571 return result;
572}
573
574
575void HValue::RegisterUse(int index, HValue* new_value) {
576 HValue* old_value = OperandAt(index);
577 if (old_value == new_value) return;
578
579 HUseListNode* removed = NULL;
580 if (old_value != NULL) {
581 removed = old_value->RemoveUse(this, index);
582 }
583
584 if (new_value != NULL) {
585 if (removed == NULL) {
586 new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
587 this, index, new_value->use_list_);
588 } else {
589 removed->set_tail(new_value->use_list_);
590 new_value->use_list_ = removed;
591 }
592 }
593}
594
595
596void HValue::AddNewRange(Range* r, Zone* zone) {
597 if (!HasRange()) ComputeInitialRange(zone);
598 if (!HasRange()) range_ = new(zone) Range();
599 DCHECK(HasRange());
600 r->StackUpon(range_);
601 range_ = r;
602}
603
604
605void HValue::RemoveLastAddedRange() {
606 DCHECK(HasRange());
607 DCHECK(range_->next() != NULL);
608 range_ = range_->next();
609}
610
611
612void HValue::ComputeInitialRange(Zone* zone) {
613 DCHECK(!HasRange());
614 range_ = InferRange(zone);
615 DCHECK(HasRange());
616}
617
618
619std::ostream& HInstruction::PrintTo(std::ostream& os) const { // NOLINT
620 os << Mnemonic() << " ";
621 PrintDataTo(os) << ChangesOf(this) << TypeOf(this);
622 if (CheckFlag(HValue::kHasNoObservableSideEffects)) os << " [noOSE]";
623 if (CheckFlag(HValue::kIsDead)) os << " [dead]";
624 return os;
625}
626
627
628std::ostream& HInstruction::PrintDataTo(std::ostream& os) const { // NOLINT
629 for (int i = 0; i < OperandCount(); ++i) {
630 if (i > 0) os << " ";
631 os << NameOf(OperandAt(i));
632 }
633 return os;
634}
635
636
637void HInstruction::Unlink() {
638 DCHECK(IsLinked());
639 DCHECK(!IsControlInstruction()); // Must never move control instructions.
640 DCHECK(!IsBlockEntry()); // Doesn't make sense to delete these.
641 DCHECK(previous_ != NULL);
642 previous_->next_ = next_;
643 if (next_ == NULL) {
644 DCHECK(block()->last() == this);
645 block()->set_last(previous_);
646 } else {
647 next_->previous_ = previous_;
648 }
649 clear_block();
650}
651
652
653void HInstruction::InsertBefore(HInstruction* next) {
654 DCHECK(!IsLinked());
655 DCHECK(!next->IsBlockEntry());
656 DCHECK(!IsControlInstruction());
657 DCHECK(!next->block()->IsStartBlock());
658 DCHECK(next->previous_ != NULL);
659 HInstruction* prev = next->previous();
660 prev->next_ = this;
661 next->previous_ = this;
662 next_ = next;
663 previous_ = prev;
664 SetBlock(next->block());
665 if (!has_position() && next->has_position()) {
666 set_position(next->position());
667 }
668}
669
670
671void HInstruction::InsertAfter(HInstruction* previous) {
672 DCHECK(!IsLinked());
673 DCHECK(!previous->IsControlInstruction());
674 DCHECK(!IsControlInstruction() || previous->next_ == NULL);
675 HBasicBlock* block = previous->block();
676 // Never insert anything except constants into the start block after finishing
677 // it.
678 if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
679 DCHECK(block->end()->SecondSuccessor() == NULL);
680 InsertAfter(block->end()->FirstSuccessor()->first());
681 return;
682 }
683
684 // If we're inserting after an instruction with side-effects that is
685 // followed by a simulate instruction, we need to insert after the
686 // simulate instruction instead.
687 HInstruction* next = previous->next_;
688 if (previous->HasObservableSideEffects() && next != NULL) {
689 DCHECK(next->IsSimulate());
690 previous = next;
691 next = previous->next_;
692 }
693
694 previous_ = previous;
695 next_ = next;
696 SetBlock(block);
697 previous->next_ = this;
698 if (next != NULL) next->previous_ = this;
699 if (block->last() == previous) {
700 block->set_last(this);
701 }
702 if (!has_position() && previous->has_position()) {
703 set_position(previous->position());
704 }
705}
706
707
708bool HInstruction::Dominates(HInstruction* other) {
709 if (block() != other->block()) {
710 return block()->Dominates(other->block());
711 }
712 // Both instructions are in the same basic block. This instruction
713 // should precede the other one in order to dominate it.
714 for (HInstruction* instr = next(); instr != NULL; instr = instr->next()) {
715 if (instr == other) {
716 return true;
717 }
718 }
719 return false;
720}
721
722
723#ifdef DEBUG
724void HInstruction::Verify() {
725 // Verify that input operands are defined before use.
726 HBasicBlock* cur_block = block();
727 for (int i = 0; i < OperandCount(); ++i) {
728 HValue* other_operand = OperandAt(i);
729 if (other_operand == NULL) continue;
730 HBasicBlock* other_block = other_operand->block();
731 if (cur_block == other_block) {
732 if (!other_operand->IsPhi()) {
733 HInstruction* cur = this->previous();
734 while (cur != NULL) {
735 if (cur == other_operand) break;
736 cur = cur->previous();
737 }
738 // Must reach other operand in the same block!
739 DCHECK(cur == other_operand);
740 }
741 } else {
742 // If the following assert fires, you may have forgotten an
743 // AddInstruction.
744 DCHECK(other_block->Dominates(cur_block));
745 }
746 }
747
748 // Verify that instructions that may have side-effects are followed
749 // by a simulate instruction.
750 if (HasObservableSideEffects() && !IsOsrEntry()) {
751 DCHECK(next()->IsSimulate());
752 }
753
754 // Verify that instructions that can be eliminated by GVN have overridden
755 // HValue::DataEquals. The default implementation is UNREACHABLE. We
756 // don't actually care whether DataEquals returns true or false here.
757 if (CheckFlag(kUseGVN)) DataEquals(this);
758
759 // Verify that all uses are in the graph.
760 for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
761 if (use.value()->IsInstruction()) {
762 DCHECK(HInstruction::cast(use.value())->IsLinked());
763 }
764 }
765}
766#endif
767
768
769bool HInstruction::CanDeoptimize() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000770 switch (opcode()) {
771 case HValue::kAbnormalExit:
772 case HValue::kAccessArgumentsAt:
773 case HValue::kAllocate:
774 case HValue::kArgumentsElements:
775 case HValue::kArgumentsLength:
776 case HValue::kArgumentsObject:
777 case HValue::kBlockEntry:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000778 case HValue::kCallNewArray:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 case HValue::kCapturedObject:
780 case HValue::kClassOfTestAndBranch:
781 case HValue::kCompareGeneric:
782 case HValue::kCompareHoleAndBranch:
783 case HValue::kCompareMap:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000784 case HValue::kCompareNumericAndBranch:
785 case HValue::kCompareObjectEqAndBranch:
786 case HValue::kConstant:
787 case HValue::kConstructDouble:
788 case HValue::kContext:
789 case HValue::kDebugBreak:
790 case HValue::kDeclareGlobals:
791 case HValue::kDoubleBits:
792 case HValue::kDummyUse:
793 case HValue::kEnterInlined:
794 case HValue::kEnvironmentMarker:
795 case HValue::kForceRepresentation:
796 case HValue::kGetCachedArrayIndex:
797 case HValue::kGoto:
798 case HValue::kHasCachedArrayIndexAndBranch:
799 case HValue::kHasInstanceTypeAndBranch:
800 case HValue::kInnerAllocatedObject:
801 case HValue::kInstanceOf:
802 case HValue::kIsSmiAndBranch:
803 case HValue::kIsStringAndBranch:
804 case HValue::kIsUndetectableAndBranch:
805 case HValue::kLeaveInlined:
806 case HValue::kLoadFieldByIndex:
807 case HValue::kLoadGlobalGeneric:
808 case HValue::kLoadNamedField:
809 case HValue::kLoadNamedGeneric:
810 case HValue::kLoadRoot:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000811 case HValue::kMathMinMax:
812 case HValue::kParameter:
813 case HValue::kPhi:
814 case HValue::kPushArguments:
815 case HValue::kReturn:
816 case HValue::kSeqStringGetChar:
817 case HValue::kStoreCodeEntry:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000818 case HValue::kStoreKeyed:
819 case HValue::kStoreNamedField:
820 case HValue::kStoreNamedGeneric:
821 case HValue::kStringCharCodeAt:
822 case HValue::kStringCharFromCode:
823 case HValue::kThisFunction:
824 case HValue::kTypeofIsAndBranch:
825 case HValue::kUnknownOSRValue:
826 case HValue::kUseConst:
827 return false;
828
829 case HValue::kAdd:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000830 case HValue::kApplyArguments:
831 case HValue::kBitwise:
832 case HValue::kBoundsCheck:
833 case HValue::kBranch:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000834 case HValue::kCallRuntime:
835 case HValue::kCallWithDescriptor:
836 case HValue::kChange:
837 case HValue::kCheckArrayBufferNotNeutered:
838 case HValue::kCheckHeapObject:
839 case HValue::kCheckInstanceType:
840 case HValue::kCheckMapValue:
841 case HValue::kCheckMaps:
842 case HValue::kCheckSmi:
843 case HValue::kCheckValue:
844 case HValue::kClampToUint8:
845 case HValue::kDeoptimize:
846 case HValue::kDiv:
847 case HValue::kForInCacheArray:
848 case HValue::kForInPrepareMap:
849 case HValue::kHasInPrototypeChainAndBranch:
850 case HValue::kInvokeFunction:
851 case HValue::kLoadContextSlot:
852 case HValue::kLoadFunctionPrototype:
853 case HValue::kLoadKeyed:
854 case HValue::kLoadKeyedGeneric:
855 case HValue::kMathFloorOfDiv:
856 case HValue::kMaybeGrowElements:
857 case HValue::kMod:
858 case HValue::kMul:
859 case HValue::kOsrEntry:
860 case HValue::kPower:
861 case HValue::kPrologue:
862 case HValue::kRor:
863 case HValue::kSar:
864 case HValue::kSeqStringSetChar:
865 case HValue::kShl:
866 case HValue::kShr:
867 case HValue::kSimulate:
868 case HValue::kStackCheck:
869 case HValue::kStoreContextSlot:
870 case HValue::kStoreKeyedGeneric:
871 case HValue::kStringAdd:
872 case HValue::kStringCompareAndBranch:
873 case HValue::kSub:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000874 case HValue::kTransitionElementsKind:
875 case HValue::kTrapAllocationMemento:
876 case HValue::kTypeof:
877 case HValue::kUnaryMathOperation:
878 case HValue::kWrapReceiver:
879 return true;
880 }
881 UNREACHABLE();
882 return true;
883}
884
885
886std::ostream& operator<<(std::ostream& os, const NameOf& v) {
887 return os << v.value->representation().Mnemonic() << v.value->id();
888}
889
890std::ostream& HDummyUse::PrintDataTo(std::ostream& os) const { // NOLINT
891 return os << NameOf(value());
892}
893
894
895std::ostream& HEnvironmentMarker::PrintDataTo(
896 std::ostream& os) const { // NOLINT
897 return os << (kind() == BIND ? "bind" : "lookup") << " var[" << index()
898 << "]";
899}
900
901
902std::ostream& HUnaryCall::PrintDataTo(std::ostream& os) const { // NOLINT
903 return os << NameOf(value()) << " #" << argument_count();
904}
905
906
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000907std::ostream& HBinaryCall::PrintDataTo(std::ostream& os) const { // NOLINT
908 return os << NameOf(first()) << " " << NameOf(second()) << " #"
909 << argument_count();
910}
911
Ben Murdochda12d292016-06-02 14:46:10 +0100912std::ostream& HInvokeFunction::PrintTo(std::ostream& os) const { // NOLINT
913 if (tail_call_mode() == TailCallMode::kAllow) os << "Tail";
914 return HBinaryCall::PrintTo(os);
915}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000916
Ben Murdochda12d292016-06-02 14:46:10 +0100917std::ostream& HInvokeFunction::PrintDataTo(std::ostream& os) const { // NOLINT
918 HBinaryCall::PrintDataTo(os);
919 if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
920 os << ", JSTailCall";
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000921 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000922 return os;
923}
924
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000925std::ostream& HBoundsCheck::PrintDataTo(std::ostream& os) const { // NOLINT
926 os << NameOf(index()) << " " << NameOf(length());
927 if (base() != NULL && (offset() != 0 || scale() != 0)) {
928 os << " base: ((";
929 if (base() != index()) {
930 os << NameOf(index());
931 } else {
932 os << "index";
933 }
934 os << " + " << offset() << ") >> " << scale() << ")";
935 }
936 if (skip_check()) os << " [DISABLED]";
937 return os;
938}
939
940
941void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
942 DCHECK(CheckFlag(kFlexibleRepresentation));
943 HValue* actual_index = index()->ActualValue();
944 HValue* actual_length = length()->ActualValue();
945 Representation index_rep = actual_index->representation();
946 Representation length_rep = actual_length->representation();
947 if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
948 index_rep = Representation::Smi();
949 }
950 if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
951 length_rep = Representation::Smi();
952 }
953 Representation r = index_rep.generalize(length_rep);
954 if (r.is_more_general_than(Representation::Integer32())) {
955 r = Representation::Integer32();
956 }
957 UpdateRepresentation(r, h_infer, "boundscheck");
958}
959
960
961Range* HBoundsCheck::InferRange(Zone* zone) {
962 Representation r = representation();
963 if (r.IsSmiOrInteger32() && length()->HasRange()) {
964 int upper = length()->range()->upper() - (allow_equality() ? 0 : 1);
965 int lower = 0;
966
967 Range* result = new(zone) Range(lower, upper);
968 if (index()->HasRange()) {
969 result->Intersect(index()->range());
970 }
971
972 // In case of Smi representation, clamp result to Smi::kMaxValue.
973 if (r.IsSmi()) result->ClampToSmi();
974 return result;
975 }
976 return HValue::InferRange(zone);
977}
978
979
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000980std::ostream& HCallWithDescriptor::PrintDataTo(
981 std::ostream& os) const { // NOLINT
982 for (int i = 0; i < OperandCount(); i++) {
983 os << NameOf(OperandAt(i)) << " ";
984 }
Ben Murdochda12d292016-06-02 14:46:10 +0100985 os << "#" << argument_count();
986 if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
987 os << ", JSTailCall";
988 }
989 return os;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000990}
991
992
993std::ostream& HCallNewArray::PrintDataTo(std::ostream& os) const { // NOLINT
994 os << ElementsKindToString(elements_kind()) << " ";
995 return HBinaryCall::PrintDataTo(os);
996}
997
998
999std::ostream& HCallRuntime::PrintDataTo(std::ostream& os) const { // NOLINT
1000 os << function()->name << " ";
1001 if (save_doubles() == kSaveFPRegs) os << "[save doubles] ";
1002 return os << "#" << argument_count();
1003}
1004
1005
1006std::ostream& HClassOfTestAndBranch::PrintDataTo(
1007 std::ostream& os) const { // NOLINT
1008 return os << "class_of_test(" << NameOf(value()) << ", \""
1009 << class_name()->ToCString().get() << "\")";
1010}
1011
1012
1013std::ostream& HWrapReceiver::PrintDataTo(std::ostream& os) const { // NOLINT
1014 return os << NameOf(receiver()) << " " << NameOf(function());
1015}
1016
1017
1018std::ostream& HAccessArgumentsAt::PrintDataTo(
1019 std::ostream& os) const { // NOLINT
1020 return os << NameOf(arguments()) << "[" << NameOf(index()) << "], length "
1021 << NameOf(length());
1022}
1023
1024
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001025std::ostream& HControlInstruction::PrintDataTo(
1026 std::ostream& os) const { // NOLINT
1027 os << " goto (";
1028 bool first_block = true;
1029 for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
1030 if (!first_block) os << ", ";
1031 os << *it.Current();
1032 first_block = false;
1033 }
1034 return os << ")";
1035}
1036
1037
1038std::ostream& HUnaryControlInstruction::PrintDataTo(
1039 std::ostream& os) const { // NOLINT
1040 os << NameOf(value());
1041 return HControlInstruction::PrintDataTo(os);
1042}
1043
1044
1045std::ostream& HReturn::PrintDataTo(std::ostream& os) const { // NOLINT
1046 return os << NameOf(value()) << " (pop " << NameOf(parameter_count())
1047 << " values)";
1048}
1049
1050
1051Representation HBranch::observed_input_representation(int index) {
Ben Murdochda12d292016-06-02 14:46:10 +01001052 if (expected_input_types_.Contains(ToBooleanICStub::NULL_TYPE) ||
1053 expected_input_types_.Contains(ToBooleanICStub::SPEC_OBJECT) ||
1054 expected_input_types_.Contains(ToBooleanICStub::STRING) ||
1055 expected_input_types_.Contains(ToBooleanICStub::SYMBOL) ||
1056 expected_input_types_.Contains(ToBooleanICStub::SIMD_VALUE)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001057 return Representation::Tagged();
1058 }
Ben Murdochda12d292016-06-02 14:46:10 +01001059 if (expected_input_types_.Contains(ToBooleanICStub::UNDEFINED)) {
1060 if (expected_input_types_.Contains(ToBooleanICStub::HEAP_NUMBER)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001061 return Representation::Double();
1062 }
1063 return Representation::Tagged();
1064 }
Ben Murdochda12d292016-06-02 14:46:10 +01001065 if (expected_input_types_.Contains(ToBooleanICStub::HEAP_NUMBER)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001066 return Representation::Double();
1067 }
Ben Murdochda12d292016-06-02 14:46:10 +01001068 if (expected_input_types_.Contains(ToBooleanICStub::SMI)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001069 return Representation::Smi();
1070 }
1071 return Representation::None();
1072}
1073
1074
1075bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
1076 HValue* value = this->value();
1077 if (value->EmitAtUses()) {
1078 DCHECK(value->IsConstant());
1079 DCHECK(!value->representation().IsDouble());
1080 *block = HConstant::cast(value)->BooleanValue()
1081 ? FirstSuccessor()
1082 : SecondSuccessor();
1083 return true;
1084 }
1085 *block = NULL;
1086 return false;
1087}
1088
1089
1090std::ostream& HBranch::PrintDataTo(std::ostream& os) const { // NOLINT
1091 return HUnaryControlInstruction::PrintDataTo(os) << " "
1092 << expected_input_types();
1093}
1094
1095
1096std::ostream& HCompareMap::PrintDataTo(std::ostream& os) const { // NOLINT
1097 os << NameOf(value()) << " (" << *map().handle() << ")";
1098 HControlInstruction::PrintDataTo(os);
1099 if (known_successor_index() == 0) {
1100 os << " [true]";
1101 } else if (known_successor_index() == 1) {
1102 os << " [false]";
1103 }
1104 return os;
1105}
1106
1107
1108const char* HUnaryMathOperation::OpName() const {
1109 switch (op()) {
1110 case kMathFloor:
1111 return "floor";
1112 case kMathFround:
1113 return "fround";
1114 case kMathRound:
1115 return "round";
1116 case kMathAbs:
1117 return "abs";
1118 case kMathLog:
1119 return "log";
1120 case kMathExp:
1121 return "exp";
1122 case kMathSqrt:
1123 return "sqrt";
1124 case kMathPowHalf:
1125 return "pow-half";
1126 case kMathClz32:
1127 return "clz32";
1128 default:
1129 UNREACHABLE();
1130 return NULL;
1131 }
1132}
1133
1134
1135Range* HUnaryMathOperation::InferRange(Zone* zone) {
1136 Representation r = representation();
1137 if (op() == kMathClz32) return new(zone) Range(0, 32);
1138 if (r.IsSmiOrInteger32() && value()->HasRange()) {
1139 if (op() == kMathAbs) {
1140 int upper = value()->range()->upper();
1141 int lower = value()->range()->lower();
1142 bool spans_zero = value()->range()->CanBeZero();
1143 // Math.abs(kMinInt) overflows its representation, on which the
1144 // instruction deopts. Hence clamp it to kMaxInt.
1145 int abs_upper = upper == kMinInt ? kMaxInt : abs(upper);
1146 int abs_lower = lower == kMinInt ? kMaxInt : abs(lower);
1147 Range* result =
1148 new(zone) Range(spans_zero ? 0 : Min(abs_lower, abs_upper),
1149 Max(abs_lower, abs_upper));
1150 // In case of Smi representation, clamp Math.abs(Smi::kMinValue) to
1151 // Smi::kMaxValue.
1152 if (r.IsSmi()) result->ClampToSmi();
1153 return result;
1154 }
1155 }
1156 return HValue::InferRange(zone);
1157}
1158
1159
1160std::ostream& HUnaryMathOperation::PrintDataTo(
1161 std::ostream& os) const { // NOLINT
1162 return os << OpName() << " " << NameOf(value());
1163}
1164
1165
1166std::ostream& HUnaryOperation::PrintDataTo(std::ostream& os) const { // NOLINT
1167 return os << NameOf(value());
1168}
1169
1170
1171std::ostream& HHasInstanceTypeAndBranch::PrintDataTo(
1172 std::ostream& os) const { // NOLINT
1173 os << NameOf(value());
1174 switch (from_) {
1175 case FIRST_JS_RECEIVER_TYPE:
1176 if (to_ == LAST_TYPE) os << " spec_object";
1177 break;
1178 case JS_REGEXP_TYPE:
1179 if (to_ == JS_REGEXP_TYPE) os << " reg_exp";
1180 break;
1181 case JS_ARRAY_TYPE:
1182 if (to_ == JS_ARRAY_TYPE) os << " array";
1183 break;
1184 case JS_FUNCTION_TYPE:
1185 if (to_ == JS_FUNCTION_TYPE) os << " function";
1186 break;
1187 default:
1188 break;
1189 }
1190 return os;
1191}
1192
1193
1194std::ostream& HTypeofIsAndBranch::PrintDataTo(
1195 std::ostream& os) const { // NOLINT
1196 os << NameOf(value()) << " == " << type_literal()->ToCString().get();
1197 return HControlInstruction::PrintDataTo(os);
1198}
1199
1200
1201namespace {
1202
1203String* TypeOfString(HConstant* constant, Isolate* isolate) {
1204 Heap* heap = isolate->heap();
1205 if (constant->HasNumberValue()) return heap->number_string();
1206 if (constant->IsUndetectable()) return heap->undefined_string();
1207 if (constant->HasStringValue()) return heap->string_string();
1208 switch (constant->GetInstanceType()) {
1209 case ODDBALL_TYPE: {
1210 Unique<Object> unique = constant->GetUnique();
1211 if (unique.IsKnownGlobal(heap->true_value()) ||
1212 unique.IsKnownGlobal(heap->false_value())) {
1213 return heap->boolean_string();
1214 }
1215 if (unique.IsKnownGlobal(heap->null_value())) {
1216 return heap->object_string();
1217 }
1218 DCHECK(unique.IsKnownGlobal(heap->undefined_value()));
1219 return heap->undefined_string();
1220 }
1221 case SYMBOL_TYPE:
1222 return heap->symbol_string();
1223 case SIMD128_VALUE_TYPE: {
1224 Unique<Map> map = constant->ObjectMap();
1225#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
1226 if (map.IsKnownGlobal(heap->type##_map())) { \
1227 return heap->type##_string(); \
1228 }
1229 SIMD128_TYPES(SIMD128_TYPE)
1230#undef SIMD128_TYPE
1231 UNREACHABLE();
1232 return nullptr;
1233 }
1234 default:
1235 if (constant->IsCallable()) return heap->function_string();
1236 return heap->object_string();
1237 }
1238}
1239
1240} // namespace
1241
1242
1243bool HTypeofIsAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
1244 if (FLAG_fold_constants && value()->IsConstant()) {
1245 HConstant* constant = HConstant::cast(value());
1246 String* type_string = TypeOfString(constant, isolate());
1247 bool same_type = type_literal_.IsKnownGlobal(type_string);
1248 *block = same_type ? FirstSuccessor() : SecondSuccessor();
1249 return true;
1250 } else if (value()->representation().IsSpecialization()) {
1251 bool number_type =
1252 type_literal_.IsKnownGlobal(isolate()->heap()->number_string());
1253 *block = number_type ? FirstSuccessor() : SecondSuccessor();
1254 return true;
1255 }
1256 *block = NULL;
1257 return false;
1258}
1259
1260
1261std::ostream& HCheckMapValue::PrintDataTo(std::ostream& os) const { // NOLINT
1262 return os << NameOf(value()) << " " << NameOf(map());
1263}
1264
1265
1266HValue* HCheckMapValue::Canonicalize() {
1267 if (map()->IsConstant()) {
1268 HConstant* c_map = HConstant::cast(map());
1269 return HCheckMaps::CreateAndInsertAfter(
1270 block()->graph()->zone(), value(), c_map->MapValue(),
1271 c_map->HasStableMapValue(), this);
1272 }
1273 return this;
1274}
1275
1276
1277std::ostream& HForInPrepareMap::PrintDataTo(std::ostream& os) const { // NOLINT
1278 return os << NameOf(enumerable());
1279}
1280
1281
1282std::ostream& HForInCacheArray::PrintDataTo(std::ostream& os) const { // NOLINT
1283 return os << NameOf(enumerable()) << " " << NameOf(map()) << "[" << idx_
1284 << "]";
1285}
1286
1287
1288std::ostream& HLoadFieldByIndex::PrintDataTo(
1289 std::ostream& os) const { // NOLINT
1290 return os << NameOf(object()) << " " << NameOf(index());
1291}
1292
1293
1294static bool MatchLeftIsOnes(HValue* l, HValue* r, HValue** negated) {
1295 if (!l->EqualsInteger32Constant(~0)) return false;
1296 *negated = r;
1297 return true;
1298}
1299
1300
1301static bool MatchNegationViaXor(HValue* instr, HValue** negated) {
1302 if (!instr->IsBitwise()) return false;
1303 HBitwise* b = HBitwise::cast(instr);
1304 return (b->op() == Token::BIT_XOR) &&
1305 (MatchLeftIsOnes(b->left(), b->right(), negated) ||
1306 MatchLeftIsOnes(b->right(), b->left(), negated));
1307}
1308
1309
1310static bool MatchDoubleNegation(HValue* instr, HValue** arg) {
1311 HValue* negated;
1312 return MatchNegationViaXor(instr, &negated) &&
1313 MatchNegationViaXor(negated, arg);
1314}
1315
1316
1317HValue* HBitwise::Canonicalize() {
1318 if (!representation().IsSmiOrInteger32()) return this;
1319 // If x is an int32, then x & -1 == x, x | 0 == x and x ^ 0 == x.
1320 int32_t nop_constant = (op() == Token::BIT_AND) ? -1 : 0;
1321 if (left()->EqualsInteger32Constant(nop_constant) &&
1322 !right()->CheckFlag(kUint32)) {
1323 return right();
1324 }
1325 if (right()->EqualsInteger32Constant(nop_constant) &&
1326 !left()->CheckFlag(kUint32)) {
1327 return left();
1328 }
1329 // Optimize double negation, a common pattern used for ToInt32(x).
1330 HValue* arg;
1331 if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
1332 return arg;
1333 }
1334 return this;
1335}
1336
1337
1338// static
1339HInstruction* HAdd::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01001340 HValue* left, HValue* right,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001341 ExternalAddType external_add_type) {
1342 // For everything else, you should use the other factory method without
1343 // ExternalAddType.
1344 DCHECK_EQ(external_add_type, AddOfExternalAndTagged);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001345 return new (zone) HAdd(context, left, right, external_add_type);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001346}
1347
1348
1349Representation HAdd::RepresentationFromInputs() {
1350 Representation left_rep = left()->representation();
1351 if (left_rep.IsExternal()) {
1352 return Representation::External();
1353 }
1354 return HArithmeticBinaryOperation::RepresentationFromInputs();
1355}
1356
1357
1358Representation HAdd::RequiredInputRepresentation(int index) {
1359 if (index == 2) {
1360 Representation left_rep = left()->representation();
1361 if (left_rep.IsExternal()) {
1362 if (external_add_type_ == AddOfExternalAndTagged) {
1363 return Representation::Tagged();
1364 } else {
1365 return Representation::Integer32();
1366 }
1367 }
1368 }
1369 return HArithmeticBinaryOperation::RequiredInputRepresentation(index);
1370}
1371
1372
1373static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
1374 return arg1->representation().IsSpecialization() &&
1375 arg2->EqualsInteger32Constant(identity);
1376}
1377
1378
1379HValue* HAdd::Canonicalize() {
1380 // Adding 0 is an identity operation except in case of -0: -0 + 0 = +0
1381 if (IsIdentityOperation(left(), right(), 0) &&
1382 !left()->representation().IsDouble()) { // Left could be -0.
1383 return left();
1384 }
1385 if (IsIdentityOperation(right(), left(), 0) &&
1386 !left()->representation().IsDouble()) { // Right could be -0.
1387 return right();
1388 }
1389 return this;
1390}
1391
1392
1393HValue* HSub::Canonicalize() {
1394 if (IsIdentityOperation(left(), right(), 0)) return left();
1395 return this;
1396}
1397
1398
1399HValue* HMul::Canonicalize() {
1400 if (IsIdentityOperation(left(), right(), 1)) return left();
1401 if (IsIdentityOperation(right(), left(), 1)) return right();
1402 return this;
1403}
1404
1405
1406bool HMul::MulMinusOne() {
1407 if (left()->EqualsInteger32Constant(-1) ||
1408 right()->EqualsInteger32Constant(-1)) {
1409 return true;
1410 }
1411
1412 return false;
1413}
1414
1415
1416HValue* HMod::Canonicalize() {
1417 return this;
1418}
1419
1420
1421HValue* HDiv::Canonicalize() {
1422 if (IsIdentityOperation(left(), right(), 1)) return left();
1423 return this;
1424}
1425
1426
1427HValue* HChange::Canonicalize() {
1428 return (from().Equals(to())) ? value() : this;
1429}
1430
1431
1432HValue* HWrapReceiver::Canonicalize() {
1433 if (HasNoUses()) return NULL;
1434 if (receiver()->type().IsJSReceiver()) {
1435 return receiver();
1436 }
1437 return this;
1438}
1439
1440
1441std::ostream& HTypeof::PrintDataTo(std::ostream& os) const { // NOLINT
1442 return os << NameOf(value());
1443}
1444
1445
1446HInstruction* HForceRepresentation::New(Isolate* isolate, Zone* zone,
1447 HValue* context, HValue* value,
1448 Representation representation) {
1449 if (FLAG_fold_constants && value->IsConstant()) {
1450 HConstant* c = HConstant::cast(value);
1451 c = c->CopyToRepresentation(representation, zone);
1452 if (c != NULL) return c;
1453 }
1454 return new(zone) HForceRepresentation(value, representation);
1455}
1456
1457
1458std::ostream& HForceRepresentation::PrintDataTo(
1459 std::ostream& os) const { // NOLINT
1460 return os << representation().Mnemonic() << " " << NameOf(value());
1461}
1462
1463
1464std::ostream& HChange::PrintDataTo(std::ostream& os) const { // NOLINT
1465 HUnaryOperation::PrintDataTo(os);
1466 os << " " << from().Mnemonic() << " to " << to().Mnemonic();
1467
1468 if (CanTruncateToSmi()) os << " truncating-smi";
1469 if (CanTruncateToInt32()) os << " truncating-int32";
1470 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
1471 if (CheckFlag(kAllowUndefinedAsNaN)) os << " allow-undefined-as-nan";
1472 return os;
1473}
1474
1475
1476HValue* HUnaryMathOperation::Canonicalize() {
1477 if (op() == kMathRound || op() == kMathFloor) {
1478 HValue* val = value();
1479 if (val->IsChange()) val = HChange::cast(val)->value();
1480 if (val->representation().IsSmiOrInteger32()) {
1481 if (val->representation().Equals(representation())) return val;
1482 return Prepend(new(block()->zone()) HChange(
1483 val, representation(), false, false));
1484 }
1485 }
Ben Murdochda12d292016-06-02 14:46:10 +01001486 if (op() == kMathFloor && representation().IsSmiOrInteger32() &&
1487 value()->IsDiv() && value()->HasOneUse()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001488 HDiv* hdiv = HDiv::cast(value());
1489
1490 HValue* left = hdiv->left();
1491 if (left->representation().IsInteger32() && !left->CheckFlag(kUint32)) {
1492 // A value with an integer representation does not need to be transformed.
1493 } else if (left->IsChange() && HChange::cast(left)->from().IsInteger32() &&
1494 !HChange::cast(left)->value()->CheckFlag(kUint32)) {
1495 // A change from an integer32 can be replaced by the integer32 value.
1496 left = HChange::cast(left)->value();
1497 } else if (hdiv->observed_input_representation(1).IsSmiOrInteger32()) {
1498 left = Prepend(new(block()->zone()) HChange(
1499 left, Representation::Integer32(), false, false));
1500 } else {
1501 return this;
1502 }
1503
1504 HValue* right = hdiv->right();
1505 if (right->IsInteger32Constant()) {
1506 right = Prepend(HConstant::cast(right)->CopyToRepresentation(
1507 Representation::Integer32(), right->block()->zone()));
1508 } else if (right->representation().IsInteger32() &&
1509 !right->CheckFlag(kUint32)) {
1510 // A value with an integer representation does not need to be transformed.
1511 } else if (right->IsChange() &&
1512 HChange::cast(right)->from().IsInteger32() &&
1513 !HChange::cast(right)->value()->CheckFlag(kUint32)) {
1514 // A change from an integer32 can be replaced by the integer32 value.
1515 right = HChange::cast(right)->value();
1516 } else if (hdiv->observed_input_representation(2).IsSmiOrInteger32()) {
1517 right = Prepend(new(block()->zone()) HChange(
1518 right, Representation::Integer32(), false, false));
1519 } else {
1520 return this;
1521 }
1522
1523 return Prepend(HMathFloorOfDiv::New(
1524 block()->graph()->isolate(), block()->zone(), context(), left, right));
1525 }
1526 return this;
1527}
1528
1529
1530HValue* HCheckInstanceType::Canonicalize() {
1531 if ((check_ == IS_JS_RECEIVER && value()->type().IsJSReceiver()) ||
1532 (check_ == IS_JS_ARRAY && value()->type().IsJSArray()) ||
1533 (check_ == IS_STRING && value()->type().IsString())) {
1534 return value();
1535 }
1536
1537 if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1538 if (HConstant::cast(value())->HasInternalizedStringValue()) {
1539 return value();
1540 }
1541 }
1542 return this;
1543}
1544
1545
1546void HCheckInstanceType::GetCheckInterval(InstanceType* first,
1547 InstanceType* last) {
1548 DCHECK(is_interval_check());
1549 switch (check_) {
1550 case IS_JS_RECEIVER:
1551 *first = FIRST_JS_RECEIVER_TYPE;
1552 *last = LAST_JS_RECEIVER_TYPE;
1553 return;
1554 case IS_JS_ARRAY:
1555 *first = *last = JS_ARRAY_TYPE;
1556 return;
1557 case IS_JS_DATE:
1558 *first = *last = JS_DATE_TYPE;
1559 return;
1560 default:
1561 UNREACHABLE();
1562 }
1563}
1564
1565
1566void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
1567 DCHECK(!is_interval_check());
1568 switch (check_) {
1569 case IS_STRING:
1570 *mask = kIsNotStringMask;
1571 *tag = kStringTag;
1572 return;
1573 case IS_INTERNALIZED_STRING:
1574 *mask = kIsNotStringMask | kIsNotInternalizedMask;
1575 *tag = kInternalizedTag;
1576 return;
1577 default:
1578 UNREACHABLE();
1579 }
1580}
1581
1582
1583std::ostream& HCheckMaps::PrintDataTo(std::ostream& os) const { // NOLINT
1584 os << NameOf(value()) << " [" << *maps()->at(0).handle();
1585 for (int i = 1; i < maps()->size(); ++i) {
1586 os << "," << *maps()->at(i).handle();
1587 }
1588 os << "]";
1589 if (IsStabilityCheck()) os << "(stability-check)";
1590 return os;
1591}
1592
1593
1594HValue* HCheckMaps::Canonicalize() {
1595 if (!IsStabilityCheck() && maps_are_stable() && value()->IsConstant()) {
1596 HConstant* c_value = HConstant::cast(value());
1597 if (c_value->HasObjectMap()) {
1598 for (int i = 0; i < maps()->size(); ++i) {
1599 if (c_value->ObjectMap() == maps()->at(i)) {
1600 if (maps()->size() > 1) {
1601 set_maps(new(block()->graph()->zone()) UniqueSet<Map>(
1602 maps()->at(i), block()->graph()->zone()));
1603 }
1604 MarkAsStabilityCheck();
1605 break;
1606 }
1607 }
1608 }
1609 }
1610 return this;
1611}
1612
1613
1614std::ostream& HCheckValue::PrintDataTo(std::ostream& os) const { // NOLINT
1615 return os << NameOf(value()) << " " << Brief(*object().handle());
1616}
1617
1618
1619HValue* HCheckValue::Canonicalize() {
1620 return (value()->IsConstant() &&
1621 HConstant::cast(value())->EqualsUnique(object_)) ? NULL : this;
1622}
1623
1624
1625const char* HCheckInstanceType::GetCheckName() const {
1626 switch (check_) {
1627 case IS_JS_RECEIVER: return "object";
1628 case IS_JS_ARRAY: return "array";
1629 case IS_JS_DATE:
1630 return "date";
1631 case IS_STRING: return "string";
1632 case IS_INTERNALIZED_STRING: return "internalized_string";
1633 }
1634 UNREACHABLE();
1635 return "";
1636}
1637
1638
1639std::ostream& HCheckInstanceType::PrintDataTo(
1640 std::ostream& os) const { // NOLINT
1641 os << GetCheckName() << " ";
1642 return HUnaryOperation::PrintDataTo(os);
1643}
1644
1645
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001646std::ostream& HUnknownOSRValue::PrintDataTo(std::ostream& os) const { // NOLINT
1647 const char* type = "expression";
1648 if (environment_->is_local_index(index_)) type = "local";
1649 if (environment_->is_special_index(index_)) type = "special";
1650 if (environment_->is_parameter_index(index_)) type = "parameter";
1651 return os << type << " @ " << index_;
1652}
1653
1654
1655std::ostream& HInstanceOf::PrintDataTo(std::ostream& os) const { // NOLINT
1656 return os << NameOf(left()) << " " << NameOf(right()) << " "
1657 << NameOf(context());
1658}
1659
1660
1661Range* HValue::InferRange(Zone* zone) {
1662 Range* result;
1663 if (representation().IsSmi() || type().IsSmi()) {
1664 result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
1665 result->set_can_be_minus_zero(false);
1666 } else {
1667 result = new(zone) Range();
1668 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
1669 // TODO(jkummerow): The range cannot be minus zero when the upper type
1670 // bound is Integer32.
1671 }
1672 return result;
1673}
1674
1675
1676Range* HChange::InferRange(Zone* zone) {
1677 Range* input_range = value()->range();
1678 if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
1679 (to().IsSmi() ||
1680 (to().IsTagged() &&
1681 input_range != NULL &&
1682 input_range->IsInSmiRange()))) {
1683 set_type(HType::Smi());
1684 ClearChangesFlag(kNewSpacePromotion);
1685 }
1686 if (to().IsSmiOrTagged() &&
1687 input_range != NULL &&
1688 input_range->IsInSmiRange() &&
1689 (!SmiValuesAre32Bits() ||
1690 !value()->CheckFlag(HValue::kUint32) ||
1691 input_range->upper() != kMaxInt)) {
1692 // The Range class can't express upper bounds in the (kMaxInt, kMaxUint32]
1693 // interval, so we treat kMaxInt as a sentinel for this entire interval.
1694 ClearFlag(kCanOverflow);
1695 }
1696 Range* result = (input_range != NULL)
1697 ? input_range->Copy(zone)
1698 : HValue::InferRange(zone);
1699 result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1700 !(CheckFlag(kAllUsesTruncatingToInt32) ||
1701 CheckFlag(kAllUsesTruncatingToSmi)));
1702 if (to().IsSmi()) result->ClampToSmi();
1703 return result;
1704}
1705
1706
1707Range* HConstant::InferRange(Zone* zone) {
1708 if (HasInteger32Value()) {
1709 Range* result = new(zone) Range(int32_value_, int32_value_);
1710 result->set_can_be_minus_zero(false);
1711 return result;
1712 }
1713 return HValue::InferRange(zone);
1714}
1715
1716
1717SourcePosition HPhi::position() const { return block()->first()->position(); }
1718
1719
1720Range* HPhi::InferRange(Zone* zone) {
1721 Representation r = representation();
1722 if (r.IsSmiOrInteger32()) {
1723 if (block()->IsLoopHeader()) {
1724 Range* range = r.IsSmi()
1725 ? new(zone) Range(Smi::kMinValue, Smi::kMaxValue)
1726 : new(zone) Range(kMinInt, kMaxInt);
1727 return range;
1728 } else {
1729 Range* range = OperandAt(0)->range()->Copy(zone);
1730 for (int i = 1; i < OperandCount(); ++i) {
1731 range->Union(OperandAt(i)->range());
1732 }
1733 return range;
1734 }
1735 } else {
1736 return HValue::InferRange(zone);
1737 }
1738}
1739
1740
1741Range* HAdd::InferRange(Zone* zone) {
1742 Representation r = representation();
1743 if (r.IsSmiOrInteger32()) {
1744 Range* a = left()->range();
1745 Range* b = right()->range();
1746 Range* res = a->Copy(zone);
1747 if (!res->AddAndCheckOverflow(r, b) ||
1748 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1749 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1750 ClearFlag(kCanOverflow);
1751 }
1752 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1753 !CheckFlag(kAllUsesTruncatingToInt32) &&
1754 a->CanBeMinusZero() && b->CanBeMinusZero());
1755 return res;
1756 } else {
1757 return HValue::InferRange(zone);
1758 }
1759}
1760
1761
1762Range* HSub::InferRange(Zone* zone) {
1763 Representation r = representation();
1764 if (r.IsSmiOrInteger32()) {
1765 Range* a = left()->range();
1766 Range* b = right()->range();
1767 Range* res = a->Copy(zone);
1768 if (!res->SubAndCheckOverflow(r, b) ||
1769 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1770 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1771 ClearFlag(kCanOverflow);
1772 }
1773 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1774 !CheckFlag(kAllUsesTruncatingToInt32) &&
1775 a->CanBeMinusZero() && b->CanBeZero());
1776 return res;
1777 } else {
1778 return HValue::InferRange(zone);
1779 }
1780}
1781
1782
1783Range* HMul::InferRange(Zone* zone) {
1784 Representation r = representation();
1785 if (r.IsSmiOrInteger32()) {
1786 Range* a = left()->range();
1787 Range* b = right()->range();
1788 Range* res = a->Copy(zone);
1789 if (!res->MulAndCheckOverflow(r, b) ||
1790 (((r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1791 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) &&
1792 MulMinusOne())) {
1793 // Truncated int multiplication is too precise and therefore not the
1794 // same as converting to Double and back.
1795 // Handle truncated integer multiplication by -1 special.
1796 ClearFlag(kCanOverflow);
1797 }
1798 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1799 !CheckFlag(kAllUsesTruncatingToInt32) &&
1800 ((a->CanBeZero() && b->CanBeNegative()) ||
1801 (a->CanBeNegative() && b->CanBeZero())));
1802 return res;
1803 } else {
1804 return HValue::InferRange(zone);
1805 }
1806}
1807
1808
1809Range* HDiv::InferRange(Zone* zone) {
1810 if (representation().IsInteger32()) {
1811 Range* a = left()->range();
1812 Range* b = right()->range();
1813 Range* result = new(zone) Range();
1814 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1815 (a->CanBeMinusZero() ||
1816 (a->CanBeZero() && b->CanBeNegative())));
1817 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1818 ClearFlag(kCanOverflow);
1819 }
1820
1821 if (!b->CanBeZero()) {
1822 ClearFlag(kCanBeDivByZero);
1823 }
1824 return result;
1825 } else {
1826 return HValue::InferRange(zone);
1827 }
1828}
1829
1830
1831Range* HMathFloorOfDiv::InferRange(Zone* zone) {
1832 if (representation().IsInteger32()) {
1833 Range* a = left()->range();
1834 Range* b = right()->range();
1835 Range* result = new(zone) Range();
1836 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1837 (a->CanBeMinusZero() ||
1838 (a->CanBeZero() && b->CanBeNegative())));
1839 if (!a->Includes(kMinInt)) {
1840 ClearFlag(kLeftCanBeMinInt);
1841 }
1842
1843 if (!a->CanBeNegative()) {
1844 ClearFlag(HValue::kLeftCanBeNegative);
1845 }
1846
1847 if (!a->CanBePositive()) {
1848 ClearFlag(HValue::kLeftCanBePositive);
1849 }
1850
1851 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1852 ClearFlag(kCanOverflow);
1853 }
1854
1855 if (!b->CanBeZero()) {
1856 ClearFlag(kCanBeDivByZero);
1857 }
1858 return result;
1859 } else {
1860 return HValue::InferRange(zone);
1861 }
1862}
1863
1864
1865// Returns the absolute value of its argument minus one, avoiding undefined
1866// behavior at kMinInt.
1867static int32_t AbsMinus1(int32_t a) { return a < 0 ? -(a + 1) : (a - 1); }
1868
1869
1870Range* HMod::InferRange(Zone* zone) {
1871 if (representation().IsInteger32()) {
1872 Range* a = left()->range();
1873 Range* b = right()->range();
1874
1875 // The magnitude of the modulus is bounded by the right operand.
1876 int32_t positive_bound = Max(AbsMinus1(b->lower()), AbsMinus1(b->upper()));
1877
1878 // The result of the modulo operation has the sign of its left operand.
1879 bool left_can_be_negative = a->CanBeMinusZero() || a->CanBeNegative();
1880 Range* result = new(zone) Range(left_can_be_negative ? -positive_bound : 0,
1881 a->CanBePositive() ? positive_bound : 0);
1882
1883 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1884 left_can_be_negative);
1885
1886 if (!a->CanBeNegative()) {
1887 ClearFlag(HValue::kLeftCanBeNegative);
1888 }
1889
1890 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1891 ClearFlag(HValue::kCanOverflow);
1892 }
1893
1894 if (!b->CanBeZero()) {
1895 ClearFlag(HValue::kCanBeDivByZero);
1896 }
1897 return result;
1898 } else {
1899 return HValue::InferRange(zone);
1900 }
1901}
1902
1903
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001904Range* HMathMinMax::InferRange(Zone* zone) {
1905 if (representation().IsSmiOrInteger32()) {
1906 Range* a = left()->range();
1907 Range* b = right()->range();
1908 Range* res = a->Copy(zone);
1909 if (operation_ == kMathMax) {
1910 res->CombinedMax(b);
1911 } else {
1912 DCHECK(operation_ == kMathMin);
1913 res->CombinedMin(b);
1914 }
1915 return res;
1916 } else {
1917 return HValue::InferRange(zone);
1918 }
1919}
1920
1921
1922void HPushArguments::AddInput(HValue* value) {
1923 inputs_.Add(NULL, value->block()->zone());
1924 SetOperandAt(OperandCount() - 1, value);
1925}
1926
1927
1928std::ostream& HPhi::PrintTo(std::ostream& os) const { // NOLINT
1929 os << "[";
1930 for (int i = 0; i < OperandCount(); ++i) {
1931 os << " " << NameOf(OperandAt(i)) << " ";
1932 }
1933 return os << " uses" << UseCount()
1934 << representation_from_indirect_uses().Mnemonic() << " "
1935 << TypeOf(this) << "]";
1936}
1937
1938
1939void HPhi::AddInput(HValue* value) {
1940 inputs_.Add(NULL, value->block()->zone());
1941 SetOperandAt(OperandCount() - 1, value);
1942 // Mark phis that may have 'arguments' directly or indirectly as an operand.
1943 if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
1944 SetFlag(kIsArguments);
1945 }
1946}
1947
1948
1949bool HPhi::HasRealUses() {
1950 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
1951 if (!it.value()->IsPhi()) return true;
1952 }
1953 return false;
1954}
1955
1956
1957HValue* HPhi::GetRedundantReplacement() {
1958 HValue* candidate = NULL;
1959 int count = OperandCount();
1960 int position = 0;
1961 while (position < count && candidate == NULL) {
1962 HValue* current = OperandAt(position++);
1963 if (current != this) candidate = current;
1964 }
1965 while (position < count) {
1966 HValue* current = OperandAt(position++);
1967 if (current != this && current != candidate) return NULL;
1968 }
1969 DCHECK(candidate != this);
1970 return candidate;
1971}
1972
1973
1974void HPhi::DeleteFromGraph() {
1975 DCHECK(block() != NULL);
1976 block()->RemovePhi(this);
1977 DCHECK(block() == NULL);
1978}
1979
1980
1981void HPhi::InitRealUses(int phi_id) {
1982 // Initialize real uses.
1983 phi_id_ = phi_id;
1984 // Compute a conservative approximation of truncating uses before inferring
1985 // representations. The proper, exact computation will be done later, when
1986 // inserting representation changes.
1987 SetFlag(kTruncatingToSmi);
1988 SetFlag(kTruncatingToInt32);
1989 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
1990 HValue* value = it.value();
1991 if (!value->IsPhi()) {
1992 Representation rep = value->observed_input_representation(it.index());
1993 representation_from_non_phi_uses_ =
1994 representation_from_non_phi_uses().generalize(rep);
1995 if (rep.IsSmi() || rep.IsInteger32() || rep.IsDouble()) {
1996 has_type_feedback_from_uses_ = true;
1997 }
1998
1999 if (FLAG_trace_representation) {
2000 PrintF("#%d Phi is used by real #%d %s as %s\n",
2001 id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2002 }
2003 if (!value->IsSimulate()) {
2004 if (!value->CheckFlag(kTruncatingToSmi)) {
2005 ClearFlag(kTruncatingToSmi);
2006 }
2007 if (!value->CheckFlag(kTruncatingToInt32)) {
2008 ClearFlag(kTruncatingToInt32);
2009 }
2010 }
2011 }
2012 }
2013}
2014
2015
2016void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2017 if (FLAG_trace_representation) {
2018 PrintF(
2019 "generalizing use representation '%s' of #%d Phi "
2020 "with uses of #%d Phi '%s'\n",
2021 representation_from_indirect_uses().Mnemonic(), id(), other->id(),
2022 other->representation_from_non_phi_uses().Mnemonic());
2023 }
2024
2025 representation_from_indirect_uses_ =
2026 representation_from_indirect_uses().generalize(
2027 other->representation_from_non_phi_uses());
2028}
2029
2030
2031void HSimulate::MergeWith(ZoneList<HSimulate*>* list) {
2032 while (!list->is_empty()) {
2033 HSimulate* from = list->RemoveLast();
2034 ZoneList<HValue*>* from_values = &from->values_;
2035 for (int i = 0; i < from_values->length(); ++i) {
2036 if (from->HasAssignedIndexAt(i)) {
2037 int index = from->GetAssignedIndexAt(i);
2038 if (HasValueForIndex(index)) continue;
2039 AddAssignedValue(index, from_values->at(i));
2040 } else {
2041 if (pop_count_ > 0) {
2042 pop_count_--;
2043 } else {
2044 AddPushedValue(from_values->at(i));
2045 }
2046 }
2047 }
2048 pop_count_ += from->pop_count_;
2049 from->DeleteAndReplaceWith(NULL);
2050 }
2051}
2052
2053
2054std::ostream& HSimulate::PrintDataTo(std::ostream& os) const { // NOLINT
2055 os << "id=" << ast_id().ToInt();
2056 if (pop_count_ > 0) os << " pop " << pop_count_;
2057 if (values_.length() > 0) {
2058 if (pop_count_ > 0) os << " /";
2059 for (int i = values_.length() - 1; i >= 0; --i) {
2060 if (HasAssignedIndexAt(i)) {
2061 os << " var[" << GetAssignedIndexAt(i) << "] = ";
2062 } else {
2063 os << " push ";
2064 }
2065 os << NameOf(values_[i]);
2066 if (i > 0) os << ",";
2067 }
2068 }
2069 return os;
2070}
2071
2072
2073void HSimulate::ReplayEnvironment(HEnvironment* env) {
2074 if (is_done_with_replay()) return;
2075 DCHECK(env != NULL);
2076 env->set_ast_id(ast_id());
2077 env->Drop(pop_count());
2078 for (int i = values()->length() - 1; i >= 0; --i) {
2079 HValue* value = values()->at(i);
2080 if (HasAssignedIndexAt(i)) {
2081 env->Bind(GetAssignedIndexAt(i), value);
2082 } else {
2083 env->Push(value);
2084 }
2085 }
2086 set_done_with_replay();
2087}
2088
2089
2090static void ReplayEnvironmentNested(const ZoneList<HValue*>* values,
2091 HCapturedObject* other) {
2092 for (int i = 0; i < values->length(); ++i) {
2093 HValue* value = values->at(i);
2094 if (value->IsCapturedObject()) {
2095 if (HCapturedObject::cast(value)->capture_id() == other->capture_id()) {
2096 values->at(i) = other;
2097 } else {
2098 ReplayEnvironmentNested(HCapturedObject::cast(value)->values(), other);
2099 }
2100 }
2101 }
2102}
2103
2104
2105// Replay captured objects by replacing all captured objects with the
2106// same capture id in the current and all outer environments.
2107void HCapturedObject::ReplayEnvironment(HEnvironment* env) {
2108 DCHECK(env != NULL);
2109 while (env != NULL) {
2110 ReplayEnvironmentNested(env->values(), this);
2111 env = env->outer();
2112 }
2113}
2114
2115
2116std::ostream& HCapturedObject::PrintDataTo(std::ostream& os) const { // NOLINT
2117 os << "#" << capture_id() << " ";
2118 return HDematerializedObject::PrintDataTo(os);
2119}
2120
2121
2122void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
2123 Zone* zone) {
2124 DCHECK(return_target->IsInlineReturnTarget());
2125 return_targets_.Add(return_target, zone);
2126}
2127
2128
2129std::ostream& HEnterInlined::PrintDataTo(std::ostream& os) const { // NOLINT
Ben Murdochda12d292016-06-02 14:46:10 +01002130 os << function()->debug_name()->ToCString().get();
2131 if (syntactic_tail_call_mode() == TailCallMode::kAllow) {
2132 os << ", JSTailCall";
2133 }
2134 return os;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002135}
2136
2137
2138static bool IsInteger32(double value) {
2139 if (value >= std::numeric_limits<int32_t>::min() &&
2140 value <= std::numeric_limits<int32_t>::max()) {
2141 double roundtrip_value = static_cast<double>(static_cast<int32_t>(value));
2142 return bit_cast<int64_t>(roundtrip_value) == bit_cast<int64_t>(value);
2143 }
2144 return false;
2145}
2146
2147
2148HConstant::HConstant(Special special)
2149 : HTemplateInstruction<0>(HType::TaggedNumber()),
2150 object_(Handle<Object>::null()),
2151 object_map_(Handle<Map>::null()),
2152 bit_field_(HasDoubleValueField::encode(true) |
2153 InstanceTypeField::encode(kUnknownInstanceType)),
2154 int32_value_(0) {
2155 DCHECK_EQ(kHoleNaN, special);
2156 std::memcpy(&double_value_, &kHoleNanInt64, sizeof(double_value_));
2157 Initialize(Representation::Double());
2158}
2159
2160
2161HConstant::HConstant(Handle<Object> object, Representation r)
2162 : HTemplateInstruction<0>(HType::FromValue(object)),
2163 object_(Unique<Object>::CreateUninitialized(object)),
2164 object_map_(Handle<Map>::null()),
2165 bit_field_(
2166 HasStableMapValueField::encode(false) |
2167 HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
2168 HasDoubleValueField::encode(false) |
2169 HasExternalReferenceValueField::encode(false) |
2170 IsNotInNewSpaceField::encode(true) |
2171 BooleanValueField::encode(object->BooleanValue()) |
2172 IsUndetectableField::encode(false) | IsCallableField::encode(false) |
2173 InstanceTypeField::encode(kUnknownInstanceType)) {
2174 if (object->IsHeapObject()) {
2175 Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
2176 Isolate* isolate = heap_object->GetIsolate();
2177 Handle<Map> map(heap_object->map(), isolate);
2178 bit_field_ = IsNotInNewSpaceField::update(
2179 bit_field_, !isolate->heap()->InNewSpace(*object));
2180 bit_field_ = InstanceTypeField::update(bit_field_, map->instance_type());
2181 bit_field_ =
2182 IsUndetectableField::update(bit_field_, map->is_undetectable());
2183 bit_field_ = IsCallableField::update(bit_field_, map->is_callable());
2184 if (map->is_stable()) object_map_ = Unique<Map>::CreateImmovable(map);
2185 bit_field_ = HasStableMapValueField::update(
2186 bit_field_,
2187 HasMapValue() && Handle<Map>::cast(heap_object)->is_stable());
2188 }
2189 if (object->IsNumber()) {
2190 double n = object->Number();
2191 bool has_int32_value = IsInteger32(n);
2192 bit_field_ = HasInt32ValueField::update(bit_field_, has_int32_value);
2193 int32_value_ = DoubleToInt32(n);
2194 bit_field_ = HasSmiValueField::update(
2195 bit_field_, has_int32_value && Smi::IsValid(int32_value_));
2196 double_value_ = n;
2197 bit_field_ = HasDoubleValueField::update(bit_field_, true);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002198 }
2199
2200 Initialize(r);
2201}
2202
2203
2204HConstant::HConstant(Unique<Object> object, Unique<Map> object_map,
2205 bool has_stable_map_value, Representation r, HType type,
2206 bool is_not_in_new_space, bool boolean_value,
2207 bool is_undetectable, InstanceType instance_type)
2208 : HTemplateInstruction<0>(type),
2209 object_(object),
2210 object_map_(object_map),
2211 bit_field_(HasStableMapValueField::encode(has_stable_map_value) |
2212 HasSmiValueField::encode(false) |
2213 HasInt32ValueField::encode(false) |
2214 HasDoubleValueField::encode(false) |
2215 HasExternalReferenceValueField::encode(false) |
2216 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2217 BooleanValueField::encode(boolean_value) |
2218 IsUndetectableField::encode(is_undetectable) |
2219 InstanceTypeField::encode(instance_type)) {
2220 DCHECK(!object.handle().is_null());
2221 DCHECK(!type.IsTaggedNumber() || type.IsNone());
2222 Initialize(r);
2223}
2224
2225
2226HConstant::HConstant(int32_t integer_value, Representation r,
2227 bool is_not_in_new_space, Unique<Object> object)
2228 : object_(object),
2229 object_map_(Handle<Map>::null()),
2230 bit_field_(HasStableMapValueField::encode(false) |
2231 HasSmiValueField::encode(Smi::IsValid(integer_value)) |
2232 HasInt32ValueField::encode(true) |
2233 HasDoubleValueField::encode(true) |
2234 HasExternalReferenceValueField::encode(false) |
2235 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2236 BooleanValueField::encode(integer_value != 0) |
2237 IsUndetectableField::encode(false) |
2238 InstanceTypeField::encode(kUnknownInstanceType)),
2239 int32_value_(integer_value),
2240 double_value_(FastI2D(integer_value)) {
2241 // It's possible to create a constant with a value in Smi-range but stored
2242 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2243 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2244 bool is_smi = HasSmiValue() && !could_be_heapobject;
2245 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2246 Initialize(r);
2247}
2248
2249
2250HConstant::HConstant(double double_value, Representation r,
2251 bool is_not_in_new_space, Unique<Object> object)
2252 : object_(object),
2253 object_map_(Handle<Map>::null()),
2254 bit_field_(HasStableMapValueField::encode(false) |
2255 HasInt32ValueField::encode(IsInteger32(double_value)) |
2256 HasDoubleValueField::encode(true) |
2257 HasExternalReferenceValueField::encode(false) |
2258 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2259 BooleanValueField::encode(double_value != 0 &&
2260 !std::isnan(double_value)) |
2261 IsUndetectableField::encode(false) |
2262 InstanceTypeField::encode(kUnknownInstanceType)),
2263 int32_value_(DoubleToInt32(double_value)),
2264 double_value_(double_value) {
2265 bit_field_ = HasSmiValueField::update(
2266 bit_field_, HasInteger32Value() && Smi::IsValid(int32_value_));
2267 // It's possible to create a constant with a value in Smi-range but stored
2268 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2269 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2270 bool is_smi = HasSmiValue() && !could_be_heapobject;
2271 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2272 Initialize(r);
2273}
2274
2275
2276HConstant::HConstant(ExternalReference reference)
2277 : HTemplateInstruction<0>(HType::Any()),
2278 object_(Unique<Object>(Handle<Object>::null())),
2279 object_map_(Handle<Map>::null()),
2280 bit_field_(
2281 HasStableMapValueField::encode(false) |
2282 HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
2283 HasDoubleValueField::encode(false) |
2284 HasExternalReferenceValueField::encode(true) |
2285 IsNotInNewSpaceField::encode(true) | BooleanValueField::encode(true) |
2286 IsUndetectableField::encode(false) |
2287 InstanceTypeField::encode(kUnknownInstanceType)),
2288 external_reference_value_(reference) {
2289 Initialize(Representation::External());
2290}
2291
2292
2293void HConstant::Initialize(Representation r) {
2294 if (r.IsNone()) {
2295 if (HasSmiValue() && SmiValuesAre31Bits()) {
2296 r = Representation::Smi();
2297 } else if (HasInteger32Value()) {
2298 r = Representation::Integer32();
2299 } else if (HasDoubleValue()) {
2300 r = Representation::Double();
2301 } else if (HasExternalReferenceValue()) {
2302 r = Representation::External();
2303 } else {
2304 Handle<Object> object = object_.handle();
2305 if (object->IsJSObject()) {
2306 // Try to eagerly migrate JSObjects that have deprecated maps.
2307 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2308 if (js_object->map()->is_deprecated()) {
2309 JSObject::TryMigrateInstance(js_object);
2310 }
2311 }
2312 r = Representation::Tagged();
2313 }
2314 }
2315 if (r.IsSmi()) {
2316 // If we have an existing handle, zap it, because it might be a heap
2317 // number which we must not re-use when copying this HConstant to
2318 // Tagged representation later, because having Smi representation now
2319 // could cause heap object checks not to get emitted.
2320 object_ = Unique<Object>(Handle<Object>::null());
2321 }
2322 if (r.IsSmiOrInteger32() && object_.handle().is_null()) {
2323 // If it's not a heap object, it can't be in new space.
2324 bit_field_ = IsNotInNewSpaceField::update(bit_field_, true);
2325 }
2326 set_representation(r);
2327 SetFlag(kUseGVN);
2328}
2329
2330
2331bool HConstant::ImmortalImmovable() const {
2332 if (HasInteger32Value()) {
2333 return false;
2334 }
2335 if (HasDoubleValue()) {
2336 if (IsSpecialDouble()) {
2337 return true;
2338 }
2339 return false;
2340 }
2341 if (HasExternalReferenceValue()) {
2342 return false;
2343 }
2344
2345 DCHECK(!object_.handle().is_null());
2346 Heap* heap = isolate()->heap();
2347 DCHECK(!object_.IsKnownGlobal(heap->minus_zero_value()));
2348 DCHECK(!object_.IsKnownGlobal(heap->nan_value()));
2349 return
2350#define IMMORTAL_IMMOVABLE_ROOT(name) \
2351 object_.IsKnownGlobal(heap->root(Heap::k##name##RootIndex)) ||
2352 IMMORTAL_IMMOVABLE_ROOT_LIST(IMMORTAL_IMMOVABLE_ROOT)
2353#undef IMMORTAL_IMMOVABLE_ROOT
2354#define INTERNALIZED_STRING(name, value) \
2355 object_.IsKnownGlobal(heap->name()) ||
2356 INTERNALIZED_STRING_LIST(INTERNALIZED_STRING)
2357#undef INTERNALIZED_STRING
2358#define STRING_TYPE(NAME, size, name, Name) \
2359 object_.IsKnownGlobal(heap->name##_map()) ||
2360 STRING_TYPE_LIST(STRING_TYPE)
2361#undef STRING_TYPE
2362 false;
2363}
2364
2365
2366bool HConstant::EmitAtUses() {
2367 DCHECK(IsLinked());
2368 if (block()->graph()->has_osr() &&
2369 block()->graph()->IsStandardConstant(this)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002370 return true;
2371 }
2372 if (HasNoUses()) return true;
2373 if (IsCell()) return false;
2374 if (representation().IsDouble()) return false;
2375 if (representation().IsExternal()) return false;
2376 return true;
2377}
2378
2379
2380HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2381 if (r.IsSmi() && !HasSmiValue()) return NULL;
2382 if (r.IsInteger32() && !HasInteger32Value()) return NULL;
2383 if (r.IsDouble() && !HasDoubleValue()) return NULL;
2384 if (r.IsExternal() && !HasExternalReferenceValue()) return NULL;
2385 if (HasInteger32Value()) {
2386 return new (zone) HConstant(int32_value_, r, NotInNewSpace(), object_);
2387 }
2388 if (HasDoubleValue()) {
2389 return new (zone) HConstant(double_value_, r, NotInNewSpace(), object_);
2390 }
2391 if (HasExternalReferenceValue()) {
2392 return new(zone) HConstant(external_reference_value_);
2393 }
2394 DCHECK(!object_.handle().is_null());
2395 return new (zone) HConstant(object_, object_map_, HasStableMapValue(), r,
2396 type_, NotInNewSpace(), BooleanValue(),
2397 IsUndetectable(), GetInstanceType());
2398}
2399
2400
2401Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
2402 HConstant* res = NULL;
2403 if (HasInteger32Value()) {
2404 res = new (zone) HConstant(int32_value_, Representation::Integer32(),
2405 NotInNewSpace(), object_);
2406 } else if (HasDoubleValue()) {
2407 res = new (zone)
2408 HConstant(DoubleToInt32(double_value_), Representation::Integer32(),
2409 NotInNewSpace(), object_);
2410 }
2411 return res != NULL ? Just(res) : Nothing<HConstant*>();
2412}
2413
2414
2415Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Isolate* isolate,
2416 Zone* zone) {
2417 HConstant* res = NULL;
2418 Handle<Object> handle = this->handle(isolate);
2419 if (handle->IsBoolean()) {
2420 res = handle->BooleanValue() ?
2421 new(zone) HConstant(1) : new(zone) HConstant(0);
2422 } else if (handle->IsUndefined()) {
2423 res = new (zone) HConstant(std::numeric_limits<double>::quiet_NaN());
2424 } else if (handle->IsNull()) {
2425 res = new(zone) HConstant(0);
Ben Murdoch097c5b22016-05-18 11:27:45 +01002426 } else if (handle->IsString()) {
2427 res = new(zone) HConstant(String::ToNumber(Handle<String>::cast(handle)));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002428 }
2429 return res != NULL ? Just(res) : Nothing<HConstant*>();
2430}
2431
2432
2433std::ostream& HConstant::PrintDataTo(std::ostream& os) const { // NOLINT
2434 if (HasInteger32Value()) {
2435 os << int32_value_ << " ";
2436 } else if (HasDoubleValue()) {
2437 os << double_value_ << " ";
2438 } else if (HasExternalReferenceValue()) {
2439 os << reinterpret_cast<void*>(external_reference_value_.address()) << " ";
2440 } else {
2441 // The handle() method is silently and lazily mutating the object.
2442 Handle<Object> h = const_cast<HConstant*>(this)->handle(isolate());
2443 os << Brief(*h) << " ";
2444 if (HasStableMapValue()) os << "[stable-map] ";
2445 if (HasObjectMap()) os << "[map " << *ObjectMap().handle() << "] ";
2446 }
2447 if (!NotInNewSpace()) os << "[new space] ";
2448 return os;
2449}
2450
2451
2452std::ostream& HBinaryOperation::PrintDataTo(std::ostream& os) const { // NOLINT
2453 os << NameOf(left()) << " " << NameOf(right());
2454 if (CheckFlag(kCanOverflow)) os << " !";
2455 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
2456 return os;
2457}
2458
2459
2460void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
2461 DCHECK(CheckFlag(kFlexibleRepresentation));
2462 Representation new_rep = RepresentationFromInputs();
2463 UpdateRepresentation(new_rep, h_infer, "inputs");
2464
2465 if (representation().IsSmi() && HasNonSmiUse()) {
2466 UpdateRepresentation(
2467 Representation::Integer32(), h_infer, "use requirements");
2468 }
2469
2470 if (observed_output_representation_.IsNone()) {
2471 new_rep = RepresentationFromUses();
2472 UpdateRepresentation(new_rep, h_infer, "uses");
2473 } else {
2474 new_rep = RepresentationFromOutput();
2475 UpdateRepresentation(new_rep, h_infer, "output");
2476 }
2477}
2478
2479
2480Representation HBinaryOperation::RepresentationFromInputs() {
2481 // Determine the worst case of observed input representations and
2482 // the currently assumed output representation.
2483 Representation rep = representation();
2484 for (int i = 1; i <= 2; ++i) {
2485 rep = rep.generalize(observed_input_representation(i));
2486 }
2487 // If any of the actual input representation is more general than what we
2488 // have so far but not Tagged, use that representation instead.
2489 Representation left_rep = left()->representation();
2490 Representation right_rep = right()->representation();
2491 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
2492 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
2493
2494 return rep;
2495}
2496
2497
2498bool HBinaryOperation::IgnoreObservedOutputRepresentation(
2499 Representation current_rep) {
2500 return ((current_rep.IsInteger32() && CheckUsesForFlag(kTruncatingToInt32)) ||
2501 (current_rep.IsSmi() && CheckUsesForFlag(kTruncatingToSmi))) &&
2502 // Mul in Integer32 mode would be too precise.
2503 (!this->IsMul() || HMul::cast(this)->MulMinusOne());
2504}
2505
2506
2507Representation HBinaryOperation::RepresentationFromOutput() {
2508 Representation rep = representation();
2509 // Consider observed output representation, but ignore it if it's Double,
2510 // this instruction is not a division, and all its uses are truncating
2511 // to Integer32.
2512 if (observed_output_representation_.is_more_general_than(rep) &&
2513 !IgnoreObservedOutputRepresentation(rep)) {
2514 return observed_output_representation_;
2515 }
2516 return Representation::None();
2517}
2518
2519
2520void HBinaryOperation::AssumeRepresentation(Representation r) {
2521 set_observed_input_representation(1, r);
2522 set_observed_input_representation(2, r);
2523 HValue::AssumeRepresentation(r);
2524}
2525
2526
2527void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
2528 DCHECK(CheckFlag(kFlexibleRepresentation));
2529 Representation new_rep = RepresentationFromInputs();
2530 UpdateRepresentation(new_rep, h_infer, "inputs");
2531 // Do not care about uses.
2532}
2533
2534
2535Range* HBitwise::InferRange(Zone* zone) {
2536 if (op() == Token::BIT_XOR) {
2537 if (left()->HasRange() && right()->HasRange()) {
2538 // The maximum value has the high bit, and all bits below, set:
2539 // (1 << high) - 1.
2540 // If the range can be negative, the minimum int is a negative number with
2541 // the high bit, and all bits below, unset:
2542 // -(1 << high).
2543 // If it cannot be negative, conservatively choose 0 as minimum int.
2544 int64_t left_upper = left()->range()->upper();
2545 int64_t left_lower = left()->range()->lower();
2546 int64_t right_upper = right()->range()->upper();
2547 int64_t right_lower = right()->range()->lower();
2548
2549 if (left_upper < 0) left_upper = ~left_upper;
2550 if (left_lower < 0) left_lower = ~left_lower;
2551 if (right_upper < 0) right_upper = ~right_upper;
2552 if (right_lower < 0) right_lower = ~right_lower;
2553
2554 int high = MostSignificantBit(
2555 static_cast<uint32_t>(
2556 left_upper | left_lower | right_upper | right_lower));
2557
2558 int64_t limit = 1;
2559 limit <<= high;
2560 int32_t min = (left()->range()->CanBeNegative() ||
2561 right()->range()->CanBeNegative())
2562 ? static_cast<int32_t>(-limit) : 0;
2563 return new(zone) Range(min, static_cast<int32_t>(limit - 1));
2564 }
2565 Range* result = HValue::InferRange(zone);
2566 result->set_can_be_minus_zero(false);
2567 return result;
2568 }
2569 const int32_t kDefaultMask = static_cast<int32_t>(0xffffffff);
2570 int32_t left_mask = (left()->range() != NULL)
2571 ? left()->range()->Mask()
2572 : kDefaultMask;
2573 int32_t right_mask = (right()->range() != NULL)
2574 ? right()->range()->Mask()
2575 : kDefaultMask;
2576 int32_t result_mask = (op() == Token::BIT_AND)
2577 ? left_mask & right_mask
2578 : left_mask | right_mask;
2579 if (result_mask >= 0) return new(zone) Range(0, result_mask);
2580
2581 Range* result = HValue::InferRange(zone);
2582 result->set_can_be_minus_zero(false);
2583 return result;
2584}
2585
2586
2587Range* HSar::InferRange(Zone* zone) {
2588 if (right()->IsConstant()) {
2589 HConstant* c = HConstant::cast(right());
2590 if (c->HasInteger32Value()) {
2591 Range* result = (left()->range() != NULL)
2592 ? left()->range()->Copy(zone)
2593 : new(zone) Range();
2594 result->Sar(c->Integer32Value());
2595 return result;
2596 }
2597 }
2598 return HValue::InferRange(zone);
2599}
2600
2601
2602Range* HShr::InferRange(Zone* zone) {
2603 if (right()->IsConstant()) {
2604 HConstant* c = HConstant::cast(right());
2605 if (c->HasInteger32Value()) {
2606 int shift_count = c->Integer32Value() & 0x1f;
2607 if (left()->range()->CanBeNegative()) {
2608 // Only compute bounds if the result always fits into an int32.
2609 return (shift_count >= 1)
2610 ? new(zone) Range(0,
2611 static_cast<uint32_t>(0xffffffff) >> shift_count)
2612 : new(zone) Range();
2613 } else {
2614 // For positive inputs we can use the >> operator.
2615 Range* result = (left()->range() != NULL)
2616 ? left()->range()->Copy(zone)
2617 : new(zone) Range();
2618 result->Sar(c->Integer32Value());
2619 return result;
2620 }
2621 }
2622 }
2623 return HValue::InferRange(zone);
2624}
2625
2626
2627Range* HShl::InferRange(Zone* zone) {
2628 if (right()->IsConstant()) {
2629 HConstant* c = HConstant::cast(right());
2630 if (c->HasInteger32Value()) {
2631 Range* result = (left()->range() != NULL)
2632 ? left()->range()->Copy(zone)
2633 : new(zone) Range();
2634 result->Shl(c->Integer32Value());
2635 return result;
2636 }
2637 }
2638 return HValue::InferRange(zone);
2639}
2640
2641
2642Range* HLoadNamedField::InferRange(Zone* zone) {
2643 if (access().representation().IsInteger8()) {
2644 return new(zone) Range(kMinInt8, kMaxInt8);
2645 }
2646 if (access().representation().IsUInteger8()) {
2647 return new(zone) Range(kMinUInt8, kMaxUInt8);
2648 }
2649 if (access().representation().IsInteger16()) {
2650 return new(zone) Range(kMinInt16, kMaxInt16);
2651 }
2652 if (access().representation().IsUInteger16()) {
2653 return new(zone) Range(kMinUInt16, kMaxUInt16);
2654 }
2655 if (access().IsStringLength()) {
2656 return new(zone) Range(0, String::kMaxLength);
2657 }
2658 return HValue::InferRange(zone);
2659}
2660
2661
2662Range* HLoadKeyed::InferRange(Zone* zone) {
2663 switch (elements_kind()) {
2664 case INT8_ELEMENTS:
2665 return new(zone) Range(kMinInt8, kMaxInt8);
2666 case UINT8_ELEMENTS:
2667 case UINT8_CLAMPED_ELEMENTS:
2668 return new(zone) Range(kMinUInt8, kMaxUInt8);
2669 case INT16_ELEMENTS:
2670 return new(zone) Range(kMinInt16, kMaxInt16);
2671 case UINT16_ELEMENTS:
2672 return new(zone) Range(kMinUInt16, kMaxUInt16);
2673 default:
2674 return HValue::InferRange(zone);
2675 }
2676}
2677
2678
2679std::ostream& HCompareGeneric::PrintDataTo(std::ostream& os) const { // NOLINT
2680 os << Token::Name(token()) << " ";
2681 return HBinaryOperation::PrintDataTo(os);
2682}
2683
2684
2685std::ostream& HStringCompareAndBranch::PrintDataTo(
2686 std::ostream& os) const { // NOLINT
2687 os << Token::Name(token()) << " ";
2688 return HControlInstruction::PrintDataTo(os);
2689}
2690
2691
2692std::ostream& HCompareNumericAndBranch::PrintDataTo(
2693 std::ostream& os) const { // NOLINT
2694 os << Token::Name(token()) << " " << NameOf(left()) << " " << NameOf(right());
2695 return HControlInstruction::PrintDataTo(os);
2696}
2697
2698
2699std::ostream& HCompareObjectEqAndBranch::PrintDataTo(
2700 std::ostream& os) const { // NOLINT
2701 os << NameOf(left()) << " " << NameOf(right());
2702 return HControlInstruction::PrintDataTo(os);
2703}
2704
2705
2706bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2707 if (known_successor_index() != kNoKnownSuccessorIndex) {
2708 *block = SuccessorAt(known_successor_index());
2709 return true;
2710 }
2711 if (FLAG_fold_constants && left()->IsConstant() && right()->IsConstant()) {
2712 *block = HConstant::cast(left())->DataEquals(HConstant::cast(right()))
2713 ? FirstSuccessor() : SecondSuccessor();
2714 return true;
2715 }
2716 *block = NULL;
2717 return false;
2718}
2719
2720
2721bool HIsStringAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2722 if (known_successor_index() != kNoKnownSuccessorIndex) {
2723 *block = SuccessorAt(known_successor_index());
2724 return true;
2725 }
2726 if (FLAG_fold_constants && value()->IsConstant()) {
2727 *block = HConstant::cast(value())->HasStringValue()
2728 ? FirstSuccessor() : SecondSuccessor();
2729 return true;
2730 }
2731 if (value()->type().IsString()) {
2732 *block = FirstSuccessor();
2733 return true;
2734 }
2735 if (value()->type().IsSmi() ||
2736 value()->type().IsNull() ||
2737 value()->type().IsBoolean() ||
2738 value()->type().IsUndefined() ||
2739 value()->type().IsJSReceiver()) {
2740 *block = SecondSuccessor();
2741 return true;
2742 }
2743 *block = NULL;
2744 return false;
2745}
2746
2747
2748bool HIsUndetectableAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2749 if (FLAG_fold_constants && value()->IsConstant()) {
2750 *block = HConstant::cast(value())->IsUndetectable()
2751 ? FirstSuccessor() : SecondSuccessor();
2752 return true;
2753 }
Ben Murdochda12d292016-06-02 14:46:10 +01002754 if (value()->type().IsNull() || value()->type().IsUndefined()) {
2755 *block = FirstSuccessor();
2756 return true;
2757 }
2758 if (value()->type().IsBoolean() ||
2759 value()->type().IsSmi() ||
2760 value()->type().IsString() ||
2761 value()->type().IsJSReceiver()) {
2762 *block = SecondSuccessor();
2763 return true;
2764 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002765 *block = NULL;
2766 return false;
2767}
2768
2769
2770bool HHasInstanceTypeAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2771 if (FLAG_fold_constants && value()->IsConstant()) {
2772 InstanceType type = HConstant::cast(value())->GetInstanceType();
2773 *block = (from_ <= type) && (type <= to_)
2774 ? FirstSuccessor() : SecondSuccessor();
2775 return true;
2776 }
2777 *block = NULL;
2778 return false;
2779}
2780
2781
2782void HCompareHoleAndBranch::InferRepresentation(
2783 HInferRepresentationPhase* h_infer) {
2784 ChangeRepresentation(value()->representation());
2785}
2786
2787
2788bool HCompareNumericAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
2789 if (left() == right() &&
2790 left()->representation().IsSmiOrInteger32()) {
2791 *block = (token() == Token::EQ ||
2792 token() == Token::EQ_STRICT ||
2793 token() == Token::LTE ||
2794 token() == Token::GTE)
2795 ? FirstSuccessor() : SecondSuccessor();
2796 return true;
2797 }
2798 *block = NULL;
2799 return false;
2800}
2801
2802
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002803std::ostream& HGoto::PrintDataTo(std::ostream& os) const { // NOLINT
2804 return os << *SuccessorAt(0);
2805}
2806
2807
2808void HCompareNumericAndBranch::InferRepresentation(
2809 HInferRepresentationPhase* h_infer) {
2810 Representation left_rep = left()->representation();
2811 Representation right_rep = right()->representation();
2812 Representation observed_left = observed_input_representation(0);
2813 Representation observed_right = observed_input_representation(1);
2814
2815 Representation rep = Representation::None();
2816 rep = rep.generalize(observed_left);
2817 rep = rep.generalize(observed_right);
2818 if (rep.IsNone() || rep.IsSmiOrInteger32()) {
2819 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
2820 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
2821 } else {
2822 rep = Representation::Double();
2823 }
2824
2825 if (rep.IsDouble()) {
2826 // According to the ES5 spec (11.9.3, 11.8.5), Equality comparisons (==, ===
2827 // and !=) have special handling of undefined, e.g. undefined == undefined
2828 // is 'true'. Relational comparisons have a different semantic, first
2829 // calling ToPrimitive() on their arguments. The standard Crankshaft
2830 // tagged-to-double conversion to ensure the HCompareNumericAndBranch's
2831 // inputs are doubles caused 'undefined' to be converted to NaN. That's
2832 // compatible out-of-the box with ordered relational comparisons (<, >, <=,
2833 // >=). However, for equality comparisons (and for 'in' and 'instanceof'),
2834 // it is not consistent with the spec. For example, it would cause undefined
2835 // == undefined (should be true) to be evaluated as NaN == NaN
2836 // (false). Therefore, any comparisons other than ordered relational
2837 // comparisons must cause a deopt when one of their arguments is undefined.
2838 // See also v8:1434
Ben Murdoch097c5b22016-05-18 11:27:45 +01002839 if (Token::IsOrderedRelationalCompareOp(token_)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002840 SetFlag(kAllowUndefinedAsNaN);
2841 }
2842 }
2843 ChangeRepresentation(rep);
2844}
2845
2846
2847std::ostream& HParameter::PrintDataTo(std::ostream& os) const { // NOLINT
2848 return os << index();
2849}
2850
2851
2852std::ostream& HLoadNamedField::PrintDataTo(std::ostream& os) const { // NOLINT
2853 os << NameOf(object()) << access_;
2854
2855 if (maps() != NULL) {
2856 os << " [" << *maps()->at(0).handle();
2857 for (int i = 1; i < maps()->size(); ++i) {
2858 os << "," << *maps()->at(i).handle();
2859 }
2860 os << "]";
2861 }
2862
2863 if (HasDependency()) os << " " << NameOf(dependency());
2864 return os;
2865}
2866
2867
2868std::ostream& HLoadNamedGeneric::PrintDataTo(
2869 std::ostream& os) const { // NOLINT
2870 Handle<String> n = Handle<String>::cast(name());
2871 return os << NameOf(object()) << "." << n->ToCString().get();
2872}
2873
2874
2875std::ostream& HLoadKeyed::PrintDataTo(std::ostream& os) const { // NOLINT
2876 if (!is_fixed_typed_array()) {
2877 os << NameOf(elements());
2878 } else {
2879 DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
2880 elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
2881 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
2882 }
2883
2884 os << "[" << NameOf(key());
2885 if (IsDehoisted()) os << " + " << base_offset();
2886 os << "]";
2887
2888 if (HasDependency()) os << " " << NameOf(dependency());
2889 if (RequiresHoleCheck()) os << " check_hole";
2890 return os;
2891}
2892
2893
2894bool HLoadKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
2895 // The base offset is usually simply the size of the array header, except
2896 // with dehoisting adds an addition offset due to a array index key
2897 // manipulation, in which case it becomes (array header size +
2898 // constant-offset-from-key * kPointerSize)
2899 uint32_t base_offset = BaseOffsetField::decode(bit_field_);
2900 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset;
2901 addition_result += increase_by_value;
2902 if (!addition_result.IsValid()) return false;
2903 base_offset = addition_result.ValueOrDie();
2904 if (!BaseOffsetField::is_valid(base_offset)) return false;
2905 bit_field_ = BaseOffsetField::update(bit_field_, base_offset);
2906 return true;
2907}
2908
2909
2910bool HLoadKeyed::UsesMustHandleHole() const {
2911 if (IsFastPackedElementsKind(elements_kind())) {
2912 return false;
2913 }
2914
2915 if (IsFixedTypedArrayElementsKind(elements_kind())) {
2916 return false;
2917 }
2918
2919 if (hole_mode() == ALLOW_RETURN_HOLE) {
2920 if (IsFastDoubleElementsKind(elements_kind())) {
2921 return AllUsesCanTreatHoleAsNaN();
2922 }
2923 return true;
2924 }
2925
2926 if (IsFastDoubleElementsKind(elements_kind())) {
2927 return false;
2928 }
2929
2930 // Holes are only returned as tagged values.
2931 if (!representation().IsTagged()) {
2932 return false;
2933 }
2934
2935 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
2936 HValue* use = it.value();
2937 if (!use->IsChange()) return false;
2938 }
2939
2940 return true;
2941}
2942
2943
2944bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
2945 return IsFastDoubleElementsKind(elements_kind()) &&
2946 CheckUsesForFlag(HValue::kAllowUndefinedAsNaN);
2947}
2948
2949
2950bool HLoadKeyed::RequiresHoleCheck() const {
2951 if (IsFastPackedElementsKind(elements_kind())) {
2952 return false;
2953 }
2954
2955 if (IsFixedTypedArrayElementsKind(elements_kind())) {
2956 return false;
2957 }
2958
2959 if (hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
2960 return false;
2961 }
2962
2963 return !UsesMustHandleHole();
2964}
2965
2966
2967std::ostream& HLoadKeyedGeneric::PrintDataTo(
2968 std::ostream& os) const { // NOLINT
2969 return os << NameOf(object()) << "[" << NameOf(key()) << "]";
2970}
2971
2972
2973HValue* HLoadKeyedGeneric::Canonicalize() {
2974 // Recognize generic keyed loads that use property name generated
2975 // by for-in statement as a key and rewrite them into fast property load
2976 // by index.
2977 if (key()->IsLoadKeyed()) {
2978 HLoadKeyed* key_load = HLoadKeyed::cast(key());
2979 if (key_load->elements()->IsForInCacheArray()) {
2980 HForInCacheArray* names_cache =
2981 HForInCacheArray::cast(key_load->elements());
2982
2983 if (names_cache->enumerable() == object()) {
2984 HForInCacheArray* index_cache =
2985 names_cache->index_cache();
2986 HCheckMapValue* map_check = HCheckMapValue::New(
2987 block()->graph()->isolate(), block()->graph()->zone(),
2988 block()->graph()->GetInvalidContext(), object(),
2989 names_cache->map());
2990 HInstruction* index = HLoadKeyed::New(
2991 block()->graph()->isolate(), block()->graph()->zone(),
2992 block()->graph()->GetInvalidContext(), index_cache, key_load->key(),
2993 key_load->key(), nullptr, key_load->elements_kind());
2994 map_check->InsertBefore(this);
2995 index->InsertBefore(this);
2996 return Prepend(new(block()->zone()) HLoadFieldByIndex(
2997 object(), index));
2998 }
2999 }
3000 }
3001
3002 return this;
3003}
3004
3005
3006std::ostream& HStoreNamedGeneric::PrintDataTo(
3007 std::ostream& os) const { // NOLINT
3008 Handle<String> n = Handle<String>::cast(name());
3009 return os << NameOf(object()) << "." << n->ToCString().get() << " = "
3010 << NameOf(value());
3011}
3012
3013
3014std::ostream& HStoreNamedField::PrintDataTo(std::ostream& os) const { // NOLINT
3015 os << NameOf(object()) << access_ << " = " << NameOf(value());
3016 if (NeedsWriteBarrier()) os << " (write-barrier)";
3017 if (has_transition()) os << " (transition map " << *transition_map() << ")";
3018 return os;
3019}
3020
3021
3022std::ostream& HStoreKeyed::PrintDataTo(std::ostream& os) const { // NOLINT
3023 if (!is_fixed_typed_array()) {
3024 os << NameOf(elements());
3025 } else {
3026 DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
3027 elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3028 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3029 }
3030
3031 os << "[" << NameOf(key());
3032 if (IsDehoisted()) os << " + " << base_offset();
3033 return os << "] = " << NameOf(value());
3034}
3035
3036
3037std::ostream& HStoreKeyedGeneric::PrintDataTo(
3038 std::ostream& os) const { // NOLINT
3039 return os << NameOf(object()) << "[" << NameOf(key())
3040 << "] = " << NameOf(value());
3041}
3042
3043
3044std::ostream& HTransitionElementsKind::PrintDataTo(
3045 std::ostream& os) const { // NOLINT
3046 os << NameOf(object());
3047 ElementsKind from_kind = original_map().handle()->elements_kind();
3048 ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3049 os << " " << *original_map().handle() << " ["
3050 << ElementsAccessor::ForKind(from_kind)->name() << "] -> "
3051 << *transitioned_map().handle() << " ["
3052 << ElementsAccessor::ForKind(to_kind)->name() << "]";
3053 if (IsSimpleMapChangeTransition(from_kind, to_kind)) os << " (simple)";
3054 return os;
3055}
3056
3057
3058std::ostream& HLoadGlobalGeneric::PrintDataTo(
3059 std::ostream& os) const { // NOLINT
3060 return os << name()->ToCString().get() << " ";
3061}
3062
3063
3064std::ostream& HInnerAllocatedObject::PrintDataTo(
3065 std::ostream& os) const { // NOLINT
3066 os << NameOf(base_object()) << " offset ";
3067 return offset()->PrintTo(os);
3068}
3069
3070
3071std::ostream& HLoadContextSlot::PrintDataTo(std::ostream& os) const { // NOLINT
3072 return os << NameOf(value()) << "[" << slot_index() << "]";
3073}
3074
3075
3076std::ostream& HStoreContextSlot::PrintDataTo(
3077 std::ostream& os) const { // NOLINT
3078 return os << NameOf(context()) << "[" << slot_index()
3079 << "] = " << NameOf(value());
3080}
3081
3082
3083// Implementation of type inference and type conversions. Calculates
3084// the inferred type of this instruction based on the input operands.
3085
3086HType HValue::CalculateInferredType() {
3087 return type_;
3088}
3089
3090
3091HType HPhi::CalculateInferredType() {
3092 if (OperandCount() == 0) return HType::Tagged();
3093 HType result = OperandAt(0)->type();
3094 for (int i = 1; i < OperandCount(); ++i) {
3095 HType current = OperandAt(i)->type();
3096 result = result.Combine(current);
3097 }
3098 return result;
3099}
3100
3101
3102HType HChange::CalculateInferredType() {
3103 if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
3104 return type();
3105}
3106
3107
3108Representation HUnaryMathOperation::RepresentationFromInputs() {
3109 if (SupportsFlexibleFloorAndRound() &&
3110 (op_ == kMathFloor || op_ == kMathRound)) {
3111 // Floor and Round always take a double input. The integral result can be
3112 // used as an integer or a double. Infer the representation from the uses.
3113 return Representation::None();
3114 }
3115 Representation rep = representation();
3116 // If any of the actual input representation is more general than what we
3117 // have so far but not Tagged, use that representation instead.
3118 Representation input_rep = value()->representation();
3119 if (!input_rep.IsTagged()) {
3120 rep = rep.generalize(input_rep);
3121 }
3122 return rep;
3123}
3124
3125
3126bool HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
3127 HValue* dominator) {
3128 DCHECK(side_effect == kNewSpacePromotion);
3129 Zone* zone = block()->zone();
3130 Isolate* isolate = block()->isolate();
3131 if (!FLAG_use_allocation_folding) return false;
3132
3133 // Try to fold allocations together with their dominating allocations.
3134 if (!dominator->IsAllocate()) {
3135 if (FLAG_trace_allocation_folding) {
3136 PrintF("#%d (%s) cannot fold into #%d (%s)\n",
3137 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3138 }
3139 return false;
3140 }
3141
3142 // Check whether we are folding within the same block for local folding.
3143 if (FLAG_use_local_allocation_folding && dominator->block() != block()) {
3144 if (FLAG_trace_allocation_folding) {
3145 PrintF("#%d (%s) cannot fold into #%d (%s), crosses basic blocks\n",
3146 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3147 }
3148 return false;
3149 }
3150
3151 HAllocate* dominator_allocate = HAllocate::cast(dominator);
3152 HValue* dominator_size = dominator_allocate->size();
3153 HValue* current_size = size();
3154
3155 // TODO(hpayer): Add support for non-constant allocation in dominator.
3156 if (!dominator_size->IsInteger32Constant()) {
3157 if (FLAG_trace_allocation_folding) {
3158 PrintF("#%d (%s) cannot fold into #%d (%s), "
3159 "dynamic allocation size in dominator\n",
3160 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3161 }
3162 return false;
3163 }
3164
3165
3166 if (!IsFoldable(dominator_allocate)) {
3167 if (FLAG_trace_allocation_folding) {
3168 PrintF("#%d (%s) cannot fold into #%d (%s), different spaces\n", id(),
3169 Mnemonic(), dominator->id(), dominator->Mnemonic());
3170 }
3171 return false;
3172 }
3173
3174 if (!has_size_upper_bound()) {
3175 if (FLAG_trace_allocation_folding) {
3176 PrintF("#%d (%s) cannot fold into #%d (%s), "
3177 "can't estimate total allocation size\n",
3178 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3179 }
3180 return false;
3181 }
3182
3183 if (!current_size->IsInteger32Constant()) {
3184 // If it's not constant then it is a size_in_bytes calculation graph
3185 // like this: (const_header_size + const_element_size * size).
3186 DCHECK(current_size->IsInstruction());
3187
3188 HInstruction* current_instr = HInstruction::cast(current_size);
3189 if (!current_instr->Dominates(dominator_allocate)) {
3190 if (FLAG_trace_allocation_folding) {
3191 PrintF("#%d (%s) cannot fold into #%d (%s), dynamic size "
3192 "value does not dominate target allocation\n",
3193 id(), Mnemonic(), dominator_allocate->id(),
3194 dominator_allocate->Mnemonic());
3195 }
3196 return false;
3197 }
3198 }
3199
3200 DCHECK(
3201 (IsNewSpaceAllocation() && dominator_allocate->IsNewSpaceAllocation()) ||
3202 (IsOldSpaceAllocation() && dominator_allocate->IsOldSpaceAllocation()));
3203
3204 // First update the size of the dominator allocate instruction.
3205 dominator_size = dominator_allocate->size();
3206 int32_t original_object_size =
3207 HConstant::cast(dominator_size)->GetInteger32Constant();
3208 int32_t dominator_size_constant = original_object_size;
3209
3210 if (MustAllocateDoubleAligned()) {
3211 if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
3212 dominator_size_constant += kDoubleSize / 2;
3213 }
3214 }
3215
3216 int32_t current_size_max_value = size_upper_bound()->GetInteger32Constant();
3217 int32_t new_dominator_size = dominator_size_constant + current_size_max_value;
3218
3219 // Since we clear the first word after folded memory, we cannot use the
3220 // whole Page::kMaxRegularHeapObjectSize memory.
3221 if (new_dominator_size > Page::kMaxRegularHeapObjectSize - kPointerSize) {
3222 if (FLAG_trace_allocation_folding) {
3223 PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3224 id(), Mnemonic(), dominator_allocate->id(),
3225 dominator_allocate->Mnemonic(), new_dominator_size);
3226 }
3227 return false;
3228 }
3229
3230 HInstruction* new_dominator_size_value;
3231
3232 if (current_size->IsInteger32Constant()) {
3233 new_dominator_size_value = HConstant::CreateAndInsertBefore(
3234 isolate, zone, context(), new_dominator_size, Representation::None(),
3235 dominator_allocate);
3236 } else {
3237 HValue* new_dominator_size_constant = HConstant::CreateAndInsertBefore(
3238 isolate, zone, context(), dominator_size_constant,
3239 Representation::Integer32(), dominator_allocate);
3240
3241 // Add old and new size together and insert.
3242 current_size->ChangeRepresentation(Representation::Integer32());
3243
3244 new_dominator_size_value = HAdd::New(
3245 isolate, zone, context(), new_dominator_size_constant, current_size);
3246 new_dominator_size_value->ClearFlag(HValue::kCanOverflow);
3247 new_dominator_size_value->ChangeRepresentation(Representation::Integer32());
3248
3249 new_dominator_size_value->InsertBefore(dominator_allocate);
3250 }
3251
3252 dominator_allocate->UpdateSize(new_dominator_size_value);
3253
3254 if (MustAllocateDoubleAligned()) {
3255 if (!dominator_allocate->MustAllocateDoubleAligned()) {
3256 dominator_allocate->MakeDoubleAligned();
3257 }
3258 }
3259
Ben Murdochda12d292016-06-02 14:46:10 +01003260 bool keep_heap_iterable = FLAG_log_gc || FLAG_heap_stats;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003261#ifdef VERIFY_HEAP
Ben Murdochda12d292016-06-02 14:46:10 +01003262 keep_heap_iterable = keep_heap_iterable || FLAG_verify_heap;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003263#endif
3264
Ben Murdochda12d292016-06-02 14:46:10 +01003265 if (keep_heap_iterable) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003266 dominator_allocate->MakePrefillWithFiller();
3267 } else {
3268 // TODO(hpayer): This is a short-term hack to make allocation mementos
3269 // work again in new space.
3270 dominator_allocate->ClearNextMapWord(original_object_size);
3271 }
3272
3273 dominator_allocate->UpdateClearNextMapWord(MustClearNextMapWord());
3274
3275 // After that replace the dominated allocate instruction.
3276 HInstruction* inner_offset = HConstant::CreateAndInsertBefore(
3277 isolate, zone, context(), dominator_size_constant, Representation::None(),
3278 this);
3279
3280 HInstruction* dominated_allocate_instr = HInnerAllocatedObject::New(
3281 isolate, zone, context(), dominator_allocate, inner_offset, type());
3282 dominated_allocate_instr->InsertBefore(this);
3283 DeleteAndReplaceWith(dominated_allocate_instr);
3284 if (FLAG_trace_allocation_folding) {
3285 PrintF("#%d (%s) folded into #%d (%s)\n",
3286 id(), Mnemonic(), dominator_allocate->id(),
3287 dominator_allocate->Mnemonic());
3288 }
3289 return true;
3290}
3291
3292
3293void HAllocate::UpdateFreeSpaceFiller(int32_t free_space_size) {
3294 DCHECK(filler_free_space_size_ != NULL);
3295 Zone* zone = block()->zone();
3296 // We must explicitly force Smi representation here because on x64 we
3297 // would otherwise automatically choose int32, but the actual store
3298 // requires a Smi-tagged value.
3299 HConstant* new_free_space_size = HConstant::CreateAndInsertBefore(
3300 block()->isolate(), zone, context(),
3301 filler_free_space_size_->value()->GetInteger32Constant() +
3302 free_space_size,
3303 Representation::Smi(), filler_free_space_size_);
3304 filler_free_space_size_->UpdateValue(new_free_space_size);
3305}
3306
3307
3308void HAllocate::CreateFreeSpaceFiller(int32_t free_space_size) {
3309 DCHECK(filler_free_space_size_ == NULL);
3310 Isolate* isolate = block()->isolate();
3311 Zone* zone = block()->zone();
3312 HInstruction* free_space_instr =
3313 HInnerAllocatedObject::New(isolate, zone, context(), dominating_allocate_,
3314 dominating_allocate_->size(), type());
3315 free_space_instr->InsertBefore(this);
3316 HConstant* filler_map = HConstant::CreateAndInsertAfter(
3317 zone, Unique<Map>::CreateImmovable(isolate->factory()->free_space_map()),
3318 true, free_space_instr);
3319 HInstruction* store_map =
3320 HStoreNamedField::New(isolate, zone, context(), free_space_instr,
3321 HObjectAccess::ForMap(), filler_map);
3322 store_map->SetFlag(HValue::kHasNoObservableSideEffects);
3323 store_map->InsertAfter(filler_map);
3324
3325 // We must explicitly force Smi representation here because on x64 we
3326 // would otherwise automatically choose int32, but the actual store
3327 // requires a Smi-tagged value.
3328 HConstant* filler_size =
3329 HConstant::CreateAndInsertAfter(isolate, zone, context(), free_space_size,
3330 Representation::Smi(), store_map);
3331 // Must force Smi representation for x64 (see comment above).
3332 HObjectAccess access = HObjectAccess::ForMapAndOffset(
3333 isolate->factory()->free_space_map(), FreeSpace::kSizeOffset,
3334 Representation::Smi());
3335 HStoreNamedField* store_size = HStoreNamedField::New(
3336 isolate, zone, context(), free_space_instr, access, filler_size);
3337 store_size->SetFlag(HValue::kHasNoObservableSideEffects);
3338 store_size->InsertAfter(filler_size);
3339 filler_free_space_size_ = store_size;
3340}
3341
3342
3343void HAllocate::ClearNextMapWord(int offset) {
3344 if (MustClearNextMapWord()) {
3345 Zone* zone = block()->zone();
3346 HObjectAccess access =
3347 HObjectAccess::ForObservableJSObjectOffset(offset);
3348 HStoreNamedField* clear_next_map =
3349 HStoreNamedField::New(block()->isolate(), zone, context(), this, access,
3350 block()->graph()->GetConstant0());
3351 clear_next_map->ClearAllSideEffects();
3352 clear_next_map->InsertAfter(this);
3353 }
3354}
3355
3356
3357std::ostream& HAllocate::PrintDataTo(std::ostream& os) const { // NOLINT
3358 os << NameOf(size()) << " (";
3359 if (IsNewSpaceAllocation()) os << "N";
3360 if (IsOldSpaceAllocation()) os << "P";
3361 if (MustAllocateDoubleAligned()) os << "A";
3362 if (MustPrefillWithFiller()) os << "F";
3363 return os << ")";
3364}
3365
3366
3367bool HStoreKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
3368 // The base offset is usually simply the size of the array header, except
3369 // with dehoisting adds an addition offset due to a array index key
3370 // manipulation, in which case it becomes (array header size +
3371 // constant-offset-from-key * kPointerSize)
3372 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset_;
3373 addition_result += increase_by_value;
3374 if (!addition_result.IsValid()) return false;
3375 base_offset_ = addition_result.ValueOrDie();
3376 return true;
3377}
3378
3379
3380bool HStoreKeyed::NeedsCanonicalization() {
3381 switch (value()->opcode()) {
3382 case kLoadKeyed: {
3383 ElementsKind load_kind = HLoadKeyed::cast(value())->elements_kind();
3384 return IsFixedFloatElementsKind(load_kind);
3385 }
3386 case kChange: {
3387 Representation from = HChange::cast(value())->from();
3388 return from.IsTagged() || from.IsHeapObject();
3389 }
3390 case kLoadNamedField:
3391 case kPhi: {
3392 // Better safe than sorry...
3393 return true;
3394 }
3395 default:
3396 return false;
3397 }
3398}
3399
3400
3401#define H_CONSTANT_INT(val) \
3402 HConstant::New(isolate, zone, context, static_cast<int32_t>(val))
3403#define H_CONSTANT_DOUBLE(val) \
3404 HConstant::New(isolate, zone, context, static_cast<double>(val))
3405
Ben Murdoch097c5b22016-05-18 11:27:45 +01003406#define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op) \
3407 HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context, \
3408 HValue* left, HValue* right) { \
3409 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
3410 HConstant* c_left = HConstant::cast(left); \
3411 HConstant* c_right = HConstant::cast(right); \
3412 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
3413 double double_res = c_left->DoubleValue() op c_right->DoubleValue(); \
3414 if (IsInt32Double(double_res)) { \
3415 return H_CONSTANT_INT(double_res); \
3416 } \
3417 return H_CONSTANT_DOUBLE(double_res); \
3418 } \
3419 } \
3420 return new (zone) HInstr(context, left, right); \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003421 }
3422
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003423DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HAdd, +)
3424DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HMul, *)
3425DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HSub, -)
3426
3427#undef DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR
3428
3429
3430HInstruction* HStringAdd::New(Isolate* isolate, Zone* zone, HValue* context,
3431 HValue* left, HValue* right,
3432 PretenureFlag pretenure_flag,
3433 StringAddFlags flags,
3434 Handle<AllocationSite> allocation_site) {
3435 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3436 HConstant* c_right = HConstant::cast(right);
3437 HConstant* c_left = HConstant::cast(left);
3438 if (c_left->HasStringValue() && c_right->HasStringValue()) {
3439 Handle<String> left_string = c_left->StringValue();
3440 Handle<String> right_string = c_right->StringValue();
3441 // Prevent possible exception by invalid string length.
3442 if (left_string->length() + right_string->length() < String::kMaxLength) {
3443 MaybeHandle<String> concat = isolate->factory()->NewConsString(
3444 c_left->StringValue(), c_right->StringValue());
3445 return HConstant::New(isolate, zone, context, concat.ToHandleChecked());
3446 }
3447 }
3448 }
3449 return new (zone)
3450 HStringAdd(context, left, right, pretenure_flag, flags, allocation_site);
3451}
3452
3453
3454std::ostream& HStringAdd::PrintDataTo(std::ostream& os) const { // NOLINT
3455 if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
3456 os << "_CheckBoth";
3457 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_LEFT) {
3458 os << "_CheckLeft";
3459 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_RIGHT) {
3460 os << "_CheckRight";
3461 }
3462 HBinaryOperation::PrintDataTo(os);
3463 os << " (";
3464 if (pretenure_flag() == NOT_TENURED)
3465 os << "N";
3466 else if (pretenure_flag() == TENURED)
3467 os << "D";
3468 return os << ")";
3469}
3470
3471
3472HInstruction* HStringCharFromCode::New(Isolate* isolate, Zone* zone,
3473 HValue* context, HValue* char_code) {
3474 if (FLAG_fold_constants && char_code->IsConstant()) {
3475 HConstant* c_code = HConstant::cast(char_code);
3476 if (c_code->HasNumberValue()) {
3477 if (std::isfinite(c_code->DoubleValue())) {
3478 uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
3479 return HConstant::New(
3480 isolate, zone, context,
3481 isolate->factory()->LookupSingleCharacterStringFromCode(code));
3482 }
3483 return HConstant::New(isolate, zone, context,
3484 isolate->factory()->empty_string());
3485 }
3486 }
3487 return new(zone) HStringCharFromCode(context, char_code);
3488}
3489
3490
3491HInstruction* HUnaryMathOperation::New(Isolate* isolate, Zone* zone,
3492 HValue* context, HValue* value,
3493 BuiltinFunctionId op) {
3494 do {
3495 if (!FLAG_fold_constants) break;
3496 if (!value->IsConstant()) break;
3497 HConstant* constant = HConstant::cast(value);
3498 if (!constant->HasNumberValue()) break;
3499 double d = constant->DoubleValue();
3500 if (std::isnan(d)) { // NaN poisons everything.
3501 return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3502 }
3503 if (std::isinf(d)) { // +Infinity and -Infinity.
3504 switch (op) {
3505 case kMathExp:
3506 return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
3507 case kMathLog:
3508 case kMathSqrt:
3509 return H_CONSTANT_DOUBLE(
3510 (d > 0.0) ? d : std::numeric_limits<double>::quiet_NaN());
3511 case kMathPowHalf:
3512 case kMathAbs:
3513 return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
3514 case kMathRound:
3515 case kMathFround:
3516 case kMathFloor:
3517 return H_CONSTANT_DOUBLE(d);
3518 case kMathClz32:
3519 return H_CONSTANT_INT(32);
3520 default:
3521 UNREACHABLE();
3522 break;
3523 }
3524 }
3525 switch (op) {
3526 case kMathExp:
3527 lazily_initialize_fast_exp(isolate);
3528 return H_CONSTANT_DOUBLE(fast_exp(d, isolate));
3529 case kMathLog:
3530 return H_CONSTANT_DOUBLE(std::log(d));
3531 case kMathSqrt:
3532 lazily_initialize_fast_sqrt(isolate);
3533 return H_CONSTANT_DOUBLE(fast_sqrt(d, isolate));
3534 case kMathPowHalf:
3535 return H_CONSTANT_DOUBLE(power_double_double(d, 0.5));
3536 case kMathAbs:
3537 return H_CONSTANT_DOUBLE((d >= 0.0) ? d + 0.0 : -d);
3538 case kMathRound:
3539 // -0.5 .. -0.0 round to -0.0.
3540 if ((d >= -0.5 && Double(d).Sign() < 0)) return H_CONSTANT_DOUBLE(-0.0);
3541 // Doubles are represented as Significant * 2 ^ Exponent. If the
3542 // Exponent is not negative, the double value is already an integer.
3543 if (Double(d).Exponent() >= 0) return H_CONSTANT_DOUBLE(d);
3544 return H_CONSTANT_DOUBLE(Floor(d + 0.5));
3545 case kMathFround:
3546 return H_CONSTANT_DOUBLE(static_cast<double>(static_cast<float>(d)));
3547 case kMathFloor:
3548 return H_CONSTANT_DOUBLE(Floor(d));
3549 case kMathClz32: {
3550 uint32_t i = DoubleToUint32(d);
3551 return H_CONSTANT_INT(base::bits::CountLeadingZeros32(i));
3552 }
3553 default:
3554 UNREACHABLE();
3555 break;
3556 }
3557 } while (false);
3558 return new(zone) HUnaryMathOperation(context, value, op);
3559}
3560
3561
3562Representation HUnaryMathOperation::RepresentationFromUses() {
3563 if (op_ != kMathFloor && op_ != kMathRound) {
3564 return HValue::RepresentationFromUses();
3565 }
3566
3567 // The instruction can have an int32 or double output. Prefer a double
3568 // representation if there are double uses.
3569 bool use_double = false;
3570
3571 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3572 HValue* use = it.value();
3573 int use_index = it.index();
3574 Representation rep_observed = use->observed_input_representation(use_index);
3575 Representation rep_required = use->RequiredInputRepresentation(use_index);
3576 use_double |= (rep_observed.IsDouble() || rep_required.IsDouble());
3577 if (use_double && !FLAG_trace_representation) {
3578 // Having seen one double is enough.
3579 break;
3580 }
3581 if (FLAG_trace_representation) {
3582 if (!rep_required.IsDouble() || rep_observed.IsDouble()) {
3583 PrintF("#%d %s is used by #%d %s as %s%s\n",
3584 id(), Mnemonic(), use->id(),
3585 use->Mnemonic(), rep_observed.Mnemonic(),
3586 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
3587 } else {
3588 PrintF("#%d %s is required by #%d %s as %s%s\n",
3589 id(), Mnemonic(), use->id(),
3590 use->Mnemonic(), rep_required.Mnemonic(),
3591 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
3592 }
3593 }
3594 }
3595 return use_double ? Representation::Double() : Representation::Integer32();
3596}
3597
3598
3599HInstruction* HPower::New(Isolate* isolate, Zone* zone, HValue* context,
3600 HValue* left, HValue* right) {
3601 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3602 HConstant* c_left = HConstant::cast(left);
3603 HConstant* c_right = HConstant::cast(right);
3604 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
3605 double result =
3606 power_helper(isolate, c_left->DoubleValue(), c_right->DoubleValue());
3607 return H_CONSTANT_DOUBLE(std::isnan(result)
3608 ? std::numeric_limits<double>::quiet_NaN()
3609 : result);
3610 }
3611 }
3612 return new(zone) HPower(left, right);
3613}
3614
3615
3616HInstruction* HMathMinMax::New(Isolate* isolate, Zone* zone, HValue* context,
3617 HValue* left, HValue* right, Operation op) {
3618 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3619 HConstant* c_left = HConstant::cast(left);
3620 HConstant* c_right = HConstant::cast(right);
3621 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
3622 double d_left = c_left->DoubleValue();
3623 double d_right = c_right->DoubleValue();
3624 if (op == kMathMin) {
3625 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_right);
3626 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_left);
3627 if (d_left == d_right) {
3628 // Handle +0 and -0.
3629 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_left
3630 : d_right);
3631 }
3632 } else {
3633 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_right);
3634 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_left);
3635 if (d_left == d_right) {
3636 // Handle +0 and -0.
3637 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_right
3638 : d_left);
3639 }
3640 }
3641 // All comparisons failed, must be NaN.
3642 return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
3643 }
3644 }
3645 return new(zone) HMathMinMax(context, left, right, op);
3646}
3647
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003648HInstruction* HMod::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01003649 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003650 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3651 HConstant* c_left = HConstant::cast(left);
3652 HConstant* c_right = HConstant::cast(right);
3653 if (c_left->HasInteger32Value() && c_right->HasInteger32Value()) {
3654 int32_t dividend = c_left->Integer32Value();
3655 int32_t divisor = c_right->Integer32Value();
3656 if (dividend == kMinInt && divisor == -1) {
3657 return H_CONSTANT_DOUBLE(-0.0);
3658 }
3659 if (divisor != 0) {
3660 int32_t res = dividend % divisor;
3661 if ((res == 0) && (dividend < 0)) {
3662 return H_CONSTANT_DOUBLE(-0.0);
3663 }
3664 return H_CONSTANT_INT(res);
3665 }
3666 }
3667 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01003668 return new (zone) HMod(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003669}
3670
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003671HInstruction* HDiv::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01003672 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003673 // If left and right are constant values, try to return a constant value.
3674 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3675 HConstant* c_left = HConstant::cast(left);
3676 HConstant* c_right = HConstant::cast(right);
3677 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
3678 if (c_right->DoubleValue() != 0) {
3679 double double_res = c_left->DoubleValue() / c_right->DoubleValue();
3680 if (IsInt32Double(double_res)) {
3681 return H_CONSTANT_INT(double_res);
3682 }
3683 return H_CONSTANT_DOUBLE(double_res);
3684 } else {
3685 int sign = Double(c_left->DoubleValue()).Sign() *
3686 Double(c_right->DoubleValue()).Sign(); // Right could be -0.
3687 return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
3688 }
3689 }
3690 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01003691 return new (zone) HDiv(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003692}
3693
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003694HInstruction* HBitwise::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01003695 Token::Value op, HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003696 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3697 HConstant* c_left = HConstant::cast(left);
3698 HConstant* c_right = HConstant::cast(right);
3699 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
3700 int32_t result;
3701 int32_t v_left = c_left->NumberValueAsInteger32();
3702 int32_t v_right = c_right->NumberValueAsInteger32();
3703 switch (op) {
3704 case Token::BIT_XOR:
3705 result = v_left ^ v_right;
3706 break;
3707 case Token::BIT_AND:
3708 result = v_left & v_right;
3709 break;
3710 case Token::BIT_OR:
3711 result = v_left | v_right;
3712 break;
3713 default:
3714 result = 0; // Please the compiler.
3715 UNREACHABLE();
3716 }
3717 return H_CONSTANT_INT(result);
3718 }
3719 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01003720 return new (zone) HBitwise(context, op, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003721}
3722
Ben Murdoch097c5b22016-05-18 11:27:45 +01003723#define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result) \
3724 HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context, \
3725 HValue* left, HValue* right) { \
3726 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
3727 HConstant* c_left = HConstant::cast(left); \
3728 HConstant* c_right = HConstant::cast(right); \
3729 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
3730 return H_CONSTANT_INT(result); \
3731 } \
3732 } \
3733 return new (zone) HInstr(context, left, right); \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003734 }
3735
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003736DEFINE_NEW_H_BITWISE_INSTR(HSar,
3737c_left->NumberValueAsInteger32() >> (c_right->NumberValueAsInteger32() & 0x1f))
3738DEFINE_NEW_H_BITWISE_INSTR(HShl,
3739c_left->NumberValueAsInteger32() << (c_right->NumberValueAsInteger32() & 0x1f))
3740
3741#undef DEFINE_NEW_H_BITWISE_INSTR
3742
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003743HInstruction* HShr::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01003744 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003745 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3746 HConstant* c_left = HConstant::cast(left);
3747 HConstant* c_right = HConstant::cast(right);
3748 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
3749 int32_t left_val = c_left->NumberValueAsInteger32();
3750 int32_t right_val = c_right->NumberValueAsInteger32() & 0x1f;
3751 if ((right_val == 0) && (left_val < 0)) {
3752 return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
3753 }
3754 return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
3755 }
3756 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01003757 return new (zone) HShr(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003758}
3759
3760
3761HInstruction* HSeqStringGetChar::New(Isolate* isolate, Zone* zone,
3762 HValue* context, String::Encoding encoding,
3763 HValue* string, HValue* index) {
3764 if (FLAG_fold_constants && string->IsConstant() && index->IsConstant()) {
3765 HConstant* c_string = HConstant::cast(string);
3766 HConstant* c_index = HConstant::cast(index);
3767 if (c_string->HasStringValue() && c_index->HasInteger32Value()) {
3768 Handle<String> s = c_string->StringValue();
3769 int32_t i = c_index->Integer32Value();
3770 DCHECK_LE(0, i);
3771 DCHECK_LT(i, s->length());
3772 return H_CONSTANT_INT(s->Get(i));
3773 }
3774 }
3775 return new(zone) HSeqStringGetChar(encoding, string, index);
3776}
3777
3778
3779#undef H_CONSTANT_INT
3780#undef H_CONSTANT_DOUBLE
3781
3782
3783std::ostream& HBitwise::PrintDataTo(std::ostream& os) const { // NOLINT
3784 os << Token::Name(op_) << " ";
3785 return HBitwiseBinaryOperation::PrintDataTo(os);
3786}
3787
3788
3789void HPhi::SimplifyConstantInputs() {
3790 // Convert constant inputs to integers when all uses are truncating.
3791 // This must happen before representation inference takes place.
3792 if (!CheckUsesForFlag(kTruncatingToInt32)) return;
3793 for (int i = 0; i < OperandCount(); ++i) {
3794 if (!OperandAt(i)->IsConstant()) return;
3795 }
3796 HGraph* graph = block()->graph();
3797 for (int i = 0; i < OperandCount(); ++i) {
3798 HConstant* operand = HConstant::cast(OperandAt(i));
3799 if (operand->HasInteger32Value()) {
3800 continue;
3801 } else if (operand->HasDoubleValue()) {
3802 HConstant* integer_input = HConstant::New(
3803 graph->isolate(), graph->zone(), graph->GetInvalidContext(),
3804 DoubleToInt32(operand->DoubleValue()));
3805 integer_input->InsertAfter(operand);
3806 SetOperandAt(i, integer_input);
3807 } else if (operand->HasBooleanValue()) {
3808 SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
3809 : graph->GetConstant0());
3810 } else if (operand->ImmortalImmovable()) {
3811 SetOperandAt(i, graph->GetConstant0());
3812 }
3813 }
3814 // Overwrite observed input representations because they are likely Tagged.
3815 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3816 HValue* use = it.value();
3817 if (use->IsBinaryOperation()) {
3818 HBinaryOperation::cast(use)->set_observed_input_representation(
3819 it.index(), Representation::Smi());
3820 }
3821 }
3822}
3823
3824
3825void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
3826 DCHECK(CheckFlag(kFlexibleRepresentation));
3827 Representation new_rep = RepresentationFromUses();
3828 UpdateRepresentation(new_rep, h_infer, "uses");
3829 new_rep = RepresentationFromInputs();
3830 UpdateRepresentation(new_rep, h_infer, "inputs");
3831 new_rep = RepresentationFromUseRequirements();
3832 UpdateRepresentation(new_rep, h_infer, "use requirements");
3833}
3834
3835
3836Representation HPhi::RepresentationFromInputs() {
3837 Representation r = representation();
3838 for (int i = 0; i < OperandCount(); ++i) {
3839 // Ignore conservative Tagged assumption of parameters if we have
3840 // reason to believe that it's too conservative.
3841 if (has_type_feedback_from_uses() && OperandAt(i)->IsParameter()) {
3842 continue;
3843 }
3844
3845 r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
3846 }
3847 return r;
3848}
3849
3850
3851// Returns a representation if all uses agree on the same representation.
3852// Integer32 is also returned when some uses are Smi but others are Integer32.
3853Representation HValue::RepresentationFromUseRequirements() {
3854 Representation rep = Representation::None();
3855 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3856 // Ignore the use requirement from never run code
3857 if (it.value()->block()->IsUnreachable()) continue;
3858
3859 // We check for observed_input_representation elsewhere.
3860 Representation use_rep =
3861 it.value()->RequiredInputRepresentation(it.index());
3862 if (rep.IsNone()) {
3863 rep = use_rep;
3864 continue;
3865 }
3866 if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
3867 if (rep.generalize(use_rep).IsInteger32()) {
3868 rep = Representation::Integer32();
3869 continue;
3870 }
3871 return Representation::None();
3872 }
3873 return rep;
3874}
3875
3876
3877bool HValue::HasNonSmiUse() {
3878 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3879 // We check for observed_input_representation elsewhere.
3880 Representation use_rep =
3881 it.value()->RequiredInputRepresentation(it.index());
3882 if (!use_rep.IsNone() &&
3883 !use_rep.IsSmi() &&
3884 !use_rep.IsTagged()) {
3885 return true;
3886 }
3887 }
3888 return false;
3889}
3890
3891
3892// Node-specific verification code is only included in debug mode.
3893#ifdef DEBUG
3894
3895void HPhi::Verify() {
3896 DCHECK(OperandCount() == block()->predecessors()->length());
3897 for (int i = 0; i < OperandCount(); ++i) {
3898 HValue* value = OperandAt(i);
3899 HBasicBlock* defining_block = value->block();
3900 HBasicBlock* predecessor_block = block()->predecessors()->at(i);
3901 DCHECK(defining_block == predecessor_block ||
3902 defining_block->Dominates(predecessor_block));
3903 }
3904}
3905
3906
3907void HSimulate::Verify() {
3908 HInstruction::Verify();
3909 DCHECK(HasAstId() || next()->IsEnterInlined());
3910}
3911
3912
3913void HCheckHeapObject::Verify() {
3914 HInstruction::Verify();
3915 DCHECK(HasNoUses());
3916}
3917
3918
3919void HCheckValue::Verify() {
3920 HInstruction::Verify();
3921 DCHECK(HasNoUses());
3922}
3923
3924#endif
3925
3926
3927HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
3928 DCHECK(offset >= 0);
3929 DCHECK(offset < FixedArray::kHeaderSize);
3930 if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
3931 return HObjectAccess(kInobject, offset);
3932}
3933
3934
3935HObjectAccess HObjectAccess::ForMapAndOffset(Handle<Map> map, int offset,
3936 Representation representation) {
3937 DCHECK(offset >= 0);
3938 Portion portion = kInobject;
3939
3940 if (offset == JSObject::kElementsOffset) {
3941 portion = kElementsPointer;
3942 } else if (offset == JSObject::kMapOffset) {
3943 portion = kMaps;
3944 }
3945 bool existing_inobject_property = true;
3946 if (!map.is_null()) {
3947 existing_inobject_property = (offset <
3948 map->instance_size() - map->unused_property_fields() * kPointerSize);
3949 }
3950 return HObjectAccess(portion, offset, representation, Handle<String>::null(),
3951 false, existing_inobject_property);
3952}
3953
3954
3955HObjectAccess HObjectAccess::ForAllocationSiteOffset(int offset) {
3956 switch (offset) {
3957 case AllocationSite::kTransitionInfoOffset:
3958 return HObjectAccess(kInobject, offset, Representation::Tagged());
3959 case AllocationSite::kNestedSiteOffset:
3960 return HObjectAccess(kInobject, offset, Representation::Tagged());
3961 case AllocationSite::kPretenureDataOffset:
3962 return HObjectAccess(kInobject, offset, Representation::Smi());
3963 case AllocationSite::kPretenureCreateCountOffset:
3964 return HObjectAccess(kInobject, offset, Representation::Smi());
3965 case AllocationSite::kDependentCodeOffset:
3966 return HObjectAccess(kInobject, offset, Representation::Tagged());
3967 case AllocationSite::kWeakNextOffset:
3968 return HObjectAccess(kInobject, offset, Representation::Tagged());
3969 default:
3970 UNREACHABLE();
3971 }
3972 return HObjectAccess(kInobject, offset);
3973}
3974
3975
3976HObjectAccess HObjectAccess::ForContextSlot(int index) {
3977 DCHECK(index >= 0);
3978 Portion portion = kInobject;
3979 int offset = Context::kHeaderSize + index * kPointerSize;
3980 DCHECK_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
3981 return HObjectAccess(portion, offset, Representation::Tagged());
3982}
3983
3984
3985HObjectAccess HObjectAccess::ForScriptContext(int index) {
3986 DCHECK(index >= 0);
3987 Portion portion = kInobject;
3988 int offset = ScriptContextTable::GetContextOffset(index);
3989 return HObjectAccess(portion, offset, Representation::Tagged());
3990}
3991
3992
3993HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
3994 DCHECK(offset >= 0);
3995 Portion portion = kInobject;
3996
3997 if (offset == JSObject::kElementsOffset) {
3998 portion = kElementsPointer;
3999 } else if (offset == JSArray::kLengthOffset) {
4000 portion = kArrayLengths;
4001 } else if (offset == JSObject::kMapOffset) {
4002 portion = kMaps;
4003 }
4004 return HObjectAccess(portion, offset);
4005}
4006
4007
4008HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
4009 Representation representation) {
4010 DCHECK(offset >= 0);
4011 return HObjectAccess(kBackingStore, offset, representation,
4012 Handle<String>::null(), false, false);
4013}
4014
4015
4016HObjectAccess HObjectAccess::ForField(Handle<Map> map, int index,
4017 Representation representation,
4018 Handle<Name> name) {
4019 if (index < 0) {
4020 // Negative property indices are in-object properties, indexed
4021 // from the end of the fixed part of the object.
4022 int offset = (index * kPointerSize) + map->instance_size();
4023 return HObjectAccess(kInobject, offset, representation, name, false, true);
4024 } else {
4025 // Non-negative property indices are in the properties array.
4026 int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
4027 return HObjectAccess(kBackingStore, offset, representation, name,
4028 false, false);
4029 }
4030}
4031
4032
4033void HObjectAccess::SetGVNFlags(HValue *instr, PropertyAccessType access_type) {
4034 // set the appropriate GVN flags for a given load or store instruction
4035 if (access_type == STORE) {
4036 // track dominating allocations in order to eliminate write barriers
4037 instr->SetDependsOnFlag(::v8::internal::kNewSpacePromotion);
4038 instr->SetFlag(HValue::kTrackSideEffectDominators);
4039 } else {
4040 // try to GVN loads, but don't hoist above map changes
4041 instr->SetFlag(HValue::kUseGVN);
4042 instr->SetDependsOnFlag(::v8::internal::kMaps);
4043 }
4044
4045 switch (portion()) {
4046 case kArrayLengths:
4047 if (access_type == STORE) {
4048 instr->SetChangesFlag(::v8::internal::kArrayLengths);
4049 } else {
4050 instr->SetDependsOnFlag(::v8::internal::kArrayLengths);
4051 }
4052 break;
4053 case kStringLengths:
4054 if (access_type == STORE) {
4055 instr->SetChangesFlag(::v8::internal::kStringLengths);
4056 } else {
4057 instr->SetDependsOnFlag(::v8::internal::kStringLengths);
4058 }
4059 break;
4060 case kInobject:
4061 if (access_type == STORE) {
4062 instr->SetChangesFlag(::v8::internal::kInobjectFields);
4063 } else {
4064 instr->SetDependsOnFlag(::v8::internal::kInobjectFields);
4065 }
4066 break;
4067 case kDouble:
4068 if (access_type == STORE) {
4069 instr->SetChangesFlag(::v8::internal::kDoubleFields);
4070 } else {
4071 instr->SetDependsOnFlag(::v8::internal::kDoubleFields);
4072 }
4073 break;
4074 case kBackingStore:
4075 if (access_type == STORE) {
4076 instr->SetChangesFlag(::v8::internal::kBackingStoreFields);
4077 } else {
4078 instr->SetDependsOnFlag(::v8::internal::kBackingStoreFields);
4079 }
4080 break;
4081 case kElementsPointer:
4082 if (access_type == STORE) {
4083 instr->SetChangesFlag(::v8::internal::kElementsPointer);
4084 } else {
4085 instr->SetDependsOnFlag(::v8::internal::kElementsPointer);
4086 }
4087 break;
4088 case kMaps:
4089 if (access_type == STORE) {
4090 instr->SetChangesFlag(::v8::internal::kMaps);
4091 } else {
4092 instr->SetDependsOnFlag(::v8::internal::kMaps);
4093 }
4094 break;
4095 case kExternalMemory:
4096 if (access_type == STORE) {
4097 instr->SetChangesFlag(::v8::internal::kExternalMemory);
4098 } else {
4099 instr->SetDependsOnFlag(::v8::internal::kExternalMemory);
4100 }
4101 break;
4102 }
4103}
4104
4105
4106std::ostream& operator<<(std::ostream& os, const HObjectAccess& access) {
4107 os << ".";
4108
4109 switch (access.portion()) {
4110 case HObjectAccess::kArrayLengths:
4111 case HObjectAccess::kStringLengths:
4112 os << "%length";
4113 break;
4114 case HObjectAccess::kElementsPointer:
4115 os << "%elements";
4116 break;
4117 case HObjectAccess::kMaps:
4118 os << "%map";
4119 break;
4120 case HObjectAccess::kDouble: // fall through
4121 case HObjectAccess::kInobject:
4122 if (!access.name().is_null() && access.name()->IsString()) {
4123 os << Handle<String>::cast(access.name())->ToCString().get();
4124 }
4125 os << "[in-object]";
4126 break;
4127 case HObjectAccess::kBackingStore:
4128 if (!access.name().is_null() && access.name()->IsString()) {
4129 os << Handle<String>::cast(access.name())->ToCString().get();
4130 }
4131 os << "[backing-store]";
4132 break;
4133 case HObjectAccess::kExternalMemory:
4134 os << "[external-memory]";
4135 break;
4136 }
4137
4138 return os << "@" << access.offset();
4139}
4140
4141} // namespace internal
4142} // namespace v8