Reland of "Remove ExternalArray, derived types, and element kinds"
[platform/upstream/v8.git] / src / hydrogen.cc
1 // Copyright 2013 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/hydrogen.h"
6
7 #include <sstream>
8
9 #include "src/v8.h"
10
11 #include "src/allocation-site-scopes.h"
12 #include "src/ast-numbering.h"
13 #include "src/full-codegen/full-codegen.h"
14 #include "src/hydrogen-bce.h"
15 #include "src/hydrogen-bch.h"
16 #include "src/hydrogen-canonicalize.h"
17 #include "src/hydrogen-check-elimination.h"
18 #include "src/hydrogen-dce.h"
19 #include "src/hydrogen-dehoist.h"
20 #include "src/hydrogen-environment-liveness.h"
21 #include "src/hydrogen-escape-analysis.h"
22 #include "src/hydrogen-gvn.h"
23 #include "src/hydrogen-infer-representation.h"
24 #include "src/hydrogen-infer-types.h"
25 #include "src/hydrogen-load-elimination.h"
26 #include "src/hydrogen-mark-deoptimize.h"
27 #include "src/hydrogen-mark-unreachable.h"
28 #include "src/hydrogen-osr.h"
29 #include "src/hydrogen-range-analysis.h"
30 #include "src/hydrogen-redundant-phi.h"
31 #include "src/hydrogen-removable-simulates.h"
32 #include "src/hydrogen-representation-changes.h"
33 #include "src/hydrogen-sce.h"
34 #include "src/hydrogen-store-elimination.h"
35 #include "src/hydrogen-uint32-analysis.h"
36 #include "src/ic/call-optimization.h"
37 #include "src/ic/ic.h"
38 // GetRootConstructor
39 #include "src/ic/ic-inl.h"
40 #include "src/lithium-allocator.h"
41 #include "src/parser.h"
42 #include "src/runtime/runtime.h"
43 #include "src/scopeinfo.h"
44 #include "src/typing.h"
45
46 #if V8_TARGET_ARCH_IA32
47 #include "src/ia32/lithium-codegen-ia32.h"  // NOLINT
48 #elif V8_TARGET_ARCH_X64
49 #include "src/x64/lithium-codegen-x64.h"  // NOLINT
50 #elif V8_TARGET_ARCH_ARM64
51 #include "src/arm64/lithium-codegen-arm64.h"  // NOLINT
52 #elif V8_TARGET_ARCH_ARM
53 #include "src/arm/lithium-codegen-arm.h"  // NOLINT
54 #elif V8_TARGET_ARCH_PPC
55 #include "src/ppc/lithium-codegen-ppc.h"  // NOLINT
56 #elif V8_TARGET_ARCH_MIPS
57 #include "src/mips/lithium-codegen-mips.h"  // NOLINT
58 #elif V8_TARGET_ARCH_MIPS64
59 #include "src/mips64/lithium-codegen-mips64.h"  // NOLINT
60 #elif V8_TARGET_ARCH_X87
61 #include "src/x87/lithium-codegen-x87.h"  // NOLINT
62 #else
63 #error Unsupported target architecture.
64 #endif
65
66 namespace v8 {
67 namespace internal {
68
69 HBasicBlock::HBasicBlock(HGraph* graph)
70     : block_id_(graph->GetNextBlockID()),
71       graph_(graph),
72       phis_(4, graph->zone()),
73       first_(NULL),
74       last_(NULL),
75       end_(NULL),
76       loop_information_(NULL),
77       predecessors_(2, graph->zone()),
78       dominator_(NULL),
79       dominated_blocks_(4, graph->zone()),
80       last_environment_(NULL),
81       argument_count_(-1),
82       first_instruction_index_(-1),
83       last_instruction_index_(-1),
84       deleted_phis_(4, graph->zone()),
85       parent_loop_header_(NULL),
86       inlined_entry_block_(NULL),
87       is_inline_return_target_(false),
88       is_reachable_(true),
89       dominates_loop_successors_(false),
90       is_osr_entry_(false),
91       is_ordered_(false) { }
92
93
94 Isolate* HBasicBlock::isolate() const {
95   return graph_->isolate();
96 }
97
98
99 void HBasicBlock::MarkUnreachable() {
100   is_reachable_ = false;
101 }
102
103
104 void HBasicBlock::AttachLoopInformation() {
105   DCHECK(!IsLoopHeader());
106   loop_information_ = new(zone()) HLoopInformation(this, zone());
107 }
108
109
110 void HBasicBlock::DetachLoopInformation() {
111   DCHECK(IsLoopHeader());
112   loop_information_ = NULL;
113 }
114
115
116 void HBasicBlock::AddPhi(HPhi* phi) {
117   DCHECK(!IsStartBlock());
118   phis_.Add(phi, zone());
119   phi->SetBlock(this);
120 }
121
122
123 void HBasicBlock::RemovePhi(HPhi* phi) {
124   DCHECK(phi->block() == this);
125   DCHECK(phis_.Contains(phi));
126   phi->Kill();
127   phis_.RemoveElement(phi);
128   phi->SetBlock(NULL);
129 }
130
131
132 void HBasicBlock::AddInstruction(HInstruction* instr, SourcePosition position) {
133   DCHECK(!IsStartBlock() || !IsFinished());
134   DCHECK(!instr->IsLinked());
135   DCHECK(!IsFinished());
136
137   if (!position.IsUnknown()) {
138     instr->set_position(position);
139   }
140   if (first_ == NULL) {
141     DCHECK(last_environment() != NULL);
142     DCHECK(!last_environment()->ast_id().IsNone());
143     HBlockEntry* entry = new(zone()) HBlockEntry();
144     entry->InitializeAsFirst(this);
145     if (!position.IsUnknown()) {
146       entry->set_position(position);
147     } else {
148       DCHECK(!FLAG_hydrogen_track_positions ||
149              !graph()->info()->IsOptimizing() || instr->IsAbnormalExit());
150     }
151     first_ = last_ = entry;
152   }
153   instr->InsertAfter(last_);
154 }
155
156
157 HPhi* HBasicBlock::AddNewPhi(int merged_index) {
158   if (graph()->IsInsideNoSideEffectsScope()) {
159     merged_index = HPhi::kInvalidMergedIndex;
160   }
161   HPhi* phi = new(zone()) HPhi(merged_index, zone());
162   AddPhi(phi);
163   return phi;
164 }
165
166
167 HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id,
168                                        RemovableSimulate removable) {
169   DCHECK(HasEnvironment());
170   HEnvironment* environment = last_environment();
171   DCHECK(ast_id.IsNone() ||
172          ast_id == BailoutId::StubEntry() ||
173          environment->closure()->shared()->VerifyBailoutId(ast_id));
174
175   int push_count = environment->push_count();
176   int pop_count = environment->pop_count();
177
178   HSimulate* instr =
179       new(zone()) HSimulate(ast_id, pop_count, zone(), removable);
180 #ifdef DEBUG
181   instr->set_closure(environment->closure());
182 #endif
183   // Order of pushed values: newest (top of stack) first. This allows
184   // HSimulate::MergeWith() to easily append additional pushed values
185   // that are older (from further down the stack).
186   for (int i = 0; i < push_count; ++i) {
187     instr->AddPushedValue(environment->ExpressionStackAt(i));
188   }
189   for (GrowableBitVector::Iterator it(environment->assigned_variables(),
190                                       zone());
191        !it.Done();
192        it.Advance()) {
193     int index = it.Current();
194     instr->AddAssignedValue(index, environment->Lookup(index));
195   }
196   environment->ClearHistory();
197   return instr;
198 }
199
200
201 void HBasicBlock::Finish(HControlInstruction* end, SourcePosition position) {
202   DCHECK(!IsFinished());
203   AddInstruction(end, position);
204   end_ = end;
205   for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
206     it.Current()->RegisterPredecessor(this);
207   }
208 }
209
210
211 void HBasicBlock::Goto(HBasicBlock* block, SourcePosition position,
212                        FunctionState* state, bool add_simulate) {
213   bool drop_extra = state != NULL &&
214       state->inlining_kind() == NORMAL_RETURN;
215
216   if (block->IsInlineReturnTarget()) {
217     HEnvironment* env = last_environment();
218     int argument_count = env->arguments_environment()->parameter_count();
219     AddInstruction(new(zone())
220                    HLeaveInlined(state->entry(), argument_count),
221                    position);
222     UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
223   }
224
225   if (add_simulate) AddNewSimulate(BailoutId::None(), position);
226   HGoto* instr = new(zone()) HGoto(block);
227   Finish(instr, position);
228 }
229
230
231 void HBasicBlock::AddLeaveInlined(HValue* return_value, FunctionState* state,
232                                   SourcePosition position) {
233   HBasicBlock* target = state->function_return();
234   bool drop_extra = state->inlining_kind() == NORMAL_RETURN;
235
236   DCHECK(target->IsInlineReturnTarget());
237   DCHECK(return_value != NULL);
238   HEnvironment* env = last_environment();
239   int argument_count = env->arguments_environment()->parameter_count();
240   AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count),
241                  position);
242   UpdateEnvironment(last_environment()->DiscardInlined(drop_extra));
243   last_environment()->Push(return_value);
244   AddNewSimulate(BailoutId::None(), position);
245   HGoto* instr = new(zone()) HGoto(target);
246   Finish(instr, position);
247 }
248
249
250 void HBasicBlock::SetInitialEnvironment(HEnvironment* env) {
251   DCHECK(!HasEnvironment());
252   DCHECK(first() == NULL);
253   UpdateEnvironment(env);
254 }
255
256
257 void HBasicBlock::UpdateEnvironment(HEnvironment* env) {
258   last_environment_ = env;
259   graph()->update_maximum_environment_size(env->first_expression_index());
260 }
261
262
263 void HBasicBlock::SetJoinId(BailoutId ast_id) {
264   int length = predecessors_.length();
265   DCHECK(length > 0);
266   for (int i = 0; i < length; i++) {
267     HBasicBlock* predecessor = predecessors_[i];
268     DCHECK(predecessor->end()->IsGoto());
269     HSimulate* simulate = HSimulate::cast(predecessor->end()->previous());
270     DCHECK(i != 0 ||
271            (predecessor->last_environment()->closure().is_null() ||
272             predecessor->last_environment()->closure()->shared()
273               ->VerifyBailoutId(ast_id)));
274     simulate->set_ast_id(ast_id);
275     predecessor->last_environment()->set_ast_id(ast_id);
276   }
277 }
278
279
280 bool HBasicBlock::Dominates(HBasicBlock* other) const {
281   HBasicBlock* current = other->dominator();
282   while (current != NULL) {
283     if (current == this) return true;
284     current = current->dominator();
285   }
286   return false;
287 }
288
289
290 bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const {
291   if (this == other) return true;
292   return Dominates(other);
293 }
294
295
296 int HBasicBlock::LoopNestingDepth() const {
297   const HBasicBlock* current = this;
298   int result  = (current->IsLoopHeader()) ? 1 : 0;
299   while (current->parent_loop_header() != NULL) {
300     current = current->parent_loop_header();
301     result++;
302   }
303   return result;
304 }
305
306
307 void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) {
308   DCHECK(IsLoopHeader());
309
310   SetJoinId(stmt->EntryId());
311   if (predecessors()->length() == 1) {
312     // This is a degenerated loop.
313     DetachLoopInformation();
314     return;
315   }
316
317   // Only the first entry into the loop is from outside the loop. All other
318   // entries must be back edges.
319   for (int i = 1; i < predecessors()->length(); ++i) {
320     loop_information()->RegisterBackEdge(predecessors()->at(i));
321   }
322 }
323
324
325 void HBasicBlock::MarkSuccEdgeUnreachable(int succ) {
326   DCHECK(IsFinished());
327   HBasicBlock* succ_block = end()->SuccessorAt(succ);
328
329   DCHECK(succ_block->predecessors()->length() == 1);
330   succ_block->MarkUnreachable();
331 }
332
333
334 void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) {
335   if (HasPredecessor()) {
336     // Only loop header blocks can have a predecessor added after
337     // instructions have been added to the block (they have phis for all
338     // values in the environment, these phis may be eliminated later).
339     DCHECK(IsLoopHeader() || first_ == NULL);
340     HEnvironment* incoming_env = pred->last_environment();
341     if (IsLoopHeader()) {
342       DCHECK_EQ(phis()->length(), incoming_env->length());
343       for (int i = 0; i < phis_.length(); ++i) {
344         phis_[i]->AddInput(incoming_env->values()->at(i));
345       }
346     } else {
347       last_environment()->AddIncomingEdge(this, pred->last_environment());
348     }
349   } else if (!HasEnvironment() && !IsFinished()) {
350     DCHECK(!IsLoopHeader());
351     SetInitialEnvironment(pred->last_environment()->Copy());
352   }
353
354   predecessors_.Add(pred, zone());
355 }
356
357
358 void HBasicBlock::AddDominatedBlock(HBasicBlock* block) {
359   DCHECK(!dominated_blocks_.Contains(block));
360   // Keep the list of dominated blocks sorted such that if there is two
361   // succeeding block in this list, the predecessor is before the successor.
362   int index = 0;
363   while (index < dominated_blocks_.length() &&
364          dominated_blocks_[index]->block_id() < block->block_id()) {
365     ++index;
366   }
367   dominated_blocks_.InsertAt(index, block, zone());
368 }
369
370
371 void HBasicBlock::AssignCommonDominator(HBasicBlock* other) {
372   if (dominator_ == NULL) {
373     dominator_ = other;
374     other->AddDominatedBlock(this);
375   } else if (other->dominator() != NULL) {
376     HBasicBlock* first = dominator_;
377     HBasicBlock* second = other;
378
379     while (first != second) {
380       if (first->block_id() > second->block_id()) {
381         first = first->dominator();
382       } else {
383         second = second->dominator();
384       }
385       DCHECK(first != NULL && second != NULL);
386     }
387
388     if (dominator_ != first) {
389       DCHECK(dominator_->dominated_blocks_.Contains(this));
390       dominator_->dominated_blocks_.RemoveElement(this);
391       dominator_ = first;
392       first->AddDominatedBlock(this);
393     }
394   }
395 }
396
397
398 void HBasicBlock::AssignLoopSuccessorDominators() {
399   // Mark blocks that dominate all subsequent reachable blocks inside their
400   // loop. Exploit the fact that blocks are sorted in reverse post order. When
401   // the loop is visited in increasing block id order, if the number of
402   // non-loop-exiting successor edges at the dominator_candidate block doesn't
403   // exceed the number of previously encountered predecessor edges, there is no
404   // path from the loop header to any block with higher id that doesn't go
405   // through the dominator_candidate block. In this case, the
406   // dominator_candidate block is guaranteed to dominate all blocks reachable
407   // from it with higher ids.
408   HBasicBlock* last = loop_information()->GetLastBackEdge();
409   int outstanding_successors = 1;  // one edge from the pre-header
410   // Header always dominates everything.
411   MarkAsLoopSuccessorDominator();
412   for (int j = block_id(); j <= last->block_id(); ++j) {
413     HBasicBlock* dominator_candidate = graph_->blocks()->at(j);
414     for (HPredecessorIterator it(dominator_candidate); !it.Done();
415          it.Advance()) {
416       HBasicBlock* predecessor = it.Current();
417       // Don't count back edges.
418       if (predecessor->block_id() < dominator_candidate->block_id()) {
419         outstanding_successors--;
420       }
421     }
422
423     // If more successors than predecessors have been seen in the loop up to
424     // now, it's not possible to guarantee that the current block dominates
425     // all of the blocks with higher IDs. In this case, assume conservatively
426     // that those paths through loop that don't go through the current block
427     // contain all of the loop's dependencies. Also be careful to record
428     // dominator information about the current loop that's being processed,
429     // and not nested loops, which will be processed when
430     // AssignLoopSuccessorDominators gets called on their header.
431     DCHECK(outstanding_successors >= 0);
432     HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header();
433     if (outstanding_successors == 0 &&
434         (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) {
435       dominator_candidate->MarkAsLoopSuccessorDominator();
436     }
437     HControlInstruction* end = dominator_candidate->end();
438     for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
439       HBasicBlock* successor = it.Current();
440       // Only count successors that remain inside the loop and don't loop back
441       // to a loop header.
442       if (successor->block_id() > dominator_candidate->block_id() &&
443           successor->block_id() <= last->block_id()) {
444         // Backwards edges must land on loop headers.
445         DCHECK(successor->block_id() > dominator_candidate->block_id() ||
446                successor->IsLoopHeader());
447         outstanding_successors++;
448       }
449     }
450   }
451 }
452
453
454 int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const {
455   for (int i = 0; i < predecessors_.length(); ++i) {
456     if (predecessors_[i] == predecessor) return i;
457   }
458   UNREACHABLE();
459   return -1;
460 }
461
462
463 #ifdef DEBUG
464 void HBasicBlock::Verify() {
465   // Check that every block is finished.
466   DCHECK(IsFinished());
467   DCHECK(block_id() >= 0);
468
469   // Check that the incoming edges are in edge split form.
470   if (predecessors_.length() > 1) {
471     for (int i = 0; i < predecessors_.length(); ++i) {
472       DCHECK(predecessors_[i]->end()->SecondSuccessor() == NULL);
473     }
474   }
475 }
476 #endif
477
478
479 void HLoopInformation::RegisterBackEdge(HBasicBlock* block) {
480   this->back_edges_.Add(block, block->zone());
481   AddBlock(block);
482 }
483
484
485 HBasicBlock* HLoopInformation::GetLastBackEdge() const {
486   int max_id = -1;
487   HBasicBlock* result = NULL;
488   for (int i = 0; i < back_edges_.length(); ++i) {
489     HBasicBlock* cur = back_edges_[i];
490     if (cur->block_id() > max_id) {
491       max_id = cur->block_id();
492       result = cur;
493     }
494   }
495   return result;
496 }
497
498
499 void HLoopInformation::AddBlock(HBasicBlock* block) {
500   if (block == loop_header()) return;
501   if (block->parent_loop_header() == loop_header()) return;
502   if (block->parent_loop_header() != NULL) {
503     AddBlock(block->parent_loop_header());
504   } else {
505     block->set_parent_loop_header(loop_header());
506     blocks_.Add(block, block->zone());
507     for (int i = 0; i < block->predecessors()->length(); ++i) {
508       AddBlock(block->predecessors()->at(i));
509     }
510   }
511 }
512
513
514 #ifdef DEBUG
515
516 // Checks reachability of the blocks in this graph and stores a bit in
517 // the BitVector "reachable()" for every block that can be reached
518 // from the start block of the graph. If "dont_visit" is non-null, the given
519 // block is treated as if it would not be part of the graph. "visited_count()"
520 // returns the number of reachable blocks.
521 class ReachabilityAnalyzer BASE_EMBEDDED {
522  public:
523   ReachabilityAnalyzer(HBasicBlock* entry_block,
524                        int block_count,
525                        HBasicBlock* dont_visit)
526       : visited_count_(0),
527         stack_(16, entry_block->zone()),
528         reachable_(block_count, entry_block->zone()),
529         dont_visit_(dont_visit) {
530     PushBlock(entry_block);
531     Analyze();
532   }
533
534   int visited_count() const { return visited_count_; }
535   const BitVector* reachable() const { return &reachable_; }
536
537  private:
538   void PushBlock(HBasicBlock* block) {
539     if (block != NULL && block != dont_visit_ &&
540         !reachable_.Contains(block->block_id())) {
541       reachable_.Add(block->block_id());
542       stack_.Add(block, block->zone());
543       visited_count_++;
544     }
545   }
546
547   void Analyze() {
548     while (!stack_.is_empty()) {
549       HControlInstruction* end = stack_.RemoveLast()->end();
550       for (HSuccessorIterator it(end); !it.Done(); it.Advance()) {
551         PushBlock(it.Current());
552       }
553     }
554   }
555
556   int visited_count_;
557   ZoneList<HBasicBlock*> stack_;
558   BitVector reachable_;
559   HBasicBlock* dont_visit_;
560 };
561
562
563 void HGraph::Verify(bool do_full_verify) const {
564   Heap::RelocationLock relocation_lock(isolate()->heap());
565   AllowHandleDereference allow_deref;
566   AllowDeferredHandleDereference allow_deferred_deref;
567   for (int i = 0; i < blocks_.length(); i++) {
568     HBasicBlock* block = blocks_.at(i);
569
570     block->Verify();
571
572     // Check that every block contains at least one node and that only the last
573     // node is a control instruction.
574     HInstruction* current = block->first();
575     DCHECK(current != NULL && current->IsBlockEntry());
576     while (current != NULL) {
577       DCHECK((current->next() == NULL) == current->IsControlInstruction());
578       DCHECK(current->block() == block);
579       current->Verify();
580       current = current->next();
581     }
582
583     // Check that successors are correctly set.
584     HBasicBlock* first = block->end()->FirstSuccessor();
585     HBasicBlock* second = block->end()->SecondSuccessor();
586     DCHECK(second == NULL || first != NULL);
587
588     // Check that the predecessor array is correct.
589     if (first != NULL) {
590       DCHECK(first->predecessors()->Contains(block));
591       if (second != NULL) {
592         DCHECK(second->predecessors()->Contains(block));
593       }
594     }
595
596     // Check that phis have correct arguments.
597     for (int j = 0; j < block->phis()->length(); j++) {
598       HPhi* phi = block->phis()->at(j);
599       phi->Verify();
600     }
601
602     // Check that all join blocks have predecessors that end with an
603     // unconditional goto and agree on their environment node id.
604     if (block->predecessors()->length() >= 2) {
605       BailoutId id =
606           block->predecessors()->first()->last_environment()->ast_id();
607       for (int k = 0; k < block->predecessors()->length(); k++) {
608         HBasicBlock* predecessor = block->predecessors()->at(k);
609         DCHECK(predecessor->end()->IsGoto() ||
610                predecessor->end()->IsDeoptimize());
611         DCHECK(predecessor->last_environment()->ast_id() == id);
612       }
613     }
614   }
615
616   // Check special property of first block to have no predecessors.
617   DCHECK(blocks_.at(0)->predecessors()->is_empty());
618
619   if (do_full_verify) {
620     // Check that the graph is fully connected.
621     ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL);
622     DCHECK(analyzer.visited_count() == blocks_.length());
623
624     // Check that entry block dominator is NULL.
625     DCHECK(entry_block_->dominator() == NULL);
626
627     // Check dominators.
628     for (int i = 0; i < blocks_.length(); ++i) {
629       HBasicBlock* block = blocks_.at(i);
630       if (block->dominator() == NULL) {
631         // Only start block may have no dominator assigned to.
632         DCHECK(i == 0);
633       } else {
634         // Assert that block is unreachable if dominator must not be visited.
635         ReachabilityAnalyzer dominator_analyzer(entry_block_,
636                                                 blocks_.length(),
637                                                 block->dominator());
638         DCHECK(!dominator_analyzer.reachable()->Contains(block->block_id()));
639       }
640     }
641   }
642 }
643
644 #endif
645
646
647 HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer,
648                                int32_t value) {
649   if (!pointer->is_set()) {
650     // Can't pass GetInvalidContext() to HConstant::New, because that will
651     // recursively call GetConstant
652     HConstant* constant = HConstant::New(isolate(), zone(), NULL, value);
653     constant->InsertAfter(entry_block()->first());
654     pointer->set(constant);
655     return constant;
656   }
657   return ReinsertConstantIfNecessary(pointer->get());
658 }
659
660
661 HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) {
662   if (!constant->IsLinked()) {
663     // The constant was removed from the graph. Reinsert.
664     constant->ClearFlag(HValue::kIsDead);
665     constant->InsertAfter(entry_block()->first());
666   }
667   return constant;
668 }
669
670
671 HConstant* HGraph::GetConstant0() {
672   return GetConstant(&constant_0_, 0);
673 }
674
675
676 HConstant* HGraph::GetConstant1() {
677   return GetConstant(&constant_1_, 1);
678 }
679
680
681 HConstant* HGraph::GetConstantMinus1() {
682   return GetConstant(&constant_minus1_, -1);
683 }
684
685
686 HConstant* HGraph::GetConstantBool(bool value) {
687   return value ? GetConstantTrue() : GetConstantFalse();
688 }
689
690
691 #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value)            \
692 HConstant* HGraph::GetConstant##Name() {                                       \
693   if (!constant_##name##_.is_set()) {                                          \
694     HConstant* constant = new(zone()) HConstant(                               \
695         Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \
696         Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()),      \
697         false,                                                                 \
698         Representation::Tagged(),                                              \
699         htype,                                                                 \
700         true,                                                                  \
701         boolean_value,                                                         \
702         false,                                                                 \
703         ODDBALL_TYPE);                                                         \
704     constant->InsertAfter(entry_block()->first());                             \
705     constant_##name##_.set(constant);                                          \
706   }                                                                            \
707   return ReinsertConstantIfNecessary(constant_##name##_.get());                \
708 }
709
710
711 DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false)
712 DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true)
713 DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false)
714 DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false)
715 DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false)
716
717
718 #undef DEFINE_GET_CONSTANT
719
720 #define DEFINE_IS_CONSTANT(Name, name)                                         \
721 bool HGraph::IsConstant##Name(HConstant* constant) {                           \
722   return constant_##name##_.is_set() && constant == constant_##name##_.get();  \
723 }
724 DEFINE_IS_CONSTANT(Undefined, undefined)
725 DEFINE_IS_CONSTANT(0, 0)
726 DEFINE_IS_CONSTANT(1, 1)
727 DEFINE_IS_CONSTANT(Minus1, minus1)
728 DEFINE_IS_CONSTANT(True, true)
729 DEFINE_IS_CONSTANT(False, false)
730 DEFINE_IS_CONSTANT(Hole, the_hole)
731 DEFINE_IS_CONSTANT(Null, null)
732
733 #undef DEFINE_IS_CONSTANT
734
735
736 HConstant* HGraph::GetInvalidContext() {
737   return GetConstant(&constant_invalid_context_, 0xFFFFC0C7);
738 }
739
740
741 bool HGraph::IsStandardConstant(HConstant* constant) {
742   if (IsConstantUndefined(constant)) return true;
743   if (IsConstant0(constant)) return true;
744   if (IsConstant1(constant)) return true;
745   if (IsConstantMinus1(constant)) return true;
746   if (IsConstantTrue(constant)) return true;
747   if (IsConstantFalse(constant)) return true;
748   if (IsConstantHole(constant)) return true;
749   if (IsConstantNull(constant)) return true;
750   return false;
751 }
752
753
754 HGraphBuilder::IfBuilder::IfBuilder() : builder_(NULL), needs_compare_(true) {}
755
756
757 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder)
758     : needs_compare_(true) {
759   Initialize(builder);
760 }
761
762
763 HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder,
764                                     HIfContinuation* continuation)
765     : needs_compare_(false), first_true_block_(NULL), first_false_block_(NULL) {
766   InitializeDontCreateBlocks(builder);
767   continuation->Continue(&first_true_block_, &first_false_block_);
768 }
769
770
771 void HGraphBuilder::IfBuilder::InitializeDontCreateBlocks(
772     HGraphBuilder* builder) {
773   builder_ = builder;
774   finished_ = false;
775   did_then_ = false;
776   did_else_ = false;
777   did_else_if_ = false;
778   did_and_ = false;
779   did_or_ = false;
780   captured_ = false;
781   pending_merge_block_ = false;
782   split_edge_merge_block_ = NULL;
783   merge_at_join_blocks_ = NULL;
784   normal_merge_at_join_block_count_ = 0;
785   deopt_merge_at_join_block_count_ = 0;
786 }
787
788
789 void HGraphBuilder::IfBuilder::Initialize(HGraphBuilder* builder) {
790   InitializeDontCreateBlocks(builder);
791   HEnvironment* env = builder->environment();
792   first_true_block_ = builder->CreateBasicBlock(env->Copy());
793   first_false_block_ = builder->CreateBasicBlock(env->Copy());
794 }
795
796
797 HControlInstruction* HGraphBuilder::IfBuilder::AddCompare(
798     HControlInstruction* compare) {
799   DCHECK(did_then_ == did_else_);
800   if (did_else_) {
801     // Handle if-then-elseif
802     did_else_if_ = true;
803     did_else_ = false;
804     did_then_ = false;
805     did_and_ = false;
806     did_or_ = false;
807     pending_merge_block_ = false;
808     split_edge_merge_block_ = NULL;
809     HEnvironment* env = builder()->environment();
810     first_true_block_ = builder()->CreateBasicBlock(env->Copy());
811     first_false_block_ = builder()->CreateBasicBlock(env->Copy());
812   }
813   if (split_edge_merge_block_ != NULL) {
814     HEnvironment* env = first_false_block_->last_environment();
815     HBasicBlock* split_edge = builder()->CreateBasicBlock(env->Copy());
816     if (did_or_) {
817       compare->SetSuccessorAt(0, split_edge);
818       compare->SetSuccessorAt(1, first_false_block_);
819     } else {
820       compare->SetSuccessorAt(0, first_true_block_);
821       compare->SetSuccessorAt(1, split_edge);
822     }
823     builder()->GotoNoSimulate(split_edge, split_edge_merge_block_);
824   } else {
825     compare->SetSuccessorAt(0, first_true_block_);
826     compare->SetSuccessorAt(1, first_false_block_);
827   }
828   builder()->FinishCurrentBlock(compare);
829   needs_compare_ = false;
830   return compare;
831 }
832
833
834 void HGraphBuilder::IfBuilder::Or() {
835   DCHECK(!needs_compare_);
836   DCHECK(!did_and_);
837   did_or_ = true;
838   HEnvironment* env = first_false_block_->last_environment();
839   if (split_edge_merge_block_ == NULL) {
840     split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
841     builder()->GotoNoSimulate(first_true_block_, split_edge_merge_block_);
842     first_true_block_ = split_edge_merge_block_;
843   }
844   builder()->set_current_block(first_false_block_);
845   first_false_block_ = builder()->CreateBasicBlock(env->Copy());
846 }
847
848
849 void HGraphBuilder::IfBuilder::And() {
850   DCHECK(!needs_compare_);
851   DCHECK(!did_or_);
852   did_and_ = true;
853   HEnvironment* env = first_false_block_->last_environment();
854   if (split_edge_merge_block_ == NULL) {
855     split_edge_merge_block_ = builder()->CreateBasicBlock(env->Copy());
856     builder()->GotoNoSimulate(first_false_block_, split_edge_merge_block_);
857     first_false_block_ = split_edge_merge_block_;
858   }
859   builder()->set_current_block(first_true_block_);
860   first_true_block_ = builder()->CreateBasicBlock(env->Copy());
861 }
862
863
864 void HGraphBuilder::IfBuilder::CaptureContinuation(
865     HIfContinuation* continuation) {
866   DCHECK(!did_else_if_);
867   DCHECK(!finished_);
868   DCHECK(!captured_);
869
870   HBasicBlock* true_block = NULL;
871   HBasicBlock* false_block = NULL;
872   Finish(&true_block, &false_block);
873   DCHECK(true_block != NULL);
874   DCHECK(false_block != NULL);
875   continuation->Capture(true_block, false_block);
876   captured_ = true;
877   builder()->set_current_block(NULL);
878   End();
879 }
880
881
882 void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) {
883   DCHECK(!did_else_if_);
884   DCHECK(!finished_);
885   DCHECK(!captured_);
886   HBasicBlock* true_block = NULL;
887   HBasicBlock* false_block = NULL;
888   Finish(&true_block, &false_block);
889   merge_at_join_blocks_ = NULL;
890   if (true_block != NULL && !true_block->IsFinished()) {
891     DCHECK(continuation->IsTrueReachable());
892     builder()->GotoNoSimulate(true_block, continuation->true_branch());
893   }
894   if (false_block != NULL && !false_block->IsFinished()) {
895     DCHECK(continuation->IsFalseReachable());
896     builder()->GotoNoSimulate(false_block, continuation->false_branch());
897   }
898   captured_ = true;
899   End();
900 }
901
902
903 void HGraphBuilder::IfBuilder::Then() {
904   DCHECK(!captured_);
905   DCHECK(!finished_);
906   did_then_ = true;
907   if (needs_compare_) {
908     // Handle if's without any expressions, they jump directly to the "else"
909     // branch. However, we must pretend that the "then" branch is reachable,
910     // so that the graph builder visits it and sees any live range extending
911     // constructs within it.
912     HConstant* constant_false = builder()->graph()->GetConstantFalse();
913     ToBooleanStub::Types boolean_type = ToBooleanStub::Types();
914     boolean_type.Add(ToBooleanStub::BOOLEAN);
915     HBranch* branch = builder()->New<HBranch>(
916         constant_false, boolean_type, first_true_block_, first_false_block_);
917     builder()->FinishCurrentBlock(branch);
918   }
919   builder()->set_current_block(first_true_block_);
920   pending_merge_block_ = true;
921 }
922
923
924 void HGraphBuilder::IfBuilder::Else() {
925   DCHECK(did_then_);
926   DCHECK(!captured_);
927   DCHECK(!finished_);
928   AddMergeAtJoinBlock(false);
929   builder()->set_current_block(first_false_block_);
930   pending_merge_block_ = true;
931   did_else_ = true;
932 }
933
934
935 void HGraphBuilder::IfBuilder::Deopt(Deoptimizer::DeoptReason reason) {
936   DCHECK(did_then_);
937   builder()->Add<HDeoptimize>(reason, Deoptimizer::EAGER);
938   AddMergeAtJoinBlock(true);
939 }
940
941
942 void HGraphBuilder::IfBuilder::Return(HValue* value) {
943   HValue* parameter_count = builder()->graph()->GetConstantMinus1();
944   builder()->FinishExitCurrentBlock(
945       builder()->New<HReturn>(value, parameter_count));
946   AddMergeAtJoinBlock(false);
947 }
948
949
950 void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) {
951   if (!pending_merge_block_) return;
952   HBasicBlock* block = builder()->current_block();
953   DCHECK(block == NULL || !block->IsFinished());
954   MergeAtJoinBlock* record = new (builder()->zone())
955       MergeAtJoinBlock(block, deopt, merge_at_join_blocks_);
956   merge_at_join_blocks_ = record;
957   if (block != NULL) {
958     DCHECK(block->end() == NULL);
959     if (deopt) {
960       normal_merge_at_join_block_count_++;
961     } else {
962       deopt_merge_at_join_block_count_++;
963     }
964   }
965   builder()->set_current_block(NULL);
966   pending_merge_block_ = false;
967 }
968
969
970 void HGraphBuilder::IfBuilder::Finish() {
971   DCHECK(!finished_);
972   if (!did_then_) {
973     Then();
974   }
975   AddMergeAtJoinBlock(false);
976   if (!did_else_) {
977     Else();
978     AddMergeAtJoinBlock(false);
979   }
980   finished_ = true;
981 }
982
983
984 void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation,
985                                       HBasicBlock** else_continuation) {
986   Finish();
987
988   MergeAtJoinBlock* else_record = merge_at_join_blocks_;
989   if (else_continuation != NULL) {
990     *else_continuation = else_record->block_;
991   }
992   MergeAtJoinBlock* then_record = else_record->next_;
993   if (then_continuation != NULL) {
994     *then_continuation = then_record->block_;
995   }
996   DCHECK(then_record->next_ == NULL);
997 }
998
999
1000 void HGraphBuilder::IfBuilder::EndUnreachable() {
1001   if (captured_) return;
1002   Finish();
1003   builder()->set_current_block(nullptr);
1004 }
1005
1006
1007 void HGraphBuilder::IfBuilder::End() {
1008   if (captured_) return;
1009   Finish();
1010
1011   int total_merged_blocks = normal_merge_at_join_block_count_ +
1012     deopt_merge_at_join_block_count_;
1013   DCHECK(total_merged_blocks >= 1);
1014   HBasicBlock* merge_block =
1015       total_merged_blocks == 1 ? NULL : builder()->graph()->CreateBasicBlock();
1016
1017   // Merge non-deopt blocks first to ensure environment has right size for
1018   // padding.
1019   MergeAtJoinBlock* current = merge_at_join_blocks_;
1020   while (current != NULL) {
1021     if (!current->deopt_ && current->block_ != NULL) {
1022       // If there is only one block that makes it through to the end of the
1023       // if, then just set it as the current block and continue rather then
1024       // creating an unnecessary merge block.
1025       if (total_merged_blocks == 1) {
1026         builder()->set_current_block(current->block_);
1027         return;
1028       }
1029       builder()->GotoNoSimulate(current->block_, merge_block);
1030     }
1031     current = current->next_;
1032   }
1033
1034   // Merge deopt blocks, padding when necessary.
1035   current = merge_at_join_blocks_;
1036   while (current != NULL) {
1037     if (current->deopt_ && current->block_ != NULL) {
1038       current->block_->FinishExit(
1039           HAbnormalExit::New(builder()->isolate(), builder()->zone(), NULL),
1040           SourcePosition::Unknown());
1041     }
1042     current = current->next_;
1043   }
1044   builder()->set_current_block(merge_block);
1045 }
1046
1047
1048 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder) {
1049   Initialize(builder, NULL, kWhileTrue, NULL);
1050 }
1051
1052
1053 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1054                                         LoopBuilder::Direction direction) {
1055   Initialize(builder, context, direction, builder->graph()->GetConstant1());
1056 }
1057
1058
1059 HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context,
1060                                         LoopBuilder::Direction direction,
1061                                         HValue* increment_amount) {
1062   Initialize(builder, context, direction, increment_amount);
1063   increment_amount_ = increment_amount;
1064 }
1065
1066
1067 void HGraphBuilder::LoopBuilder::Initialize(HGraphBuilder* builder,
1068                                             HValue* context,
1069                                             Direction direction,
1070                                             HValue* increment_amount) {
1071   builder_ = builder;
1072   context_ = context;
1073   direction_ = direction;
1074   increment_amount_ = increment_amount;
1075
1076   finished_ = false;
1077   header_block_ = builder->CreateLoopHeaderBlock();
1078   body_block_ = NULL;
1079   exit_block_ = NULL;
1080   exit_trampoline_block_ = NULL;
1081 }
1082
1083
1084 HValue* HGraphBuilder::LoopBuilder::BeginBody(
1085     HValue* initial,
1086     HValue* terminating,
1087     Token::Value token) {
1088   DCHECK(direction_ != kWhileTrue);
1089   HEnvironment* env = builder_->environment();
1090   phi_ = header_block_->AddNewPhi(env->values()->length());
1091   phi_->AddInput(initial);
1092   env->Push(initial);
1093   builder_->GotoNoSimulate(header_block_);
1094
1095   HEnvironment* body_env = env->Copy();
1096   HEnvironment* exit_env = env->Copy();
1097   // Remove the phi from the expression stack
1098   body_env->Pop();
1099   exit_env->Pop();
1100   body_block_ = builder_->CreateBasicBlock(body_env);
1101   exit_block_ = builder_->CreateBasicBlock(exit_env);
1102
1103   builder_->set_current_block(header_block_);
1104   env->Pop();
1105   builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>(
1106           phi_, terminating, token, body_block_, exit_block_));
1107
1108   builder_->set_current_block(body_block_);
1109   if (direction_ == kPreIncrement || direction_ == kPreDecrement) {
1110     Isolate* isolate = builder_->isolate();
1111     HValue* one = builder_->graph()->GetConstant1();
1112     if (direction_ == kPreIncrement) {
1113       increment_ = HAdd::New(isolate, zone(), context_, phi_, one);
1114     } else {
1115       increment_ = HSub::New(isolate, zone(), context_, phi_, one);
1116     }
1117     increment_->ClearFlag(HValue::kCanOverflow);
1118     builder_->AddInstruction(increment_);
1119     return increment_;
1120   } else {
1121     return phi_;
1122   }
1123 }
1124
1125
1126 void HGraphBuilder::LoopBuilder::BeginBody(int drop_count) {
1127   DCHECK(direction_ == kWhileTrue);
1128   HEnvironment* env = builder_->environment();
1129   builder_->GotoNoSimulate(header_block_);
1130   builder_->set_current_block(header_block_);
1131   env->Drop(drop_count);
1132 }
1133
1134
1135 void HGraphBuilder::LoopBuilder::Break() {
1136   if (exit_trampoline_block_ == NULL) {
1137     // Its the first time we saw a break.
1138     if (direction_ == kWhileTrue) {
1139       HEnvironment* env = builder_->environment()->Copy();
1140       exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1141     } else {
1142       HEnvironment* env = exit_block_->last_environment()->Copy();
1143       exit_trampoline_block_ = builder_->CreateBasicBlock(env);
1144       builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_);
1145     }
1146   }
1147
1148   builder_->GotoNoSimulate(exit_trampoline_block_);
1149   builder_->set_current_block(NULL);
1150 }
1151
1152
1153 void HGraphBuilder::LoopBuilder::EndBody() {
1154   DCHECK(!finished_);
1155
1156   if (direction_ == kPostIncrement || direction_ == kPostDecrement) {
1157     Isolate* isolate = builder_->isolate();
1158     if (direction_ == kPostIncrement) {
1159       increment_ =
1160           HAdd::New(isolate, zone(), context_, phi_, increment_amount_);
1161     } else {
1162       increment_ =
1163           HSub::New(isolate, zone(), context_, phi_, increment_amount_);
1164     }
1165     increment_->ClearFlag(HValue::kCanOverflow);
1166     builder_->AddInstruction(increment_);
1167   }
1168
1169   if (direction_ != kWhileTrue) {
1170     // Push the new increment value on the expression stack to merge into
1171     // the phi.
1172     builder_->environment()->Push(increment_);
1173   }
1174   HBasicBlock* last_block = builder_->current_block();
1175   builder_->GotoNoSimulate(last_block, header_block_);
1176   header_block_->loop_information()->RegisterBackEdge(last_block);
1177
1178   if (exit_trampoline_block_ != NULL) {
1179     builder_->set_current_block(exit_trampoline_block_);
1180   } else {
1181     builder_->set_current_block(exit_block_);
1182   }
1183   finished_ = true;
1184 }
1185
1186
1187 HGraph* HGraphBuilder::CreateGraph() {
1188   graph_ = new(zone()) HGraph(info_);
1189   if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_);
1190   CompilationPhase phase("H_Block building", info_);
1191   set_current_block(graph()->entry_block());
1192   if (!BuildGraph()) return NULL;
1193   graph()->FinalizeUniqueness();
1194   return graph_;
1195 }
1196
1197
1198 HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) {
1199   DCHECK(current_block() != NULL);
1200   DCHECK(!FLAG_hydrogen_track_positions ||
1201          !position_.IsUnknown() ||
1202          !info_->IsOptimizing());
1203   current_block()->AddInstruction(instr, source_position());
1204   if (graph()->IsInsideNoSideEffectsScope()) {
1205     instr->SetFlag(HValue::kHasNoObservableSideEffects);
1206   }
1207   return instr;
1208 }
1209
1210
1211 void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) {
1212   DCHECK(!FLAG_hydrogen_track_positions ||
1213          !info_->IsOptimizing() ||
1214          !position_.IsUnknown());
1215   current_block()->Finish(last, source_position());
1216   if (last->IsReturn() || last->IsAbnormalExit()) {
1217     set_current_block(NULL);
1218   }
1219 }
1220
1221
1222 void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) {
1223   DCHECK(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() ||
1224          !position_.IsUnknown());
1225   current_block()->FinishExit(instruction, source_position());
1226   if (instruction->IsReturn() || instruction->IsAbnormalExit()) {
1227     set_current_block(NULL);
1228   }
1229 }
1230
1231
1232 void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) {
1233   if (FLAG_native_code_counters && counter->Enabled()) {
1234     HValue* reference = Add<HConstant>(ExternalReference(counter));
1235     HValue* old_value =
1236         Add<HLoadNamedField>(reference, nullptr, HObjectAccess::ForCounter());
1237     HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1());
1238     new_value->ClearFlag(HValue::kCanOverflow);  // Ignore counter overflow
1239     Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(),
1240                           new_value, STORE_TO_INITIALIZED_ENTRY);
1241   }
1242 }
1243
1244
1245 void HGraphBuilder::AddSimulate(BailoutId id,
1246                                 RemovableSimulate removable) {
1247   DCHECK(current_block() != NULL);
1248   DCHECK(!graph()->IsInsideNoSideEffectsScope());
1249   current_block()->AddNewSimulate(id, source_position(), removable);
1250 }
1251
1252
1253 HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) {
1254   HBasicBlock* b = graph()->CreateBasicBlock();
1255   b->SetInitialEnvironment(env);
1256   return b;
1257 }
1258
1259
1260 HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() {
1261   HBasicBlock* header = graph()->CreateBasicBlock();
1262   HEnvironment* entry_env = environment()->CopyAsLoopHeader(header);
1263   header->SetInitialEnvironment(entry_env);
1264   header->AttachLoopInformation();
1265   return header;
1266 }
1267
1268
1269 HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) {
1270   HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
1271
1272   HValue* bit_field2 =
1273       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2());
1274   return BuildDecodeField<Map::ElementsKindBits>(bit_field2);
1275 }
1276
1277
1278 HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) {
1279   if (obj->type().IsHeapObject()) return obj;
1280   return Add<HCheckHeapObject>(obj);
1281 }
1282
1283
1284 void HGraphBuilder::FinishExitWithHardDeoptimization(
1285     Deoptimizer::DeoptReason reason) {
1286   Add<HDeoptimize>(reason, Deoptimizer::EAGER);
1287   FinishExitCurrentBlock(New<HAbnormalExit>());
1288 }
1289
1290
1291 HValue* HGraphBuilder::BuildCheckString(HValue* string) {
1292   if (!string->type().IsString()) {
1293     DCHECK(!string->IsConstant() ||
1294            !HConstant::cast(string)->HasStringValue());
1295     BuildCheckHeapObject(string);
1296     return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING);
1297   }
1298   return string;
1299 }
1300
1301
1302 HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) {
1303   if (object->type().IsJSObject()) return object;
1304   if (function->IsConstant() &&
1305       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
1306     Handle<JSFunction> f = Handle<JSFunction>::cast(
1307         HConstant::cast(function)->handle(isolate()));
1308     SharedFunctionInfo* shared = f->shared();
1309     if (is_strict(shared->language_mode()) || shared->native()) return object;
1310   }
1311   return Add<HWrapReceiver>(object, function);
1312 }
1313
1314
1315 HValue* HGraphBuilder::BuildCheckAndGrowElementsCapacity(
1316     HValue* object, HValue* elements, ElementsKind kind, HValue* length,
1317     HValue* capacity, HValue* key) {
1318   HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap));
1319   HValue* max_capacity = AddUncasted<HAdd>(capacity, max_gap);
1320   Add<HBoundsCheck>(key, max_capacity);
1321
1322   HValue* new_capacity = BuildNewElementsCapacity(key);
1323   HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind,
1324                                                    length, new_capacity);
1325   return new_elements;
1326 }
1327
1328
1329 HValue* HGraphBuilder::BuildCheckForCapacityGrow(
1330     HValue* object,
1331     HValue* elements,
1332     ElementsKind kind,
1333     HValue* length,
1334     HValue* key,
1335     bool is_js_array,
1336     PropertyAccessType access_type) {
1337   IfBuilder length_checker(this);
1338
1339   Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ;
1340   length_checker.If<HCompareNumericAndBranch>(key, length, token);
1341
1342   length_checker.Then();
1343
1344   HValue* current_capacity = AddLoadFixedArrayLength(elements);
1345
1346   if (top_info()->IsStub()) {
1347     IfBuilder capacity_checker(this);
1348     capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity,
1349                                                   Token::GTE);
1350     capacity_checker.Then();
1351     HValue* new_elements = BuildCheckAndGrowElementsCapacity(
1352         object, elements, kind, length, current_capacity, key);
1353     environment()->Push(new_elements);
1354     capacity_checker.Else();
1355     environment()->Push(elements);
1356     capacity_checker.End();
1357   } else {
1358     HValue* result = Add<HMaybeGrowElements>(
1359         object, elements, key, current_capacity, is_js_array, kind);
1360     environment()->Push(result);
1361   }
1362
1363   if (is_js_array) {
1364     HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1());
1365     new_length->ClearFlag(HValue::kCanOverflow);
1366
1367     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind),
1368                           new_length);
1369   }
1370
1371   if (access_type == STORE && kind == FAST_SMI_ELEMENTS) {
1372     HValue* checked_elements = environment()->Top();
1373
1374     // Write zero to ensure that the new element is initialized with some smi.
1375     Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind);
1376   }
1377
1378   length_checker.Else();
1379   Add<HBoundsCheck>(key, length);
1380
1381   environment()->Push(elements);
1382   length_checker.End();
1383
1384   return environment()->Pop();
1385 }
1386
1387
1388 HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object,
1389                                                 HValue* elements,
1390                                                 ElementsKind kind,
1391                                                 HValue* length) {
1392   Factory* factory = isolate()->factory();
1393
1394   IfBuilder cow_checker(this);
1395
1396   cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map());
1397   cow_checker.Then();
1398
1399   HValue* capacity = AddLoadFixedArrayLength(elements);
1400
1401   HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind,
1402                                                    kind, length, capacity);
1403
1404   environment()->Push(new_elements);
1405
1406   cow_checker.Else();
1407
1408   environment()->Push(elements);
1409
1410   cow_checker.End();
1411
1412   return environment()->Pop();
1413 }
1414
1415
1416 void HGraphBuilder::BuildTransitionElementsKind(HValue* object,
1417                                                 HValue* map,
1418                                                 ElementsKind from_kind,
1419                                                 ElementsKind to_kind,
1420                                                 bool is_jsarray) {
1421   DCHECK(!IsFastHoleyElementsKind(from_kind) ||
1422          IsFastHoleyElementsKind(to_kind));
1423
1424   if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) {
1425     Add<HTrapAllocationMemento>(object);
1426   }
1427
1428   if (!IsSimpleMapChangeTransition(from_kind, to_kind)) {
1429     HInstruction* elements = AddLoadElements(object);
1430
1431     HInstruction* empty_fixed_array = Add<HConstant>(
1432         isolate()->factory()->empty_fixed_array());
1433
1434     IfBuilder if_builder(this);
1435
1436     if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array);
1437
1438     if_builder.Then();
1439
1440     HInstruction* elements_length = AddLoadFixedArrayLength(elements);
1441
1442     HInstruction* array_length =
1443         is_jsarray
1444             ? Add<HLoadNamedField>(object, nullptr,
1445                                    HObjectAccess::ForArrayLength(from_kind))
1446             : elements_length;
1447
1448     BuildGrowElementsCapacity(object, elements, from_kind, to_kind,
1449                               array_length, elements_length);
1450
1451     if_builder.End();
1452   }
1453
1454   Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map);
1455 }
1456
1457
1458 void HGraphBuilder::BuildJSObjectCheck(HValue* receiver,
1459                                        int bit_field_mask) {
1460   // Check that the object isn't a smi.
1461   Add<HCheckHeapObject>(receiver);
1462
1463   // Get the map of the receiver.
1464   HValue* map =
1465       Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap());
1466
1467   // Check the instance type and if an access check is needed, this can be
1468   // done with a single load, since both bytes are adjacent in the map.
1469   HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField());
1470   HValue* instance_type_and_bit_field =
1471       Add<HLoadNamedField>(map, nullptr, access);
1472
1473   HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8));
1474   HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND,
1475                                              instance_type_and_bit_field,
1476                                              mask);
1477   HValue* sub_result = AddUncasted<HSub>(and_result,
1478                                          Add<HConstant>(JS_OBJECT_TYPE));
1479   Add<HBoundsCheck>(sub_result,
1480                     Add<HConstant>(LAST_JS_OBJECT_TYPE + 1 - JS_OBJECT_TYPE));
1481 }
1482
1483
1484 void HGraphBuilder::BuildKeyedIndexCheck(HValue* key,
1485                                          HIfContinuation* join_continuation) {
1486   // The sometimes unintuitively backward ordering of the ifs below is
1487   // convoluted, but necessary.  All of the paths must guarantee that the
1488   // if-true of the continuation returns a smi element index and the if-false of
1489   // the continuation returns either a symbol or a unique string key. All other
1490   // object types cause a deopt to fall back to the runtime.
1491
1492   IfBuilder key_smi_if(this);
1493   key_smi_if.If<HIsSmiAndBranch>(key);
1494   key_smi_if.Then();
1495   {
1496     Push(key);  // Nothing to do, just continue to true of continuation.
1497   }
1498   key_smi_if.Else();
1499   {
1500     HValue* map = Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForMap());
1501     HValue* instance_type =
1502         Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1503
1504     // Non-unique string, check for a string with a hash code that is actually
1505     // an index.
1506     STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE);
1507     IfBuilder not_string_or_name_if(this);
1508     not_string_or_name_if.If<HCompareNumericAndBranch>(
1509         instance_type,
1510         Add<HConstant>(LAST_UNIQUE_NAME_TYPE),
1511         Token::GT);
1512
1513     not_string_or_name_if.Then();
1514     {
1515       // Non-smi, non-Name, non-String: Try to convert to smi in case of
1516       // HeapNumber.
1517       // TODO(danno): This could call some variant of ToString
1518       Push(AddUncasted<HForceRepresentation>(key, Representation::Smi()));
1519     }
1520     not_string_or_name_if.Else();
1521     {
1522       // String or Name: check explicitly for Name, they can short-circuit
1523       // directly to unique non-index key path.
1524       IfBuilder not_symbol_if(this);
1525       not_symbol_if.If<HCompareNumericAndBranch>(
1526           instance_type,
1527           Add<HConstant>(SYMBOL_TYPE),
1528           Token::NE);
1529
1530       not_symbol_if.Then();
1531       {
1532         // String: check whether the String is a String of an index. If it is,
1533         // extract the index value from the hash.
1534         HValue* hash = Add<HLoadNamedField>(key, nullptr,
1535                                             HObjectAccess::ForNameHashField());
1536         HValue* not_index_mask = Add<HConstant>(static_cast<int>(
1537             String::kContainsCachedArrayIndexMask));
1538
1539         HValue* not_index_test = AddUncasted<HBitwise>(
1540             Token::BIT_AND, hash, not_index_mask);
1541
1542         IfBuilder string_index_if(this);
1543         string_index_if.If<HCompareNumericAndBranch>(not_index_test,
1544                                                      graph()->GetConstant0(),
1545                                                      Token::EQ);
1546         string_index_if.Then();
1547         {
1548           // String with index in hash: extract string and merge to index path.
1549           Push(BuildDecodeField<String::ArrayIndexValueBits>(hash));
1550         }
1551         string_index_if.Else();
1552         {
1553           // Key is a non-index String, check for uniqueness/internalization.
1554           // If it's not internalized yet, internalize it now.
1555           HValue* not_internalized_bit = AddUncasted<HBitwise>(
1556               Token::BIT_AND,
1557               instance_type,
1558               Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1559
1560           IfBuilder internalized(this);
1561           internalized.If<HCompareNumericAndBranch>(not_internalized_bit,
1562                                                     graph()->GetConstant0(),
1563                                                     Token::EQ);
1564           internalized.Then();
1565           Push(key);
1566
1567           internalized.Else();
1568           Add<HPushArguments>(key);
1569           HValue* intern_key = Add<HCallRuntime>(
1570               isolate()->factory()->empty_string(),
1571               Runtime::FunctionForId(Runtime::kInternalizeString), 1);
1572           Push(intern_key);
1573
1574           internalized.End();
1575           // Key guaranteed to be a unique string
1576         }
1577         string_index_if.JoinContinuation(join_continuation);
1578       }
1579       not_symbol_if.Else();
1580       {
1581         Push(key);  // Key is symbol
1582       }
1583       not_symbol_if.JoinContinuation(join_continuation);
1584     }
1585     not_string_or_name_if.JoinContinuation(join_continuation);
1586   }
1587   key_smi_if.JoinContinuation(join_continuation);
1588 }
1589
1590
1591 void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) {
1592   // Get the the instance type of the receiver, and make sure that it is
1593   // not one of the global object types.
1594   HValue* map =
1595       Add<HLoadNamedField>(receiver, nullptr, HObjectAccess::ForMap());
1596   HValue* instance_type =
1597       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1598   STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1);
1599   HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE);
1600   HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE);
1601
1602   IfBuilder if_global_object(this);
1603   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1604                                                 max_global_type,
1605                                                 Token::LTE);
1606   if_global_object.And();
1607   if_global_object.If<HCompareNumericAndBranch>(instance_type,
1608                                                 min_global_type,
1609                                                 Token::GTE);
1610   if_global_object.ThenDeopt(Deoptimizer::kReceiverWasAGlobalObject);
1611   if_global_object.End();
1612 }
1613
1614
1615 void HGraphBuilder::BuildTestForDictionaryProperties(
1616     HValue* object,
1617     HIfContinuation* continuation) {
1618   HValue* properties = Add<HLoadNamedField>(
1619       object, nullptr, HObjectAccess::ForPropertiesPointer());
1620   HValue* properties_map =
1621       Add<HLoadNamedField>(properties, nullptr, HObjectAccess::ForMap());
1622   HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex);
1623   IfBuilder builder(this);
1624   builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map);
1625   builder.CaptureContinuation(continuation);
1626 }
1627
1628
1629 HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object,
1630                                                  HValue* key) {
1631   // Load the map of the receiver, compute the keyed lookup cache hash
1632   // based on 32 bits of the map pointer and the string hash.
1633   HValue* object_map =
1634       Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMapAsInteger32());
1635   HValue* shifted_map = AddUncasted<HShr>(
1636       object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift));
1637   HValue* string_hash =
1638       Add<HLoadNamedField>(key, nullptr, HObjectAccess::ForStringHashField());
1639   HValue* shifted_hash = AddUncasted<HShr>(
1640       string_hash, Add<HConstant>(String::kHashShift));
1641   HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map,
1642                                              shifted_hash);
1643   int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask);
1644   return AddUncasted<HBitwise>(Token::BIT_AND, xor_result,
1645                                Add<HConstant>(mask));
1646 }
1647
1648
1649 HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) {
1650   int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed());
1651   HValue* seed = Add<HConstant>(seed_value);
1652   HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed);
1653
1654   // hash = ~hash + (hash << 15);
1655   HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15));
1656   HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash,
1657                                            graph()->GetConstantMinus1());
1658   hash = AddUncasted<HAdd>(shifted_hash, not_hash);
1659
1660   // hash = hash ^ (hash >> 12);
1661   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12));
1662   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1663
1664   // hash = hash + (hash << 2);
1665   shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2));
1666   hash = AddUncasted<HAdd>(hash, shifted_hash);
1667
1668   // hash = hash ^ (hash >> 4);
1669   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4));
1670   hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1671
1672   // hash = hash * 2057;
1673   hash = AddUncasted<HMul>(hash, Add<HConstant>(2057));
1674   hash->ClearFlag(HValue::kCanOverflow);
1675
1676   // hash = hash ^ (hash >> 16);
1677   shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16));
1678   return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash);
1679 }
1680
1681
1682 HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(
1683     HValue* receiver, HValue* elements, HValue* key, HValue* hash,
1684     LanguageMode language_mode) {
1685   HValue* capacity =
1686       Add<HLoadKeyed>(elements, Add<HConstant>(NameDictionary::kCapacityIndex),
1687                       nullptr, FAST_ELEMENTS);
1688
1689   HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1());
1690   mask->ChangeRepresentation(Representation::Integer32());
1691   mask->ClearFlag(HValue::kCanOverflow);
1692
1693   HValue* entry = hash;
1694   HValue* count = graph()->GetConstant1();
1695   Push(entry);
1696   Push(count);
1697
1698   HIfContinuation return_or_loop_continuation(graph()->CreateBasicBlock(),
1699                                               graph()->CreateBasicBlock());
1700   HIfContinuation found_key_match_continuation(graph()->CreateBasicBlock(),
1701                                                graph()->CreateBasicBlock());
1702   LoopBuilder probe_loop(this);
1703   probe_loop.BeginBody(2);  // Drop entry, count from last environment to
1704                             // appease live range building without simulates.
1705
1706   count = Pop();
1707   entry = Pop();
1708   entry = AddUncasted<HBitwise>(Token::BIT_AND, entry, mask);
1709   int entry_size = SeededNumberDictionary::kEntrySize;
1710   HValue* base_index = AddUncasted<HMul>(entry, Add<HConstant>(entry_size));
1711   base_index->ClearFlag(HValue::kCanOverflow);
1712   int start_offset = SeededNumberDictionary::kElementsStartIndex;
1713   HValue* key_index =
1714       AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset));
1715   key_index->ClearFlag(HValue::kCanOverflow);
1716
1717   HValue* candidate_key =
1718       Add<HLoadKeyed>(elements, key_index, nullptr, FAST_ELEMENTS);
1719   IfBuilder if_undefined(this);
1720   if_undefined.If<HCompareObjectEqAndBranch>(candidate_key,
1721                                              graph()->GetConstantUndefined());
1722   if_undefined.Then();
1723   {
1724     // element == undefined means "not found". Call the runtime.
1725     // TODO(jkummerow): walk the prototype chain instead.
1726     Add<HPushArguments>(receiver, key);
1727     Push(Add<HCallRuntime>(
1728         isolate()->factory()->empty_string(),
1729         Runtime::FunctionForId(is_strong(language_mode)
1730                                    ? Runtime::kKeyedGetPropertyStrong
1731                                    : Runtime::kKeyedGetProperty),
1732         2));
1733   }
1734   if_undefined.Else();
1735   {
1736     IfBuilder if_match(this);
1737     if_match.If<HCompareObjectEqAndBranch>(candidate_key, key);
1738     if_match.Then();
1739     if_match.Else();
1740
1741     // Update non-internalized string in the dictionary with internalized key?
1742     IfBuilder if_update_with_internalized(this);
1743     HValue* smi_check =
1744         if_update_with_internalized.IfNot<HIsSmiAndBranch>(candidate_key);
1745     if_update_with_internalized.And();
1746     HValue* map = AddLoadMap(candidate_key, smi_check);
1747     HValue* instance_type =
1748         Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
1749     HValue* not_internalized_bit = AddUncasted<HBitwise>(
1750         Token::BIT_AND, instance_type,
1751         Add<HConstant>(static_cast<int>(kIsNotInternalizedMask)));
1752     if_update_with_internalized.If<HCompareNumericAndBranch>(
1753         not_internalized_bit, graph()->GetConstant0(), Token::NE);
1754     if_update_with_internalized.And();
1755     if_update_with_internalized.IfNot<HCompareObjectEqAndBranch>(
1756         candidate_key, graph()->GetConstantHole());
1757     if_update_with_internalized.AndIf<HStringCompareAndBranch>(candidate_key,
1758                                                                key, Token::EQ);
1759     if_update_with_internalized.Then();
1760     // Replace a key that is a non-internalized string by the equivalent
1761     // internalized string for faster further lookups.
1762     Add<HStoreKeyed>(elements, key_index, key, FAST_ELEMENTS);
1763     if_update_with_internalized.Else();
1764
1765     if_update_with_internalized.JoinContinuation(&found_key_match_continuation);
1766     if_match.JoinContinuation(&found_key_match_continuation);
1767
1768     IfBuilder found_key_match(this, &found_key_match_continuation);
1769     found_key_match.Then();
1770     // Key at current probe matches. Relevant bits in the |details| field must
1771     // be zero, otherwise the dictionary element requires special handling.
1772     HValue* details_index =
1773         AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 2));
1774     details_index->ClearFlag(HValue::kCanOverflow);
1775     HValue* details =
1776         Add<HLoadKeyed>(elements, details_index, nullptr, FAST_ELEMENTS);
1777     int details_mask = PropertyDetails::TypeField::kMask;
1778     details = AddUncasted<HBitwise>(Token::BIT_AND, details,
1779                                     Add<HConstant>(details_mask));
1780     IfBuilder details_compare(this);
1781     details_compare.If<HCompareNumericAndBranch>(
1782         details, graph()->GetConstant0(), Token::EQ);
1783     details_compare.Then();
1784     HValue* result_index =
1785         AddUncasted<HAdd>(base_index, Add<HConstant>(start_offset + 1));
1786     result_index->ClearFlag(HValue::kCanOverflow);
1787     Push(Add<HLoadKeyed>(elements, result_index, nullptr, FAST_ELEMENTS));
1788     details_compare.Else();
1789     Add<HPushArguments>(receiver, key);
1790     Push(Add<HCallRuntime>(
1791         isolate()->factory()->empty_string(),
1792         Runtime::FunctionForId(is_strong(language_mode)
1793                                    ? Runtime::kKeyedGetPropertyStrong
1794                                    : Runtime::kKeyedGetProperty),
1795         2));
1796     details_compare.End();
1797
1798     found_key_match.Else();
1799     found_key_match.JoinContinuation(&return_or_loop_continuation);
1800   }
1801   if_undefined.JoinContinuation(&return_or_loop_continuation);
1802
1803   IfBuilder return_or_loop(this, &return_or_loop_continuation);
1804   return_or_loop.Then();
1805   probe_loop.Break();
1806
1807   return_or_loop.Else();
1808   entry = AddUncasted<HAdd>(entry, count);
1809   entry->ClearFlag(HValue::kCanOverflow);
1810   count = AddUncasted<HAdd>(count, graph()->GetConstant1());
1811   count->ClearFlag(HValue::kCanOverflow);
1812   Push(entry);
1813   Push(count);
1814
1815   probe_loop.EndBody();
1816
1817   return_or_loop.End();
1818
1819   return Pop();
1820 }
1821
1822
1823 HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length,
1824                                                   HValue* index,
1825                                                   HValue* input) {
1826   NoObservableSideEffectsScope scope(this);
1827   HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray);
1828   Add<HBoundsCheck>(length, max_length);
1829
1830   // Generate size calculation code here in order to make it dominate
1831   // the JSRegExpResult allocation.
1832   ElementsKind elements_kind = FAST_ELEMENTS;
1833   HValue* size = BuildCalculateElementsSize(elements_kind, length);
1834
1835   // Allocate the JSRegExpResult and the FixedArray in one step.
1836   HValue* result = Add<HAllocate>(
1837       Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(),
1838       NOT_TENURED, JS_ARRAY_TYPE);
1839
1840   // Initialize the JSRegExpResult header.
1841   HValue* global_object = Add<HLoadNamedField>(
1842       context(), nullptr,
1843       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1844   HValue* native_context = Add<HLoadNamedField>(
1845       global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext());
1846   Add<HStoreNamedField>(
1847       result, HObjectAccess::ForMap(),
1848       Add<HLoadNamedField>(
1849           native_context, nullptr,
1850           HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX)));
1851   HConstant* empty_fixed_array =
1852       Add<HConstant>(isolate()->factory()->empty_fixed_array());
1853   Add<HStoreNamedField>(
1854       result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
1855       empty_fixed_array);
1856   Add<HStoreNamedField>(
1857       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1858       empty_fixed_array);
1859   Add<HStoreNamedField>(
1860       result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length);
1861
1862   // Initialize the additional fields.
1863   Add<HStoreNamedField>(
1864       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset),
1865       index);
1866   Add<HStoreNamedField>(
1867       result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset),
1868       input);
1869
1870   // Allocate and initialize the elements header.
1871   HAllocate* elements = BuildAllocateElements(elements_kind, size);
1872   BuildInitializeElementsHeader(elements, elements_kind, length);
1873
1874   if (!elements->has_size_upper_bound()) {
1875     HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize(
1876         elements_kind, max_length->Integer32Value());
1877     elements->set_size_upper_bound(size_in_bytes_upper_bound);
1878   }
1879
1880   Add<HStoreNamedField>(
1881       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
1882       elements);
1883
1884   // Initialize the elements contents with undefined.
1885   BuildFillElementsWithValue(
1886       elements, elements_kind, graph()->GetConstant0(), length,
1887       graph()->GetConstantUndefined());
1888
1889   return result;
1890 }
1891
1892
1893 HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) {
1894   NoObservableSideEffectsScope scope(this);
1895
1896   // Convert constant numbers at compile time.
1897   if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) {
1898     Handle<Object> number = HConstant::cast(object)->handle(isolate());
1899     Handle<String> result = isolate()->factory()->NumberToString(number);
1900     return Add<HConstant>(result);
1901   }
1902
1903   // Create a joinable continuation.
1904   HIfContinuation found(graph()->CreateBasicBlock(),
1905                         graph()->CreateBasicBlock());
1906
1907   // Load the number string cache.
1908   HValue* number_string_cache =
1909       Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex);
1910
1911   // Make the hash mask from the length of the number string cache. It
1912   // contains two elements (number and string) for each cache entry.
1913   HValue* mask = AddLoadFixedArrayLength(number_string_cache);
1914   mask->set_type(HType::Smi());
1915   mask = AddUncasted<HSar>(mask, graph()->GetConstant1());
1916   mask = AddUncasted<HSub>(mask, graph()->GetConstant1());
1917
1918   // Check whether object is a smi.
1919   IfBuilder if_objectissmi(this);
1920   if_objectissmi.If<HIsSmiAndBranch>(object);
1921   if_objectissmi.Then();
1922   {
1923     // Compute hash for smi similar to smi_get_hash().
1924     HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask);
1925
1926     // Load the key.
1927     HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1928     HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr,
1929                                   FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1930
1931     // Check if object == key.
1932     IfBuilder if_objectiskey(this);
1933     if_objectiskey.If<HCompareObjectEqAndBranch>(object, key);
1934     if_objectiskey.Then();
1935     {
1936       // Make the key_index available.
1937       Push(key_index);
1938     }
1939     if_objectiskey.JoinContinuation(&found);
1940   }
1941   if_objectissmi.Else();
1942   {
1943     if (type->Is(Type::SignedSmall())) {
1944       if_objectissmi.Deopt(Deoptimizer::kExpectedSmi);
1945     } else {
1946       // Check if the object is a heap number.
1947       IfBuilder if_objectisnumber(this);
1948       HValue* objectisnumber = if_objectisnumber.If<HCompareMap>(
1949           object, isolate()->factory()->heap_number_map());
1950       if_objectisnumber.Then();
1951       {
1952         // Compute hash for heap number similar to double_get_hash().
1953         HValue* low = Add<HLoadNamedField>(
1954             object, objectisnumber,
1955             HObjectAccess::ForHeapNumberValueLowestBits());
1956         HValue* high = Add<HLoadNamedField>(
1957             object, objectisnumber,
1958             HObjectAccess::ForHeapNumberValueHighestBits());
1959         HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high);
1960         hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask);
1961
1962         // Load the key.
1963         HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1());
1964         HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, nullptr,
1965                                       FAST_ELEMENTS, ALLOW_RETURN_HOLE);
1966
1967         // Check if the key is a heap number and compare it with the object.
1968         IfBuilder if_keyisnotsmi(this);
1969         HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key);
1970         if_keyisnotsmi.Then();
1971         {
1972           IfBuilder if_keyisheapnumber(this);
1973           if_keyisheapnumber.If<HCompareMap>(
1974               key, isolate()->factory()->heap_number_map());
1975           if_keyisheapnumber.Then();
1976           {
1977             // Check if values of key and object match.
1978             IfBuilder if_keyeqobject(this);
1979             if_keyeqobject.If<HCompareNumericAndBranch>(
1980                 Add<HLoadNamedField>(key, keyisnotsmi,
1981                                      HObjectAccess::ForHeapNumberValue()),
1982                 Add<HLoadNamedField>(object, objectisnumber,
1983                                      HObjectAccess::ForHeapNumberValue()),
1984                 Token::EQ);
1985             if_keyeqobject.Then();
1986             {
1987               // Make the key_index available.
1988               Push(key_index);
1989             }
1990             if_keyeqobject.JoinContinuation(&found);
1991           }
1992           if_keyisheapnumber.JoinContinuation(&found);
1993         }
1994         if_keyisnotsmi.JoinContinuation(&found);
1995       }
1996       if_objectisnumber.Else();
1997       {
1998         if (type->Is(Type::Number())) {
1999           if_objectisnumber.Deopt(Deoptimizer::kExpectedHeapNumber);
2000         }
2001       }
2002       if_objectisnumber.JoinContinuation(&found);
2003     }
2004   }
2005   if_objectissmi.JoinContinuation(&found);
2006
2007   // Check for cache hit.
2008   IfBuilder if_found(this, &found);
2009   if_found.Then();
2010   {
2011     // Count number to string operation in native code.
2012     AddIncrementCounter(isolate()->counters()->number_to_string_native());
2013
2014     // Load the value in case of cache hit.
2015     HValue* key_index = Pop();
2016     HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1());
2017     Push(Add<HLoadKeyed>(number_string_cache, value_index, nullptr,
2018                          FAST_ELEMENTS, ALLOW_RETURN_HOLE));
2019   }
2020   if_found.Else();
2021   {
2022     // Cache miss, fallback to runtime.
2023     Add<HPushArguments>(object);
2024     Push(Add<HCallRuntime>(
2025             isolate()->factory()->empty_string(),
2026             Runtime::FunctionForId(Runtime::kNumberToStringSkipCache),
2027             1));
2028   }
2029   if_found.End();
2030
2031   return Pop();
2032 }
2033
2034
2035 HAllocate* HGraphBuilder::BuildAllocate(
2036     HValue* object_size,
2037     HType type,
2038     InstanceType instance_type,
2039     HAllocationMode allocation_mode) {
2040   // Compute the effective allocation size.
2041   HValue* size = object_size;
2042   if (allocation_mode.CreateAllocationMementos()) {
2043     size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize));
2044     size->ClearFlag(HValue::kCanOverflow);
2045   }
2046
2047   // Perform the actual allocation.
2048   HAllocate* object = Add<HAllocate>(
2049       size, type, allocation_mode.GetPretenureMode(),
2050       instance_type, allocation_mode.feedback_site());
2051
2052   // Setup the allocation memento.
2053   if (allocation_mode.CreateAllocationMementos()) {
2054     BuildCreateAllocationMemento(
2055         object, object_size, allocation_mode.current_site());
2056   }
2057
2058   return object;
2059 }
2060
2061
2062 HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length,
2063                                              HValue* right_length) {
2064   // Compute the combined string length and check against max string length.
2065   HValue* length = AddUncasted<HAdd>(left_length, right_length);
2066   // Check that length <= kMaxLength <=> length < MaxLength + 1.
2067   HValue* max_length = Add<HConstant>(String::kMaxLength + 1);
2068   Add<HBoundsCheck>(length, max_length);
2069   return length;
2070 }
2071
2072
2073 HValue* HGraphBuilder::BuildCreateConsString(
2074     HValue* length,
2075     HValue* left,
2076     HValue* right,
2077     HAllocationMode allocation_mode) {
2078   // Determine the string instance types.
2079   HInstruction* left_instance_type = AddLoadStringInstanceType(left);
2080   HInstruction* right_instance_type = AddLoadStringInstanceType(right);
2081
2082   // Allocate the cons string object. HAllocate does not care whether we
2083   // pass CONS_STRING_TYPE or CONS_ONE_BYTE_STRING_TYPE here, so we just use
2084   // CONS_STRING_TYPE here. Below we decide whether the cons string is
2085   // one-byte or two-byte and set the appropriate map.
2086   DCHECK(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE,
2087                                             CONS_ONE_BYTE_STRING_TYPE));
2088   HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize),
2089                                     HType::String(), CONS_STRING_TYPE,
2090                                     allocation_mode);
2091
2092   // Compute intersection and difference of instance types.
2093   HValue* anded_instance_types = AddUncasted<HBitwise>(
2094       Token::BIT_AND, left_instance_type, right_instance_type);
2095   HValue* xored_instance_types = AddUncasted<HBitwise>(
2096       Token::BIT_XOR, left_instance_type, right_instance_type);
2097
2098   // We create a one-byte cons string if
2099   // 1. both strings are one-byte, or
2100   // 2. at least one of the strings is two-byte, but happens to contain only
2101   //    one-byte characters.
2102   // To do this, we check
2103   // 1. if both strings are one-byte, or if the one-byte data hint is set in
2104   //    both strings, or
2105   // 2. if one of the strings has the one-byte data hint set and the other
2106   //    string is one-byte.
2107   IfBuilder if_onebyte(this);
2108   STATIC_ASSERT(kOneByteStringTag != 0);
2109   STATIC_ASSERT(kOneByteDataHintMask != 0);
2110   if_onebyte.If<HCompareNumericAndBranch>(
2111       AddUncasted<HBitwise>(
2112           Token::BIT_AND, anded_instance_types,
2113           Add<HConstant>(static_cast<int32_t>(
2114                   kStringEncodingMask | kOneByteDataHintMask))),
2115       graph()->GetConstant0(), Token::NE);
2116   if_onebyte.Or();
2117   STATIC_ASSERT(kOneByteStringTag != 0 &&
2118                 kOneByteDataHintTag != 0 &&
2119                 kOneByteDataHintTag != kOneByteStringTag);
2120   if_onebyte.If<HCompareNumericAndBranch>(
2121       AddUncasted<HBitwise>(
2122           Token::BIT_AND, xored_instance_types,
2123           Add<HConstant>(static_cast<int32_t>(
2124                   kOneByteStringTag | kOneByteDataHintTag))),
2125       Add<HConstant>(static_cast<int32_t>(
2126               kOneByteStringTag | kOneByteDataHintTag)), Token::EQ);
2127   if_onebyte.Then();
2128   {
2129     // We can safely skip the write barrier for storing the map here.
2130     Add<HStoreNamedField>(
2131         result, HObjectAccess::ForMap(),
2132         Add<HConstant>(isolate()->factory()->cons_one_byte_string_map()));
2133   }
2134   if_onebyte.Else();
2135   {
2136     // We can safely skip the write barrier for storing the map here.
2137     Add<HStoreNamedField>(
2138         result, HObjectAccess::ForMap(),
2139         Add<HConstant>(isolate()->factory()->cons_string_map()));
2140   }
2141   if_onebyte.End();
2142
2143   // Initialize the cons string fields.
2144   Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2145                         Add<HConstant>(String::kEmptyHashField));
2146   Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2147   Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left);
2148   Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right);
2149
2150   // Count the native string addition.
2151   AddIncrementCounter(isolate()->counters()->string_add_native());
2152
2153   return result;
2154 }
2155
2156
2157 void HGraphBuilder::BuildCopySeqStringChars(HValue* src,
2158                                             HValue* src_offset,
2159                                             String::Encoding src_encoding,
2160                                             HValue* dst,
2161                                             HValue* dst_offset,
2162                                             String::Encoding dst_encoding,
2163                                             HValue* length) {
2164   DCHECK(dst_encoding != String::ONE_BYTE_ENCODING ||
2165          src_encoding == String::ONE_BYTE_ENCODING);
2166   LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
2167   HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT);
2168   {
2169     HValue* src_index = AddUncasted<HAdd>(src_offset, index);
2170     HValue* value =
2171         AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index);
2172     HValue* dst_index = AddUncasted<HAdd>(dst_offset, index);
2173     Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value);
2174   }
2175   loop.EndBody();
2176 }
2177
2178
2179 HValue* HGraphBuilder::BuildObjectSizeAlignment(
2180     HValue* unaligned_size, int header_size) {
2181   DCHECK((header_size & kObjectAlignmentMask) == 0);
2182   HValue* size = AddUncasted<HAdd>(
2183       unaligned_size, Add<HConstant>(static_cast<int32_t>(
2184           header_size + kObjectAlignmentMask)));
2185   size->ClearFlag(HValue::kCanOverflow);
2186   return AddUncasted<HBitwise>(
2187       Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>(
2188           ~kObjectAlignmentMask)));
2189 }
2190
2191
2192 HValue* HGraphBuilder::BuildUncheckedStringAdd(
2193     HValue* left,
2194     HValue* right,
2195     HAllocationMode allocation_mode) {
2196   // Determine the string lengths.
2197   HValue* left_length = AddLoadStringLength(left);
2198   HValue* right_length = AddLoadStringLength(right);
2199
2200   // Compute the combined string length.
2201   HValue* length = BuildAddStringLengths(left_length, right_length);
2202
2203   // Do some manual constant folding here.
2204   if (left_length->IsConstant()) {
2205     HConstant* c_left_length = HConstant::cast(left_length);
2206     DCHECK_NE(0, c_left_length->Integer32Value());
2207     if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2208       // The right string contains at least one character.
2209       return BuildCreateConsString(length, left, right, allocation_mode);
2210     }
2211   } else if (right_length->IsConstant()) {
2212     HConstant* c_right_length = HConstant::cast(right_length);
2213     DCHECK_NE(0, c_right_length->Integer32Value());
2214     if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) {
2215       // The left string contains at least one character.
2216       return BuildCreateConsString(length, left, right, allocation_mode);
2217     }
2218   }
2219
2220   // Check if we should create a cons string.
2221   IfBuilder if_createcons(this);
2222   if_createcons.If<HCompareNumericAndBranch>(
2223       length, Add<HConstant>(ConsString::kMinLength), Token::GTE);
2224   if_createcons.Then();
2225   {
2226     // Create a cons string.
2227     Push(BuildCreateConsString(length, left, right, allocation_mode));
2228   }
2229   if_createcons.Else();
2230   {
2231     // Determine the string instance types.
2232     HValue* left_instance_type = AddLoadStringInstanceType(left);
2233     HValue* right_instance_type = AddLoadStringInstanceType(right);
2234
2235     // Compute union and difference of instance types.
2236     HValue* ored_instance_types = AddUncasted<HBitwise>(
2237         Token::BIT_OR, left_instance_type, right_instance_type);
2238     HValue* xored_instance_types = AddUncasted<HBitwise>(
2239         Token::BIT_XOR, left_instance_type, right_instance_type);
2240
2241     // Check if both strings have the same encoding and both are
2242     // sequential.
2243     IfBuilder if_sameencodingandsequential(this);
2244     if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2245         AddUncasted<HBitwise>(
2246             Token::BIT_AND, xored_instance_types,
2247             Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2248         graph()->GetConstant0(), Token::EQ);
2249     if_sameencodingandsequential.And();
2250     STATIC_ASSERT(kSeqStringTag == 0);
2251     if_sameencodingandsequential.If<HCompareNumericAndBranch>(
2252         AddUncasted<HBitwise>(
2253             Token::BIT_AND, ored_instance_types,
2254             Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))),
2255         graph()->GetConstant0(), Token::EQ);
2256     if_sameencodingandsequential.Then();
2257     {
2258       HConstant* string_map =
2259           Add<HConstant>(isolate()->factory()->string_map());
2260       HConstant* one_byte_string_map =
2261           Add<HConstant>(isolate()->factory()->one_byte_string_map());
2262
2263       // Determine map and size depending on whether result is one-byte string.
2264       IfBuilder if_onebyte(this);
2265       STATIC_ASSERT(kOneByteStringTag != 0);
2266       if_onebyte.If<HCompareNumericAndBranch>(
2267           AddUncasted<HBitwise>(
2268               Token::BIT_AND, ored_instance_types,
2269               Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))),
2270           graph()->GetConstant0(), Token::NE);
2271       if_onebyte.Then();
2272       {
2273         // Allocate sequential one-byte string object.
2274         Push(length);
2275         Push(one_byte_string_map);
2276       }
2277       if_onebyte.Else();
2278       {
2279         // Allocate sequential two-byte string object.
2280         HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1());
2281         size->ClearFlag(HValue::kCanOverflow);
2282         size->SetFlag(HValue::kUint32);
2283         Push(size);
2284         Push(string_map);
2285       }
2286       if_onebyte.End();
2287       HValue* map = Pop();
2288
2289       // Calculate the number of bytes needed for the characters in the
2290       // string while observing object alignment.
2291       STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0);
2292       HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize);
2293
2294       // Allocate the string object. HAllocate does not care whether we pass
2295       // STRING_TYPE or ONE_BYTE_STRING_TYPE here, so we just use STRING_TYPE.
2296       HAllocate* result = BuildAllocate(
2297           size, HType::String(), STRING_TYPE, allocation_mode);
2298       Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map);
2299
2300       // Initialize the string fields.
2301       Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(),
2302                             Add<HConstant>(String::kEmptyHashField));
2303       Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length);
2304
2305       // Copy characters to the result string.
2306       IfBuilder if_twobyte(this);
2307       if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map);
2308       if_twobyte.Then();
2309       {
2310         // Copy characters from the left string.
2311         BuildCopySeqStringChars(
2312             left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2313             result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2314             left_length);
2315
2316         // Copy characters from the right string.
2317         BuildCopySeqStringChars(
2318             right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING,
2319             result, left_length, String::TWO_BYTE_ENCODING,
2320             right_length);
2321       }
2322       if_twobyte.Else();
2323       {
2324         // Copy characters from the left string.
2325         BuildCopySeqStringChars(
2326             left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2327             result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2328             left_length);
2329
2330         // Copy characters from the right string.
2331         BuildCopySeqStringChars(
2332             right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING,
2333             result, left_length, String::ONE_BYTE_ENCODING,
2334             right_length);
2335       }
2336       if_twobyte.End();
2337
2338       // Count the native string addition.
2339       AddIncrementCounter(isolate()->counters()->string_add_native());
2340
2341       // Return the sequential string.
2342       Push(result);
2343     }
2344     if_sameencodingandsequential.Else();
2345     {
2346       // Fallback to the runtime to add the two strings.
2347       Add<HPushArguments>(left, right);
2348       Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
2349                              Runtime::FunctionForId(Runtime::kStringAddRT), 2));
2350     }
2351     if_sameencodingandsequential.End();
2352   }
2353   if_createcons.End();
2354
2355   return Pop();
2356 }
2357
2358
2359 HValue* HGraphBuilder::BuildStringAdd(
2360     HValue* left,
2361     HValue* right,
2362     HAllocationMode allocation_mode) {
2363   NoObservableSideEffectsScope no_effects(this);
2364
2365   // Determine string lengths.
2366   HValue* left_length = AddLoadStringLength(left);
2367   HValue* right_length = AddLoadStringLength(right);
2368
2369   // Check if left string is empty.
2370   IfBuilder if_leftempty(this);
2371   if_leftempty.If<HCompareNumericAndBranch>(
2372       left_length, graph()->GetConstant0(), Token::EQ);
2373   if_leftempty.Then();
2374   {
2375     // Count the native string addition.
2376     AddIncrementCounter(isolate()->counters()->string_add_native());
2377
2378     // Just return the right string.
2379     Push(right);
2380   }
2381   if_leftempty.Else();
2382   {
2383     // Check if right string is empty.
2384     IfBuilder if_rightempty(this);
2385     if_rightempty.If<HCompareNumericAndBranch>(
2386         right_length, graph()->GetConstant0(), Token::EQ);
2387     if_rightempty.Then();
2388     {
2389       // Count the native string addition.
2390       AddIncrementCounter(isolate()->counters()->string_add_native());
2391
2392       // Just return the left string.
2393       Push(left);
2394     }
2395     if_rightempty.Else();
2396     {
2397       // Add the two non-empty strings.
2398       Push(BuildUncheckedStringAdd(left, right, allocation_mode));
2399     }
2400     if_rightempty.End();
2401   }
2402   if_leftempty.End();
2403
2404   return Pop();
2405 }
2406
2407
2408 HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess(
2409     HValue* checked_object,
2410     HValue* key,
2411     HValue* val,
2412     bool is_js_array,
2413     ElementsKind elements_kind,
2414     PropertyAccessType access_type,
2415     LoadKeyedHoleMode load_mode,
2416     KeyedAccessStoreMode store_mode) {
2417   DCHECK(top_info()->IsStub() || checked_object->IsCompareMap() ||
2418          checked_object->IsCheckMaps());
2419   DCHECK(!IsFixedTypedArrayElementsKind(elements_kind) || !is_js_array);
2420   // No GVNFlag is necessary for ElementsKind if there is an explicit dependency
2421   // on a HElementsTransition instruction. The flag can also be removed if the
2422   // map to check has FAST_HOLEY_ELEMENTS, since there can be no further
2423   // ElementsKind transitions. Finally, the dependency can be removed for stores
2424   // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the
2425   // generated store code.
2426   if ((elements_kind == FAST_HOLEY_ELEMENTS) ||
2427       (elements_kind == FAST_ELEMENTS && access_type == STORE)) {
2428     checked_object->ClearDependsOnFlag(kElementsKind);
2429   }
2430
2431   bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind);
2432   bool fast_elements = IsFastObjectElementsKind(elements_kind);
2433   HValue* elements = AddLoadElements(checked_object);
2434   if (access_type == STORE && (fast_elements || fast_smi_only_elements) &&
2435       store_mode != STORE_NO_TRANSITION_HANDLE_COW) {
2436     HCheckMaps* check_cow_map = Add<HCheckMaps>(
2437         elements, isolate()->factory()->fixed_array_map());
2438     check_cow_map->ClearDependsOnFlag(kElementsKind);
2439   }
2440   HInstruction* length = NULL;
2441   if (is_js_array) {
2442     length = Add<HLoadNamedField>(
2443         checked_object->ActualValue(), checked_object,
2444         HObjectAccess::ForArrayLength(elements_kind));
2445   } else {
2446     length = AddLoadFixedArrayLength(elements);
2447   }
2448   length->set_type(HType::Smi());
2449   HValue* checked_key = NULL;
2450   if (IsFixedTypedArrayElementsKind(elements_kind)) {
2451     checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
2452
2453     HValue* external_pointer = Add<HLoadNamedField>(
2454         elements, nullptr,
2455         HObjectAccess::ForFixedTypedArrayBaseExternalPointer());
2456     HValue* base_pointer = Add<HLoadNamedField>(
2457         elements, nullptr, HObjectAccess::ForFixedTypedArrayBaseBasePointer());
2458     HValue* backing_store = AddUncasted<HAdd>(
2459         external_pointer, base_pointer, Strength::WEAK, AddOfExternalAndTagged);
2460
2461     if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
2462       NoObservableSideEffectsScope no_effects(this);
2463       IfBuilder length_checker(this);
2464       length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT);
2465       length_checker.Then();
2466       IfBuilder negative_checker(this);
2467       HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>(
2468           key, graph()->GetConstant0(), Token::GTE);
2469       negative_checker.Then();
2470       HInstruction* result = AddElementAccess(
2471           backing_store, key, val, bounds_check, elements_kind, access_type);
2472       negative_checker.ElseDeopt(Deoptimizer::kNegativeKeyEncountered);
2473       negative_checker.End();
2474       length_checker.End();
2475       return result;
2476     } else {
2477       DCHECK(store_mode == STANDARD_STORE);
2478       checked_key = Add<HBoundsCheck>(key, length);
2479       return AddElementAccess(
2480           backing_store, checked_key, val,
2481           checked_object, elements_kind, access_type);
2482     }
2483   }
2484   DCHECK(fast_smi_only_elements ||
2485          fast_elements ||
2486          IsFastDoubleElementsKind(elements_kind));
2487
2488   // In case val is stored into a fast smi array, assure that the value is a smi
2489   // before manipulating the backing store. Otherwise the actual store may
2490   // deopt, leaving the backing store in an invalid state.
2491   if (access_type == STORE && IsFastSmiElementsKind(elements_kind) &&
2492       !val->type().IsSmi()) {
2493     val = AddUncasted<HForceRepresentation>(val, Representation::Smi());
2494   }
2495
2496   if (IsGrowStoreMode(store_mode)) {
2497     NoObservableSideEffectsScope no_effects(this);
2498     Representation representation = HStoreKeyed::RequiredValueRepresentation(
2499         elements_kind, STORE_TO_INITIALIZED_ENTRY);
2500     val = AddUncasted<HForceRepresentation>(val, representation);
2501     elements = BuildCheckForCapacityGrow(checked_object, elements,
2502                                          elements_kind, length, key,
2503                                          is_js_array, access_type);
2504     checked_key = key;
2505   } else {
2506     checked_key = Add<HBoundsCheck>(key, length);
2507
2508     if (access_type == STORE && (fast_elements || fast_smi_only_elements)) {
2509       if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) {
2510         NoObservableSideEffectsScope no_effects(this);
2511         elements = BuildCopyElementsOnWrite(checked_object, elements,
2512                                             elements_kind, length);
2513       } else {
2514         HCheckMaps* check_cow_map = Add<HCheckMaps>(
2515             elements, isolate()->factory()->fixed_array_map());
2516         check_cow_map->ClearDependsOnFlag(kElementsKind);
2517       }
2518     }
2519   }
2520   return AddElementAccess(elements, checked_key, val, checked_object,
2521                           elements_kind, access_type, load_mode);
2522 }
2523
2524
2525 HValue* HGraphBuilder::BuildAllocateArrayFromLength(
2526     JSArrayBuilder* array_builder,
2527     HValue* length_argument) {
2528   if (length_argument->IsConstant() &&
2529       HConstant::cast(length_argument)->HasSmiValue()) {
2530     int array_length = HConstant::cast(length_argument)->Integer32Value();
2531     if (array_length == 0) {
2532       return array_builder->AllocateEmptyArray();
2533     } else {
2534       return array_builder->AllocateArray(length_argument,
2535                                           array_length,
2536                                           length_argument);
2537     }
2538   }
2539
2540   HValue* constant_zero = graph()->GetConstant0();
2541   HConstant* max_alloc_length =
2542       Add<HConstant>(JSObject::kInitialMaxFastElementArray);
2543   HInstruction* checked_length = Add<HBoundsCheck>(length_argument,
2544                                                    max_alloc_length);
2545   IfBuilder if_builder(this);
2546   if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero,
2547                                           Token::EQ);
2548   if_builder.Then();
2549   const int initial_capacity = JSArray::kPreallocatedArrayElements;
2550   HConstant* initial_capacity_node = Add<HConstant>(initial_capacity);
2551   Push(initial_capacity_node);  // capacity
2552   Push(constant_zero);          // length
2553   if_builder.Else();
2554   if (!(top_info()->IsStub()) &&
2555       IsFastPackedElementsKind(array_builder->kind())) {
2556     // We'll come back later with better (holey) feedback.
2557     if_builder.Deopt(
2558         Deoptimizer::kHoleyArrayDespitePackedElements_kindFeedback);
2559   } else {
2560     Push(checked_length);         // capacity
2561     Push(checked_length);         // length
2562   }
2563   if_builder.End();
2564
2565   // Figure out total size
2566   HValue* length = Pop();
2567   HValue* capacity = Pop();
2568   return array_builder->AllocateArray(capacity, max_alloc_length, length);
2569 }
2570
2571
2572 HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind,
2573                                                   HValue* capacity) {
2574   int elements_size = IsFastDoubleElementsKind(kind)
2575       ? kDoubleSize
2576       : kPointerSize;
2577
2578   HConstant* elements_size_value = Add<HConstant>(elements_size);
2579   HInstruction* mul =
2580       HMul::NewImul(isolate(), zone(), context(), capacity->ActualValue(),
2581                     elements_size_value);
2582   AddInstruction(mul);
2583   mul->ClearFlag(HValue::kCanOverflow);
2584
2585   STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);
2586
2587   HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize);
2588   HValue* total_size = AddUncasted<HAdd>(mul, header_size);
2589   total_size->ClearFlag(HValue::kCanOverflow);
2590   return total_size;
2591 }
2592
2593
2594 HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) {
2595   int base_size = JSArray::kSize;
2596   if (mode == TRACK_ALLOCATION_SITE) {
2597     base_size += AllocationMemento::kSize;
2598   }
2599   HConstant* size_in_bytes = Add<HConstant>(base_size);
2600   return Add<HAllocate>(
2601       size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE);
2602 }
2603
2604
2605 HConstant* HGraphBuilder::EstablishElementsAllocationSize(
2606     ElementsKind kind,
2607     int capacity) {
2608   int base_size = IsFastDoubleElementsKind(kind)
2609       ? FixedDoubleArray::SizeFor(capacity)
2610       : FixedArray::SizeFor(capacity);
2611
2612   return Add<HConstant>(base_size);
2613 }
2614
2615
2616 HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind,
2617                                                 HValue* size_in_bytes) {
2618   InstanceType instance_type = IsFastDoubleElementsKind(kind)
2619       ? FIXED_DOUBLE_ARRAY_TYPE
2620       : FIXED_ARRAY_TYPE;
2621
2622   return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED,
2623                         instance_type);
2624 }
2625
2626
2627 void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements,
2628                                                   ElementsKind kind,
2629                                                   HValue* capacity) {
2630   Factory* factory = isolate()->factory();
2631   Handle<Map> map = IsFastDoubleElementsKind(kind)
2632       ? factory->fixed_double_array_map()
2633       : factory->fixed_array_map();
2634
2635   Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map));
2636   Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(),
2637                         capacity);
2638 }
2639
2640
2641 HValue* HGraphBuilder::BuildAllocateAndInitializeArray(ElementsKind kind,
2642                                                        HValue* capacity) {
2643   // The HForceRepresentation is to prevent possible deopt on int-smi
2644   // conversion after allocation but before the new object fields are set.
2645   capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi());
2646   HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity);
2647   HValue* new_array = BuildAllocateElements(kind, size_in_bytes);
2648   BuildInitializeElementsHeader(new_array, kind, capacity);
2649   return new_array;
2650 }
2651
2652
2653 void HGraphBuilder::BuildJSArrayHeader(HValue* array,
2654                                        HValue* array_map,
2655                                        HValue* elements,
2656                                        AllocationSiteMode mode,
2657                                        ElementsKind elements_kind,
2658                                        HValue* allocation_site_payload,
2659                                        HValue* length_field) {
2660   Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map);
2661
2662   HConstant* empty_fixed_array =
2663     Add<HConstant>(isolate()->factory()->empty_fixed_array());
2664
2665   Add<HStoreNamedField>(
2666       array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array);
2667
2668   Add<HStoreNamedField>(
2669       array, HObjectAccess::ForElementsPointer(),
2670       elements != NULL ? elements : empty_fixed_array);
2671
2672   Add<HStoreNamedField>(
2673       array, HObjectAccess::ForArrayLength(elements_kind), length_field);
2674
2675   if (mode == TRACK_ALLOCATION_SITE) {
2676     BuildCreateAllocationMemento(
2677         array, Add<HConstant>(JSArray::kSize), allocation_site_payload);
2678   }
2679 }
2680
2681
2682 HInstruction* HGraphBuilder::AddElementAccess(
2683     HValue* elements,
2684     HValue* checked_key,
2685     HValue* val,
2686     HValue* dependency,
2687     ElementsKind elements_kind,
2688     PropertyAccessType access_type,
2689     LoadKeyedHoleMode load_mode) {
2690   if (access_type == STORE) {
2691     DCHECK(val != NULL);
2692     if (elements_kind == UINT8_CLAMPED_ELEMENTS) {
2693       val = Add<HClampToUint8>(val);
2694     }
2695     return Add<HStoreKeyed>(elements, checked_key, val, elements_kind,
2696                             STORE_TO_INITIALIZED_ENTRY);
2697   }
2698
2699   DCHECK(access_type == LOAD);
2700   DCHECK(val == NULL);
2701   HLoadKeyed* load = Add<HLoadKeyed>(
2702       elements, checked_key, dependency, elements_kind, load_mode);
2703   if (elements_kind == UINT32_ELEMENTS) {
2704     graph()->RecordUint32Instruction(load);
2705   }
2706   return load;
2707 }
2708
2709
2710 HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object,
2711                                            HValue* dependency) {
2712   return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap());
2713 }
2714
2715
2716 HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object,
2717                                                 HValue* dependency) {
2718   return Add<HLoadNamedField>(
2719       object, dependency, HObjectAccess::ForElementsPointer());
2720 }
2721
2722
2723 HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength(
2724     HValue* array,
2725     HValue* dependency) {
2726   return Add<HLoadNamedField>(
2727       array, dependency, HObjectAccess::ForFixedArrayLength());
2728 }
2729
2730
2731 HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array,
2732                                                    ElementsKind kind,
2733                                                    HValue* dependency) {
2734   return Add<HLoadNamedField>(
2735       array, dependency, HObjectAccess::ForArrayLength(kind));
2736 }
2737
2738
2739 HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) {
2740   HValue* half_old_capacity = AddUncasted<HShr>(old_capacity,
2741                                                 graph_->GetConstant1());
2742
2743   HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity);
2744   new_capacity->ClearFlag(HValue::kCanOverflow);
2745
2746   HValue* min_growth = Add<HConstant>(16);
2747
2748   new_capacity = AddUncasted<HAdd>(new_capacity, min_growth);
2749   new_capacity->ClearFlag(HValue::kCanOverflow);
2750
2751   return new_capacity;
2752 }
2753
2754
2755 HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object,
2756                                                  HValue* elements,
2757                                                  ElementsKind kind,
2758                                                  ElementsKind new_kind,
2759                                                  HValue* length,
2760                                                  HValue* new_capacity) {
2761   Add<HBoundsCheck>(new_capacity, Add<HConstant>(
2762           (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >>
2763           ElementsKindToShiftSize(new_kind)));
2764
2765   HValue* new_elements =
2766       BuildAllocateAndInitializeArray(new_kind, new_capacity);
2767
2768   BuildCopyElements(elements, kind, new_elements,
2769                     new_kind, length, new_capacity);
2770
2771   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
2772                         new_elements);
2773
2774   return new_elements;
2775 }
2776
2777
2778 void HGraphBuilder::BuildFillElementsWithValue(HValue* elements,
2779                                                ElementsKind elements_kind,
2780                                                HValue* from,
2781                                                HValue* to,
2782                                                HValue* value) {
2783   if (to == NULL) {
2784     to = AddLoadFixedArrayLength(elements);
2785   }
2786
2787   // Special loop unfolding case
2788   STATIC_ASSERT(JSArray::kPreallocatedArrayElements <=
2789                 kElementLoopUnrollThreshold);
2790   int initial_capacity = -1;
2791   if (from->IsInteger32Constant() && to->IsInteger32Constant()) {
2792     int constant_from = from->GetInteger32Constant();
2793     int constant_to = to->GetInteger32Constant();
2794
2795     if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) {
2796       initial_capacity = constant_to;
2797     }
2798   }
2799
2800   if (initial_capacity >= 0) {
2801     for (int i = 0; i < initial_capacity; i++) {
2802       HInstruction* key = Add<HConstant>(i);
2803       Add<HStoreKeyed>(elements, key, value, elements_kind);
2804     }
2805   } else {
2806     // Carefully loop backwards so that the "from" remains live through the loop
2807     // rather than the to. This often corresponds to keeping length live rather
2808     // then capacity, which helps register allocation, since length is used more
2809     // other than capacity after filling with holes.
2810     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2811
2812     HValue* key = builder.BeginBody(to, from, Token::GT);
2813
2814     HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1());
2815     adjusted_key->ClearFlag(HValue::kCanOverflow);
2816
2817     Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind);
2818
2819     builder.EndBody();
2820   }
2821 }
2822
2823
2824 void HGraphBuilder::BuildFillElementsWithHole(HValue* elements,
2825                                               ElementsKind elements_kind,
2826                                               HValue* from,
2827                                               HValue* to) {
2828   // Fast elements kinds need to be initialized in case statements below cause a
2829   // garbage collection.
2830
2831   HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
2832                      ? graph()->GetConstantHole()
2833                      : Add<HConstant>(HConstant::kHoleNaN);
2834
2835   // Since we're about to store a hole value, the store instruction below must
2836   // assume an elements kind that supports heap object values.
2837   if (IsFastSmiOrObjectElementsKind(elements_kind)) {
2838     elements_kind = FAST_HOLEY_ELEMENTS;
2839   }
2840
2841   BuildFillElementsWithValue(elements, elements_kind, from, to, hole);
2842 }
2843
2844
2845 void HGraphBuilder::BuildCopyProperties(HValue* from_properties,
2846                                         HValue* to_properties, HValue* length,
2847                                         HValue* capacity) {
2848   ElementsKind kind = FAST_ELEMENTS;
2849
2850   BuildFillElementsWithValue(to_properties, kind, length, capacity,
2851                              graph()->GetConstantUndefined());
2852
2853   LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2854
2855   HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT);
2856
2857   key = AddUncasted<HSub>(key, graph()->GetConstant1());
2858   key->ClearFlag(HValue::kCanOverflow);
2859
2860   HValue* element = Add<HLoadKeyed>(from_properties, key, nullptr, kind);
2861
2862   Add<HStoreKeyed>(to_properties, key, element, kind);
2863
2864   builder.EndBody();
2865 }
2866
2867
2868 void HGraphBuilder::BuildCopyElements(HValue* from_elements,
2869                                       ElementsKind from_elements_kind,
2870                                       HValue* to_elements,
2871                                       ElementsKind to_elements_kind,
2872                                       HValue* length,
2873                                       HValue* capacity) {
2874   int constant_capacity = -1;
2875   if (capacity != NULL &&
2876       capacity->IsConstant() &&
2877       HConstant::cast(capacity)->HasInteger32Value()) {
2878     int constant_candidate = HConstant::cast(capacity)->Integer32Value();
2879     if (constant_candidate <= kElementLoopUnrollThreshold) {
2880       constant_capacity = constant_candidate;
2881     }
2882   }
2883
2884   bool pre_fill_with_holes =
2885     IsFastDoubleElementsKind(from_elements_kind) &&
2886     IsFastObjectElementsKind(to_elements_kind);
2887   if (pre_fill_with_holes) {
2888     // If the copy might trigger a GC, make sure that the FixedArray is
2889     // pre-initialized with holes to make sure that it's always in a
2890     // consistent state.
2891     BuildFillElementsWithHole(to_elements, to_elements_kind,
2892                               graph()->GetConstant0(), NULL);
2893   }
2894
2895   if (constant_capacity != -1) {
2896     // Unroll the loop for small elements kinds.
2897     for (int i = 0; i < constant_capacity; i++) {
2898       HValue* key_constant = Add<HConstant>(i);
2899       HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant,
2900                                             nullptr, from_elements_kind);
2901       Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind);
2902     }
2903   } else {
2904     if (!pre_fill_with_holes &&
2905         (capacity == NULL || !length->Equals(capacity))) {
2906       BuildFillElementsWithHole(to_elements, to_elements_kind,
2907                                 length, NULL);
2908     }
2909
2910     LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement);
2911
2912     HValue* key = builder.BeginBody(length, graph()->GetConstant0(),
2913                                     Token::GT);
2914
2915     key = AddUncasted<HSub>(key, graph()->GetConstant1());
2916     key->ClearFlag(HValue::kCanOverflow);
2917
2918     HValue* element = Add<HLoadKeyed>(from_elements, key, nullptr,
2919                                       from_elements_kind, ALLOW_RETURN_HOLE);
2920
2921     ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) &&
2922                          IsFastSmiElementsKind(to_elements_kind))
2923       ? FAST_HOLEY_ELEMENTS : to_elements_kind;
2924
2925     if (IsHoleyElementsKind(from_elements_kind) &&
2926         from_elements_kind != to_elements_kind) {
2927       IfBuilder if_hole(this);
2928       if_hole.If<HCompareHoleAndBranch>(element);
2929       if_hole.Then();
2930       HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind)
2931                                      ? Add<HConstant>(HConstant::kHoleNaN)
2932                                      : graph()->GetConstantHole();
2933       Add<HStoreKeyed>(to_elements, key, hole_constant, kind);
2934       if_hole.Else();
2935       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2936       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2937       if_hole.End();
2938     } else {
2939       HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind);
2940       store->SetFlag(HValue::kAllowUndefinedAsNaN);
2941     }
2942
2943     builder.EndBody();
2944   }
2945
2946   Counters* counters = isolate()->counters();
2947   AddIncrementCounter(counters->inlined_copied_elements());
2948 }
2949
2950
2951 HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate,
2952                                                  HValue* allocation_site,
2953                                                  AllocationSiteMode mode,
2954                                                  ElementsKind kind) {
2955   HAllocate* array = AllocateJSArrayObject(mode);
2956
2957   HValue* map = AddLoadMap(boilerplate);
2958   HValue* elements = AddLoadElements(boilerplate);
2959   HValue* length = AddLoadArrayLength(boilerplate, kind);
2960
2961   BuildJSArrayHeader(array,
2962                      map,
2963                      elements,
2964                      mode,
2965                      FAST_ELEMENTS,
2966                      allocation_site,
2967                      length);
2968   return array;
2969 }
2970
2971
2972 HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate,
2973                                                    HValue* allocation_site,
2974                                                    AllocationSiteMode mode) {
2975   HAllocate* array = AllocateJSArrayObject(mode);
2976
2977   HValue* map = AddLoadMap(boilerplate);
2978
2979   BuildJSArrayHeader(array,
2980                      map,
2981                      NULL,  // set elements to empty fixed array
2982                      mode,
2983                      FAST_ELEMENTS,
2984                      allocation_site,
2985                      graph()->GetConstant0());
2986   return array;
2987 }
2988
2989
2990 HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
2991                                                       HValue* allocation_site,
2992                                                       AllocationSiteMode mode,
2993                                                       ElementsKind kind) {
2994   HValue* boilerplate_elements = AddLoadElements(boilerplate);
2995   HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements);
2996
2997   // Generate size calculation code here in order to make it dominate
2998   // the JSArray allocation.
2999   HValue* elements_size = BuildCalculateElementsSize(kind, capacity);
3000
3001   // Create empty JSArray object for now, store elimination should remove
3002   // redundant initialization of elements and length fields and at the same
3003   // time the object will be fully prepared for GC if it happens during
3004   // elements allocation.
3005   HValue* result = BuildCloneShallowArrayEmpty(
3006       boilerplate, allocation_site, mode);
3007
3008   HAllocate* elements = BuildAllocateElements(kind, elements_size);
3009
3010   // This function implicitly relies on the fact that the
3011   // FastCloneShallowArrayStub is called only for literals shorter than
3012   // JSObject::kInitialMaxFastElementArray.
3013   // Can't add HBoundsCheck here because otherwise the stub will eager a frame.
3014   HConstant* size_upper_bound = EstablishElementsAllocationSize(
3015       kind, JSObject::kInitialMaxFastElementArray);
3016   elements->set_size_upper_bound(size_upper_bound);
3017
3018   Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements);
3019
3020   // The allocation for the cloned array above causes register pressure on
3021   // machines with low register counts. Force a reload of the boilerplate
3022   // elements here to free up a register for the allocation to avoid unnecessary
3023   // spillage.
3024   boilerplate_elements = AddLoadElements(boilerplate);
3025   boilerplate_elements->SetFlag(HValue::kCantBeReplaced);
3026
3027   // Copy the elements array header.
3028   for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) {
3029     HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i);
3030     Add<HStoreNamedField>(
3031         elements, access,
3032         Add<HLoadNamedField>(boilerplate_elements, nullptr, access));
3033   }
3034
3035   // And the result of the length
3036   HValue* length = AddLoadArrayLength(boilerplate, kind);
3037   Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length);
3038
3039   BuildCopyElements(boilerplate_elements, kind, elements,
3040                     kind, length, NULL);
3041   return result;
3042 }
3043
3044
3045 void HGraphBuilder::BuildCompareNil(HValue* value, Type* type,
3046                                     HIfContinuation* continuation,
3047                                     MapEmbedding map_embedding) {
3048   IfBuilder if_nil(this);
3049   bool some_case_handled = false;
3050   bool some_case_missing = false;
3051
3052   if (type->Maybe(Type::Null())) {
3053     if (some_case_handled) if_nil.Or();
3054     if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull());
3055     some_case_handled = true;
3056   } else {
3057     some_case_missing = true;
3058   }
3059
3060   if (type->Maybe(Type::Undefined())) {
3061     if (some_case_handled) if_nil.Or();
3062     if_nil.If<HCompareObjectEqAndBranch>(value,
3063                                          graph()->GetConstantUndefined());
3064     some_case_handled = true;
3065   } else {
3066     some_case_missing = true;
3067   }
3068
3069   if (type->Maybe(Type::Undetectable())) {
3070     if (some_case_handled) if_nil.Or();
3071     if_nil.If<HIsUndetectableAndBranch>(value);
3072     some_case_handled = true;
3073   } else {
3074     some_case_missing = true;
3075   }
3076
3077   if (some_case_missing) {
3078     if_nil.Then();
3079     if_nil.Else();
3080     if (type->NumClasses() == 1) {
3081       BuildCheckHeapObject(value);
3082       // For ICs, the map checked below is a sentinel map that gets replaced by
3083       // the monomorphic map when the code is used as a template to generate a
3084       // new IC. For optimized functions, there is no sentinel map, the map
3085       // emitted below is the actual monomorphic map.
3086       if (map_embedding == kEmbedMapsViaWeakCells) {
3087         HValue* cell =
3088             Add<HConstant>(Map::WeakCellForMap(type->Classes().Current()));
3089         HValue* expected_map = Add<HLoadNamedField>(
3090             cell, nullptr, HObjectAccess::ForWeakCellValue());
3091         HValue* map =
3092             Add<HLoadNamedField>(value, nullptr, HObjectAccess::ForMap());
3093         IfBuilder map_check(this);
3094         map_check.IfNot<HCompareObjectEqAndBranch>(expected_map, map);
3095         map_check.ThenDeopt(Deoptimizer::kUnknownMap);
3096         map_check.End();
3097       } else {
3098         DCHECK(map_embedding == kEmbedMapsDirectly);
3099         Add<HCheckMaps>(value, type->Classes().Current());
3100       }
3101     } else {
3102       if_nil.Deopt(Deoptimizer::kTooManyUndetectableTypes);
3103     }
3104   }
3105
3106   if_nil.CaptureContinuation(continuation);
3107 }
3108
3109
3110 void HGraphBuilder::BuildCreateAllocationMemento(
3111     HValue* previous_object,
3112     HValue* previous_object_size,
3113     HValue* allocation_site) {
3114   DCHECK(allocation_site != NULL);
3115   HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>(
3116       previous_object, previous_object_size, HType::HeapObject());
3117   AddStoreMapConstant(
3118       allocation_memento, isolate()->factory()->allocation_memento_map());
3119   Add<HStoreNamedField>(
3120       allocation_memento,
3121       HObjectAccess::ForAllocationMementoSite(),
3122       allocation_site);
3123   if (FLAG_allocation_site_pretenuring) {
3124     HValue* memento_create_count =
3125         Add<HLoadNamedField>(allocation_site, nullptr,
3126                              HObjectAccess::ForAllocationSiteOffset(
3127                                  AllocationSite::kPretenureCreateCountOffset));
3128     memento_create_count = AddUncasted<HAdd>(
3129         memento_create_count, graph()->GetConstant1());
3130     // This smi value is reset to zero after every gc, overflow isn't a problem
3131     // since the counter is bounded by the new space size.
3132     memento_create_count->ClearFlag(HValue::kCanOverflow);
3133     Add<HStoreNamedField>(
3134         allocation_site, HObjectAccess::ForAllocationSiteOffset(
3135             AllocationSite::kPretenureCreateCountOffset), memento_create_count);
3136   }
3137 }
3138
3139
3140 HInstruction* HGraphBuilder::BuildGetNativeContext() {
3141   // Get the global object, then the native context
3142   HValue* global_object = Add<HLoadNamedField>(
3143       context(), nullptr,
3144       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3145   return Add<HLoadNamedField>(global_object, nullptr,
3146                               HObjectAccess::ForObservableJSObjectOffset(
3147                                   GlobalObject::kNativeContextOffset));
3148 }
3149
3150
3151 HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) {
3152   // Get the global object, then the native context
3153   HInstruction* context = Add<HLoadNamedField>(
3154       closure, nullptr, HObjectAccess::ForFunctionContextPointer());
3155   HInstruction* global_object = Add<HLoadNamedField>(
3156       context, nullptr,
3157       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3158   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3159       GlobalObject::kNativeContextOffset);
3160   return Add<HLoadNamedField>(global_object, nullptr, access);
3161 }
3162
3163
3164 HInstruction* HGraphBuilder::BuildGetScriptContext(int context_index) {
3165   HValue* native_context = BuildGetNativeContext();
3166   HValue* script_context_table = Add<HLoadNamedField>(
3167       native_context, nullptr,
3168       HObjectAccess::ForContextSlot(Context::SCRIPT_CONTEXT_TABLE_INDEX));
3169   return Add<HLoadNamedField>(script_context_table, nullptr,
3170                               HObjectAccess::ForScriptContext(context_index));
3171 }
3172
3173
3174 HValue* HGraphBuilder::BuildGetParentContext(HValue* depth, int depth_value) {
3175   HValue* script_context = context();
3176   if (depth != NULL) {
3177     HValue* zero = graph()->GetConstant0();
3178
3179     Push(script_context);
3180     Push(depth);
3181
3182     LoopBuilder loop(this);
3183     loop.BeginBody(2);  // Drop script_context and depth from last environment
3184                         // to appease live range building without simulates.
3185     depth = Pop();
3186     script_context = Pop();
3187
3188     script_context = Add<HLoadNamedField>(
3189         script_context, nullptr,
3190         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3191     depth = AddUncasted<HSub>(depth, graph()->GetConstant1());
3192     depth->ClearFlag(HValue::kCanOverflow);
3193
3194     IfBuilder if_break(this);
3195     if_break.If<HCompareNumericAndBranch, HValue*>(depth, zero, Token::EQ);
3196     if_break.Then();
3197     {
3198       Push(script_context);  // The result.
3199       loop.Break();
3200     }
3201     if_break.Else();
3202     {
3203       Push(script_context);
3204       Push(depth);
3205     }
3206     loop.EndBody();
3207     if_break.End();
3208
3209     script_context = Pop();
3210   } else if (depth_value > 0) {
3211     // Unroll the above loop.
3212     for (int i = 0; i < depth_value; i++) {
3213       script_context = Add<HLoadNamedField>(
3214           script_context, nullptr,
3215           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
3216     }
3217   }
3218   return script_context;
3219 }
3220
3221
3222 HInstruction* HGraphBuilder::BuildGetArrayFunction() {
3223   HInstruction* native_context = BuildGetNativeContext();
3224   HInstruction* index =
3225       Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX));
3226   return Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3227 }
3228
3229
3230 HValue* HGraphBuilder::BuildArrayBufferViewFieldAccessor(HValue* object,
3231                                                          HValue* checked_object,
3232                                                          FieldIndex index) {
3233   NoObservableSideEffectsScope scope(this);
3234   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3235       index.offset(), Representation::Tagged());
3236   HInstruction* buffer = Add<HLoadNamedField>(
3237       object, checked_object, HObjectAccess::ForJSArrayBufferViewBuffer());
3238   HInstruction* field = Add<HLoadNamedField>(object, checked_object, access);
3239
3240   HInstruction* flags = Add<HLoadNamedField>(
3241       buffer, nullptr, HObjectAccess::ForJSArrayBufferBitField());
3242   HValue* was_neutered_mask =
3243       Add<HConstant>(1 << JSArrayBuffer::WasNeutered::kShift);
3244   HValue* was_neutered_test =
3245       AddUncasted<HBitwise>(Token::BIT_AND, flags, was_neutered_mask);
3246
3247   IfBuilder if_was_neutered(this);
3248   if_was_neutered.If<HCompareNumericAndBranch>(
3249       was_neutered_test, graph()->GetConstant0(), Token::NE);
3250   if_was_neutered.Then();
3251   Push(graph()->GetConstant0());
3252   if_was_neutered.Else();
3253   Push(field);
3254   if_was_neutered.End();
3255
3256   return Pop();
3257 }
3258
3259
3260 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3261     ElementsKind kind,
3262     HValue* allocation_site_payload,
3263     HValue* constructor_function,
3264     AllocationSiteOverrideMode override_mode) :
3265         builder_(builder),
3266         kind_(kind),
3267         allocation_site_payload_(allocation_site_payload),
3268         constructor_function_(constructor_function) {
3269   DCHECK(!allocation_site_payload->IsConstant() ||
3270          HConstant::cast(allocation_site_payload)->handle(
3271              builder_->isolate())->IsAllocationSite());
3272   mode_ = override_mode == DISABLE_ALLOCATION_SITES
3273       ? DONT_TRACK_ALLOCATION_SITE
3274       : AllocationSite::GetMode(kind);
3275 }
3276
3277
3278 HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder,
3279                                               ElementsKind kind,
3280                                               HValue* constructor_function) :
3281     builder_(builder),
3282     kind_(kind),
3283     mode_(DONT_TRACK_ALLOCATION_SITE),
3284     allocation_site_payload_(NULL),
3285     constructor_function_(constructor_function) {
3286 }
3287
3288
3289 HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() {
3290   if (!builder()->top_info()->IsStub()) {
3291     // A constant map is fine.
3292     Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_),
3293                     builder()->isolate());
3294     return builder()->Add<HConstant>(map);
3295   }
3296
3297   if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) {
3298     // No need for a context lookup if the kind_ matches the initial
3299     // map, because we can just load the map in that case.
3300     HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3301     return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3302                                            access);
3303   }
3304
3305   // TODO(mvstanton): we should always have a constructor function if we
3306   // are creating a stub.
3307   HInstruction* native_context = constructor_function_ != NULL
3308       ? builder()->BuildGetNativeContext(constructor_function_)
3309       : builder()->BuildGetNativeContext();
3310
3311   HInstruction* index = builder()->Add<HConstant>(
3312       static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX));
3313
3314   HInstruction* map_array =
3315       builder()->Add<HLoadKeyed>(native_context, index, nullptr, FAST_ELEMENTS);
3316
3317   HInstruction* kind_index = builder()->Add<HConstant>(kind_);
3318
3319   return builder()->Add<HLoadKeyed>(map_array, kind_index, nullptr,
3320                                     FAST_ELEMENTS);
3321 }
3322
3323
3324 HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() {
3325   // Find the map near the constructor function
3326   HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap();
3327   return builder()->Add<HLoadNamedField>(constructor_function_, nullptr,
3328                                          access);
3329 }
3330
3331
3332 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() {
3333   HConstant* capacity = builder()->Add<HConstant>(initial_capacity());
3334   return AllocateArray(capacity,
3335                        capacity,
3336                        builder()->graph()->GetConstant0());
3337 }
3338
3339
3340 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3341     HValue* capacity,
3342     HConstant* capacity_upper_bound,
3343     HValue* length_field,
3344     FillMode fill_mode) {
3345   return AllocateArray(capacity,
3346                        capacity_upper_bound->GetInteger32Constant(),
3347                        length_field,
3348                        fill_mode);
3349 }
3350
3351
3352 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3353     HValue* capacity,
3354     int capacity_upper_bound,
3355     HValue* length_field,
3356     FillMode fill_mode) {
3357   HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant()
3358       ? HConstant::cast(capacity)
3359       : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound);
3360
3361   HAllocate* array = AllocateArray(capacity, length_field, fill_mode);
3362   if (!elements_location_->has_size_upper_bound()) {
3363     elements_location_->set_size_upper_bound(elememts_size_upper_bound);
3364   }
3365   return array;
3366 }
3367
3368
3369 HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray(
3370     HValue* capacity,
3371     HValue* length_field,
3372     FillMode fill_mode) {
3373   // These HForceRepresentations are because we store these as fields in the
3374   // objects we construct, and an int32-to-smi HChange could deopt. Accept
3375   // the deopt possibility now, before allocation occurs.
3376   capacity =
3377       builder()->AddUncasted<HForceRepresentation>(capacity,
3378                                                    Representation::Smi());
3379   length_field =
3380       builder()->AddUncasted<HForceRepresentation>(length_field,
3381                                                    Representation::Smi());
3382
3383   // Generate size calculation code here in order to make it dominate
3384   // the JSArray allocation.
3385   HValue* elements_size =
3386       builder()->BuildCalculateElementsSize(kind_, capacity);
3387
3388   // Allocate (dealing with failure appropriately)
3389   HAllocate* array_object = builder()->AllocateJSArrayObject(mode_);
3390
3391   // Fill in the fields: map, properties, length
3392   HValue* map;
3393   if (allocation_site_payload_ == NULL) {
3394     map = EmitInternalMapCode();
3395   } else {
3396     map = EmitMapCode();
3397   }
3398
3399   builder()->BuildJSArrayHeader(array_object,
3400                                 map,
3401                                 NULL,  // set elements to empty fixed array
3402                                 mode_,
3403                                 kind_,
3404                                 allocation_site_payload_,
3405                                 length_field);
3406
3407   // Allocate and initialize the elements
3408   elements_location_ = builder()->BuildAllocateElements(kind_, elements_size);
3409
3410   builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity);
3411
3412   // Set the elements
3413   builder()->Add<HStoreNamedField>(
3414       array_object, HObjectAccess::ForElementsPointer(), elements_location_);
3415
3416   if (fill_mode == FILL_WITH_HOLE) {
3417     builder()->BuildFillElementsWithHole(elements_location_, kind_,
3418                                          graph()->GetConstant0(), capacity);
3419   }
3420
3421   return array_object;
3422 }
3423
3424
3425 HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) {
3426   HValue* global_object = Add<HLoadNamedField>(
3427       context(), nullptr,
3428       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
3429   HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(
3430       GlobalObject::kBuiltinsOffset);
3431   HValue* builtins = Add<HLoadNamedField>(global_object, nullptr, access);
3432   HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset(
3433           JSBuiltinsObject::OffsetOfFunctionWithId(builtin));
3434   return Add<HLoadNamedField>(builtins, nullptr, function_access);
3435 }
3436
3437
3438 HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info)
3439     : HGraphBuilder(info),
3440       function_state_(NULL),
3441       initial_function_state_(this, info, NORMAL_RETURN, 0),
3442       ast_context_(NULL),
3443       break_scope_(NULL),
3444       inlined_count_(0),
3445       globals_(10, info->zone()),
3446       osr_(new(info->zone()) HOsrBuilder(this)) {
3447   // This is not initialized in the initializer list because the
3448   // constructor for the initial state relies on function_state_ == NULL
3449   // to know it's the initial state.
3450   function_state_ = &initial_function_state_;
3451   InitializeAstVisitor(info->isolate(), info->zone());
3452   if (top_info()->is_tracking_positions()) {
3453     SetSourcePosition(info->shared_info()->start_position());
3454   }
3455 }
3456
3457
3458 HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first,
3459                                                 HBasicBlock* second,
3460                                                 BailoutId join_id) {
3461   if (first == NULL) {
3462     return second;
3463   } else if (second == NULL) {
3464     return first;
3465   } else {
3466     HBasicBlock* join_block = graph()->CreateBasicBlock();
3467     Goto(first, join_block);
3468     Goto(second, join_block);
3469     join_block->SetJoinId(join_id);
3470     return join_block;
3471   }
3472 }
3473
3474
3475 HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement,
3476                                                   HBasicBlock* exit_block,
3477                                                   HBasicBlock* continue_block) {
3478   if (continue_block != NULL) {
3479     if (exit_block != NULL) Goto(exit_block, continue_block);
3480     continue_block->SetJoinId(statement->ContinueId());
3481     return continue_block;
3482   }
3483   return exit_block;
3484 }
3485
3486
3487 HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement,
3488                                                 HBasicBlock* loop_entry,
3489                                                 HBasicBlock* body_exit,
3490                                                 HBasicBlock* loop_successor,
3491                                                 HBasicBlock* break_block) {
3492   if (body_exit != NULL) Goto(body_exit, loop_entry);
3493   loop_entry->PostProcessLoopHeader(statement);
3494   if (break_block != NULL) {
3495     if (loop_successor != NULL) Goto(loop_successor, break_block);
3496     break_block->SetJoinId(statement->ExitId());
3497     return break_block;
3498   }
3499   return loop_successor;
3500 }
3501
3502
3503 // Build a new loop header block and set it as the current block.
3504 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() {
3505   HBasicBlock* loop_entry = CreateLoopHeaderBlock();
3506   Goto(loop_entry);
3507   set_current_block(loop_entry);
3508   return loop_entry;
3509 }
3510
3511
3512 HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry(
3513     IterationStatement* statement) {
3514   HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement)
3515       ? osr()->BuildOsrLoopEntry(statement)
3516       : BuildLoopEntry();
3517   return loop_entry;
3518 }
3519
3520
3521 void HBasicBlock::FinishExit(HControlInstruction* instruction,
3522                              SourcePosition position) {
3523   Finish(instruction, position);
3524   ClearEnvironment();
3525 }
3526
3527
3528 std::ostream& operator<<(std::ostream& os, const HBasicBlock& b) {
3529   return os << "B" << b.block_id();
3530 }
3531
3532
3533 HGraph::HGraph(CompilationInfo* info)
3534     : isolate_(info->isolate()),
3535       next_block_id_(0),
3536       entry_block_(NULL),
3537       blocks_(8, info->zone()),
3538       values_(16, info->zone()),
3539       phi_list_(NULL),
3540       uint32_instructions_(NULL),
3541       osr_(NULL),
3542       info_(info),
3543       zone_(info->zone()),
3544       is_recursive_(false),
3545       use_optimistic_licm_(false),
3546       depends_on_empty_array_proto_elements_(false),
3547       type_change_checksum_(0),
3548       maximum_environment_size_(0),
3549       no_side_effects_scope_count_(0),
3550       disallow_adding_new_values_(false) {
3551   if (info->IsStub()) {
3552     CallInterfaceDescriptor descriptor =
3553         info->code_stub()->GetCallInterfaceDescriptor();
3554     start_environment_ =
3555         new (zone_) HEnvironment(zone_, descriptor.GetRegisterParameterCount());
3556   } else {
3557     if (info->is_tracking_positions()) {
3558       info->TraceInlinedFunction(info->shared_info(), SourcePosition::Unknown(),
3559                                  InlinedFunctionInfo::kNoParentId);
3560     }
3561     start_environment_ =
3562         new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_);
3563   }
3564   start_environment_->set_ast_id(BailoutId::FunctionEntry());
3565   entry_block_ = CreateBasicBlock();
3566   entry_block_->SetInitialEnvironment(start_environment_);
3567 }
3568
3569
3570 HBasicBlock* HGraph::CreateBasicBlock() {
3571   HBasicBlock* result = new(zone()) HBasicBlock(this);
3572   blocks_.Add(result, zone());
3573   return result;
3574 }
3575
3576
3577 void HGraph::FinalizeUniqueness() {
3578   DisallowHeapAllocation no_gc;
3579   for (int i = 0; i < blocks()->length(); ++i) {
3580     for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) {
3581       it.Current()->FinalizeUniqueness();
3582     }
3583   }
3584 }
3585
3586
3587 int HGraph::SourcePositionToScriptPosition(SourcePosition pos) {
3588   return (FLAG_hydrogen_track_positions && !pos.IsUnknown())
3589              ? info()->start_position_for(pos.inlining_id()) + pos.position()
3590              : pos.raw();
3591 }
3592
3593
3594 // Block ordering was implemented with two mutually recursive methods,
3595 // HGraph::Postorder and HGraph::PostorderLoopBlocks.
3596 // The recursion could lead to stack overflow so the algorithm has been
3597 // implemented iteratively.
3598 // At a high level the algorithm looks like this:
3599 //
3600 // Postorder(block, loop_header) : {
3601 //   if (block has already been visited or is of another loop) return;
3602 //   mark block as visited;
3603 //   if (block is a loop header) {
3604 //     VisitLoopMembers(block, loop_header);
3605 //     VisitSuccessorsOfLoopHeader(block);
3606 //   } else {
3607 //     VisitSuccessors(block)
3608 //   }
3609 //   put block in result list;
3610 // }
3611 //
3612 // VisitLoopMembers(block, outer_loop_header) {
3613 //   foreach (block b in block loop members) {
3614 //     VisitSuccessorsOfLoopMember(b, outer_loop_header);
3615 //     if (b is loop header) VisitLoopMembers(b);
3616 //   }
3617 // }
3618 //
3619 // VisitSuccessorsOfLoopMember(block, outer_loop_header) {
3620 //   foreach (block b in block successors) Postorder(b, outer_loop_header)
3621 // }
3622 //
3623 // VisitSuccessorsOfLoopHeader(block) {
3624 //   foreach (block b in block successors) Postorder(b, block)
3625 // }
3626 //
3627 // VisitSuccessors(block, loop_header) {
3628 //   foreach (block b in block successors) Postorder(b, loop_header)
3629 // }
3630 //
3631 // The ordering is started calling Postorder(entry, NULL).
3632 //
3633 // Each instance of PostorderProcessor represents the "stack frame" of the
3634 // recursion, and particularly keeps the state of the loop (iteration) of the
3635 // "Visit..." function it represents.
3636 // To recycle memory we keep all the frames in a double linked list but
3637 // this means that we cannot use constructors to initialize the frames.
3638 //
3639 class PostorderProcessor : public ZoneObject {
3640  public:
3641   // Back link (towards the stack bottom).
3642   PostorderProcessor* parent() {return father_; }
3643   // Forward link (towards the stack top).
3644   PostorderProcessor* child() {return child_; }
3645   HBasicBlock* block() { return block_; }
3646   HLoopInformation* loop() { return loop_; }
3647   HBasicBlock* loop_header() { return loop_header_; }
3648
3649   static PostorderProcessor* CreateEntryProcessor(Zone* zone,
3650                                                   HBasicBlock* block) {
3651     PostorderProcessor* result = new(zone) PostorderProcessor(NULL);
3652     return result->SetupSuccessors(zone, block, NULL);
3653   }
3654
3655   PostorderProcessor* PerformStep(Zone* zone,
3656                                   ZoneList<HBasicBlock*>* order) {
3657     PostorderProcessor* next =
3658         PerformNonBacktrackingStep(zone, order);
3659     if (next != NULL) {
3660       return next;
3661     } else {
3662       return Backtrack(zone, order);
3663     }
3664   }
3665
3666  private:
3667   explicit PostorderProcessor(PostorderProcessor* father)
3668       : father_(father), child_(NULL), successor_iterator(NULL) { }
3669
3670   // Each enum value states the cycle whose state is kept by this instance.
3671   enum LoopKind {
3672     NONE,
3673     SUCCESSORS,
3674     SUCCESSORS_OF_LOOP_HEADER,
3675     LOOP_MEMBERS,
3676     SUCCESSORS_OF_LOOP_MEMBER
3677   };
3678
3679   // Each "Setup..." method is like a constructor for a cycle state.
3680   PostorderProcessor* SetupSuccessors(Zone* zone,
3681                                       HBasicBlock* block,
3682                                       HBasicBlock* loop_header) {
3683     if (block == NULL || block->IsOrdered() ||
3684         block->parent_loop_header() != loop_header) {
3685       kind_ = NONE;
3686       block_ = NULL;
3687       loop_ = NULL;
3688       loop_header_ = NULL;
3689       return this;
3690     } else {
3691       block_ = block;
3692       loop_ = NULL;
3693       block->MarkAsOrdered();
3694
3695       if (block->IsLoopHeader()) {
3696         kind_ = SUCCESSORS_OF_LOOP_HEADER;
3697         loop_header_ = block;
3698         InitializeSuccessors();
3699         PostorderProcessor* result = Push(zone);
3700         return result->SetupLoopMembers(zone, block, block->loop_information(),
3701                                         loop_header);
3702       } else {
3703         DCHECK(block->IsFinished());
3704         kind_ = SUCCESSORS;
3705         loop_header_ = loop_header;
3706         InitializeSuccessors();
3707         return this;
3708       }
3709     }
3710   }
3711
3712   PostorderProcessor* SetupLoopMembers(Zone* zone,
3713                                        HBasicBlock* block,
3714                                        HLoopInformation* loop,
3715                                        HBasicBlock* loop_header) {
3716     kind_ = LOOP_MEMBERS;
3717     block_ = block;
3718     loop_ = loop;
3719     loop_header_ = loop_header;
3720     InitializeLoopMembers();
3721     return this;
3722   }
3723
3724   PostorderProcessor* SetupSuccessorsOfLoopMember(
3725       HBasicBlock* block,
3726       HLoopInformation* loop,
3727       HBasicBlock* loop_header) {
3728     kind_ = SUCCESSORS_OF_LOOP_MEMBER;
3729     block_ = block;
3730     loop_ = loop;
3731     loop_header_ = loop_header;
3732     InitializeSuccessors();
3733     return this;
3734   }
3735
3736   // This method "allocates" a new stack frame.
3737   PostorderProcessor* Push(Zone* zone) {
3738     if (child_ == NULL) {
3739       child_ = new(zone) PostorderProcessor(this);
3740     }
3741     return child_;
3742   }
3743
3744   void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) {
3745     DCHECK(block_->end()->FirstSuccessor() == NULL ||
3746            order->Contains(block_->end()->FirstSuccessor()) ||
3747            block_->end()->FirstSuccessor()->IsLoopHeader());
3748     DCHECK(block_->end()->SecondSuccessor() == NULL ||
3749            order->Contains(block_->end()->SecondSuccessor()) ||
3750            block_->end()->SecondSuccessor()->IsLoopHeader());
3751     order->Add(block_, zone);
3752   }
3753
3754   // This method is the basic block to walk up the stack.
3755   PostorderProcessor* Pop(Zone* zone,
3756                           ZoneList<HBasicBlock*>* order) {
3757     switch (kind_) {
3758       case SUCCESSORS:
3759       case SUCCESSORS_OF_LOOP_HEADER:
3760         ClosePostorder(order, zone);
3761         return father_;
3762       case LOOP_MEMBERS:
3763         return father_;
3764       case SUCCESSORS_OF_LOOP_MEMBER:
3765         if (block()->IsLoopHeader() && block() != loop_->loop_header()) {
3766           // In this case we need to perform a LOOP_MEMBERS cycle so we
3767           // initialize it and return this instead of father.
3768           return SetupLoopMembers(zone, block(),
3769                                   block()->loop_information(), loop_header_);
3770         } else {
3771           return father_;
3772         }
3773       case NONE:
3774         return father_;
3775     }
3776     UNREACHABLE();
3777     return NULL;
3778   }
3779
3780   // Walks up the stack.
3781   PostorderProcessor* Backtrack(Zone* zone,
3782                                 ZoneList<HBasicBlock*>* order) {
3783     PostorderProcessor* parent = Pop(zone, order);
3784     while (parent != NULL) {
3785       PostorderProcessor* next =
3786           parent->PerformNonBacktrackingStep(zone, order);
3787       if (next != NULL) {
3788         return next;
3789       } else {
3790         parent = parent->Pop(zone, order);
3791       }
3792     }
3793     return NULL;
3794   }
3795
3796   PostorderProcessor* PerformNonBacktrackingStep(
3797       Zone* zone,
3798       ZoneList<HBasicBlock*>* order) {
3799     HBasicBlock* next_block;
3800     switch (kind_) {
3801       case SUCCESSORS:
3802         next_block = AdvanceSuccessors();
3803         if (next_block != NULL) {
3804           PostorderProcessor* result = Push(zone);
3805           return result->SetupSuccessors(zone, next_block, loop_header_);
3806         }
3807         break;
3808       case SUCCESSORS_OF_LOOP_HEADER:
3809         next_block = AdvanceSuccessors();
3810         if (next_block != NULL) {
3811           PostorderProcessor* result = Push(zone);
3812           return result->SetupSuccessors(zone, next_block, block());
3813         }
3814         break;
3815       case LOOP_MEMBERS:
3816         next_block = AdvanceLoopMembers();
3817         if (next_block != NULL) {
3818           PostorderProcessor* result = Push(zone);
3819           return result->SetupSuccessorsOfLoopMember(next_block,
3820                                                      loop_, loop_header_);
3821         }
3822         break;
3823       case SUCCESSORS_OF_LOOP_MEMBER:
3824         next_block = AdvanceSuccessors();
3825         if (next_block != NULL) {
3826           PostorderProcessor* result = Push(zone);
3827           return result->SetupSuccessors(zone, next_block, loop_header_);
3828         }
3829         break;
3830       case NONE:
3831         return NULL;
3832     }
3833     return NULL;
3834   }
3835
3836   // The following two methods implement a "foreach b in successors" cycle.
3837   void InitializeSuccessors() {
3838     loop_index = 0;
3839     loop_length = 0;
3840     successor_iterator = HSuccessorIterator(block_->end());
3841   }
3842
3843   HBasicBlock* AdvanceSuccessors() {
3844     if (!successor_iterator.Done()) {
3845       HBasicBlock* result = successor_iterator.Current();
3846       successor_iterator.Advance();
3847       return result;
3848     }
3849     return NULL;
3850   }
3851
3852   // The following two methods implement a "foreach b in loop members" cycle.
3853   void InitializeLoopMembers() {
3854     loop_index = 0;
3855     loop_length = loop_->blocks()->length();
3856   }
3857
3858   HBasicBlock* AdvanceLoopMembers() {
3859     if (loop_index < loop_length) {
3860       HBasicBlock* result = loop_->blocks()->at(loop_index);
3861       loop_index++;
3862       return result;
3863     } else {
3864       return NULL;
3865     }
3866   }
3867
3868   LoopKind kind_;
3869   PostorderProcessor* father_;
3870   PostorderProcessor* child_;
3871   HLoopInformation* loop_;
3872   HBasicBlock* block_;
3873   HBasicBlock* loop_header_;
3874   int loop_index;
3875   int loop_length;
3876   HSuccessorIterator successor_iterator;
3877 };
3878
3879
3880 void HGraph::OrderBlocks() {
3881   CompilationPhase phase("H_Block ordering", info());
3882
3883 #ifdef DEBUG
3884   // Initially the blocks must not be ordered.
3885   for (int i = 0; i < blocks_.length(); ++i) {
3886     DCHECK(!blocks_[i]->IsOrdered());
3887   }
3888 #endif
3889
3890   PostorderProcessor* postorder =
3891       PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]);
3892   blocks_.Rewind(0);
3893   while (postorder) {
3894     postorder = postorder->PerformStep(zone(), &blocks_);
3895   }
3896
3897 #ifdef DEBUG
3898   // Now all blocks must be marked as ordered.
3899   for (int i = 0; i < blocks_.length(); ++i) {
3900     DCHECK(blocks_[i]->IsOrdered());
3901   }
3902 #endif
3903
3904   // Reverse block list and assign block IDs.
3905   for (int i = 0, j = blocks_.length(); --j >= i; ++i) {
3906     HBasicBlock* bi = blocks_[i];
3907     HBasicBlock* bj = blocks_[j];
3908     bi->set_block_id(j);
3909     bj->set_block_id(i);
3910     blocks_[i] = bj;
3911     blocks_[j] = bi;
3912   }
3913 }
3914
3915
3916 void HGraph::AssignDominators() {
3917   HPhase phase("H_Assign dominators", this);
3918   for (int i = 0; i < blocks_.length(); ++i) {
3919     HBasicBlock* block = blocks_[i];
3920     if (block->IsLoopHeader()) {
3921       // Only the first predecessor of a loop header is from outside the loop.
3922       // All others are back edges, and thus cannot dominate the loop header.
3923       block->AssignCommonDominator(block->predecessors()->first());
3924       block->AssignLoopSuccessorDominators();
3925     } else {
3926       for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) {
3927         blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j));
3928       }
3929     }
3930   }
3931 }
3932
3933
3934 bool HGraph::CheckArgumentsPhiUses() {
3935   int block_count = blocks_.length();
3936   for (int i = 0; i < block_count; ++i) {
3937     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3938       HPhi* phi = blocks_[i]->phis()->at(j);
3939       // We don't support phi uses of arguments for now.
3940       if (phi->CheckFlag(HValue::kIsArguments)) return false;
3941     }
3942   }
3943   return true;
3944 }
3945
3946
3947 bool HGraph::CheckConstPhiUses() {
3948   int block_count = blocks_.length();
3949   for (int i = 0; i < block_count; ++i) {
3950     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3951       HPhi* phi = blocks_[i]->phis()->at(j);
3952       // Check for the hole value (from an uninitialized const).
3953       for (int k = 0; k < phi->OperandCount(); k++) {
3954         if (phi->OperandAt(k) == GetConstantHole()) return false;
3955       }
3956     }
3957   }
3958   return true;
3959 }
3960
3961
3962 void HGraph::CollectPhis() {
3963   int block_count = blocks_.length();
3964   phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone());
3965   for (int i = 0; i < block_count; ++i) {
3966     for (int j = 0; j < blocks_[i]->phis()->length(); ++j) {
3967       HPhi* phi = blocks_[i]->phis()->at(j);
3968       phi_list_->Add(phi, zone());
3969     }
3970   }
3971 }
3972
3973
3974 // Implementation of utility class to encapsulate the translation state for
3975 // a (possibly inlined) function.
3976 FunctionState::FunctionState(HOptimizedGraphBuilder* owner,
3977                              CompilationInfo* info, InliningKind inlining_kind,
3978                              int inlining_id)
3979     : owner_(owner),
3980       compilation_info_(info),
3981       call_context_(NULL),
3982       inlining_kind_(inlining_kind),
3983       function_return_(NULL),
3984       test_context_(NULL),
3985       entry_(NULL),
3986       arguments_object_(NULL),
3987       arguments_elements_(NULL),
3988       inlining_id_(inlining_id),
3989       outer_source_position_(SourcePosition::Unknown()),
3990       outer_(owner->function_state()) {
3991   if (outer_ != NULL) {
3992     // State for an inline function.
3993     if (owner->ast_context()->IsTest()) {
3994       HBasicBlock* if_true = owner->graph()->CreateBasicBlock();
3995       HBasicBlock* if_false = owner->graph()->CreateBasicBlock();
3996       if_true->MarkAsInlineReturnTarget(owner->current_block());
3997       if_false->MarkAsInlineReturnTarget(owner->current_block());
3998       TestContext* outer_test_context = TestContext::cast(owner->ast_context());
3999       Expression* cond = outer_test_context->condition();
4000       // The AstContext constructor pushed on the context stack.  This newed
4001       // instance is the reason that AstContext can't be BASE_EMBEDDED.
4002       test_context_ = new TestContext(owner, cond, if_true, if_false);
4003     } else {
4004       function_return_ = owner->graph()->CreateBasicBlock();
4005       function_return()->MarkAsInlineReturnTarget(owner->current_block());
4006     }
4007     // Set this after possibly allocating a new TestContext above.
4008     call_context_ = owner->ast_context();
4009   }
4010
4011   // Push on the state stack.
4012   owner->set_function_state(this);
4013
4014   if (compilation_info_->is_tracking_positions()) {
4015     outer_source_position_ = owner->source_position();
4016     owner->EnterInlinedSource(
4017       info->shared_info()->start_position(),
4018       inlining_id);
4019     owner->SetSourcePosition(info->shared_info()->start_position());
4020   }
4021 }
4022
4023
4024 FunctionState::~FunctionState() {
4025   delete test_context_;
4026   owner_->set_function_state(outer_);
4027
4028   if (compilation_info_->is_tracking_positions()) {
4029     owner_->set_source_position(outer_source_position_);
4030     owner_->EnterInlinedSource(
4031       outer_->compilation_info()->shared_info()->start_position(),
4032       outer_->inlining_id());
4033   }
4034 }
4035
4036
4037 // Implementation of utility classes to represent an expression's context in
4038 // the AST.
4039 AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind)
4040     : owner_(owner),
4041       kind_(kind),
4042       outer_(owner->ast_context()),
4043       typeof_mode_(NOT_INSIDE_TYPEOF) {
4044   owner->set_ast_context(this);  // Push.
4045 #ifdef DEBUG
4046   DCHECK(owner->environment()->frame_type() == JS_FUNCTION);
4047   original_length_ = owner->environment()->length();
4048 #endif
4049 }
4050
4051
4052 AstContext::~AstContext() {
4053   owner_->set_ast_context(outer_);  // Pop.
4054 }
4055
4056
4057 EffectContext::~EffectContext() {
4058   DCHECK(owner()->HasStackOverflow() ||
4059          owner()->current_block() == NULL ||
4060          (owner()->environment()->length() == original_length_ &&
4061           owner()->environment()->frame_type() == JS_FUNCTION));
4062 }
4063
4064
4065 ValueContext::~ValueContext() {
4066   DCHECK(owner()->HasStackOverflow() ||
4067          owner()->current_block() == NULL ||
4068          (owner()->environment()->length() == original_length_ + 1 &&
4069           owner()->environment()->frame_type() == JS_FUNCTION));
4070 }
4071
4072
4073 void EffectContext::ReturnValue(HValue* value) {
4074   // The value is simply ignored.
4075 }
4076
4077
4078 void ValueContext::ReturnValue(HValue* value) {
4079   // The value is tracked in the bailout environment, and communicated
4080   // through the environment as the result of the expression.
4081   if (value->CheckFlag(HValue::kIsArguments)) {
4082     if (flag_ == ARGUMENTS_FAKED) {
4083       value = owner()->graph()->GetConstantUndefined();
4084     } else if (!arguments_allowed()) {
4085       owner()->Bailout(kBadValueContextForArgumentsValue);
4086     }
4087   }
4088   owner()->Push(value);
4089 }
4090
4091
4092 void TestContext::ReturnValue(HValue* value) {
4093   BuildBranch(value);
4094 }
4095
4096
4097 void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4098   DCHECK(!instr->IsControlInstruction());
4099   owner()->AddInstruction(instr);
4100   if (instr->HasObservableSideEffects()) {
4101     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4102   }
4103 }
4104
4105
4106 void EffectContext::ReturnControl(HControlInstruction* instr,
4107                                   BailoutId ast_id) {
4108   DCHECK(!instr->HasObservableSideEffects());
4109   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4110   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4111   instr->SetSuccessorAt(0, empty_true);
4112   instr->SetSuccessorAt(1, empty_false);
4113   owner()->FinishCurrentBlock(instr);
4114   HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id);
4115   owner()->set_current_block(join);
4116 }
4117
4118
4119 void EffectContext::ReturnContinuation(HIfContinuation* continuation,
4120                                        BailoutId ast_id) {
4121   HBasicBlock* true_branch = NULL;
4122   HBasicBlock* false_branch = NULL;
4123   continuation->Continue(&true_branch, &false_branch);
4124   if (!continuation->IsTrueReachable()) {
4125     owner()->set_current_block(false_branch);
4126   } else if (!continuation->IsFalseReachable()) {
4127     owner()->set_current_block(true_branch);
4128   } else {
4129     HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id);
4130     owner()->set_current_block(join);
4131   }
4132 }
4133
4134
4135 void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4136   DCHECK(!instr->IsControlInstruction());
4137   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4138     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4139   }
4140   owner()->AddInstruction(instr);
4141   owner()->Push(instr);
4142   if (instr->HasObservableSideEffects()) {
4143     owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4144   }
4145 }
4146
4147
4148 void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4149   DCHECK(!instr->HasObservableSideEffects());
4150   if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) {
4151     return owner()->Bailout(kBadValueContextForArgumentsObjectValue);
4152   }
4153   HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock();
4154   HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock();
4155   instr->SetSuccessorAt(0, materialize_true);
4156   instr->SetSuccessorAt(1, materialize_false);
4157   owner()->FinishCurrentBlock(instr);
4158   owner()->set_current_block(materialize_true);
4159   owner()->Push(owner()->graph()->GetConstantTrue());
4160   owner()->set_current_block(materialize_false);
4161   owner()->Push(owner()->graph()->GetConstantFalse());
4162   HBasicBlock* join =
4163     owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4164   owner()->set_current_block(join);
4165 }
4166
4167
4168 void ValueContext::ReturnContinuation(HIfContinuation* continuation,
4169                                       BailoutId ast_id) {
4170   HBasicBlock* materialize_true = NULL;
4171   HBasicBlock* materialize_false = NULL;
4172   continuation->Continue(&materialize_true, &materialize_false);
4173   if (continuation->IsTrueReachable()) {
4174     owner()->set_current_block(materialize_true);
4175     owner()->Push(owner()->graph()->GetConstantTrue());
4176     owner()->set_current_block(materialize_true);
4177   }
4178   if (continuation->IsFalseReachable()) {
4179     owner()->set_current_block(materialize_false);
4180     owner()->Push(owner()->graph()->GetConstantFalse());
4181     owner()->set_current_block(materialize_false);
4182   }
4183   if (continuation->TrueAndFalseReachable()) {
4184     HBasicBlock* join =
4185         owner()->CreateJoin(materialize_true, materialize_false, ast_id);
4186     owner()->set_current_block(join);
4187   }
4188 }
4189
4190
4191 void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) {
4192   DCHECK(!instr->IsControlInstruction());
4193   HOptimizedGraphBuilder* builder = owner();
4194   builder->AddInstruction(instr);
4195   // We expect a simulate after every expression with side effects, though
4196   // this one isn't actually needed (and wouldn't work if it were targeted).
4197   if (instr->HasObservableSideEffects()) {
4198     builder->Push(instr);
4199     builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
4200     builder->Pop();
4201   }
4202   BuildBranch(instr);
4203 }
4204
4205
4206 void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) {
4207   DCHECK(!instr->HasObservableSideEffects());
4208   HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock();
4209   HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock();
4210   instr->SetSuccessorAt(0, empty_true);
4211   instr->SetSuccessorAt(1, empty_false);
4212   owner()->FinishCurrentBlock(instr);
4213   owner()->Goto(empty_true, if_true(), owner()->function_state());
4214   owner()->Goto(empty_false, if_false(), owner()->function_state());
4215   owner()->set_current_block(NULL);
4216 }
4217
4218
4219 void TestContext::ReturnContinuation(HIfContinuation* continuation,
4220                                      BailoutId ast_id) {
4221   HBasicBlock* true_branch = NULL;
4222   HBasicBlock* false_branch = NULL;
4223   continuation->Continue(&true_branch, &false_branch);
4224   if (continuation->IsTrueReachable()) {
4225     owner()->Goto(true_branch, if_true(), owner()->function_state());
4226   }
4227   if (continuation->IsFalseReachable()) {
4228     owner()->Goto(false_branch, if_false(), owner()->function_state());
4229   }
4230   owner()->set_current_block(NULL);
4231 }
4232
4233
4234 void TestContext::BuildBranch(HValue* value) {
4235   // We expect the graph to be in edge-split form: there is no edge that
4236   // connects a branch node to a join node.  We conservatively ensure that
4237   // property by always adding an empty block on the outgoing edges of this
4238   // branch.
4239   HOptimizedGraphBuilder* builder = owner();
4240   if (value != NULL && value->CheckFlag(HValue::kIsArguments)) {
4241     builder->Bailout(kArgumentsObjectValueInATestContext);
4242   }
4243   ToBooleanStub::Types expected(condition()->to_boolean_types());
4244   ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None());
4245 }
4246
4247
4248 // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts.
4249 #define CHECK_BAILOUT(call)                     \
4250   do {                                          \
4251     call;                                       \
4252     if (HasStackOverflow()) return;             \
4253   } while (false)
4254
4255
4256 #define CHECK_ALIVE(call)                                       \
4257   do {                                                          \
4258     call;                                                       \
4259     if (HasStackOverflow() || current_block() == NULL) return;  \
4260   } while (false)
4261
4262
4263 #define CHECK_ALIVE_OR_RETURN(call, value)                            \
4264   do {                                                                \
4265     call;                                                             \
4266     if (HasStackOverflow() || current_block() == NULL) return value;  \
4267   } while (false)
4268
4269
4270 void HOptimizedGraphBuilder::Bailout(BailoutReason reason) {
4271   current_info()->AbortOptimization(reason);
4272   SetStackOverflow();
4273 }
4274
4275
4276 void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) {
4277   EffectContext for_effect(this);
4278   Visit(expr);
4279 }
4280
4281
4282 void HOptimizedGraphBuilder::VisitForValue(Expression* expr,
4283                                            ArgumentsAllowedFlag flag) {
4284   ValueContext for_value(this, flag);
4285   Visit(expr);
4286 }
4287
4288
4289 void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) {
4290   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
4291   for_value.set_typeof_mode(INSIDE_TYPEOF);
4292   Visit(expr);
4293 }
4294
4295
4296 void HOptimizedGraphBuilder::VisitForControl(Expression* expr,
4297                                              HBasicBlock* true_block,
4298                                              HBasicBlock* false_block) {
4299   TestContext for_test(this, expr, true_block, false_block);
4300   Visit(expr);
4301 }
4302
4303
4304 void HOptimizedGraphBuilder::VisitExpressions(
4305     ZoneList<Expression*>* exprs) {
4306   for (int i = 0; i < exprs->length(); ++i) {
4307     CHECK_ALIVE(VisitForValue(exprs->at(i)));
4308   }
4309 }
4310
4311
4312 void HOptimizedGraphBuilder::VisitExpressions(ZoneList<Expression*>* exprs,
4313                                               ArgumentsAllowedFlag flag) {
4314   for (int i = 0; i < exprs->length(); ++i) {
4315     CHECK_ALIVE(VisitForValue(exprs->at(i), flag));
4316   }
4317 }
4318
4319
4320 bool HOptimizedGraphBuilder::BuildGraph() {
4321   if (IsSubclassConstructor(current_info()->function()->kind())) {
4322     Bailout(kSuperReference);
4323     return false;
4324   }
4325
4326   int slots = current_info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
4327   if (current_info()->scope()->is_script_scope() && slots > 0) {
4328     Bailout(kScriptContext);
4329     return false;
4330   }
4331
4332   Scope* scope = current_info()->scope();
4333   SetUpScope(scope);
4334
4335   // Add an edge to the body entry.  This is warty: the graph's start
4336   // environment will be used by the Lithium translation as the initial
4337   // environment on graph entry, but it has now been mutated by the
4338   // Hydrogen translation of the instructions in the start block.  This
4339   // environment uses values which have not been defined yet.  These
4340   // Hydrogen instructions will then be replayed by the Lithium
4341   // translation, so they cannot have an environment effect.  The edge to
4342   // the body's entry block (along with some special logic for the start
4343   // block in HInstruction::InsertAfter) seals the start block from
4344   // getting unwanted instructions inserted.
4345   //
4346   // TODO(kmillikin): Fix this.  Stop mutating the initial environment.
4347   // Make the Hydrogen instructions in the initial block into Hydrogen
4348   // values (but not instructions), present in the initial environment and
4349   // not replayed by the Lithium translation.
4350   HEnvironment* initial_env = environment()->CopyWithoutHistory();
4351   HBasicBlock* body_entry = CreateBasicBlock(initial_env);
4352   Goto(body_entry);
4353   body_entry->SetJoinId(BailoutId::FunctionEntry());
4354   set_current_block(body_entry);
4355
4356   VisitDeclarations(scope->declarations());
4357   Add<HSimulate>(BailoutId::Declarations());
4358
4359   Add<HStackCheck>(HStackCheck::kFunctionEntry);
4360
4361   VisitStatements(current_info()->function()->body());
4362   if (HasStackOverflow()) return false;
4363
4364   if (current_block() != NULL) {
4365     Add<HReturn>(graph()->GetConstantUndefined());
4366     set_current_block(NULL);
4367   }
4368
4369   // If the checksum of the number of type info changes is the same as the
4370   // last time this function was compiled, then this recompile is likely not
4371   // due to missing/inadequate type feedback, but rather too aggressive
4372   // optimization. Disable optimistic LICM in that case.
4373   Handle<Code> unoptimized_code(current_info()->shared_info()->code());
4374   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
4375   Handle<TypeFeedbackInfo> type_info(
4376       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
4377   int checksum = type_info->own_type_change_checksum();
4378   int composite_checksum = graph()->update_type_change_checksum(checksum);
4379   graph()->set_use_optimistic_licm(
4380       !type_info->matches_inlined_type_change_checksum(composite_checksum));
4381   type_info->set_inlined_type_change_checksum(composite_checksum);
4382
4383   // Perform any necessary OSR-specific cleanups or changes to the graph.
4384   osr()->FinishGraph();
4385
4386   return true;
4387 }
4388
4389
4390 bool HGraph::Optimize(BailoutReason* bailout_reason) {
4391   OrderBlocks();
4392   AssignDominators();
4393
4394   // We need to create a HConstant "zero" now so that GVN will fold every
4395   // zero-valued constant in the graph together.
4396   // The constant is needed to make idef-based bounds check work: the pass
4397   // evaluates relations with "zero" and that zero cannot be created after GVN.
4398   GetConstant0();
4399
4400 #ifdef DEBUG
4401   // Do a full verify after building the graph and computing dominators.
4402   Verify(true);
4403 #endif
4404
4405   if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) {
4406     Run<HEnvironmentLivenessAnalysisPhase>();
4407   }
4408
4409   if (!CheckConstPhiUses()) {
4410     *bailout_reason = kUnsupportedPhiUseOfConstVariable;
4411     return false;
4412   }
4413   Run<HRedundantPhiEliminationPhase>();
4414   if (!CheckArgumentsPhiUses()) {
4415     *bailout_reason = kUnsupportedPhiUseOfArguments;
4416     return false;
4417   }
4418
4419   // Find and mark unreachable code to simplify optimizations, especially gvn,
4420   // where unreachable code could unnecessarily defeat LICM.
4421   Run<HMarkUnreachableBlocksPhase>();
4422
4423   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4424   if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>();
4425
4426   if (FLAG_load_elimination) Run<HLoadEliminationPhase>();
4427
4428   CollectPhis();
4429
4430   if (has_osr()) osr()->FinishOsrValues();
4431
4432   Run<HInferRepresentationPhase>();
4433
4434   // Remove HSimulate instructions that have turned out not to be needed
4435   // after all by folding them into the following HSimulate.
4436   // This must happen after inferring representations.
4437   Run<HMergeRemovableSimulatesPhase>();
4438
4439   Run<HMarkDeoptimizeOnUndefinedPhase>();
4440   Run<HRepresentationChangesPhase>();
4441
4442   Run<HInferTypesPhase>();
4443
4444   // Must be performed before canonicalization to ensure that Canonicalize
4445   // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with
4446   // zero.
4447   Run<HUint32AnalysisPhase>();
4448
4449   if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>();
4450
4451   if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>();
4452
4453   if (FLAG_check_elimination) Run<HCheckEliminationPhase>();
4454
4455   if (FLAG_store_elimination) Run<HStoreEliminationPhase>();
4456
4457   Run<HRangeAnalysisPhase>();
4458
4459   Run<HComputeChangeUndefinedToNaN>();
4460
4461   // Eliminate redundant stack checks on backwards branches.
4462   Run<HStackCheckEliminationPhase>();
4463
4464   if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>();
4465   if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>();
4466   if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>();
4467   if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>();
4468
4469   RestoreActualValues();
4470
4471   // Find unreachable code a second time, GVN and other optimizations may have
4472   // made blocks unreachable that were previously reachable.
4473   Run<HMarkUnreachableBlocksPhase>();
4474
4475   return true;
4476 }
4477
4478
4479 void HGraph::RestoreActualValues() {
4480   HPhase phase("H_Restore actual values", this);
4481
4482   for (int block_index = 0; block_index < blocks()->length(); block_index++) {
4483     HBasicBlock* block = blocks()->at(block_index);
4484
4485 #ifdef DEBUG
4486     for (int i = 0; i < block->phis()->length(); i++) {
4487       HPhi* phi = block->phis()->at(i);
4488       DCHECK(phi->ActualValue() == phi);
4489     }
4490 #endif
4491
4492     for (HInstructionIterator it(block); !it.Done(); it.Advance()) {
4493       HInstruction* instruction = it.Current();
4494       if (instruction->ActualValue() == instruction) continue;
4495       if (instruction->CheckFlag(HValue::kIsDead)) {
4496         // The instruction was marked as deleted but left in the graph
4497         // as a control flow dependency point for subsequent
4498         // instructions.
4499         instruction->DeleteAndReplaceWith(instruction->ActualValue());
4500       } else {
4501         DCHECK(instruction->IsInformativeDefinition());
4502         if (instruction->IsPurelyInformativeDefinition()) {
4503           instruction->DeleteAndReplaceWith(instruction->RedefinedOperand());
4504         } else {
4505           instruction->ReplaceAllUsesWith(instruction->ActualValue());
4506         }
4507       }
4508     }
4509   }
4510 }
4511
4512
4513 void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) {
4514   ZoneList<HValue*> arguments(count, zone());
4515   for (int i = 0; i < count; ++i) {
4516     arguments.Add(Pop(), zone());
4517   }
4518
4519   HPushArguments* push_args = New<HPushArguments>();
4520   while (!arguments.is_empty()) {
4521     push_args->AddInput(arguments.RemoveLast());
4522   }
4523   AddInstruction(push_args);
4524 }
4525
4526
4527 template <class Instruction>
4528 HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) {
4529   PushArgumentsFromEnvironment(call->argument_count());
4530   return call;
4531 }
4532
4533
4534 void HOptimizedGraphBuilder::SetUpScope(Scope* scope) {
4535   // First special is HContext.
4536   HInstruction* context = Add<HContext>();
4537   environment()->BindContext(context);
4538
4539   // Create an arguments object containing the initial parameters.  Set the
4540   // initial values of parameters including "this" having parameter index 0.
4541   DCHECK_EQ(scope->num_parameters() + 1, environment()->parameter_count());
4542   HArgumentsObject* arguments_object =
4543       New<HArgumentsObject>(environment()->parameter_count());
4544   for (int i = 0; i < environment()->parameter_count(); ++i) {
4545     HInstruction* parameter = Add<HParameter>(i);
4546     arguments_object->AddArgument(parameter, zone());
4547     environment()->Bind(i, parameter);
4548   }
4549   AddInstruction(arguments_object);
4550   graph()->SetArgumentsObject(arguments_object);
4551
4552   HConstant* undefined_constant = graph()->GetConstantUndefined();
4553   // Initialize specials and locals to undefined.
4554   for (int i = environment()->parameter_count() + 1;
4555        i < environment()->length();
4556        ++i) {
4557     environment()->Bind(i, undefined_constant);
4558   }
4559
4560   // Handle the arguments and arguments shadow variables specially (they do
4561   // not have declarations).
4562   if (scope->arguments() != NULL) {
4563     environment()->Bind(scope->arguments(),
4564                         graph()->GetArgumentsObject());
4565   }
4566
4567   int rest_index;
4568   Variable* rest = scope->rest_parameter(&rest_index);
4569   if (rest) {
4570     return Bailout(kRestParameter);
4571   }
4572
4573   if (scope->this_function_var() != nullptr ||
4574       scope->new_target_var() != nullptr) {
4575     return Bailout(kSuperReference);
4576   }
4577 }
4578
4579
4580 void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) {
4581   for (int i = 0; i < statements->length(); i++) {
4582     Statement* stmt = statements->at(i);
4583     CHECK_ALIVE(Visit(stmt));
4584     if (stmt->IsJump()) break;
4585   }
4586 }
4587
4588
4589 void HOptimizedGraphBuilder::VisitBlock(Block* stmt) {
4590   DCHECK(!HasStackOverflow());
4591   DCHECK(current_block() != NULL);
4592   DCHECK(current_block()->HasPredecessor());
4593
4594   Scope* outer_scope = scope();
4595   Scope* scope = stmt->scope();
4596   BreakAndContinueInfo break_info(stmt, outer_scope);
4597
4598   { BreakAndContinueScope push(&break_info, this);
4599     if (scope != NULL) {
4600       if (scope->ContextLocalCount() > 0) {
4601         // Load the function object.
4602         Scope* declaration_scope = scope->DeclarationScope();
4603         HInstruction* function;
4604         HValue* outer_context = environment()->context();
4605         if (declaration_scope->is_script_scope() ||
4606             declaration_scope->is_eval_scope()) {
4607           function = new (zone())
4608               HLoadContextSlot(outer_context, Context::CLOSURE_INDEX,
4609                                HLoadContextSlot::kNoCheck);
4610         } else {
4611           function = New<HThisFunction>();
4612         }
4613         AddInstruction(function);
4614         // Allocate a block context and store it to the stack frame.
4615         HInstruction* inner_context = Add<HAllocateBlockContext>(
4616             outer_context, function, scope->GetScopeInfo(isolate()));
4617         HInstruction* instr = Add<HStoreFrameContext>(inner_context);
4618         set_scope(scope);
4619         environment()->BindContext(inner_context);
4620         if (instr->HasObservableSideEffects()) {
4621           AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE);
4622         }
4623       }
4624       VisitDeclarations(scope->declarations());
4625       AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE);
4626     }
4627     CHECK_BAILOUT(VisitStatements(stmt->statements()));
4628   }
4629   set_scope(outer_scope);
4630   if (scope != NULL && current_block() != NULL &&
4631       scope->ContextLocalCount() > 0) {
4632     HValue* inner_context = environment()->context();
4633     HValue* outer_context = Add<HLoadNamedField>(
4634         inner_context, nullptr,
4635         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4636
4637     HInstruction* instr = Add<HStoreFrameContext>(outer_context);
4638     environment()->BindContext(outer_context);
4639     if (instr->HasObservableSideEffects()) {
4640       AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE);
4641     }
4642   }
4643   HBasicBlock* break_block = break_info.break_block();
4644   if (break_block != NULL) {
4645     if (current_block() != NULL) Goto(break_block);
4646     break_block->SetJoinId(stmt->ExitId());
4647     set_current_block(break_block);
4648   }
4649 }
4650
4651
4652 void HOptimizedGraphBuilder::VisitExpressionStatement(
4653     ExpressionStatement* stmt) {
4654   DCHECK(!HasStackOverflow());
4655   DCHECK(current_block() != NULL);
4656   DCHECK(current_block()->HasPredecessor());
4657   VisitForEffect(stmt->expression());
4658 }
4659
4660
4661 void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) {
4662   DCHECK(!HasStackOverflow());
4663   DCHECK(current_block() != NULL);
4664   DCHECK(current_block()->HasPredecessor());
4665 }
4666
4667
4668 void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) {
4669   DCHECK(!HasStackOverflow());
4670   DCHECK(current_block() != NULL);
4671   DCHECK(current_block()->HasPredecessor());
4672   if (stmt->condition()->ToBooleanIsTrue()) {
4673     Add<HSimulate>(stmt->ThenId());
4674     Visit(stmt->then_statement());
4675   } else if (stmt->condition()->ToBooleanIsFalse()) {
4676     Add<HSimulate>(stmt->ElseId());
4677     Visit(stmt->else_statement());
4678   } else {
4679     HBasicBlock* cond_true = graph()->CreateBasicBlock();
4680     HBasicBlock* cond_false = graph()->CreateBasicBlock();
4681     CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false));
4682
4683     if (cond_true->HasPredecessor()) {
4684       cond_true->SetJoinId(stmt->ThenId());
4685       set_current_block(cond_true);
4686       CHECK_BAILOUT(Visit(stmt->then_statement()));
4687       cond_true = current_block();
4688     } else {
4689       cond_true = NULL;
4690     }
4691
4692     if (cond_false->HasPredecessor()) {
4693       cond_false->SetJoinId(stmt->ElseId());
4694       set_current_block(cond_false);
4695       CHECK_BAILOUT(Visit(stmt->else_statement()));
4696       cond_false = current_block();
4697     } else {
4698       cond_false = NULL;
4699     }
4700
4701     HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId());
4702     set_current_block(join);
4703   }
4704 }
4705
4706
4707 HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get(
4708     BreakableStatement* stmt,
4709     BreakType type,
4710     Scope** scope,
4711     int* drop_extra) {
4712   *drop_extra = 0;
4713   BreakAndContinueScope* current = this;
4714   while (current != NULL && current->info()->target() != stmt) {
4715     *drop_extra += current->info()->drop_extra();
4716     current = current->next();
4717   }
4718   DCHECK(current != NULL);  // Always found (unless stack is malformed).
4719   *scope = current->info()->scope();
4720
4721   if (type == BREAK) {
4722     *drop_extra += current->info()->drop_extra();
4723   }
4724
4725   HBasicBlock* block = NULL;
4726   switch (type) {
4727     case BREAK:
4728       block = current->info()->break_block();
4729       if (block == NULL) {
4730         block = current->owner()->graph()->CreateBasicBlock();
4731         current->info()->set_break_block(block);
4732       }
4733       break;
4734
4735     case CONTINUE:
4736       block = current->info()->continue_block();
4737       if (block == NULL) {
4738         block = current->owner()->graph()->CreateBasicBlock();
4739         current->info()->set_continue_block(block);
4740       }
4741       break;
4742   }
4743
4744   return block;
4745 }
4746
4747
4748 void HOptimizedGraphBuilder::VisitContinueStatement(
4749     ContinueStatement* stmt) {
4750   DCHECK(!HasStackOverflow());
4751   DCHECK(current_block() != NULL);
4752   DCHECK(current_block()->HasPredecessor());
4753   Scope* outer_scope = NULL;
4754   Scope* inner_scope = scope();
4755   int drop_extra = 0;
4756   HBasicBlock* continue_block = break_scope()->Get(
4757       stmt->target(), BreakAndContinueScope::CONTINUE,
4758       &outer_scope, &drop_extra);
4759   HValue* context = environment()->context();
4760   Drop(drop_extra);
4761   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4762   if (context_pop_count > 0) {
4763     while (context_pop_count-- > 0) {
4764       HInstruction* context_instruction = Add<HLoadNamedField>(
4765           context, nullptr,
4766           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4767       context = context_instruction;
4768     }
4769     HInstruction* instr = Add<HStoreFrameContext>(context);
4770     if (instr->HasObservableSideEffects()) {
4771       AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE);
4772     }
4773     environment()->BindContext(context);
4774   }
4775
4776   Goto(continue_block);
4777   set_current_block(NULL);
4778 }
4779
4780
4781 void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) {
4782   DCHECK(!HasStackOverflow());
4783   DCHECK(current_block() != NULL);
4784   DCHECK(current_block()->HasPredecessor());
4785   Scope* outer_scope = NULL;
4786   Scope* inner_scope = scope();
4787   int drop_extra = 0;
4788   HBasicBlock* break_block = break_scope()->Get(
4789       stmt->target(), BreakAndContinueScope::BREAK,
4790       &outer_scope, &drop_extra);
4791   HValue* context = environment()->context();
4792   Drop(drop_extra);
4793   int context_pop_count = inner_scope->ContextChainLength(outer_scope);
4794   if (context_pop_count > 0) {
4795     while (context_pop_count-- > 0) {
4796       HInstruction* context_instruction = Add<HLoadNamedField>(
4797           context, nullptr,
4798           HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
4799       context = context_instruction;
4800     }
4801     HInstruction* instr = Add<HStoreFrameContext>(context);
4802     if (instr->HasObservableSideEffects()) {
4803       AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE);
4804     }
4805     environment()->BindContext(context);
4806   }
4807   Goto(break_block);
4808   set_current_block(NULL);
4809 }
4810
4811
4812 void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) {
4813   DCHECK(!HasStackOverflow());
4814   DCHECK(current_block() != NULL);
4815   DCHECK(current_block()->HasPredecessor());
4816   FunctionState* state = function_state();
4817   AstContext* context = call_context();
4818   if (context == NULL) {
4819     // Not an inlined return, so an actual one.
4820     CHECK_ALIVE(VisitForValue(stmt->expression()));
4821     HValue* result = environment()->Pop();
4822     Add<HReturn>(result);
4823   } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
4824     // Return from an inlined construct call. In a test context the return value
4825     // will always evaluate to true, in a value context the return value needs
4826     // to be a JSObject.
4827     if (context->IsTest()) {
4828       TestContext* test = TestContext::cast(context);
4829       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4830       Goto(test->if_true(), state);
4831     } else if (context->IsEffect()) {
4832       CHECK_ALIVE(VisitForEffect(stmt->expression()));
4833       Goto(function_return(), state);
4834     } else {
4835       DCHECK(context->IsValue());
4836       CHECK_ALIVE(VisitForValue(stmt->expression()));
4837       HValue* return_value = Pop();
4838       HValue* receiver = environment()->arguments_environment()->Lookup(0);
4839       HHasInstanceTypeAndBranch* typecheck =
4840           New<HHasInstanceTypeAndBranch>(return_value,
4841                                          FIRST_SPEC_OBJECT_TYPE,
4842                                          LAST_SPEC_OBJECT_TYPE);
4843       HBasicBlock* if_spec_object = graph()->CreateBasicBlock();
4844       HBasicBlock* not_spec_object = graph()->CreateBasicBlock();
4845       typecheck->SetSuccessorAt(0, if_spec_object);
4846       typecheck->SetSuccessorAt(1, not_spec_object);
4847       FinishCurrentBlock(typecheck);
4848       AddLeaveInlined(if_spec_object, return_value, state);
4849       AddLeaveInlined(not_spec_object, receiver, state);
4850     }
4851   } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
4852     // Return from an inlined setter call. The returned value is never used, the
4853     // value of an assignment is always the value of the RHS of the assignment.
4854     CHECK_ALIVE(VisitForEffect(stmt->expression()));
4855     if (context->IsTest()) {
4856       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4857       context->ReturnValue(rhs);
4858     } else if (context->IsEffect()) {
4859       Goto(function_return(), state);
4860     } else {
4861       DCHECK(context->IsValue());
4862       HValue* rhs = environment()->arguments_environment()->Lookup(1);
4863       AddLeaveInlined(rhs, state);
4864     }
4865   } else {
4866     // Return from a normal inlined function. Visit the subexpression in the
4867     // expression context of the call.
4868     if (context->IsTest()) {
4869       TestContext* test = TestContext::cast(context);
4870       VisitForControl(stmt->expression(), test->if_true(), test->if_false());
4871     } else if (context->IsEffect()) {
4872       // Visit in value context and ignore the result. This is needed to keep
4873       // environment in sync with full-codegen since some visitors (e.g.
4874       // VisitCountOperation) use the operand stack differently depending on
4875       // context.
4876       CHECK_ALIVE(VisitForValue(stmt->expression()));
4877       Pop();
4878       Goto(function_return(), state);
4879     } else {
4880       DCHECK(context->IsValue());
4881       CHECK_ALIVE(VisitForValue(stmt->expression()));
4882       AddLeaveInlined(Pop(), state);
4883     }
4884   }
4885   set_current_block(NULL);
4886 }
4887
4888
4889 void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) {
4890   DCHECK(!HasStackOverflow());
4891   DCHECK(current_block() != NULL);
4892   DCHECK(current_block()->HasPredecessor());
4893   return Bailout(kWithStatement);
4894 }
4895
4896
4897 void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) {
4898   DCHECK(!HasStackOverflow());
4899   DCHECK(current_block() != NULL);
4900   DCHECK(current_block()->HasPredecessor());
4901
4902   ZoneList<CaseClause*>* clauses = stmt->cases();
4903   int clause_count = clauses->length();
4904   ZoneList<HBasicBlock*> body_blocks(clause_count, zone());
4905
4906   CHECK_ALIVE(VisitForValue(stmt->tag()));
4907   Add<HSimulate>(stmt->EntryId());
4908   HValue* tag_value = Top();
4909   Type* tag_type = stmt->tag()->bounds().lower;
4910
4911   // 1. Build all the tests, with dangling true branches
4912   BailoutId default_id = BailoutId::None();
4913   for (int i = 0; i < clause_count; ++i) {
4914     CaseClause* clause = clauses->at(i);
4915     if (clause->is_default()) {
4916       body_blocks.Add(NULL, zone());
4917       if (default_id.IsNone()) default_id = clause->EntryId();
4918       continue;
4919     }
4920
4921     // Generate a compare and branch.
4922     CHECK_ALIVE(VisitForValue(clause->label()));
4923     HValue* label_value = Pop();
4924
4925     Type* label_type = clause->label()->bounds().lower;
4926     Type* combined_type = clause->compare_type();
4927     HControlInstruction* compare = BuildCompareInstruction(
4928         Token::EQ_STRICT, tag_value, label_value, tag_type, label_type,
4929         combined_type,
4930         ScriptPositionToSourcePosition(stmt->tag()->position()),
4931         ScriptPositionToSourcePosition(clause->label()->position()),
4932         PUSH_BEFORE_SIMULATE, clause->id());
4933
4934     HBasicBlock* next_test_block = graph()->CreateBasicBlock();
4935     HBasicBlock* body_block = graph()->CreateBasicBlock();
4936     body_blocks.Add(body_block, zone());
4937     compare->SetSuccessorAt(0, body_block);
4938     compare->SetSuccessorAt(1, next_test_block);
4939     FinishCurrentBlock(compare);
4940
4941     set_current_block(body_block);
4942     Drop(1);  // tag_value
4943
4944     set_current_block(next_test_block);
4945   }
4946
4947   // Save the current block to use for the default or to join with the
4948   // exit.
4949   HBasicBlock* last_block = current_block();
4950   Drop(1);  // tag_value
4951
4952   // 2. Loop over the clauses and the linked list of tests in lockstep,
4953   // translating the clause bodies.
4954   HBasicBlock* fall_through_block = NULL;
4955
4956   BreakAndContinueInfo break_info(stmt, scope());
4957   { BreakAndContinueScope push(&break_info, this);
4958     for (int i = 0; i < clause_count; ++i) {
4959       CaseClause* clause = clauses->at(i);
4960
4961       // Identify the block where normal (non-fall-through) control flow
4962       // goes to.
4963       HBasicBlock* normal_block = NULL;
4964       if (clause->is_default()) {
4965         if (last_block == NULL) continue;
4966         normal_block = last_block;
4967         last_block = NULL;  // Cleared to indicate we've handled it.
4968       } else {
4969         normal_block = body_blocks[i];
4970       }
4971
4972       if (fall_through_block == NULL) {
4973         set_current_block(normal_block);
4974       } else {
4975         HBasicBlock* join = CreateJoin(fall_through_block,
4976                                        normal_block,
4977                                        clause->EntryId());
4978         set_current_block(join);
4979       }
4980
4981       CHECK_BAILOUT(VisitStatements(clause->statements()));
4982       fall_through_block = current_block();
4983     }
4984   }
4985
4986   // Create an up-to-3-way join.  Use the break block if it exists since
4987   // it's already a join block.
4988   HBasicBlock* break_block = break_info.break_block();
4989   if (break_block == NULL) {
4990     set_current_block(CreateJoin(fall_through_block,
4991                                  last_block,
4992                                  stmt->ExitId()));
4993   } else {
4994     if (fall_through_block != NULL) Goto(fall_through_block, break_block);
4995     if (last_block != NULL) Goto(last_block, break_block);
4996     break_block->SetJoinId(stmt->ExitId());
4997     set_current_block(break_block);
4998   }
4999 }
5000
5001
5002 void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt,
5003                                            HBasicBlock* loop_entry) {
5004   Add<HSimulate>(stmt->StackCheckId());
5005   HStackCheck* stack_check =
5006       HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch));
5007   DCHECK(loop_entry->IsLoopHeader());
5008   loop_entry->loop_information()->set_stack_check(stack_check);
5009   CHECK_BAILOUT(Visit(stmt->body()));
5010 }
5011
5012
5013 void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) {
5014   DCHECK(!HasStackOverflow());
5015   DCHECK(current_block() != NULL);
5016   DCHECK(current_block()->HasPredecessor());
5017   DCHECK(current_block() != NULL);
5018   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5019
5020   BreakAndContinueInfo break_info(stmt, scope());
5021   {
5022     BreakAndContinueScope push(&break_info, this);
5023     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5024   }
5025   HBasicBlock* body_exit =
5026       JoinContinue(stmt, current_block(), break_info.continue_block());
5027   HBasicBlock* loop_successor = NULL;
5028   if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) {
5029     set_current_block(body_exit);
5030     loop_successor = graph()->CreateBasicBlock();
5031     if (stmt->cond()->ToBooleanIsFalse()) {
5032       loop_entry->loop_information()->stack_check()->Eliminate();
5033       Goto(loop_successor);
5034       body_exit = NULL;
5035     } else {
5036       // The block for a true condition, the actual predecessor block of the
5037       // back edge.
5038       body_exit = graph()->CreateBasicBlock();
5039       CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor));
5040     }
5041     if (body_exit != NULL && body_exit->HasPredecessor()) {
5042       body_exit->SetJoinId(stmt->BackEdgeId());
5043     } else {
5044       body_exit = NULL;
5045     }
5046     if (loop_successor->HasPredecessor()) {
5047       loop_successor->SetJoinId(stmt->ExitId());
5048     } else {
5049       loop_successor = NULL;
5050     }
5051   }
5052   HBasicBlock* loop_exit = CreateLoop(stmt,
5053                                       loop_entry,
5054                                       body_exit,
5055                                       loop_successor,
5056                                       break_info.break_block());
5057   set_current_block(loop_exit);
5058 }
5059
5060
5061 void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) {
5062   DCHECK(!HasStackOverflow());
5063   DCHECK(current_block() != NULL);
5064   DCHECK(current_block()->HasPredecessor());
5065   DCHECK(current_block() != NULL);
5066   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5067
5068   // If the condition is constant true, do not generate a branch.
5069   HBasicBlock* loop_successor = NULL;
5070   if (!stmt->cond()->ToBooleanIsTrue()) {
5071     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5072     loop_successor = graph()->CreateBasicBlock();
5073     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5074     if (body_entry->HasPredecessor()) {
5075       body_entry->SetJoinId(stmt->BodyId());
5076       set_current_block(body_entry);
5077     }
5078     if (loop_successor->HasPredecessor()) {
5079       loop_successor->SetJoinId(stmt->ExitId());
5080     } else {
5081       loop_successor = NULL;
5082     }
5083   }
5084
5085   BreakAndContinueInfo break_info(stmt, scope());
5086   if (current_block() != NULL) {
5087     BreakAndContinueScope push(&break_info, this);
5088     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5089   }
5090   HBasicBlock* body_exit =
5091       JoinContinue(stmt, current_block(), break_info.continue_block());
5092   HBasicBlock* loop_exit = CreateLoop(stmt,
5093                                       loop_entry,
5094                                       body_exit,
5095                                       loop_successor,
5096                                       break_info.break_block());
5097   set_current_block(loop_exit);
5098 }
5099
5100
5101 void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) {
5102   DCHECK(!HasStackOverflow());
5103   DCHECK(current_block() != NULL);
5104   DCHECK(current_block()->HasPredecessor());
5105   if (stmt->init() != NULL) {
5106     CHECK_ALIVE(Visit(stmt->init()));
5107   }
5108   DCHECK(current_block() != NULL);
5109   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5110
5111   HBasicBlock* loop_successor = NULL;
5112   if (stmt->cond() != NULL) {
5113     HBasicBlock* body_entry = graph()->CreateBasicBlock();
5114     loop_successor = graph()->CreateBasicBlock();
5115     CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor));
5116     if (body_entry->HasPredecessor()) {
5117       body_entry->SetJoinId(stmt->BodyId());
5118       set_current_block(body_entry);
5119     }
5120     if (loop_successor->HasPredecessor()) {
5121       loop_successor->SetJoinId(stmt->ExitId());
5122     } else {
5123       loop_successor = NULL;
5124     }
5125   }
5126
5127   BreakAndContinueInfo break_info(stmt, scope());
5128   if (current_block() != NULL) {
5129     BreakAndContinueScope push(&break_info, this);
5130     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5131   }
5132   HBasicBlock* body_exit =
5133       JoinContinue(stmt, current_block(), break_info.continue_block());
5134
5135   if (stmt->next() != NULL && body_exit != NULL) {
5136     set_current_block(body_exit);
5137     CHECK_BAILOUT(Visit(stmt->next()));
5138     body_exit = current_block();
5139   }
5140
5141   HBasicBlock* loop_exit = CreateLoop(stmt,
5142                                       loop_entry,
5143                                       body_exit,
5144                                       loop_successor,
5145                                       break_info.break_block());
5146   set_current_block(loop_exit);
5147 }
5148
5149
5150 void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) {
5151   DCHECK(!HasStackOverflow());
5152   DCHECK(current_block() != NULL);
5153   DCHECK(current_block()->HasPredecessor());
5154
5155   if (!FLAG_optimize_for_in) {
5156     return Bailout(kForInStatementOptimizationIsDisabled);
5157   }
5158
5159   if (!stmt->each()->IsVariableProxy() ||
5160       !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) {
5161     return Bailout(kForInStatementWithNonLocalEachVariable);
5162   }
5163
5164   Variable* each_var = stmt->each()->AsVariableProxy()->var();
5165
5166   CHECK_ALIVE(VisitForValue(stmt->enumerable()));
5167   HValue* enumerable = Top();  // Leave enumerable at the top.
5168
5169   IfBuilder if_undefined_or_null(this);
5170   if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5171       enumerable, graph()->GetConstantUndefined());
5172   if_undefined_or_null.Or();
5173   if_undefined_or_null.If<HCompareObjectEqAndBranch>(
5174       enumerable, graph()->GetConstantNull());
5175   if_undefined_or_null.ThenDeopt(Deoptimizer::kUndefinedOrNullInForIn);
5176   if_undefined_or_null.End();
5177   BuildForInBody(stmt, each_var, enumerable);
5178 }
5179
5180
5181 void HOptimizedGraphBuilder::BuildForInBody(ForInStatement* stmt,
5182                                             Variable* each_var,
5183                                             HValue* enumerable) {
5184   HInstruction* map;
5185   HInstruction* array;
5186   HInstruction* enum_length;
5187   bool fast = stmt->for_in_type() == ForInStatement::FAST_FOR_IN;
5188   if (fast) {
5189     map = Add<HForInPrepareMap>(enumerable);
5190     Add<HSimulate>(stmt->PrepareId());
5191
5192     array = Add<HForInCacheArray>(enumerable, map,
5193                                   DescriptorArray::kEnumCacheBridgeCacheIndex);
5194     enum_length = Add<HMapEnumLength>(map);
5195
5196     HInstruction* index_cache = Add<HForInCacheArray>(
5197         enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex);
5198     HForInCacheArray::cast(array)
5199         ->set_index_cache(HForInCacheArray::cast(index_cache));
5200   } else {
5201     Add<HSimulate>(stmt->PrepareId());
5202     {
5203       NoObservableSideEffectsScope no_effects(this);
5204       BuildJSObjectCheck(enumerable, 0);
5205     }
5206     Add<HSimulate>(stmt->ToObjectId());
5207
5208     map = graph()->GetConstant1();
5209     Runtime::FunctionId function_id = Runtime::kGetPropertyNamesFast;
5210     Add<HPushArguments>(enumerable);
5211     array = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5212                               Runtime::FunctionForId(function_id), 1);
5213     Push(array);
5214     Add<HSimulate>(stmt->EnumId());
5215     Drop(1);
5216     Handle<Map> array_map = isolate()->factory()->fixed_array_map();
5217     HValue* check = Add<HCheckMaps>(array, array_map);
5218     enum_length = AddLoadFixedArrayLength(array, check);
5219   }
5220
5221   HInstruction* start_index = Add<HConstant>(0);
5222
5223   Push(map);
5224   Push(array);
5225   Push(enum_length);
5226   Push(start_index);
5227
5228   HBasicBlock* loop_entry = BuildLoopEntry(stmt);
5229
5230   // Reload the values to ensure we have up-to-date values inside of the loop.
5231   // This is relevant especially for OSR where the values don't come from the
5232   // computation above, but from the OSR entry block.
5233   enumerable = environment()->ExpressionStackAt(4);
5234   HValue* index = environment()->ExpressionStackAt(0);
5235   HValue* limit = environment()->ExpressionStackAt(1);
5236
5237   // Check that we still have more keys.
5238   HCompareNumericAndBranch* compare_index =
5239       New<HCompareNumericAndBranch>(index, limit, Token::LT);
5240   compare_index->set_observed_input_representation(
5241       Representation::Smi(), Representation::Smi());
5242
5243   HBasicBlock* loop_body = graph()->CreateBasicBlock();
5244   HBasicBlock* loop_successor = graph()->CreateBasicBlock();
5245
5246   compare_index->SetSuccessorAt(0, loop_body);
5247   compare_index->SetSuccessorAt(1, loop_successor);
5248   FinishCurrentBlock(compare_index);
5249
5250   set_current_block(loop_successor);
5251   Drop(5);
5252
5253   set_current_block(loop_body);
5254
5255   HValue* key =
5256       Add<HLoadKeyed>(environment()->ExpressionStackAt(2),  // Enum cache.
5257                       index, index, FAST_ELEMENTS);
5258
5259   if (fast) {
5260     // Check if the expected map still matches that of the enumerable.
5261     // If not just deoptimize.
5262     Add<HCheckMapValue>(enumerable, environment()->ExpressionStackAt(3));
5263     Bind(each_var, key);
5264   } else {
5265     Add<HPushArguments>(enumerable, key);
5266     Runtime::FunctionId function_id = Runtime::kForInFilter;
5267     key = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5268                             Runtime::FunctionForId(function_id), 2);
5269     Push(key);
5270     Add<HSimulate>(stmt->FilterId());
5271     key = Pop();
5272     Bind(each_var, key);
5273     IfBuilder if_undefined(this);
5274     if_undefined.If<HCompareObjectEqAndBranch>(key,
5275                                                graph()->GetConstantUndefined());
5276     if_undefined.ThenDeopt(Deoptimizer::kUndefined);
5277     if_undefined.End();
5278     Add<HSimulate>(stmt->AssignmentId());
5279   }
5280
5281   BreakAndContinueInfo break_info(stmt, scope(), 5);
5282   {
5283     BreakAndContinueScope push(&break_info, this);
5284     CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry));
5285   }
5286
5287   HBasicBlock* body_exit =
5288       JoinContinue(stmt, current_block(), break_info.continue_block());
5289
5290   if (body_exit != NULL) {
5291     set_current_block(body_exit);
5292
5293     HValue* current_index = Pop();
5294     Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1()));
5295     body_exit = current_block();
5296   }
5297
5298   HBasicBlock* loop_exit = CreateLoop(stmt,
5299                                       loop_entry,
5300                                       body_exit,
5301                                       loop_successor,
5302                                       break_info.break_block());
5303
5304   set_current_block(loop_exit);
5305 }
5306
5307
5308 void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) {
5309   DCHECK(!HasStackOverflow());
5310   DCHECK(current_block() != NULL);
5311   DCHECK(current_block()->HasPredecessor());
5312   return Bailout(kForOfStatement);
5313 }
5314
5315
5316 void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) {
5317   DCHECK(!HasStackOverflow());
5318   DCHECK(current_block() != NULL);
5319   DCHECK(current_block()->HasPredecessor());
5320   return Bailout(kTryCatchStatement);
5321 }
5322
5323
5324 void HOptimizedGraphBuilder::VisitTryFinallyStatement(
5325     TryFinallyStatement* stmt) {
5326   DCHECK(!HasStackOverflow());
5327   DCHECK(current_block() != NULL);
5328   DCHECK(current_block()->HasPredecessor());
5329   return Bailout(kTryFinallyStatement);
5330 }
5331
5332
5333 void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) {
5334   DCHECK(!HasStackOverflow());
5335   DCHECK(current_block() != NULL);
5336   DCHECK(current_block()->HasPredecessor());
5337   return Bailout(kDebuggerStatement);
5338 }
5339
5340
5341 void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) {
5342   UNREACHABLE();
5343 }
5344
5345
5346 void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) {
5347   DCHECK(!HasStackOverflow());
5348   DCHECK(current_block() != NULL);
5349   DCHECK(current_block()->HasPredecessor());
5350   Handle<SharedFunctionInfo> shared_info = Compiler::GetSharedFunctionInfo(
5351       expr, current_info()->script(), top_info());
5352   // We also have a stack overflow if the recursive compilation did.
5353   if (HasStackOverflow()) return;
5354   HFunctionLiteral* instr =
5355       New<HFunctionLiteral>(shared_info, expr->pretenure());
5356   return ast_context()->ReturnInstruction(instr, expr->id());
5357 }
5358
5359
5360 void HOptimizedGraphBuilder::VisitClassLiteral(ClassLiteral* lit) {
5361   DCHECK(!HasStackOverflow());
5362   DCHECK(current_block() != NULL);
5363   DCHECK(current_block()->HasPredecessor());
5364   return Bailout(kClassLiteral);
5365 }
5366
5367
5368 void HOptimizedGraphBuilder::VisitNativeFunctionLiteral(
5369     NativeFunctionLiteral* expr) {
5370   DCHECK(!HasStackOverflow());
5371   DCHECK(current_block() != NULL);
5372   DCHECK(current_block()->HasPredecessor());
5373   return Bailout(kNativeFunctionLiteral);
5374 }
5375
5376
5377 void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) {
5378   DCHECK(!HasStackOverflow());
5379   DCHECK(current_block() != NULL);
5380   DCHECK(current_block()->HasPredecessor());
5381   HBasicBlock* cond_true = graph()->CreateBasicBlock();
5382   HBasicBlock* cond_false = graph()->CreateBasicBlock();
5383   CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false));
5384
5385   // Visit the true and false subexpressions in the same AST context as the
5386   // whole expression.
5387   if (cond_true->HasPredecessor()) {
5388     cond_true->SetJoinId(expr->ThenId());
5389     set_current_block(cond_true);
5390     CHECK_BAILOUT(Visit(expr->then_expression()));
5391     cond_true = current_block();
5392   } else {
5393     cond_true = NULL;
5394   }
5395
5396   if (cond_false->HasPredecessor()) {
5397     cond_false->SetJoinId(expr->ElseId());
5398     set_current_block(cond_false);
5399     CHECK_BAILOUT(Visit(expr->else_expression()));
5400     cond_false = current_block();
5401   } else {
5402     cond_false = NULL;
5403   }
5404
5405   if (!ast_context()->IsTest()) {
5406     HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id());
5407     set_current_block(join);
5408     if (join != NULL && !ast_context()->IsEffect()) {
5409       return ast_context()->ReturnValue(Pop());
5410     }
5411   }
5412 }
5413
5414
5415 HOptimizedGraphBuilder::GlobalPropertyAccess
5416 HOptimizedGraphBuilder::LookupGlobalProperty(Variable* var, LookupIterator* it,
5417                                              PropertyAccessType access_type) {
5418   if (var->is_this() || !current_info()->has_global_object()) {
5419     return kUseGeneric;
5420   }
5421
5422   switch (it->state()) {
5423     case LookupIterator::ACCESSOR:
5424     case LookupIterator::ACCESS_CHECK:
5425     case LookupIterator::INTERCEPTOR:
5426     case LookupIterator::INTEGER_INDEXED_EXOTIC:
5427     case LookupIterator::NOT_FOUND:
5428       return kUseGeneric;
5429     case LookupIterator::DATA:
5430       if (access_type == STORE && it->IsReadOnly()) return kUseGeneric;
5431       return kUseCell;
5432     case LookupIterator::JSPROXY:
5433     case LookupIterator::TRANSITION:
5434       UNREACHABLE();
5435   }
5436   UNREACHABLE();
5437   return kUseGeneric;
5438 }
5439
5440
5441 HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) {
5442   DCHECK(var->IsContextSlot());
5443   HValue* context = environment()->context();
5444   int length = scope()->ContextChainLength(var->scope());
5445   while (length-- > 0) {
5446     context = Add<HLoadNamedField>(
5447         context, nullptr,
5448         HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX));
5449   }
5450   return context;
5451 }
5452
5453
5454 void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) {
5455   DCHECK(!HasStackOverflow());
5456   DCHECK(current_block() != NULL);
5457   DCHECK(current_block()->HasPredecessor());
5458   Variable* variable = expr->var();
5459   switch (variable->location()) {
5460     case VariableLocation::GLOBAL:
5461     case VariableLocation::UNALLOCATED: {
5462       if (IsLexicalVariableMode(variable->mode())) {
5463         // TODO(rossberg): should this be an DCHECK?
5464         return Bailout(kReferenceToGlobalLexicalVariable);
5465       }
5466       // Handle known global constants like 'undefined' specially to avoid a
5467       // load from a global cell for them.
5468       Handle<Object> constant_value =
5469           isolate()->factory()->GlobalConstantFor(variable->name());
5470       if (!constant_value.is_null()) {
5471         HConstant* instr = New<HConstant>(constant_value);
5472         return ast_context()->ReturnInstruction(instr, expr->id());
5473       }
5474
5475       Handle<GlobalObject> global(current_info()->global_object());
5476
5477       // Lookup in script contexts.
5478       {
5479         Handle<ScriptContextTable> script_contexts(
5480             global->native_context()->script_context_table());
5481         ScriptContextTable::LookupResult lookup;
5482         if (ScriptContextTable::Lookup(script_contexts, variable->name(),
5483                                        &lookup)) {
5484           Handle<Context> script_context = ScriptContextTable::GetContext(
5485               script_contexts, lookup.context_index);
5486           Handle<Object> current_value =
5487               FixedArray::get(script_context, lookup.slot_index);
5488
5489           // If the values is not the hole, it will stay initialized,
5490           // so no need to generate a check.
5491           if (*current_value == *isolate()->factory()->the_hole_value()) {
5492             return Bailout(kReferenceToUninitializedVariable);
5493           }
5494           HInstruction* result = New<HLoadNamedField>(
5495               Add<HConstant>(script_context), nullptr,
5496               HObjectAccess::ForContextSlot(lookup.slot_index));
5497           return ast_context()->ReturnInstruction(result, expr->id());
5498         }
5499       }
5500
5501       LookupIterator it(global, variable->name(), LookupIterator::OWN);
5502       GlobalPropertyAccess type = LookupGlobalProperty(variable, &it, LOAD);
5503
5504       if (type == kUseCell) {
5505         Handle<PropertyCell> cell = it.GetPropertyCell();
5506         top_info()->dependencies()->AssumePropertyCell(cell);
5507         auto cell_type = it.property_details().cell_type();
5508         if (cell_type == PropertyCellType::kConstant ||
5509             cell_type == PropertyCellType::kUndefined) {
5510           Handle<Object> constant_object(cell->value(), isolate());
5511           if (constant_object->IsConsString()) {
5512             constant_object =
5513                 String::Flatten(Handle<String>::cast(constant_object));
5514           }
5515           HConstant* constant = New<HConstant>(constant_object);
5516           return ast_context()->ReturnInstruction(constant, expr->id());
5517         } else {
5518           auto access = HObjectAccess::ForPropertyCellValue();
5519           UniqueSet<Map>* field_maps = nullptr;
5520           if (cell_type == PropertyCellType::kConstantType) {
5521             switch (cell->GetConstantType()) {
5522               case PropertyCellConstantType::kSmi:
5523                 access = access.WithRepresentation(Representation::Smi());
5524                 break;
5525               case PropertyCellConstantType::kStableMap: {
5526                 // Check that the map really is stable. The heap object could
5527                 // have mutated without the cell updating state. In that case,
5528                 // make no promises about the loaded value except that it's a
5529                 // heap object.
5530                 access =
5531                     access.WithRepresentation(Representation::HeapObject());
5532                 Handle<Map> map(HeapObject::cast(cell->value())->map());
5533                 if (map->is_stable()) {
5534                   field_maps = new (zone())
5535                       UniqueSet<Map>(Unique<Map>::CreateImmovable(map), zone());
5536                 }
5537                 break;
5538               }
5539             }
5540           }
5541           HConstant* cell_constant = Add<HConstant>(cell);
5542           HLoadNamedField* instr;
5543           if (field_maps == nullptr) {
5544             instr = New<HLoadNamedField>(cell_constant, nullptr, access);
5545           } else {
5546             instr = New<HLoadNamedField>(cell_constant, nullptr, access,
5547                                          field_maps, HType::HeapObject());
5548           }
5549           instr->ClearDependsOnFlag(kInobjectFields);
5550           instr->SetDependsOnFlag(kGlobalVars);
5551           return ast_context()->ReturnInstruction(instr, expr->id());
5552         }
5553       } else if (variable->IsGlobalSlot()) {
5554         DCHECK(variable->index() > 0);
5555         DCHECK(variable->IsStaticGlobalObjectProperty());
5556         int slot_index = variable->index();
5557         int depth = scope()->ContextChainLength(variable->scope());
5558
5559         HLoadGlobalViaContext* instr =
5560             New<HLoadGlobalViaContext>(depth, slot_index);
5561         return ast_context()->ReturnInstruction(instr, expr->id());
5562
5563       } else {
5564         HValue* global_object = Add<HLoadNamedField>(
5565             context(), nullptr,
5566             HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
5567         HLoadGlobalGeneric* instr = New<HLoadGlobalGeneric>(
5568             global_object, variable->name(), ast_context()->typeof_mode());
5569         instr->SetVectorAndSlot(handle(current_feedback_vector(), isolate()),
5570                                 expr->VariableFeedbackSlot());
5571         return ast_context()->ReturnInstruction(instr, expr->id());
5572       }
5573     }
5574
5575     case VariableLocation::PARAMETER:
5576     case VariableLocation::LOCAL: {
5577       HValue* value = LookupAndMakeLive(variable);
5578       if (value == graph()->GetConstantHole()) {
5579         DCHECK(IsDeclaredVariableMode(variable->mode()) &&
5580                variable->mode() != VAR);
5581         return Bailout(kReferenceToUninitializedVariable);
5582       }
5583       return ast_context()->ReturnValue(value);
5584     }
5585
5586     case VariableLocation::CONTEXT: {
5587       HValue* context = BuildContextChainWalk(variable);
5588       HLoadContextSlot::Mode mode;
5589       switch (variable->mode()) {
5590         case LET:
5591         case CONST:
5592           mode = HLoadContextSlot::kCheckDeoptimize;
5593           break;
5594         case CONST_LEGACY:
5595           mode = HLoadContextSlot::kCheckReturnUndefined;
5596           break;
5597         default:
5598           mode = HLoadContextSlot::kNoCheck;
5599           break;
5600       }
5601       HLoadContextSlot* instr =
5602           new(zone()) HLoadContextSlot(context, variable->index(), mode);
5603       return ast_context()->ReturnInstruction(instr, expr->id());
5604     }
5605
5606     case VariableLocation::LOOKUP:
5607       return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup);
5608   }
5609 }
5610
5611
5612 void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) {
5613   DCHECK(!HasStackOverflow());
5614   DCHECK(current_block() != NULL);
5615   DCHECK(current_block()->HasPredecessor());
5616   HConstant* instr = New<HConstant>(expr->value());
5617   return ast_context()->ReturnInstruction(instr, expr->id());
5618 }
5619
5620
5621 void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) {
5622   DCHECK(!HasStackOverflow());
5623   DCHECK(current_block() != NULL);
5624   DCHECK(current_block()->HasPredecessor());
5625   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5626   Handle<FixedArray> literals(closure->literals());
5627   HRegExpLiteral* instr = New<HRegExpLiteral>(literals,
5628                                               expr->pattern(),
5629                                               expr->flags(),
5630                                               expr->literal_index());
5631   return ast_context()->ReturnInstruction(instr, expr->id());
5632 }
5633
5634
5635 static bool CanInlinePropertyAccess(Handle<Map> map) {
5636   if (map->instance_type() == HEAP_NUMBER_TYPE) return true;
5637   if (map->instance_type() < FIRST_NONSTRING_TYPE) return true;
5638   return map->IsJSObjectMap() && !map->is_dictionary_map() &&
5639          !map->has_named_interceptor() &&
5640          // TODO(verwaest): Whitelist contexts to which we have access.
5641          !map->is_access_check_needed();
5642 }
5643
5644
5645 // Determines whether the given array or object literal boilerplate satisfies
5646 // all limits to be considered for fast deep-copying and computes the total
5647 // size of all objects that are part of the graph.
5648 static bool IsFastLiteral(Handle<JSObject> boilerplate,
5649                           int max_depth,
5650                           int* max_properties) {
5651   if (boilerplate->map()->is_deprecated() &&
5652       !JSObject::TryMigrateInstance(boilerplate)) {
5653     return false;
5654   }
5655
5656   DCHECK(max_depth >= 0 && *max_properties >= 0);
5657   if (max_depth == 0) return false;
5658
5659   Isolate* isolate = boilerplate->GetIsolate();
5660   Handle<FixedArrayBase> elements(boilerplate->elements());
5661   if (elements->length() > 0 &&
5662       elements->map() != isolate->heap()->fixed_cow_array_map()) {
5663     if (boilerplate->HasFastSmiOrObjectElements()) {
5664       Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
5665       int length = elements->length();
5666       for (int i = 0; i < length; i++) {
5667         if ((*max_properties)-- == 0) return false;
5668         Handle<Object> value(fast_elements->get(i), isolate);
5669         if (value->IsJSObject()) {
5670           Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5671           if (!IsFastLiteral(value_object,
5672                              max_depth - 1,
5673                              max_properties)) {
5674             return false;
5675           }
5676         }
5677       }
5678     } else if (!boilerplate->HasFastDoubleElements()) {
5679       return false;
5680     }
5681   }
5682
5683   Handle<FixedArray> properties(boilerplate->properties());
5684   if (properties->length() > 0) {
5685     return false;
5686   } else {
5687     Handle<DescriptorArray> descriptors(
5688         boilerplate->map()->instance_descriptors());
5689     int limit = boilerplate->map()->NumberOfOwnDescriptors();
5690     for (int i = 0; i < limit; i++) {
5691       PropertyDetails details = descriptors->GetDetails(i);
5692       if (details.type() != DATA) continue;
5693       if ((*max_properties)-- == 0) return false;
5694       FieldIndex field_index = FieldIndex::ForDescriptor(boilerplate->map(), i);
5695       if (boilerplate->IsUnboxedDoubleField(field_index)) continue;
5696       Handle<Object> value(boilerplate->RawFastPropertyAt(field_index),
5697                            isolate);
5698       if (value->IsJSObject()) {
5699         Handle<JSObject> value_object = Handle<JSObject>::cast(value);
5700         if (!IsFastLiteral(value_object,
5701                            max_depth - 1,
5702                            max_properties)) {
5703           return false;
5704         }
5705       }
5706     }
5707   }
5708   return true;
5709 }
5710
5711
5712 void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) {
5713   DCHECK(!HasStackOverflow());
5714   DCHECK(current_block() != NULL);
5715   DCHECK(current_block()->HasPredecessor());
5716
5717   Handle<JSFunction> closure = function_state()->compilation_info()->closure();
5718   HInstruction* literal;
5719
5720   // Check whether to use fast or slow deep-copying for boilerplate.
5721   int max_properties = kMaxFastLiteralProperties;
5722   Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()),
5723                                isolate());
5724   Handle<AllocationSite> site;
5725   Handle<JSObject> boilerplate;
5726   if (!literals_cell->IsUndefined()) {
5727     // Retrieve the boilerplate
5728     site = Handle<AllocationSite>::cast(literals_cell);
5729     boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
5730                                    isolate());
5731   }
5732
5733   if (!boilerplate.is_null() &&
5734       IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) {
5735     AllocationSiteUsageContext site_context(isolate(), site, false);
5736     site_context.EnterNewScope();
5737     literal = BuildFastLiteral(boilerplate, &site_context);
5738     site_context.ExitScope(site, boilerplate);
5739   } else {
5740     NoObservableSideEffectsScope no_effects(this);
5741     Handle<FixedArray> closure_literals(closure->literals(), isolate());
5742     Handle<FixedArray> constant_properties = expr->constant_properties();
5743     int literal_index = expr->literal_index();
5744     int flags = expr->ComputeFlags(true);
5745
5746     Add<HPushArguments>(Add<HConstant>(closure_literals),
5747                         Add<HConstant>(literal_index),
5748                         Add<HConstant>(constant_properties),
5749                         Add<HConstant>(flags));
5750
5751     Runtime::FunctionId function_id = Runtime::kCreateObjectLiteral;
5752     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5753                                 Runtime::FunctionForId(function_id),
5754                                 4);
5755   }
5756
5757   // The object is expected in the bailout environment during computation
5758   // of the property values and is the value of the entire expression.
5759   Push(literal);
5760
5761   for (int i = 0; i < expr->properties()->length(); i++) {
5762     ObjectLiteral::Property* property = expr->properties()->at(i);
5763     if (property->is_computed_name()) return Bailout(kComputedPropertyName);
5764     if (property->IsCompileTimeValue()) continue;
5765
5766     Literal* key = property->key()->AsLiteral();
5767     Expression* value = property->value();
5768
5769     switch (property->kind()) {
5770       case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5771         DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
5772         // Fall through.
5773       case ObjectLiteral::Property::COMPUTED:
5774         // It is safe to use [[Put]] here because the boilerplate already
5775         // contains computed properties with an uninitialized value.
5776         if (key->value()->IsInternalizedString()) {
5777           if (property->emit_store()) {
5778             CHECK_ALIVE(VisitForValue(value));
5779             HValue* value = Pop();
5780
5781             // Add [[HomeObject]] to function literals.
5782             if (FunctionLiteral::NeedsHomeObject(property->value())) {
5783               Handle<Symbol> sym = isolate()->factory()->home_object_symbol();
5784               HInstruction* store_home = BuildKeyedGeneric(
5785                   STORE, NULL, value, Add<HConstant>(sym), literal);
5786               AddInstruction(store_home);
5787               DCHECK(store_home->HasObservableSideEffects());
5788               Add<HSimulate>(property->value()->id(), REMOVABLE_SIMULATE);
5789             }
5790
5791             Handle<Map> map = property->GetReceiverType();
5792             Handle<String> name = key->AsPropertyName();
5793             HValue* store;
5794             if (map.is_null()) {
5795               // If we don't know the monomorphic type, do a generic store.
5796               CHECK_ALIVE(store = BuildNamedGeneric(
5797                   STORE, NULL, literal, name, value));
5798             } else {
5799               PropertyAccessInfo info(this, STORE, map, name);
5800               if (info.CanAccessMonomorphic()) {
5801                 HValue* checked_literal = Add<HCheckMaps>(literal, map);
5802                 DCHECK(!info.IsAccessorConstant());
5803                 store = BuildMonomorphicAccess(
5804                     &info, literal, checked_literal, value,
5805                     BailoutId::None(), BailoutId::None());
5806               } else {
5807                 CHECK_ALIVE(store = BuildNamedGeneric(
5808                     STORE, NULL, literal, name, value));
5809               }
5810             }
5811             if (store->IsInstruction()) {
5812               AddInstruction(HInstruction::cast(store));
5813             }
5814             DCHECK(store->HasObservableSideEffects());
5815             Add<HSimulate>(key->id(), REMOVABLE_SIMULATE);
5816           } else {
5817             CHECK_ALIVE(VisitForEffect(value));
5818           }
5819           break;
5820         }
5821         // Fall through.
5822       case ObjectLiteral::Property::PROTOTYPE:
5823       case ObjectLiteral::Property::SETTER:
5824       case ObjectLiteral::Property::GETTER:
5825         return Bailout(kObjectLiteralWithComplexProperty);
5826       default: UNREACHABLE();
5827     }
5828   }
5829
5830   if (expr->has_function()) {
5831     // Return the result of the transformation to fast properties
5832     // instead of the original since this operation changes the map
5833     // of the object. This makes sure that the original object won't
5834     // be used by other optimized code before it is transformed
5835     // (e.g. because of code motion).
5836     HToFastProperties* result = Add<HToFastProperties>(Pop());
5837     return ast_context()->ReturnValue(result);
5838   } else {
5839     return ast_context()->ReturnValue(Pop());
5840   }
5841 }
5842
5843
5844 void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) {
5845   DCHECK(!HasStackOverflow());
5846   DCHECK(current_block() != NULL);
5847   DCHECK(current_block()->HasPredecessor());
5848   expr->BuildConstantElements(isolate());
5849   ZoneList<Expression*>* subexprs = expr->values();
5850   int length = subexprs->length();
5851   HInstruction* literal;
5852
5853   Handle<AllocationSite> site;
5854   Handle<FixedArray> literals(environment()->closure()->literals(), isolate());
5855   bool uninitialized = false;
5856   Handle<Object> literals_cell(literals->get(expr->literal_index()),
5857                                isolate());
5858   Handle<JSObject> boilerplate_object;
5859   if (literals_cell->IsUndefined()) {
5860     uninitialized = true;
5861     Handle<Object> raw_boilerplate;
5862     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
5863         isolate(), raw_boilerplate,
5864         Runtime::CreateArrayLiteralBoilerplate(
5865             isolate(), literals, expr->constant_elements(),
5866             is_strong(function_language_mode())),
5867         Bailout(kArrayBoilerplateCreationFailed));
5868
5869     boilerplate_object = Handle<JSObject>::cast(raw_boilerplate);
5870     AllocationSiteCreationContext creation_context(isolate());
5871     site = creation_context.EnterNewScope();
5872     if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) {
5873       return Bailout(kArrayBoilerplateCreationFailed);
5874     }
5875     creation_context.ExitScope(site, boilerplate_object);
5876     literals->set(expr->literal_index(), *site);
5877
5878     if (boilerplate_object->elements()->map() ==
5879         isolate()->heap()->fixed_cow_array_map()) {
5880       isolate()->counters()->cow_arrays_created_runtime()->Increment();
5881     }
5882   } else {
5883     DCHECK(literals_cell->IsAllocationSite());
5884     site = Handle<AllocationSite>::cast(literals_cell);
5885     boilerplate_object = Handle<JSObject>(
5886         JSObject::cast(site->transition_info()), isolate());
5887   }
5888
5889   DCHECK(!boilerplate_object.is_null());
5890   DCHECK(site->SitePointsToLiteral());
5891
5892   ElementsKind boilerplate_elements_kind =
5893       boilerplate_object->GetElementsKind();
5894
5895   // Check whether to use fast or slow deep-copying for boilerplate.
5896   int max_properties = kMaxFastLiteralProperties;
5897   if (IsFastLiteral(boilerplate_object,
5898                     kMaxFastLiteralDepth,
5899                     &max_properties)) {
5900     AllocationSiteUsageContext site_context(isolate(), site, false);
5901     site_context.EnterNewScope();
5902     literal = BuildFastLiteral(boilerplate_object, &site_context);
5903     site_context.ExitScope(site, boilerplate_object);
5904   } else {
5905     NoObservableSideEffectsScope no_effects(this);
5906     // Boilerplate already exists and constant elements are never accessed,
5907     // pass an empty fixed array to the runtime function instead.
5908     Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array();
5909     int literal_index = expr->literal_index();
5910     int flags = expr->ComputeFlags(true);
5911
5912     Add<HPushArguments>(Add<HConstant>(literals),
5913                         Add<HConstant>(literal_index),
5914                         Add<HConstant>(constants),
5915                         Add<HConstant>(flags));
5916
5917     Runtime::FunctionId function_id = Runtime::kCreateArrayLiteral;
5918     literal = Add<HCallRuntime>(isolate()->factory()->empty_string(),
5919                                 Runtime::FunctionForId(function_id),
5920                                 4);
5921
5922     // Register to deopt if the boilerplate ElementsKind changes.
5923     top_info()->dependencies()->AssumeTransitionStable(site);
5924   }
5925
5926   // The array is expected in the bailout environment during computation
5927   // of the property values and is the value of the entire expression.
5928   Push(literal);
5929   // The literal index is on the stack, too.
5930   Push(Add<HConstant>(expr->literal_index()));
5931
5932   HInstruction* elements = NULL;
5933
5934   for (int i = 0; i < length; i++) {
5935     Expression* subexpr = subexprs->at(i);
5936     if (subexpr->IsSpread()) {
5937       return Bailout(kSpread);
5938     }
5939
5940     // If the subexpression is a literal or a simple materialized literal it
5941     // is already set in the cloned array.
5942     if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
5943
5944     CHECK_ALIVE(VisitForValue(subexpr));
5945     HValue* value = Pop();
5946     if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral);
5947
5948     elements = AddLoadElements(literal);
5949
5950     HValue* key = Add<HConstant>(i);
5951
5952     switch (boilerplate_elements_kind) {
5953       case FAST_SMI_ELEMENTS:
5954       case FAST_HOLEY_SMI_ELEMENTS:
5955       case FAST_ELEMENTS:
5956       case FAST_HOLEY_ELEMENTS:
5957       case FAST_DOUBLE_ELEMENTS:
5958       case FAST_HOLEY_DOUBLE_ELEMENTS: {
5959         HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value,
5960                                               boilerplate_elements_kind);
5961         instr->SetUninitialized(uninitialized);
5962         break;
5963       }
5964       default:
5965         UNREACHABLE();
5966         break;
5967     }
5968
5969     Add<HSimulate>(expr->GetIdForElement(i));
5970   }
5971
5972   Drop(1);  // array literal index
5973   return ast_context()->ReturnValue(Pop());
5974 }
5975
5976
5977 HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object,
5978                                                 Handle<Map> map) {
5979   BuildCheckHeapObject(object);
5980   return Add<HCheckMaps>(object, map);
5981 }
5982
5983
5984 HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField(
5985     PropertyAccessInfo* info,
5986     HValue* checked_object) {
5987   // See if this is a load for an immutable property
5988   if (checked_object->ActualValue()->IsConstant()) {
5989     Handle<Object> object(
5990         HConstant::cast(checked_object->ActualValue())->handle(isolate()));
5991
5992     if (object->IsJSObject()) {
5993       LookupIterator it(object, info->name(),
5994                         LookupIterator::OWN_SKIP_INTERCEPTOR);
5995       Handle<Object> value = JSReceiver::GetDataProperty(&it);
5996       if (it.IsFound() && it.IsReadOnly() && !it.IsConfigurable()) {
5997         return New<HConstant>(value);
5998       }
5999     }
6000   }
6001
6002   HObjectAccess access = info->access();
6003   if (access.representation().IsDouble() &&
6004       (!FLAG_unbox_double_fields || !access.IsInobject())) {
6005     // Load the heap number.
6006     checked_object = Add<HLoadNamedField>(
6007         checked_object, nullptr,
6008         access.WithRepresentation(Representation::Tagged()));
6009     // Load the double value from it.
6010     access = HObjectAccess::ForHeapNumberValue();
6011   }
6012
6013   SmallMapList* map_list = info->field_maps();
6014   if (map_list->length() == 0) {
6015     return New<HLoadNamedField>(checked_object, checked_object, access);
6016   }
6017
6018   UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone());
6019   for (int i = 0; i < map_list->length(); ++i) {
6020     maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone());
6021   }
6022   return New<HLoadNamedField>(
6023       checked_object, checked_object, access, maps, info->field_type());
6024 }
6025
6026
6027 HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField(
6028     PropertyAccessInfo* info,
6029     HValue* checked_object,
6030     HValue* value) {
6031   bool transition_to_field = info->IsTransition();
6032   // TODO(verwaest): Move this logic into PropertyAccessInfo.
6033   HObjectAccess field_access = info->access();
6034
6035   HStoreNamedField *instr;
6036   if (field_access.representation().IsDouble() &&
6037       (!FLAG_unbox_double_fields || !field_access.IsInobject())) {
6038     HObjectAccess heap_number_access =
6039         field_access.WithRepresentation(Representation::Tagged());
6040     if (transition_to_field) {
6041       // The store requires a mutable HeapNumber to be allocated.
6042       NoObservableSideEffectsScope no_side_effects(this);
6043       HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);
6044
6045       // TODO(hpayer): Allocation site pretenuring support.
6046       HInstruction* heap_number = Add<HAllocate>(heap_number_size,
6047           HType::HeapObject(),
6048           NOT_TENURED,
6049           MUTABLE_HEAP_NUMBER_TYPE);
6050       AddStoreMapConstant(
6051           heap_number, isolate()->factory()->mutable_heap_number_map());
6052       Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
6053                             value);
6054       instr = New<HStoreNamedField>(checked_object->ActualValue(),
6055                                     heap_number_access,
6056                                     heap_number);
6057     } else {
6058       // Already holds a HeapNumber; load the box and write its value field.
6059       HInstruction* heap_number =
6060           Add<HLoadNamedField>(checked_object, nullptr, heap_number_access);
6061       instr = New<HStoreNamedField>(heap_number,
6062                                     HObjectAccess::ForHeapNumberValue(),
6063                                     value, STORE_TO_INITIALIZED_ENTRY);
6064     }
6065   } else {
6066     if (field_access.representation().IsHeapObject()) {
6067       BuildCheckHeapObject(value);
6068     }
6069
6070     if (!info->field_maps()->is_empty()) {
6071       DCHECK(field_access.representation().IsHeapObject());
6072       value = Add<HCheckMaps>(value, info->field_maps());
6073     }
6074
6075     // This is a normal store.
6076     instr = New<HStoreNamedField>(
6077         checked_object->ActualValue(), field_access, value,
6078         transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY);
6079   }
6080
6081   if (transition_to_field) {
6082     Handle<Map> transition(info->transition());
6083     DCHECK(!transition->is_deprecated());
6084     instr->SetTransition(Add<HConstant>(transition));
6085   }
6086   return instr;
6087 }
6088
6089
6090 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible(
6091     PropertyAccessInfo* info) {
6092   if (!CanInlinePropertyAccess(map_)) return false;
6093
6094   // Currently only handle Type::Number as a polymorphic case.
6095   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6096   // instruction.
6097   if (IsNumberType()) return false;
6098
6099   // Values are only compatible for monomorphic load if they all behave the same
6100   // regarding value wrappers.
6101   if (IsValueWrapped() != info->IsValueWrapped()) return false;
6102
6103   if (!LookupDescriptor()) return false;
6104
6105   if (!IsFound()) {
6106     return (!info->IsFound() || info->has_holder()) &&
6107            map()->prototype() == info->map()->prototype();
6108   }
6109
6110   // Mismatch if the other access info found the property in the prototype
6111   // chain.
6112   if (info->has_holder()) return false;
6113
6114   if (IsAccessorConstant()) {
6115     return accessor_.is_identical_to(info->accessor_) &&
6116         api_holder_.is_identical_to(info->api_holder_);
6117   }
6118
6119   if (IsDataConstant()) {
6120     return constant_.is_identical_to(info->constant_);
6121   }
6122
6123   DCHECK(IsData());
6124   if (!info->IsData()) return false;
6125
6126   Representation r = access_.representation();
6127   if (IsLoad()) {
6128     if (!info->access_.representation().IsCompatibleForLoad(r)) return false;
6129   } else {
6130     if (!info->access_.representation().IsCompatibleForStore(r)) return false;
6131   }
6132   if (info->access_.offset() != access_.offset()) return false;
6133   if (info->access_.IsInobject() != access_.IsInobject()) return false;
6134   if (IsLoad()) {
6135     if (field_maps_.is_empty()) {
6136       info->field_maps_.Clear();
6137     } else if (!info->field_maps_.is_empty()) {
6138       for (int i = 0; i < field_maps_.length(); ++i) {
6139         info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone());
6140       }
6141       info->field_maps_.Sort();
6142     }
6143   } else {
6144     // We can only merge stores that agree on their field maps. The comparison
6145     // below is safe, since we keep the field maps sorted.
6146     if (field_maps_.length() != info->field_maps_.length()) return false;
6147     for (int i = 0; i < field_maps_.length(); ++i) {
6148       if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) {
6149         return false;
6150       }
6151     }
6152   }
6153   info->GeneralizeRepresentation(r);
6154   info->field_type_ = info->field_type_.Combine(field_type_);
6155   return true;
6156 }
6157
6158
6159 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() {
6160   if (!map_->IsJSObjectMap()) return true;
6161   LookupDescriptor(*map_, *name_);
6162   return LoadResult(map_);
6163 }
6164
6165
6166 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) {
6167   if (!IsLoad() && IsProperty() && IsReadOnly()) {
6168     return false;
6169   }
6170
6171   if (IsData()) {
6172     // Construct the object field access.
6173     int index = GetLocalFieldIndexFromMap(map);
6174     access_ = HObjectAccess::ForField(map, index, representation(), name_);
6175
6176     // Load field map for heap objects.
6177     return LoadFieldMaps(map);
6178   } else if (IsAccessorConstant()) {
6179     Handle<Object> accessors = GetAccessorsFromMap(map);
6180     if (!accessors->IsAccessorPair()) return false;
6181     Object* raw_accessor =
6182         IsLoad() ? Handle<AccessorPair>::cast(accessors)->getter()
6183                  : Handle<AccessorPair>::cast(accessors)->setter();
6184     if (!raw_accessor->IsJSFunction()) return false;
6185     Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor));
6186     if (accessor->shared()->IsApiFunction()) {
6187       CallOptimization call_optimization(accessor);
6188       if (call_optimization.is_simple_api_call()) {
6189         CallOptimization::HolderLookup holder_lookup;
6190         api_holder_ =
6191             call_optimization.LookupHolderOfExpectedType(map_, &holder_lookup);
6192       }
6193     }
6194     accessor_ = accessor;
6195   } else if (IsDataConstant()) {
6196     constant_ = GetConstantFromMap(map);
6197   }
6198
6199   return true;
6200 }
6201
6202
6203 bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps(
6204     Handle<Map> map) {
6205   // Clear any previously collected field maps/type.
6206   field_maps_.Clear();
6207   field_type_ = HType::Tagged();
6208
6209   // Figure out the field type from the accessor map.
6210   Handle<HeapType> field_type = GetFieldTypeFromMap(map);
6211
6212   // Collect the (stable) maps from the field type.
6213   int num_field_maps = field_type->NumClasses();
6214   if (num_field_maps > 0) {
6215     DCHECK(access_.representation().IsHeapObject());
6216     field_maps_.Reserve(num_field_maps, zone());
6217     HeapType::Iterator<Map> it = field_type->Classes();
6218     while (!it.Done()) {
6219       Handle<Map> field_map = it.Current();
6220       if (!field_map->is_stable()) {
6221         field_maps_.Clear();
6222         break;
6223       }
6224       field_maps_.Add(field_map, zone());
6225       it.Advance();
6226     }
6227   }
6228
6229   if (field_maps_.is_empty()) {
6230     // Store is not safe if the field map was cleared.
6231     return IsLoad() || !field_type->Is(HeapType::None());
6232   }
6233
6234   field_maps_.Sort();
6235   DCHECK_EQ(num_field_maps, field_maps_.length());
6236
6237   // Determine field HType from field HeapType.
6238   field_type_ = HType::FromType<HeapType>(field_type);
6239   DCHECK(field_type_.IsHeapObject());
6240
6241   // Add dependency on the map that introduced the field.
6242   top_info()->dependencies()->AssumeFieldType(GetFieldOwnerFromMap(map));
6243   return true;
6244 }
6245
6246
6247 bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() {
6248   Handle<Map> map = this->map();
6249
6250   while (map->prototype()->IsJSObject()) {
6251     holder_ = handle(JSObject::cast(map->prototype()));
6252     if (holder_->map()->is_deprecated()) {
6253       JSObject::TryMigrateInstance(holder_);
6254     }
6255     map = Handle<Map>(holder_->map());
6256     if (!CanInlinePropertyAccess(map)) {
6257       NotFound();
6258       return false;
6259     }
6260     LookupDescriptor(*map, *name_);
6261     if (IsFound()) return LoadResult(map);
6262   }
6263
6264   NotFound();
6265   return !map->prototype()->IsJSReceiver();
6266 }
6267
6268
6269 bool HOptimizedGraphBuilder::PropertyAccessInfo::IsIntegerIndexedExotic() {
6270   InstanceType instance_type = map_->instance_type();
6271   return instance_type == JS_TYPED_ARRAY_TYPE &&
6272          IsSpecialIndex(isolate()->unicode_cache(), *name_);
6273 }
6274
6275
6276 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() {
6277   if (!CanInlinePropertyAccess(map_)) return false;
6278   if (IsJSObjectFieldAccessor()) return IsLoad();
6279   if (IsJSArrayBufferViewFieldAccessor()) return IsLoad();
6280   if (map_->function_with_prototype() && !map_->has_non_instance_prototype() &&
6281       name_.is_identical_to(isolate()->factory()->prototype_string())) {
6282     return IsLoad();
6283   }
6284   if (!LookupDescriptor()) return false;
6285   if (IsFound()) return IsLoad() || !IsReadOnly();
6286   if (IsIntegerIndexedExotic()) return false;
6287   if (!LookupInPrototypes()) return false;
6288   if (IsLoad()) return true;
6289
6290   if (IsAccessorConstant()) return true;
6291   LookupTransition(*map_, *name_, NONE);
6292   if (IsTransitionToData() && map_->unused_property_fields() > 0) {
6293     // Construct the object field access.
6294     int descriptor = transition()->LastAdded();
6295     int index =
6296         transition()->instance_descriptors()->GetFieldIndex(descriptor) -
6297         map_->inobject_properties();
6298     PropertyDetails details =
6299         transition()->instance_descriptors()->GetDetails(descriptor);
6300     Representation representation = details.representation();
6301     access_ = HObjectAccess::ForField(map_, index, representation, name_);
6302
6303     // Load field map for heap objects.
6304     return LoadFieldMaps(transition());
6305   }
6306   return false;
6307 }
6308
6309
6310 bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic(
6311     SmallMapList* maps) {
6312   DCHECK(map_.is_identical_to(maps->first()));
6313   if (!CanAccessMonomorphic()) return false;
6314   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6315   if (maps->length() > kMaxLoadPolymorphism) return false;
6316   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6317   if (GetJSObjectFieldAccess(&access)) {
6318     for (int i = 1; i < maps->length(); ++i) {
6319       PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6320       HObjectAccess test_access = HObjectAccess::ForMap();  // bogus default
6321       if (!test_info.GetJSObjectFieldAccess(&test_access)) return false;
6322       if (!access.Equals(test_access)) return false;
6323     }
6324     return true;
6325   }
6326   if (GetJSArrayBufferViewFieldAccess(&access)) {
6327     for (int i = 1; i < maps->length(); ++i) {
6328       PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6329       HObjectAccess test_access = HObjectAccess::ForMap();  // bogus default
6330       if (!test_info.GetJSArrayBufferViewFieldAccess(&test_access)) {
6331         return false;
6332       }
6333       if (!access.Equals(test_access)) return false;
6334     }
6335     return true;
6336   }
6337
6338   // Currently only handle numbers as a polymorphic case.
6339   // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber
6340   // instruction.
6341   if (IsNumberType()) return false;
6342
6343   // Multiple maps cannot transition to the same target map.
6344   DCHECK(!IsLoad() || !IsTransition());
6345   if (IsTransition() && maps->length() > 1) return false;
6346
6347   for (int i = 1; i < maps->length(); ++i) {
6348     PropertyAccessInfo test_info(builder_, access_type_, maps->at(i), name_);
6349     if (!test_info.IsCompatible(this)) return false;
6350   }
6351
6352   return true;
6353 }
6354
6355
6356 Handle<Map> HOptimizedGraphBuilder::PropertyAccessInfo::map() {
6357   JSFunction* ctor = IC::GetRootConstructor(
6358       *map_, current_info()->closure()->context()->native_context());
6359   if (ctor != NULL) return handle(ctor->initial_map());
6360   return map_;
6361 }
6362
6363
6364 static bool NeedsWrapping(Handle<Map> map, Handle<JSFunction> target) {
6365   return !map->IsJSObjectMap() &&
6366          is_sloppy(target->shared()->language_mode()) &&
6367          !target->shared()->native();
6368 }
6369
6370
6371 bool HOptimizedGraphBuilder::PropertyAccessInfo::NeedsWrappingFor(
6372     Handle<JSFunction> target) const {
6373   return NeedsWrapping(map_, target);
6374 }
6375
6376
6377 HValue* HOptimizedGraphBuilder::BuildMonomorphicAccess(
6378     PropertyAccessInfo* info, HValue* object, HValue* checked_object,
6379     HValue* value, BailoutId ast_id, BailoutId return_id,
6380     bool can_inline_accessor) {
6381   HObjectAccess access = HObjectAccess::ForMap();  // bogus default
6382   if (info->GetJSObjectFieldAccess(&access)) {
6383     DCHECK(info->IsLoad());
6384     return New<HLoadNamedField>(object, checked_object, access);
6385   }
6386
6387   if (info->GetJSArrayBufferViewFieldAccess(&access)) {
6388     DCHECK(info->IsLoad());
6389     checked_object = Add<HCheckArrayBufferNotNeutered>(checked_object);
6390     return New<HLoadNamedField>(object, checked_object, access);
6391   }
6392
6393   if (info->name().is_identical_to(isolate()->factory()->prototype_string()) &&
6394       info->map()->function_with_prototype()) {
6395     DCHECK(!info->map()->has_non_instance_prototype());
6396     return New<HLoadFunctionPrototype>(checked_object);
6397   }
6398
6399   HValue* checked_holder = checked_object;
6400   if (info->has_holder()) {
6401     Handle<JSObject> prototype(JSObject::cast(info->map()->prototype()));
6402     checked_holder = BuildCheckPrototypeMaps(prototype, info->holder());
6403   }
6404
6405   if (!info->IsFound()) {
6406     DCHECK(info->IsLoad());
6407     if (is_strong(function_language_mode())) {
6408       return New<HCallRuntime>(
6409           isolate()->factory()->empty_string(),
6410           Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
6411           0);
6412     } else {
6413       return graph()->GetConstantUndefined();
6414     }
6415   }
6416
6417   if (info->IsData()) {
6418     if (info->IsLoad()) {
6419       return BuildLoadNamedField(info, checked_holder);
6420     } else {
6421       return BuildStoreNamedField(info, checked_object, value);
6422     }
6423   }
6424
6425   if (info->IsTransition()) {
6426     DCHECK(!info->IsLoad());
6427     return BuildStoreNamedField(info, checked_object, value);
6428   }
6429
6430   if (info->IsAccessorConstant()) {
6431     Push(checked_object);
6432     int argument_count = 1;
6433     if (!info->IsLoad()) {
6434       argument_count = 2;
6435       Push(value);
6436     }
6437
6438     if (info->NeedsWrappingFor(info->accessor())) {
6439       HValue* function = Add<HConstant>(info->accessor());
6440       PushArgumentsFromEnvironment(argument_count);
6441       return New<HCallFunction>(function, argument_count, WRAP_AND_CALL);
6442     } else if (FLAG_inline_accessors && can_inline_accessor) {
6443       bool success = info->IsLoad()
6444           ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id)
6445           : TryInlineSetter(
6446               info->accessor(), info->map(), ast_id, return_id, value);
6447       if (success || HasStackOverflow()) return NULL;
6448     }
6449
6450     PushArgumentsFromEnvironment(argument_count);
6451     return BuildCallConstantFunction(info->accessor(), argument_count);
6452   }
6453
6454   DCHECK(info->IsDataConstant());
6455   if (info->IsLoad()) {
6456     return New<HConstant>(info->constant());
6457   } else {
6458     return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant()));
6459   }
6460 }
6461
6462
6463 void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess(
6464     PropertyAccessType access_type, Expression* expr, BailoutId ast_id,
6465     BailoutId return_id, HValue* object, HValue* value, SmallMapList* maps,
6466     Handle<String> name) {
6467   // Something did not match; must use a polymorphic load.
6468   int count = 0;
6469   HBasicBlock* join = NULL;
6470   HBasicBlock* number_block = NULL;
6471   bool handled_string = false;
6472
6473   bool handle_smi = false;
6474   STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism);
6475   int i;
6476   for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6477     PropertyAccessInfo info(this, access_type, maps->at(i), name);
6478     if (info.IsStringType()) {
6479       if (handled_string) continue;
6480       handled_string = true;
6481     }
6482     if (info.CanAccessMonomorphic()) {
6483       count++;
6484       if (info.IsNumberType()) {
6485         handle_smi = true;
6486         break;
6487       }
6488     }
6489   }
6490
6491   if (i < maps->length()) {
6492     count = -1;
6493     maps->Clear();
6494   } else {
6495     count = 0;
6496   }
6497   HControlInstruction* smi_check = NULL;
6498   handled_string = false;
6499
6500   for (i = 0; i < maps->length() && count < kMaxLoadPolymorphism; ++i) {
6501     PropertyAccessInfo info(this, access_type, maps->at(i), name);
6502     if (info.IsStringType()) {
6503       if (handled_string) continue;
6504       handled_string = true;
6505     }
6506     if (!info.CanAccessMonomorphic()) continue;
6507
6508     if (count == 0) {
6509       join = graph()->CreateBasicBlock();
6510       if (handle_smi) {
6511         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
6512         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
6513         number_block = graph()->CreateBasicBlock();
6514         smi_check = New<HIsSmiAndBranch>(
6515             object, empty_smi_block, not_smi_block);
6516         FinishCurrentBlock(smi_check);
6517         GotoNoSimulate(empty_smi_block, number_block);
6518         set_current_block(not_smi_block);
6519       } else {
6520         BuildCheckHeapObject(object);
6521       }
6522     }
6523     ++count;
6524     HBasicBlock* if_true = graph()->CreateBasicBlock();
6525     HBasicBlock* if_false = graph()->CreateBasicBlock();
6526     HUnaryControlInstruction* compare;
6527
6528     HValue* dependency;
6529     if (info.IsNumberType()) {
6530       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
6531       compare = New<HCompareMap>(object, heap_number_map, if_true, if_false);
6532       dependency = smi_check;
6533     } else if (info.IsStringType()) {
6534       compare = New<HIsStringAndBranch>(object, if_true, if_false);
6535       dependency = compare;
6536     } else {
6537       compare = New<HCompareMap>(object, info.map(), if_true, if_false);
6538       dependency = compare;
6539     }
6540     FinishCurrentBlock(compare);
6541
6542     if (info.IsNumberType()) {
6543       GotoNoSimulate(if_true, number_block);
6544       if_true = number_block;
6545     }
6546
6547     set_current_block(if_true);
6548
6549     HValue* access =
6550         BuildMonomorphicAccess(&info, object, dependency, value, ast_id,
6551                                return_id, FLAG_polymorphic_inlining);
6552
6553     HValue* result = NULL;
6554     switch (access_type) {
6555       case LOAD:
6556         result = access;
6557         break;
6558       case STORE:
6559         result = value;
6560         break;
6561     }
6562
6563     if (access == NULL) {
6564       if (HasStackOverflow()) return;
6565     } else {
6566       if (access->IsInstruction()) {
6567         HInstruction* instr = HInstruction::cast(access);
6568         if (!instr->IsLinked()) AddInstruction(instr);
6569       }
6570       if (!ast_context()->IsEffect()) Push(result);
6571     }
6572
6573     if (current_block() != NULL) Goto(join);
6574     set_current_block(if_false);
6575   }
6576
6577   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
6578   // know about and do not want to handle ones we've never seen.  Otherwise
6579   // use a generic IC.
6580   if (count == maps->length() && FLAG_deoptimize_uncommon_cases) {
6581     FinishExitWithHardDeoptimization(
6582         Deoptimizer::kUnknownMapInPolymorphicAccess);
6583   } else {
6584     HInstruction* instr = BuildNamedGeneric(access_type, expr, object, name,
6585                                             value);
6586     AddInstruction(instr);
6587     if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value);
6588
6589     if (join != NULL) {
6590       Goto(join);
6591     } else {
6592       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6593       if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6594       return;
6595     }
6596   }
6597
6598   DCHECK(join != NULL);
6599   if (join->HasPredecessor()) {
6600     join->SetJoinId(ast_id);
6601     set_current_block(join);
6602     if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop());
6603   } else {
6604     set_current_block(NULL);
6605   }
6606 }
6607
6608
6609 static bool ComputeReceiverTypes(Expression* expr,
6610                                  HValue* receiver,
6611                                  SmallMapList** t,
6612                                  Zone* zone) {
6613   SmallMapList* maps = expr->GetReceiverTypes();
6614   *t = maps;
6615   bool monomorphic = expr->IsMonomorphic();
6616   if (maps != NULL && receiver->HasMonomorphicJSObjectType()) {
6617     Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap();
6618     maps->FilterForPossibleTransitions(root_map);
6619     monomorphic = maps->length() == 1;
6620   }
6621   return monomorphic && CanInlinePropertyAccess(maps->first());
6622 }
6623
6624
6625 static bool AreStringTypes(SmallMapList* maps) {
6626   for (int i = 0; i < maps->length(); i++) {
6627     if (maps->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false;
6628   }
6629   return true;
6630 }
6631
6632
6633 void HOptimizedGraphBuilder::BuildStore(Expression* expr,
6634                                         Property* prop,
6635                                         BailoutId ast_id,
6636                                         BailoutId return_id,
6637                                         bool is_uninitialized) {
6638   if (!prop->key()->IsPropertyName()) {
6639     // Keyed store.
6640     HValue* value = Pop();
6641     HValue* key = Pop();
6642     HValue* object = Pop();
6643     bool has_side_effects = false;
6644     HValue* result = HandleKeyedElementAccess(
6645         object, key, value, expr, ast_id, return_id, STORE, &has_side_effects);
6646     if (has_side_effects) {
6647       if (!ast_context()->IsEffect()) Push(value);
6648       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6649       if (!ast_context()->IsEffect()) Drop(1);
6650     }
6651     if (result == NULL) return;
6652     return ast_context()->ReturnValue(value);
6653   }
6654
6655   // Named store.
6656   HValue* value = Pop();
6657   HValue* object = Pop();
6658
6659   Literal* key = prop->key()->AsLiteral();
6660   Handle<String> name = Handle<String>::cast(key->value());
6661   DCHECK(!name.is_null());
6662
6663   HValue* access = BuildNamedAccess(STORE, ast_id, return_id, expr, object,
6664                                     name, value, is_uninitialized);
6665   if (access == NULL) return;
6666
6667   if (!ast_context()->IsEffect()) Push(value);
6668   if (access->IsInstruction()) AddInstruction(HInstruction::cast(access));
6669   if (access->HasObservableSideEffects()) {
6670     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6671   }
6672   if (!ast_context()->IsEffect()) Drop(1);
6673   return ast_context()->ReturnValue(value);
6674 }
6675
6676
6677 void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) {
6678   Property* prop = expr->target()->AsProperty();
6679   DCHECK(prop != NULL);
6680   CHECK_ALIVE(VisitForValue(prop->obj()));
6681   if (!prop->key()->IsPropertyName()) {
6682     CHECK_ALIVE(VisitForValue(prop->key()));
6683   }
6684   CHECK_ALIVE(VisitForValue(expr->value()));
6685   BuildStore(expr, prop, expr->id(),
6686              expr->AssignmentId(), expr->IsUninitialized());
6687 }
6688
6689
6690 // Because not every expression has a position and there is not common
6691 // superclass of Assignment and CountOperation, we cannot just pass the
6692 // owning expression instead of position and ast_id separately.
6693 void HOptimizedGraphBuilder::HandleGlobalVariableAssignment(
6694     Variable* var,
6695     HValue* value,
6696     BailoutId ast_id) {
6697   Handle<GlobalObject> global(current_info()->global_object());
6698
6699   // Lookup in script contexts.
6700   {
6701     Handle<ScriptContextTable> script_contexts(
6702         global->native_context()->script_context_table());
6703     ScriptContextTable::LookupResult lookup;
6704     if (ScriptContextTable::Lookup(script_contexts, var->name(), &lookup)) {
6705       if (lookup.mode == CONST) {
6706         return Bailout(kNonInitializerAssignmentToConst);
6707       }
6708       Handle<Context> script_context =
6709           ScriptContextTable::GetContext(script_contexts, lookup.context_index);
6710
6711       Handle<Object> current_value =
6712           FixedArray::get(script_context, lookup.slot_index);
6713
6714       // If the values is not the hole, it will stay initialized,
6715       // so no need to generate a check.
6716       if (*current_value == *isolate()->factory()->the_hole_value()) {
6717         return Bailout(kReferenceToUninitializedVariable);
6718       }
6719
6720       HStoreNamedField* instr = Add<HStoreNamedField>(
6721           Add<HConstant>(script_context),
6722           HObjectAccess::ForContextSlot(lookup.slot_index), value);
6723       USE(instr);
6724       DCHECK(instr->HasObservableSideEffects());
6725       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6726       return;
6727     }
6728   }
6729
6730   LookupIterator it(global, var->name(), LookupIterator::OWN);
6731   GlobalPropertyAccess type = LookupGlobalProperty(var, &it, STORE);
6732   if (type == kUseCell) {
6733     Handle<PropertyCell> cell = it.GetPropertyCell();
6734     top_info()->dependencies()->AssumePropertyCell(cell);
6735     auto cell_type = it.property_details().cell_type();
6736     if (cell_type == PropertyCellType::kConstant ||
6737         cell_type == PropertyCellType::kUndefined) {
6738       Handle<Object> constant(cell->value(), isolate());
6739       if (value->IsConstant()) {
6740         HConstant* c_value = HConstant::cast(value);
6741         if (!constant.is_identical_to(c_value->handle(isolate()))) {
6742           Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6743                            Deoptimizer::EAGER);
6744         }
6745       } else {
6746         HValue* c_constant = Add<HConstant>(constant);
6747         IfBuilder builder(this);
6748         if (constant->IsNumber()) {
6749           builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ);
6750         } else {
6751           builder.If<HCompareObjectEqAndBranch>(value, c_constant);
6752         }
6753         builder.Then();
6754         builder.Else();
6755         Add<HDeoptimize>(Deoptimizer::kConstantGlobalVariableAssignment,
6756                          Deoptimizer::EAGER);
6757         builder.End();
6758       }
6759     }
6760     HConstant* cell_constant = Add<HConstant>(cell);
6761     auto access = HObjectAccess::ForPropertyCellValue();
6762     if (cell_type == PropertyCellType::kConstantType) {
6763       switch (cell->GetConstantType()) {
6764         case PropertyCellConstantType::kSmi:
6765           access = access.WithRepresentation(Representation::Smi());
6766           break;
6767         case PropertyCellConstantType::kStableMap: {
6768           // The map may no longer be stable, deopt if it's ever different from
6769           // what is currently there, which will allow for restablization.
6770           Handle<Map> map(HeapObject::cast(cell->value())->map());
6771           Add<HCheckHeapObject>(value);
6772           value = Add<HCheckMaps>(value, map);
6773           access = access.WithRepresentation(Representation::HeapObject());
6774           break;
6775         }
6776       }
6777     }
6778     HInstruction* instr = Add<HStoreNamedField>(cell_constant, access, value);
6779     instr->ClearChangesFlag(kInobjectFields);
6780     instr->SetChangesFlag(kGlobalVars);
6781     if (instr->HasObservableSideEffects()) {
6782       Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6783     }
6784   } else if (var->IsGlobalSlot()) {
6785     DCHECK(var->index() > 0);
6786     DCHECK(var->IsStaticGlobalObjectProperty());
6787     int slot_index = var->index();
6788     int depth = scope()->ContextChainLength(var->scope());
6789
6790     HStoreGlobalViaContext* instr = Add<HStoreGlobalViaContext>(
6791         value, depth, slot_index, function_language_mode());
6792     USE(instr);
6793     DCHECK(instr->HasObservableSideEffects());
6794     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6795
6796   } else {
6797     HValue* global_object = Add<HLoadNamedField>(
6798         context(), nullptr,
6799         HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
6800     HStoreNamedGeneric* instr =
6801         Add<HStoreNamedGeneric>(global_object, var->name(), value,
6802                                 function_language_mode(), PREMONOMORPHIC);
6803     USE(instr);
6804     DCHECK(instr->HasObservableSideEffects());
6805     Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
6806   }
6807 }
6808
6809
6810 void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) {
6811   Expression* target = expr->target();
6812   VariableProxy* proxy = target->AsVariableProxy();
6813   Property* prop = target->AsProperty();
6814   DCHECK(proxy == NULL || prop == NULL);
6815
6816   // We have a second position recorded in the FullCodeGenerator to have
6817   // type feedback for the binary operation.
6818   BinaryOperation* operation = expr->binary_operation();
6819
6820   if (proxy != NULL) {
6821     Variable* var = proxy->var();
6822     if (var->mode() == LET)  {
6823       return Bailout(kUnsupportedLetCompoundAssignment);
6824     }
6825
6826     CHECK_ALIVE(VisitForValue(operation));
6827
6828     switch (var->location()) {
6829       case VariableLocation::GLOBAL:
6830       case VariableLocation::UNALLOCATED:
6831         HandleGlobalVariableAssignment(var,
6832                                        Top(),
6833                                        expr->AssignmentId());
6834         break;
6835
6836       case VariableLocation::PARAMETER:
6837       case VariableLocation::LOCAL:
6838         if (var->mode() == CONST_LEGACY)  {
6839           return Bailout(kUnsupportedConstCompoundAssignment);
6840         }
6841         if (var->mode() == CONST) {
6842           return Bailout(kNonInitializerAssignmentToConst);
6843         }
6844         BindIfLive(var, Top());
6845         break;
6846
6847       case VariableLocation::CONTEXT: {
6848         // Bail out if we try to mutate a parameter value in a function
6849         // using the arguments object.  We do not (yet) correctly handle the
6850         // arguments property of the function.
6851         if (current_info()->scope()->arguments() != NULL) {
6852           // Parameters will be allocated to context slots.  We have no
6853           // direct way to detect that the variable is a parameter so we do
6854           // a linear search of the parameter variables.
6855           int count = current_info()->scope()->num_parameters();
6856           for (int i = 0; i < count; ++i) {
6857             if (var == current_info()->scope()->parameter(i)) {
6858               Bailout(kAssignmentToParameterFunctionUsesArgumentsObject);
6859             }
6860           }
6861         }
6862
6863         HStoreContextSlot::Mode mode;
6864
6865         switch (var->mode()) {
6866           case LET:
6867             mode = HStoreContextSlot::kCheckDeoptimize;
6868             break;
6869           case CONST:
6870             return Bailout(kNonInitializerAssignmentToConst);
6871           case CONST_LEGACY:
6872             return ast_context()->ReturnValue(Pop());
6873           default:
6874             mode = HStoreContextSlot::kNoCheck;
6875         }
6876
6877         HValue* context = BuildContextChainWalk(var);
6878         HStoreContextSlot* instr = Add<HStoreContextSlot>(
6879             context, var->index(), mode, Top());
6880         if (instr->HasObservableSideEffects()) {
6881           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
6882         }
6883         break;
6884       }
6885
6886       case VariableLocation::LOOKUP:
6887         return Bailout(kCompoundAssignmentToLookupSlot);
6888     }
6889     return ast_context()->ReturnValue(Pop());
6890
6891   } else if (prop != NULL) {
6892     CHECK_ALIVE(VisitForValue(prop->obj()));
6893     HValue* object = Top();
6894     HValue* key = NULL;
6895     if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
6896       CHECK_ALIVE(VisitForValue(prop->key()));
6897       key = Top();
6898     }
6899
6900     CHECK_ALIVE(PushLoad(prop, object, key));
6901
6902     CHECK_ALIVE(VisitForValue(expr->value()));
6903     HValue* right = Pop();
6904     HValue* left = Pop();
6905
6906     Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE));
6907
6908     BuildStore(expr, prop, expr->id(),
6909                expr->AssignmentId(), expr->IsUninitialized());
6910   } else {
6911     return Bailout(kInvalidLhsInCompoundAssignment);
6912   }
6913 }
6914
6915
6916 void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) {
6917   DCHECK(!HasStackOverflow());
6918   DCHECK(current_block() != NULL);
6919   DCHECK(current_block()->HasPredecessor());
6920   VariableProxy* proxy = expr->target()->AsVariableProxy();
6921   Property* prop = expr->target()->AsProperty();
6922   DCHECK(proxy == NULL || prop == NULL);
6923
6924   if (expr->is_compound()) {
6925     HandleCompoundAssignment(expr);
6926     return;
6927   }
6928
6929   if (prop != NULL) {
6930     HandlePropertyAssignment(expr);
6931   } else if (proxy != NULL) {
6932     Variable* var = proxy->var();
6933
6934     if (var->mode() == CONST) {
6935       if (expr->op() != Token::INIT_CONST) {
6936         return Bailout(kNonInitializerAssignmentToConst);
6937       }
6938     } else if (var->mode() == CONST_LEGACY) {
6939       if (expr->op() != Token::INIT_CONST_LEGACY) {
6940         CHECK_ALIVE(VisitForValue(expr->value()));
6941         return ast_context()->ReturnValue(Pop());
6942       }
6943
6944       if (var->IsStackAllocated()) {
6945         // We insert a use of the old value to detect unsupported uses of const
6946         // variables (e.g. initialization inside a loop).
6947         HValue* old_value = environment()->Lookup(var);
6948         Add<HUseConst>(old_value);
6949       }
6950     }
6951
6952     if (proxy->IsArguments()) return Bailout(kAssignmentToArguments);
6953
6954     // Handle the assignment.
6955     switch (var->location()) {
6956       case VariableLocation::GLOBAL:
6957       case VariableLocation::UNALLOCATED:
6958         CHECK_ALIVE(VisitForValue(expr->value()));
6959         HandleGlobalVariableAssignment(var,
6960                                        Top(),
6961                                        expr->AssignmentId());
6962         return ast_context()->ReturnValue(Pop());
6963
6964       case VariableLocation::PARAMETER:
6965       case VariableLocation::LOCAL: {
6966         // Perform an initialization check for let declared variables
6967         // or parameters.
6968         if (var->mode() == LET && expr->op() == Token::ASSIGN) {
6969           HValue* env_value = environment()->Lookup(var);
6970           if (env_value == graph()->GetConstantHole()) {
6971             return Bailout(kAssignmentToLetVariableBeforeInitialization);
6972           }
6973         }
6974         // We do not allow the arguments object to occur in a context where it
6975         // may escape, but assignments to stack-allocated locals are
6976         // permitted.
6977         CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED));
6978         HValue* value = Pop();
6979         BindIfLive(var, value);
6980         return ast_context()->ReturnValue(value);
6981       }
6982
6983       case VariableLocation::CONTEXT: {
6984         // Bail out if we try to mutate a parameter value in a function using
6985         // the arguments object.  We do not (yet) correctly handle the
6986         // arguments property of the function.
6987         if (current_info()->scope()->arguments() != NULL) {
6988           // Parameters will rewrite to context slots.  We have no direct way
6989           // to detect that the variable is a parameter.
6990           int count = current_info()->scope()->num_parameters();
6991           for (int i = 0; i < count; ++i) {
6992             if (var == current_info()->scope()->parameter(i)) {
6993               return Bailout(kAssignmentToParameterInArgumentsObject);
6994             }
6995           }
6996         }
6997
6998         CHECK_ALIVE(VisitForValue(expr->value()));
6999         HStoreContextSlot::Mode mode;
7000         if (expr->op() == Token::ASSIGN) {
7001           switch (var->mode()) {
7002             case LET:
7003               mode = HStoreContextSlot::kCheckDeoptimize;
7004               break;
7005             case CONST:
7006               // This case is checked statically so no need to
7007               // perform checks here
7008               UNREACHABLE();
7009             case CONST_LEGACY:
7010               return ast_context()->ReturnValue(Pop());
7011             default:
7012               mode = HStoreContextSlot::kNoCheck;
7013           }
7014         } else if (expr->op() == Token::INIT_VAR ||
7015                    expr->op() == Token::INIT_LET ||
7016                    expr->op() == Token::INIT_CONST) {
7017           mode = HStoreContextSlot::kNoCheck;
7018         } else {
7019           DCHECK(expr->op() == Token::INIT_CONST_LEGACY);
7020
7021           mode = HStoreContextSlot::kCheckIgnoreAssignment;
7022         }
7023
7024         HValue* context = BuildContextChainWalk(var);
7025         HStoreContextSlot* instr = Add<HStoreContextSlot>(
7026             context, var->index(), mode, Top());
7027         if (instr->HasObservableSideEffects()) {
7028           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
7029         }
7030         return ast_context()->ReturnValue(Pop());
7031       }
7032
7033       case VariableLocation::LOOKUP:
7034         return Bailout(kAssignmentToLOOKUPVariable);
7035     }
7036   } else {
7037     return Bailout(kInvalidLeftHandSideInAssignment);
7038   }
7039 }
7040
7041
7042 void HOptimizedGraphBuilder::VisitYield(Yield* expr) {
7043   // Generators are not optimized, so we should never get here.
7044   UNREACHABLE();
7045 }
7046
7047
7048 void HOptimizedGraphBuilder::VisitThrow(Throw* expr) {
7049   DCHECK(!HasStackOverflow());
7050   DCHECK(current_block() != NULL);
7051   DCHECK(current_block()->HasPredecessor());
7052   if (!ast_context()->IsEffect()) {
7053     // The parser turns invalid left-hand sides in assignments into throw
7054     // statements, which may not be in effect contexts. We might still try
7055     // to optimize such functions; bail out now if we do.
7056     return Bailout(kInvalidLeftHandSideInAssignment);
7057   }
7058   CHECK_ALIVE(VisitForValue(expr->exception()));
7059
7060   HValue* value = environment()->Pop();
7061   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
7062   Add<HPushArguments>(value);
7063   Add<HCallRuntime>(isolate()->factory()->empty_string(),
7064                     Runtime::FunctionForId(Runtime::kThrow), 1);
7065   Add<HSimulate>(expr->id());
7066
7067   // If the throw definitely exits the function, we can finish with a dummy
7068   // control flow at this point.  This is not the case if the throw is inside
7069   // an inlined function which may be replaced.
7070   if (call_context() == NULL) {
7071     FinishExitCurrentBlock(New<HAbnormalExit>());
7072   }
7073 }
7074
7075
7076 HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) {
7077   if (string->IsConstant()) {
7078     HConstant* c_string = HConstant::cast(string);
7079     if (c_string->HasStringValue()) {
7080       return Add<HConstant>(c_string->StringValue()->map()->instance_type());
7081     }
7082   }
7083   return Add<HLoadNamedField>(
7084       Add<HLoadNamedField>(string, nullptr, HObjectAccess::ForMap()), nullptr,
7085       HObjectAccess::ForMapInstanceType());
7086 }
7087
7088
7089 HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) {
7090   return AddInstruction(BuildLoadStringLength(string));
7091 }
7092
7093
7094 HInstruction* HGraphBuilder::BuildLoadStringLength(HValue* string) {
7095   if (string->IsConstant()) {
7096     HConstant* c_string = HConstant::cast(string);
7097     if (c_string->HasStringValue()) {
7098       return New<HConstant>(c_string->StringValue()->length());
7099     }
7100   }
7101   return New<HLoadNamedField>(string, nullptr,
7102                               HObjectAccess::ForStringLength());
7103 }
7104
7105
7106 HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric(
7107     PropertyAccessType access_type, Expression* expr, HValue* object,
7108     Handle<String> name, HValue* value, bool is_uninitialized) {
7109   if (is_uninitialized) {
7110     Add<HDeoptimize>(
7111         Deoptimizer::kInsufficientTypeFeedbackForGenericNamedAccess,
7112         Deoptimizer::SOFT);
7113   }
7114   if (access_type == LOAD) {
7115     Handle<TypeFeedbackVector> vector =
7116         handle(current_feedback_vector(), isolate());
7117     FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot();
7118
7119     if (!expr->AsProperty()->key()->IsPropertyName()) {
7120       // It's possible that a keyed load of a constant string was converted
7121       // to a named load. Here, at the last minute, we need to make sure to
7122       // use a generic Keyed Load if we are using the type vector, because
7123       // it has to share information with full code.
7124       HConstant* key = Add<HConstant>(name);
7125       HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7126           object, key, function_language_mode(), PREMONOMORPHIC);
7127       result->SetVectorAndSlot(vector, slot);
7128       return result;
7129     }
7130
7131     HLoadNamedGeneric* result = New<HLoadNamedGeneric>(
7132         object, name, function_language_mode(), PREMONOMORPHIC);
7133     result->SetVectorAndSlot(vector, slot);
7134     return result;
7135   } else {
7136     return New<HStoreNamedGeneric>(object, name, value,
7137                                    function_language_mode(), PREMONOMORPHIC);
7138   }
7139 }
7140
7141
7142
7143 HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric(
7144     PropertyAccessType access_type,
7145     Expression* expr,
7146     HValue* object,
7147     HValue* key,
7148     HValue* value) {
7149   if (access_type == LOAD) {
7150     InlineCacheState initial_state = expr->AsProperty()->GetInlineCacheState();
7151     HLoadKeyedGeneric* result = New<HLoadKeyedGeneric>(
7152         object, key, function_language_mode(), initial_state);
7153     // HLoadKeyedGeneric with vector ics benefits from being encoded as
7154     // MEGAMORPHIC because the vector/slot combo becomes unnecessary.
7155     if (initial_state != MEGAMORPHIC) {
7156       // We need to pass vector information.
7157       Handle<TypeFeedbackVector> vector =
7158           handle(current_feedback_vector(), isolate());
7159       FeedbackVectorICSlot slot = expr->AsProperty()->PropertyFeedbackSlot();
7160       result->SetVectorAndSlot(vector, slot);
7161     }
7162     return result;
7163   } else {
7164     return New<HStoreKeyedGeneric>(object, key, value, function_language_mode(),
7165                                    PREMONOMORPHIC);
7166   }
7167 }
7168
7169
7170 LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) {
7171   // Loads from a "stock" fast holey double arrays can elide the hole check.
7172   // Loads from a "stock" fast holey array can convert the hole to undefined
7173   // with impunity.
7174   LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE;
7175   bool holey_double_elements =
7176       *map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS);
7177   bool holey_elements =
7178       *map == isolate()->get_initial_js_array_map(FAST_HOLEY_ELEMENTS);
7179   if ((holey_double_elements || holey_elements) &&
7180       isolate()->IsFastArrayConstructorPrototypeChainIntact()) {
7181     load_mode =
7182         holey_double_elements ? ALLOW_RETURN_HOLE : CONVERT_HOLE_TO_UNDEFINED;
7183
7184     Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate());
7185     Handle<JSObject> object_prototype = isolate()->initial_object_prototype();
7186     BuildCheckPrototypeMaps(prototype, object_prototype);
7187     graph()->MarkDependsOnEmptyArrayProtoElements();
7188   }
7189   return load_mode;
7190 }
7191
7192
7193 HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess(
7194     HValue* object,
7195     HValue* key,
7196     HValue* val,
7197     HValue* dependency,
7198     Handle<Map> map,
7199     PropertyAccessType access_type,
7200     KeyedAccessStoreMode store_mode) {
7201   HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency);
7202
7203   if (access_type == STORE && map->prototype()->IsJSObject()) {
7204     // monomorphic stores need a prototype chain check because shape
7205     // changes could allow callbacks on elements in the chain that
7206     // aren't compatible with monomorphic keyed stores.
7207     PrototypeIterator iter(map);
7208     JSObject* holder = NULL;
7209     while (!iter.IsAtEnd()) {
7210       holder = JSObject::cast(*PrototypeIterator::GetCurrent(iter));
7211       iter.Advance();
7212     }
7213     DCHECK(holder && holder->IsJSObject());
7214
7215     BuildCheckPrototypeMaps(handle(JSObject::cast(map->prototype())),
7216                             Handle<JSObject>(holder));
7217   }
7218
7219   LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7220   return BuildUncheckedMonomorphicElementAccess(
7221       checked_object, key, val,
7222       map->instance_type() == JS_ARRAY_TYPE,
7223       map->elements_kind(), access_type,
7224       load_mode, store_mode);
7225 }
7226
7227
7228 static bool CanInlineElementAccess(Handle<Map> map) {
7229   return map->IsJSObjectMap() && !map->has_dictionary_elements() &&
7230          !map->has_sloppy_arguments_elements() &&
7231          !map->has_indexed_interceptor() && !map->is_access_check_needed();
7232 }
7233
7234
7235 HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad(
7236     HValue* object,
7237     HValue* key,
7238     HValue* val,
7239     SmallMapList* maps) {
7240   // For polymorphic loads of similar elements kinds (i.e. all tagged or all
7241   // double), always use the "worst case" code without a transition.  This is
7242   // much faster than transitioning the elements to the worst case, trading a
7243   // HTransitionElements for a HCheckMaps, and avoiding mutation of the array.
7244   bool has_double_maps = false;
7245   bool has_smi_or_object_maps = false;
7246   bool has_js_array_access = false;
7247   bool has_non_js_array_access = false;
7248   bool has_seen_holey_elements = false;
7249   Handle<Map> most_general_consolidated_map;
7250   for (int i = 0; i < maps->length(); ++i) {
7251     Handle<Map> map = maps->at(i);
7252     if (!CanInlineElementAccess(map)) return NULL;
7253     // Don't allow mixing of JSArrays with JSObjects.
7254     if (map->instance_type() == JS_ARRAY_TYPE) {
7255       if (has_non_js_array_access) return NULL;
7256       has_js_array_access = true;
7257     } else if (has_js_array_access) {
7258       return NULL;
7259     } else {
7260       has_non_js_array_access = true;
7261     }
7262     // Don't allow mixed, incompatible elements kinds.
7263     if (map->has_fast_double_elements()) {
7264       if (has_smi_or_object_maps) return NULL;
7265       has_double_maps = true;
7266     } else if (map->has_fast_smi_or_object_elements()) {
7267       if (has_double_maps) return NULL;
7268       has_smi_or_object_maps = true;
7269     } else {
7270       return NULL;
7271     }
7272     // Remember if we've ever seen holey elements.
7273     if (IsHoleyElementsKind(map->elements_kind())) {
7274       has_seen_holey_elements = true;
7275     }
7276     // Remember the most general elements kind, the code for its load will
7277     // properly handle all of the more specific cases.
7278     if ((i == 0) || IsMoreGeneralElementsKindTransition(
7279             most_general_consolidated_map->elements_kind(),
7280             map->elements_kind())) {
7281       most_general_consolidated_map = map;
7282     }
7283   }
7284   if (!has_double_maps && !has_smi_or_object_maps) return NULL;
7285
7286   HCheckMaps* checked_object = Add<HCheckMaps>(object, maps);
7287   // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS.
7288   // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS.
7289   ElementsKind consolidated_elements_kind = has_seen_holey_elements
7290       ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind())
7291       : most_general_consolidated_map->elements_kind();
7292   HInstruction* instr = BuildUncheckedMonomorphicElementAccess(
7293       checked_object, key, val,
7294       most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE,
7295       consolidated_elements_kind,
7296       LOAD, NEVER_RETURN_HOLE, STANDARD_STORE);
7297   return instr;
7298 }
7299
7300
7301 HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess(
7302     Expression* expr,
7303     HValue* object,
7304     HValue* key,
7305     HValue* val,
7306     SmallMapList* maps,
7307     PropertyAccessType access_type,
7308     KeyedAccessStoreMode store_mode,
7309     bool* has_side_effects) {
7310   *has_side_effects = false;
7311   BuildCheckHeapObject(object);
7312
7313   if (access_type == LOAD) {
7314     HInstruction* consolidated_load =
7315         TryBuildConsolidatedElementLoad(object, key, val, maps);
7316     if (consolidated_load != NULL) {
7317       *has_side_effects |= consolidated_load->HasObservableSideEffects();
7318       return consolidated_load;
7319     }
7320   }
7321
7322   // Elements_kind transition support.
7323   MapHandleList transition_target(maps->length());
7324   // Collect possible transition targets.
7325   MapHandleList possible_transitioned_maps(maps->length());
7326   for (int i = 0; i < maps->length(); ++i) {
7327     Handle<Map> map = maps->at(i);
7328     // Loads from strings or loads with a mix of string and non-string maps
7329     // shouldn't be handled polymorphically.
7330     DCHECK(access_type != LOAD || !map->IsStringMap());
7331     ElementsKind elements_kind = map->elements_kind();
7332     if (CanInlineElementAccess(map) && IsFastElementsKind(elements_kind) &&
7333         elements_kind != GetInitialFastElementsKind()) {
7334       possible_transitioned_maps.Add(map);
7335     }
7336     if (IsSloppyArgumentsElements(elements_kind)) {
7337       HInstruction* result = BuildKeyedGeneric(access_type, expr, object, key,
7338                                                val);
7339       *has_side_effects = result->HasObservableSideEffects();
7340       return AddInstruction(result);
7341     }
7342   }
7343   // Get transition target for each map (NULL == no transition).
7344   for (int i = 0; i < maps->length(); ++i) {
7345     Handle<Map> map = maps->at(i);
7346     Handle<Map> transitioned_map =
7347         Map::FindTransitionedMap(map, &possible_transitioned_maps);
7348     transition_target.Add(transitioned_map);
7349   }
7350
7351   MapHandleList untransitionable_maps(maps->length());
7352   HTransitionElementsKind* transition = NULL;
7353   for (int i = 0; i < maps->length(); ++i) {
7354     Handle<Map> map = maps->at(i);
7355     DCHECK(map->IsMap());
7356     if (!transition_target.at(i).is_null()) {
7357       DCHECK(Map::IsValidElementsTransition(
7358           map->elements_kind(),
7359           transition_target.at(i)->elements_kind()));
7360       transition = Add<HTransitionElementsKind>(object, map,
7361                                                 transition_target.at(i));
7362     } else {
7363       untransitionable_maps.Add(map);
7364     }
7365   }
7366
7367   // If only one map is left after transitioning, handle this case
7368   // monomorphically.
7369   DCHECK(untransitionable_maps.length() >= 1);
7370   if (untransitionable_maps.length() == 1) {
7371     Handle<Map> untransitionable_map = untransitionable_maps[0];
7372     HInstruction* instr = NULL;
7373     if (!CanInlineElementAccess(untransitionable_map)) {
7374       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7375                                                val));
7376     } else {
7377       instr = BuildMonomorphicElementAccess(
7378           object, key, val, transition, untransitionable_map, access_type,
7379           store_mode);
7380     }
7381     *has_side_effects |= instr->HasObservableSideEffects();
7382     return access_type == STORE ? val : instr;
7383   }
7384
7385   HBasicBlock* join = graph()->CreateBasicBlock();
7386
7387   for (int i = 0; i < untransitionable_maps.length(); ++i) {
7388     Handle<Map> map = untransitionable_maps[i];
7389     ElementsKind elements_kind = map->elements_kind();
7390     HBasicBlock* this_map = graph()->CreateBasicBlock();
7391     HBasicBlock* other_map = graph()->CreateBasicBlock();
7392     HCompareMap* mapcompare =
7393         New<HCompareMap>(object, map, this_map, other_map);
7394     FinishCurrentBlock(mapcompare);
7395
7396     set_current_block(this_map);
7397     HInstruction* access = NULL;
7398     if (!CanInlineElementAccess(map)) {
7399       access = AddInstruction(BuildKeyedGeneric(access_type, expr, object, key,
7400                                                 val));
7401     } else {
7402       DCHECK(IsFastElementsKind(elements_kind) ||
7403              IsFixedTypedArrayElementsKind(elements_kind));
7404       LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map);
7405       // Happily, mapcompare is a checked object.
7406       access = BuildUncheckedMonomorphicElementAccess(
7407           mapcompare, key, val,
7408           map->instance_type() == JS_ARRAY_TYPE,
7409           elements_kind, access_type,
7410           load_mode,
7411           store_mode);
7412     }
7413     *has_side_effects |= access->HasObservableSideEffects();
7414     // The caller will use has_side_effects and add a correct Simulate.
7415     access->SetFlag(HValue::kHasNoObservableSideEffects);
7416     if (access_type == LOAD) {
7417       Push(access);
7418     }
7419     NoObservableSideEffectsScope scope(this);
7420     GotoNoSimulate(join);
7421     set_current_block(other_map);
7422   }
7423
7424   // Ensure that we visited at least one map above that goes to join. This is
7425   // necessary because FinishExitWithHardDeoptimization does an AbnormalExit
7426   // rather than joining the join block. If this becomes an issue, insert a
7427   // generic access in the case length() == 0.
7428   DCHECK(join->predecessors()->length() > 0);
7429   // Deopt if none of the cases matched.
7430   NoObservableSideEffectsScope scope(this);
7431   FinishExitWithHardDeoptimization(
7432       Deoptimizer::kUnknownMapInPolymorphicElementAccess);
7433   set_current_block(join);
7434   return access_type == STORE ? val : Pop();
7435 }
7436
7437
7438 HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess(
7439     HValue* obj, HValue* key, HValue* val, Expression* expr, BailoutId ast_id,
7440     BailoutId return_id, PropertyAccessType access_type,
7441     bool* has_side_effects) {
7442   if (key->ActualValue()->IsConstant()) {
7443     Handle<Object> constant =
7444         HConstant::cast(key->ActualValue())->handle(isolate());
7445     uint32_t array_index;
7446     if (constant->IsString() &&
7447         !Handle<String>::cast(constant)->AsArrayIndex(&array_index)) {
7448       if (!constant->IsUniqueName()) {
7449         constant = isolate()->factory()->InternalizeString(
7450             Handle<String>::cast(constant));
7451       }
7452       HValue* access =
7453           BuildNamedAccess(access_type, ast_id, return_id, expr, obj,
7454                            Handle<String>::cast(constant), val, false);
7455       if (access == NULL || access->IsPhi() ||
7456           HInstruction::cast(access)->IsLinked()) {
7457         *has_side_effects = false;
7458       } else {
7459         HInstruction* instr = HInstruction::cast(access);
7460         AddInstruction(instr);
7461         *has_side_effects = instr->HasObservableSideEffects();
7462       }
7463       return access;
7464     }
7465   }
7466
7467   DCHECK(!expr->IsPropertyName());
7468   HInstruction* instr = NULL;
7469
7470   SmallMapList* maps;
7471   bool monomorphic = ComputeReceiverTypes(expr, obj, &maps, zone());
7472
7473   bool force_generic = false;
7474   if (expr->GetKeyType() == PROPERTY) {
7475     // Non-Generic accesses assume that elements are being accessed, and will
7476     // deopt for non-index keys, which the IC knows will occur.
7477     // TODO(jkummerow): Consider adding proper support for property accesses.
7478     force_generic = true;
7479     monomorphic = false;
7480   } else if (access_type == STORE &&
7481              (monomorphic || (maps != NULL && !maps->is_empty()))) {
7482     // Stores can't be mono/polymorphic if their prototype chain has dictionary
7483     // elements. However a receiver map that has dictionary elements itself
7484     // should be left to normal mono/poly behavior (the other maps may benefit
7485     // from highly optimized stores).
7486     for (int i = 0; i < maps->length(); i++) {
7487       Handle<Map> current_map = maps->at(i);
7488       if (current_map->DictionaryElementsInPrototypeChainOnly()) {
7489         force_generic = true;
7490         monomorphic = false;
7491         break;
7492       }
7493     }
7494   } else if (access_type == LOAD && !monomorphic &&
7495              (maps != NULL && !maps->is_empty())) {
7496     // Polymorphic loads have to go generic if any of the maps are strings.
7497     // If some, but not all of the maps are strings, we should go generic
7498     // because polymorphic access wants to key on ElementsKind and isn't
7499     // compatible with strings.
7500     for (int i = 0; i < maps->length(); i++) {
7501       Handle<Map> current_map = maps->at(i);
7502       if (current_map->IsStringMap()) {
7503         force_generic = true;
7504         break;
7505       }
7506     }
7507   }
7508
7509   if (monomorphic) {
7510     Handle<Map> map = maps->first();
7511     if (!CanInlineElementAccess(map)) {
7512       instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key,
7513                                                val));
7514     } else {
7515       BuildCheckHeapObject(obj);
7516       instr = BuildMonomorphicElementAccess(
7517           obj, key, val, NULL, map, access_type, expr->GetStoreMode());
7518     }
7519   } else if (!force_generic && (maps != NULL && !maps->is_empty())) {
7520     return HandlePolymorphicElementAccess(expr, obj, key, val, maps,
7521                                           access_type, expr->GetStoreMode(),
7522                                           has_side_effects);
7523   } else {
7524     if (access_type == STORE) {
7525       if (expr->IsAssignment() &&
7526           expr->AsAssignment()->HasNoTypeInformation()) {
7527         Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedStore,
7528                          Deoptimizer::SOFT);
7529       }
7530     } else {
7531       if (expr->AsProperty()->HasNoTypeInformation()) {
7532         Add<HDeoptimize>(Deoptimizer::kInsufficientTypeFeedbackForKeyedLoad,
7533                          Deoptimizer::SOFT);
7534       }
7535     }
7536     instr = AddInstruction(BuildKeyedGeneric(access_type, expr, obj, key, val));
7537   }
7538   *has_side_effects = instr->HasObservableSideEffects();
7539   return instr;
7540 }
7541
7542
7543 void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() {
7544   // Outermost function already has arguments on the stack.
7545   if (function_state()->outer() == NULL) return;
7546
7547   if (function_state()->arguments_pushed()) return;
7548
7549   // Push arguments when entering inlined function.
7550   HEnterInlined* entry = function_state()->entry();
7551   entry->set_arguments_pushed();
7552
7553   HArgumentsObject* arguments = entry->arguments_object();
7554   const ZoneList<HValue*>* arguments_values = arguments->arguments_values();
7555
7556   HInstruction* insert_after = entry;
7557   for (int i = 0; i < arguments_values->length(); i++) {
7558     HValue* argument = arguments_values->at(i);
7559     HInstruction* push_argument = New<HPushArguments>(argument);
7560     push_argument->InsertAfter(insert_after);
7561     insert_after = push_argument;
7562   }
7563
7564   HArgumentsElements* arguments_elements = New<HArgumentsElements>(true);
7565   arguments_elements->ClearFlag(HValue::kUseGVN);
7566   arguments_elements->InsertAfter(insert_after);
7567   function_state()->set_arguments_elements(arguments_elements);
7568 }
7569
7570
7571 bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) {
7572   VariableProxy* proxy = expr->obj()->AsVariableProxy();
7573   if (proxy == NULL) return false;
7574   if (!proxy->var()->IsStackAllocated()) return false;
7575   if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) {
7576     return false;
7577   }
7578
7579   HInstruction* result = NULL;
7580   if (expr->key()->IsPropertyName()) {
7581     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7582     if (!String::Equals(name, isolate()->factory()->length_string())) {
7583       return false;
7584     }
7585
7586     if (function_state()->outer() == NULL) {
7587       HInstruction* elements = Add<HArgumentsElements>(false);
7588       result = New<HArgumentsLength>(elements);
7589     } else {
7590       // Number of arguments without receiver.
7591       int argument_count = environment()->
7592           arguments_environment()->parameter_count() - 1;
7593       result = New<HConstant>(argument_count);
7594     }
7595   } else {
7596     Push(graph()->GetArgumentsObject());
7597     CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true);
7598     HValue* key = Pop();
7599     Drop(1);  // Arguments object.
7600     if (function_state()->outer() == NULL) {
7601       HInstruction* elements = Add<HArgumentsElements>(false);
7602       HInstruction* length = Add<HArgumentsLength>(elements);
7603       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7604       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7605     } else {
7606       EnsureArgumentsArePushedForAccess();
7607
7608       // Number of arguments without receiver.
7609       HInstruction* elements = function_state()->arguments_elements();
7610       int argument_count = environment()->
7611           arguments_environment()->parameter_count() - 1;
7612       HInstruction* length = Add<HConstant>(argument_count);
7613       HInstruction* checked_key = Add<HBoundsCheck>(key, length);
7614       result = New<HAccessArgumentsAt>(elements, length, checked_key);
7615     }
7616   }
7617   ast_context()->ReturnInstruction(result, expr->id());
7618   return true;
7619 }
7620
7621
7622 HValue* HOptimizedGraphBuilder::BuildNamedAccess(
7623     PropertyAccessType access, BailoutId ast_id, BailoutId return_id,
7624     Expression* expr, HValue* object, Handle<String> name, HValue* value,
7625     bool is_uninitialized) {
7626   SmallMapList* maps;
7627   ComputeReceiverTypes(expr, object, &maps, zone());
7628   DCHECK(maps != NULL);
7629
7630   if (maps->length() > 0) {
7631     PropertyAccessInfo info(this, access, maps->first(), name);
7632     if (!info.CanAccessAsMonomorphic(maps)) {
7633       HandlePolymorphicNamedFieldAccess(access, expr, ast_id, return_id, object,
7634                                         value, maps, name);
7635       return NULL;
7636     }
7637
7638     HValue* checked_object;
7639     // Type::Number() is only supported by polymorphic load/call handling.
7640     DCHECK(!info.IsNumberType());
7641     BuildCheckHeapObject(object);
7642     if (AreStringTypes(maps)) {
7643       checked_object =
7644           Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING);
7645     } else {
7646       checked_object = Add<HCheckMaps>(object, maps);
7647     }
7648     return BuildMonomorphicAccess(
7649         &info, object, checked_object, value, ast_id, return_id);
7650   }
7651
7652   return BuildNamedGeneric(access, expr, object, name, value, is_uninitialized);
7653 }
7654
7655
7656 void HOptimizedGraphBuilder::PushLoad(Property* expr,
7657                                       HValue* object,
7658                                       HValue* key) {
7659   ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED);
7660   Push(object);
7661   if (key != NULL) Push(key);
7662   BuildLoad(expr, expr->LoadId());
7663 }
7664
7665
7666 void HOptimizedGraphBuilder::BuildLoad(Property* expr,
7667                                        BailoutId ast_id) {
7668   HInstruction* instr = NULL;
7669   if (expr->IsStringAccess()) {
7670     HValue* index = Pop();
7671     HValue* string = Pop();
7672     HInstruction* char_code = BuildStringCharCodeAt(string, index);
7673     AddInstruction(char_code);
7674     instr = NewUncasted<HStringCharFromCode>(char_code);
7675
7676   } else if (expr->key()->IsPropertyName()) {
7677     Handle<String> name = expr->key()->AsLiteral()->AsPropertyName();
7678     HValue* object = Pop();
7679
7680     HValue* value = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr, object,
7681                                      name, NULL, expr->IsUninitialized());
7682     if (value == NULL) return;
7683     if (value->IsPhi()) return ast_context()->ReturnValue(value);
7684     instr = HInstruction::cast(value);
7685     if (instr->IsLinked()) return ast_context()->ReturnValue(instr);
7686
7687   } else {
7688     HValue* key = Pop();
7689     HValue* obj = Pop();
7690
7691     bool has_side_effects = false;
7692     HValue* load = HandleKeyedElementAccess(
7693         obj, key, NULL, expr, ast_id, expr->LoadId(), LOAD, &has_side_effects);
7694     if (has_side_effects) {
7695       if (ast_context()->IsEffect()) {
7696         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7697       } else {
7698         Push(load);
7699         Add<HSimulate>(ast_id, REMOVABLE_SIMULATE);
7700         Drop(1);
7701       }
7702     }
7703     if (load == NULL) return;
7704     return ast_context()->ReturnValue(load);
7705   }
7706   return ast_context()->ReturnInstruction(instr, ast_id);
7707 }
7708
7709
7710 void HOptimizedGraphBuilder::VisitProperty(Property* expr) {
7711   DCHECK(!HasStackOverflow());
7712   DCHECK(current_block() != NULL);
7713   DCHECK(current_block()->HasPredecessor());
7714
7715   if (TryArgumentsAccess(expr)) return;
7716
7717   CHECK_ALIVE(VisitForValue(expr->obj()));
7718   if (!expr->key()->IsPropertyName() || expr->IsStringAccess()) {
7719     CHECK_ALIVE(VisitForValue(expr->key()));
7720   }
7721
7722   BuildLoad(expr, expr->id());
7723 }
7724
7725
7726 HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) {
7727   HCheckMaps* check = Add<HCheckMaps>(
7728       Add<HConstant>(constant), handle(constant->map()));
7729   check->ClearDependsOnFlag(kElementsKind);
7730   return check;
7731 }
7732
7733
7734 HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype,
7735                                                      Handle<JSObject> holder) {
7736   PrototypeIterator iter(isolate(), prototype,
7737                          PrototypeIterator::START_AT_RECEIVER);
7738   while (holder.is_null() ||
7739          !PrototypeIterator::GetCurrent(iter).is_identical_to(holder)) {
7740     BuildConstantMapCheck(
7741         Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7742     iter.Advance();
7743     if (iter.IsAtEnd()) {
7744       return NULL;
7745     }
7746   }
7747   return BuildConstantMapCheck(
7748       Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)));
7749 }
7750
7751
7752 void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder,
7753                                                    Handle<Map> receiver_map) {
7754   if (!holder.is_null()) {
7755     Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
7756     BuildCheckPrototypeMaps(prototype, holder);
7757   }
7758 }
7759
7760
7761 HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall(
7762     HValue* fun, int argument_count, bool pass_argument_count) {
7763   return New<HCallJSFunction>(fun, argument_count, pass_argument_count);
7764 }
7765
7766
7767 HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall(
7768     HValue* fun, HValue* context,
7769     int argument_count, HValue* expected_param_count) {
7770   ArgumentAdaptorDescriptor descriptor(isolate());
7771   HValue* arity = Add<HConstant>(argument_count - 1);
7772
7773   HValue* op_vals[] = { context, fun, arity, expected_param_count };
7774
7775   Handle<Code> adaptor =
7776       isolate()->builtins()->ArgumentsAdaptorTrampoline();
7777   HConstant* adaptor_value = Add<HConstant>(adaptor);
7778
7779   return New<HCallWithDescriptor>(adaptor_value, argument_count, descriptor,
7780                                   Vector<HValue*>(op_vals, arraysize(op_vals)));
7781 }
7782
7783
7784 HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction(
7785     Handle<JSFunction> jsfun, int argument_count) {
7786   HValue* target = Add<HConstant>(jsfun);
7787   // For constant functions, we try to avoid calling the
7788   // argument adaptor and instead call the function directly
7789   int formal_parameter_count =
7790       jsfun->shared()->internal_formal_parameter_count();
7791   bool dont_adapt_arguments =
7792       (formal_parameter_count ==
7793        SharedFunctionInfo::kDontAdaptArgumentsSentinel);
7794   int arity = argument_count - 1;
7795   bool can_invoke_directly =
7796       dont_adapt_arguments || formal_parameter_count == arity;
7797   if (can_invoke_directly) {
7798     if (jsfun.is_identical_to(current_info()->closure())) {
7799       graph()->MarkRecursive();
7800     }
7801     return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments);
7802   } else {
7803     HValue* param_count_value = Add<HConstant>(formal_parameter_count);
7804     HValue* context = Add<HLoadNamedField>(
7805         target, nullptr, HObjectAccess::ForFunctionContextPointer());
7806     return NewArgumentAdaptorCall(target, context,
7807         argument_count, param_count_value);
7808   }
7809   UNREACHABLE();
7810   return NULL;
7811 }
7812
7813
7814 class FunctionSorter {
7815  public:
7816   explicit FunctionSorter(int index = 0, int ticks = 0, int size = 0)
7817       : index_(index), ticks_(ticks), size_(size) {}
7818
7819   int index() const { return index_; }
7820   int ticks() const { return ticks_; }
7821   int size() const { return size_; }
7822
7823  private:
7824   int index_;
7825   int ticks_;
7826   int size_;
7827 };
7828
7829
7830 inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) {
7831   int diff = lhs.ticks() - rhs.ticks();
7832   if (diff != 0) return diff > 0;
7833   return lhs.size() < rhs.size();
7834 }
7835
7836
7837 void HOptimizedGraphBuilder::HandlePolymorphicCallNamed(Call* expr,
7838                                                         HValue* receiver,
7839                                                         SmallMapList* maps,
7840                                                         Handle<String> name) {
7841   int argument_count = expr->arguments()->length() + 1;  // Includes receiver.
7842   FunctionSorter order[kMaxCallPolymorphism];
7843
7844   bool handle_smi = false;
7845   bool handled_string = false;
7846   int ordered_functions = 0;
7847
7848   int i;
7849   for (i = 0; i < maps->length() && ordered_functions < kMaxCallPolymorphism;
7850        ++i) {
7851     PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7852     if (info.CanAccessMonomorphic() && info.IsDataConstant() &&
7853         info.constant()->IsJSFunction()) {
7854       if (info.IsStringType()) {
7855         if (handled_string) continue;
7856         handled_string = true;
7857       }
7858       Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7859       if (info.IsNumberType()) {
7860         handle_smi = true;
7861       }
7862       expr->set_target(target);
7863       order[ordered_functions++] = FunctionSorter(
7864           i, target->shared()->profiler_ticks(), InliningAstSize(target));
7865     }
7866   }
7867
7868   std::sort(order, order + ordered_functions);
7869
7870   if (i < maps->length()) {
7871     maps->Clear();
7872     ordered_functions = -1;
7873   }
7874
7875   HBasicBlock* number_block = NULL;
7876   HBasicBlock* join = NULL;
7877   handled_string = false;
7878   int count = 0;
7879
7880   for (int fn = 0; fn < ordered_functions; ++fn) {
7881     int i = order[fn].index();
7882     PropertyAccessInfo info(this, LOAD, maps->at(i), name);
7883     if (info.IsStringType()) {
7884       if (handled_string) continue;
7885       handled_string = true;
7886     }
7887     // Reloads the target.
7888     info.CanAccessMonomorphic();
7889     Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant());
7890
7891     expr->set_target(target);
7892     if (count == 0) {
7893       // Only needed once.
7894       join = graph()->CreateBasicBlock();
7895       if (handle_smi) {
7896         HBasicBlock* empty_smi_block = graph()->CreateBasicBlock();
7897         HBasicBlock* not_smi_block = graph()->CreateBasicBlock();
7898         number_block = graph()->CreateBasicBlock();
7899         FinishCurrentBlock(New<HIsSmiAndBranch>(
7900                 receiver, empty_smi_block, not_smi_block));
7901         GotoNoSimulate(empty_smi_block, number_block);
7902         set_current_block(not_smi_block);
7903       } else {
7904         BuildCheckHeapObject(receiver);
7905       }
7906     }
7907     ++count;
7908     HBasicBlock* if_true = graph()->CreateBasicBlock();
7909     HBasicBlock* if_false = graph()->CreateBasicBlock();
7910     HUnaryControlInstruction* compare;
7911
7912     Handle<Map> map = info.map();
7913     if (info.IsNumberType()) {
7914       Handle<Map> heap_number_map = isolate()->factory()->heap_number_map();
7915       compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false);
7916     } else if (info.IsStringType()) {
7917       compare = New<HIsStringAndBranch>(receiver, if_true, if_false);
7918     } else {
7919       compare = New<HCompareMap>(receiver, map, if_true, if_false);
7920     }
7921     FinishCurrentBlock(compare);
7922
7923     if (info.IsNumberType()) {
7924       GotoNoSimulate(if_true, number_block);
7925       if_true = number_block;
7926     }
7927
7928     set_current_block(if_true);
7929
7930     AddCheckPrototypeMaps(info.holder(), map);
7931
7932     HValue* function = Add<HConstant>(expr->target());
7933     environment()->SetExpressionStackAt(0, function);
7934     Push(receiver);
7935     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7936     bool needs_wrapping = info.NeedsWrappingFor(target);
7937     bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping;
7938     if (FLAG_trace_inlining && try_inline) {
7939       Handle<JSFunction> caller = current_info()->closure();
7940       base::SmartArrayPointer<char> caller_name =
7941           caller->shared()->DebugName()->ToCString();
7942       PrintF("Trying to inline the polymorphic call to %s from %s\n",
7943              name->ToCString().get(),
7944              caller_name.get());
7945     }
7946     if (try_inline && TryInlineCall(expr)) {
7947       // Trying to inline will signal that we should bailout from the
7948       // entire compilation by setting stack overflow on the visitor.
7949       if (HasStackOverflow()) return;
7950     } else {
7951       // Since HWrapReceiver currently cannot actually wrap numbers and strings,
7952       // use the regular CallFunctionStub for method calls to wrap the receiver.
7953       // TODO(verwaest): Support creation of value wrappers directly in
7954       // HWrapReceiver.
7955       HInstruction* call = needs_wrapping
7956           ? NewUncasted<HCallFunction>(
7957               function, argument_count, WRAP_AND_CALL)
7958           : BuildCallConstantFunction(target, argument_count);
7959       PushArgumentsFromEnvironment(argument_count);
7960       AddInstruction(call);
7961       Drop(1);  // Drop the function.
7962       if (!ast_context()->IsEffect()) Push(call);
7963     }
7964
7965     if (current_block() != NULL) Goto(join);
7966     set_current_block(if_false);
7967   }
7968
7969   // Finish up.  Unconditionally deoptimize if we've handled all the maps we
7970   // know about and do not want to handle ones we've never seen.  Otherwise
7971   // use a generic IC.
7972   if (ordered_functions == maps->length() && FLAG_deoptimize_uncommon_cases) {
7973     FinishExitWithHardDeoptimization(Deoptimizer::kUnknownMapInPolymorphicCall);
7974   } else {
7975     Property* prop = expr->expression()->AsProperty();
7976     HInstruction* function = BuildNamedGeneric(
7977         LOAD, prop, receiver, name, NULL, prop->IsUninitialized());
7978     AddInstruction(function);
7979     Push(function);
7980     AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE);
7981
7982     environment()->SetExpressionStackAt(1, function);
7983     environment()->SetExpressionStackAt(0, receiver);
7984     CHECK_ALIVE(VisitExpressions(expr->arguments()));
7985
7986     CallFunctionFlags flags = receiver->type().IsJSObject()
7987         ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
7988     HInstruction* call = New<HCallFunction>(
7989         function, argument_count, flags);
7990
7991     PushArgumentsFromEnvironment(argument_count);
7992
7993     Drop(1);  // Function.
7994
7995     if (join != NULL) {
7996       AddInstruction(call);
7997       if (!ast_context()->IsEffect()) Push(call);
7998       Goto(join);
7999     } else {
8000       return ast_context()->ReturnInstruction(call, expr->id());
8001     }
8002   }
8003
8004   // We assume that control flow is always live after an expression.  So
8005   // even without predecessors to the join block, we set it as the exit
8006   // block and continue by adding instructions there.
8007   DCHECK(join != NULL);
8008   if (join->HasPredecessor()) {
8009     set_current_block(join);
8010     join->SetJoinId(expr->id());
8011     if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop());
8012   } else {
8013     set_current_block(NULL);
8014   }
8015 }
8016
8017
8018 void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target,
8019                                          Handle<JSFunction> caller,
8020                                          const char* reason) {
8021   if (FLAG_trace_inlining) {
8022     base::SmartArrayPointer<char> target_name =
8023         target->shared()->DebugName()->ToCString();
8024     base::SmartArrayPointer<char> caller_name =
8025         caller->shared()->DebugName()->ToCString();
8026     if (reason == NULL) {
8027       PrintF("Inlined %s called from %s.\n", target_name.get(),
8028              caller_name.get());
8029     } else {
8030       PrintF("Did not inline %s called from %s (%s).\n",
8031              target_name.get(), caller_name.get(), reason);
8032     }
8033   }
8034 }
8035
8036
8037 static const int kNotInlinable = 1000000000;
8038
8039
8040 int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) {
8041   if (!FLAG_use_inlining) return kNotInlinable;
8042
8043   // Precondition: call is monomorphic and we have found a target with the
8044   // appropriate arity.
8045   Handle<JSFunction> caller = current_info()->closure();
8046   Handle<SharedFunctionInfo> target_shared(target->shared());
8047
8048   // Always inline functions that force inlining.
8049   if (target_shared->force_inline()) {
8050     return 0;
8051   }
8052   if (target->IsBuiltin()) {
8053     return kNotInlinable;
8054   }
8055
8056   if (target_shared->IsApiFunction()) {
8057     TraceInline(target, caller, "target is api function");
8058     return kNotInlinable;
8059   }
8060
8061   // Do a quick check on source code length to avoid parsing large
8062   // inlining candidates.
8063   if (target_shared->SourceSize() >
8064       Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) {
8065     TraceInline(target, caller, "target text too big");
8066     return kNotInlinable;
8067   }
8068
8069   // Target must be inlineable.
8070   if (!target_shared->IsInlineable()) {
8071     TraceInline(target, caller, "target not inlineable");
8072     return kNotInlinable;
8073   }
8074   if (target_shared->disable_optimization_reason() != kNoReason) {
8075     TraceInline(target, caller, "target contains unsupported syntax [early]");
8076     return kNotInlinable;
8077   }
8078
8079   int nodes_added = target_shared->ast_node_count();
8080   return nodes_added;
8081 }
8082
8083
8084 bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target,
8085                                        int arguments_count,
8086                                        HValue* implicit_return_value,
8087                                        BailoutId ast_id, BailoutId return_id,
8088                                        InliningKind inlining_kind) {
8089   if (target->context()->native_context() !=
8090       top_info()->closure()->context()->native_context()) {
8091     return false;
8092   }
8093   int nodes_added = InliningAstSize(target);
8094   if (nodes_added == kNotInlinable) return false;
8095
8096   Handle<JSFunction> caller = current_info()->closure();
8097
8098   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8099     TraceInline(target, caller, "target AST is too large [early]");
8100     return false;
8101   }
8102
8103   // Don't inline deeper than the maximum number of inlining levels.
8104   HEnvironment* env = environment();
8105   int current_level = 1;
8106   while (env->outer() != NULL) {
8107     if (current_level == FLAG_max_inlining_levels) {
8108       TraceInline(target, caller, "inline depth limit reached");
8109       return false;
8110     }
8111     if (env->outer()->frame_type() == JS_FUNCTION) {
8112       current_level++;
8113     }
8114     env = env->outer();
8115   }
8116
8117   // Don't inline recursive functions.
8118   for (FunctionState* state = function_state();
8119        state != NULL;
8120        state = state->outer()) {
8121     if (*state->compilation_info()->closure() == *target) {
8122       TraceInline(target, caller, "target is recursive");
8123       return false;
8124     }
8125   }
8126
8127   // We don't want to add more than a certain number of nodes from inlining.
8128   // Always inline small methods (<= 10 nodes).
8129   if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative,
8130                            kUnlimitedMaxInlinedNodesCumulative)) {
8131     TraceInline(target, caller, "cumulative AST node limit reached");
8132     return false;
8133   }
8134
8135   // Parse and allocate variables.
8136   // Use the same AstValueFactory for creating strings in the sub-compilation
8137   // step, but don't transfer ownership to target_info.
8138   ParseInfo parse_info(zone(), target);
8139   parse_info.set_ast_value_factory(
8140       top_info()->parse_info()->ast_value_factory());
8141   parse_info.set_ast_value_factory_owned(false);
8142
8143   CompilationInfo target_info(&parse_info);
8144   Handle<SharedFunctionInfo> target_shared(target->shared());
8145   if (target_shared->HasDebugInfo()) {
8146     TraceInline(target, caller, "target is being debugged");
8147     return false;
8148   }
8149   if (!Compiler::ParseAndAnalyze(target_info.parse_info())) {
8150     if (target_info.isolate()->has_pending_exception()) {
8151       // Parse or scope error, never optimize this function.
8152       SetStackOverflow();
8153       target_shared->DisableOptimization(kParseScopeError);
8154     }
8155     TraceInline(target, caller, "parse failure");
8156     return false;
8157   }
8158
8159   if (target_info.scope()->num_heap_slots() > 0) {
8160     TraceInline(target, caller, "target has context-allocated variables");
8161     return false;
8162   }
8163   FunctionLiteral* function = target_info.function();
8164
8165   // The following conditions must be checked again after re-parsing, because
8166   // earlier the information might not have been complete due to lazy parsing.
8167   nodes_added = function->ast_node_count();
8168   if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) {
8169     TraceInline(target, caller, "target AST is too large [late]");
8170     return false;
8171   }
8172   if (function->dont_optimize()) {
8173     TraceInline(target, caller, "target contains unsupported syntax [late]");
8174     return false;
8175   }
8176
8177   // If the function uses the arguments object check that inlining of functions
8178   // with arguments object is enabled and the arguments-variable is
8179   // stack allocated.
8180   if (function->scope()->arguments() != NULL) {
8181     if (!FLAG_inline_arguments) {
8182       TraceInline(target, caller, "target uses arguments object");
8183       return false;
8184     }
8185   }
8186
8187   // All declarations must be inlineable.
8188   ZoneList<Declaration*>* decls = target_info.scope()->declarations();
8189   int decl_count = decls->length();
8190   for (int i = 0; i < decl_count; ++i) {
8191     if (!decls->at(i)->IsInlineable()) {
8192       TraceInline(target, caller, "target has non-trivial declaration");
8193       return false;
8194     }
8195   }
8196
8197   // Generate the deoptimization data for the unoptimized version of
8198   // the target function if we don't already have it.
8199   if (!Compiler::EnsureDeoptimizationSupport(&target_info)) {
8200     TraceInline(target, caller, "could not generate deoptimization info");
8201     return false;
8202   }
8203
8204   // In strong mode it is an error to call a function with too few arguments.
8205   // In that case do not inline because then the arity check would be skipped.
8206   if (is_strong(function->language_mode()) &&
8207       arguments_count < function->parameter_count()) {
8208     TraceInline(target, caller,
8209                 "too few arguments passed to a strong function");
8210     return false;
8211   }
8212
8213   // ----------------------------------------------------------------
8214   // After this point, we've made a decision to inline this function (so
8215   // TryInline should always return true).
8216
8217   // Type-check the inlined function.
8218   DCHECK(target_shared->has_deoptimization_support());
8219   AstTyper::Run(&target_info);
8220
8221   int inlining_id = 0;
8222   if (top_info()->is_tracking_positions()) {
8223     inlining_id = top_info()->TraceInlinedFunction(
8224         target_shared, source_position(), function_state()->inlining_id());
8225   }
8226
8227   // Save the pending call context. Set up new one for the inlined function.
8228   // The function state is new-allocated because we need to delete it
8229   // in two different places.
8230   FunctionState* target_state =
8231       new FunctionState(this, &target_info, inlining_kind, inlining_id);
8232
8233   HConstant* undefined = graph()->GetConstantUndefined();
8234
8235   HEnvironment* inner_env =
8236       environment()->CopyForInlining(target,
8237                                      arguments_count,
8238                                      function,
8239                                      undefined,
8240                                      function_state()->inlining_kind());
8241
8242   HConstant* context = Add<HConstant>(Handle<Context>(target->context()));
8243   inner_env->BindContext(context);
8244
8245   // Create a dematerialized arguments object for the function, also copy the
8246   // current arguments values to use them for materialization.
8247   HEnvironment* arguments_env = inner_env->arguments_environment();
8248   int parameter_count = arguments_env->parameter_count();
8249   HArgumentsObject* arguments_object = Add<HArgumentsObject>(parameter_count);
8250   for (int i = 0; i < parameter_count; i++) {
8251     arguments_object->AddArgument(arguments_env->Lookup(i), zone());
8252   }
8253
8254   // If the function uses arguments object then bind bind one.
8255   if (function->scope()->arguments() != NULL) {
8256     DCHECK(function->scope()->arguments()->IsStackAllocated());
8257     inner_env->Bind(function->scope()->arguments(), arguments_object);
8258   }
8259
8260   // Capture the state before invoking the inlined function for deopt in the
8261   // inlined function. This simulate has no bailout-id since it's not directly
8262   // reachable for deopt, and is only used to capture the state. If the simulate
8263   // becomes reachable by merging, the ast id of the simulate merged into it is
8264   // adopted.
8265   Add<HSimulate>(BailoutId::None());
8266
8267   current_block()->UpdateEnvironment(inner_env);
8268   Scope* saved_scope = scope();
8269   set_scope(target_info.scope());
8270   HEnterInlined* enter_inlined =
8271       Add<HEnterInlined>(return_id, target, context, arguments_count, function,
8272                          function_state()->inlining_kind(),
8273                          function->scope()->arguments(), arguments_object);
8274   if (top_info()->is_tracking_positions()) {
8275     enter_inlined->set_inlining_id(inlining_id);
8276   }
8277   function_state()->set_entry(enter_inlined);
8278
8279   VisitDeclarations(target_info.scope()->declarations());
8280   VisitStatements(function->body());
8281   set_scope(saved_scope);
8282   if (HasStackOverflow()) {
8283     // Bail out if the inline function did, as we cannot residualize a call
8284     // instead, but do not disable optimization for the outer function.
8285     TraceInline(target, caller, "inline graph construction failed");
8286     target_shared->DisableOptimization(kInliningBailedOut);
8287     current_info()->RetryOptimization(kInliningBailedOut);
8288     delete target_state;
8289     return true;
8290   }
8291
8292   // Update inlined nodes count.
8293   inlined_count_ += nodes_added;
8294
8295   Handle<Code> unoptimized_code(target_shared->code());
8296   DCHECK(unoptimized_code->kind() == Code::FUNCTION);
8297   Handle<TypeFeedbackInfo> type_info(
8298       TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info()));
8299   graph()->update_type_change_checksum(type_info->own_type_change_checksum());
8300
8301   TraceInline(target, caller, NULL);
8302
8303   if (current_block() != NULL) {
8304     FunctionState* state = function_state();
8305     if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) {
8306       // Falling off the end of an inlined construct call. In a test context the
8307       // return value will always evaluate to true, in a value context the
8308       // return value is the newly allocated receiver.
8309       if (call_context()->IsTest()) {
8310         Goto(inlined_test_context()->if_true(), state);
8311       } else if (call_context()->IsEffect()) {
8312         Goto(function_return(), state);
8313       } else {
8314         DCHECK(call_context()->IsValue());
8315         AddLeaveInlined(implicit_return_value, state);
8316       }
8317     } else if (state->inlining_kind() == SETTER_CALL_RETURN) {
8318       // Falling off the end of an inlined setter call. The returned value is
8319       // never used, the value of an assignment is always the value of the RHS
8320       // of the assignment.
8321       if (call_context()->IsTest()) {
8322         inlined_test_context()->ReturnValue(implicit_return_value);
8323       } else if (call_context()->IsEffect()) {
8324         Goto(function_return(), state);
8325       } else {
8326         DCHECK(call_context()->IsValue());
8327         AddLeaveInlined(implicit_return_value, state);
8328       }
8329     } else {
8330       // Falling off the end of a normal inlined function. This basically means
8331       // returning undefined.
8332       if (call_context()->IsTest()) {
8333         Goto(inlined_test_context()->if_false(), state);
8334       } else if (call_context()->IsEffect()) {
8335         Goto(function_return(), state);
8336       } else {
8337         DCHECK(call_context()->IsValue());
8338         AddLeaveInlined(undefined, state);
8339       }
8340     }
8341   }
8342
8343   // Fix up the function exits.
8344   if (inlined_test_context() != NULL) {
8345     HBasicBlock* if_true = inlined_test_context()->if_true();
8346     HBasicBlock* if_false = inlined_test_context()->if_false();
8347
8348     HEnterInlined* entry = function_state()->entry();
8349
8350     // Pop the return test context from the expression context stack.
8351     DCHECK(ast_context() == inlined_test_context());
8352     ClearInlinedTestContext();
8353     delete target_state;
8354
8355     // Forward to the real test context.
8356     if (if_true->HasPredecessor()) {
8357       entry->RegisterReturnTarget(if_true, zone());
8358       if_true->SetJoinId(ast_id);
8359       HBasicBlock* true_target = TestContext::cast(ast_context())->if_true();
8360       Goto(if_true, true_target, function_state());
8361     }
8362     if (if_false->HasPredecessor()) {
8363       entry->RegisterReturnTarget(if_false, zone());
8364       if_false->SetJoinId(ast_id);
8365       HBasicBlock* false_target = TestContext::cast(ast_context())->if_false();
8366       Goto(if_false, false_target, function_state());
8367     }
8368     set_current_block(NULL);
8369     return true;
8370
8371   } else if (function_return()->HasPredecessor()) {
8372     function_state()->entry()->RegisterReturnTarget(function_return(), zone());
8373     function_return()->SetJoinId(ast_id);
8374     set_current_block(function_return());
8375   } else {
8376     set_current_block(NULL);
8377   }
8378   delete target_state;
8379   return true;
8380 }
8381
8382
8383 bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) {
8384   return TryInline(expr->target(), expr->arguments()->length(), NULL,
8385                    expr->id(), expr->ReturnId(), NORMAL_RETURN);
8386 }
8387
8388
8389 bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr,
8390                                                 HValue* implicit_return_value) {
8391   return TryInline(expr->target(), expr->arguments()->length(),
8392                    implicit_return_value, expr->id(), expr->ReturnId(),
8393                    CONSTRUCT_CALL_RETURN);
8394 }
8395
8396
8397 bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter,
8398                                              Handle<Map> receiver_map,
8399                                              BailoutId ast_id,
8400                                              BailoutId return_id) {
8401   if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true;
8402   return TryInline(getter, 0, NULL, ast_id, return_id, GETTER_CALL_RETURN);
8403 }
8404
8405
8406 bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter,
8407                                              Handle<Map> receiver_map,
8408                                              BailoutId id,
8409                                              BailoutId assignment_id,
8410                                              HValue* implicit_return_value) {
8411   if (TryInlineApiSetter(setter, receiver_map, id)) return true;
8412   return TryInline(setter, 1, implicit_return_value, id, assignment_id,
8413                    SETTER_CALL_RETURN);
8414 }
8415
8416
8417 bool HOptimizedGraphBuilder::TryInlineIndirectCall(Handle<JSFunction> function,
8418                                                    Call* expr,
8419                                                    int arguments_count) {
8420   return TryInline(function, arguments_count, NULL, expr->id(),
8421                    expr->ReturnId(), NORMAL_RETURN);
8422 }
8423
8424
8425 bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) {
8426   if (!expr->target()->shared()->HasBuiltinFunctionId()) return false;
8427   BuiltinFunctionId id = expr->target()->shared()->builtin_function_id();
8428   switch (id) {
8429     case kMathExp:
8430       if (!FLAG_fast_math) break;
8431       // Fall through if FLAG_fast_math.
8432     case kMathRound:
8433     case kMathFround:
8434     case kMathFloor:
8435     case kMathAbs:
8436     case kMathSqrt:
8437     case kMathLog:
8438     case kMathClz32:
8439       if (expr->arguments()->length() == 1) {
8440         HValue* argument = Pop();
8441         Drop(2);  // Receiver and function.
8442         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8443         ast_context()->ReturnInstruction(op, expr->id());
8444         return true;
8445       }
8446       break;
8447     case kMathImul:
8448       if (expr->arguments()->length() == 2) {
8449         HValue* right = Pop();
8450         HValue* left = Pop();
8451         Drop(2);  // Receiver and function.
8452         HInstruction* op =
8453             HMul::NewImul(isolate(), zone(), context(), left, right);
8454         ast_context()->ReturnInstruction(op, expr->id());
8455         return true;
8456       }
8457       break;
8458     default:
8459       // Not supported for inlining yet.
8460       break;
8461   }
8462   return false;
8463 }
8464
8465
8466 // static
8467 bool HOptimizedGraphBuilder::IsReadOnlyLengthDescriptor(
8468     Handle<Map> jsarray_map) {
8469   DCHECK(!jsarray_map->is_dictionary_map());
8470   Isolate* isolate = jsarray_map->GetIsolate();
8471   Handle<Name> length_string = isolate->factory()->length_string();
8472   DescriptorArray* descriptors = jsarray_map->instance_descriptors();
8473   int number = descriptors->SearchWithCache(*length_string, *jsarray_map);
8474   DCHECK_NE(DescriptorArray::kNotFound, number);
8475   return descriptors->GetDetails(number).IsReadOnly();
8476 }
8477
8478
8479 // static
8480 bool HOptimizedGraphBuilder::CanInlineArrayResizeOperation(
8481     Handle<Map> receiver_map) {
8482   return !receiver_map.is_null() &&
8483          receiver_map->instance_type() == JS_ARRAY_TYPE &&
8484          IsFastElementsKind(receiver_map->elements_kind()) &&
8485          !receiver_map->is_dictionary_map() &&
8486          !IsReadOnlyLengthDescriptor(receiver_map) &&
8487          !receiver_map->is_observed() && receiver_map->is_extensible();
8488 }
8489
8490
8491 bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall(
8492     Call* expr, Handle<JSFunction> function, Handle<Map> receiver_map,
8493     int args_count_no_receiver) {
8494   if (!function->shared()->HasBuiltinFunctionId()) return false;
8495   BuiltinFunctionId id = function->shared()->builtin_function_id();
8496   int argument_count = args_count_no_receiver + 1;  // Plus receiver.
8497
8498   if (receiver_map.is_null()) {
8499     HValue* receiver = environment()->ExpressionStackAt(args_count_no_receiver);
8500     if (receiver->IsConstant() &&
8501         HConstant::cast(receiver)->handle(isolate())->IsHeapObject()) {
8502       receiver_map =
8503           handle(Handle<HeapObject>::cast(
8504                      HConstant::cast(receiver)->handle(isolate()))->map());
8505     }
8506   }
8507   // Try to inline calls like Math.* as operations in the calling function.
8508   switch (id) {
8509     case kStringCharCodeAt:
8510     case kStringCharAt:
8511       if (argument_count == 2) {
8512         HValue* index = Pop();
8513         HValue* string = Pop();
8514         Drop(1);  // Function.
8515         HInstruction* char_code =
8516             BuildStringCharCodeAt(string, index);
8517         if (id == kStringCharCodeAt) {
8518           ast_context()->ReturnInstruction(char_code, expr->id());
8519           return true;
8520         }
8521         AddInstruction(char_code);
8522         HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
8523         ast_context()->ReturnInstruction(result, expr->id());
8524         return true;
8525       }
8526       break;
8527     case kStringFromCharCode:
8528       if (argument_count == 2) {
8529         HValue* argument = Pop();
8530         Drop(2);  // Receiver and function.
8531         HInstruction* result = NewUncasted<HStringCharFromCode>(argument);
8532         ast_context()->ReturnInstruction(result, expr->id());
8533         return true;
8534       }
8535       break;
8536     case kMathExp:
8537       if (!FLAG_fast_math) break;
8538       // Fall through if FLAG_fast_math.
8539     case kMathRound:
8540     case kMathFround:
8541     case kMathFloor:
8542     case kMathAbs:
8543     case kMathSqrt:
8544     case kMathLog:
8545     case kMathClz32:
8546       if (argument_count == 2) {
8547         HValue* argument = Pop();
8548         Drop(2);  // Receiver and function.
8549         HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id);
8550         ast_context()->ReturnInstruction(op, expr->id());
8551         return true;
8552       }
8553       break;
8554     case kMathPow:
8555       if (argument_count == 3) {
8556         HValue* right = Pop();
8557         HValue* left = Pop();
8558         Drop(2);  // Receiver and function.
8559         HInstruction* result = NULL;
8560         // Use sqrt() if exponent is 0.5 or -0.5.
8561         if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) {
8562           double exponent = HConstant::cast(right)->DoubleValue();
8563           if (exponent == 0.5) {
8564             result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf);
8565           } else if (exponent == -0.5) {
8566             HValue* one = graph()->GetConstant1();
8567             HInstruction* sqrt = AddUncasted<HUnaryMathOperation>(
8568                 left, kMathPowHalf);
8569             // MathPowHalf doesn't have side effects so there's no need for
8570             // an environment simulation here.
8571             DCHECK(!sqrt->HasObservableSideEffects());
8572             result = NewUncasted<HDiv>(one, sqrt);
8573           } else if (exponent == 2.0) {
8574             result = NewUncasted<HMul>(left, left);
8575           }
8576         }
8577
8578         if (result == NULL) {
8579           result = NewUncasted<HPower>(left, right);
8580         }
8581         ast_context()->ReturnInstruction(result, expr->id());
8582         return true;
8583       }
8584       break;
8585     case kMathMax:
8586     case kMathMin:
8587       if (argument_count == 3) {
8588         HValue* right = Pop();
8589         HValue* left = Pop();
8590         Drop(2);  // Receiver and function.
8591         HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin
8592                                                      : HMathMinMax::kMathMax;
8593         HInstruction* result = NewUncasted<HMathMinMax>(left, right, op);
8594         ast_context()->ReturnInstruction(result, expr->id());
8595         return true;
8596       }
8597       break;
8598     case kMathImul:
8599       if (argument_count == 3) {
8600         HValue* right = Pop();
8601         HValue* left = Pop();
8602         Drop(2);  // Receiver and function.
8603         HInstruction* result =
8604             HMul::NewImul(isolate(), zone(), context(), left, right);
8605         ast_context()->ReturnInstruction(result, expr->id());
8606         return true;
8607       }
8608       break;
8609     case kArrayPop: {
8610       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8611       ElementsKind elements_kind = receiver_map->elements_kind();
8612
8613       Drop(args_count_no_receiver);
8614       HValue* result;
8615       HValue* reduced_length;
8616       HValue* receiver = Pop();
8617
8618       HValue* checked_object = AddCheckMap(receiver, receiver_map);
8619       HValue* length =
8620           Add<HLoadNamedField>(checked_object, nullptr,
8621                                HObjectAccess::ForArrayLength(elements_kind));
8622
8623       Drop(1);  // Function.
8624
8625       { NoObservableSideEffectsScope scope(this);
8626         IfBuilder length_checker(this);
8627
8628         HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>(
8629             length, graph()->GetConstant0(), Token::EQ);
8630         length_checker.Then();
8631
8632         if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8633
8634         length_checker.Else();
8635         HValue* elements = AddLoadElements(checked_object);
8636         // Ensure that we aren't popping from a copy-on-write array.
8637         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8638           elements = BuildCopyElementsOnWrite(checked_object, elements,
8639                                               elements_kind, length);
8640         }
8641         reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1());
8642         result = AddElementAccess(elements, reduced_length, NULL,
8643                                   bounds_check, elements_kind, LOAD);
8644         HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind)
8645                            ? graph()->GetConstantHole()
8646                            : Add<HConstant>(HConstant::kHoleNaN);
8647         if (IsFastSmiOrObjectElementsKind(elements_kind)) {
8648           elements_kind = FAST_HOLEY_ELEMENTS;
8649         }
8650         AddElementAccess(
8651             elements, reduced_length, hole, bounds_check, elements_kind, STORE);
8652         Add<HStoreNamedField>(
8653             checked_object, HObjectAccess::ForArrayLength(elements_kind),
8654             reduced_length, STORE_TO_INITIALIZED_ENTRY);
8655
8656         if (!ast_context()->IsEffect()) Push(result);
8657
8658         length_checker.End();
8659       }
8660       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8661       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8662       if (!ast_context()->IsEffect()) Drop(1);
8663
8664       ast_context()->ReturnValue(result);
8665       return true;
8666     }
8667     case kArrayPush: {
8668       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8669       ElementsKind elements_kind = receiver_map->elements_kind();
8670
8671       // If there may be elements accessors in the prototype chain, the fast
8672       // inlined version can't be used.
8673       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8674       // If there currently can be no elements accessors on the prototype chain,
8675       // it doesn't mean that there won't be any later. Install a full prototype
8676       // chain check to trap element accessors being installed on the prototype
8677       // chain, which would cause elements to go to dictionary mode and result
8678       // in a map change.
8679       Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype()));
8680       BuildCheckPrototypeMaps(prototype, Handle<JSObject>());
8681
8682       // Protect against adding elements to the Array prototype, which needs to
8683       // route through appropriate bottlenecks.
8684       if (isolate()->IsFastArrayConstructorPrototypeChainIntact() &&
8685           !prototype->IsJSArray()) {
8686         return false;
8687       }
8688
8689       const int argc = args_count_no_receiver;
8690       if (argc != 1) return false;
8691
8692       HValue* value_to_push = Pop();
8693       HValue* array = Pop();
8694       Drop(1);  // Drop function.
8695
8696       HInstruction* new_size = NULL;
8697       HValue* length = NULL;
8698
8699       {
8700         NoObservableSideEffectsScope scope(this);
8701
8702         length = Add<HLoadNamedField>(
8703             array, nullptr, HObjectAccess::ForArrayLength(elements_kind));
8704
8705         new_size = AddUncasted<HAdd>(length, graph()->GetConstant1());
8706
8707         bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE;
8708         HValue* checked_array = Add<HCheckMaps>(array, receiver_map);
8709         BuildUncheckedMonomorphicElementAccess(
8710             checked_array, length, value_to_push, is_array, elements_kind,
8711             STORE, NEVER_RETURN_HOLE, STORE_AND_GROW_NO_TRANSITION);
8712
8713         if (!ast_context()->IsEffect()) Push(new_size);
8714         Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8715         if (!ast_context()->IsEffect()) Drop(1);
8716       }
8717
8718       ast_context()->ReturnValue(new_size);
8719       return true;
8720     }
8721     case kArrayShift: {
8722       if (!CanInlineArrayResizeOperation(receiver_map)) return false;
8723       ElementsKind kind = receiver_map->elements_kind();
8724
8725       // If there may be elements accessors in the prototype chain, the fast
8726       // inlined version can't be used.
8727       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8728
8729       // If there currently can be no elements accessors on the prototype chain,
8730       // it doesn't mean that there won't be any later. Install a full prototype
8731       // chain check to trap element accessors being installed on the prototype
8732       // chain, which would cause elements to go to dictionary mode and result
8733       // in a map change.
8734       BuildCheckPrototypeMaps(
8735           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8736           Handle<JSObject>::null());
8737
8738       // Threshold for fast inlined Array.shift().
8739       HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16));
8740
8741       Drop(args_count_no_receiver);
8742       HValue* receiver = Pop();
8743       HValue* function = Pop();
8744       HValue* result;
8745
8746       {
8747         NoObservableSideEffectsScope scope(this);
8748
8749         HValue* length = Add<HLoadNamedField>(
8750             receiver, nullptr, HObjectAccess::ForArrayLength(kind));
8751
8752         IfBuilder if_lengthiszero(this);
8753         HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>(
8754             length, graph()->GetConstant0(), Token::EQ);
8755         if_lengthiszero.Then();
8756         {
8757           if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined());
8758         }
8759         if_lengthiszero.Else();
8760         {
8761           HValue* elements = AddLoadElements(receiver);
8762
8763           // Check if we can use the fast inlined Array.shift().
8764           IfBuilder if_inline(this);
8765           if_inline.If<HCompareNumericAndBranch>(
8766               length, inline_threshold, Token::LTE);
8767           if (IsFastSmiOrObjectElementsKind(kind)) {
8768             // We cannot handle copy-on-write backing stores here.
8769             if_inline.AndIf<HCompareMap>(
8770                 elements, isolate()->factory()->fixed_array_map());
8771           }
8772           if_inline.Then();
8773           {
8774             // Remember the result.
8775             if (!ast_context()->IsEffect()) {
8776               Push(AddElementAccess(elements, graph()->GetConstant0(), NULL,
8777                                     lengthiszero, kind, LOAD));
8778             }
8779
8780             // Compute the new length.
8781             HValue* new_length = AddUncasted<HSub>(
8782                 length, graph()->GetConstant1());
8783             new_length->ClearFlag(HValue::kCanOverflow);
8784
8785             // Copy the remaining elements.
8786             LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement);
8787             {
8788               HValue* new_key = loop.BeginBody(
8789                   graph()->GetConstant0(), new_length, Token::LT);
8790               HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1());
8791               key->ClearFlag(HValue::kCanOverflow);
8792               ElementsKind copy_kind =
8793                   kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
8794               HValue* element = AddUncasted<HLoadKeyed>(
8795                   elements, key, lengthiszero, copy_kind, ALLOW_RETURN_HOLE);
8796               HStoreKeyed* store =
8797                   Add<HStoreKeyed>(elements, new_key, element, copy_kind);
8798               store->SetFlag(HValue::kAllowUndefinedAsNaN);
8799             }
8800             loop.EndBody();
8801
8802             // Put a hole at the end.
8803             HValue* hole = IsFastSmiOrObjectElementsKind(kind)
8804                                ? graph()->GetConstantHole()
8805                                : Add<HConstant>(HConstant::kHoleNaN);
8806             if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS;
8807             Add<HStoreKeyed>(
8808                 elements, new_length, hole, kind, INITIALIZING_STORE);
8809
8810             // Remember new length.
8811             Add<HStoreNamedField>(
8812                 receiver, HObjectAccess::ForArrayLength(kind),
8813                 new_length, STORE_TO_INITIALIZED_ENTRY);
8814           }
8815           if_inline.Else();
8816           {
8817             Add<HPushArguments>(receiver);
8818             result = Add<HCallJSFunction>(function, 1, true);
8819             if (!ast_context()->IsEffect()) Push(result);
8820           }
8821           if_inline.End();
8822         }
8823         if_lengthiszero.End();
8824       }
8825       result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top();
8826       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8827       if (!ast_context()->IsEffect()) Drop(1);
8828       ast_context()->ReturnValue(result);
8829       return true;
8830     }
8831     case kArrayIndexOf:
8832     case kArrayLastIndexOf: {
8833       if (receiver_map.is_null()) return false;
8834       if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false;
8835       ElementsKind kind = receiver_map->elements_kind();
8836       if (!IsFastElementsKind(kind)) return false;
8837       if (receiver_map->is_observed()) return false;
8838       if (argument_count != 2) return false;
8839       if (!receiver_map->is_extensible()) return false;
8840
8841       // If there may be elements accessors in the prototype chain, the fast
8842       // inlined version can't be used.
8843       if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false;
8844
8845       // If there currently can be no elements accessors on the prototype chain,
8846       // it doesn't mean that there won't be any later. Install a full prototype
8847       // chain check to trap element accessors being installed on the prototype
8848       // chain, which would cause elements to go to dictionary mode and result
8849       // in a map change.
8850       BuildCheckPrototypeMaps(
8851           handle(JSObject::cast(receiver_map->prototype()), isolate()),
8852           Handle<JSObject>::null());
8853
8854       HValue* search_element = Pop();
8855       HValue* receiver = Pop();
8856       Drop(1);  // Drop function.
8857
8858       ArrayIndexOfMode mode = (id == kArrayIndexOf)
8859           ? kFirstIndexOf : kLastIndexOf;
8860       HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode);
8861
8862       if (!ast_context()->IsEffect()) Push(index);
8863       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
8864       if (!ast_context()->IsEffect()) Drop(1);
8865       ast_context()->ReturnValue(index);
8866       return true;
8867     }
8868     default:
8869       // Not yet supported for inlining.
8870       break;
8871   }
8872   return false;
8873 }
8874
8875
8876 bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr,
8877                                                       HValue* receiver) {
8878   Handle<JSFunction> function = expr->target();
8879   int argc = expr->arguments()->length();
8880   SmallMapList receiver_maps;
8881   return TryInlineApiCall(function,
8882                           receiver,
8883                           &receiver_maps,
8884                           argc,
8885                           expr->id(),
8886                           kCallApiFunction);
8887 }
8888
8889
8890 bool HOptimizedGraphBuilder::TryInlineApiMethodCall(
8891     Call* expr,
8892     HValue* receiver,
8893     SmallMapList* receiver_maps) {
8894   Handle<JSFunction> function = expr->target();
8895   int argc = expr->arguments()->length();
8896   return TryInlineApiCall(function,
8897                           receiver,
8898                           receiver_maps,
8899                           argc,
8900                           expr->id(),
8901                           kCallApiMethod);
8902 }
8903
8904
8905 bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function,
8906                                                 Handle<Map> receiver_map,
8907                                                 BailoutId ast_id) {
8908   SmallMapList receiver_maps(1, zone());
8909   receiver_maps.Add(receiver_map, zone());
8910   return TryInlineApiCall(function,
8911                           NULL,  // Receiver is on expression stack.
8912                           &receiver_maps,
8913                           0,
8914                           ast_id,
8915                           kCallApiGetter);
8916 }
8917
8918
8919 bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function,
8920                                                 Handle<Map> receiver_map,
8921                                                 BailoutId ast_id) {
8922   SmallMapList receiver_maps(1, zone());
8923   receiver_maps.Add(receiver_map, zone());
8924   return TryInlineApiCall(function,
8925                           NULL,  // Receiver is on expression stack.
8926                           &receiver_maps,
8927                           1,
8928                           ast_id,
8929                           kCallApiSetter);
8930 }
8931
8932
8933 bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function,
8934                                                HValue* receiver,
8935                                                SmallMapList* receiver_maps,
8936                                                int argc,
8937                                                BailoutId ast_id,
8938                                                ApiCallType call_type) {
8939   if (function->context()->native_context() !=
8940       top_info()->closure()->context()->native_context()) {
8941     return false;
8942   }
8943   CallOptimization optimization(function);
8944   if (!optimization.is_simple_api_call()) return false;
8945   Handle<Map> holder_map;
8946   for (int i = 0; i < receiver_maps->length(); ++i) {
8947     auto map = receiver_maps->at(i);
8948     // Don't inline calls to receivers requiring accesschecks.
8949     if (map->is_access_check_needed()) return false;
8950   }
8951   if (call_type == kCallApiFunction) {
8952     // Cannot embed a direct reference to the global proxy map
8953     // as it maybe dropped on deserialization.
8954     CHECK(!isolate()->serializer_enabled());
8955     DCHECK_EQ(0, receiver_maps->length());
8956     receiver_maps->Add(handle(function->global_proxy()->map()), zone());
8957   }
8958   CallOptimization::HolderLookup holder_lookup =
8959       CallOptimization::kHolderNotFound;
8960   Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
8961       receiver_maps->first(), &holder_lookup);
8962   if (holder_lookup == CallOptimization::kHolderNotFound) return false;
8963
8964   if (FLAG_trace_inlining) {
8965     PrintF("Inlining api function ");
8966     function->ShortPrint();
8967     PrintF("\n");
8968   }
8969
8970   bool is_function = false;
8971   bool is_store = false;
8972   switch (call_type) {
8973     case kCallApiFunction:
8974     case kCallApiMethod:
8975       // Need to check that none of the receiver maps could have changed.
8976       Add<HCheckMaps>(receiver, receiver_maps);
8977       // Need to ensure the chain between receiver and api_holder is intact.
8978       if (holder_lookup == CallOptimization::kHolderFound) {
8979         AddCheckPrototypeMaps(api_holder, receiver_maps->first());
8980       } else {
8981         DCHECK_EQ(holder_lookup, CallOptimization::kHolderIsReceiver);
8982       }
8983       // Includes receiver.
8984       PushArgumentsFromEnvironment(argc + 1);
8985       is_function = true;
8986       break;
8987     case kCallApiGetter:
8988       // Receiver and prototype chain cannot have changed.
8989       DCHECK_EQ(0, argc);
8990       DCHECK_NULL(receiver);
8991       // Receiver is on expression stack.
8992       receiver = Pop();
8993       Add<HPushArguments>(receiver);
8994       break;
8995     case kCallApiSetter:
8996       {
8997         is_store = true;
8998         // Receiver and prototype chain cannot have changed.
8999         DCHECK_EQ(1, argc);
9000         DCHECK_NULL(receiver);
9001         // Receiver and value are on expression stack.
9002         HValue* value = Pop();
9003         receiver = Pop();
9004         Add<HPushArguments>(receiver, value);
9005         break;
9006      }
9007   }
9008
9009   HValue* holder = NULL;
9010   switch (holder_lookup) {
9011     case CallOptimization::kHolderFound:
9012       holder = Add<HConstant>(api_holder);
9013       break;
9014     case CallOptimization::kHolderIsReceiver:
9015       holder = receiver;
9016       break;
9017     case CallOptimization::kHolderNotFound:
9018       UNREACHABLE();
9019       break;
9020   }
9021   Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
9022   Handle<Object> call_data_obj(api_call_info->data(), isolate());
9023   bool call_data_undefined = call_data_obj->IsUndefined();
9024   HValue* call_data = Add<HConstant>(call_data_obj);
9025   ApiFunction fun(v8::ToCData<Address>(api_call_info->callback()));
9026   ExternalReference ref = ExternalReference(&fun,
9027                                             ExternalReference::DIRECT_API_CALL,
9028                                             isolate());
9029   HValue* api_function_address = Add<HConstant>(ExternalReference(ref));
9030
9031   HValue* op_vals[] = {context(), Add<HConstant>(function), call_data, holder,
9032                        api_function_address, nullptr};
9033
9034   HInstruction* call = nullptr;
9035   if (!is_function) {
9036     CallApiAccessorStub stub(isolate(), is_store, call_data_undefined);
9037     Handle<Code> code = stub.GetCode();
9038     HConstant* code_value = Add<HConstant>(code);
9039     ApiAccessorDescriptor descriptor(isolate());
9040     call = New<HCallWithDescriptor>(
9041         code_value, argc + 1, descriptor,
9042         Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9043   } else if (argc <= CallApiFunctionWithFixedArgsStub::kMaxFixedArgs) {
9044     CallApiFunctionWithFixedArgsStub stub(isolate(), argc, call_data_undefined);
9045     Handle<Code> code = stub.GetCode();
9046     HConstant* code_value = Add<HConstant>(code);
9047     ApiFunctionWithFixedArgsDescriptor descriptor(isolate());
9048     call = New<HCallWithDescriptor>(
9049         code_value, argc + 1, descriptor,
9050         Vector<HValue*>(op_vals, arraysize(op_vals) - 1));
9051     Drop(1);  // Drop function.
9052   } else {
9053     op_vals[arraysize(op_vals) - 1] = Add<HConstant>(argc);
9054     CallApiFunctionStub stub(isolate(), call_data_undefined);
9055     Handle<Code> code = stub.GetCode();
9056     HConstant* code_value = Add<HConstant>(code);
9057     ApiFunctionDescriptor descriptor(isolate());
9058     call =
9059         New<HCallWithDescriptor>(code_value, argc + 1, descriptor,
9060                                  Vector<HValue*>(op_vals, arraysize(op_vals)));
9061     Drop(1);  // Drop function.
9062   }
9063
9064   ast_context()->ReturnInstruction(call, ast_id);
9065   return true;
9066 }
9067
9068
9069 void HOptimizedGraphBuilder::HandleIndirectCall(Call* expr, HValue* function,
9070                                                 int arguments_count) {
9071   Handle<JSFunction> known_function;
9072   int args_count_no_receiver = arguments_count - 1;
9073   if (function->IsConstant() &&
9074       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9075     known_function =
9076         Handle<JSFunction>::cast(HConstant::cast(function)->handle(isolate()));
9077     if (TryInlineBuiltinMethodCall(expr, known_function, Handle<Map>(),
9078                                    args_count_no_receiver)) {
9079       if (FLAG_trace_inlining) {
9080         PrintF("Inlining builtin ");
9081         known_function->ShortPrint();
9082         PrintF("\n");
9083       }
9084       return;
9085     }
9086
9087     if (TryInlineIndirectCall(known_function, expr, args_count_no_receiver)) {
9088       return;
9089     }
9090   }
9091
9092   PushArgumentsFromEnvironment(arguments_count);
9093   HInvokeFunction* call =
9094       New<HInvokeFunction>(function, known_function, arguments_count);
9095   Drop(1);  // Function
9096   ast_context()->ReturnInstruction(call, expr->id());
9097 }
9098
9099
9100 bool HOptimizedGraphBuilder::TryIndirectCall(Call* expr) {
9101   DCHECK(expr->expression()->IsProperty());
9102
9103   if (!expr->IsMonomorphic()) {
9104     return false;
9105   }
9106   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9107   if (function_map->instance_type() != JS_FUNCTION_TYPE ||
9108       !expr->target()->shared()->HasBuiltinFunctionId()) {
9109     return false;
9110   }
9111
9112   switch (expr->target()->shared()->builtin_function_id()) {
9113     case kFunctionCall: {
9114       if (expr->arguments()->length() == 0) return false;
9115       BuildFunctionCall(expr);
9116       return true;
9117     }
9118     case kFunctionApply: {
9119       // For .apply, only the pattern f.apply(receiver, arguments)
9120       // is supported.
9121       if (current_info()->scope()->arguments() == NULL) return false;
9122
9123       if (!CanBeFunctionApplyArguments(expr)) return false;
9124
9125       BuildFunctionApply(expr);
9126       return true;
9127     }
9128     default: { return false; }
9129   }
9130   UNREACHABLE();
9131 }
9132
9133
9134 void HOptimizedGraphBuilder::BuildFunctionApply(Call* expr) {
9135   ZoneList<Expression*>* args = expr->arguments();
9136   CHECK_ALIVE(VisitForValue(args->at(0)));
9137   HValue* receiver = Pop();  // receiver
9138   HValue* function = Pop();  // f
9139   Drop(1);  // apply
9140
9141   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9142   HValue* checked_function = AddCheckMap(function, function_map);
9143
9144   if (function_state()->outer() == NULL) {
9145     HInstruction* elements = Add<HArgumentsElements>(false);
9146     HInstruction* length = Add<HArgumentsLength>(elements);
9147     HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function);
9148     HInstruction* result = New<HApplyArguments>(function,
9149                                                 wrapped_receiver,
9150                                                 length,
9151                                                 elements);
9152     ast_context()->ReturnInstruction(result, expr->id());
9153   } else {
9154     // We are inside inlined function and we know exactly what is inside
9155     // arguments object. But we need to be able to materialize at deopt.
9156     DCHECK_EQ(environment()->arguments_environment()->parameter_count(),
9157               function_state()->entry()->arguments_object()->arguments_count());
9158     HArgumentsObject* args = function_state()->entry()->arguments_object();
9159     const ZoneList<HValue*>* arguments_values = args->arguments_values();
9160     int arguments_count = arguments_values->length();
9161     Push(function);
9162     Push(BuildWrapReceiver(receiver, checked_function));
9163     for (int i = 1; i < arguments_count; i++) {
9164       Push(arguments_values->at(i));
9165     }
9166     HandleIndirectCall(expr, function, arguments_count);
9167   }
9168 }
9169
9170
9171 // f.call(...)
9172 void HOptimizedGraphBuilder::BuildFunctionCall(Call* expr) {
9173   HValue* function = Top();  // f
9174   Handle<Map> function_map = expr->GetReceiverTypes()->first();
9175   HValue* checked_function = AddCheckMap(function, function_map);
9176
9177   // f and call are on the stack in the unoptimized code
9178   // during evaluation of the arguments.
9179   CHECK_ALIVE(VisitExpressions(expr->arguments()));
9180
9181   int args_length = expr->arguments()->length();
9182   int receiver_index = args_length - 1;
9183   // Patch the receiver.
9184   HValue* receiver = BuildWrapReceiver(
9185       environment()->ExpressionStackAt(receiver_index), checked_function);
9186   environment()->SetExpressionStackAt(receiver_index, receiver);
9187
9188   // Call must not be on the stack from now on.
9189   int call_index = args_length + 1;
9190   environment()->RemoveExpressionStackAt(call_index);
9191
9192   HandleIndirectCall(expr, function, args_length);
9193 }
9194
9195
9196 HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function,
9197                                                     Handle<JSFunction> target) {
9198   SharedFunctionInfo* shared = target->shared();
9199   if (is_sloppy(shared->language_mode()) && !shared->native()) {
9200     // Cannot embed a direct reference to the global proxy
9201     // as is it dropped on deserialization.
9202     CHECK(!isolate()->serializer_enabled());
9203     Handle<JSObject> global_proxy(target->context()->global_proxy());
9204     return Add<HConstant>(global_proxy);
9205   }
9206   return graph()->GetConstantUndefined();
9207 }
9208
9209
9210 void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression,
9211                                             int arguments_count,
9212                                             HValue* function,
9213                                             Handle<AllocationSite> site) {
9214   Add<HCheckValue>(function, array_function());
9215
9216   if (IsCallArrayInlineable(arguments_count, site)) {
9217     BuildInlinedCallArray(expression, arguments_count, site);
9218     return;
9219   }
9220
9221   HInstruction* call = PreProcessCall(New<HCallNewArray>(
9222       function, arguments_count + 1, site->GetElementsKind(), site));
9223   if (expression->IsCall()) {
9224     Drop(1);
9225   }
9226   ast_context()->ReturnInstruction(call, expression->id());
9227 }
9228
9229
9230 HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver,
9231                                                   HValue* search_element,
9232                                                   ElementsKind kind,
9233                                                   ArrayIndexOfMode mode) {
9234   DCHECK(IsFastElementsKind(kind));
9235
9236   NoObservableSideEffectsScope no_effects(this);
9237
9238   HValue* elements = AddLoadElements(receiver);
9239   HValue* length = AddLoadArrayLength(receiver, kind);
9240
9241   HValue* initial;
9242   HValue* terminating;
9243   Token::Value token;
9244   LoopBuilder::Direction direction;
9245   if (mode == kFirstIndexOf) {
9246     initial = graph()->GetConstant0();
9247     terminating = length;
9248     token = Token::LT;
9249     direction = LoopBuilder::kPostIncrement;
9250   } else {
9251     DCHECK_EQ(kLastIndexOf, mode);
9252     initial = length;
9253     terminating = graph()->GetConstant0();
9254     token = Token::GT;
9255     direction = LoopBuilder::kPreDecrement;
9256   }
9257
9258   Push(graph()->GetConstantMinus1());
9259   if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) {
9260     // Make sure that we can actually compare numbers correctly below, see
9261     // https://code.google.com/p/chromium/issues/detail?id=407946 for details.
9262     search_element = AddUncasted<HForceRepresentation>(
9263         search_element, IsFastSmiElementsKind(kind) ? Representation::Smi()
9264                                                     : Representation::Double());
9265
9266     LoopBuilder loop(this, context(), direction);
9267     {
9268       HValue* index = loop.BeginBody(initial, terminating, token);
9269       HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr, kind,
9270                                                 ALLOW_RETURN_HOLE);
9271       IfBuilder if_issame(this);
9272       if_issame.If<HCompareNumericAndBranch>(element, search_element,
9273                                              Token::EQ_STRICT);
9274       if_issame.Then();
9275       {
9276         Drop(1);
9277         Push(index);
9278         loop.Break();
9279       }
9280       if_issame.End();
9281     }
9282     loop.EndBody();
9283   } else {
9284     IfBuilder if_isstring(this);
9285     if_isstring.If<HIsStringAndBranch>(search_element);
9286     if_isstring.Then();
9287     {
9288       LoopBuilder loop(this, context(), direction);
9289       {
9290         HValue* index = loop.BeginBody(initial, terminating, token);
9291         HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9292                                                   kind, ALLOW_RETURN_HOLE);
9293         IfBuilder if_issame(this);
9294         if_issame.If<HIsStringAndBranch>(element);
9295         if_issame.AndIf<HStringCompareAndBranch>(
9296             element, search_element, Token::EQ_STRICT);
9297         if_issame.Then();
9298         {
9299           Drop(1);
9300           Push(index);
9301           loop.Break();
9302         }
9303         if_issame.End();
9304       }
9305       loop.EndBody();
9306     }
9307     if_isstring.Else();
9308     {
9309       IfBuilder if_isnumber(this);
9310       if_isnumber.If<HIsSmiAndBranch>(search_element);
9311       if_isnumber.OrIf<HCompareMap>(
9312           search_element, isolate()->factory()->heap_number_map());
9313       if_isnumber.Then();
9314       {
9315         HValue* search_number =
9316             AddUncasted<HForceRepresentation>(search_element,
9317                                               Representation::Double());
9318         LoopBuilder loop(this, context(), direction);
9319         {
9320           HValue* index = loop.BeginBody(initial, terminating, token);
9321           HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9322                                                     kind, ALLOW_RETURN_HOLE);
9323
9324           IfBuilder if_element_isnumber(this);
9325           if_element_isnumber.If<HIsSmiAndBranch>(element);
9326           if_element_isnumber.OrIf<HCompareMap>(
9327               element, isolate()->factory()->heap_number_map());
9328           if_element_isnumber.Then();
9329           {
9330             HValue* number =
9331                 AddUncasted<HForceRepresentation>(element,
9332                                                   Representation::Double());
9333             IfBuilder if_issame(this);
9334             if_issame.If<HCompareNumericAndBranch>(
9335                 number, search_number, Token::EQ_STRICT);
9336             if_issame.Then();
9337             {
9338               Drop(1);
9339               Push(index);
9340               loop.Break();
9341             }
9342             if_issame.End();
9343           }
9344           if_element_isnumber.End();
9345         }
9346         loop.EndBody();
9347       }
9348       if_isnumber.Else();
9349       {
9350         LoopBuilder loop(this, context(), direction);
9351         {
9352           HValue* index = loop.BeginBody(initial, terminating, token);
9353           HValue* element = AddUncasted<HLoadKeyed>(elements, index, nullptr,
9354                                                     kind, ALLOW_RETURN_HOLE);
9355           IfBuilder if_issame(this);
9356           if_issame.If<HCompareObjectEqAndBranch>(
9357               element, search_element);
9358           if_issame.Then();
9359           {
9360             Drop(1);
9361             Push(index);
9362             loop.Break();
9363           }
9364           if_issame.End();
9365         }
9366         loop.EndBody();
9367       }
9368       if_isnumber.End();
9369     }
9370     if_isstring.End();
9371   }
9372
9373   return Pop();
9374 }
9375
9376
9377 bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) {
9378   if (!array_function().is_identical_to(expr->target())) {
9379     return false;
9380   }
9381
9382   Handle<AllocationSite> site = expr->allocation_site();
9383   if (site.is_null()) return false;
9384
9385   BuildArrayCall(expr,
9386                  expr->arguments()->length(),
9387                  function,
9388                  site);
9389   return true;
9390 }
9391
9392
9393 bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr,
9394                                                    HValue* function) {
9395   if (!array_function().is_identical_to(expr->target())) {
9396     return false;
9397   }
9398
9399   Handle<AllocationSite> site = expr->allocation_site();
9400   if (site.is_null()) return false;
9401
9402   BuildArrayCall(expr, expr->arguments()->length(), function, site);
9403   return true;
9404 }
9405
9406
9407 bool HOptimizedGraphBuilder::CanBeFunctionApplyArguments(Call* expr) {
9408   ZoneList<Expression*>* args = expr->arguments();
9409   if (args->length() != 2) return false;
9410   VariableProxy* arg_two = args->at(1)->AsVariableProxy();
9411   if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false;
9412   HValue* arg_two_value = LookupAndMakeLive(arg_two->var());
9413   if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false;
9414   return true;
9415 }
9416
9417
9418 void HOptimizedGraphBuilder::VisitCall(Call* expr) {
9419   DCHECK(!HasStackOverflow());
9420   DCHECK(current_block() != NULL);
9421   DCHECK(current_block()->HasPredecessor());
9422   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9423   Expression* callee = expr->expression();
9424   int argument_count = expr->arguments()->length() + 1;  // Plus receiver.
9425   HInstruction* call = NULL;
9426
9427   Property* prop = callee->AsProperty();
9428   if (prop != NULL) {
9429     CHECK_ALIVE(VisitForValue(prop->obj()));
9430     HValue* receiver = Top();
9431
9432     SmallMapList* maps;
9433     ComputeReceiverTypes(expr, receiver, &maps, zone());
9434
9435     if (prop->key()->IsPropertyName() && maps->length() > 0) {
9436       Handle<String> name = prop->key()->AsLiteral()->AsPropertyName();
9437       PropertyAccessInfo info(this, LOAD, maps->first(), name);
9438       if (!info.CanAccessAsMonomorphic(maps)) {
9439         HandlePolymorphicCallNamed(expr, receiver, maps, name);
9440         return;
9441       }
9442     }
9443     HValue* key = NULL;
9444     if (!prop->key()->IsPropertyName()) {
9445       CHECK_ALIVE(VisitForValue(prop->key()));
9446       key = Pop();
9447     }
9448
9449     CHECK_ALIVE(PushLoad(prop, receiver, key));
9450     HValue* function = Pop();
9451
9452     if (function->IsConstant() &&
9453         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9454       // Push the function under the receiver.
9455       environment()->SetExpressionStackAt(0, function);
9456       Push(receiver);
9457
9458       Handle<JSFunction> known_function = Handle<JSFunction>::cast(
9459           HConstant::cast(function)->handle(isolate()));
9460       expr->set_target(known_function);
9461
9462       if (TryIndirectCall(expr)) return;
9463       CHECK_ALIVE(VisitExpressions(expr->arguments()));
9464
9465       Handle<Map> map = maps->length() == 1 ? maps->first() : Handle<Map>();
9466       if (TryInlineBuiltinMethodCall(expr, known_function, map,
9467                                      expr->arguments()->length())) {
9468         if (FLAG_trace_inlining) {
9469           PrintF("Inlining builtin ");
9470           known_function->ShortPrint();
9471           PrintF("\n");
9472         }
9473         return;
9474       }
9475       if (TryInlineApiMethodCall(expr, receiver, maps)) return;
9476
9477       // Wrap the receiver if necessary.
9478       if (NeedsWrapping(maps->first(), known_function)) {
9479         // Since HWrapReceiver currently cannot actually wrap numbers and
9480         // strings, use the regular CallFunctionStub for method calls to wrap
9481         // the receiver.
9482         // TODO(verwaest): Support creation of value wrappers directly in
9483         // HWrapReceiver.
9484         call = New<HCallFunction>(
9485             function, argument_count, WRAP_AND_CALL);
9486       } else if (TryInlineCall(expr)) {
9487         return;
9488       } else {
9489         call = BuildCallConstantFunction(known_function, argument_count);
9490       }
9491
9492     } else {
9493       ArgumentsAllowedFlag arguments_flag = ARGUMENTS_NOT_ALLOWED;
9494       if (CanBeFunctionApplyArguments(expr) && expr->is_uninitialized()) {
9495         // We have to use EAGER deoptimization here because Deoptimizer::SOFT
9496         // gets ignored by the always-opt flag, which leads to incorrect code.
9497         Add<HDeoptimize>(
9498             Deoptimizer::kInsufficientTypeFeedbackForCallWithArguments,
9499             Deoptimizer::EAGER);
9500         arguments_flag = ARGUMENTS_FAKED;
9501       }
9502
9503       // Push the function under the receiver.
9504       environment()->SetExpressionStackAt(0, function);
9505       Push(receiver);
9506
9507       CHECK_ALIVE(VisitExpressions(expr->arguments(), arguments_flag));
9508       CallFunctionFlags flags = receiver->type().IsJSObject()
9509           ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD;
9510       call = New<HCallFunction>(function, argument_count, flags);
9511     }
9512     PushArgumentsFromEnvironment(argument_count);
9513
9514   } else {
9515     VariableProxy* proxy = expr->expression()->AsVariableProxy();
9516     if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) {
9517       return Bailout(kPossibleDirectCallToEval);
9518     }
9519
9520     // The function is on the stack in the unoptimized code during
9521     // evaluation of the arguments.
9522     CHECK_ALIVE(VisitForValue(expr->expression()));
9523     HValue* function = Top();
9524     if (function->IsConstant() &&
9525         HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9526       Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9527       Handle<JSFunction> target = Handle<JSFunction>::cast(constant);
9528       expr->SetKnownGlobalTarget(target);
9529     }
9530
9531     // Placeholder for the receiver.
9532     Push(graph()->GetConstantUndefined());
9533     CHECK_ALIVE(VisitExpressions(expr->arguments()));
9534
9535     if (expr->IsMonomorphic()) {
9536       Add<HCheckValue>(function, expr->target());
9537
9538       // Patch the global object on the stack by the expected receiver.
9539       HValue* receiver = ImplicitReceiverFor(function, expr->target());
9540       const int receiver_index = argument_count - 1;
9541       environment()->SetExpressionStackAt(receiver_index, receiver);
9542
9543       if (TryInlineBuiltinFunctionCall(expr)) {
9544         if (FLAG_trace_inlining) {
9545           PrintF("Inlining builtin ");
9546           expr->target()->ShortPrint();
9547           PrintF("\n");
9548         }
9549         return;
9550       }
9551       if (TryInlineApiFunctionCall(expr, receiver)) return;
9552       if (TryHandleArrayCall(expr, function)) return;
9553       if (TryInlineCall(expr)) return;
9554
9555       PushArgumentsFromEnvironment(argument_count);
9556       call = BuildCallConstantFunction(expr->target(), argument_count);
9557     } else {
9558       PushArgumentsFromEnvironment(argument_count);
9559       HCallFunction* call_function =
9560           New<HCallFunction>(function, argument_count);
9561       call = call_function;
9562       if (expr->is_uninitialized() &&
9563           expr->IsUsingCallFeedbackICSlot(isolate())) {
9564         // We've never seen this call before, so let's have Crankshaft learn
9565         // through the type vector.
9566         Handle<TypeFeedbackVector> vector =
9567             handle(current_feedback_vector(), isolate());
9568         FeedbackVectorICSlot slot = expr->CallFeedbackICSlot();
9569         call_function->SetVectorAndSlot(vector, slot);
9570       }
9571     }
9572   }
9573
9574   Drop(1);  // Drop the function.
9575   return ast_context()->ReturnInstruction(call, expr->id());
9576 }
9577
9578
9579 void HOptimizedGraphBuilder::BuildInlinedCallArray(
9580     Expression* expression,
9581     int argument_count,
9582     Handle<AllocationSite> site) {
9583   DCHECK(!site.is_null());
9584   DCHECK(argument_count >= 0 && argument_count <= 1);
9585   NoObservableSideEffectsScope no_effects(this);
9586
9587   // We should at least have the constructor on the expression stack.
9588   HValue* constructor = environment()->ExpressionStackAt(argument_count);
9589
9590   // Register on the site for deoptimization if the transition feedback changes.
9591   top_info()->dependencies()->AssumeTransitionStable(site);
9592   ElementsKind kind = site->GetElementsKind();
9593   HInstruction* site_instruction = Add<HConstant>(site);
9594
9595   // In the single constant argument case, we may have to adjust elements kind
9596   // to avoid creating a packed non-empty array.
9597   if (argument_count == 1 && !IsHoleyElementsKind(kind)) {
9598     HValue* argument = environment()->Top();
9599     if (argument->IsConstant()) {
9600       HConstant* constant_argument = HConstant::cast(argument);
9601       DCHECK(constant_argument->HasSmiValue());
9602       int constant_array_size = constant_argument->Integer32Value();
9603       if (constant_array_size != 0) {
9604         kind = GetHoleyElementsKind(kind);
9605       }
9606     }
9607   }
9608
9609   // Build the array.
9610   JSArrayBuilder array_builder(this,
9611                                kind,
9612                                site_instruction,
9613                                constructor,
9614                                DISABLE_ALLOCATION_SITES);
9615   HValue* new_object = argument_count == 0
9616       ? array_builder.AllocateEmptyArray()
9617       : BuildAllocateArrayFromLength(&array_builder, Top());
9618
9619   int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1);
9620   Drop(args_to_drop);
9621   ast_context()->ReturnValue(new_object);
9622 }
9623
9624
9625 // Checks whether allocation using the given constructor can be inlined.
9626 static bool IsAllocationInlineable(Handle<JSFunction> constructor) {
9627   return constructor->has_initial_map() &&
9628          constructor->initial_map()->instance_type() == JS_OBJECT_TYPE &&
9629          constructor->initial_map()->instance_size() <
9630              HAllocate::kMaxInlineSize;
9631 }
9632
9633
9634 bool HOptimizedGraphBuilder::IsCallArrayInlineable(
9635     int argument_count,
9636     Handle<AllocationSite> site) {
9637   Handle<JSFunction> caller = current_info()->closure();
9638   Handle<JSFunction> target = array_function();
9639   // We should have the function plus array arguments on the environment stack.
9640   DCHECK(environment()->length() >= (argument_count + 1));
9641   DCHECK(!site.is_null());
9642
9643   bool inline_ok = false;
9644   if (site->CanInlineCall()) {
9645     // We also want to avoid inlining in certain 1 argument scenarios.
9646     if (argument_count == 1) {
9647       HValue* argument = Top();
9648       if (argument->IsConstant()) {
9649         // Do not inline if the constant length argument is not a smi or
9650         // outside the valid range for unrolled loop initialization.
9651         HConstant* constant_argument = HConstant::cast(argument);
9652         if (constant_argument->HasSmiValue()) {
9653           int value = constant_argument->Integer32Value();
9654           inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold;
9655           if (!inline_ok) {
9656             TraceInline(target, caller,
9657                         "Constant length outside of valid inlining range.");
9658           }
9659         }
9660       } else {
9661         TraceInline(target, caller,
9662                     "Dont inline [new] Array(n) where n isn't constant.");
9663       }
9664     } else if (argument_count == 0) {
9665       inline_ok = true;
9666     } else {
9667       TraceInline(target, caller, "Too many arguments to inline.");
9668     }
9669   } else {
9670     TraceInline(target, caller, "AllocationSite requested no inlining.");
9671   }
9672
9673   if (inline_ok) {
9674     TraceInline(target, caller, NULL);
9675   }
9676   return inline_ok;
9677 }
9678
9679
9680 void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) {
9681   DCHECK(!HasStackOverflow());
9682   DCHECK(current_block() != NULL);
9683   DCHECK(current_block()->HasPredecessor());
9684   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
9685   int argument_count = expr->arguments()->length() + 1;  // Plus constructor.
9686   Factory* factory = isolate()->factory();
9687
9688   // The constructor function is on the stack in the unoptimized code
9689   // during evaluation of the arguments.
9690   CHECK_ALIVE(VisitForValue(expr->expression()));
9691   HValue* function = Top();
9692   CHECK_ALIVE(VisitExpressions(expr->arguments()));
9693
9694   if (function->IsConstant() &&
9695       HConstant::cast(function)->handle(isolate())->IsJSFunction()) {
9696     Handle<Object> constant = HConstant::cast(function)->handle(isolate());
9697     expr->SetKnownGlobalTarget(Handle<JSFunction>::cast(constant));
9698   }
9699
9700   if (FLAG_inline_construct &&
9701       expr->IsMonomorphic() &&
9702       IsAllocationInlineable(expr->target())) {
9703     Handle<JSFunction> constructor = expr->target();
9704     HValue* check = Add<HCheckValue>(function, constructor);
9705
9706     // Force completion of inobject slack tracking before generating
9707     // allocation code to finalize instance size.
9708     if (constructor->IsInobjectSlackTrackingInProgress()) {
9709       constructor->CompleteInobjectSlackTracking();
9710     }
9711
9712     // Calculate instance size from initial map of constructor.
9713     DCHECK(constructor->has_initial_map());
9714     Handle<Map> initial_map(constructor->initial_map());
9715     int instance_size = initial_map->instance_size();
9716
9717     // Allocate an instance of the implicit receiver object.
9718     HValue* size_in_bytes = Add<HConstant>(instance_size);
9719     HAllocationMode allocation_mode;
9720     if (FLAG_pretenuring_call_new) {
9721       if (FLAG_allocation_site_pretenuring) {
9722         // Try to use pretenuring feedback.
9723         Handle<AllocationSite> allocation_site = expr->allocation_site();
9724         allocation_mode = HAllocationMode(allocation_site);
9725         // Take a dependency on allocation site.
9726         top_info()->dependencies()->AssumeTenuringDecision(allocation_site);
9727       }
9728     }
9729
9730     HAllocate* receiver = BuildAllocate(
9731         size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode);
9732     receiver->set_known_initial_map(initial_map);
9733
9734     // Initialize map and fields of the newly allocated object.
9735     { NoObservableSideEffectsScope no_effects(this);
9736       DCHECK(initial_map->instance_type() == JS_OBJECT_TYPE);
9737       Add<HStoreNamedField>(receiver,
9738           HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset),
9739           Add<HConstant>(initial_map));
9740       HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array());
9741       Add<HStoreNamedField>(receiver,
9742           HObjectAccess::ForMapAndOffset(initial_map,
9743                                          JSObject::kPropertiesOffset),
9744           empty_fixed_array);
9745       Add<HStoreNamedField>(receiver,
9746           HObjectAccess::ForMapAndOffset(initial_map,
9747                                          JSObject::kElementsOffset),
9748           empty_fixed_array);
9749       BuildInitializeInobjectProperties(receiver, initial_map);
9750     }
9751
9752     // Replace the constructor function with a newly allocated receiver using
9753     // the index of the receiver from the top of the expression stack.
9754     const int receiver_index = argument_count - 1;
9755     DCHECK(environment()->ExpressionStackAt(receiver_index) == function);
9756     environment()->SetExpressionStackAt(receiver_index, receiver);
9757
9758     if (TryInlineConstruct(expr, receiver)) {
9759       // Inlining worked, add a dependency on the initial map to make sure that
9760       // this code is deoptimized whenever the initial map of the constructor
9761       // changes.
9762       top_info()->dependencies()->AssumeInitialMapCantChange(initial_map);
9763       return;
9764     }
9765
9766     // TODO(mstarzinger): For now we remove the previous HAllocate and all
9767     // corresponding instructions and instead add HPushArguments for the
9768     // arguments in case inlining failed.  What we actually should do is for
9769     // inlining to try to build a subgraph without mutating the parent graph.
9770     HInstruction* instr = current_block()->last();
9771     do {
9772       HInstruction* prev_instr = instr->previous();
9773       instr->DeleteAndReplaceWith(NULL);
9774       instr = prev_instr;
9775     } while (instr != check);
9776     environment()->SetExpressionStackAt(receiver_index, function);
9777     HInstruction* call =
9778       PreProcessCall(New<HCallNew>(function, argument_count));
9779     return ast_context()->ReturnInstruction(call, expr->id());
9780   } else {
9781     // The constructor function is both an operand to the instruction and an
9782     // argument to the construct call.
9783     if (TryHandleArrayCallNew(expr, function)) return;
9784
9785     HInstruction* call =
9786         PreProcessCall(New<HCallNew>(function, argument_count));
9787     return ast_context()->ReturnInstruction(call, expr->id());
9788   }
9789 }
9790
9791
9792 void HOptimizedGraphBuilder::BuildInitializeInobjectProperties(
9793     HValue* receiver, Handle<Map> initial_map) {
9794   if (initial_map->inobject_properties() != 0) {
9795     HConstant* undefined = graph()->GetConstantUndefined();
9796     for (int i = 0; i < initial_map->inobject_properties(); i++) {
9797       int property_offset = initial_map->GetInObjectPropertyOffset(i);
9798       Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(
9799                                           initial_map, property_offset),
9800                             undefined);
9801     }
9802   }
9803 }
9804
9805
9806 HValue* HGraphBuilder::BuildAllocateEmptyArrayBuffer(HValue* byte_length) {
9807   // We HForceRepresentation here to avoid allocations during an *-to-tagged
9808   // HChange that could cause GC while the array buffer object is not fully
9809   // initialized.
9810   HObjectAccess byte_length_access(HObjectAccess::ForJSArrayBufferByteLength());
9811   byte_length = AddUncasted<HForceRepresentation>(
9812       byte_length, byte_length_access.representation());
9813   HAllocate* result =
9814       BuildAllocate(Add<HConstant>(JSArrayBuffer::kSizeWithInternalFields),
9815                     HType::JSObject(), JS_ARRAY_BUFFER_TYPE, HAllocationMode());
9816
9817   HValue* global_object = Add<HLoadNamedField>(
9818       context(), nullptr,
9819       HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
9820   HValue* native_context = Add<HLoadNamedField>(
9821       global_object, nullptr, HObjectAccess::ForGlobalObjectNativeContext());
9822   Add<HStoreNamedField>(
9823       result, HObjectAccess::ForMap(),
9824       Add<HLoadNamedField>(
9825           native_context, nullptr,
9826           HObjectAccess::ForContextSlot(Context::ARRAY_BUFFER_MAP_INDEX)));
9827
9828   HConstant* empty_fixed_array =
9829       Add<HConstant>(isolate()->factory()->empty_fixed_array());
9830   Add<HStoreNamedField>(
9831       result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset),
9832       empty_fixed_array);
9833   Add<HStoreNamedField>(
9834       result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset),
9835       empty_fixed_array);
9836   Add<HStoreNamedField>(
9837       result, HObjectAccess::ForJSArrayBufferBackingStore().WithRepresentation(
9838                   Representation::Smi()),
9839       graph()->GetConstant0());
9840   Add<HStoreNamedField>(result, byte_length_access, byte_length);
9841   Add<HStoreNamedField>(result, HObjectAccess::ForJSArrayBufferBitFieldSlot(),
9842                         graph()->GetConstant0());
9843   Add<HStoreNamedField>(
9844       result, HObjectAccess::ForJSArrayBufferBitField(),
9845       Add<HConstant>((1 << JSArrayBuffer::IsExternal::kShift) |
9846                      (1 << JSArrayBuffer::IsNeuterable::kShift)));
9847
9848   for (int field = 0; field < v8::ArrayBuffer::kInternalFieldCount; ++field) {
9849     Add<HStoreNamedField>(
9850         result,
9851         HObjectAccess::ForObservableJSObjectOffset(
9852             JSArrayBuffer::kSize + field * kPointerSize, Representation::Smi()),
9853         graph()->GetConstant0());
9854   }
9855
9856   return result;
9857 }
9858
9859
9860 template <class ViewClass>
9861 void HGraphBuilder::BuildArrayBufferViewInitialization(
9862     HValue* obj,
9863     HValue* buffer,
9864     HValue* byte_offset,
9865     HValue* byte_length) {
9866
9867   for (int offset = ViewClass::kSize;
9868        offset < ViewClass::kSizeWithInternalFields;
9869        offset += kPointerSize) {
9870     Add<HStoreNamedField>(obj,
9871         HObjectAccess::ForObservableJSObjectOffset(offset),
9872         graph()->GetConstant0());
9873   }
9874
9875   Add<HStoreNamedField>(
9876       obj,
9877       HObjectAccess::ForJSArrayBufferViewByteOffset(),
9878       byte_offset);
9879   Add<HStoreNamedField>(
9880       obj,
9881       HObjectAccess::ForJSArrayBufferViewByteLength(),
9882       byte_length);
9883   Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewBuffer(),
9884                         buffer);
9885 }
9886
9887
9888 void HOptimizedGraphBuilder::GenerateDataViewInitialize(
9889     CallRuntime* expr) {
9890   ZoneList<Expression*>* arguments = expr->arguments();
9891
9892   DCHECK(arguments->length()== 4);
9893   CHECK_ALIVE(VisitForValue(arguments->at(0)));
9894   HValue* obj = Pop();
9895
9896   CHECK_ALIVE(VisitForValue(arguments->at(1)));
9897   HValue* buffer = Pop();
9898
9899   CHECK_ALIVE(VisitForValue(arguments->at(2)));
9900   HValue* byte_offset = Pop();
9901
9902   CHECK_ALIVE(VisitForValue(arguments->at(3)));
9903   HValue* byte_length = Pop();
9904
9905   {
9906     NoObservableSideEffectsScope scope(this);
9907     BuildArrayBufferViewInitialization<JSDataView>(
9908         obj, buffer, byte_offset, byte_length);
9909   }
9910 }
9911
9912
9913 static Handle<Map> TypedArrayMap(Isolate* isolate,
9914                                  ExternalArrayType array_type,
9915                                  ElementsKind target_kind) {
9916   Handle<Context> native_context = isolate->native_context();
9917   Handle<JSFunction> fun;
9918   switch (array_type) {
9919 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
9920     case kExternal##Type##Array:                                              \
9921       fun = Handle<JSFunction>(native_context->type##_array_fun());           \
9922       break;
9923
9924     TYPED_ARRAYS(TYPED_ARRAY_CASE)
9925 #undef TYPED_ARRAY_CASE
9926   }
9927   Handle<Map> map(fun->initial_map());
9928   return Map::AsElementsKind(map, target_kind);
9929 }
9930
9931
9932 HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements(
9933     ExternalArrayType array_type,
9934     bool is_zero_byte_offset,
9935     HValue* buffer, HValue* byte_offset, HValue* length) {
9936   Handle<Map> external_array_map(
9937       isolate()->heap()->MapForFixedTypedArray(array_type));
9938
9939   // The HForceRepresentation is to prevent possible deopt on int-smi
9940   // conversion after allocation but before the new object fields are set.
9941   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9942   HValue* elements = Add<HAllocate>(
9943       Add<HConstant>(FixedTypedArrayBase::kHeaderSize), HType::HeapObject(),
9944       NOT_TENURED, external_array_map->instance_type());
9945
9946   AddStoreMapConstant(elements, external_array_map);
9947   Add<HStoreNamedField>(elements,
9948       HObjectAccess::ForFixedArrayLength(), length);
9949
9950   HValue* backing_store = Add<HLoadNamedField>(
9951       buffer, nullptr, HObjectAccess::ForJSArrayBufferBackingStore());
9952
9953   HValue* typed_array_start;
9954   if (is_zero_byte_offset) {
9955     typed_array_start = backing_store;
9956   } else {
9957     HInstruction* external_pointer =
9958         AddUncasted<HAdd>(backing_store, byte_offset);
9959     // Arguments are checked prior to call to TypedArrayInitialize,
9960     // including byte_offset.
9961     external_pointer->ClearFlag(HValue::kCanOverflow);
9962     typed_array_start = external_pointer;
9963   }
9964
9965   Add<HStoreNamedField>(elements,
9966                         HObjectAccess::ForFixedTypedArrayBaseBasePointer(),
9967                         graph()->GetConstant0());
9968   Add<HStoreNamedField>(elements,
9969                         HObjectAccess::ForFixedTypedArrayBaseExternalPointer(),
9970                         typed_array_start);
9971
9972   return elements;
9973 }
9974
9975
9976 HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray(
9977     ExternalArrayType array_type, size_t element_size,
9978     ElementsKind fixed_elements_kind, HValue* byte_length, HValue* length,
9979     bool initialize) {
9980   STATIC_ASSERT(
9981       (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0);
9982   HValue* total_size;
9983
9984   // if fixed array's elements are not aligned to object's alignment,
9985   // we need to align the whole array to object alignment.
9986   if (element_size % kObjectAlignment != 0) {
9987     total_size = BuildObjectSizeAlignment(
9988         byte_length, FixedTypedArrayBase::kHeaderSize);
9989   } else {
9990     total_size = AddUncasted<HAdd>(byte_length,
9991         Add<HConstant>(FixedTypedArrayBase::kHeaderSize));
9992     total_size->ClearFlag(HValue::kCanOverflow);
9993   }
9994
9995   // The HForceRepresentation is to prevent possible deopt on int-smi
9996   // conversion after allocation but before the new object fields are set.
9997   length = AddUncasted<HForceRepresentation>(length, Representation::Smi());
9998   Handle<Map> fixed_typed_array_map(
9999       isolate()->heap()->MapForFixedTypedArray(array_type));
10000   HAllocate* elements =
10001       Add<HAllocate>(total_size, HType::HeapObject(), NOT_TENURED,
10002                      fixed_typed_array_map->instance_type());
10003
10004 #ifndef V8_HOST_ARCH_64_BIT
10005   if (array_type == kExternalFloat64Array) {
10006     elements->MakeDoubleAligned();
10007   }
10008 #endif
10009
10010   AddStoreMapConstant(elements, fixed_typed_array_map);
10011
10012   Add<HStoreNamedField>(elements,
10013       HObjectAccess::ForFixedArrayLength(),
10014       length);
10015   Add<HStoreNamedField>(
10016       elements, HObjectAccess::ForFixedTypedArrayBaseBasePointer(), elements);
10017
10018   Add<HStoreNamedField>(
10019       elements, HObjectAccess::ForFixedTypedArrayBaseExternalPointer(),
10020       Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()));
10021
10022   HValue* filler = Add<HConstant>(static_cast<int32_t>(0));
10023
10024   if (initialize) {
10025     LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement);
10026
10027     HValue* backing_store = AddUncasted<HAdd>(
10028         Add<HConstant>(ExternalReference::fixed_typed_array_base_data_offset()),
10029         elements, Strength::WEAK, AddOfExternalAndTagged);
10030
10031     HValue* key = builder.BeginBody(
10032         Add<HConstant>(static_cast<int32_t>(0)),
10033         length, Token::LT);
10034     Add<HStoreKeyed>(backing_store, key, filler, fixed_elements_kind);
10035
10036     builder.EndBody();
10037   }
10038   return elements;
10039 }
10040
10041
10042 void HOptimizedGraphBuilder::GenerateTypedArrayInitialize(
10043     CallRuntime* expr) {
10044   ZoneList<Expression*>* arguments = expr->arguments();
10045
10046   static const int kObjectArg = 0;
10047   static const int kArrayIdArg = 1;
10048   static const int kBufferArg = 2;
10049   static const int kByteOffsetArg = 3;
10050   static const int kByteLengthArg = 4;
10051   static const int kInitializeArg = 5;
10052   static const int kArgsLength = 6;
10053   DCHECK(arguments->length() == kArgsLength);
10054
10055
10056   CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg)));
10057   HValue* obj = Pop();
10058
10059   if (!arguments->at(kArrayIdArg)->IsLiteral()) {
10060     // This should never happen in real use, but can happen when fuzzing.
10061     // Just bail out.
10062     Bailout(kNeedSmiLiteral);
10063     return;
10064   }
10065   Handle<Object> value =
10066       static_cast<Literal*>(arguments->at(kArrayIdArg))->value();
10067   if (!value->IsSmi()) {
10068     // This should never happen in real use, but can happen when fuzzing.
10069     // Just bail out.
10070     Bailout(kNeedSmiLiteral);
10071     return;
10072   }
10073   int array_id = Smi::cast(*value)->value();
10074
10075   HValue* buffer;
10076   if (!arguments->at(kBufferArg)->IsNullLiteral()) {
10077     CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg)));
10078     buffer = Pop();
10079   } else {
10080     buffer = NULL;
10081   }
10082
10083   HValue* byte_offset;
10084   bool is_zero_byte_offset;
10085
10086   if (arguments->at(kByteOffsetArg)->IsLiteral()
10087       && Smi::FromInt(0) ==
10088       *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) {
10089     byte_offset = Add<HConstant>(static_cast<int32_t>(0));
10090     is_zero_byte_offset = true;
10091   } else {
10092     CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg)));
10093     byte_offset = Pop();
10094     is_zero_byte_offset = false;
10095     DCHECK(buffer != NULL);
10096   }
10097
10098   CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg)));
10099   HValue* byte_length = Pop();
10100
10101   CHECK(arguments->at(kInitializeArg)->IsLiteral());
10102   bool initialize = static_cast<Literal*>(arguments->at(kInitializeArg))
10103                         ->value()
10104                         ->BooleanValue();
10105
10106   NoObservableSideEffectsScope scope(this);
10107   IfBuilder byte_offset_smi(this);
10108
10109   if (!is_zero_byte_offset) {
10110     byte_offset_smi.If<HIsSmiAndBranch>(byte_offset);
10111     byte_offset_smi.Then();
10112   }
10113
10114   ExternalArrayType array_type =
10115       kExternalInt8Array;  // Bogus initialization.
10116   size_t element_size = 1;  // Bogus initialization.
10117   ElementsKind fixed_elements_kind =  // Bogus initialization.
10118       INT8_ELEMENTS;
10119   Runtime::ArrayIdToTypeAndSize(array_id,
10120       &array_type,
10121       &fixed_elements_kind,
10122       &element_size);
10123
10124
10125   { //  byte_offset is Smi.
10126     HValue* allocated_buffer = buffer;
10127     if (buffer == NULL) {
10128       allocated_buffer = BuildAllocateEmptyArrayBuffer(byte_length);
10129     }
10130     BuildArrayBufferViewInitialization<JSTypedArray>(obj, allocated_buffer,
10131                                                      byte_offset, byte_length);
10132
10133
10134     HInstruction* length = AddUncasted<HDiv>(byte_length,
10135         Add<HConstant>(static_cast<int32_t>(element_size)));
10136
10137     Add<HStoreNamedField>(obj,
10138         HObjectAccess::ForJSTypedArrayLength(),
10139         length);
10140
10141     HValue* elements;
10142     if (buffer != NULL) {
10143       elements = BuildAllocateExternalElements(
10144           array_type, is_zero_byte_offset, buffer, byte_offset, length);
10145       Handle<Map> obj_map =
10146           TypedArrayMap(isolate(), array_type, fixed_elements_kind);
10147       AddStoreMapConstant(obj, obj_map);
10148     } else {
10149       DCHECK(is_zero_byte_offset);
10150       elements = BuildAllocateFixedTypedArray(array_type, element_size,
10151                                               fixed_elements_kind, byte_length,
10152                                               length, initialize);
10153     }
10154     Add<HStoreNamedField>(
10155         obj, HObjectAccess::ForElementsPointer(), elements);
10156   }
10157
10158   if (!is_zero_byte_offset) {
10159     byte_offset_smi.Else();
10160     { //  byte_offset is not Smi.
10161       Push(obj);
10162       CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg)));
10163       Push(buffer);
10164       Push(byte_offset);
10165       Push(byte_length);
10166       CHECK_ALIVE(VisitForValue(arguments->at(kInitializeArg)));
10167       PushArgumentsFromEnvironment(kArgsLength);
10168       Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength);
10169     }
10170   }
10171   byte_offset_smi.End();
10172 }
10173
10174
10175 void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) {
10176   DCHECK(expr->arguments()->length() == 0);
10177   HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue));
10178   return ast_context()->ReturnInstruction(max_smi, expr->id());
10179 }
10180
10181
10182 void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap(
10183     CallRuntime* expr) {
10184   DCHECK(expr->arguments()->length() == 0);
10185   HConstant* result = New<HConstant>(static_cast<int32_t>(
10186         FLAG_typed_array_max_size_in_heap));
10187   return ast_context()->ReturnInstruction(result, expr->id());
10188 }
10189
10190
10191 void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength(
10192     CallRuntime* expr) {
10193   DCHECK(expr->arguments()->length() == 1);
10194   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10195   HValue* buffer = Pop();
10196   HInstruction* result = New<HLoadNamedField>(
10197       buffer, nullptr, HObjectAccess::ForJSArrayBufferByteLength());
10198   return ast_context()->ReturnInstruction(result, expr->id());
10199 }
10200
10201
10202 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength(
10203     CallRuntime* expr) {
10204   NoObservableSideEffectsScope scope(this);
10205   DCHECK(expr->arguments()->length() == 1);
10206   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10207   HValue* view = Pop();
10208
10209   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10210       view, nullptr,
10211       FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteLengthOffset)));
10212 }
10213
10214
10215 void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset(
10216     CallRuntime* expr) {
10217   NoObservableSideEffectsScope scope(this);
10218   DCHECK(expr->arguments()->length() == 1);
10219   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10220   HValue* view = Pop();
10221
10222   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10223       view, nullptr,
10224       FieldIndex::ForInObjectOffset(JSArrayBufferView::kByteOffsetOffset)));
10225 }
10226
10227
10228 void HOptimizedGraphBuilder::GenerateTypedArrayGetLength(
10229     CallRuntime* expr) {
10230   NoObservableSideEffectsScope scope(this);
10231   DCHECK(expr->arguments()->length() == 1);
10232   CHECK_ALIVE(VisitForValue(expr->arguments()->at(0)));
10233   HValue* view = Pop();
10234
10235   return ast_context()->ReturnValue(BuildArrayBufferViewFieldAccessor(
10236       view, nullptr,
10237       FieldIndex::ForInObjectOffset(JSTypedArray::kLengthOffset)));
10238 }
10239
10240
10241 void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) {
10242   DCHECK(!HasStackOverflow());
10243   DCHECK(current_block() != NULL);
10244   DCHECK(current_block()->HasPredecessor());
10245   if (expr->is_jsruntime()) {
10246     return Bailout(kCallToAJavaScriptRuntimeFunction);
10247   }
10248
10249   const Runtime::Function* function = expr->function();
10250   DCHECK(function != NULL);
10251   switch (function->function_id) {
10252 #define CALL_INTRINSIC_GENERATOR(Name) \
10253   case Runtime::kInline##Name:         \
10254     return Generate##Name(expr);
10255
10256     FOR_EACH_HYDROGEN_INTRINSIC(CALL_INTRINSIC_GENERATOR)
10257 #undef CALL_INTRINSIC_GENERATOR
10258     default: {
10259       Handle<String> name = expr->name();
10260       int argument_count = expr->arguments()->length();
10261       CHECK_ALIVE(VisitExpressions(expr->arguments()));
10262       PushArgumentsFromEnvironment(argument_count);
10263       HCallRuntime* call = New<HCallRuntime>(name, function, argument_count);
10264       return ast_context()->ReturnInstruction(call, expr->id());
10265     }
10266   }
10267 }
10268
10269
10270 void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) {
10271   DCHECK(!HasStackOverflow());
10272   DCHECK(current_block() != NULL);
10273   DCHECK(current_block()->HasPredecessor());
10274   switch (expr->op()) {
10275     case Token::DELETE: return VisitDelete(expr);
10276     case Token::VOID: return VisitVoid(expr);
10277     case Token::TYPEOF: return VisitTypeof(expr);
10278     case Token::NOT: return VisitNot(expr);
10279     default: UNREACHABLE();
10280   }
10281 }
10282
10283
10284 void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) {
10285   Property* prop = expr->expression()->AsProperty();
10286   VariableProxy* proxy = expr->expression()->AsVariableProxy();
10287   if (prop != NULL) {
10288     CHECK_ALIVE(VisitForValue(prop->obj()));
10289     CHECK_ALIVE(VisitForValue(prop->key()));
10290     HValue* key = Pop();
10291     HValue* obj = Pop();
10292     HValue* function = AddLoadJSBuiltin(Builtins::DELETE);
10293     Add<HPushArguments>(obj, key, Add<HConstant>(function_language_mode()));
10294     // TODO(olivf) InvokeFunction produces a check for the parameter count,
10295     // even though we are certain to pass the correct number of arguments here.
10296     HInstruction* instr = New<HInvokeFunction>(function, 3);
10297     return ast_context()->ReturnInstruction(instr, expr->id());
10298   } else if (proxy != NULL) {
10299     Variable* var = proxy->var();
10300     if (var->IsUnallocatedOrGlobalSlot()) {
10301       Bailout(kDeleteWithGlobalVariable);
10302     } else if (var->IsStackAllocated() || var->IsContextSlot()) {
10303       // Result of deleting non-global variables is false.  'this' is not really
10304       // a variable, though we implement it as one.  The subexpression does not
10305       // have side effects.
10306       HValue* value = var->HasThisName(isolate()) ? graph()->GetConstantTrue()
10307                                                   : graph()->GetConstantFalse();
10308       return ast_context()->ReturnValue(value);
10309     } else {
10310       Bailout(kDeleteWithNonGlobalVariable);
10311     }
10312   } else {
10313     // Result of deleting non-property, non-variable reference is true.
10314     // Evaluate the subexpression for side effects.
10315     CHECK_ALIVE(VisitForEffect(expr->expression()));
10316     return ast_context()->ReturnValue(graph()->GetConstantTrue());
10317   }
10318 }
10319
10320
10321 void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) {
10322   CHECK_ALIVE(VisitForEffect(expr->expression()));
10323   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
10324 }
10325
10326
10327 void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) {
10328   CHECK_ALIVE(VisitForTypeOf(expr->expression()));
10329   HValue* value = Pop();
10330   HInstruction* instr = New<HTypeof>(value);
10331   return ast_context()->ReturnInstruction(instr, expr->id());
10332 }
10333
10334
10335 void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) {
10336   if (ast_context()->IsTest()) {
10337     TestContext* context = TestContext::cast(ast_context());
10338     VisitForControl(expr->expression(),
10339                     context->if_false(),
10340                     context->if_true());
10341     return;
10342   }
10343
10344   if (ast_context()->IsEffect()) {
10345     VisitForEffect(expr->expression());
10346     return;
10347   }
10348
10349   DCHECK(ast_context()->IsValue());
10350   HBasicBlock* materialize_false = graph()->CreateBasicBlock();
10351   HBasicBlock* materialize_true = graph()->CreateBasicBlock();
10352   CHECK_BAILOUT(VisitForControl(expr->expression(),
10353                                 materialize_false,
10354                                 materialize_true));
10355
10356   if (materialize_false->HasPredecessor()) {
10357     materialize_false->SetJoinId(expr->MaterializeFalseId());
10358     set_current_block(materialize_false);
10359     Push(graph()->GetConstantFalse());
10360   } else {
10361     materialize_false = NULL;
10362   }
10363
10364   if (materialize_true->HasPredecessor()) {
10365     materialize_true->SetJoinId(expr->MaterializeTrueId());
10366     set_current_block(materialize_true);
10367     Push(graph()->GetConstantTrue());
10368   } else {
10369     materialize_true = NULL;
10370   }
10371
10372   HBasicBlock* join =
10373     CreateJoin(materialize_false, materialize_true, expr->id());
10374   set_current_block(join);
10375   if (join != NULL) return ast_context()->ReturnValue(Pop());
10376 }
10377
10378
10379 static Representation RepresentationFor(Type* type) {
10380   DisallowHeapAllocation no_allocation;
10381   if (type->Is(Type::None())) return Representation::None();
10382   if (type->Is(Type::SignedSmall())) return Representation::Smi();
10383   if (type->Is(Type::Signed32())) return Representation::Integer32();
10384   if (type->Is(Type::Number())) return Representation::Double();
10385   return Representation::Tagged();
10386 }
10387
10388
10389 HInstruction* HOptimizedGraphBuilder::BuildIncrement(
10390     bool returns_original_input,
10391     CountOperation* expr) {
10392   // The input to the count operation is on top of the expression stack.
10393   Representation rep = RepresentationFor(expr->type());
10394   if (rep.IsNone() || rep.IsTagged()) {
10395     rep = Representation::Smi();
10396   }
10397
10398   if (returns_original_input && !is_strong(function_language_mode())) {
10399     // We need an explicit HValue representing ToNumber(input).  The
10400     // actual HChange instruction we need is (sometimes) added in a later
10401     // phase, so it is not available now to be used as an input to HAdd and
10402     // as the return value.
10403     HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep);
10404     if (!rep.IsDouble()) {
10405       number_input->SetFlag(HInstruction::kFlexibleRepresentation);
10406       number_input->SetFlag(HInstruction::kCannotBeTagged);
10407     }
10408     Push(number_input);
10409   }
10410
10411   // The addition has no side effects, so we do not need
10412   // to simulate the expression stack after this instruction.
10413   // Any later failures deopt to the load of the input or earlier.
10414   HConstant* delta = (expr->op() == Token::INC)
10415       ? graph()->GetConstant1()
10416       : graph()->GetConstantMinus1();
10417   HInstruction* instr =
10418       AddUncasted<HAdd>(Top(), delta, strength(function_language_mode()));
10419   if (instr->IsAdd()) {
10420     HAdd* add = HAdd::cast(instr);
10421     add->set_observed_input_representation(1, rep);
10422     add->set_observed_input_representation(2, Representation::Smi());
10423   }
10424   if (!is_strong(function_language_mode())) {
10425     instr->ClearAllSideEffects();
10426   } else {
10427     Add<HSimulate>(expr->ToNumberId(), REMOVABLE_SIMULATE);
10428   }
10429   instr->SetFlag(HInstruction::kCannotBeTagged);
10430   return instr;
10431 }
10432
10433
10434 void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr,
10435                                                  Property* prop,
10436                                                  BailoutId ast_id,
10437                                                  BailoutId return_id,
10438                                                  HValue* object,
10439                                                  HValue* key,
10440                                                  HValue* value) {
10441   EffectContext for_effect(this);
10442   Push(object);
10443   if (key != NULL) Push(key);
10444   Push(value);
10445   BuildStore(expr, prop, ast_id, return_id);
10446 }
10447
10448
10449 void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) {
10450   DCHECK(!HasStackOverflow());
10451   DCHECK(current_block() != NULL);
10452   DCHECK(current_block()->HasPredecessor());
10453   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
10454   Expression* target = expr->expression();
10455   VariableProxy* proxy = target->AsVariableProxy();
10456   Property* prop = target->AsProperty();
10457   if (proxy == NULL && prop == NULL) {
10458     return Bailout(kInvalidLhsInCountOperation);
10459   }
10460
10461   // Match the full code generator stack by simulating an extra stack
10462   // element for postfix operations in a non-effect context.  The return
10463   // value is ToNumber(input).
10464   bool returns_original_input =
10465       expr->is_postfix() && !ast_context()->IsEffect();
10466   HValue* input = NULL;  // ToNumber(original_input).
10467   HValue* after = NULL;  // The result after incrementing or decrementing.
10468
10469   if (proxy != NULL) {
10470     Variable* var = proxy->var();
10471     if (var->mode() == CONST_LEGACY)  {
10472       return Bailout(kUnsupportedCountOperationWithConst);
10473     }
10474     if (var->mode() == CONST) {
10475       return Bailout(kNonInitializerAssignmentToConst);
10476     }
10477     // Argument of the count operation is a variable, not a property.
10478     DCHECK(prop == NULL);
10479     CHECK_ALIVE(VisitForValue(target));
10480
10481     after = BuildIncrement(returns_original_input, expr);
10482     input = returns_original_input ? Top() : Pop();
10483     Push(after);
10484
10485     switch (var->location()) {
10486       case VariableLocation::GLOBAL:
10487       case VariableLocation::UNALLOCATED:
10488         HandleGlobalVariableAssignment(var,
10489                                        after,
10490                                        expr->AssignmentId());
10491         break;
10492
10493       case VariableLocation::PARAMETER:
10494       case VariableLocation::LOCAL:
10495         BindIfLive(var, after);
10496         break;
10497
10498       case VariableLocation::CONTEXT: {
10499         // Bail out if we try to mutate a parameter value in a function
10500         // using the arguments object.  We do not (yet) correctly handle the
10501         // arguments property of the function.
10502         if (current_info()->scope()->arguments() != NULL) {
10503           // Parameters will rewrite to context slots.  We have no direct
10504           // way to detect that the variable is a parameter so we use a
10505           // linear search of the parameter list.
10506           int count = current_info()->scope()->num_parameters();
10507           for (int i = 0; i < count; ++i) {
10508             if (var == current_info()->scope()->parameter(i)) {
10509               return Bailout(kAssignmentToParameterInArgumentsObject);
10510             }
10511           }
10512         }
10513
10514         HValue* context = BuildContextChainWalk(var);
10515         HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode())
10516             ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck;
10517         HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(),
10518                                                           mode, after);
10519         if (instr->HasObservableSideEffects()) {
10520           Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE);
10521         }
10522         break;
10523       }
10524
10525       case VariableLocation::LOOKUP:
10526         return Bailout(kLookupVariableInCountOperation);
10527     }
10528
10529     Drop(returns_original_input ? 2 : 1);
10530     return ast_context()->ReturnValue(expr->is_postfix() ? input : after);
10531   }
10532
10533   // Argument of the count operation is a property.
10534   DCHECK(prop != NULL);
10535   if (returns_original_input) Push(graph()->GetConstantUndefined());
10536
10537   CHECK_ALIVE(VisitForValue(prop->obj()));
10538   HValue* object = Top();
10539
10540   HValue* key = NULL;
10541   if (!prop->key()->IsPropertyName() || prop->IsStringAccess()) {
10542     CHECK_ALIVE(VisitForValue(prop->key()));
10543     key = Top();
10544   }
10545
10546   CHECK_ALIVE(PushLoad(prop, object, key));
10547
10548   after = BuildIncrement(returns_original_input, expr);
10549
10550   if (returns_original_input) {
10551     input = Pop();
10552     // Drop object and key to push it again in the effect context below.
10553     Drop(key == NULL ? 1 : 2);
10554     environment()->SetExpressionStackAt(0, input);
10555     CHECK_ALIVE(BuildStoreForEffect(
10556         expr, prop, expr->id(), expr->AssignmentId(), object, key, after));
10557     return ast_context()->ReturnValue(Pop());
10558   }
10559
10560   environment()->SetExpressionStackAt(0, after);
10561   return BuildStore(expr, prop, expr->id(), expr->AssignmentId());
10562 }
10563
10564
10565 HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt(
10566     HValue* string,
10567     HValue* index) {
10568   if (string->IsConstant() && index->IsConstant()) {
10569     HConstant* c_string = HConstant::cast(string);
10570     HConstant* c_index = HConstant::cast(index);
10571     if (c_string->HasStringValue() && c_index->HasNumberValue()) {
10572       int32_t i = c_index->NumberValueAsInteger32();
10573       Handle<String> s = c_string->StringValue();
10574       if (i < 0 || i >= s->length()) {
10575         return New<HConstant>(std::numeric_limits<double>::quiet_NaN());
10576       }
10577       return New<HConstant>(s->Get(i));
10578     }
10579   }
10580   string = BuildCheckString(string);
10581   index = Add<HBoundsCheck>(index, AddLoadStringLength(string));
10582   return New<HStringCharCodeAt>(string, index);
10583 }
10584
10585
10586 // Checks if the given shift amounts have following forms:
10587 // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa).
10588 static bool ShiftAmountsAllowReplaceByRotate(HValue* sa,
10589                                              HValue* const32_minus_sa) {
10590   if (sa->IsConstant() && const32_minus_sa->IsConstant()) {
10591     const HConstant* c1 = HConstant::cast(sa);
10592     const HConstant* c2 = HConstant::cast(const32_minus_sa);
10593     return c1->HasInteger32Value() && c2->HasInteger32Value() &&
10594         (c1->Integer32Value() + c2->Integer32Value() == 32);
10595   }
10596   if (!const32_minus_sa->IsSub()) return false;
10597   HSub* sub = HSub::cast(const32_minus_sa);
10598   return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa;
10599 }
10600
10601
10602 // Checks if the left and the right are shift instructions with the oposite
10603 // directions that can be replaced by one rotate right instruction or not.
10604 // Returns the operand and the shift amount for the rotate instruction in the
10605 // former case.
10606 bool HGraphBuilder::MatchRotateRight(HValue* left,
10607                                      HValue* right,
10608                                      HValue** operand,
10609                                      HValue** shift_amount) {
10610   HShl* shl;
10611   HShr* shr;
10612   if (left->IsShl() && right->IsShr()) {
10613     shl = HShl::cast(left);
10614     shr = HShr::cast(right);
10615   } else if (left->IsShr() && right->IsShl()) {
10616     shl = HShl::cast(right);
10617     shr = HShr::cast(left);
10618   } else {
10619     return false;
10620   }
10621   if (shl->left() != shr->left()) return false;
10622
10623   if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) &&
10624       !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) {
10625     return false;
10626   }
10627   *operand = shr->left();
10628   *shift_amount = shr->right();
10629   return true;
10630 }
10631
10632
10633 bool CanBeZero(HValue* right) {
10634   if (right->IsConstant()) {
10635     HConstant* right_const = HConstant::cast(right);
10636     if (right_const->HasInteger32Value() &&
10637        (right_const->Integer32Value() & 0x1f) != 0) {
10638       return false;
10639     }
10640   }
10641   return true;
10642 }
10643
10644
10645 HValue* HGraphBuilder::EnforceNumberType(HValue* number,
10646                                          Type* expected) {
10647   if (expected->Is(Type::SignedSmall())) {
10648     return AddUncasted<HForceRepresentation>(number, Representation::Smi());
10649   }
10650   if (expected->Is(Type::Signed32())) {
10651     return AddUncasted<HForceRepresentation>(number,
10652                                              Representation::Integer32());
10653   }
10654   return number;
10655 }
10656
10657
10658 HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) {
10659   if (value->IsConstant()) {
10660     HConstant* constant = HConstant::cast(value);
10661     Maybe<HConstant*> number =
10662         constant->CopyToTruncatedNumber(isolate(), zone());
10663     if (number.IsJust()) {
10664       *expected = Type::Number(zone());
10665       return AddInstruction(number.FromJust());
10666     }
10667   }
10668
10669   // We put temporary values on the stack, which don't correspond to anything
10670   // in baseline code. Since nothing is observable we avoid recording those
10671   // pushes with a NoObservableSideEffectsScope.
10672   NoObservableSideEffectsScope no_effects(this);
10673
10674   Type* expected_type = *expected;
10675
10676   // Separate the number type from the rest.
10677   Type* expected_obj =
10678       Type::Intersect(expected_type, Type::NonNumber(zone()), zone());
10679   Type* expected_number =
10680       Type::Intersect(expected_type, Type::Number(zone()), zone());
10681
10682   // We expect to get a number.
10683   // (We need to check first, since Type::None->Is(Type::Any()) == true.
10684   if (expected_obj->Is(Type::None())) {
10685     DCHECK(!expected_number->Is(Type::None(zone())));
10686     return value;
10687   }
10688
10689   if (expected_obj->Is(Type::Undefined(zone()))) {
10690     // This is already done by HChange.
10691     *expected = Type::Union(expected_number, Type::Number(zone()), zone());
10692     return value;
10693   }
10694
10695   return value;
10696 }
10697
10698
10699 HValue* HOptimizedGraphBuilder::BuildBinaryOperation(
10700     BinaryOperation* expr,
10701     HValue* left,
10702     HValue* right,
10703     PushBeforeSimulateBehavior push_sim_result) {
10704   Type* left_type = expr->left()->bounds().lower;
10705   Type* right_type = expr->right()->bounds().lower;
10706   Type* result_type = expr->bounds().lower;
10707   Maybe<int> fixed_right_arg = expr->fixed_right_arg();
10708   Handle<AllocationSite> allocation_site = expr->allocation_site();
10709
10710   HAllocationMode allocation_mode;
10711   if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) {
10712     allocation_mode = HAllocationMode(allocation_site);
10713   }
10714   HValue* result = HGraphBuilder::BuildBinaryOperation(
10715       expr->op(), left, right, left_type, right_type, result_type,
10716       fixed_right_arg, allocation_mode, strength(function_language_mode()),
10717       expr->id());
10718   // Add a simulate after instructions with observable side effects, and
10719   // after phis, which are the result of BuildBinaryOperation when we
10720   // inlined some complex subgraph.
10721   if (result->HasObservableSideEffects() || result->IsPhi()) {
10722     if (push_sim_result == PUSH_BEFORE_SIMULATE) {
10723       Push(result);
10724       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10725       Drop(1);
10726     } else {
10727       Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE);
10728     }
10729   }
10730   return result;
10731 }
10732
10733
10734 HValue* HGraphBuilder::BuildBinaryOperation(
10735     Token::Value op, HValue* left, HValue* right, Type* left_type,
10736     Type* right_type, Type* result_type, Maybe<int> fixed_right_arg,
10737     HAllocationMode allocation_mode, Strength strength, BailoutId opt_id) {
10738   bool maybe_string_add = false;
10739   if (op == Token::ADD) {
10740     // If we are adding constant string with something for which we don't have
10741     // a feedback yet, assume that it's also going to be a string and don't
10742     // generate deopt instructions.
10743     if (!left_type->IsInhabited() && right->IsConstant() &&
10744         HConstant::cast(right)->HasStringValue()) {
10745       left_type = Type::String();
10746     }
10747
10748     if (!right_type->IsInhabited() && left->IsConstant() &&
10749         HConstant::cast(left)->HasStringValue()) {
10750       right_type = Type::String();
10751     }
10752
10753     maybe_string_add = (left_type->Maybe(Type::String()) ||
10754                         left_type->Maybe(Type::Receiver()) ||
10755                         right_type->Maybe(Type::String()) ||
10756                         right_type->Maybe(Type::Receiver()));
10757   }
10758
10759   Representation left_rep = RepresentationFor(left_type);
10760   Representation right_rep = RepresentationFor(right_type);
10761
10762   if (!left_type->IsInhabited()) {
10763     Add<HDeoptimize>(
10764         Deoptimizer::kInsufficientTypeFeedbackForLHSOfBinaryOperation,
10765         Deoptimizer::SOFT);
10766     left_type = Type::Any(zone());
10767     left_rep = RepresentationFor(left_type);
10768     maybe_string_add = op == Token::ADD;
10769   }
10770
10771   if (!right_type->IsInhabited()) {
10772     Add<HDeoptimize>(
10773         Deoptimizer::kInsufficientTypeFeedbackForRHSOfBinaryOperation,
10774         Deoptimizer::SOFT);
10775     right_type = Type::Any(zone());
10776     right_rep = RepresentationFor(right_type);
10777     maybe_string_add = op == Token::ADD;
10778   }
10779
10780   if (!maybe_string_add && !is_strong(strength)) {
10781     left = TruncateToNumber(left, &left_type);
10782     right = TruncateToNumber(right, &right_type);
10783   }
10784
10785   // Special case for string addition here.
10786   if (op == Token::ADD &&
10787       (left_type->Is(Type::String()) || right_type->Is(Type::String()))) {
10788     // Validate type feedback for left argument.
10789     if (left_type->Is(Type::String())) {
10790       left = BuildCheckString(left);
10791     }
10792
10793     // Validate type feedback for right argument.
10794     if (right_type->Is(Type::String())) {
10795       right = BuildCheckString(right);
10796     }
10797
10798     // Convert left argument as necessary.
10799     if (left_type->Is(Type::Number()) && !is_strong(strength)) {
10800       DCHECK(right_type->Is(Type::String()));
10801       left = BuildNumberToString(left, left_type);
10802     } else if (!left_type->Is(Type::String())) {
10803       DCHECK(right_type->Is(Type::String()));
10804       HValue* function = AddLoadJSBuiltin(
10805           is_strong(strength) ? Builtins::STRING_ADD_RIGHT_STRONG
10806                               : Builtins::STRING_ADD_RIGHT);
10807       Add<HPushArguments>(left, right);
10808       return AddUncasted<HInvokeFunction>(function, 2);
10809     }
10810
10811     // Convert right argument as necessary.
10812     if (right_type->Is(Type::Number()) && !is_strong(strength)) {
10813       DCHECK(left_type->Is(Type::String()));
10814       right = BuildNumberToString(right, right_type);
10815     } else if (!right_type->Is(Type::String())) {
10816       DCHECK(left_type->Is(Type::String()));
10817       HValue* function = AddLoadJSBuiltin(is_strong(strength)
10818                                               ? Builtins::STRING_ADD_LEFT_STRONG
10819                                               : Builtins::STRING_ADD_LEFT);
10820       Add<HPushArguments>(left, right);
10821       return AddUncasted<HInvokeFunction>(function, 2);
10822     }
10823
10824     // Fast paths for empty constant strings.
10825     Handle<String> left_string =
10826         left->IsConstant() && HConstant::cast(left)->HasStringValue()
10827             ? HConstant::cast(left)->StringValue()
10828             : Handle<String>();
10829     Handle<String> right_string =
10830         right->IsConstant() && HConstant::cast(right)->HasStringValue()
10831             ? HConstant::cast(right)->StringValue()
10832             : Handle<String>();
10833     if (!left_string.is_null() && left_string->length() == 0) return right;
10834     if (!right_string.is_null() && right_string->length() == 0) return left;
10835     if (!left_string.is_null() && !right_string.is_null()) {
10836       return AddUncasted<HStringAdd>(
10837           left, right, strength, allocation_mode.GetPretenureMode(),
10838           STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10839     }
10840
10841     // Register the dependent code with the allocation site.
10842     if (!allocation_mode.feedback_site().is_null()) {
10843       DCHECK(!graph()->info()->IsStub());
10844       Handle<AllocationSite> site(allocation_mode.feedback_site());
10845       top_info()->dependencies()->AssumeTenuringDecision(site);
10846     }
10847
10848     // Inline the string addition into the stub when creating allocation
10849     // mementos to gather allocation site feedback, or if we can statically
10850     // infer that we're going to create a cons string.
10851     if ((graph()->info()->IsStub() &&
10852          allocation_mode.CreateAllocationMementos()) ||
10853         (left->IsConstant() &&
10854          HConstant::cast(left)->HasStringValue() &&
10855          HConstant::cast(left)->StringValue()->length() + 1 >=
10856            ConsString::kMinLength) ||
10857         (right->IsConstant() &&
10858          HConstant::cast(right)->HasStringValue() &&
10859          HConstant::cast(right)->StringValue()->length() + 1 >=
10860            ConsString::kMinLength)) {
10861       return BuildStringAdd(left, right, allocation_mode);
10862     }
10863
10864     // Fallback to using the string add stub.
10865     return AddUncasted<HStringAdd>(
10866         left, right, strength, allocation_mode.GetPretenureMode(),
10867         STRING_ADD_CHECK_NONE, allocation_mode.feedback_site());
10868   }
10869
10870   if (graph()->info()->IsStub()) {
10871     left = EnforceNumberType(left, left_type);
10872     right = EnforceNumberType(right, right_type);
10873   }
10874
10875   Representation result_rep = RepresentationFor(result_type);
10876
10877   bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) ||
10878                           (right_rep.IsTagged() && !right_rep.IsSmi());
10879
10880   HInstruction* instr = NULL;
10881   // Only the stub is allowed to call into the runtime, since otherwise we would
10882   // inline several instructions (including the two pushes) for every tagged
10883   // operation in optimized code, which is more expensive, than a stub call.
10884   if (graph()->info()->IsStub() && is_non_primitive) {
10885     HValue* function =
10886         AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op, strength));
10887     Add<HPushArguments>(left, right);
10888     instr = AddUncasted<HInvokeFunction>(function, 2);
10889   } else {
10890     if (is_strong(strength) && Token::IsBitOp(op)) {
10891       // TODO(conradw): This is not efficient, but is necessary to prevent
10892       // conversion of oddball values to numbers in strong mode. It would be
10893       // better to prevent the conversion rather than adding a runtime check.
10894       IfBuilder if_builder(this);
10895       if_builder.If<HHasInstanceTypeAndBranch>(left, ODDBALL_TYPE);
10896       if_builder.OrIf<HHasInstanceTypeAndBranch>(right, ODDBALL_TYPE);
10897       if_builder.Then();
10898       Add<HCallRuntime>(
10899           isolate()->factory()->empty_string(),
10900           Runtime::FunctionForId(Runtime::kThrowStrongModeImplicitConversion),
10901           0);
10902       if (!graph()->info()->IsStub()) {
10903         Add<HSimulate>(opt_id, REMOVABLE_SIMULATE);
10904       }
10905       if_builder.End();
10906     }
10907     switch (op) {
10908       case Token::ADD:
10909         instr = AddUncasted<HAdd>(left, right, strength);
10910         break;
10911       case Token::SUB:
10912         instr = AddUncasted<HSub>(left, right, strength);
10913         break;
10914       case Token::MUL:
10915         instr = AddUncasted<HMul>(left, right, strength);
10916         break;
10917       case Token::MOD: {
10918         if (fixed_right_arg.IsJust() &&
10919             !right->EqualsInteger32Constant(fixed_right_arg.FromJust())) {
10920           HConstant* fixed_right =
10921               Add<HConstant>(static_cast<int>(fixed_right_arg.FromJust()));
10922           IfBuilder if_same(this);
10923           if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ);
10924           if_same.Then();
10925           if_same.ElseDeopt(Deoptimizer::kUnexpectedRHSOfBinaryOperation);
10926           right = fixed_right;
10927         }
10928         instr = AddUncasted<HMod>(left, right, strength);
10929         break;
10930       }
10931       case Token::DIV:
10932         instr = AddUncasted<HDiv>(left, right, strength);
10933         break;
10934       case Token::BIT_XOR:
10935       case Token::BIT_AND:
10936         instr = AddUncasted<HBitwise>(op, left, right, strength);
10937         break;
10938       case Token::BIT_OR: {
10939         HValue* operand, *shift_amount;
10940         if (left_type->Is(Type::Signed32()) &&
10941             right_type->Is(Type::Signed32()) &&
10942             MatchRotateRight(left, right, &operand, &shift_amount)) {
10943           instr = AddUncasted<HRor>(operand, shift_amount, strength);
10944         } else {
10945           instr = AddUncasted<HBitwise>(op, left, right, strength);
10946         }
10947         break;
10948       }
10949       case Token::SAR:
10950         instr = AddUncasted<HSar>(left, right, strength);
10951         break;
10952       case Token::SHR:
10953         instr = AddUncasted<HShr>(left, right, strength);
10954         if (instr->IsShr() && CanBeZero(right)) {
10955           graph()->RecordUint32Instruction(instr);
10956         }
10957         break;
10958       case Token::SHL:
10959         instr = AddUncasted<HShl>(left, right, strength);
10960         break;
10961       default:
10962         UNREACHABLE();
10963     }
10964   }
10965
10966   if (instr->IsBinaryOperation()) {
10967     HBinaryOperation* binop = HBinaryOperation::cast(instr);
10968     binop->set_observed_input_representation(1, left_rep);
10969     binop->set_observed_input_representation(2, right_rep);
10970     binop->initialize_output_representation(result_rep);
10971     if (graph()->info()->IsStub()) {
10972       // Stub should not call into stub.
10973       instr->SetFlag(HValue::kCannotBeTagged);
10974       // And should truncate on HForceRepresentation already.
10975       if (left->IsForceRepresentation()) {
10976         left->CopyFlag(HValue::kTruncatingToSmi, instr);
10977         left->CopyFlag(HValue::kTruncatingToInt32, instr);
10978       }
10979       if (right->IsForceRepresentation()) {
10980         right->CopyFlag(HValue::kTruncatingToSmi, instr);
10981         right->CopyFlag(HValue::kTruncatingToInt32, instr);
10982       }
10983     }
10984   }
10985   return instr;
10986 }
10987
10988
10989 // Check for the form (%_ClassOf(foo) === 'BarClass').
10990 static bool IsClassOfTest(CompareOperation* expr) {
10991   if (expr->op() != Token::EQ_STRICT) return false;
10992   CallRuntime* call = expr->left()->AsCallRuntime();
10993   if (call == NULL) return false;
10994   Literal* literal = expr->right()->AsLiteral();
10995   if (literal == NULL) return false;
10996   if (!literal->value()->IsString()) return false;
10997   if (!call->name()->IsOneByteEqualTo(STATIC_CHAR_VECTOR("_ClassOf"))) {
10998     return false;
10999   }
11000   DCHECK(call->arguments()->length() == 1);
11001   return true;
11002 }
11003
11004
11005 void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) {
11006   DCHECK(!HasStackOverflow());
11007   DCHECK(current_block() != NULL);
11008   DCHECK(current_block()->HasPredecessor());
11009   switch (expr->op()) {
11010     case Token::COMMA:
11011       return VisitComma(expr);
11012     case Token::OR:
11013     case Token::AND:
11014       return VisitLogicalExpression(expr);
11015     default:
11016       return VisitArithmeticExpression(expr);
11017   }
11018 }
11019
11020
11021 void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) {
11022   CHECK_ALIVE(VisitForEffect(expr->left()));
11023   // Visit the right subexpression in the same AST context as the entire
11024   // expression.
11025   Visit(expr->right());
11026 }
11027
11028
11029 void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) {
11030   bool is_logical_and = expr->op() == Token::AND;
11031   if (ast_context()->IsTest()) {
11032     TestContext* context = TestContext::cast(ast_context());
11033     // Translate left subexpression.
11034     HBasicBlock* eval_right = graph()->CreateBasicBlock();
11035     if (is_logical_and) {
11036       CHECK_BAILOUT(VisitForControl(expr->left(),
11037                                     eval_right,
11038                                     context->if_false()));
11039     } else {
11040       CHECK_BAILOUT(VisitForControl(expr->left(),
11041                                     context->if_true(),
11042                                     eval_right));
11043     }
11044
11045     // Translate right subexpression by visiting it in the same AST
11046     // context as the entire expression.
11047     if (eval_right->HasPredecessor()) {
11048       eval_right->SetJoinId(expr->RightId());
11049       set_current_block(eval_right);
11050       Visit(expr->right());
11051     }
11052
11053   } else if (ast_context()->IsValue()) {
11054     CHECK_ALIVE(VisitForValue(expr->left()));
11055     DCHECK(current_block() != NULL);
11056     HValue* left_value = Top();
11057
11058     // Short-circuit left values that always evaluate to the same boolean value.
11059     if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) {
11060       // l (evals true)  && r -> r
11061       // l (evals true)  || r -> l
11062       // l (evals false) && r -> l
11063       // l (evals false) || r -> r
11064       if (is_logical_and == expr->left()->ToBooleanIsTrue()) {
11065         Drop(1);
11066         CHECK_ALIVE(VisitForValue(expr->right()));
11067       }
11068       return ast_context()->ReturnValue(Pop());
11069     }
11070
11071     // We need an extra block to maintain edge-split form.
11072     HBasicBlock* empty_block = graph()->CreateBasicBlock();
11073     HBasicBlock* eval_right = graph()->CreateBasicBlock();
11074     ToBooleanStub::Types expected(expr->left()->to_boolean_types());
11075     HBranch* test = is_logical_and
11076         ? New<HBranch>(left_value, expected, eval_right, empty_block)
11077         : New<HBranch>(left_value, expected, empty_block, eval_right);
11078     FinishCurrentBlock(test);
11079
11080     set_current_block(eval_right);
11081     Drop(1);  // Value of the left subexpression.
11082     CHECK_BAILOUT(VisitForValue(expr->right()));
11083
11084     HBasicBlock* join_block =
11085       CreateJoin(empty_block, current_block(), expr->id());
11086     set_current_block(join_block);
11087     return ast_context()->ReturnValue(Pop());
11088
11089   } else {
11090     DCHECK(ast_context()->IsEffect());
11091     // In an effect context, we don't need the value of the left subexpression,
11092     // only its control flow and side effects.  We need an extra block to
11093     // maintain edge-split form.
11094     HBasicBlock* empty_block = graph()->CreateBasicBlock();
11095     HBasicBlock* right_block = graph()->CreateBasicBlock();
11096     if (is_logical_and) {
11097       CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block));
11098     } else {
11099       CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block));
11100     }
11101
11102     // TODO(kmillikin): Find a way to fix this.  It's ugly that there are
11103     // actually two empty blocks (one here and one inserted by
11104     // TestContext::BuildBranch, and that they both have an HSimulate though the
11105     // second one is not a merge node, and that we really have no good AST ID to
11106     // put on that first HSimulate.
11107
11108     if (empty_block->HasPredecessor()) {
11109       empty_block->SetJoinId(expr->id());
11110     } else {
11111       empty_block = NULL;
11112     }
11113
11114     if (right_block->HasPredecessor()) {
11115       right_block->SetJoinId(expr->RightId());
11116       set_current_block(right_block);
11117       CHECK_BAILOUT(VisitForEffect(expr->right()));
11118       right_block = current_block();
11119     } else {
11120       right_block = NULL;
11121     }
11122
11123     HBasicBlock* join_block =
11124       CreateJoin(empty_block, right_block, expr->id());
11125     set_current_block(join_block);
11126     // We did not materialize any value in the predecessor environments,
11127     // so there is no need to handle it here.
11128   }
11129 }
11130
11131
11132 void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) {
11133   CHECK_ALIVE(VisitForValue(expr->left()));
11134   CHECK_ALIVE(VisitForValue(expr->right()));
11135   SetSourcePosition(expr->position());
11136   HValue* right = Pop();
11137   HValue* left = Pop();
11138   HValue* result =
11139       BuildBinaryOperation(expr, left, right,
11140           ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11141                                     : PUSH_BEFORE_SIMULATE);
11142   if (top_info()->is_tracking_positions() && result->IsBinaryOperation()) {
11143     HBinaryOperation::cast(result)->SetOperandPositions(
11144         zone(),
11145         ScriptPositionToSourcePosition(expr->left()->position()),
11146         ScriptPositionToSourcePosition(expr->right()->position()));
11147   }
11148   return ast_context()->ReturnValue(result);
11149 }
11150
11151
11152 void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr,
11153                                                         Expression* sub_expr,
11154                                                         Handle<String> check) {
11155   CHECK_ALIVE(VisitForTypeOf(sub_expr));
11156   SetSourcePosition(expr->position());
11157   HValue* value = Pop();
11158   HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check);
11159   return ast_context()->ReturnControl(instr, expr->id());
11160 }
11161
11162
11163 static bool IsLiteralCompareBool(Isolate* isolate,
11164                                  HValue* left,
11165                                  Token::Value op,
11166                                  HValue* right) {
11167   return op == Token::EQ_STRICT &&
11168       ((left->IsConstant() &&
11169           HConstant::cast(left)->handle(isolate)->IsBoolean()) ||
11170        (right->IsConstant() &&
11171            HConstant::cast(right)->handle(isolate)->IsBoolean()));
11172 }
11173
11174
11175 void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) {
11176   DCHECK(!HasStackOverflow());
11177   DCHECK(current_block() != NULL);
11178   DCHECK(current_block()->HasPredecessor());
11179
11180   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11181
11182   // Check for a few fast cases. The AST visiting behavior must be in sync
11183   // with the full codegen: We don't push both left and right values onto
11184   // the expression stack when one side is a special-case literal.
11185   Expression* sub_expr = NULL;
11186   Handle<String> check;
11187   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
11188     return HandleLiteralCompareTypeof(expr, sub_expr, check);
11189   }
11190   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
11191     return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);
11192   }
11193   if (expr->IsLiteralCompareNull(&sub_expr)) {
11194     return HandleLiteralCompareNil(expr, sub_expr, kNullValue);
11195   }
11196
11197   if (IsClassOfTest(expr)) {
11198     CallRuntime* call = expr->left()->AsCallRuntime();
11199     DCHECK(call->arguments()->length() == 1);
11200     CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11201     HValue* value = Pop();
11202     Literal* literal = expr->right()->AsLiteral();
11203     Handle<String> rhs = Handle<String>::cast(literal->value());
11204     HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs);
11205     return ast_context()->ReturnControl(instr, expr->id());
11206   }
11207
11208   Type* left_type = expr->left()->bounds().lower;
11209   Type* right_type = expr->right()->bounds().lower;
11210   Type* combined_type = expr->combined_type();
11211
11212   CHECK_ALIVE(VisitForValue(expr->left()));
11213   CHECK_ALIVE(VisitForValue(expr->right()));
11214
11215   HValue* right = Pop();
11216   HValue* left = Pop();
11217   Token::Value op = expr->op();
11218
11219   if (IsLiteralCompareBool(isolate(), left, op, right)) {
11220     HCompareObjectEqAndBranch* result =
11221         New<HCompareObjectEqAndBranch>(left, right);
11222     return ast_context()->ReturnControl(result, expr->id());
11223   }
11224
11225   if (op == Token::INSTANCEOF) {
11226     // Check to see if the rhs of the instanceof is a known function.
11227     if (right->IsConstant() &&
11228         HConstant::cast(right)->handle(isolate())->IsJSFunction()) {
11229       Handle<Object> function = HConstant::cast(right)->handle(isolate());
11230       Handle<JSFunction> target = Handle<JSFunction>::cast(function);
11231       HInstanceOfKnownGlobal* result =
11232           New<HInstanceOfKnownGlobal>(left, target);
11233       return ast_context()->ReturnInstruction(result, expr->id());
11234     }
11235
11236     HInstanceOf* result = New<HInstanceOf>(left, right);
11237     return ast_context()->ReturnInstruction(result, expr->id());
11238
11239   } else if (op == Token::IN) {
11240     HValue* function = AddLoadJSBuiltin(Builtins::IN);
11241     Add<HPushArguments>(left, right);
11242     // TODO(olivf) InvokeFunction produces a check for the parameter count,
11243     // even though we are certain to pass the correct number of arguments here.
11244     HInstruction* result = New<HInvokeFunction>(function, 2);
11245     return ast_context()->ReturnInstruction(result, expr->id());
11246   }
11247
11248   PushBeforeSimulateBehavior push_behavior =
11249     ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE
11250                               : PUSH_BEFORE_SIMULATE;
11251   HControlInstruction* compare = BuildCompareInstruction(
11252       op, left, right, left_type, right_type, combined_type,
11253       ScriptPositionToSourcePosition(expr->left()->position()),
11254       ScriptPositionToSourcePosition(expr->right()->position()),
11255       push_behavior, expr->id());
11256   if (compare == NULL) return;  // Bailed out.
11257   return ast_context()->ReturnControl(compare, expr->id());
11258 }
11259
11260
11261 HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction(
11262     Token::Value op, HValue* left, HValue* right, Type* left_type,
11263     Type* right_type, Type* combined_type, SourcePosition left_position,
11264     SourcePosition right_position, PushBeforeSimulateBehavior push_sim_result,
11265     BailoutId bailout_id) {
11266   // Cases handled below depend on collected type feedback. They should
11267   // soft deoptimize when there is no type feedback.
11268   if (!combined_type->IsInhabited()) {
11269     Add<HDeoptimize>(
11270         Deoptimizer::kInsufficientTypeFeedbackForCombinedTypeOfBinaryOperation,
11271         Deoptimizer::SOFT);
11272     combined_type = left_type = right_type = Type::Any(zone());
11273   }
11274
11275   Representation left_rep = RepresentationFor(left_type);
11276   Representation right_rep = RepresentationFor(right_type);
11277   Representation combined_rep = RepresentationFor(combined_type);
11278
11279   if (combined_type->Is(Type::Receiver())) {
11280     if (Token::IsEqualityOp(op)) {
11281       // HCompareObjectEqAndBranch can only deal with object, so
11282       // exclude numbers.
11283       if ((left->IsConstant() &&
11284            HConstant::cast(left)->HasNumberValue()) ||
11285           (right->IsConstant() &&
11286            HConstant::cast(right)->HasNumberValue())) {
11287         Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11288                          Deoptimizer::SOFT);
11289         // The caller expects a branch instruction, so make it happy.
11290         return New<HBranch>(graph()->GetConstantTrue());
11291       }
11292       // Can we get away with map check and not instance type check?
11293       HValue* operand_to_check =
11294           left->block()->block_id() < right->block()->block_id() ? left : right;
11295       if (combined_type->IsClass()) {
11296         Handle<Map> map = combined_type->AsClass()->Map();
11297         AddCheckMap(operand_to_check, map);
11298         HCompareObjectEqAndBranch* result =
11299             New<HCompareObjectEqAndBranch>(left, right);
11300         if (top_info()->is_tracking_positions()) {
11301           result->set_operand_position(zone(), 0, left_position);
11302           result->set_operand_position(zone(), 1, right_position);
11303         }
11304         return result;
11305       } else {
11306         BuildCheckHeapObject(operand_to_check);
11307         Add<HCheckInstanceType>(operand_to_check,
11308                                 HCheckInstanceType::IS_SPEC_OBJECT);
11309         HCompareObjectEqAndBranch* result =
11310             New<HCompareObjectEqAndBranch>(left, right);
11311         return result;
11312       }
11313     } else {
11314       Bailout(kUnsupportedNonPrimitiveCompare);
11315       return NULL;
11316     }
11317   } else if (combined_type->Is(Type::InternalizedString()) &&
11318              Token::IsEqualityOp(op)) {
11319     // If we have a constant argument, it should be consistent with the type
11320     // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch).
11321     if ((left->IsConstant() &&
11322          !HConstant::cast(left)->HasInternalizedStringValue()) ||
11323         (right->IsConstant() &&
11324          !HConstant::cast(right)->HasInternalizedStringValue())) {
11325       Add<HDeoptimize>(Deoptimizer::kTypeMismatchBetweenFeedbackAndConstant,
11326                        Deoptimizer::SOFT);
11327       // The caller expects a branch instruction, so make it happy.
11328       return New<HBranch>(graph()->GetConstantTrue());
11329     }
11330     BuildCheckHeapObject(left);
11331     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING);
11332     BuildCheckHeapObject(right);
11333     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING);
11334     HCompareObjectEqAndBranch* result =
11335         New<HCompareObjectEqAndBranch>(left, right);
11336     return result;
11337   } else if (combined_type->Is(Type::String())) {
11338     BuildCheckHeapObject(left);
11339     Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING);
11340     BuildCheckHeapObject(right);
11341     Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING);
11342     HStringCompareAndBranch* result =
11343         New<HStringCompareAndBranch>(left, right, op);
11344     return result;
11345   } else {
11346     if (combined_rep.IsTagged() || combined_rep.IsNone()) {
11347       HCompareGeneric* result = Add<HCompareGeneric>(
11348           left, right, op, strength(function_language_mode()));
11349       result->set_observed_input_representation(1, left_rep);
11350       result->set_observed_input_representation(2, right_rep);
11351       if (result->HasObservableSideEffects()) {
11352         if (push_sim_result == PUSH_BEFORE_SIMULATE) {
11353           Push(result);
11354           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11355           Drop(1);
11356         } else {
11357           AddSimulate(bailout_id, REMOVABLE_SIMULATE);
11358         }
11359       }
11360       // TODO(jkummerow): Can we make this more efficient?
11361       HBranch* branch = New<HBranch>(result);
11362       return branch;
11363     } else {
11364       HCompareNumericAndBranch* result = New<HCompareNumericAndBranch>(
11365           left, right, op, strength(function_language_mode()));
11366       result->set_observed_input_representation(left_rep, right_rep);
11367       if (top_info()->is_tracking_positions()) {
11368         result->SetOperandPositions(zone(), left_position, right_position);
11369       }
11370       return result;
11371     }
11372   }
11373 }
11374
11375
11376 void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr,
11377                                                      Expression* sub_expr,
11378                                                      NilValue nil) {
11379   DCHECK(!HasStackOverflow());
11380   DCHECK(current_block() != NULL);
11381   DCHECK(current_block()->HasPredecessor());
11382   DCHECK(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT);
11383   if (!top_info()->is_tracking_positions()) SetSourcePosition(expr->position());
11384   CHECK_ALIVE(VisitForValue(sub_expr));
11385   HValue* value = Pop();
11386   if (expr->op() == Token::EQ_STRICT) {
11387     HConstant* nil_constant = nil == kNullValue
11388         ? graph()->GetConstantNull()
11389         : graph()->GetConstantUndefined();
11390     HCompareObjectEqAndBranch* instr =
11391         New<HCompareObjectEqAndBranch>(value, nil_constant);
11392     return ast_context()->ReturnControl(instr, expr->id());
11393   } else {
11394     DCHECK_EQ(Token::EQ, expr->op());
11395     Type* type = expr->combined_type()->Is(Type::None())
11396         ? Type::Any(zone()) : expr->combined_type();
11397     HIfContinuation continuation;
11398     BuildCompareNil(value, type, &continuation);
11399     return ast_context()->ReturnContinuation(&continuation, expr->id());
11400   }
11401 }
11402
11403
11404 void HOptimizedGraphBuilder::VisitSpread(Spread* expr) { UNREACHABLE(); }
11405
11406
11407 HInstruction* HOptimizedGraphBuilder::BuildThisFunction() {
11408   // If we share optimized code between different closures, the
11409   // this-function is not a constant, except inside an inlined body.
11410   if (function_state()->outer() != NULL) {
11411       return New<HConstant>(
11412           function_state()->compilation_info()->closure());
11413   } else {
11414       return New<HThisFunction>();
11415   }
11416 }
11417
11418
11419 HInstruction* HOptimizedGraphBuilder::BuildFastLiteral(
11420     Handle<JSObject> boilerplate_object,
11421     AllocationSiteUsageContext* site_context) {
11422   NoObservableSideEffectsScope no_effects(this);
11423   Handle<Map> initial_map(boilerplate_object->map());
11424   InstanceType instance_type = initial_map->instance_type();
11425   DCHECK(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE);
11426
11427   HType type = instance_type == JS_ARRAY_TYPE
11428       ? HType::JSArray() : HType::JSObject();
11429   HValue* object_size_constant = Add<HConstant>(initial_map->instance_size());
11430
11431   PretenureFlag pretenure_flag = NOT_TENURED;
11432   Handle<AllocationSite> current_site(*site_context->current(), isolate());
11433   if (FLAG_allocation_site_pretenuring) {
11434     pretenure_flag = current_site->GetPretenureMode();
11435     top_info()->dependencies()->AssumeTenuringDecision(current_site);
11436   }
11437
11438   top_info()->dependencies()->AssumeTransitionStable(current_site);
11439
11440   HInstruction* object = Add<HAllocate>(
11441       object_size_constant, type, pretenure_flag, instance_type, current_site);
11442
11443   // If allocation folding reaches Page::kMaxRegularHeapObjectSize the
11444   // elements array may not get folded into the object. Hence, we set the
11445   // elements pointer to empty fixed array and let store elimination remove
11446   // this store in the folding case.
11447   HConstant* empty_fixed_array = Add<HConstant>(
11448       isolate()->factory()->empty_fixed_array());
11449   Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11450       empty_fixed_array);
11451
11452   BuildEmitObjectHeader(boilerplate_object, object);
11453
11454   // Similarly to the elements pointer, there is no guarantee that all
11455   // property allocations can get folded, so pre-initialize all in-object
11456   // properties to a safe value.
11457   BuildInitializeInobjectProperties(object, initial_map);
11458
11459   Handle<FixedArrayBase> elements(boilerplate_object->elements());
11460   int elements_size = (elements->length() > 0 &&
11461       elements->map() != isolate()->heap()->fixed_cow_array_map()) ?
11462           elements->Size() : 0;
11463
11464   if (pretenure_flag == TENURED &&
11465       elements->map() == isolate()->heap()->fixed_cow_array_map() &&
11466       isolate()->heap()->InNewSpace(*elements)) {
11467     // If we would like to pretenure a fixed cow array, we must ensure that the
11468     // array is already in old space, otherwise we'll create too many old-to-
11469     // new-space pointers (overflowing the store buffer).
11470     elements = Handle<FixedArrayBase>(
11471         isolate()->factory()->CopyAndTenureFixedCOWArray(
11472             Handle<FixedArray>::cast(elements)));
11473     boilerplate_object->set_elements(*elements);
11474   }
11475
11476   HInstruction* object_elements = NULL;
11477   if (elements_size > 0) {
11478     HValue* object_elements_size = Add<HConstant>(elements_size);
11479     InstanceType instance_type = boilerplate_object->HasFastDoubleElements()
11480         ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE;
11481     object_elements =
11482         Add<HAllocate>(object_elements_size, HType::HeapObject(),
11483                        pretenure_flag, instance_type, current_site);
11484     BuildEmitElements(boilerplate_object, elements, object_elements,
11485                       site_context);
11486     Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11487                           object_elements);
11488   } else {
11489     Handle<Object> elements_field =
11490         Handle<Object>(boilerplate_object->elements(), isolate());
11491     HInstruction* object_elements_cow = Add<HConstant>(elements_field);
11492     Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(),
11493                           object_elements_cow);
11494   }
11495
11496   // Copy in-object properties.
11497   if (initial_map->NumberOfFields() != 0 ||
11498       initial_map->unused_property_fields() > 0) {
11499     BuildEmitInObjectProperties(boilerplate_object, object, site_context,
11500                                 pretenure_flag);
11501   }
11502   return object;
11503 }
11504
11505
11506 void HOptimizedGraphBuilder::BuildEmitObjectHeader(
11507     Handle<JSObject> boilerplate_object,
11508     HInstruction* object) {
11509   DCHECK(boilerplate_object->properties()->length() == 0);
11510
11511   Handle<Map> boilerplate_object_map(boilerplate_object->map());
11512   AddStoreMapConstant(object, boilerplate_object_map);
11513
11514   Handle<Object> properties_field =
11515       Handle<Object>(boilerplate_object->properties(), isolate());
11516   DCHECK(*properties_field == isolate()->heap()->empty_fixed_array());
11517   HInstruction* properties = Add<HConstant>(properties_field);
11518   HObjectAccess access = HObjectAccess::ForPropertiesPointer();
11519   Add<HStoreNamedField>(object, access, properties);
11520
11521   if (boilerplate_object->IsJSArray()) {
11522     Handle<JSArray> boilerplate_array =
11523         Handle<JSArray>::cast(boilerplate_object);
11524     Handle<Object> length_field =
11525         Handle<Object>(boilerplate_array->length(), isolate());
11526     HInstruction* length = Add<HConstant>(length_field);
11527
11528     DCHECK(boilerplate_array->length()->IsSmi());
11529     Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(
11530         boilerplate_array->GetElementsKind()), length);
11531   }
11532 }
11533
11534
11535 void HOptimizedGraphBuilder::BuildEmitInObjectProperties(
11536     Handle<JSObject> boilerplate_object,
11537     HInstruction* object,
11538     AllocationSiteUsageContext* site_context,
11539     PretenureFlag pretenure_flag) {
11540   Handle<Map> boilerplate_map(boilerplate_object->map());
11541   Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors());
11542   int limit = boilerplate_map->NumberOfOwnDescriptors();
11543
11544   int copied_fields = 0;
11545   for (int i = 0; i < limit; i++) {
11546     PropertyDetails details = descriptors->GetDetails(i);
11547     if (details.type() != DATA) continue;
11548     copied_fields++;
11549     FieldIndex field_index = FieldIndex::ForDescriptor(*boilerplate_map, i);
11550
11551
11552     int property_offset = field_index.offset();
11553     Handle<Name> name(descriptors->GetKey(i));
11554
11555     // The access for the store depends on the type of the boilerplate.
11556     HObjectAccess access = boilerplate_object->IsJSArray() ?
11557         HObjectAccess::ForJSArrayOffset(property_offset) :
11558         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11559
11560     if (boilerplate_object->IsUnboxedDoubleField(field_index)) {
11561       CHECK(!boilerplate_object->IsJSArray());
11562       double value = boilerplate_object->RawFastDoublePropertyAt(field_index);
11563       access = access.WithRepresentation(Representation::Double());
11564       Add<HStoreNamedField>(object, access, Add<HConstant>(value));
11565       continue;
11566     }
11567     Handle<Object> value(boilerplate_object->RawFastPropertyAt(field_index),
11568                          isolate());
11569
11570     if (value->IsJSObject()) {
11571       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11572       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11573       HInstruction* result =
11574           BuildFastLiteral(value_object, site_context);
11575       site_context->ExitScope(current_site, value_object);
11576       Add<HStoreNamedField>(object, access, result);
11577     } else {
11578       Representation representation = details.representation();
11579       HInstruction* value_instruction;
11580
11581       if (representation.IsDouble()) {
11582         // Allocate a HeapNumber box and store the value into it.
11583         HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize);
11584         // This heap number alloc does not have a corresponding
11585         // AllocationSite. That is okay because
11586         // 1) it's a child object of another object with a valid allocation site
11587         // 2) we can just use the mode of the parent object for pretenuring
11588         HInstruction* double_box =
11589             Add<HAllocate>(heap_number_constant, HType::HeapObject(),
11590                 pretenure_flag, MUTABLE_HEAP_NUMBER_TYPE);
11591         AddStoreMapConstant(double_box,
11592             isolate()->factory()->mutable_heap_number_map());
11593         // Unwrap the mutable heap number from the boilerplate.
11594         HValue* double_value =
11595             Add<HConstant>(Handle<HeapNumber>::cast(value)->value());
11596         Add<HStoreNamedField>(
11597             double_box, HObjectAccess::ForHeapNumberValue(), double_value);
11598         value_instruction = double_box;
11599       } else if (representation.IsSmi()) {
11600         value_instruction = value->IsUninitialized()
11601             ? graph()->GetConstant0()
11602             : Add<HConstant>(value);
11603         // Ensure that value is stored as smi.
11604         access = access.WithRepresentation(representation);
11605       } else {
11606         value_instruction = Add<HConstant>(value);
11607       }
11608
11609       Add<HStoreNamedField>(object, access, value_instruction);
11610     }
11611   }
11612
11613   int inobject_properties = boilerplate_object->map()->inobject_properties();
11614   HInstruction* value_instruction =
11615       Add<HConstant>(isolate()->factory()->one_pointer_filler_map());
11616   for (int i = copied_fields; i < inobject_properties; i++) {
11617     DCHECK(boilerplate_object->IsJSObject());
11618     int property_offset = boilerplate_object->GetInObjectPropertyOffset(i);
11619     HObjectAccess access =
11620         HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset);
11621     Add<HStoreNamedField>(object, access, value_instruction);
11622   }
11623 }
11624
11625
11626 void HOptimizedGraphBuilder::BuildEmitElements(
11627     Handle<JSObject> boilerplate_object,
11628     Handle<FixedArrayBase> elements,
11629     HValue* object_elements,
11630     AllocationSiteUsageContext* site_context) {
11631   ElementsKind kind = boilerplate_object->map()->elements_kind();
11632   int elements_length = elements->length();
11633   HValue* object_elements_length = Add<HConstant>(elements_length);
11634   BuildInitializeElementsHeader(object_elements, kind, object_elements_length);
11635
11636   // Copy elements backing store content.
11637   if (elements->IsFixedDoubleArray()) {
11638     BuildEmitFixedDoubleArray(elements, kind, object_elements);
11639   } else if (elements->IsFixedArray()) {
11640     BuildEmitFixedArray(elements, kind, object_elements,
11641                         site_context);
11642   } else {
11643     UNREACHABLE();
11644   }
11645 }
11646
11647
11648 void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray(
11649     Handle<FixedArrayBase> elements,
11650     ElementsKind kind,
11651     HValue* object_elements) {
11652   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11653   int elements_length = elements->length();
11654   for (int i = 0; i < elements_length; i++) {
11655     HValue* key_constant = Add<HConstant>(i);
11656     HInstruction* value_instruction = Add<HLoadKeyed>(
11657         boilerplate_elements, key_constant, nullptr, kind, ALLOW_RETURN_HOLE);
11658     HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant,
11659                                            value_instruction, kind);
11660     store->SetFlag(HValue::kAllowUndefinedAsNaN);
11661   }
11662 }
11663
11664
11665 void HOptimizedGraphBuilder::BuildEmitFixedArray(
11666     Handle<FixedArrayBase> elements,
11667     ElementsKind kind,
11668     HValue* object_elements,
11669     AllocationSiteUsageContext* site_context) {
11670   HInstruction* boilerplate_elements = Add<HConstant>(elements);
11671   int elements_length = elements->length();
11672   Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
11673   for (int i = 0; i < elements_length; i++) {
11674     Handle<Object> value(fast_elements->get(i), isolate());
11675     HValue* key_constant = Add<HConstant>(i);
11676     if (value->IsJSObject()) {
11677       Handle<JSObject> value_object = Handle<JSObject>::cast(value);
11678       Handle<AllocationSite> current_site = site_context->EnterNewScope();
11679       HInstruction* result =
11680           BuildFastLiteral(value_object, site_context);
11681       site_context->ExitScope(current_site, value_object);
11682       Add<HStoreKeyed>(object_elements, key_constant, result, kind);
11683     } else {
11684       ElementsKind copy_kind =
11685           kind == FAST_HOLEY_SMI_ELEMENTS ? FAST_HOLEY_ELEMENTS : kind;
11686       HInstruction* value_instruction =
11687           Add<HLoadKeyed>(boilerplate_elements, key_constant, nullptr,
11688                           copy_kind, ALLOW_RETURN_HOLE);
11689       Add<HStoreKeyed>(object_elements, key_constant, value_instruction,
11690                        copy_kind);
11691     }
11692   }
11693 }
11694
11695
11696 void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) {
11697   DCHECK(!HasStackOverflow());
11698   DCHECK(current_block() != NULL);
11699   DCHECK(current_block()->HasPredecessor());
11700   HInstruction* instr = BuildThisFunction();
11701   return ast_context()->ReturnInstruction(instr, expr->id());
11702 }
11703
11704
11705 void HOptimizedGraphBuilder::VisitSuperPropertyReference(
11706     SuperPropertyReference* expr) {
11707   DCHECK(!HasStackOverflow());
11708   DCHECK(current_block() != NULL);
11709   DCHECK(current_block()->HasPredecessor());
11710   return Bailout(kSuperReference);
11711 }
11712
11713
11714 void HOptimizedGraphBuilder::VisitSuperCallReference(SuperCallReference* expr) {
11715   DCHECK(!HasStackOverflow());
11716   DCHECK(current_block() != NULL);
11717   DCHECK(current_block()->HasPredecessor());
11718   return Bailout(kSuperReference);
11719 }
11720
11721
11722 void HOptimizedGraphBuilder::VisitDeclarations(
11723     ZoneList<Declaration*>* declarations) {
11724   DCHECK(globals_.is_empty());
11725   AstVisitor::VisitDeclarations(declarations);
11726   if (!globals_.is_empty()) {
11727     Handle<FixedArray> array =
11728        isolate()->factory()->NewFixedArray(globals_.length(), TENURED);
11729     for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i));
11730     int flags =
11731         DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) |
11732         DeclareGlobalsNativeFlag::encode(current_info()->is_native()) |
11733         DeclareGlobalsLanguageMode::encode(current_info()->language_mode());
11734     Add<HDeclareGlobals>(array, flags);
11735     globals_.Rewind(0);
11736   }
11737 }
11738
11739
11740 void HOptimizedGraphBuilder::VisitVariableDeclaration(
11741     VariableDeclaration* declaration) {
11742   VariableProxy* proxy = declaration->proxy();
11743   VariableMode mode = declaration->mode();
11744   Variable* variable = proxy->var();
11745   bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
11746   switch (variable->location()) {
11747     case VariableLocation::GLOBAL:
11748     case VariableLocation::UNALLOCATED:
11749       globals_.Add(variable->name(), zone());
11750       globals_.Add(variable->binding_needs_init()
11751                        ? isolate()->factory()->the_hole_value()
11752                        : isolate()->factory()->undefined_value(), zone());
11753       return;
11754     case VariableLocation::PARAMETER:
11755     case VariableLocation::LOCAL:
11756       if (hole_init) {
11757         HValue* value = graph()->GetConstantHole();
11758         environment()->Bind(variable, value);
11759       }
11760       break;
11761     case VariableLocation::CONTEXT:
11762       if (hole_init) {
11763         HValue* value = graph()->GetConstantHole();
11764         HValue* context = environment()->context();
11765         HStoreContextSlot* store = Add<HStoreContextSlot>(
11766             context, variable->index(), HStoreContextSlot::kNoCheck, value);
11767         if (store->HasObservableSideEffects()) {
11768           Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11769         }
11770       }
11771       break;
11772     case VariableLocation::LOOKUP:
11773       return Bailout(kUnsupportedLookupSlotInDeclaration);
11774   }
11775 }
11776
11777
11778 void HOptimizedGraphBuilder::VisitFunctionDeclaration(
11779     FunctionDeclaration* declaration) {
11780   VariableProxy* proxy = declaration->proxy();
11781   Variable* variable = proxy->var();
11782   switch (variable->location()) {
11783     case VariableLocation::GLOBAL:
11784     case VariableLocation::UNALLOCATED: {
11785       globals_.Add(variable->name(), zone());
11786       Handle<SharedFunctionInfo> function = Compiler::GetSharedFunctionInfo(
11787           declaration->fun(), current_info()->script(), top_info());
11788       // Check for stack-overflow exception.
11789       if (function.is_null()) return SetStackOverflow();
11790       globals_.Add(function, zone());
11791       return;
11792     }
11793     case VariableLocation::PARAMETER:
11794     case VariableLocation::LOCAL: {
11795       CHECK_ALIVE(VisitForValue(declaration->fun()));
11796       HValue* value = Pop();
11797       BindIfLive(variable, value);
11798       break;
11799     }
11800     case VariableLocation::CONTEXT: {
11801       CHECK_ALIVE(VisitForValue(declaration->fun()));
11802       HValue* value = Pop();
11803       HValue* context = environment()->context();
11804       HStoreContextSlot* store = Add<HStoreContextSlot>(
11805           context, variable->index(), HStoreContextSlot::kNoCheck, value);
11806       if (store->HasObservableSideEffects()) {
11807         Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE);
11808       }
11809       break;
11810     }
11811     case VariableLocation::LOOKUP:
11812       return Bailout(kUnsupportedLookupSlotInDeclaration);
11813   }
11814 }
11815
11816
11817 void HOptimizedGraphBuilder::VisitImportDeclaration(
11818     ImportDeclaration* declaration) {
11819   UNREACHABLE();
11820 }
11821
11822
11823 void HOptimizedGraphBuilder::VisitExportDeclaration(
11824     ExportDeclaration* declaration) {
11825   UNREACHABLE();
11826 }
11827
11828
11829 // Generators for inline runtime functions.
11830 // Support for types.
11831 void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) {
11832   DCHECK(call->arguments()->length() == 1);
11833   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11834   HValue* value = Pop();
11835   HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value);
11836   return ast_context()->ReturnControl(result, call->id());
11837 }
11838
11839
11840 void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) {
11841   DCHECK(call->arguments()->length() == 1);
11842   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11843   HValue* value = Pop();
11844   HHasInstanceTypeAndBranch* result =
11845       New<HHasInstanceTypeAndBranch>(value,
11846                                      FIRST_SPEC_OBJECT_TYPE,
11847                                      LAST_SPEC_OBJECT_TYPE);
11848   return ast_context()->ReturnControl(result, call->id());
11849 }
11850
11851
11852 void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) {
11853   DCHECK(call->arguments()->length() == 1);
11854   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11855   HValue* value = Pop();
11856   HHasInstanceTypeAndBranch* result =
11857       New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE);
11858   return ast_context()->ReturnControl(result, call->id());
11859 }
11860
11861
11862 void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) {
11863   DCHECK(call->arguments()->length() == 1);
11864   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11865   HValue* value = Pop();
11866   HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value);
11867   return ast_context()->ReturnControl(result, call->id());
11868 }
11869
11870
11871 void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) {
11872   DCHECK(call->arguments()->length() == 1);
11873   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11874   HValue* value = Pop();
11875   HHasCachedArrayIndexAndBranch* result =
11876       New<HHasCachedArrayIndexAndBranch>(value);
11877   return ast_context()->ReturnControl(result, call->id());
11878 }
11879
11880
11881 void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) {
11882   DCHECK(call->arguments()->length() == 1);
11883   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11884   HValue* value = Pop();
11885   HHasInstanceTypeAndBranch* result =
11886       New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE);
11887   return ast_context()->ReturnControl(result, call->id());
11888 }
11889
11890
11891 void HOptimizedGraphBuilder::GenerateIsTypedArray(CallRuntime* call) {
11892   DCHECK(call->arguments()->length() == 1);
11893   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11894   HValue* value = Pop();
11895   HHasInstanceTypeAndBranch* result =
11896       New<HHasInstanceTypeAndBranch>(value, JS_TYPED_ARRAY_TYPE);
11897   return ast_context()->ReturnControl(result, call->id());
11898 }
11899
11900
11901 void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) {
11902   DCHECK(call->arguments()->length() == 1);
11903   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11904   HValue* value = Pop();
11905   HHasInstanceTypeAndBranch* result =
11906       New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE);
11907   return ast_context()->ReturnControl(result, call->id());
11908 }
11909
11910
11911 void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) {
11912   DCHECK(call->arguments()->length() == 1);
11913   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11914   HValue* value = Pop();
11915   HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value);
11916   return ast_context()->ReturnControl(result, call->id());
11917 }
11918
11919
11920 void HOptimizedGraphBuilder::GenerateIsJSProxy(CallRuntime* call) {
11921   DCHECK(call->arguments()->length() == 1);
11922   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11923   HValue* value = Pop();
11924   HIfContinuation continuation;
11925   IfBuilder if_proxy(this);
11926
11927   HValue* smicheck = if_proxy.IfNot<HIsSmiAndBranch>(value);
11928   if_proxy.And();
11929   HValue* map = Add<HLoadNamedField>(value, smicheck, HObjectAccess::ForMap());
11930   HValue* instance_type =
11931       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapInstanceType());
11932   if_proxy.If<HCompareNumericAndBranch>(
11933       instance_type, Add<HConstant>(FIRST_JS_PROXY_TYPE), Token::GTE);
11934   if_proxy.And();
11935   if_proxy.If<HCompareNumericAndBranch>(
11936       instance_type, Add<HConstant>(LAST_JS_PROXY_TYPE), Token::LTE);
11937
11938   if_proxy.CaptureContinuation(&continuation);
11939   return ast_context()->ReturnContinuation(&continuation, call->id());
11940 }
11941
11942
11943 void HOptimizedGraphBuilder::GenerateHasFastPackedElements(CallRuntime* call) {
11944   DCHECK(call->arguments()->length() == 1);
11945   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11946   HValue* object = Pop();
11947   HIfContinuation continuation(graph()->CreateBasicBlock(),
11948                                graph()->CreateBasicBlock());
11949   IfBuilder if_not_smi(this);
11950   if_not_smi.IfNot<HIsSmiAndBranch>(object);
11951   if_not_smi.Then();
11952   {
11953     NoObservableSideEffectsScope no_effects(this);
11954
11955     IfBuilder if_fast_packed(this);
11956     HValue* elements_kind = BuildGetElementsKind(object);
11957     if_fast_packed.If<HCompareNumericAndBranch>(
11958         elements_kind, Add<HConstant>(FAST_SMI_ELEMENTS), Token::EQ);
11959     if_fast_packed.Or();
11960     if_fast_packed.If<HCompareNumericAndBranch>(
11961         elements_kind, Add<HConstant>(FAST_ELEMENTS), Token::EQ);
11962     if_fast_packed.Or();
11963     if_fast_packed.If<HCompareNumericAndBranch>(
11964         elements_kind, Add<HConstant>(FAST_DOUBLE_ELEMENTS), Token::EQ);
11965     if_fast_packed.JoinContinuation(&continuation);
11966   }
11967   if_not_smi.JoinContinuation(&continuation);
11968   return ast_context()->ReturnContinuation(&continuation, call->id());
11969 }
11970
11971
11972 void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) {
11973   DCHECK(call->arguments()->length() == 1);
11974   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
11975   HValue* value = Pop();
11976   HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value);
11977   return ast_context()->ReturnControl(result, call->id());
11978 }
11979
11980
11981 // Support for construct call checks.
11982 void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) {
11983   DCHECK(call->arguments()->length() == 0);
11984   if (function_state()->outer() != NULL) {
11985     // We are generating graph for inlined function.
11986     HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN
11987         ? graph()->GetConstantTrue()
11988         : graph()->GetConstantFalse();
11989     return ast_context()->ReturnValue(value);
11990   } else {
11991     return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(),
11992                                         call->id());
11993   }
11994 }
11995
11996
11997 // Support for arguments.length and arguments[?].
11998 void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) {
11999   DCHECK(call->arguments()->length() == 0);
12000   HInstruction* result = NULL;
12001   if (function_state()->outer() == NULL) {
12002     HInstruction* elements = Add<HArgumentsElements>(false);
12003     result = New<HArgumentsLength>(elements);
12004   } else {
12005     // Number of arguments without receiver.
12006     int argument_count = environment()->
12007         arguments_environment()->parameter_count() - 1;
12008     result = New<HConstant>(argument_count);
12009   }
12010   return ast_context()->ReturnInstruction(result, call->id());
12011 }
12012
12013
12014 void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) {
12015   DCHECK(call->arguments()->length() == 1);
12016   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12017   HValue* index = Pop();
12018   HInstruction* result = NULL;
12019   if (function_state()->outer() == NULL) {
12020     HInstruction* elements = Add<HArgumentsElements>(false);
12021     HInstruction* length = Add<HArgumentsLength>(elements);
12022     HInstruction* checked_index = Add<HBoundsCheck>(index, length);
12023     result = New<HAccessArgumentsAt>(elements, length, checked_index);
12024   } else {
12025     EnsureArgumentsArePushedForAccess();
12026
12027     // Number of arguments without receiver.
12028     HInstruction* elements = function_state()->arguments_elements();
12029     int argument_count = environment()->
12030         arguments_environment()->parameter_count() - 1;
12031     HInstruction* length = Add<HConstant>(argument_count);
12032     HInstruction* checked_key = Add<HBoundsCheck>(index, length);
12033     result = New<HAccessArgumentsAt>(elements, length, checked_key);
12034   }
12035   return ast_context()->ReturnInstruction(result, call->id());
12036 }
12037
12038
12039 void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) {
12040   DCHECK(call->arguments()->length() == 1);
12041   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12042   HValue* object = Pop();
12043
12044   IfBuilder if_objectisvalue(this);
12045   HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>(
12046       object, JS_VALUE_TYPE);
12047   if_objectisvalue.Then();
12048   {
12049     // Return the actual value.
12050     Push(Add<HLoadNamedField>(
12051             object, objectisvalue,
12052             HObjectAccess::ForObservableJSObjectOffset(
12053                 JSValue::kValueOffset)));
12054     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12055   }
12056   if_objectisvalue.Else();
12057   {
12058     // If the object is not a value return the object.
12059     Push(object);
12060     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12061   }
12062   if_objectisvalue.End();
12063   return ast_context()->ReturnValue(Pop());
12064 }
12065
12066
12067 void HOptimizedGraphBuilder::GenerateJSValueGetValue(CallRuntime* call) {
12068   DCHECK(call->arguments()->length() == 1);
12069   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12070   HValue* value = Pop();
12071   HInstruction* result = Add<HLoadNamedField>(
12072       value, nullptr,
12073       HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset));
12074   return ast_context()->ReturnInstruction(result, call->id());
12075 }
12076
12077
12078 void HOptimizedGraphBuilder::GenerateIsDate(CallRuntime* call) {
12079   DCHECK_EQ(1, call->arguments()->length());
12080   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12081   HValue* value = Pop();
12082   HHasInstanceTypeAndBranch* result =
12083       New<HHasInstanceTypeAndBranch>(value, JS_DATE_TYPE);
12084   return ast_context()->ReturnControl(result, call->id());
12085 }
12086
12087
12088 void HOptimizedGraphBuilder::GenerateThrowNotDateError(CallRuntime* call) {
12089   DCHECK_EQ(0, call->arguments()->length());
12090   Add<HDeoptimize>(Deoptimizer::kNotADateObject, Deoptimizer::EAGER);
12091   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12092   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12093 }
12094
12095
12096 void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) {
12097   DCHECK(call->arguments()->length() == 2);
12098   DCHECK_NOT_NULL(call->arguments()->at(1)->AsLiteral());
12099   Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value()));
12100   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12101   HValue* date = Pop();
12102   HDateField* result = New<HDateField>(date, index);
12103   return ast_context()->ReturnInstruction(result, call->id());
12104 }
12105
12106
12107 void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar(
12108     CallRuntime* call) {
12109   DCHECK(call->arguments()->length() == 3);
12110   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12111   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12112   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12113   HValue* string = Pop();
12114   HValue* value = Pop();
12115   HValue* index = Pop();
12116   Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string,
12117                          index, value);
12118   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12119   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12120 }
12121
12122
12123 void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar(
12124     CallRuntime* call) {
12125   DCHECK(call->arguments()->length() == 3);
12126   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12127   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12128   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12129   HValue* string = Pop();
12130   HValue* value = Pop();
12131   HValue* index = Pop();
12132   Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string,
12133                          index, value);
12134   Add<HSimulate>(call->id(), FIXED_SIMULATE);
12135   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12136 }
12137
12138
12139 void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) {
12140   DCHECK(call->arguments()->length() == 2);
12141   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12142   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12143   HValue* value = Pop();
12144   HValue* object = Pop();
12145
12146   // Check if object is a JSValue.
12147   IfBuilder if_objectisvalue(this);
12148   if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE);
12149   if_objectisvalue.Then();
12150   {
12151     // Create in-object property store to kValueOffset.
12152     Add<HStoreNamedField>(object,
12153         HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset),
12154         value);
12155     if (!ast_context()->IsEffect()) {
12156       Push(value);
12157     }
12158     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12159   }
12160   if_objectisvalue.Else();
12161   {
12162     // Nothing to do in this case.
12163     if (!ast_context()->IsEffect()) {
12164       Push(value);
12165     }
12166     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12167   }
12168   if_objectisvalue.End();
12169   if (!ast_context()->IsEffect()) {
12170     Drop(1);
12171   }
12172   return ast_context()->ReturnValue(value);
12173 }
12174
12175
12176 // Fast support for charCodeAt(n).
12177 void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) {
12178   DCHECK(call->arguments()->length() == 2);
12179   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12180   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12181   HValue* index = Pop();
12182   HValue* string = Pop();
12183   HInstruction* result = BuildStringCharCodeAt(string, index);
12184   return ast_context()->ReturnInstruction(result, call->id());
12185 }
12186
12187
12188 // Fast support for string.charAt(n) and string[n].
12189 void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) {
12190   DCHECK(call->arguments()->length() == 1);
12191   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12192   HValue* char_code = Pop();
12193   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12194   return ast_context()->ReturnInstruction(result, call->id());
12195 }
12196
12197
12198 // Fast support for string.charAt(n) and string[n].
12199 void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) {
12200   DCHECK(call->arguments()->length() == 2);
12201   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12202   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12203   HValue* index = Pop();
12204   HValue* string = Pop();
12205   HInstruction* char_code = BuildStringCharCodeAt(string, index);
12206   AddInstruction(char_code);
12207   HInstruction* result = NewUncasted<HStringCharFromCode>(char_code);
12208   return ast_context()->ReturnInstruction(result, call->id());
12209 }
12210
12211
12212 // Fast support for object equality testing.
12213 void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) {
12214   DCHECK(call->arguments()->length() == 2);
12215   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12216   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12217   HValue* right = Pop();
12218   HValue* left = Pop();
12219   HCompareObjectEqAndBranch* result =
12220       New<HCompareObjectEqAndBranch>(left, right);
12221   return ast_context()->ReturnControl(result, call->id());
12222 }
12223
12224
12225 // Fast support for StringAdd.
12226 void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) {
12227   DCHECK_EQ(2, call->arguments()->length());
12228   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12229   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12230   HValue* right = Pop();
12231   HValue* left = Pop();
12232   HInstruction* result =
12233       NewUncasted<HStringAdd>(left, right, strength(function_language_mode()));
12234   return ast_context()->ReturnInstruction(result, call->id());
12235 }
12236
12237
12238 // Fast support for SubString.
12239 void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) {
12240   DCHECK_EQ(3, call->arguments()->length());
12241   CHECK_ALIVE(VisitExpressions(call->arguments()));
12242   PushArgumentsFromEnvironment(call->arguments()->length());
12243   HCallStub* result = New<HCallStub>(CodeStub::SubString, 3);
12244   return ast_context()->ReturnInstruction(result, call->id());
12245 }
12246
12247
12248 // Fast support for StringCompare.
12249 void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) {
12250   DCHECK_EQ(2, call->arguments()->length());
12251   CHECK_ALIVE(VisitExpressions(call->arguments()));
12252   PushArgumentsFromEnvironment(call->arguments()->length());
12253   HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2);
12254   return ast_context()->ReturnInstruction(result, call->id());
12255 }
12256
12257
12258 void HOptimizedGraphBuilder::GenerateStringGetLength(CallRuntime* call) {
12259   DCHECK(call->arguments()->length() == 1);
12260   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12261   HValue* string = Pop();
12262   HInstruction* result = BuildLoadStringLength(string);
12263   return ast_context()->ReturnInstruction(result, call->id());
12264 }
12265
12266
12267 // Support for direct calls from JavaScript to native RegExp code.
12268 void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) {
12269   DCHECK_EQ(4, call->arguments()->length());
12270   CHECK_ALIVE(VisitExpressions(call->arguments()));
12271   PushArgumentsFromEnvironment(call->arguments()->length());
12272   HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4);
12273   return ast_context()->ReturnInstruction(result, call->id());
12274 }
12275
12276
12277 void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) {
12278   DCHECK_EQ(1, call->arguments()->length());
12279   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12280   HValue* value = Pop();
12281   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW);
12282   return ast_context()->ReturnInstruction(result, call->id());
12283 }
12284
12285
12286 void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) {
12287   DCHECK_EQ(1, call->arguments()->length());
12288   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12289   HValue* value = Pop();
12290   HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH);
12291   return ast_context()->ReturnInstruction(result, call->id());
12292 }
12293
12294
12295 void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) {
12296   DCHECK_EQ(2, call->arguments()->length());
12297   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12298   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12299   HValue* lo = Pop();
12300   HValue* hi = Pop();
12301   HInstruction* result = NewUncasted<HConstructDouble>(hi, lo);
12302   return ast_context()->ReturnInstruction(result, call->id());
12303 }
12304
12305
12306 // Construct a RegExp exec result with two in-object properties.
12307 void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) {
12308   DCHECK_EQ(3, call->arguments()->length());
12309   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12310   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12311   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12312   HValue* input = Pop();
12313   HValue* index = Pop();
12314   HValue* length = Pop();
12315   HValue* result = BuildRegExpConstructResult(length, index, input);
12316   return ast_context()->ReturnValue(result);
12317 }
12318
12319
12320 // Support for fast native caches.
12321 void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) {
12322   return Bailout(kInlinedRuntimeFunctionGetFromCache);
12323 }
12324
12325
12326 // Fast support for number to string.
12327 void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) {
12328   DCHECK_EQ(1, call->arguments()->length());
12329   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12330   HValue* number = Pop();
12331   HValue* result = BuildNumberToString(number, Type::Any(zone()));
12332   return ast_context()->ReturnValue(result);
12333 }
12334
12335
12336 // Fast call for custom callbacks.
12337 void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) {
12338   // 1 ~ The function to call is not itself an argument to the call.
12339   int arg_count = call->arguments()->length() - 1;
12340   DCHECK(arg_count >= 1);  // There's always at least a receiver.
12341
12342   CHECK_ALIVE(VisitExpressions(call->arguments()));
12343   // The function is the last argument
12344   HValue* function = Pop();
12345   // Push the arguments to the stack
12346   PushArgumentsFromEnvironment(arg_count);
12347
12348   IfBuilder if_is_jsfunction(this);
12349   if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE);
12350
12351   if_is_jsfunction.Then();
12352   {
12353     HInstruction* invoke_result =
12354         Add<HInvokeFunction>(function, arg_count);
12355     if (!ast_context()->IsEffect()) {
12356       Push(invoke_result);
12357     }
12358     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12359   }
12360
12361   if_is_jsfunction.Else();
12362   {
12363     HInstruction* call_result =
12364         Add<HCallFunction>(function, arg_count);
12365     if (!ast_context()->IsEffect()) {
12366       Push(call_result);
12367     }
12368     Add<HSimulate>(call->id(), FIXED_SIMULATE);
12369   }
12370   if_is_jsfunction.End();
12371
12372   if (ast_context()->IsEffect()) {
12373     // EffectContext::ReturnValue ignores the value, so we can just pass
12374     // 'undefined' (as we do not have the call result anymore).
12375     return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12376   } else {
12377     return ast_context()->ReturnValue(Pop());
12378   }
12379 }
12380
12381
12382 // Fast call to math functions.
12383 void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) {
12384   DCHECK_EQ(2, call->arguments()->length());
12385   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12386   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12387   HValue* right = Pop();
12388   HValue* left = Pop();
12389   HInstruction* result = NewUncasted<HPower>(left, right);
12390   return ast_context()->ReturnInstruction(result, call->id());
12391 }
12392
12393
12394 void HOptimizedGraphBuilder::GenerateMathClz32(CallRuntime* call) {
12395   DCHECK(call->arguments()->length() == 1);
12396   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12397   HValue* value = Pop();
12398   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathClz32);
12399   return ast_context()->ReturnInstruction(result, call->id());
12400 }
12401
12402
12403 void HOptimizedGraphBuilder::GenerateMathFloor(CallRuntime* call) {
12404   DCHECK(call->arguments()->length() == 1);
12405   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12406   HValue* value = Pop();
12407   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathFloor);
12408   return ast_context()->ReturnInstruction(result, call->id());
12409 }
12410
12411
12412 void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) {
12413   DCHECK(call->arguments()->length() == 1);
12414   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12415   HValue* value = Pop();
12416   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog);
12417   return ast_context()->ReturnInstruction(result, call->id());
12418 }
12419
12420
12421 void HOptimizedGraphBuilder::GenerateMathSqrt(CallRuntime* call) {
12422   DCHECK(call->arguments()->length() == 1);
12423   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12424   HValue* value = Pop();
12425   HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt);
12426   return ast_context()->ReturnInstruction(result, call->id());
12427 }
12428
12429
12430 void HOptimizedGraphBuilder::GenerateLikely(CallRuntime* call) {
12431   DCHECK(call->arguments()->length() == 1);
12432   Visit(call->arguments()->at(0));
12433 }
12434
12435
12436 void HOptimizedGraphBuilder::GenerateUnlikely(CallRuntime* call) {
12437   return GenerateLikely(call);
12438 }
12439
12440
12441 void HOptimizedGraphBuilder::GenerateFixedArrayGet(CallRuntime* call) {
12442   DCHECK(call->arguments()->length() == 2);
12443   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12444   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12445   HValue* index = Pop();
12446   HValue* object = Pop();
12447   HInstruction* result = New<HLoadKeyed>(
12448       object, index, nullptr, FAST_HOLEY_ELEMENTS, ALLOW_RETURN_HOLE);
12449   return ast_context()->ReturnInstruction(result, call->id());
12450 }
12451
12452
12453 void HOptimizedGraphBuilder::GenerateFixedArraySet(CallRuntime* call) {
12454   DCHECK(call->arguments()->length() == 3);
12455   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12456   CHECK_ALIVE(VisitForValue(call->arguments()->at(1)));
12457   CHECK_ALIVE(VisitForValue(call->arguments()->at(2)));
12458   HValue* value = Pop();
12459   HValue* index = Pop();
12460   HValue* object = Pop();
12461   NoObservableSideEffectsScope no_effects(this);
12462   Add<HStoreKeyed>(object, index, value, FAST_HOLEY_ELEMENTS);
12463   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12464 }
12465
12466
12467 void HOptimizedGraphBuilder::GenerateTheHole(CallRuntime* call) {
12468   DCHECK(call->arguments()->length() == 0);
12469   return ast_context()->ReturnValue(graph()->GetConstantHole());
12470 }
12471
12472
12473 void HOptimizedGraphBuilder::GenerateJSCollectionGetTable(CallRuntime* call) {
12474   DCHECK(call->arguments()->length() == 1);
12475   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12476   HValue* receiver = Pop();
12477   HInstruction* result = New<HLoadNamedField>(
12478       receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12479   return ast_context()->ReturnInstruction(result, call->id());
12480 }
12481
12482
12483 void HOptimizedGraphBuilder::GenerateStringGetRawHashField(CallRuntime* call) {
12484   DCHECK(call->arguments()->length() == 1);
12485   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12486   HValue* object = Pop();
12487   HInstruction* result = New<HLoadNamedField>(
12488       object, nullptr, HObjectAccess::ForStringHashField());
12489   return ast_context()->ReturnInstruction(result, call->id());
12490 }
12491
12492
12493 template <typename CollectionType>
12494 HValue* HOptimizedGraphBuilder::BuildAllocateOrderedHashTable() {
12495   static const int kCapacity = CollectionType::kMinCapacity;
12496   static const int kBucketCount = kCapacity / CollectionType::kLoadFactor;
12497   static const int kFixedArrayLength = CollectionType::kHashTableStartIndex +
12498                                        kBucketCount +
12499                                        (kCapacity * CollectionType::kEntrySize);
12500   static const int kSizeInBytes =
12501       FixedArray::kHeaderSize + (kFixedArrayLength * kPointerSize);
12502
12503   // Allocate the table and add the proper map.
12504   HValue* table =
12505       Add<HAllocate>(Add<HConstant>(kSizeInBytes), HType::HeapObject(),
12506                      NOT_TENURED, FIXED_ARRAY_TYPE);
12507   AddStoreMapConstant(table, isolate()->factory()->ordered_hash_table_map());
12508
12509   // Initialize the FixedArray...
12510   HValue* length = Add<HConstant>(kFixedArrayLength);
12511   Add<HStoreNamedField>(table, HObjectAccess::ForFixedArrayLength(), length);
12512
12513   // ...and the OrderedHashTable fields.
12514   Add<HStoreNamedField>(
12515       table,
12516       HObjectAccess::ForOrderedHashTableNumberOfBuckets<CollectionType>(),
12517       Add<HConstant>(kBucketCount));
12518   Add<HStoreNamedField>(
12519       table,
12520       HObjectAccess::ForOrderedHashTableNumberOfElements<CollectionType>(),
12521       graph()->GetConstant0());
12522   Add<HStoreNamedField>(
12523       table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12524                  CollectionType>(),
12525       graph()->GetConstant0());
12526
12527   // Fill the buckets with kNotFound.
12528   HValue* not_found = Add<HConstant>(CollectionType::kNotFound);
12529   for (int i = 0; i < kBucketCount; ++i) {
12530     Add<HStoreNamedField>(
12531         table, HObjectAccess::ForOrderedHashTableBucket<CollectionType>(i),
12532         not_found);
12533   }
12534
12535   // Fill the data table with undefined.
12536   HValue* undefined = graph()->GetConstantUndefined();
12537   for (int i = 0; i < (kCapacity * CollectionType::kEntrySize); ++i) {
12538     Add<HStoreNamedField>(table,
12539                           HObjectAccess::ForOrderedHashTableDataTableIndex<
12540                               CollectionType, kBucketCount>(i),
12541                           undefined);
12542   }
12543
12544   return table;
12545 }
12546
12547
12548 void HOptimizedGraphBuilder::GenerateSetInitialize(CallRuntime* call) {
12549   DCHECK(call->arguments()->length() == 1);
12550   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12551   HValue* receiver = Pop();
12552
12553   NoObservableSideEffectsScope no_effects(this);
12554   HValue* table = BuildAllocateOrderedHashTable<OrderedHashSet>();
12555   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12556   return ast_context()->ReturnValue(receiver);
12557 }
12558
12559
12560 void HOptimizedGraphBuilder::GenerateMapInitialize(CallRuntime* call) {
12561   DCHECK(call->arguments()->length() == 1);
12562   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12563   HValue* receiver = Pop();
12564
12565   NoObservableSideEffectsScope no_effects(this);
12566   HValue* table = BuildAllocateOrderedHashTable<OrderedHashMap>();
12567   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(), table);
12568   return ast_context()->ReturnValue(receiver);
12569 }
12570
12571
12572 template <typename CollectionType>
12573 void HOptimizedGraphBuilder::BuildOrderedHashTableClear(HValue* receiver) {
12574   HValue* old_table = Add<HLoadNamedField>(
12575       receiver, nullptr, HObjectAccess::ForJSCollectionTable());
12576   HValue* new_table = BuildAllocateOrderedHashTable<CollectionType>();
12577   Add<HStoreNamedField>(
12578       old_table, HObjectAccess::ForOrderedHashTableNextTable<CollectionType>(),
12579       new_table);
12580   Add<HStoreNamedField>(
12581       old_table, HObjectAccess::ForOrderedHashTableNumberOfDeletedElements<
12582                      CollectionType>(),
12583       Add<HConstant>(CollectionType::kClearedTableSentinel));
12584   Add<HStoreNamedField>(receiver, HObjectAccess::ForJSCollectionTable(),
12585                         new_table);
12586 }
12587
12588
12589 void HOptimizedGraphBuilder::GenerateSetClear(CallRuntime* call) {
12590   DCHECK(call->arguments()->length() == 1);
12591   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12592   HValue* receiver = Pop();
12593
12594   NoObservableSideEffectsScope no_effects(this);
12595   BuildOrderedHashTableClear<OrderedHashSet>(receiver);
12596   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12597 }
12598
12599
12600 void HOptimizedGraphBuilder::GenerateMapClear(CallRuntime* call) {
12601   DCHECK(call->arguments()->length() == 1);
12602   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12603   HValue* receiver = Pop();
12604
12605   NoObservableSideEffectsScope no_effects(this);
12606   BuildOrderedHashTableClear<OrderedHashMap>(receiver);
12607   return ast_context()->ReturnValue(graph()->GetConstantUndefined());
12608 }
12609
12610
12611 void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) {
12612   DCHECK(call->arguments()->length() == 1);
12613   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12614   HValue* value = Pop();
12615   HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value);
12616   return ast_context()->ReturnInstruction(result, call->id());
12617 }
12618
12619
12620 void HOptimizedGraphBuilder::GenerateFastOneByteArrayJoin(CallRuntime* call) {
12621   // Simply returning undefined here would be semantically correct and even
12622   // avoid the bailout. Nevertheless, some ancient benchmarks like SunSpider's
12623   // string-fasta would tank, because fullcode contains an optimized version.
12624   // Obviously the fullcode => Crankshaft => bailout => fullcode dance is
12625   // faster... *sigh*
12626   return Bailout(kInlinedRuntimeFunctionFastOneByteArrayJoin);
12627 }
12628
12629
12630 void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode(
12631     CallRuntime* call) {
12632   Add<HDebugBreak>();
12633   return ast_context()->ReturnValue(graph()->GetConstant0());
12634 }
12635
12636
12637 void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) {
12638   DCHECK(call->arguments()->length() == 0);
12639   HValue* ref =
12640       Add<HConstant>(ExternalReference::debug_is_active_address(isolate()));
12641   HValue* value =
12642       Add<HLoadNamedField>(ref, nullptr, HObjectAccess::ForExternalUInteger8());
12643   return ast_context()->ReturnValue(value);
12644 }
12645
12646
12647 void HOptimizedGraphBuilder::GenerateGetPrototype(CallRuntime* call) {
12648   DCHECK(call->arguments()->length() == 1);
12649   CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));
12650   HValue* object = Pop();
12651
12652   NoObservableSideEffectsScope no_effects(this);
12653
12654   HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap());
12655   HValue* bit_field =
12656       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField());
12657   HValue* is_access_check_needed_mask =
12658       Add<HConstant>(1 << Map::kIsAccessCheckNeeded);
12659   HValue* is_access_check_needed_test = AddUncasted<HBitwise>(
12660       Token::BIT_AND, bit_field, is_access_check_needed_mask);
12661
12662   HValue* proto =
12663       Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForPrototype());
12664   HValue* proto_map =
12665       Add<HLoadNamedField>(proto, nullptr, HObjectAccess::ForMap());
12666   HValue* proto_bit_field =
12667       Add<HLoadNamedField>(proto_map, nullptr, HObjectAccess::ForMapBitField());
12668   HValue* is_hidden_prototype_mask =
12669       Add<HConstant>(1 << Map::kIsHiddenPrototype);
12670   HValue* is_hidden_prototype_test = AddUncasted<HBitwise>(
12671       Token::BIT_AND, proto_bit_field, is_hidden_prototype_mask);
12672
12673   {
12674     IfBuilder needs_runtime(this);
12675     needs_runtime.If<HCompareNumericAndBranch>(
12676         is_access_check_needed_test, graph()->GetConstant0(), Token::NE);
12677     needs_runtime.OrIf<HCompareNumericAndBranch>(
12678         is_hidden_prototype_test, graph()->GetConstant0(), Token::NE);
12679
12680     needs_runtime.Then();
12681     {
12682       Add<HPushArguments>(object);
12683       Push(Add<HCallRuntime>(
12684           call->name(), Runtime::FunctionForId(Runtime::kGetPrototype), 1));
12685     }
12686
12687     needs_runtime.Else();
12688     Push(proto);
12689   }
12690   return ast_context()->ReturnValue(Pop());
12691 }
12692
12693
12694 #undef CHECK_BAILOUT
12695 #undef CHECK_ALIVE
12696
12697
12698 HEnvironment::HEnvironment(HEnvironment* outer,
12699                            Scope* scope,
12700                            Handle<JSFunction> closure,
12701                            Zone* zone)
12702     : closure_(closure),
12703       values_(0, zone),
12704       frame_type_(JS_FUNCTION),
12705       parameter_count_(0),
12706       specials_count_(1),
12707       local_count_(0),
12708       outer_(outer),
12709       entry_(NULL),
12710       pop_count_(0),
12711       push_count_(0),
12712       ast_id_(BailoutId::None()),
12713       zone_(zone) {
12714   Scope* declaration_scope = scope->DeclarationScope();
12715   Initialize(declaration_scope->num_parameters() + 1,
12716              declaration_scope->num_stack_slots(), 0);
12717 }
12718
12719
12720 HEnvironment::HEnvironment(Zone* zone, int parameter_count)
12721     : values_(0, zone),
12722       frame_type_(STUB),
12723       parameter_count_(parameter_count),
12724       specials_count_(1),
12725       local_count_(0),
12726       outer_(NULL),
12727       entry_(NULL),
12728       pop_count_(0),
12729       push_count_(0),
12730       ast_id_(BailoutId::None()),
12731       zone_(zone) {
12732   Initialize(parameter_count, 0, 0);
12733 }
12734
12735
12736 HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone)
12737     : values_(0, zone),
12738       frame_type_(JS_FUNCTION),
12739       parameter_count_(0),
12740       specials_count_(0),
12741       local_count_(0),
12742       outer_(NULL),
12743       entry_(NULL),
12744       pop_count_(0),
12745       push_count_(0),
12746       ast_id_(other->ast_id()),
12747       zone_(zone) {
12748   Initialize(other);
12749 }
12750
12751
12752 HEnvironment::HEnvironment(HEnvironment* outer,
12753                            Handle<JSFunction> closure,
12754                            FrameType frame_type,
12755                            int arguments,
12756                            Zone* zone)
12757     : closure_(closure),
12758       values_(arguments, zone),
12759       frame_type_(frame_type),
12760       parameter_count_(arguments),
12761       specials_count_(0),
12762       local_count_(0),
12763       outer_(outer),
12764       entry_(NULL),
12765       pop_count_(0),
12766       push_count_(0),
12767       ast_id_(BailoutId::None()),
12768       zone_(zone) {
12769 }
12770
12771
12772 void HEnvironment::Initialize(int parameter_count,
12773                               int local_count,
12774                               int stack_height) {
12775   parameter_count_ = parameter_count;
12776   local_count_ = local_count;
12777
12778   // Avoid reallocating the temporaries' backing store on the first Push.
12779   int total = parameter_count + specials_count_ + local_count + stack_height;
12780   values_.Initialize(total + 4, zone());
12781   for (int i = 0; i < total; ++i) values_.Add(NULL, zone());
12782 }
12783
12784
12785 void HEnvironment::Initialize(const HEnvironment* other) {
12786   closure_ = other->closure();
12787   values_.AddAll(other->values_, zone());
12788   assigned_variables_.Union(other->assigned_variables_, zone());
12789   frame_type_ = other->frame_type_;
12790   parameter_count_ = other->parameter_count_;
12791   local_count_ = other->local_count_;
12792   if (other->outer_ != NULL) outer_ = other->outer_->Copy();  // Deep copy.
12793   entry_ = other->entry_;
12794   pop_count_ = other->pop_count_;
12795   push_count_ = other->push_count_;
12796   specials_count_ = other->specials_count_;
12797   ast_id_ = other->ast_id_;
12798 }
12799
12800
12801 void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) {
12802   DCHECK(!block->IsLoopHeader());
12803   DCHECK(values_.length() == other->values_.length());
12804
12805   int length = values_.length();
12806   for (int i = 0; i < length; ++i) {
12807     HValue* value = values_[i];
12808     if (value != NULL && value->IsPhi() && value->block() == block) {
12809       // There is already a phi for the i'th value.
12810       HPhi* phi = HPhi::cast(value);
12811       // Assert index is correct and that we haven't missed an incoming edge.
12812       DCHECK(phi->merged_index() == i || !phi->HasMergedIndex());
12813       DCHECK(phi->OperandCount() == block->predecessors()->length());
12814       phi->AddInput(other->values_[i]);
12815     } else if (values_[i] != other->values_[i]) {
12816       // There is a fresh value on the incoming edge, a phi is needed.
12817       DCHECK(values_[i] != NULL && other->values_[i] != NULL);
12818       HPhi* phi = block->AddNewPhi(i);
12819       HValue* old_value = values_[i];
12820       for (int j = 0; j < block->predecessors()->length(); j++) {
12821         phi->AddInput(old_value);
12822       }
12823       phi->AddInput(other->values_[i]);
12824       this->values_[i] = phi;
12825     }
12826   }
12827 }
12828
12829
12830 void HEnvironment::Bind(int index, HValue* value) {
12831   DCHECK(value != NULL);
12832   assigned_variables_.Add(index, zone());
12833   values_[index] = value;
12834 }
12835
12836
12837 bool HEnvironment::HasExpressionAt(int index) const {
12838   return index >= parameter_count_ + specials_count_ + local_count_;
12839 }
12840
12841
12842 bool HEnvironment::ExpressionStackIsEmpty() const {
12843   DCHECK(length() >= first_expression_index());
12844   return length() == first_expression_index();
12845 }
12846
12847
12848 void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) {
12849   int count = index_from_top + 1;
12850   int index = values_.length() - count;
12851   DCHECK(HasExpressionAt(index));
12852   // The push count must include at least the element in question or else
12853   // the new value will not be included in this environment's history.
12854   if (push_count_ < count) {
12855     // This is the same effect as popping then re-pushing 'count' elements.
12856     pop_count_ += (count - push_count_);
12857     push_count_ = count;
12858   }
12859   values_[index] = value;
12860 }
12861
12862
12863 HValue* HEnvironment::RemoveExpressionStackAt(int index_from_top) {
12864   int count = index_from_top + 1;
12865   int index = values_.length() - count;
12866   DCHECK(HasExpressionAt(index));
12867   // Simulate popping 'count' elements and then
12868   // pushing 'count - 1' elements back.
12869   pop_count_ += Max(count - push_count_, 0);
12870   push_count_ = Max(push_count_ - count, 0) + (count - 1);
12871   return values_.Remove(index);
12872 }
12873
12874
12875 void HEnvironment::Drop(int count) {
12876   for (int i = 0; i < count; ++i) {
12877     Pop();
12878   }
12879 }
12880
12881
12882 HEnvironment* HEnvironment::Copy() const {
12883   return new(zone()) HEnvironment(this, zone());
12884 }
12885
12886
12887 HEnvironment* HEnvironment::CopyWithoutHistory() const {
12888   HEnvironment* result = Copy();
12889   result->ClearHistory();
12890   return result;
12891 }
12892
12893
12894 HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const {
12895   HEnvironment* new_env = Copy();
12896   for (int i = 0; i < values_.length(); ++i) {
12897     HPhi* phi = loop_header->AddNewPhi(i);
12898     phi->AddInput(values_[i]);
12899     new_env->values_[i] = phi;
12900   }
12901   new_env->ClearHistory();
12902   return new_env;
12903 }
12904
12905
12906 HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer,
12907                                                   Handle<JSFunction> target,
12908                                                   FrameType frame_type,
12909                                                   int arguments) const {
12910   HEnvironment* new_env =
12911       new(zone()) HEnvironment(outer, target, frame_type,
12912                                arguments + 1, zone());
12913   for (int i = 0; i <= arguments; ++i) {  // Include receiver.
12914     new_env->Push(ExpressionStackAt(arguments - i));
12915   }
12916   new_env->ClearHistory();
12917   return new_env;
12918 }
12919
12920
12921 HEnvironment* HEnvironment::CopyForInlining(
12922     Handle<JSFunction> target,
12923     int arguments,
12924     FunctionLiteral* function,
12925     HConstant* undefined,
12926     InliningKind inlining_kind) const {
12927   DCHECK(frame_type() == JS_FUNCTION);
12928
12929   // Outer environment is a copy of this one without the arguments.
12930   int arity = function->scope()->num_parameters();
12931
12932   HEnvironment* outer = Copy();
12933   outer->Drop(arguments + 1);  // Including receiver.
12934   outer->ClearHistory();
12935
12936   if (inlining_kind == CONSTRUCT_CALL_RETURN) {
12937     // Create artificial constructor stub environment.  The receiver should
12938     // actually be the constructor function, but we pass the newly allocated
12939     // object instead, DoComputeConstructStubFrame() relies on that.
12940     outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments);
12941   } else if (inlining_kind == GETTER_CALL_RETURN) {
12942     // We need an additional StackFrame::INTERNAL frame for restoring the
12943     // correct context.
12944     outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments);
12945   } else if (inlining_kind == SETTER_CALL_RETURN) {
12946     // We need an additional StackFrame::INTERNAL frame for temporarily saving
12947     // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter.
12948     outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments);
12949   }
12950
12951   if (arity != arguments) {
12952     // Create artificial arguments adaptation environment.
12953     outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments);
12954   }
12955
12956   HEnvironment* inner =
12957       new(zone()) HEnvironment(outer, function->scope(), target, zone());
12958   // Get the argument values from the original environment.
12959   for (int i = 0; i <= arity; ++i) {  // Include receiver.
12960     HValue* push = (i <= arguments) ?
12961         ExpressionStackAt(arguments - i) : undefined;
12962     inner->SetValueAt(i, push);
12963   }
12964   inner->SetValueAt(arity + 1, context());
12965   for (int i = arity + 2; i < inner->length(); ++i) {
12966     inner->SetValueAt(i, undefined);
12967   }
12968
12969   inner->set_ast_id(BailoutId::FunctionEntry());
12970   return inner;
12971 }
12972
12973
12974 std::ostream& operator<<(std::ostream& os, const HEnvironment& env) {
12975   for (int i = 0; i < env.length(); i++) {
12976     if (i == 0) os << "parameters\n";
12977     if (i == env.parameter_count()) os << "specials\n";
12978     if (i == env.parameter_count() + env.specials_count()) os << "locals\n";
12979     if (i == env.parameter_count() + env.specials_count() + env.local_count()) {
12980       os << "expressions\n";
12981     }
12982     HValue* val = env.values()->at(i);
12983     os << i << ": ";
12984     if (val != NULL) {
12985       os << val;
12986     } else {
12987       os << "NULL";
12988     }
12989     os << "\n";
12990   }
12991   return os << "\n";
12992 }
12993
12994
12995 void HTracer::TraceCompilation(CompilationInfo* info) {
12996   Tag tag(this, "compilation");
12997   if (info->IsOptimizing()) {
12998     Handle<String> name = info->function()->debug_name();
12999     PrintStringProperty("name", name->ToCString().get());
13000     PrintIndent();
13001     trace_.Add("method \"%s:%d\"\n",
13002                name->ToCString().get(),
13003                info->optimization_id());
13004   } else {
13005     CodeStub::Major major_key = info->code_stub()->MajorKey();
13006     PrintStringProperty("name", CodeStub::MajorName(major_key, false));
13007     PrintStringProperty("method", "stub");
13008   }
13009   PrintLongProperty("date",
13010                     static_cast<int64_t>(base::OS::TimeCurrentMillis()));
13011 }
13012
13013
13014 void HTracer::TraceLithium(const char* name, LChunk* chunk) {
13015   DCHECK(!chunk->isolate()->concurrent_recompilation_enabled());
13016   AllowHandleDereference allow_deref;
13017   AllowDeferredHandleDereference allow_deferred_deref;
13018   Trace(name, chunk->graph(), chunk);
13019 }
13020
13021
13022 void HTracer::TraceHydrogen(const char* name, HGraph* graph) {
13023   DCHECK(!graph->isolate()->concurrent_recompilation_enabled());
13024   AllowHandleDereference allow_deref;
13025   AllowDeferredHandleDereference allow_deferred_deref;
13026   Trace(name, graph, NULL);
13027 }
13028
13029
13030 void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) {
13031   Tag tag(this, "cfg");
13032   PrintStringProperty("name", name);
13033   const ZoneList<HBasicBlock*>* blocks = graph->blocks();
13034   for (int i = 0; i < blocks->length(); i++) {
13035     HBasicBlock* current = blocks->at(i);
13036     Tag block_tag(this, "block");
13037     PrintBlockProperty("name", current->block_id());
13038     PrintIntProperty("from_bci", -1);
13039     PrintIntProperty("to_bci", -1);
13040
13041     if (!current->predecessors()->is_empty()) {
13042       PrintIndent();
13043       trace_.Add("predecessors");
13044       for (int j = 0; j < current->predecessors()->length(); ++j) {
13045         trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id());
13046       }
13047       trace_.Add("\n");
13048     } else {
13049       PrintEmptyProperty("predecessors");
13050     }
13051
13052     if (current->end()->SuccessorCount() == 0) {
13053       PrintEmptyProperty("successors");
13054     } else  {
13055       PrintIndent();
13056       trace_.Add("successors");
13057       for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) {
13058         trace_.Add(" \"B%d\"", it.Current()->block_id());
13059       }
13060       trace_.Add("\n");
13061     }
13062
13063     PrintEmptyProperty("xhandlers");
13064
13065     {
13066       PrintIndent();
13067       trace_.Add("flags");
13068       if (current->IsLoopSuccessorDominator()) {
13069         trace_.Add(" \"dom-loop-succ\"");
13070       }
13071       if (current->IsUnreachable()) {
13072         trace_.Add(" \"dead\"");
13073       }
13074       if (current->is_osr_entry()) {
13075         trace_.Add(" \"osr\"");
13076       }
13077       trace_.Add("\n");
13078     }
13079
13080     if (current->dominator() != NULL) {
13081       PrintBlockProperty("dominator", current->dominator()->block_id());
13082     }
13083
13084     PrintIntProperty("loop_depth", current->LoopNestingDepth());
13085
13086     if (chunk != NULL) {
13087       int first_index = current->first_instruction_index();
13088       int last_index = current->last_instruction_index();
13089       PrintIntProperty(
13090           "first_lir_id",
13091           LifetimePosition::FromInstructionIndex(first_index).Value());
13092       PrintIntProperty(
13093           "last_lir_id",
13094           LifetimePosition::FromInstructionIndex(last_index).Value());
13095     }
13096
13097     {
13098       Tag states_tag(this, "states");
13099       Tag locals_tag(this, "locals");
13100       int total = current->phis()->length();
13101       PrintIntProperty("size", current->phis()->length());
13102       PrintStringProperty("method", "None");
13103       for (int j = 0; j < total; ++j) {
13104         HPhi* phi = current->phis()->at(j);
13105         PrintIndent();
13106         std::ostringstream os;
13107         os << phi->merged_index() << " " << NameOf(phi) << " " << *phi << "\n";
13108         trace_.Add(os.str().c_str());
13109       }
13110     }
13111
13112     {
13113       Tag HIR_tag(this, "HIR");
13114       for (HInstructionIterator it(current); !it.Done(); it.Advance()) {
13115         HInstruction* instruction = it.Current();
13116         int uses = instruction->UseCount();
13117         PrintIndent();
13118         std::ostringstream os;
13119         os << "0 " << uses << " " << NameOf(instruction) << " " << *instruction;
13120         if (graph->info()->is_tracking_positions() &&
13121             instruction->has_position() && instruction->position().raw() != 0) {
13122           const SourcePosition pos = instruction->position();
13123           os << " pos:";
13124           if (pos.inlining_id() != 0) os << pos.inlining_id() << "_";
13125           os << pos.position();
13126         }
13127         os << " <|@\n";
13128         trace_.Add(os.str().c_str());
13129       }
13130     }
13131
13132
13133     if (chunk != NULL) {
13134       Tag LIR_tag(this, "LIR");
13135       int first_index = current->first_instruction_index();
13136       int last_index = current->last_instruction_index();
13137       if (first_index != -1 && last_index != -1) {
13138         const ZoneList<LInstruction*>* instructions = chunk->instructions();
13139         for (int i = first_index; i <= last_index; ++i) {
13140           LInstruction* linstr = instructions->at(i);
13141           if (linstr != NULL) {
13142             PrintIndent();
13143             trace_.Add("%d ",
13144                        LifetimePosition::FromInstructionIndex(i).Value());
13145             linstr->PrintTo(&trace_);
13146             std::ostringstream os;
13147             os << " [hir:" << NameOf(linstr->hydrogen_value()) << "] <|@\n";
13148             trace_.Add(os.str().c_str());
13149           }
13150         }
13151       }
13152     }
13153   }
13154 }
13155
13156
13157 void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) {
13158   Tag tag(this, "intervals");
13159   PrintStringProperty("name", name);
13160
13161   const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges();
13162   for (int i = 0; i < fixed_d->length(); ++i) {
13163     TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone());
13164   }
13165
13166   const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges();
13167   for (int i = 0; i < fixed->length(); ++i) {
13168     TraceLiveRange(fixed->at(i), "fixed", allocator->zone());
13169   }
13170
13171   const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges();
13172   for (int i = 0; i < live_ranges->length(); ++i) {
13173     TraceLiveRange(live_ranges->at(i), "object", allocator->zone());
13174   }
13175 }
13176
13177
13178 void HTracer::TraceLiveRange(LiveRange* range, const char* type,
13179                              Zone* zone) {
13180   if (range != NULL && !range->IsEmpty()) {
13181     PrintIndent();
13182     trace_.Add("%d %s", range->id(), type);
13183     if (range->HasRegisterAssigned()) {
13184       LOperand* op = range->CreateAssignedOperand(zone);
13185       int assigned_reg = op->index();
13186       if (op->IsDoubleRegister()) {
13187         trace_.Add(" \"%s\"",
13188                    DoubleRegister::AllocationIndexToString(assigned_reg));
13189       } else {
13190         DCHECK(op->IsRegister());
13191         trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg));
13192       }
13193     } else if (range->IsSpilled()) {
13194       LOperand* op = range->TopLevel()->GetSpillOperand();
13195       if (op->IsDoubleStackSlot()) {
13196         trace_.Add(" \"double_stack:%d\"", op->index());
13197       } else {
13198         DCHECK(op->IsStackSlot());
13199         trace_.Add(" \"stack:%d\"", op->index());
13200       }
13201     }
13202     int parent_index = -1;
13203     if (range->IsChild()) {
13204       parent_index = range->parent()->id();
13205     } else {
13206       parent_index = range->id();
13207     }
13208     LOperand* op = range->FirstHint();
13209     int hint_index = -1;
13210     if (op != NULL && op->IsUnallocated()) {
13211       hint_index = LUnallocated::cast(op)->virtual_register();
13212     }
13213     trace_.Add(" %d %d", parent_index, hint_index);
13214     UseInterval* cur_interval = range->first_interval();
13215     while (cur_interval != NULL && range->Covers(cur_interval->start())) {
13216       trace_.Add(" [%d, %d[",
13217                  cur_interval->start().Value(),
13218                  cur_interval->end().Value());
13219       cur_interval = cur_interval->next();
13220     }
13221
13222     UsePosition* current_pos = range->first_pos();
13223     while (current_pos != NULL) {
13224       if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
13225         trace_.Add(" %d M", current_pos->pos().Value());
13226       }
13227       current_pos = current_pos->next();
13228     }
13229
13230     trace_.Add(" \"\"\n");
13231   }
13232 }
13233
13234
13235 void HTracer::FlushToFile() {
13236   AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(),
13237               false);
13238   trace_.Reset();
13239 }
13240
13241
13242 void HStatistics::Initialize(CompilationInfo* info) {
13243   if (info->shared_info().is_null()) return;
13244   source_size_ += info->shared_info()->SourceSize();
13245 }
13246
13247
13248 void HStatistics::Print() {
13249   PrintF(
13250       "\n"
13251       "----------------------------------------"
13252       "----------------------------------------\n"
13253       "--- Hydrogen timing results:\n"
13254       "----------------------------------------"
13255       "----------------------------------------\n");
13256   base::TimeDelta sum;
13257   for (int i = 0; i < times_.length(); ++i) {
13258     sum += times_[i];
13259   }
13260
13261   for (int i = 0; i < names_.length(); ++i) {
13262     PrintF("%33s", names_[i]);
13263     double ms = times_[i].InMillisecondsF();
13264     double percent = times_[i].PercentOf(sum);
13265     PrintF(" %8.3f ms / %4.1f %% ", ms, percent);
13266
13267     size_t size = sizes_[i];
13268     double size_percent = static_cast<double>(size) * 100 / total_size_;
13269     PrintF(" %9zu bytes / %4.1f %%\n", size, size_percent);
13270   }
13271
13272   PrintF(
13273       "----------------------------------------"
13274       "----------------------------------------\n");
13275   base::TimeDelta total = create_graph_ + optimize_graph_ + generate_code_;
13276   PrintF("%33s %8.3f ms / %4.1f %% \n", "Create graph",
13277          create_graph_.InMillisecondsF(), create_graph_.PercentOf(total));
13278   PrintF("%33s %8.3f ms / %4.1f %% \n", "Optimize graph",
13279          optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total));
13280   PrintF("%33s %8.3f ms / %4.1f %% \n", "Generate and install code",
13281          generate_code_.InMillisecondsF(), generate_code_.PercentOf(total));
13282   PrintF(
13283       "----------------------------------------"
13284       "----------------------------------------\n");
13285   PrintF("%33s %8.3f ms           %9zu bytes\n", "Total",
13286          total.InMillisecondsF(), total_size_);
13287   PrintF("%33s     (%.1f times slower than full code gen)\n", "",
13288          total.TimesOf(full_code_gen_));
13289
13290   double source_size_in_kb = static_cast<double>(source_size_) / 1024;
13291   double normalized_time =  source_size_in_kb > 0
13292       ? total.InMillisecondsF() / source_size_in_kb
13293       : 0;
13294   double normalized_size_in_kb =
13295       source_size_in_kb > 0
13296           ? static_cast<double>(total_size_) / 1024 / source_size_in_kb
13297           : 0;
13298   PrintF("%33s %8.3f ms           %7.3f kB allocated\n",
13299          "Average per kB source", normalized_time, normalized_size_in_kb);
13300 }
13301
13302
13303 void HStatistics::SaveTiming(const char* name, base::TimeDelta time,
13304                              size_t size) {
13305   total_size_ += size;
13306   for (int i = 0; i < names_.length(); ++i) {
13307     if (strcmp(names_[i], name) == 0) {
13308       times_[i] += time;
13309       sizes_[i] += size;
13310       return;
13311     }
13312   }
13313   names_.Add(name);
13314   times_.Add(time);
13315   sizes_.Add(size);
13316 }
13317
13318
13319 HPhase::~HPhase() {
13320   if (ShouldProduceTraceOutput()) {
13321     isolate()->GetHTracer()->TraceHydrogen(name(), graph_);
13322   }
13323
13324 #ifdef DEBUG
13325   graph_->Verify(false);  // No full verify.
13326 #endif
13327 }
13328
13329 }  // namespace internal
13330 }  // namespace v8