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

#ifndef V8_HYDROGEN_H_
#define V8_HYDROGEN_H_

8 9 10 11 12
#include "src/v8.h"

#include "src/accessors.h"
#include "src/allocation.h"
#include "src/ast.h"
13
#include "src/bailout-reason.h"
14 15 16
#include "src/compiler.h"
#include "src/hydrogen-instructions.h"
#include "src/scopes.h"
17
#include "src/zone.h"
18 19 20 21 22

namespace v8 {
namespace internal {

// Forward declarations.
23
class BitVector;
24
class FunctionState;
25 26 27
class HEnvironment;
class HGraph;
class HLoopInformation;
28
class HOsrBuilder;
29 30
class HTracer;
class LAllocator;
31
class LChunk;
32 33 34
class LiveRange;


35
class HBasicBlock FINAL : public ZoneObject {
36 37
 public:
  explicit HBasicBlock(HGraph* graph);
38
  ~HBasicBlock() { }
39 40 41 42 43

  // Simple accessors.
  int block_id() const { return block_id_; }
  void set_block_id(int id) { block_id_ = id; }
  HGraph* graph() const { return graph_; }
44
  Isolate* isolate() const;
45 46
  const ZoneList<HPhi*>* phis() const { return &phis_; }
  HInstruction* first() const { return first_; }
47 48
  HInstruction* last() const { return last_; }
  void set_last(HInstruction* instr) { last_ = instr; }
49 50
  HControlInstruction* end() const { return end_; }
  HLoopInformation* loop_information() const { return loop_information_; }
51 52 53 54 55
  HLoopInformation* current_loop() const {
    return IsLoopHeader() ? loop_information()
                          : (parent_loop_header() != NULL
                            ? parent_loop_header()->loop_information() : NULL);
  }
56 57 58 59 60 61 62 63 64
  const ZoneList<HBasicBlock*>* predecessors() const { return &predecessors_; }
  bool HasPredecessor() const { return predecessors_.length() > 0; }
  const ZoneList<HBasicBlock*>* dominated_blocks() const {
    return &dominated_blocks_;
  }
  const ZoneList<int>* deleted_phis() const {
    return &deleted_phis_;
  }
  void RecordDeletedPhi(int merge_index) {
65
    deleted_phis_.Add(merge_index, zone());
66 67 68 69 70 71 72 73 74 75 76 77 78
  }
  HBasicBlock* dominator() const { return dominator_; }
  HEnvironment* last_environment() const { return last_environment_; }
  int argument_count() const { return argument_count_; }
  void set_argument_count(int count) { argument_count_ = count; }
  int first_instruction_index() const { return first_instruction_index_; }
  void set_first_instruction_index(int index) {
    first_instruction_index_ = index;
  }
  int last_instruction_index() const { return last_instruction_index_; }
  void set_last_instruction_index(int index) {
    last_instruction_index_ = index;
  }
79 80
  bool is_osr_entry() { return is_osr_entry_; }
  void set_osr_entry() { is_osr_entry_ = true; }
81 82 83 84 85 86 87 88 89 90

  void AttachLoopInformation();
  void DetachLoopInformation();
  bool IsLoopHeader() const { return loop_information() != NULL; }
  bool IsStartBlock() const { return block_id() == 0; }
  void PostProcessLoopHeader(IterationStatement* stmt);

  bool IsFinished() const { return end_ != NULL; }
  void AddPhi(HPhi* phi);
  void RemovePhi(HPhi* phi);
91
  void AddInstruction(HInstruction* instr, HSourcePosition position);
92
  bool Dominates(HBasicBlock* other) const;
93
  bool EqualToOrDominates(HBasicBlock* other) const;
94
  int LoopNestingDepth() const;
95

96
  void SetInitialEnvironment(HEnvironment* env);
97
  void ClearEnvironment() {
98 99
    DCHECK(IsFinished());
    DCHECK(end()->SuccessorCount() == 0);
100 101
    last_environment_ = NULL;
  }
102
  bool HasEnvironment() const { return last_environment_ != NULL; }
103
  void UpdateEnvironment(HEnvironment* env);
104
  HBasicBlock* parent_loop_header() const { return parent_loop_header_; }
105 106

  void set_parent_loop_header(HBasicBlock* block) {
107
    DCHECK(parent_loop_header_ == NULL);
108
    parent_loop_header_ = block;
109 110
  }

111
  bool HasParentLoopHeader() const { return parent_loop_header_ != NULL; }
112

113
  void SetJoinId(BailoutId ast_id);
114 115

  int PredecessorIndexOf(HBasicBlock* predecessor) const;
116 117
  HPhi* AddNewPhi(int merged_index);
  HSimulate* AddNewSimulate(BailoutId ast_id,
118
                            HSourcePosition position,
119
                            RemovableSimulate removable = FIXED_SIMULATE) {
120
    HSimulate* instr = CreateSimulate(ast_id, removable);
121
    AddInstruction(instr, position);
122
    return instr;
123
  }
124
  void AssignCommonDominator(HBasicBlock* other);
125
  void AssignLoopSuccessorDominators();
126 127 128 129 130 131 132 133

  // If a target block is tagged as an inline function return, all
  // predecessors should contain the inlined exit sequence:
  //
  // LeaveInlined
  // Simulate (caller's environment)
  // Goto (target block)
  bool IsInlineReturnTarget() const { return is_inline_return_target_; }
134 135 136 137 138
  void MarkAsInlineReturnTarget(HBasicBlock* inlined_entry_block) {
    is_inline_return_target_ = true;
    inlined_entry_block_ = inlined_entry_block;
  }
  HBasicBlock* inlined_entry_block() { return inlined_entry_block_; }
139

140 141 142 143 144 145 146
  bool IsDeoptimizing() const {
    return end() != NULL && end()->IsDeoptimize();
  }

  void MarkUnreachable();
  bool IsUnreachable() const { return !is_reachable_; }
  bool IsReachable() const { return is_reachable_; }
147

148 149 150 151 152 153 154
  bool IsLoopSuccessorDominator() const {
    return dominates_loop_successors_;
  }
  void MarkAsLoopSuccessorDominator() {
    dominates_loop_successors_ = true;
  }

155 156 157
  bool IsOrdered() const { return is_ordered_; }
  void MarkAsOrdered() { is_ordered_ = true; }

158 159
  void MarkSuccEdgeUnreachable(int succ);

160
  inline Zone* zone() const;
161

162 163 164 165
#ifdef DEBUG
  void Verify();
#endif

166
 protected:
167 168
  friend class HGraphBuilder;

169
  HSimulate* CreateSimulate(BailoutId ast_id, RemovableSimulate removable);
170 171
  void Finish(HControlInstruction* last, HSourcePosition position);
  void FinishExit(HControlInstruction* instruction, HSourcePosition position);
172
  void Goto(HBasicBlock* block,
173
            HSourcePosition position,
174 175
            FunctionState* state = NULL,
            bool add_simulate = true);
176
  void GotoNoSimulate(HBasicBlock* block, HSourcePosition position) {
177 178 179 180 181 182 183
    Goto(block, position, NULL, false);
  }

  // Add the inlined function exit sequence, adding an HLeaveInlined
  // instruction and updating the bailout environment.
  void AddLeaveInlined(HValue* return_value,
                       FunctionState* state,
184
                       HSourcePosition position);
185 186

 private:
187 188 189 190 191 192 193
  void RegisterPredecessor(HBasicBlock* pred);
  void AddDominatedBlock(HBasicBlock* block);

  int block_id_;
  HGraph* graph_;
  ZoneList<HPhi*> phis_;
  HInstruction* first_;
194
  HInstruction* last_;
195 196 197 198 199 200 201 202 203 204 205 206
  HControlInstruction* end_;
  HLoopInformation* loop_information_;
  ZoneList<HBasicBlock*> predecessors_;
  HBasicBlock* dominator_;
  ZoneList<HBasicBlock*> dominated_blocks_;
  HEnvironment* last_environment_;
  // Outgoing parameter count at block exit, set during lithium translation.
  int argument_count_;
  // Instruction indices into the lithium code stream.
  int first_instruction_index_;
  int last_instruction_index_;
  ZoneList<int> deleted_phis_;
207
  HBasicBlock* parent_loop_header_;
208 209 210
  // For blocks marked as inline return target: the block with HEnterInlined.
  HBasicBlock* inlined_entry_block_;
  bool is_inline_return_target_ : 1;
211
  bool is_reachable_ : 1;
212 213
  bool dominates_loop_successors_ : 1;
  bool is_osr_entry_ : 1;
214
  bool is_ordered_ : 1;
215 216 217
};


218
std::ostream& operator<<(std::ostream& os, const HBasicBlock& b);
219 220


221
class HPredecessorIterator FINAL BASE_EMBEDDED {
222 223 224 225 226 227 228 229 230 231 232
 public:
  explicit HPredecessorIterator(HBasicBlock* block)
      : predecessor_list_(block->predecessors()), current_(0) { }

  bool Done() { return current_ >= predecessor_list_->length(); }
  HBasicBlock* Current() { return predecessor_list_->at(current_); }
  void Advance() { current_++; }

 private:
  const ZoneList<HBasicBlock*>* predecessor_list_;
  int current_;
233 234 235
};


236
class HInstructionIterator FINAL BASE_EMBEDDED {
237
 public:
238 239 240 241
  explicit HInstructionIterator(HBasicBlock* block)
      : instr_(block->first()) {
    next_ = Done() ? NULL : instr_->next();
  }
242

243 244 245 246 247 248
  inline bool Done() const { return instr_ == NULL; }
  inline HInstruction* Current() { return instr_; }
  inline void Advance() {
    instr_ = next_;
    next_ = Done() ? NULL : instr_->next();
  }
249 250 251

 private:
  HInstruction* instr_;
252
  HInstruction* next_;
253 254 255
};


256
class HLoopInformation FINAL : public ZoneObject {
257
 public:
258 259
  HLoopInformation(HBasicBlock* loop_header, Zone* zone)
      : back_edges_(4, zone),
260
        loop_header_(loop_header),
261
        blocks_(8, zone),
262
        stack_check_(NULL) {
263
    blocks_.Add(loop_header, zone);
264
  }
265
  ~HLoopInformation() {}
266 267 268 269 270 271 272

  const ZoneList<HBasicBlock*>* back_edges() const { return &back_edges_; }
  const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
  HBasicBlock* loop_header() const { return loop_header_; }
  HBasicBlock* GetLastBackEdge() const;
  void RegisterBackEdge(HBasicBlock* block);

273 274 275 276 277
  HStackCheck* stack_check() const { return stack_check_; }
  void set_stack_check(HStackCheck* stack_check) {
    stack_check_ = stack_check;
  }

278 279 280 281 282 283 284 285 286 287 288 289 290 291
  bool IsNestedInThisLoop(HLoopInformation* other) {
    while (other != NULL) {
      if (other == this) {
        return true;
      }
      other = other->parent_loop();
    }
    return false;
  }
  HLoopInformation* parent_loop() {
    HBasicBlock* parent_header = loop_header()->parent_loop_header();
    return parent_header != NULL ? parent_header->loop_information() : NULL;
  }

292 293 294 295 296 297
 private:
  void AddBlock(HBasicBlock* block);

  ZoneList<HBasicBlock*> back_edges_;
  HBasicBlock* loop_header_;
  ZoneList<HBasicBlock*> blocks_;
298
  HStackCheck* stack_check_;
299 300
};

301

302
class BoundsCheckTable;
303
class InductionVariableBlocksTable;
304
class HGraph FINAL : public ZoneObject {
305
 public:
306
  explicit HGraph(CompilationInfo* info);
307

308
  Isolate* isolate() const { return isolate_; }
309
  Zone* zone() const { return zone_; }
310
  CompilationInfo* info() const { return info_; }
311

312 313
  const ZoneList<HBasicBlock*>* blocks() const { return &blocks_; }
  const ZoneList<HPhi*>* phi_list() const { return phi_list_; }
314
  HBasicBlock* entry_block() const { return entry_block_; }
315 316
  HEnvironment* start_environment() const { return start_environment_; }

317
  void FinalizeUniqueness();
318 319
  void OrderBlocks();
  void AssignDominators();
320
  void RestoreActualValues();
321 322 323

  // Returns false if there are phi-uses of the arguments-object
  // which are not supported by the optimizing compiler.
324
  bool CheckArgumentsPhiUses();
325

326 327 328 329 330
  // Returns false if there are phi-uses of an uninitialized const
  // which are not supported by the optimizing compiler.
  bool CheckConstPhiUses();

  void CollectPhis();
331

332
  HConstant* GetConstantUndefined();
333
  HConstant* GetConstant0();
334 335 336 337
  HConstant* GetConstant1();
  HConstant* GetConstantMinus1();
  HConstant* GetConstantTrue();
  HConstant* GetConstantFalse();
338
  HConstant* GetConstantHole();
339
  HConstant* GetConstantNull();
340
  HConstant* GetInvalidContext();
341

342 343 344 345 346 347 348 349
  bool IsConstantUndefined(HConstant* constant);
  bool IsConstant0(HConstant* constant);
  bool IsConstant1(HConstant* constant);
  bool IsConstantMinus1(HConstant* constant);
  bool IsConstantTrue(HConstant* constant);
  bool IsConstantFalse(HConstant* constant);
  bool IsConstantHole(HConstant* constant);
  bool IsConstantNull(HConstant* constant);
350 351
  bool IsStandardConstant(HConstant* constant);

352 353 354 355 356 357 358 359 360 361 362 363
  HBasicBlock* CreateBasicBlock();
  HArgumentsObject* GetArgumentsObject() const {
    return arguments_object_.get();
  }

  void SetArgumentsObject(HArgumentsObject* object) {
    arguments_object_.set(object);
  }

  int GetMaximumValueID() const { return values_.length(); }
  int GetNextBlockID() { return next_block_id_++; }
  int GetNextValueID(HValue* value) {
364
    DCHECK(!disallow_adding_new_values_);
365
    values_.Add(value, zone());
366 367 368 369 370 371
    return values_.length() - 1;
  }
  HValue* LookupValue(int id) const {
    if (id >= 0 && id < values_.length()) return values_[id];
    return NULL;
  }
372 373 374
  void DisallowAddingNewValues() {
    disallow_adding_new_values_ = true;
  }
375

376
  bool Optimize(BailoutReason* bailout_reason);
377

378
#ifdef DEBUG
379
  void Verify(bool do_full_verify) const;
380 381
#endif

382 383
  bool has_osr() {
    return osr_ != NULL;
384 385
  }

386 387
  void set_osr(HOsrBuilder* osr) {
    osr_ = osr;
388 389
  }

390 391
  HOsrBuilder* osr() {
    return osr_;
392 393
  }

394 395 396 397 398
  int update_type_change_checksum(int delta) {
    type_change_checksum_ += delta;
    return type_change_checksum_;
  }

399 400 401 402 403 404 405
  void update_maximum_environment_size(int environment_size) {
    if (environment_size > maximum_environment_size_) {
      maximum_environment_size_ = environment_size;
    }
  }
  int maximum_environment_size() { return maximum_environment_size_; }

406 407 408 409 410 411 412 413
  bool use_optimistic_licm() {
    return use_optimistic_licm_;
  }

  void set_use_optimistic_licm(bool value) {
    use_optimistic_licm_ = value;
  }

414 415 416 417 418 419 420 421
  void MarkRecursive() {
    is_recursive_ = true;
  }

  bool is_recursive() const {
    return is_recursive_;
  }

422
  void MarkDependsOnEmptyArrayProtoElements() {
423 424
    // Add map dependency if not already added.
    if (depends_on_empty_array_proto_elements_) return;
425 426
    Map::AddDependentCompilationInfo(
        handle(isolate()->initial_object_prototype()->map()),
427
        DependentCode::kElementsCantBeAddedGroup, info());
428 429
    Map::AddDependentCompilationInfo(
        handle(isolate()->initial_array_prototype()->map()),
430
        DependentCode::kElementsCantBeAddedGroup, info());
431 432 433
    depends_on_empty_array_proto_elements_ = true;
  }

434 435 436 437
  bool depends_on_empty_array_proto_elements() {
    return depends_on_empty_array_proto_elements_;
  }

438
  bool has_uint32_instructions() {
439
    DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
440 441 442 443
    return uint32_instructions_ != NULL;
  }

  ZoneList<HInstruction*>* uint32_instructions() {
444
    DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
445 446 447
    return uint32_instructions_;
  }

448
  void RecordUint32Instruction(HInstruction* instr) {
449
    DCHECK(uint32_instructions_ == NULL || !uint32_instructions_->is_empty());
450 451 452 453 454 455
    if (uint32_instructions_ == NULL) {
      uint32_instructions_ = new(zone()) ZoneList<HInstruction*>(4, zone());
    }
    uint32_instructions_->Add(instr, zone());
  }

456 457 458 459
  void IncrementInNoSideEffectsScope() { no_side_effects_scope_count_++; }
  void DecrementInNoSideEffectsScope() { no_side_effects_scope_count_--; }
  bool IsInsideNoSideEffectsScope() { return no_side_effects_scope_count_ > 0; }

460 461 462 463 464 465 466 467 468 469
  // If we are tracking source positions then this function assigns a unique
  // identifier to each inlining and dumps function source if it was inlined
  // for the first time during the current optimization.
  int TraceInlinedFunction(Handle<SharedFunctionInfo> shared,
                           HSourcePosition position);

  // Converts given HSourcePosition to the absolute offset from the start of
  // the corresponding script.
  int SourcePositionToScriptPosition(HSourcePosition position);

470
 private:
471
  HConstant* ReinsertConstantIfNecessary(HConstant* constant);
472 473
  HConstant* GetConstant(SetOncePointer<HConstant>* pointer,
                         int32_t integer_value);
474

475
  template<class Phase>
476 477 478 479
  void Run() {
    Phase phase(this);
    phase.Run();
  }
480

481
  Isolate* isolate_;
482
  int next_block_id_;
483
  HBasicBlock* entry_block_;
484 485 486 487
  HEnvironment* start_environment_;
  ZoneList<HBasicBlock*> blocks_;
  ZoneList<HValue*> values_;
  ZoneList<HPhi*>* phi_list_;
488
  ZoneList<HInstruction*>* uint32_instructions_;
489
  SetOncePointer<HConstant> constant_undefined_;
490
  SetOncePointer<HConstant> constant_0_;
491 492 493 494
  SetOncePointer<HConstant> constant_1_;
  SetOncePointer<HConstant> constant_minus1_;
  SetOncePointer<HConstant> constant_true_;
  SetOncePointer<HConstant> constant_false_;
495
  SetOncePointer<HConstant> constant_the_hole_;
496
  SetOncePointer<HConstant> constant_null_;
497
  SetOncePointer<HConstant> constant_invalid_context_;
498 499
  SetOncePointer<HArgumentsObject> arguments_object_;

500
  HOsrBuilder* osr_;
501

502
  CompilationInfo* info_;
503 504
  Zone* zone_;

505
  bool is_recursive_;
506
  bool use_optimistic_licm_;
507
  bool depends_on_empty_array_proto_elements_;
508
  int type_change_checksum_;
509
  int maximum_environment_size_;
510
  int no_side_effects_scope_count_;
511
  bool disallow_adding_new_values_;
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
  class InlinedFunctionInfo {
   public:
    explicit InlinedFunctionInfo(Handle<SharedFunctionInfo> shared)
      : shared_(shared), start_position_(shared->start_position()) {
    }

    Handle<SharedFunctionInfo> shared() const { return shared_; }
    int start_position() const { return start_position_; }

   private:
    Handle<SharedFunctionInfo> shared_;
    int start_position_;
  };

  ZoneList<InlinedFunctionInfo> inlined_functions_;
528
  ZoneList<int> inlining_id_to_function_id_;
529

530 531 532 533
  DISALLOW_COPY_AND_ASSIGN(HGraph);
};


534
Zone* HBasicBlock::zone() const { return graph_->zone(); }
535 536


537
// Type of stack frame an environment might refer to.
538 539 540
enum FrameType {
  JS_FUNCTION,
  JS_CONSTRUCT,
541
  JS_GETTER,
542
  JS_SETTER,
543 544
  ARGUMENTS_ADAPTOR,
  STUB
545
};
546 547


548
class HEnvironment FINAL : public ZoneObject {
549 550 551
 public:
  HEnvironment(HEnvironment* outer,
               Scope* scope,
552 553
               Handle<JSFunction> closure,
               Zone* zone);
554

555
  HEnvironment(Zone* zone, int parameter_count);
556

557 558 559 560
  HEnvironment* arguments_environment() {
    return outer()->frame_type() == ARGUMENTS_ADAPTOR ? outer() : this;
  }

561 562 563
  // Simple accessors.
  Handle<JSFunction> closure() const { return closure_; }
  const ZoneList<HValue*>* values() const { return &values_; }
564
  const GrowableBitVector* assigned_variables() const {
565 566
    return &assigned_variables_;
  }
567
  FrameType frame_type() const { return frame_type_; }
568
  int parameter_count() const { return parameter_count_; }
569
  int specials_count() const { return specials_count_; }
570 571 572 573 574
  int local_count() const { return local_count_; }
  HEnvironment* outer() const { return outer_; }
  int pop_count() const { return pop_count_; }
  int push_count() const { return push_count_; }

575 576
  BailoutId ast_id() const { return ast_id_; }
  void set_ast_id(BailoutId id) { ast_id_ = id; }
577

578 579 580
  HEnterInlined* entry() const { return entry_; }
  void set_entry(HEnterInlined* entry) { entry_ = entry; }

581 582
  int length() const { return values_.length(); }

583 584 585 586
  int first_expression_index() const {
    return parameter_count() + specials_count() + local_count();
  }

587 588 589 590
  int first_local_index() const {
    return parameter_count() + specials_count();
  }

591 592 593 594
  void Bind(Variable* variable, HValue* value) {
    Bind(IndexFor(variable), value);
  }

595
  void Bind(int index, HValue* value);
596

597 598 599 600
  void BindContext(HValue* value) {
    Bind(parameter_count(), value);
  }

601 602 603
  HValue* Lookup(Variable* variable) const {
    return Lookup(IndexFor(variable));
  }
604

605 606
  HValue* Lookup(int index) const {
    HValue* result = values_[index];
607
    DCHECK(result != NULL);
608 609 610
    return result;
  }

611
  HValue* context() const {
612 613 614 615
    // Return first special.
    return Lookup(parameter_count());
  }

616
  void Push(HValue* value) {
617
    DCHECK(value != NULL);
618
    ++push_count_;
619
    values_.Add(value, zone());
620 621 622
  }

  HValue* Pop() {
623
    DCHECK(!ExpressionStackIsEmpty());
624 625 626 627 628 629 630 631
    if (push_count_ > 0) {
      --push_count_;
    } else {
      ++pop_count_;
    }
    return values_.RemoveLast();
  }

632
  void Drop(int count);
633

634
  HValue* Top() const { return ExpressionStackAt(0); }
635

636 637
  bool ExpressionStackIsEmpty() const;

638 639
  HValue* ExpressionStackAt(int index_from_top) const {
    int index = length() - index_from_top - 1;
640
    DCHECK(HasExpressionAt(index));
641
    return values_[index];
642
  }
643 644

  void SetExpressionStackAt(int index_from_top, HValue* value);
645
  HValue* RemoveExpressionStackAt(int index_from_top);
646

647 648 649 650 651 652
  HEnvironment* Copy() const;
  HEnvironment* CopyWithoutHistory() const;
  HEnvironment* CopyAsLoopHeader(HBasicBlock* block) const;

  // Create an "inlined version" of this environment, where the original
  // environment is the outer environment but the top expression stack
653
  // elements are moved to an inner environment as parameters.
654
  HEnvironment* CopyForInlining(Handle<JSFunction> target,
655
                                int arguments,
656
                                FunctionLiteral* function,
657
                                HConstant* undefined,
658
                                InliningKind inlining_kind) const;
659

660 661 662 663 664 665 666
  HEnvironment* DiscardInlined(bool drop_extra) {
    HEnvironment* outer = outer_;
    while (outer->frame_type() != JS_FUNCTION) outer = outer->outer_;
    if (drop_extra) outer->Drop(1);
    return outer;
  }

667
  void AddIncomingEdge(HBasicBlock* block, HEnvironment* other);
668

669 670 671
  void ClearHistory() {
    pop_count_ = 0;
    push_count_ = 0;
672
    assigned_variables_.Clear();
673
  }
674

675
  void SetValueAt(int index, HValue* value) {
676
    DCHECK(index < length());
677 678 679
    values_[index] = value;
  }

680 681 682 683
  // Map a variable to an environment index.  Parameter indices are shifted
  // by 1 (receiver is parameter index -1 but environment index 0).
  // Stack-allocated local indices are shifted by the number of parameters.
  int IndexFor(Variable* variable) const {
684
    DCHECK(variable->IsStackAllocated());
685 686 687 688 689 690 691
    int shift = variable->IsParameter()
        ? 1
        : parameter_count_ + specials_count_;
    return variable->index() + shift;
  }

  bool is_local_index(int i) const {
692 693 694 695 696 697 698 699 700
    return i >= first_local_index() && i < first_expression_index();
  }

  bool is_parameter_index(int i) const {
    return i >= 0 && i < parameter_count();
  }

  bool is_special_index(int i) const {
    return i >= parameter_count() && i < parameter_count() + specials_count();
701 702
  }

703 704
  Zone* zone() const { return zone_; }

705
 private:
706
  HEnvironment(const HEnvironment* other, Zone* zone);
707

708 709 710
  HEnvironment(HEnvironment* outer,
               Handle<JSFunction> closure,
               FrameType frame_type,
711 712
               int arguments,
               Zone* zone);
713

714 715 716 717 718 719
  // Create an artificial stub environment (e.g. for argument adaptor or
  // constructor stub).
  HEnvironment* CreateStubEnvironment(HEnvironment* outer,
                                      Handle<JSFunction> target,
                                      FrameType frame_type,
                                      int arguments) const;
720

721 722 723
  // True if index is included in the expression stack part of the environment.
  bool HasExpressionAt(int index) const;

724 725
  void Initialize(int parameter_count, int local_count, int stack_height);
  void Initialize(const HEnvironment* other);
726

727
  Handle<JSFunction> closure_;
728
  // Value array [parameters] [specials] [locals] [temporaries].
729
  ZoneList<HValue*> values_;
730
  GrowableBitVector assigned_variables_;
731
  FrameType frame_type_;
732
  int parameter_count_;
733
  int specials_count_;
734 735
  int local_count_;
  HEnvironment* outer_;
736
  HEnterInlined* entry_;
737 738
  int pop_count_;
  int push_count_;
739
  BailoutId ast_id_;
740
  Zone* zone_;
741 742 743
};


744
std::ostream& operator<<(std::ostream& os, const HEnvironment& env);
745 746


747
class HOptimizedGraphBuilder;
748

749 750
enum ArgumentsAllowedFlag {
  ARGUMENTS_NOT_ALLOWED,
751 752
  ARGUMENTS_ALLOWED,
  ARGUMENTS_FAKED
753 754
};

755 756 757

class HIfContinuation;

758 759
// This class is not BASE_EMBEDDED because our inlining implementation uses
// new and delete.
760 761 762 763 764 765
class AstContext {
 public:
  bool IsEffect() const { return kind_ == Expression::kEffect; }
  bool IsValue() const { return kind_ == Expression::kValue; }
  bool IsTest() const { return kind_ == Expression::kTest; }

766 767 768 769 770 771 772 773 774
  // 'Fill' this context with a hydrogen value.  The value is assumed to
  // have already been inserted in the instruction stream (or not need to
  // be, e.g., HPhi).  Call this function in tail position in the Visit
  // functions for expressions.
  virtual void ReturnValue(HValue* value) = 0;

  // Add a hydrogen instruction to the instruction stream (recording an
  // environment simulation if necessary) and then fill this context with
  // the instruction as value.
775
  virtual void ReturnInstruction(HInstruction* instr, BailoutId ast_id) = 0;
776

777 778 779 780
  // Finishes the current basic block and materialize a boolean for
  // value context, nothing for effect, generate a branch for test context.
  // Call this function in tail position in the Visit functions for
  // expressions.
781
  virtual void ReturnControl(HControlInstruction* instr, BailoutId ast_id) = 0;
782

783 784 785 786 787 788 789
  // Finishes the current basic block and materialize a boolean for
  // value context, nothing for effect, generate a branch for test context.
  // Call this function in tail position in the Visit functions for
  // expressions that use an IfBuilder.
  virtual void ReturnContinuation(HIfContinuation* continuation,
                                  BailoutId ast_id) = 0;

790 791 792
  void set_for_typeof(bool for_typeof) { for_typeof_ = for_typeof; }
  bool is_for_typeof() { return for_typeof_; }

793
 protected:
794
  AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind);
795 796
  virtual ~AstContext();

797
  HOptimizedGraphBuilder* owner() const { return owner_; }
798

799
  inline Zone* zone() const;
800

801 802 803
  // We want to be able to assert, in a context-specific way, that the stack
  // height makes sense when the context is filled.
#ifdef DEBUG
804
  int original_length_;
805 806
#endif

807
 private:
808
  HOptimizedGraphBuilder* owner_;
809 810
  Expression::Context kind_;
  AstContext* outer_;
811
  bool for_typeof_;
812 813 814
};


815
class EffectContext FINAL : public AstContext {
816
 public:
817
  explicit EffectContext(HOptimizedGraphBuilder* owner)
818 819
      : AstContext(owner, Expression::kEffect) {
  }
820 821
  virtual ~EffectContext();

822
  void ReturnValue(HValue* value) OVERRIDE;
823
  virtual void ReturnInstruction(HInstruction* instr,
824
                                 BailoutId ast_id) OVERRIDE;
825
  virtual void ReturnControl(HControlInstruction* instr,
826
                             BailoutId ast_id) OVERRIDE;
827
  virtual void ReturnContinuation(HIfContinuation* continuation,
828
                                  BailoutId ast_id) OVERRIDE;
829 830 831
};


832
class ValueContext FINAL : public AstContext {
833
 public:
834
  ValueContext(HOptimizedGraphBuilder* owner, ArgumentsAllowedFlag flag)
835
      : AstContext(owner, Expression::kValue), flag_(flag) {
836
  }
837 838
  virtual ~ValueContext();

839
  void ReturnValue(HValue* value) OVERRIDE;
840
  virtual void ReturnInstruction(HInstruction* instr,
841
                                 BailoutId ast_id) OVERRIDE;
842
  virtual void ReturnControl(HControlInstruction* instr,
843
                             BailoutId ast_id) OVERRIDE;
844
  virtual void ReturnContinuation(HIfContinuation* continuation,
845
                                  BailoutId ast_id) OVERRIDE;
846 847 848 849 850

  bool arguments_allowed() { return flag_ == ARGUMENTS_ALLOWED; }

 private:
  ArgumentsAllowedFlag flag_;
851 852 853
};


854
class TestContext FINAL : public AstContext {
855
 public:
856
  TestContext(HOptimizedGraphBuilder* owner,
857
              Expression* condition,
858
              HBasicBlock* if_true,
859
              HBasicBlock* if_false)
860
      : AstContext(owner, Expression::kTest),
861
        condition_(condition),
862
        if_true_(if_true),
863
        if_false_(if_false) {
864 865
  }

866
  void ReturnValue(HValue* value) OVERRIDE;
867
  virtual void ReturnInstruction(HInstruction* instr,
868
                                 BailoutId ast_id) OVERRIDE;
869
  virtual void ReturnControl(HControlInstruction* instr,
870
                             BailoutId ast_id) OVERRIDE;
871
  virtual void ReturnContinuation(HIfContinuation* continuation,
872
                                  BailoutId ast_id) OVERRIDE;
873

874
  static TestContext* cast(AstContext* context) {
875
    DCHECK(context->IsTest());
876 877 878
    return reinterpret_cast<TestContext*>(context);
  }

879
  Expression* condition() const { return condition_; }
880 881 882 883
  HBasicBlock* if_true() const { return if_true_; }
  HBasicBlock* if_false() const { return if_false_; }

 private:
884 885 886 887
  // Build the shared core part of the translation unpacking a value into
  // control flow.
  void BuildBranch(HValue* value);

888
  Expression* condition_;
889 890 891 892 893
  HBasicBlock* if_true_;
  HBasicBlock* if_false_;
};


894
class FunctionState FINAL {
895
 public:
896
  FunctionState(HOptimizedGraphBuilder* owner,
897
                CompilationInfo* info,
898 899
                InliningKind inlining_kind,
                int inlining_id);
900 901 902 903
  ~FunctionState();

  CompilationInfo* compilation_info() { return compilation_info_; }
  AstContext* call_context() { return call_context_; }
904
  InliningKind inlining_kind() const { return inlining_kind_; }
905 906 907 908 909 910 911
  HBasicBlock* function_return() { return function_return_; }
  TestContext* test_context() { return test_context_; }
  void ClearInlinedTestContext() {
    delete test_context_;
    test_context_ = NULL;
  }

912 913
  FunctionState* outer() { return outer_; }

914 915 916
  HEnterInlined* entry() { return entry_; }
  void set_entry(HEnterInlined* entry) { entry_ = entry; }

917 918 919 920 921
  HArgumentsObject* arguments_object() { return arguments_object_; }
  void set_arguments_object(HArgumentsObject* arguments_object) {
    arguments_object_ = arguments_object;
  }

922 923 924 925 926 927 928
  HArgumentsElements* arguments_elements() { return arguments_elements_; }
  void set_arguments_elements(HArgumentsElements* arguments_elements) {
    arguments_elements_ = arguments_elements;
  }

  bool arguments_pushed() { return arguments_elements() != NULL; }

929 930
  int inlining_id() const { return inlining_id_; }

931
 private:
932
  HOptimizedGraphBuilder* owner_;
933 934 935 936 937 938 939

  CompilationInfo* compilation_info_;

  // During function inlining, expression context of the call being
  // inlined. NULL when not inlining.
  AstContext* call_context_;

940 941
  // The kind of call which is currently being inlined.
  InliningKind inlining_kind_;
942

943
  // When inlining in an effect or value context, this is the return block.
944 945 946 947 948 949 950 951 952
  // It is NULL otherwise.  When inlining in a test context, there are a
  // pair of return blocks in the context.  When not inlining, there is no
  // local return point.
  HBasicBlock* function_return_;

  // When inlining a call in a test context, a context containing a pair of
  // return blocks.  NULL in all other cases.
  TestContext* test_context_;

953 954 955 956
  // When inlining HEnterInlined instruction corresponding to the function
  // entry.
  HEnterInlined* entry_;

957
  HArgumentsObject* arguments_object_;
958 959
  HArgumentsElements* arguments_elements_;

960 961 962
  int inlining_id_;
  HSourcePosition outer_source_position_;

963 964 965 966
  FunctionState* outer_;
};


967
class HIfContinuation FINAL {
968
 public:
969 970 971 972
  HIfContinuation()
    : continuation_captured_(false),
      true_branch_(NULL),
      false_branch_(NULL) {}
973
  HIfContinuation(HBasicBlock* true_branch,
974
                  HBasicBlock* false_branch)
975
      : continuation_captured_(true), true_branch_(true_branch),
976
        false_branch_(false_branch) {}
977
  ~HIfContinuation() { DCHECK(!continuation_captured_); }
978 979

  void Capture(HBasicBlock* true_branch,
980
               HBasicBlock* false_branch) {
981
    DCHECK(!continuation_captured_);
982 983 984 985 986 987
    true_branch_ = true_branch;
    false_branch_ = false_branch;
    continuation_captured_ = true;
  }

  void Continue(HBasicBlock** true_branch,
988
                HBasicBlock** false_branch) {
989
    DCHECK(continuation_captured_);
990 991 992 993 994 995 996 997 998 999 1000
    *true_branch = true_branch_;
    *false_branch = false_branch_;
    continuation_captured_ = false;
  }

  bool IsTrueReachable() { return true_branch_ != NULL; }
  bool IsFalseReachable() { return false_branch_ != NULL; }
  bool TrueAndFalseReachable() {
    return IsTrueReachable() || IsFalseReachable();
  }

1001 1002 1003 1004
  HBasicBlock* true_branch() const { return true_branch_; }
  HBasicBlock* false_branch() const { return false_branch_; }

 private:
1005 1006 1007 1008 1009 1010
  bool continuation_captured_;
  HBasicBlock* true_branch_;
  HBasicBlock* false_branch_;
};


1011
class HAllocationMode FINAL BASE_EMBEDDED {
1012 1013 1014 1015 1016 1017 1018 1019
 public:
  explicit HAllocationMode(Handle<AllocationSite> feedback_site)
      : current_site_(NULL), feedback_site_(feedback_site),
        pretenure_flag_(NOT_TENURED) {}
  explicit HAllocationMode(HValue* current_site)
      : current_site_(current_site), pretenure_flag_(NOT_TENURED) {}
  explicit HAllocationMode(PretenureFlag pretenure_flag)
      : current_site_(NULL), pretenure_flag_(pretenure_flag) {}
1020 1021
  HAllocationMode()
      : current_site_(NULL), pretenure_flag_(NOT_TENURED) {}
1022 1023 1024 1025

  HValue* current_site() const { return current_site_; }
  Handle<AllocationSite> feedback_site() const { return feedback_site_; }

1026
  bool CreateAllocationMementos() const WARN_UNUSED_RESULT {
1027 1028 1029
    return current_site() != NULL;
  }

1030
  PretenureFlag GetPretenureMode() const WARN_UNUSED_RESULT {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    if (!feedback_site().is_null()) return feedback_site()->GetPretenureMode();
    return pretenure_flag_;
  }

 private:
  HValue* current_site_;
  Handle<AllocationSite> feedback_site_;
  PretenureFlag pretenure_flag_;
};


1042 1043 1044
class HGraphBuilder {
 public:
  explicit HGraphBuilder(CompilationInfo* info)
1045 1046
      : info_(info),
        graph_(NULL),
1047
        current_block_(NULL),
1048
        scope_(info->scope()),
1049 1050
        position_(HSourcePosition::Unknown()),
        start_position_(0) {}
1051 1052
  virtual ~HGraphBuilder() {}

1053 1054 1055
  Scope* scope() const { return scope_; }
  void set_scope(Scope* scope) { scope_ = scope; }

1056 1057 1058 1059 1060 1061
  HBasicBlock* current_block() const { return current_block_; }
  void set_current_block(HBasicBlock* block) { current_block_ = block; }
  HEnvironment* environment() const {
    return current_block()->last_environment();
  }
  Zone* zone() const { return info_->zone(); }
1062 1063
  HGraph* graph() const { return graph_; }
  Isolate* isolate() const { return graph_->isolate(); }
1064
  CompilationInfo* top_info() { return info_; }
1065 1066 1067

  HGraph* CreateGraph();

1068 1069 1070 1071
  // Bailout environment manipulation.
  void Push(HValue* value) { environment()->Push(value); }
  HValue* Pop() { return environment()->Pop(); }

1072 1073
  virtual HValue* context() = 0;

1074 1075
  // Adding instructions.
  HInstruction* AddInstruction(HInstruction* instr);
1076 1077 1078 1079 1080 1081 1082
  void FinishCurrentBlock(HControlInstruction* last);
  void FinishExitCurrentBlock(HControlInstruction* instruction);

  void Goto(HBasicBlock* from,
            HBasicBlock* target,
            FunctionState* state = NULL,
            bool add_simulate = true) {
1083
    from->Goto(target, source_position(), state, add_simulate);
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  }
  void Goto(HBasicBlock* target,
            FunctionState* state = NULL,
            bool add_simulate = true) {
    Goto(current_block(), target, state, add_simulate);
  }
  void GotoNoSimulate(HBasicBlock* from, HBasicBlock* target) {
    Goto(from, target, NULL, false);
  }
  void GotoNoSimulate(HBasicBlock* target) {
    Goto(target, NULL, false);
  }
  void AddLeaveInlined(HBasicBlock* block,
                       HValue* return_value,
                       FunctionState* state) {
1099
    block->AddLeaveInlined(return_value, state, source_position());
1100 1101 1102 1103
  }
  void AddLeaveInlined(HValue* return_value, FunctionState* state) {
    return AddLeaveInlined(current_block(), return_value, state);
  }
1104

1105 1106 1107 1108
  template <class I>
  HInstruction* NewUncasted() {
    return I::New(isolate(), zone(), context());
  }
1109

1110 1111 1112 1113
  template <class I>
  I* New() {
    return I::New(isolate(), zone(), context());
  }
1114 1115 1116 1117 1118

  template<class I>
  HInstruction* AddUncasted() { return AddInstruction(NewUncasted<I>());}

  template<class I>
1119
  I* Add() { return AddInstructionTyped(New<I>());}
1120 1121 1122

  template<class I, class P1>
  HInstruction* NewUncasted(P1 p1) {
1123
    return I::New(isolate(), zone(), context(), p1);
1124 1125
  }

1126 1127 1128 1129
  template <class I, class P1>
  I* New(P1 p1) {
    return I::New(isolate(), zone(), context(), p1);
  }
1130 1131 1132 1133 1134 1135

  template<class I, class P1>
  HInstruction* AddUncasted(P1 p1) {
    HInstruction* result = AddInstruction(NewUncasted<I>(p1));
    // Specializations must have their parameters properly casted
    // to avoid landing here.
1136
    DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1137 1138 1139
           !result->IsDeoptimize());
    return result;
  }
1140 1141 1142

  template<class I, class P1>
  I* Add(P1 p1) {
1143 1144 1145
    I* result = AddInstructionTyped(New<I>(p1));
    // Specializations must have their parameters properly casted
    // to avoid landing here.
1146
    DCHECK(!result->IsReturn() && !result->IsSimulate() &&
1147 1148
           !result->IsDeoptimize());
    return result;
1149 1150 1151 1152
  }

  template<class I, class P1, class P2>
  HInstruction* NewUncasted(P1 p1, P2 p2) {
1153
    return I::New(isolate(), zone(), context(), p1, p2);
1154 1155 1156 1157
  }

  template<class I, class P1, class P2>
  I* New(P1 p1, P2 p2) {
1158
    return I::New(isolate(), zone(), context(), p1, p2);
1159 1160 1161 1162 1163 1164 1165
  }

  template<class I, class P1, class P2>
  HInstruction* AddUncasted(P1 p1, P2 p2) {
    HInstruction* result = AddInstruction(NewUncasted<I>(p1, p2));
    // Specializations must have their parameters properly casted
    // to avoid landing here.
1166
    DCHECK(!result->IsSimulate());
1167
    return result;
1168 1169 1170 1171
  }

  template<class I, class P1, class P2>
  I* Add(P1 p1, P2 p2) {
1172 1173 1174
    I* result = AddInstructionTyped(New<I>(p1, p2));
    // Specializations must have their parameters properly casted
    // to avoid landing here.
1175
    DCHECK(!result->IsSimulate());
1176
    return result;
1177 1178 1179 1180
  }

  template<class I, class P1, class P2, class P3>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3) {
1181
    return I::New(isolate(), zone(), context(), p1, p2, p3);
1182 1183 1184 1185
  }

  template<class I, class P1, class P2, class P3>
  I* New(P1 p1, P2 p2, P3 p3) {
1186
    return I::New(isolate(), zone(), context(), p1, p2, p3);
1187 1188 1189 1190 1191
  }

  template<class I, class P1, class P2, class P3>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3));
1192 1193 1194 1195
  }

  template<class I, class P1, class P2, class P3>
  I* Add(P1 p1, P2 p2, P3 p3) {
1196
    return AddInstructionTyped(New<I>(p1, p2, p3));
1197 1198 1199 1200
  }

  template<class I, class P1, class P2, class P3, class P4>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
1201
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4);
1202 1203 1204 1205
  }

  template<class I, class P1, class P2, class P3, class P4>
  I* New(P1 p1, P2 p2, P3 p3, P4 p4) {
1206
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4);
1207 1208 1209 1210 1211
  }

  template<class I, class P1, class P2, class P3, class P4>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3, p4));
1212 1213
  }

1214 1215
  template<class I, class P1, class P2, class P3, class P4>
  I* Add(P1 p1, P2 p2, P3 p3, P4 p4) {
1216
    return AddInstructionTyped(New<I>(p1, p2, p3, p4));
1217 1218 1219 1220
  }

  template<class I, class P1, class P2, class P3, class P4, class P5>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1221
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5);
1222 1223 1224 1225
  }

  template<class I, class P1, class P2, class P3, class P4, class P5>
  I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1226
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5);
1227 1228 1229 1230 1231
  }

  template<class I, class P1, class P2, class P3, class P4, class P5>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5));
1232 1233 1234 1235
  }

  template<class I, class P1, class P2, class P3, class P4, class P5>
  I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
1236
    return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5));
1237 1238 1239 1240
  }

  template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1241
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6);
1242 1243 1244 1245
  }

  template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
  I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1246
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6);
1247 1248 1249 1250 1251
  }

  template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6));
1252 1253 1254 1255
  }

  template<class I, class P1, class P2, class P3, class P4, class P5, class P6>
  I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
1256
    return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6));
1257 1258 1259 1260 1261
  }

  template<class I, class P1, class P2, class P3, class P4,
      class P5, class P6, class P7>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1262
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1263 1264 1265 1266 1267
  }

  template<class I, class P1, class P2, class P3, class P4,
      class P5, class P6, class P7>
      I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1268
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7);
1269 1270 1271 1272 1273 1274
  }

  template<class I, class P1, class P2, class P3,
           class P4, class P5, class P6, class P7>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7));
1275 1276 1277 1278 1279
  }

  template<class I, class P1, class P2, class P3,
           class P4, class P5, class P6, class P7>
  I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
1280
    return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7));
1281 1282 1283 1284 1285 1286
  }

  template<class I, class P1, class P2, class P3, class P4,
      class P5, class P6, class P7, class P8>
  HInstruction* NewUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
                            P5 p5, P6 p6, P7 p7, P8 p8) {
1287
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1288 1289 1290 1291 1292
  }

  template<class I, class P1, class P2, class P3, class P4,
      class P5, class P6, class P7, class P8>
      I* New(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1293
    return I::New(isolate(), zone(), context(), p1, p2, p3, p4, p5, p6, p7, p8);
1294 1295 1296 1297 1298 1299 1300
  }

  template<class I, class P1, class P2, class P3, class P4,
           class P5, class P6, class P7, class P8>
  HInstruction* AddUncasted(P1 p1, P2 p2, P3 p3, P4 p4,
                            P5 p5, P6 p6, P7 p7, P8 p8) {
    return AddInstruction(NewUncasted<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1301 1302 1303 1304 1305
  }

  template<class I, class P1, class P2, class P3, class P4,
           class P5, class P6, class P7, class P8>
  I* Add(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
1306
    return AddInstructionTyped(New<I>(p1, p2, p3, p4, p5, p6, p7, p8));
1307 1308
  }

1309
  void AddSimulate(BailoutId id, RemovableSimulate removable = FIXED_SIMULATE);
1310

1311 1312 1313 1314
  // When initializing arrays, we'll unfold the loop if the number of elements
  // is known at compile time and is <= kElementLoopUnrollThreshold.
  static const int kElementLoopUnrollThreshold = 8;

1315 1316 1317
 protected:
  virtual bool BuildGraph() = 0;

1318
  HBasicBlock* CreateBasicBlock(HEnvironment* env);
1319
  HBasicBlock* CreateLoopHeaderBlock();
1320

1321 1322 1323
  template <class BitFieldClass>
  HValue* BuildDecodeField(HValue* encoded_field) {
    HValue* mask_value = Add<HConstant>(static_cast<int>(BitFieldClass::kMask));
1324 1325 1326 1327
    HValue* masked_field =
        AddUncasted<HBitwise>(Token::BIT_AND, encoded_field, mask_value);
    return AddUncasted<HShr>(masked_field,
        Add<HConstant>(static_cast<int>(BitFieldClass::kShift)));
1328 1329 1330 1331
  }

  HValue* BuildGetElementsKind(HValue* object);

1332
  HValue* BuildCheckHeapObject(HValue* object);
1333
  HValue* BuildCheckString(HValue* string);
1334
  HValue* BuildWrapReceiver(HValue* object, HValue* function);
1335

1336
  // Building common constructs
1337 1338 1339 1340 1341
  HValue* BuildCheckForCapacityGrow(HValue* object,
                                    HValue* elements,
                                    ElementsKind kind,
                                    HValue* length,
                                    HValue* key,
1342
                                    bool is_js_array,
1343
                                    PropertyAccessType access_type);
1344 1345 1346 1347 1348

  HValue* BuildCopyElementsOnWrite(HValue* object,
                                   HValue* elements,
                                   ElementsKind kind,
                                   HValue* length);
1349

1350 1351 1352 1353 1354 1355
  void BuildTransitionElementsKind(HValue* object,
                                   HValue* map,
                                   ElementsKind from_kind,
                                   ElementsKind to_kind,
                                   bool is_jsarray);

1356
  HValue* BuildNumberToString(HValue* object, Type* type);
1357

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  void BuildJSObjectCheck(HValue* receiver,
                          int bit_field_mask);

  // Checks a key value that's being used for a keyed element access context. If
  // the key is a index, i.e. a smi or a number in a unique string with a cached
  // numeric value, the "true" of the continuation is joined. Otherwise,
  // if the key is a name or a unique string, the "false" of the continuation is
  // joined. Otherwise, a deoptimization is triggered. In both paths of the
  // continuation, the key is pushed on the top of the environment.
  void BuildKeyedIndexCheck(HValue* key,
                            HIfContinuation* join_continuation);

  // Checks the properties of an object if they are in dictionary case, in which
  // case "true" of continuation is taken, otherwise the "false"
  void BuildTestForDictionaryProperties(HValue* object,
                                        HIfContinuation* continuation);

  void BuildNonGlobalObjectCheck(HValue* receiver);

  HValue* BuildKeyedLookupCacheHash(HValue* object,
                                    HValue* key);

1380
  HValue* BuildUncheckedDictionaryElementLoad(HValue* receiver,
1381 1382 1383
                                              HValue* elements,
                                              HValue* key,
                                              HValue* hash);
1384

1385 1386 1387 1388
  HValue* BuildRegExpConstructResult(HValue* length,
                                     HValue* index,
                                     HValue* input);

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  // Allocates a new object according with the given allocation properties.
  HAllocate* BuildAllocate(HValue* object_size,
                           HType type,
                           InstanceType instance_type,
                           HAllocationMode allocation_mode);
  // Computes the sum of two string lengths, taking care of overflow handling.
  HValue* BuildAddStringLengths(HValue* left_length, HValue* right_length);
  // Creates a cons string using the two input strings.
  HValue* BuildCreateConsString(HValue* length,
                                HValue* left,
                                HValue* right,
                                HAllocationMode allocation_mode);
1401 1402 1403 1404 1405 1406 1407 1408
  // Copies characters from one sequential string to another.
  void BuildCopySeqStringChars(HValue* src,
                               HValue* src_offset,
                               String::Encoding src_encoding,
                               HValue* dst,
                               HValue* dst_offset,
                               String::Encoding dst_encoding,
                               HValue* length);
1409 1410 1411 1412

  // Align an object size to object alignment boundary
  HValue* BuildObjectSizeAlignment(HValue* unaligned_size, int header_size);

1413 1414 1415
  // Both operands are non-empty strings.
  HValue* BuildUncheckedStringAdd(HValue* left,
                                  HValue* right,
1416 1417
                                  HAllocationMode allocation_mode);
  // Add two strings using allocation mode, validating type feedback.
1418 1419
  HValue* BuildStringAdd(HValue* left,
                         HValue* right,
1420
                         HAllocationMode allocation_mode);
1421

1422
  HInstruction* BuildUncheckedMonomorphicElementAccess(
1423
      HValue* checked_object,
1424 1425 1426 1427
      HValue* key,
      HValue* val,
      bool is_js_array,
      ElementsKind elements_kind,
1428
      PropertyAccessType access_type,
1429
      LoadKeyedHoleMode load_mode,
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1430
      KeyedAccessStoreMode store_mode);
1431

1432
  HInstruction* AddElementAccess(
1433 1434 1435 1436 1437
      HValue* elements,
      HValue* checked_key,
      HValue* val,
      HValue* dependency,
      ElementsKind elements_kind,
1438
      PropertyAccessType access_type,
1439
      LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE);
1440

1441 1442
  HInstruction* AddLoadStringInstanceType(HValue* string);
  HInstruction* AddLoadStringLength(HValue* string);
1443 1444 1445
  HStoreNamedField* AddStoreMapConstant(HValue* object, Handle<Map> map) {
    return Add<HStoreNamedField>(object, HObjectAccess::ForMap(),
                                 Add<HConstant>(map));
1446
  }
1447 1448
  HLoadNamedField* AddLoadMap(HValue* object,
                              HValue* dependency = NULL);
1449 1450
  HLoadNamedField* AddLoadElements(HValue* object,
                                   HValue* dependency = NULL);
1451 1452 1453 1454 1455 1456

  bool MatchRotateRight(HValue* left,
                        HValue* right,
                        HValue** operand,
                        HValue** shift_amount);

1457 1458 1459
  HValue* BuildBinaryOperation(Token::Value op,
                               HValue* left,
                               HValue* right,
1460 1461 1462
                               Type* left_type,
                               Type* right_type,
                               Type* result_type,
1463 1464
                               Maybe<int> fixed_right_arg,
                               HAllocationMode allocation_mode);
1465

1466 1467 1468 1469 1470 1471
  HLoadNamedField* AddLoadFixedArrayLength(HValue *object,
                                           HValue *dependency = NULL);

  HLoadNamedField* AddLoadArrayLength(HValue *object,
                                      ElementsKind kind,
                                      HValue *dependency = NULL);
1472

1473
  HValue* AddLoadJSBuiltin(Builtins::JavaScript builtin);
1474

1475 1476
  HValue* EnforceNumberType(HValue* number, Type* expected);
  HValue* TruncateToNumber(HValue* value, Type** expected);
1477

1478
  void FinishExitWithHardDeoptimization(Deoptimizer::DeoptReason reason);
1479

1480
  void AddIncrementCounter(StatsCounter* counter);
1481

1482
  class IfBuilder FINAL {
1483
   public:
1484 1485 1486
    // If using this constructor, Initialize() must be called explicitly!
    IfBuilder();

1487
    explicit IfBuilder(HGraphBuilder* builder);
1488 1489 1490
    IfBuilder(HGraphBuilder* builder,
              HIfContinuation* continuation);

1491 1492 1493 1494
    ~IfBuilder() {
      if (!finished_) End();
    }

1495 1496
    void Initialize(HGraphBuilder* builder);

1497
    template<class Condition>
1498 1499
    Condition* If(HValue *p) {
      Condition* compare = builder()->New<Condition>(p);
1500 1501 1502 1503 1504
      AddCompare(compare);
      return compare;
    }

    template<class Condition, class P2>
1505 1506
    Condition* If(HValue* p1, P2 p2) {
      Condition* compare = builder()->New<Condition>(p1, p2);
1507 1508 1509 1510
      AddCompare(compare);
      return compare;
    }

1511
    template<class Condition, class P2, class P3>
1512 1513
    Condition* If(HValue* p1, P2 p2, P3 p3) {
      Condition* compare = builder()->New<Condition>(p1, p2, p3);
1514 1515 1516 1517
      AddCompare(compare);
      return compare;
    }

1518 1519 1520
    template<class Condition>
    Condition* IfNot(HValue* p) {
      Condition* compare = If<Condition>(p);
1521
      compare->Not();
1522 1523 1524
      return compare;
    }

1525
    template<class Condition, class P2>
1526
    Condition* IfNot(HValue* p1, P2 p2) {
1527
      Condition* compare = If<Condition>(p1, p2);
1528
      compare->Not();
1529 1530 1531
      return compare;
    }

1532
    template<class Condition, class P2, class P3>
1533
    Condition* IfNot(HValue* p1, P2 p2, P3 p3) {
1534
      Condition* compare = If<Condition>(p1, p2, p3);
1535
      compare->Not();
1536
      return compare;
1537 1538 1539
    }

    template<class Condition>
1540
    Condition* OrIf(HValue *p) {
1541 1542 1543 1544 1545
      Or();
      return If<Condition>(p);
    }

    template<class Condition, class P2>
1546
    Condition* OrIf(HValue* p1, P2 p2) {
1547 1548 1549 1550
      Or();
      return If<Condition>(p1, p2);
    }

1551
    template<class Condition, class P2, class P3>
1552
    Condition* OrIf(HValue* p1, P2 p2, P3 p3) {
1553 1554
      Or();
      return If<Condition>(p1, p2, p3);
1555 1556 1557
    }

    template<class Condition>
1558
    Condition* AndIf(HValue *p) {
1559 1560 1561 1562 1563
      And();
      return If<Condition>(p);
    }

    template<class Condition, class P2>
1564
    Condition* AndIf(HValue* p1, P2 p2) {
1565 1566 1567 1568
      And();
      return If<Condition>(p1, p2);
    }

1569
    template<class Condition, class P2, class P3>
1570
    Condition* AndIf(HValue* p1, P2 p2, P3 p3) {
1571 1572 1573 1574
      And();
      return If<Condition>(p1, p2, p3);
    }

1575 1576 1577
    void Or();
    void And();

1578 1579
    // Captures the current state of this IfBuilder in the specified
    // continuation and ends this IfBuilder.
1580 1581
    void CaptureContinuation(HIfContinuation* continuation);

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    // Joins the specified continuation from this IfBuilder and ends this
    // IfBuilder. This appends a Goto instruction from the true branch of
    // this IfBuilder to the true branch of the continuation unless the
    // true branch of this IfBuilder is already finished. And vice versa
    // for the false branch.
    //
    // The basic idea is as follows: You have several nested IfBuilder's
    // that you want to join based on two possible outcomes (i.e. success
    // and failure, or whatever). You can do this easily using this method
    // now, for example:
    //
    //   HIfContinuation cont(graph()->CreateBasicBlock(),
    //                        graph()->CreateBasicBlock());
    //   ...
    //     IfBuilder if_whatever(this);
    //     if_whatever.If<Condition>(arg);
    //     if_whatever.Then();
    //     ...
    //     if_whatever.Else();
    //     ...
    //     if_whatever.JoinContinuation(&cont);
    //   ...
    //     IfBuilder if_something(this);
    //     if_something.If<Condition>(arg1, arg2);
    //     if_something.Then();
    //     ...
    //     if_something.Else();
    //     ...
    //     if_something.JoinContinuation(&cont);
    //   ...
    //   IfBuilder if_finally(this, &cont);
    //   if_finally.Then();
    //   // continues after then code of if_whatever or if_something.
    //   ...
    //   if_finally.Else();
    //   // continues after else code of if_whatever or if_something.
    //   ...
    //   if_finally.End();
    void JoinContinuation(HIfContinuation* continuation);

1622 1623
    void Then();
    void Else();
1624 1625
    void End();

1626 1627
    void Deopt(Deoptimizer::DeoptReason reason);
    void ThenDeopt(Deoptimizer::DeoptReason reason) {
1628 1629 1630
      Then();
      Deopt(reason);
    }
1631
    void ElseDeopt(Deoptimizer::DeoptReason reason) {
1632
      Else();
1633
      Deopt(reason);
1634
    }
1635

1636 1637
    void Return(HValue* value);

1638
   private:
1639 1640
    void InitializeDontCreateBlocks(HGraphBuilder* builder);

1641
    HControlInstruction* AddCompare(HControlInstruction* compare);
1642

1643
    HGraphBuilder* builder() const {
1644
      DCHECK(builder_ != NULL);  // Have you called "Initialize"?
1645 1646
      return builder_;
    }
1647

1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    void AddMergeAtJoinBlock(bool deopt);

    void Finish();
    void Finish(HBasicBlock** then_continuation,
                HBasicBlock** else_continuation);

    class MergeAtJoinBlock : public ZoneObject {
     public:
      MergeAtJoinBlock(HBasicBlock* block,
                       bool deopt,
                       MergeAtJoinBlock* next)
        : block_(block),
          deopt_(deopt),
          next_(next) {}
      HBasicBlock* block_;
      bool deopt_;
      MergeAtJoinBlock* next_;
    };

1667
    HGraphBuilder* builder_;
1668 1669 1670
    bool finished_ : 1;
    bool did_then_ : 1;
    bool did_else_ : 1;
1671
    bool did_else_if_ : 1;
1672 1673 1674 1675
    bool did_and_ : 1;
    bool did_or_ : 1;
    bool captured_ : 1;
    bool needs_compare_ : 1;
1676
    bool pending_merge_block_ : 1;
1677 1678
    HBasicBlock* first_true_block_;
    HBasicBlock* first_false_block_;
1679
    HBasicBlock* split_edge_merge_block_;
1680 1681 1682
    MergeAtJoinBlock* merge_at_join_blocks_;
    int normal_merge_at_join_block_count_;
    int deopt_merge_at_join_block_count_;
1683 1684
  };

1685
  class LoopBuilder FINAL {
1686 1687 1688 1689 1690
   public:
    enum Direction {
      kPreIncrement,
      kPostIncrement,
      kPreDecrement,
1691 1692
      kPostDecrement,
      kWhileTrue
1693 1694
    };

1695
    explicit LoopBuilder(HGraphBuilder* builder);  // while (true) {...}
1696 1697
    LoopBuilder(HGraphBuilder* builder,
                HValue* context,
1698
                Direction direction);
1699 1700 1701 1702 1703
    LoopBuilder(HGraphBuilder* builder,
                HValue* context,
                Direction direction,
                HValue* increment_amount);

1704
    ~LoopBuilder() {
1705
      DCHECK(finished_);
1706 1707
    }

1708 1709 1710
    HValue* BeginBody(
        HValue* initial,
        HValue* terminating,
1711
        Token::Value token);
1712

1713 1714
    void BeginBody(int drop_count);

1715 1716
    void Break();

1717 1718 1719
    void EndBody();

   private:
1720 1721
    void Initialize(HGraphBuilder* builder, HValue* context,
                    Direction direction, HValue* increment_amount);
1722 1723
    Zone* zone() { return builder_->zone(); }

1724 1725
    HGraphBuilder* builder_;
    HValue* context_;
1726
    HValue* increment_amount_;
1727 1728 1729 1730 1731
    HInstruction* increment_;
    HPhi* phi_;
    HBasicBlock* header_block_;
    HBasicBlock* body_block_;
    HBasicBlock* exit_block_;
1732
    HBasicBlock* exit_trampoline_block_;
1733 1734 1735 1736
    Direction direction_;
    bool finished_;
  };

1737
  HValue* BuildNewElementsCapacity(HValue* old_capacity);
1738

1739
  class JSArrayBuilder FINAL {
1740 1741 1742 1743
   public:
    JSArrayBuilder(HGraphBuilder* builder,
                   ElementsKind kind,
                   HValue* allocation_site_payload,
1744 1745
                   HValue* constructor_function,
                   AllocationSiteOverrideMode override_mode);
1746

1747 1748
    JSArrayBuilder(HGraphBuilder* builder,
                   ElementsKind kind,
1749
                   HValue* constructor_function = NULL);
1750

1751 1752 1753 1754 1755 1756
    enum FillMode {
      DONT_FILL_WITH_HOLE,
      FILL_WITH_HOLE
    };

    ElementsKind kind() { return kind_; }
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
    HAllocate* elements_location() { return elements_location_; }

    HAllocate* AllocateEmptyArray();
    HAllocate* AllocateArray(HValue* capacity,
                             HValue* length_field,
                             FillMode fill_mode = FILL_WITH_HOLE);
    // Use these allocators when capacity could be unknown at compile time
    // but its limit is known. For constant |capacity| the value of
    // |capacity_upper_bound| is ignored and the actual |capacity|
    // value is used as an upper bound.
    HAllocate* AllocateArray(HValue* capacity,
                             int capacity_upper_bound,
                             HValue* length_field,
                             FillMode fill_mode = FILL_WITH_HOLE);
    HAllocate* AllocateArray(HValue* capacity,
                             HConstant* capacity_upper_bound,
                             HValue* length_field,
                             FillMode fill_mode = FILL_WITH_HOLE);
1775
    HValue* GetElementsLocation() { return elements_location_; }
1776
    HValue* EmitMapCode();
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789

   private:
    Zone* zone() const { return builder_->zone(); }
    int elements_size() const {
      return IsFastDoubleElementsKind(kind_) ? kDoubleSize : kPointerSize;
    }
    HGraphBuilder* builder() { return builder_; }
    HGraph* graph() { return builder_->graph(); }
    int initial_capacity() {
      STATIC_ASSERT(JSArray::kPreallocatedArrayElements > 0);
      return JSArray::kPreallocatedArrayElements;
    }

1790
    HValue* EmitInternalMapCode();
1791 1792 1793 1794 1795

    HGraphBuilder* builder_;
    ElementsKind kind_;
    AllocationSiteMode mode_;
    HValue* allocation_site_payload_;
1796
    HValue* constructor_function_;
1797
    HAllocate* elements_location_;
1798 1799
  };

1800 1801
  HValue* BuildAllocateArrayFromLength(JSArrayBuilder* array_builder,
                                       HValue* length_argument);
1802 1803 1804 1805
  HValue* BuildCalculateElementsSize(ElementsKind kind,
                                     HValue* capacity);
  HAllocate* AllocateJSArrayObject(AllocationSiteMode mode);
  HConstant* EstablishElementsAllocationSize(ElementsKind kind, int capacity);
1806

1807
  HAllocate* BuildAllocateElements(ElementsKind kind, HValue* size_in_bytes);
1808

1809 1810 1811
  void BuildInitializeElementsHeader(HValue* elements,
                                     ElementsKind kind,
                                     HValue* capacity);
1812

1813 1814 1815
  // Build allocation and header initialization code for respective successor
  // of FixedArrayBase.
  HValue* BuildAllocateAndInitializeArray(ElementsKind kind, HValue* capacity);
1816

1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
  // |array| must have been allocated with enough room for
  // 1) the JSArray and 2) an AllocationMemento if mode requires it.
  // If the |elements| value provided is NULL then the array elements storage
  // is initialized with empty array.
  void BuildJSArrayHeader(HValue* array,
                          HValue* array_map,
                          HValue* elements,
                          AllocationSiteMode mode,
                          ElementsKind elements_kind,
                          HValue* allocation_site_payload,
                          HValue* length_field);
1828

1829 1830 1831
  HValue* BuildGrowElementsCapacity(HValue* object,
                                    HValue* elements,
                                    ElementsKind kind,
1832
                                    ElementsKind new_kind,
1833
                                    HValue* length,
1834
                                    HValue* new_capacity);
1835

1836 1837 1838 1839 1840 1841
  void BuildFillElementsWithValue(HValue* elements,
                                  ElementsKind elements_kind,
                                  HValue* from,
                                  HValue* to,
                                  HValue* value);

1842
  void BuildFillElementsWithHole(HValue* elements,
1843 1844
                                 ElementsKind elements_kind,
                                 HValue* from,
1845
                                 HValue* to);
1846

1847 1848 1849
  void BuildCopyProperties(HValue* from_properties, HValue* to_properties,
                           HValue* length, HValue* capacity);

1850
  void BuildCopyElements(HValue* from_elements,
1851 1852 1853
                         ElementsKind from_elements_kind,
                         HValue* to_elements,
                         ElementsKind to_elements_kind,
1854
                         HValue* length,
1855
                         HValue* capacity);
1856

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
  HValue* BuildCloneShallowArrayCow(HValue* boilerplate,
                                    HValue* allocation_site,
                                    AllocationSiteMode mode,
                                    ElementsKind kind);

  HValue* BuildCloneShallowArrayEmpty(HValue* boilerplate,
                                      HValue* allocation_site,
                                      AllocationSiteMode mode);

  HValue* BuildCloneShallowArrayNonEmpty(HValue* boilerplate,
                                         HValue* allocation_site,
                                         AllocationSiteMode mode,
                                         ElementsKind kind);
1870

1871 1872
  HValue* BuildElementIndexHash(HValue* index);

1873 1874 1875 1876
  enum MapEmbedding { kEmbedMapsDirectly, kEmbedMapsViaWeakCells };

  void BuildCompareNil(HValue* value, Type* type, HIfContinuation* continuation,
                       MapEmbedding map_embedding = kEmbedMapsDirectly);
1877

1878 1879 1880
  void BuildCreateAllocationMemento(HValue* previous_object,
                                    HValue* previous_object_size,
                                    HValue* payload);
1881

1882
  HInstruction* BuildConstantMapCheck(Handle<JSObject> constant);
1883 1884
  HInstruction* BuildCheckPrototypeMaps(Handle<JSObject> prototype,
                                        Handle<JSObject> holder);
1885

1886
  HInstruction* BuildGetNativeContext(HValue* closure);
1887
  HInstruction* BuildGetNativeContext();
1888
  HInstruction* BuildGetScriptContext(int context_index);
1889
  HInstruction* BuildGetArrayFunction();
1890

1891 1892
 protected:
  void SetSourcePosition(int position) {
1893
    DCHECK(position != RelocInfo::kNoPosition);
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
    position_.set_position(position - start_position_);
  }

  void EnterInlinedSource(int start_position, int id) {
    if (FLAG_hydrogen_track_positions) {
      start_position_ = start_position;
      position_.set_inlining_id(id);
    }
  }

  // Convert the given absolute offset from the start of the script to
  // the HSourcePosition assuming that this position corresponds to the
  // same function as current position_.
  HSourcePosition ScriptPositionToSourcePosition(int position) {
    HSourcePosition pos = position_;
    pos.set_position(position - start_position_);
    return pos;
  }

  HSourcePosition source_position() { return position_; }
  void set_source_position(HSourcePosition position) {
1915 1916 1917
    position_ = position;
  }

1918 1919 1920 1921 1922 1923
  template <typename ViewClass>
  void BuildArrayBufferViewInitialization(HValue* obj,
                                          HValue* buffer,
                                          HValue* byte_offset,
                                          HValue* byte_length);

1924 1925
 private:
  HGraphBuilder();
1926

1927 1928 1929 1930 1931
  template <class I>
  I* AddInstructionTyped(I* instr) {
    return I::cast(AddInstruction(instr));
  }

1932 1933 1934
  CompilationInfo* info_;
  HGraph* graph_;
  HBasicBlock* current_block_;
1935
  Scope* scope_;
1936 1937
  HSourcePosition position_;
  int start_position_;
1938 1939
};

1940

1941
template <>
1942
inline HDeoptimize* HGraphBuilder::Add<HDeoptimize>(
1943
    Deoptimizer::DeoptReason reason, Deoptimizer::BailoutType type) {
1944 1945 1946 1947 1948
  if (type == Deoptimizer::SOFT) {
    isolate()->counters()->soft_deopts_requested()->Increment();
    if (FLAG_always_opt) return NULL;
  }
  if (current_block()->IsDeoptimizing()) return NULL;
1949 1950 1951
  HBasicBlock* after_deopt_block = CreateBasicBlock(
      current_block()->last_environment());
  HDeoptimize* instr = New<HDeoptimize>(reason, type, after_deopt_block);
1952 1953 1954
  if (type == Deoptimizer::SOFT) {
    isolate()->counters()->soft_deopts_inserted()->Increment();
  }
1955
  FinishCurrentBlock(instr);
1956
  set_current_block(after_deopt_block);
1957 1958 1959 1960
  return instr;
}


1961
template <>
1962
inline HInstruction* HGraphBuilder::AddUncasted<HDeoptimize>(
1963
    Deoptimizer::DeoptReason reason, Deoptimizer::BailoutType type) {
1964
  return Add<HDeoptimize>(reason, type);
1965 1966 1967 1968
}


template<>
1969
inline HSimulate* HGraphBuilder::Add<HSimulate>(
1970 1971
    BailoutId id,
    RemovableSimulate removable) {
1972 1973 1974 1975 1976 1977
  HSimulate* instr = current_block()->CreateSimulate(id, removable);
  AddInstruction(instr);
  return instr;
}


1978 1979 1980 1981 1982 1983 1984
template<>
inline HSimulate* HGraphBuilder::Add<HSimulate>(
    BailoutId id) {
  return Add<HSimulate>(id, FIXED_SIMULATE);
}


1985 1986
template<>
inline HInstruction* HGraphBuilder::AddUncasted<HSimulate>(BailoutId id) {
1987
  return Add<HSimulate>(id, FIXED_SIMULATE);
1988 1989 1990 1991
}


template<>
1992
inline HReturn* HGraphBuilder::Add<HReturn>(HValue* value) {
1993
  int num_parameters = graph()->info()->num_parameters();
1994 1995
  HValue* params = AddUncasted<HConstant>(num_parameters);
  HReturn* return_instruction = New<HReturn>(value, params);
1996
  FinishExitCurrentBlock(return_instruction);
1997 1998 1999 2000
  return return_instruction;
}


2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
template<>
inline HReturn* HGraphBuilder::Add<HReturn>(HConstant* value) {
  return Add<HReturn>(static_cast<HValue*>(value));
}

template<>
inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HValue* value) {
  return Add<HReturn>(value);
}


2012
template<>
2013
inline HInstruction* HGraphBuilder::AddUncasted<HReturn>(HConstant* value) {
2014
  return Add<HReturn>(value);
2015 2016 2017
}


2018
template<>
2019
inline HCallRuntime* HGraphBuilder::Add<HCallRuntime>(
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
    Handle<String> name,
    const Runtime::Function* c_function,
    int argument_count) {
  HCallRuntime* instr = New<HCallRuntime>(name, c_function, argument_count);
  if (graph()->info()->IsStub()) {
    // When compiling code stubs, we don't want to save all double registers
    // upon entry to the stub, but instead have the call runtime instruction
    // save the double registers only on-demand (in the fallback case).
    instr->set_save_doubles(kSaveFPRegs);
  }
  AddInstruction(instr);
  return instr;
}


2035
template<>
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
inline HInstruction* HGraphBuilder::AddUncasted<HCallRuntime>(
    Handle<String> name,
    const Runtime::Function* c_function,
    int argument_count) {
  return Add<HCallRuntime>(name, c_function, argument_count);
}


template<>
inline HContext* HGraphBuilder::New<HContext>() {
2046
  return HContext::New(zone());
2047 2048 2049
}


2050 2051 2052 2053 2054
template<>
inline HInstruction* HGraphBuilder::NewUncasted<HContext>() {
  return New<HContext>();
}

2055
class HOptimizedGraphBuilder : public HGraphBuilder, public AstVisitor {
2056
 public:
2057 2058 2059
  // A class encapsulating (lazily-allocated) break and continue blocks for
  // a breakable statement.  Separated from BreakAndContinueScope so that it
  // can have a separate lifetime.
2060
  class BreakAndContinueInfo FINAL BASE_EMBEDDED {
2061
   public:
2062
    explicit BreakAndContinueInfo(BreakableStatement* target,
2063
                                  Scope* scope,
2064 2065 2066 2067
                                  int drop_extra = 0)
        : target_(target),
          break_block_(NULL),
          continue_block_(NULL),
2068
          scope_(scope),
2069
          drop_extra_(drop_extra) {
2070 2071 2072 2073 2074 2075 2076
    }

    BreakableStatement* target() { return target_; }
    HBasicBlock* break_block() { return break_block_; }
    void set_break_block(HBasicBlock* block) { break_block_ = block; }
    HBasicBlock* continue_block() { return continue_block_; }
    void set_continue_block(HBasicBlock* block) { continue_block_ = block; }
2077
    Scope* scope() { return scope_; }
2078
    int drop_extra() { return drop_extra_; }
2079 2080 2081 2082 2083

   private:
    BreakableStatement* target_;
    HBasicBlock* break_block_;
    HBasicBlock* continue_block_;
2084
    Scope* scope_;
2085
    int drop_extra_;
2086 2087 2088 2089
  };

  // A helper class to maintain a stack of current BreakAndContinueInfo
  // structures mirroring BreakableStatement nesting.
2090
  class BreakAndContinueScope FINAL BASE_EMBEDDED {
2091
   public:
2092 2093
    BreakAndContinueScope(BreakAndContinueInfo* info,
                          HOptimizedGraphBuilder* owner)
2094 2095 2096 2097 2098 2099 2100
        : info_(info), owner_(owner), next_(owner->break_scope()) {
      owner->set_break_scope(this);
    }

    ~BreakAndContinueScope() { owner_->set_break_scope(next_); }

    BreakAndContinueInfo* info() { return info_; }
2101
    HOptimizedGraphBuilder* owner() { return owner_; }
2102 2103 2104
    BreakAndContinueScope* next() { return next_; }

    // Search the break stack for a break or continue target.
2105
    enum BreakType { BREAK, CONTINUE };
2106 2107
    HBasicBlock* Get(BreakableStatement* stmt, BreakType type,
                     Scope** scope, int* drop_extra);
2108 2109 2110

   private:
    BreakAndContinueInfo* info_;
2111
    HOptimizedGraphBuilder* owner_;
2112 2113 2114
    BreakAndContinueScope* next_;
  };

2115
  explicit HOptimizedGraphBuilder(CompilationInfo* info);
2116

2117
  bool BuildGraph() OVERRIDE;
2118

2119
  // Simple accessors.
2120 2121
  BreakAndContinueScope* break_scope() const { return break_scope_; }
  void set_break_scope(BreakAndContinueScope* head) { break_scope_ = head; }
2122

2123
  HValue* context() OVERRIDE { return environment()->context(); }
2124

2125 2126
  HOsrBuilder* osr() const { return osr_; }

2127
  void Bailout(BailoutReason reason);
2128

2129 2130
  HBasicBlock* CreateJoin(HBasicBlock* first,
                          HBasicBlock* second,
2131
                          BailoutId join_id);
2132

2133 2134
  FunctionState* function_state() const { return function_state_; }

2135
  void VisitDeclarations(ZoneList<Declaration*>* declarations) OVERRIDE;
2136

2137
  void* operator new(size_t size, Zone* zone) {
2138
    return zone->New(static_cast<int>(size));
2139
  }
2140
  void operator delete(void* pointer, Zone* zone) { }
2141
  void operator delete(void* pointer) { }
2142

2143 2144
  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();

2145
 protected:
2146
  // Type of a member function that generates inline code for a native function.
2147 2148
  typedef void (HOptimizedGraphBuilder::*InlineFunctionGenerator)
      (CallRuntime* call);
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158

  // Forward declarations for inner scope classes.
  class SubgraphScope;

  static const InlineFunctionGenerator kInlineFunctionGenerators[];

  static const int kMaxCallPolymorphism = 4;
  static const int kMaxLoadPolymorphism = 4;
  static const int kMaxStorePolymorphism = 4;

2159 2160
  // Even in the 'unlimited' case we have to have some limit in order not to
  // overflow the stack.
2161 2162 2163
  static const int kUnlimitedMaxInlinedSourceSize = 100000;
  static const int kUnlimitedMaxInlinedNodes = 10000;
  static const int kUnlimitedMaxInlinedNodesCumulative = 10000;
2164

2165 2166 2167 2168 2169
  // Maximum depth and total number of elements and properties for literal
  // graphs to be considered for fast deep-copying.
  static const int kMaxFastLiteralDepth = 3;
  static const int kMaxFastLiteralProperties = 8;

2170
  // Simple accessors.
2171 2172
  void set_function_state(FunctionState* state) { function_state_ = state; }

2173 2174
  AstContext* ast_context() const { return ast_context_; }
  void set_ast_context(AstContext* context) { ast_context_ = context; }
2175 2176

  // Accessors forwarded to the function state.
2177
  CompilationInfo* current_info() const {
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
    return function_state()->compilation_info();
  }
  AstContext* call_context() const {
    return function_state()->call_context();
  }
  HBasicBlock* function_return() const {
    return function_state()->function_return();
  }
  TestContext* inlined_test_context() const {
    return function_state()->test_context();
  }
  void ClearInlinedTestContext() {
    function_state()->ClearInlinedTestContext();
  }
2192 2193
  LanguageMode function_language_mode() {
    return function_state()->compilation_info()->language_mode();
mmaly@chromium.org's avatar
mmaly@chromium.org committed
2194
  }
2195 2196

  // Generators for inline runtime functions.
2197
#define INLINE_FUNCTION_GENERATOR_DECLARATION(Name, argc, ressize)      \
2198
  void Generate##Name(CallRuntime* call);
2199 2200

  INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_DECLARATION)
2201
  INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_DECLARATION)
2202 2203
#undef INLINE_FUNCTION_GENERATOR_DECLARATION

2204 2205 2206 2207 2208 2209
  void VisitDelete(UnaryOperation* expr);
  void VisitVoid(UnaryOperation* expr);
  void VisitTypeof(UnaryOperation* expr);
  void VisitNot(UnaryOperation* expr);

  void VisitComma(BinaryOperation* expr);
2210 2211
  void VisitLogicalExpression(BinaryOperation* expr);
  void VisitArithmeticExpression(BinaryOperation* expr);
2212

2213
  void VisitLoopBody(IterationStatement* stmt,
2214
                     HBasicBlock* loop_entry);
2215

2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
  // Create a back edge in the flow graph.  body_exit is the predecessor
  // block and loop_entry is the successor block.  loop_successor is the
  // block where control flow exits the loop normally (e.g., via failure of
  // the condition) and break_block is the block where control flow breaks
  // from the loop.  All blocks except loop_entry can be NULL.  The return
  // value is the new successor block which is the join of loop_successor
  // and break_block, or NULL.
  HBasicBlock* CreateLoop(IterationStatement* statement,
                          HBasicBlock* loop_entry,
                          HBasicBlock* body_exit,
                          HBasicBlock* loop_successor,
                          HBasicBlock* break_block);

2229 2230 2231 2232 2233 2234
  // Build a loop entry
  HBasicBlock* BuildLoopEntry();

  // Builds a loop entry respectful of OSR requirements
  HBasicBlock* BuildLoopEntry(IterationStatement* statement);

2235 2236 2237 2238
  HBasicBlock* JoinContinue(IterationStatement* statement,
                            HBasicBlock* exit_block,
                            HBasicBlock* continue_block);

2239 2240 2241
  HValue* Top() const { return environment()->Top(); }
  void Drop(int n) { environment()->Drop(n); }
  void Bind(Variable* var, HValue* value) { environment()->Bind(var, value); }
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
  bool IsEligibleForEnvironmentLivenessAnalysis(Variable* var,
                                                int index,
                                                HValue* value,
                                                HEnvironment* env) {
    if (!FLAG_analyze_environment_liveness) return false;
    // |this| and |arguments| are always live; zapping parameters isn't
    // safe because function.arguments can inspect them at any time.
    return !var->is_this() &&
           !var->is_arguments() &&
           !value->IsArgumentsObject() &&
           env->is_local_index(index);
  }
  void BindIfLive(Variable* var, HValue* value) {
    HEnvironment* env = environment();
    int index = env->IndexFor(var);
    env->Bind(index, value);
    if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
      HEnvironmentMarker* bind =
2260 2261
          Add<HEnvironmentMarker>(HEnvironmentMarker::BIND, index);
      USE(bind);
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
#ifdef DEBUG
      bind->set_closure(env->closure());
#endif
    }
  }
  HValue* LookupAndMakeLive(Variable* var) {
    HEnvironment* env = environment();
    int index = env->IndexFor(var);
    HValue* value = env->Lookup(index);
    if (IsEligibleForEnvironmentLivenessAnalysis(var, index, value, env)) {
      HEnvironmentMarker* lookup =
2273 2274
          Add<HEnvironmentMarker>(HEnvironmentMarker::LOOKUP, index);
      USE(lookup);
2275 2276 2277 2278 2279 2280
#ifdef DEBUG
      lookup->set_closure(env->closure());
#endif
    }
    return value;
  }
2281

2282 2283 2284 2285 2286
  // The value of the arguments object is allowed in some but not most value
  // contexts.  (It's allowed in all effect contexts and disallowed in all
  // test contexts.)
  void VisitForValue(Expression* expr,
                     ArgumentsAllowedFlag flag = ARGUMENTS_NOT_ALLOWED);
2287
  void VisitForTypeOf(Expression* expr);
2288 2289 2290
  void VisitForEffect(Expression* expr);
  void VisitForControl(Expression* expr,
                       HBasicBlock* true_block,
2291 2292
                       HBasicBlock* false_block);

2293
  // Visit a list of expressions from left to right, each in a value context.
2294
  void VisitExpressions(ZoneList<Expression*>* exprs) OVERRIDE;
2295 2296
  void VisitExpressions(ZoneList<Expression*>* exprs,
                        ArgumentsAllowedFlag flag);
2297

2298 2299
  // Remove the arguments from the bailout environment and emit instructions
  // to push them as outgoing parameters.
2300
  template <class Instruction> HInstruction* PreProcessCall(Instruction* call);
2301
  void PushArgumentsFromEnvironment(int count);
2302

2303
  void SetUpScope(Scope* scope);
2304
  void VisitStatements(ZoneList<Statement*>* statements) OVERRIDE;
2305

2306
#define DECLARE_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
2307 2308 2309
  AST_NODE_LIST(DECLARE_VISIT)
#undef DECLARE_VISIT

2310
  Type* ToType(Handle<Map> map);
2311

2312
 private:
2313
  // Helpers for flow graph construction.
2314 2315 2316 2317
  enum GlobalPropertyAccess {
    kUseCell,
    kUseGeneric
  };
2318
  GlobalPropertyAccess LookupGlobalProperty(Variable* var, LookupIterator* it,
2319
                                            PropertyAccessType access_type);
2320

2321
  void EnsureArgumentsArePushedForAccess();
2322
  bool TryArgumentsAccess(Property* expr);
2323

2324 2325 2326 2327 2328 2329 2330
  // Shared code for .call and .apply optimizations.
  void HandleIndirectCall(Call* expr, HValue* function, int arguments_count);
  // Try to optimize indirect calls such as fun.apply(receiver, arguments)
  // or fun.call(...).
  bool TryIndirectCall(Call* expr);
  void BuildFunctionApply(Call* expr);
  void BuildFunctionCall(Call* expr);
2331

2332 2333 2334 2335 2336
  bool TryHandleArrayCall(Call* expr, HValue* function);
  bool TryHandleArrayCallNew(CallNew* expr, HValue* function);
  void BuildArrayCall(Expression* expr, int arguments_count, HValue* function,
                      Handle<AllocationSite> cell);

2337 2338 2339 2340 2341 2342
  enum ArrayIndexOfMode { kFirstIndexOf, kLastIndexOf };
  HValue* BuildArrayIndexOf(HValue* receiver,
                            HValue* search_element,
                            ElementsKind kind,
                            ArrayIndexOfMode mode);

2343 2344 2345
  HValue* ImplicitReceiverFor(HValue* function,
                              Handle<JSFunction> target);

2346
  int InliningAstSize(Handle<JSFunction> target);
2347
  bool TryInline(Handle<JSFunction> target,
2348
                 int arguments_count,
2349
                 HValue* implicit_return_value,
2350 2351
                 BailoutId ast_id,
                 BailoutId return_id,
2352 2353
                 InliningKind inlining_kind,
                 HSourcePosition position);
2354

verwaest@chromium.org's avatar
verwaest@chromium.org committed
2355
  bool TryInlineCall(Call* expr);
2356
  bool TryInlineConstruct(CallNew* expr, HValue* implicit_return_value);
2357
  bool TryInlineGetter(Handle<JSFunction> getter,
2358
                       Handle<Map> receiver_map,
2359 2360
                       BailoutId ast_id,
                       BailoutId return_id);
2361
  bool TryInlineSetter(Handle<JSFunction> setter,
2362
                       Handle<Map> receiver_map,
2363 2364
                       BailoutId id,
                       BailoutId assignment_id,
2365
                       HValue* implicit_return_value);
2366 2367 2368 2369 2370
  bool TryInlineIndirectCall(Handle<JSFunction> function, Call* expr,
                             int arguments_count);
  bool TryInlineBuiltinMethodCall(Call* expr, Handle<JSFunction> function,
                                  Handle<Map> receiver_map,
                                  int args_count_no_receiver);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2371
  bool TryInlineBuiltinFunctionCall(Call* expr);
2372 2373 2374
  enum ApiCallType {
    kCallApiFunction,
    kCallApiMethod,
2375 2376
    kCallApiGetter,
    kCallApiSetter
2377
  };
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2378 2379
  bool TryInlineApiMethodCall(Call* expr,
                              HValue* receiver,
2380
                              SmallMapList* receiver_types);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2381
  bool TryInlineApiFunctionCall(Call* expr, HValue* receiver);
2382 2383 2384
  bool TryInlineApiGetter(Handle<JSFunction> function,
                          Handle<Map> receiver_map,
                          BailoutId ast_id);
2385 2386 2387
  bool TryInlineApiSetter(Handle<JSFunction> function,
                          Handle<Map> receiver_map,
                          BailoutId ast_id);
2388 2389 2390 2391 2392 2393
  bool TryInlineApiCall(Handle<JSFunction> function,
                         HValue* receiver,
                         SmallMapList* receiver_maps,
                         int argc,
                         BailoutId ast_id,
                         ApiCallType call_type);
2394
  static bool CanInlineArrayResizeOperation(Handle<Map> receiver_map);
2395 2396 2397 2398

  // If --trace-inlining, print a line of the inlining trace.  Inlining
  // succeeded if the reason string is NULL and failed if there is a
  // non-NULL reason string.
2399 2400 2401
  void TraceInline(Handle<JSFunction> target,
                   Handle<JSFunction> caller,
                   const char* failure_reason);
2402

2403
  void HandleGlobalVariableAssignment(Variable* var,
2404
                                      HValue* value,
2405
                                      BailoutId ast_id);
2406

2407 2408
  void HandlePropertyAssignment(Assignment* expr);
  void HandleCompoundAssignment(Assignment* expr);
2409
  void HandlePolymorphicNamedFieldAccess(PropertyAccessType access_type,
2410
                                         Expression* expr,
2411 2412 2413 2414 2415 2416
                                         BailoutId ast_id,
                                         BailoutId return_id,
                                         HValue* object,
                                         HValue* value,
                                         SmallMapList* types,
                                         Handle<String> name);
2417

2418 2419 2420 2421 2422 2423 2424 2425 2426
  HValue* BuildAllocateExternalElements(
      ExternalArrayType array_type,
      bool is_zero_byte_offset,
      HValue* buffer, HValue* byte_offset, HValue* length);
  HValue* BuildAllocateFixedTypedArray(
      ExternalArrayType array_type, size_t element_size,
      ElementsKind fixed_elements_kind,
      HValue* byte_length, HValue* length);

2427 2428 2429 2430 2431 2432 2433
  // TODO(adamk): Move all OrderedHashTable functions to their own class.
  HValue* BuildOrderedHashTableHashToBucket(HValue* hash, HValue* num_buckets);
  template <typename CollectionType>
  HValue* BuildOrderedHashTableHashToEntry(HValue* table, HValue* hash,
                                           HValue* num_buckets);
  template <typename CollectionType>
  HValue* BuildOrderedHashTableEntryToIndex(HValue* entry, HValue* num_buckets);
2434 2435 2436
  template <typename CollectionType>
  HValue* BuildOrderedHashTableFindEntry(HValue* table, HValue* key,
                                         HValue* hash);
2437 2438 2439 2440 2441
  template <typename CollectionType>
  HValue* BuildOrderedHashTableAddEntry(HValue* table, HValue* key,
                                        HValue* hash,
                                        HIfContinuation* join_continuation);
  template <typename CollectionType>
2442 2443
  HValue* BuildAllocateOrderedHashTable();
  template <typename CollectionType>
2444 2445
  void BuildOrderedHashTableClear(HValue* receiver);
  template <typename CollectionType>
2446 2447
  void BuildJSCollectionDelete(CallRuntime* call,
                               const Runtime::Function* c_function);
2448 2449 2450 2451 2452 2453
  template <typename CollectionType>
  void BuildJSCollectionHas(CallRuntime* call,
                            const Runtime::Function* c_function);
  HValue* BuildStringHashLoadIfIsStringAndHashComputed(
      HValue* object, HIfContinuation* continuation);

2454 2455 2456 2457 2458 2459 2460
  Handle<JSFunction> array_function() {
    return handle(isolate()->native_context()->array_function());
  }

  bool IsCallArrayInlineable(int argument_count, Handle<AllocationSite> site);
  void BuildInlinedCallArray(Expression* expression, int argument_count,
                             Handle<AllocationSite> site);
2461

2462 2463
  class PropertyAccessInfo {
   public:
2464
    PropertyAccessInfo(HOptimizedGraphBuilder* builder,
2465
                       PropertyAccessType access_type,
2466
                       Type* type,
2467 2468 2469
                       Handle<String> name)
        : lookup_(builder->isolate()),
          builder_(builder),
2470
          access_type_(access_type),
2471
          type_(type),
2472
          name_(name),
2473
          field_type_(HType::Tagged()),
2474 2475 2476 2477 2478
          access_(HObjectAccess::ForMap()) { }

    // Checkes whether this PropertyAccessInfo can be handled as a monomorphic
    // load named. It additionally fills in the fields necessary to generate the
    // lookup code.
2479
    bool CanAccessMonomorphic();
2480 2481 2482 2483 2484 2485 2486

    // Checks whether all types behave uniform when loading name. If all maps
    // behave the same, a single monomorphic load instruction can be emitted,
    // guarded by a single map-checks instruction that whether the receiver is
    // an instance of any of the types.
    // This method skips the first type in types, assuming that this
    // PropertyAccessInfo is built for types->first().
2487
    bool CanAccessAsMonomorphic(SmallMapList* types);
2488

2489
    Handle<Map> map();
2490
    Type* type() const { return type_; }
2491 2492
    Handle<String> name() const { return name_; }

2493 2494
    bool IsJSObjectFieldAccessor() {
      int offset;  // unused
2495
      return Accessors::IsJSObjectFieldAccessor<Type>(type_, name_, &offset);
2496 2497
    }

2498
    bool GetJSObjectFieldAccess(HObjectAccess* access) {
2499
      int offset;
2500 2501
      if (Accessors::IsJSObjectFieldAccessor<Type>(type_, name_, &offset)) {
        if (type_->Is(Type::String())) {
2502
          DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2503
          *access = HObjectAccess::ForStringLength();
2504
        } else if (type_->Is(Type::Array())) {
2505
          DCHECK(String::Equals(isolate()->factory()->length_string(), name_));
2506
          *access = HObjectAccess::ForArrayLength(map()->elements_kind());
2507
        } else {
2508
          *access = HObjectAccess::ForMapAndOffset(map(), offset);
2509
        }
2510
        return true;
2511
      }
2512
      return false;
2513 2514
    }

2515
    bool has_holder() { return !holder_.is_null(); }
2516
    bool IsLoad() const { return access_type_ == LOAD; }
2517

2518
    Isolate* isolate() const { return lookup_.isolate(); }
2519 2520 2521
    Handle<JSObject> holder() { return holder_; }
    Handle<JSFunction> accessor() { return accessor_; }
    Handle<Object> constant() { return constant_; }
2522
    Handle<Map> transition() { return handle(lookup_.GetTransitionTarget()); }
2523
    SmallMapList* field_maps() { return &field_maps_; }
2524
    HType field_type() const { return field_type_; }
2525 2526
    HObjectAccess access() { return access_; }

2527 2528
    bool IsFound() const { return lookup_.IsFound(); }
    bool IsProperty() const { return lookup_.IsProperty(); }
2529 2530 2531
    bool IsData() const { return lookup_.IsData(); }
    bool IsDataConstant() const { return lookup_.IsDataConstant(); }
    bool IsAccessorConstant() const { return lookup_.IsAccessorConstant(); }
2532 2533
    bool IsTransition() const { return lookup_.IsTransition(); }

2534
    bool IsConfigurable() const { return lookup_.IsConfigurable(); }
2535 2536
    bool IsReadOnly() const { return lookup_.IsReadOnly(); }

2537
   private:
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
    Handle<Object> GetAccessorsFromMap(Handle<Map> map) const {
      return handle(lookup_.GetValueFromMap(*map), isolate());
    }
    Handle<Object> GetConstantFromMap(Handle<Map> map) const {
      return handle(lookup_.GetConstantFromMap(*map), isolate());
    }
    Handle<HeapType> GetFieldTypeFromMap(Handle<Map> map) const {
      return handle(lookup_.GetFieldTypeFromMap(*map), isolate());
    }
    Handle<Map> GetFieldOwnerFromMap(Handle<Map> map) const {
      return handle(lookup_.GetFieldOwnerFromMap(*map));
    }
    int GetLocalFieldIndexFromMap(Handle<Map> map) const {
      return lookup_.GetLocalFieldIndexFromMap(*map);
    }
    Representation representation() const { return lookup_.representation(); }

2555
    Type* ToType(Handle<Map> map) { return builder_->ToType(map); }
2556
    Zone* zone() { return builder_->zone(); }
2557
    CompilationInfo* top_info() { return builder_->top_info(); }
2558
    CompilationInfo* current_info() { return builder_->current_info(); }
2559

2560
    bool LoadResult(Handle<Map> map);
2561
    void LoadFieldMaps(Handle<Map> map);
2562 2563
    bool LookupDescriptor();
    bool LookupInPrototypes();
2564
    bool IsCompatible(PropertyAccessInfo* other);
2565 2566 2567 2568 2569 2570 2571

    void GeneralizeRepresentation(Representation r) {
      access_ = access_.WithRepresentation(
          access_.representation().generalize(r));
    }

    LookupResult lookup_;
2572
    HOptimizedGraphBuilder* builder_;
2573
    PropertyAccessType access_type_;
2574
    Type* type_;
2575 2576 2577
    Handle<String> name_;
    Handle<JSObject> holder_;
    Handle<JSFunction> accessor_;
2578
    Handle<JSObject> api_holder_;
2579
    Handle<Object> constant_;
2580
    SmallMapList field_maps_;
2581
    HType field_type_;
2582 2583 2584
    HObjectAccess access_;
  };

2585 2586 2587 2588 2589 2590 2591
  HInstruction* BuildMonomorphicAccess(PropertyAccessInfo* info,
                                       HValue* object,
                                       HValue* checked_object,
                                       HValue* value,
                                       BailoutId ast_id,
                                       BailoutId return_id,
                                       bool can_inline_accessor = true);
2592

2593 2594 2595 2596 2597 2598 2599 2600 2601
  HInstruction* BuildNamedAccess(PropertyAccessType access,
                                 BailoutId ast_id,
                                 BailoutId reutrn_id,
                                 Expression* expr,
                                 HValue* object,
                                 Handle<String> name,
                                 HValue* value,
                                 bool is_uninitialized = false);

2602 2603
  void HandlePolymorphicCallNamed(Call* expr,
                                  HValue* receiver,
2604
                                  SmallMapList* types,
2605
                                  Handle<String> name);
2606
  void HandleLiteralCompareTypeof(CompareOperation* expr,
2607
                                  Expression* sub_expr,
2608
                                  Handle<String> check);
2609
  void HandleLiteralCompareNil(CompareOperation* expr,
2610
                               Expression* sub_expr,
2611
                               NilValue nil);
2612 2613 2614 2615 2616

  enum PushBeforeSimulateBehavior {
    PUSH_BEFORE_SIMULATE,
    NO_PUSH_BEFORE_SIMULATE
  };
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632

  HControlInstruction* BuildCompareInstruction(
      Token::Value op,
      HValue* left,
      HValue* right,
      Type* left_type,
      Type* right_type,
      Type* combined_type,
      HSourcePosition left_position,
      HSourcePosition right_position,
      PushBeforeSimulateBehavior push_sim_result,
      BailoutId bailout_id);

  HInstruction* BuildStringCharCodeAt(HValue* string,
                                      HValue* index);

2633 2634 2635 2636 2637
  HValue* BuildBinaryOperation(
      BinaryOperation* expr,
      HValue* left,
      HValue* right,
      PushBeforeSimulateBehavior push_sim_result);
2638
  HInstruction* BuildIncrement(bool returns_original_input,
2639
                               CountOperation* expr);
2640
  HInstruction* BuildKeyedGeneric(PropertyAccessType access_type,
2641
                                  Expression* expr,
2642 2643 2644
                                  HValue* object,
                                  HValue* key,
                                  HValue* value);
2645

2646 2647 2648 2649 2650
  HInstruction* TryBuildConsolidatedElementLoad(HValue* object,
                                                HValue* key,
                                                HValue* val,
                                                SmallMapList* maps);

2651 2652
  LoadKeyedHoleMode BuildKeyedHoleMode(Handle<Map> map);

2653 2654 2655
  HInstruction* BuildMonomorphicElementAccess(HValue* object,
                                              HValue* key,
                                              HValue* val,
2656
                                              HValue* dependency,
2657
                                              Handle<Map> map,
2658
                                              PropertyAccessType access_type,
2659
                                              KeyedAccessStoreMode store_mode);
2660

2661 2662
  HValue* HandlePolymorphicElementAccess(Expression* expr,
                                         HValue* object,
2663 2664
                                         HValue* key,
                                         HValue* val,
2665
                                         SmallMapList* maps,
2666
                                         PropertyAccessType access_type,
2667
                                         KeyedAccessStoreMode store_mode,
2668 2669
                                         bool* has_side_effects);

2670
  HValue* HandleKeyedElementAccess(HValue* obj, HValue* key, HValue* val,
2671 2672
                                   Expression* expr, BailoutId ast_id,
                                   BailoutId return_id,
2673
                                   PropertyAccessType access_type,
2674
                                   bool* has_side_effects);
2675

2676
  HInstruction* BuildNamedGeneric(PropertyAccessType access,
2677
                                  Expression* expr,
2678 2679 2680 2681
                                  HValue* object,
                                  Handle<String> name,
                                  HValue* value,
                                  bool is_uninitialized = false);
2682

2683
  HCheckMaps* AddCheckMap(HValue* object, Handle<Map> map);
2684

2685
  void BuildLoad(Property* property,
2686
                 BailoutId ast_id);
2687 2688
  void PushLoad(Property* property,
                HValue* object,
2689
                HValue* key);
2690

2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
  void BuildStoreForEffect(Expression* expression,
                           Property* prop,
                           BailoutId ast_id,
                           BailoutId return_id,
                           HValue* object,
                           HValue* key,
                           HValue* value);

  void BuildStore(Expression* expression,
                  Property* prop,
                  BailoutId ast_id,
                  BailoutId return_id,
                  bool is_uninitialized = false);
2704

2705 2706
  HInstruction* BuildLoadNamedField(PropertyAccessInfo* info,
                                    HValue* checked_object);
2707 2708 2709
  HInstruction* BuildStoreNamedField(PropertyAccessInfo* info,
                                     HValue* checked_object,
                                     HValue* value);
2710

2711 2712
  HValue* BuildContextChainWalk(Variable* var);

2713 2714
  HInstruction* BuildThisFunction();

2715
  HInstruction* BuildFastLiteral(Handle<JSObject> boilerplate_object,
2716
                                 AllocationSiteUsageContext* site_context);
2717

2718 2719 2720 2721 2722 2723
  void BuildEmitObjectHeader(Handle<JSObject> boilerplate_object,
                             HInstruction* object);

  void BuildInitElementsInObjectHeader(Handle<JSObject> boilerplate_object,
                                       HInstruction* object,
                                       HInstruction* object_elements);
2724

2725
  void BuildEmitInObjectProperties(Handle<JSObject> boilerplate_object,
2726
                                   HInstruction* object,
2727 2728
                                   AllocationSiteUsageContext* site_context,
                                   PretenureFlag pretenure_flag);
2729 2730 2731

  void BuildEmitElements(Handle<JSObject> boilerplate_object,
                         Handle<FixedArrayBase> elements,
2732
                         HValue* object_elements,
2733
                         AllocationSiteUsageContext* site_context);
2734 2735 2736 2737 2738 2739 2740

  void BuildEmitFixedDoubleArray(Handle<FixedArrayBase> elements,
                                 ElementsKind kind,
                                 HValue* object_elements);

  void BuildEmitFixedArray(Handle<FixedArrayBase> elements,
                           ElementsKind kind,
2741
                           HValue* object_elements,
2742
                           AllocationSiteUsageContext* site_context);
2743

2744 2745 2746
  void AddCheckPrototypeMaps(Handle<JSObject> holder,
                             Handle<Map> receiver_map);

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
  HInstruction* NewPlainFunctionCall(HValue* fun,
                                     int argument_count,
                                     bool pass_argument_count);

  HInstruction* NewArgumentAdaptorCall(HValue* fun, HValue* context,
                                       int argument_count,
                                       HValue* expected_param_count);

  HInstruction* BuildCallConstantFunction(Handle<JSFunction> target,
                                          int argument_count);

2758 2759
  bool CanBeFunctionApplyArguments(Call* expr);

2760 2761 2762 2763 2764 2765
  // The translation state of the currently-being-translated function.
  FunctionState* function_state_;

  // The base of the function state stack.
  FunctionState initial_function_state_;

2766 2767 2768 2769
  // Expression context of the currently visited subexpression. NULL when
  // visiting statements.
  AstContext* ast_context_;

2770 2771
  // A stack of breakable statements entered.
  BreakAndContinueScope* break_scope_;
2772 2773

  int inlined_count_;
2774
  ZoneList<Handle<Object> > globals_;
2775

2776 2777
  bool inline_bailout_;

2778 2779
  HOsrBuilder* osr_;

2780
  friend class FunctionState;  // Pushes and pops the state stack.
2781
  friend class AstContext;  // Pushes and pops the AST context stack.
2782
  friend class KeyedLoadFastElementStub;
2783
  friend class HOsrBuilder;
2784

2785
  DISALLOW_COPY_AND_ASSIGN(HOptimizedGraphBuilder);
2786 2787 2788
};


2789
Zone* AstContext::zone() const { return owner_->zone(); }
2790 2791


2792
class HStatistics FINAL: public Malloced {
2793
 public:
2794
  HStatistics()
2795
      : times_(5),
2796 2797 2798 2799 2800
        names_(5),
        sizes_(5),
        total_size_(0),
        source_size_(0) { }

2801
  void Initialize(CompilationInfo* info);
2802
  void Print();
2803
  void SaveTiming(const char* name, base::TimeDelta time, unsigned size);
2804

2805
  void IncrementFullCodeGen(base::TimeDelta full_code_gen) {
2806 2807 2808
    full_code_gen_ += full_code_gen;
  }

2809 2810 2811 2812 2813 2814 2815 2816
  void IncrementCreateGraph(base::TimeDelta delta) { create_graph_ += delta; }

  void IncrementOptimizeGraph(base::TimeDelta delta) {
    optimize_graph_ += delta;
  }

  void IncrementGenerateCode(base::TimeDelta delta) { generate_code_ += delta; }

2817 2818 2819
  void IncrementSubtotals(base::TimeDelta create_graph,
                          base::TimeDelta optimize_graph,
                          base::TimeDelta generate_code) {
2820 2821 2822
    IncrementCreateGraph(create_graph);
    IncrementOptimizeGraph(optimize_graph);
    IncrementGenerateCode(generate_code);
2823 2824
  }

2825
 private:
2826
  List<base::TimeDelta> times_;
2827
  List<const char*> names_;
2828
  List<unsigned> sizes_;
2829 2830 2831
  base::TimeDelta create_graph_;
  base::TimeDelta optimize_graph_;
  base::TimeDelta generate_code_;
2832
  unsigned total_size_;
2833
  base::TimeDelta full_code_gen_;
2834
  double source_size_;
2835 2836 2837
};


2838
class HPhase : public CompilationPhase {
2839
 public:
2840
  HPhase(const char* name, HGraph* graph)
2841
      : CompilationPhase(name, graph->info()),
2842
        graph_(graph) { }
2843
  ~HPhase();
2844

2845 2846 2847
 protected:
  HGraph* graph() const { return graph_; }

2848 2849
 private:
  HGraph* graph_;
2850 2851

  DISALLOW_COPY_AND_ASSIGN(HPhase);
2852 2853 2854
};


2855
class HTracer FINAL : public Malloced {
2856
 public:
2857 2858
  explicit HTracer(int isolate_id)
      : trace_(&string_allocator_), indent_(0) {
2859
    if (FLAG_trace_hydrogen_file == NULL) {
2860 2861
      SNPrintF(filename_,
               "hydrogen-%d-%d.cfg",
2862
               base::OS::GetCurrentProcessId(),
2863
               isolate_id);
2864
    } else {
2865
      StrNCpy(filename_, FLAG_trace_hydrogen_file, filename_.length());
2866
    }
2867 2868 2869
    WriteChars(filename_.start(), "", 0, false);
  }

2870
  void TraceCompilation(CompilationInfo* info);
2871
  void TraceHydrogen(const char* name, HGraph* graph);
2872
  void TraceLithium(const char* name, LChunk* chunk);
2873 2874 2875
  void TraceLiveRanges(const char* name, LAllocator* allocator);

 private:
2876
  class Tag FINAL BASE_EMBEDDED {
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
   public:
    Tag(HTracer* tracer, const char* name) {
      name_ = name;
      tracer_ = tracer;
      tracer->PrintIndent();
      tracer->trace_.Add("begin_%s\n", name);
      tracer->indent_++;
    }

    ~Tag() {
      tracer_->indent_--;
      tracer_->PrintIndent();
      tracer_->trace_.Add("end_%s\n", name_);
2890
      DCHECK(tracer_->indent_ >= 0);
2891 2892 2893 2894 2895 2896 2897 2898
      tracer_->FlushToFile();
    }

   private:
    HTracer* tracer_;
    const char* name_;
  };

2899
  void TraceLiveRange(LiveRange* range, const char* type, Zone* zone);
2900
  void Trace(const char* name, HGraph* graph, LChunk* chunk);
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
  void FlushToFile();

  void PrintEmptyProperty(const char* name) {
    PrintIndent();
    trace_.Add("%s\n", name);
  }

  void PrintStringProperty(const char* name, const char* value) {
    PrintIndent();
    trace_.Add("%s \"%s\"\n", name, value);
  }

  void PrintLongProperty(const char* name, int64_t value) {
    PrintIndent();
    trace_.Add("%s %d000\n", name, static_cast<int>(value / 1000));
  }

  void PrintBlockProperty(const char* name, int block_id) {
    PrintIndent();
    trace_.Add("%s \"B%d\"\n", name, block_id);
  }

  void PrintIntProperty(const char* name, int value) {
    PrintIndent();
    trace_.Add("%s %d\n", name, value);
  }

  void PrintIndent() {
    for (int i = 0; i < indent_; i++) {
      trace_.Add("  ");
    }
  }

2934
  EmbeddedVector<char, 64> filename_;
2935 2936 2937 2938 2939 2940
  HeapStringAllocator string_allocator_;
  StringStream trace_;
  int indent_;
};


2941
class NoObservableSideEffectsScope FINAL {
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
 public:
  explicit NoObservableSideEffectsScope(HGraphBuilder* builder) :
      builder_(builder) {
    builder_->graph()->IncrementInNoSideEffectsScope();
  }
  ~NoObservableSideEffectsScope() {
    builder_->graph()->DecrementInNoSideEffectsScope();
  }

 private:
  HGraphBuilder* builder_;
};


2956 2957 2958
} }  // namespace v8::internal

#endif  // V8_HYDROGEN_H_