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

5
#include "src/ast.h"
6

7
#include <cmath>  // For isfinite.
8 9 10 11 12 13 14
#include "src/builtins.h"
#include "src/code-stubs.h"
#include "src/contexts.h"
#include "src/conversions.h"
#include "src/hashmap.h"
#include "src/parser.h"
#include "src/property.h"
15
#include "src/property-details.h"
16 17 18
#include "src/scopes.h"
#include "src/string-stream.h"
#include "src/type-info.h"
19

20 21
namespace v8 {
namespace internal {
22 23 24 25

// ----------------------------------------------------------------------------
// All the Accept member functions for each syntax tree node type.

26 27
#define DECL_ACCEPT(type)                                       \
  void type::Accept(AstVisitor* v) { v->Visit##type(this); }
28
AST_NODE_LIST(DECL_ACCEPT)
29 30 31 32 33 34
#undef DECL_ACCEPT


// ----------------------------------------------------------------------------
// Implementation of other node functionality.

35

36
bool Expression::IsSmiLiteral() const {
37
  return IsLiteral() && AsLiteral()->value()->IsSmi();
38 39 40
}


41
bool Expression::IsStringLiteral() const {
42
  return IsLiteral() && AsLiteral()->value()->IsString();
43 44 45
}


46
bool Expression::IsNullLiteral() const {
47
  return IsLiteral() && AsLiteral()->value()->IsNull();
48 49 50
}


51 52
bool Expression::IsUndefinedLiteral(Isolate* isolate) const {
  const VariableProxy* var_proxy = AsVariableProxy();
53 54 55 56 57
  if (var_proxy == NULL) return false;
  Variable* var = var_proxy->var();
  // The global identifier "undefined" is immutable. Everything
  // else could be reassigned.
  return var != NULL && var->location() == Variable::UNALLOCATED &&
58
         var_proxy->raw_name()->IsOneByteEqualTo("undefined");
59 60 61
}


62 63
VariableProxy::VariableProxy(Zone* zone, Variable* var, int position)
    : Expression(zone, position),
64
      name_(var->raw_name()),
65 66
      var_(NULL),  // Will be set by the call to BindTo.
      is_this_(var->is_this()),
67
      is_assigned_(false),
68 69
      interface_(var->interface()),
      variable_feedback_slot_(kInvalidFeedbackSlot) {
70 71 72 73
  BindTo(var);
}


74
VariableProxy::VariableProxy(Zone* zone,
75
                             const AstRawString* name,
76
                             bool is_this,
77 78
                             Interface* interface,
                             int position)
79
    : Expression(zone, position),
80 81 82
      name_(name),
      var_(NULL),
      is_this_(is_this),
83
      is_assigned_(false),
84 85
      interface_(interface),
      variable_feedback_slot_(kInvalidFeedbackSlot) {
86 87 88 89 90 91
}


void VariableProxy::BindTo(Variable* var) {
  ASSERT(var_ == NULL);  // must be bound only once
  ASSERT(var != NULL);  // must bind
92
  ASSERT(!FLAG_harmony_modules || interface_->IsUnified(var->interface()));
93
  ASSERT((is_this() && var->is_this()) || name_ == var->raw_name());
94 95 96 97 98 99
  // Ideally CONST-ness should match. However, this is very hard to achieve
  // because we don't know the exact semantics of conflicting (const and
  // non-const) multiple variable declarations, const vars introduced via
  // eval() etc.  Const-ness and variable declarations are a complete mess
  // in JS. Sigh...
  var_ = var;
100
  var->set_is_used();
101 102 103
}


104
Assignment::Assignment(Zone* zone,
105
                       Token::Value op,
106 107 108
                       Expression* target,
                       Expression* value,
                       int pos)
109
    : Expression(zone, pos),
110
      op_(op),
111 112
      target_(target),
      value_(value),
113
      binary_operation_(NULL),
114
      assignment_id_(GetNextId(zone)),
115
      is_uninitialized_(false),
116
      store_mode_(STANDARD_STORE) { }
117 118


119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
Token::Value Assignment::binary_op() const {
  switch (op_) {
    case Token::ASSIGN_BIT_OR: return Token::BIT_OR;
    case Token::ASSIGN_BIT_XOR: return Token::BIT_XOR;
    case Token::ASSIGN_BIT_AND: return Token::BIT_AND;
    case Token::ASSIGN_SHL: return Token::SHL;
    case Token::ASSIGN_SAR: return Token::SAR;
    case Token::ASSIGN_SHR: return Token::SHR;
    case Token::ASSIGN_ADD: return Token::ADD;
    case Token::ASSIGN_SUB: return Token::SUB;
    case Token::ASSIGN_MUL: return Token::MUL;
    case Token::ASSIGN_DIV: return Token::DIV;
    case Token::ASSIGN_MOD: return Token::MOD;
    default: UNREACHABLE();
  }
  return Token::ILLEGAL;
}


bool FunctionLiteral::AllowsLazyCompilation() {
  return scope()->AllowsLazyCompilation();
}


143 144 145 146 147
bool FunctionLiteral::AllowsLazyCompilationWithoutContext() {
  return scope()->AllowsLazyCompilationWithoutContext();
}


148 149 150 151 152 153 154 155 156 157
int FunctionLiteral::start_position() const {
  return scope()->start_position();
}


int FunctionLiteral::end_position() const {
  return scope()->end_position();
}


158 159
StrictMode FunctionLiteral::strict_mode() const {
  return scope()->strict_mode();
160 161 162
}


163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
void FunctionLiteral::InitializeSharedInfo(
    Handle<Code> unoptimized_code) {
  for (RelocIterator it(*unoptimized_code); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    if (rinfo->rmode() != RelocInfo::EMBEDDED_OBJECT) continue;
    Object* obj = rinfo->target_object();
    if (obj->IsSharedFunctionInfo()) {
      SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
      if (shared->start_position() == start_position()) {
        shared_info_ = Handle<SharedFunctionInfo>(shared);
        break;
      }
    }
  }
}


180 181 182
ObjectLiteralProperty::ObjectLiteralProperty(Zone* zone,
                                             AstValueFactory* ast_value_factory,
                                             Literal* key, Expression* value) {
183
  emit_store_ = true;
184 185
  key_ = key;
  value_ = value;
186
  if (key->raw_value()->EqualsString(ast_value_factory->proto_string())) {
187
    kind_ = PROTOTYPE;
188 189
  } else if (value_->AsMaterializedLiteral() != NULL) {
    kind_ = MATERIALIZED_LITERAL;
190
  } else if (value_->IsLiteral()) {
191
    kind_ = CONSTANT;
192
  } else {
193
    kind_ = COMPUTED;
194 195 196 197
  }
}


198 199
ObjectLiteralProperty::ObjectLiteralProperty(
    Zone* zone, bool is_getter, FunctionLiteral* value) {
200
  emit_store_ = true;
201 202 203 204 205
  value_ = value;
  kind_ = is_getter ? GETTER : SETTER;
}


206 207 208 209 210 211 212
bool ObjectLiteral::Property::IsCompileTimeValue() {
  return kind_ == CONSTANT ||
      (kind_ == MATERIALIZED_LITERAL &&
       CompileTimeValue::IsCompileTimeValue(value_));
}


213 214 215 216 217 218 219 220 221 222
void ObjectLiteral::Property::set_emit_store(bool emit_store) {
  emit_store_ = emit_store;
}


bool ObjectLiteral::Property::emit_store() {
  return emit_store_;
}


223 224 225 226 227
void ObjectLiteral::CalculateEmitStore(Zone* zone) {
  ZoneAllocationPolicy allocator(zone);

  ZoneHashMap table(Literal::Match, ZoneHashMap::kDefaultHashMapCapacity,
                    allocator);
228 229
  for (int i = properties()->length() - 1; i >= 0; i--) {
    ObjectLiteral::Property* property = properties()->at(i);
230
    Literal* literal = property->key();
231
    if (literal->value()->IsNull()) continue;
232
    uint32_t hash = literal->Hash();
233 234
    // If the key of a computed property is in the table, do not emit
    // a store for the property later.
235 236
    if ((property->kind() == ObjectLiteral::Property::MATERIALIZED_LITERAL ||
         property->kind() == ObjectLiteral::Property::COMPUTED) &&
237
        table.Lookup(literal, hash, false, allocator) != NULL) {
238 239 240
      property->set_emit_store(false);
    } else {
      // Add key to the table.
241
      table.Lookup(literal, hash, true, allocator);
242 243 244 245 246
    }
  }
}


247 248 249 250 251 252
bool ObjectLiteral::IsBoilerplateProperty(ObjectLiteral::Property* property) {
  return property != NULL &&
         property->kind() != ObjectLiteral::Property::PROTOTYPE;
}


253
void ObjectLiteral::BuildConstantProperties(Isolate* isolate) {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  if (!constant_properties_.is_null()) return;

  // Allocate a fixed array to hold all the constant properties.
  Handle<FixedArray> constant_properties = isolate->factory()->NewFixedArray(
      boilerplate_properties_ * 2, TENURED);

  int position = 0;
  // Accumulate the value in local variables and store it at the end.
  bool is_simple = true;
  int depth_acc = 1;
  uint32_t max_element_index = 0;
  uint32_t elements = 0;
  for (int i = 0; i < properties()->length(); i++) {
    ObjectLiteral::Property* property = properties()->at(i);
    if (!IsBoilerplateProperty(property)) {
      is_simple = false;
      continue;
    }
    MaterializedLiteral* m_literal = property->value()->AsMaterializedLiteral();
    if (m_literal != NULL) {
274 275
      m_literal->BuildConstants(isolate);
      if (m_literal->depth() >= depth_acc) depth_acc = m_literal->depth() + 1;
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    }

    // Add CONSTANT and COMPUTED properties to boilerplate. Use undefined
    // value for COMPUTED properties, the real value is filled in at
    // runtime. The enumeration order is maintained.
    Handle<Object> key = property->key()->value();
    Handle<Object> value = GetBoilerplateValue(property->value(), isolate);

    // Ensure objects that may, at any point in time, contain fields with double
    // representation are always treated as nested objects. This is true for
    // computed fields (value is undefined), and smi and double literals
    // (value->IsNumber()).
    // TODO(verwaest): Remove once we can store them inline.
    if (FLAG_track_double_fields &&
        (value->IsNumber() || value->IsUninitialized())) {
      may_store_doubles_ = true;
    }

    is_simple = is_simple && !value->IsUninitialized();

    // Keep track of the number of elements in the object literal and
    // the largest element index.  If the largest element index is
    // much larger than the number of elements, creating an object
    // literal with fast elements will be a waste of space.
    uint32_t element_index = 0;
    if (key->IsString()
        && Handle<String>::cast(key)->AsArrayIndex(&element_index)
        && element_index > max_element_index) {
      max_element_index = element_index;
      elements++;
    } else if (key->IsSmi()) {
      int key_value = Smi::cast(*key)->value();
      if (key_value > 0
          && static_cast<uint32_t>(key_value) > max_element_index) {
        max_element_index = key_value;
      }
      elements++;
    }

    // Add name, value pair to the fixed array.
    constant_properties->set(position++, *key);
    constant_properties->set(position++, *value);
  }

  constant_properties_ = constant_properties;
  fast_elements_ =
      (max_element_index <= 32) || ((2 * elements) >= max_element_index);
  set_is_simple(is_simple);
324
  set_depth(depth_acc);
325 326 327
}


328
void ArrayLiteral::BuildConstantElements(Isolate* isolate) {
329 330 331 332 333
  if (!constant_elements_.is_null()) return;

  // Allocate a fixed array to hold all the object literals.
  Handle<JSArray> array =
      isolate->factory()->NewJSArray(0, FAST_HOLEY_SMI_ELEMENTS);
334
  JSArray::Expand(array, values()->length());
335 336 337 338 339 340 341 342 343

  // Fill in the literals.
  bool is_simple = true;
  int depth_acc = 1;
  bool is_holey = false;
  for (int i = 0, n = values()->length(); i < n; i++) {
    Expression* element = values()->at(i);
    MaterializedLiteral* m_literal = element->AsMaterializedLiteral();
    if (m_literal != NULL) {
344 345 346 347
      m_literal->BuildConstants(isolate);
      if (m_literal->depth() + 1 > depth_acc) {
        depth_acc = m_literal->depth() + 1;
      }
348 349 350 351 352 353 354
    }
    Handle<Object> boilerplate_value = GetBoilerplateValue(element, isolate);
    if (boilerplate_value->IsTheHole()) {
      is_holey = true;
    } else if (boilerplate_value->IsUninitialized()) {
      is_simple = false;
      JSObject::SetOwnElement(
355
          array, i, handle(Smi::FromInt(0), isolate), SLOPPY).Assert();
356
    } else {
357
      JSObject::SetOwnElement(array, i, boilerplate_value, SLOPPY).Assert();
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    }
  }

  Handle<FixedArrayBase> element_values(array->elements());

  // Simple and shallow arrays can be lazily copied, we transform the
  // elements array to a copy-on-write array.
  if (is_simple && depth_acc == 1 && values()->length() > 0 &&
      array->HasFastSmiOrObjectElements()) {
    element_values->set_map(isolate->heap()->fixed_cow_array_map());
  }

  // Remember both the literal's constant values as well as the ElementsKind
  // in a 2-element FixedArray.
  Handle<FixedArray> literals = isolate->factory()->NewFixedArray(2, TENURED);

  ElementsKind kind = array->GetElementsKind();
  kind = is_holey ? GetHoleyElementsKind(kind) : GetPackedElementsKind(kind);

  literals->set(0, Smi::FromInt(kind));
  literals->set(1, *element_values);

  constant_elements_ = literals;
  set_is_simple(is_simple);
382
  set_depth(depth_acc);
383 384 385 386 387
}


Handle<Object> MaterializedLiteral::GetBoilerplateValue(Expression* expression,
                                                        Isolate* isolate) {
388
  if (expression->IsLiteral()) {
389 390 391 392 393 394 395 396 397
    return expression->AsLiteral()->value();
  }
  if (CompileTimeValue::IsCompileTimeValue(expression)) {
    return CompileTimeValue::GetValue(isolate, expression);
  }
  return isolate->factory()->uninitialized_value();
}


398
void MaterializedLiteral::BuildConstants(Isolate* isolate) {
399
  if (IsArrayLiteral()) {
400
    return AsArrayLiteral()->BuildConstantElements(isolate);
401 402
  }
  if (IsObjectLiteral()) {
403
    return AsObjectLiteral()->BuildConstantProperties(isolate);
404 405
  }
  ASSERT(IsRegExpLiteral());
406
  ASSERT(depth() >= 1);  // Depth should be initialized.
407 408 409
}


410
void TargetCollector::AddTarget(Label* target, Zone* zone) {
411
  // Add the label to the collector, but discard duplicates.
412
  int length = targets_.length();
413
  for (int i = 0; i < length; i++) {
414
    if (targets_[i] == target) return;
415
  }
416
  targets_.Add(target, zone);
417 418 419
}


420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
void UnaryOperation::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
  // TODO(olivf) If this Operation is used in a test context, then the
  // expression has a ToBoolean stub and we want to collect the type
  // information. However the GraphBuilder expects it to be on the instruction
  // corresponding to the TestContext, therefore we have to store it here and
  // not on the operand.
  set_to_boolean_types(oracle->ToBooleanTypes(expression()->test_id()));
}


void BinaryOperation::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
  // TODO(olivf) If this Operation is used in a test context, then the right
  // hand side has a ToBoolean stub and we want to collect the type information.
  // However the GraphBuilder expects it to be on the instruction corresponding
  // to the TestContext, therefore we have to store it here and not on the
  // right hand operand.
  set_to_boolean_types(oracle->ToBooleanTypes(right()->test_id()));
}


440
bool BinaryOperation::ResultOverwriteAllowed() const {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  switch (op_) {
    case Token::COMMA:
    case Token::OR:
    case Token::AND:
      return false;
    case Token::BIT_OR:
    case Token::BIT_XOR:
    case Token::BIT_AND:
    case Token::SHL:
    case Token::SAR:
    case Token::SHR:
    case Token::ADD:
    case Token::SUB:
    case Token::MUL:
    case Token::DIV:
    case Token::MOD:
      return true;
    default:
      UNREACHABLE();
  }
  return false;
}


465 466 467 468 469
static bool IsTypeof(Expression* expr) {
  UnaryOperation* maybe_unary = expr->AsUnaryOperation();
  return maybe_unary != NULL && maybe_unary->op() == Token::TYPEOF;
}

470

471 472 473 474 475 476 477
// Check for the pattern: typeof <expression> equals <string literal>.
static bool MatchLiteralCompareTypeof(Expression* left,
                                      Token::Value op,
                                      Expression* right,
                                      Expression** expr,
                                      Handle<String>* check) {
  if (IsTypeof(left) && right->IsStringLiteral() && Token::IsEqualityOp(op)) {
478
    *expr = left->AsUnaryOperation()->expression();
479
    *check = Handle<String>::cast(right->AsLiteral()->value());
480 481 482 483 484 485
    return true;
  }
  return false;
}


486 487 488 489 490
bool CompareOperation::IsLiteralCompareTypeof(Expression** expr,
                                              Handle<String>* check) {
  return MatchLiteralCompareTypeof(left_, op_, right_, expr, check) ||
      MatchLiteralCompareTypeof(right_, op_, left_, expr, check);
}
491 492


493 494 495 496
static bool IsVoidOfLiteral(Expression* expr) {
  UnaryOperation* maybe_unary = expr->AsUnaryOperation();
  return maybe_unary != NULL &&
      maybe_unary->op() == Token::VOID &&
497
      maybe_unary->expression()->IsLiteral();
498 499
}

500

501 502
// Check for the pattern: void <literal> equals <expression> or
// undefined equals <expression>
503 504 505
static bool MatchLiteralCompareUndefined(Expression* left,
                                         Token::Value op,
                                         Expression* right,
506 507
                                         Expression** expr,
                                         Isolate* isolate) {
508
  if (IsVoidOfLiteral(left) && Token::IsEqualityOp(op)) {
509 510 511
    *expr = right;
    return true;
  }
512
  if (left->IsUndefinedLiteral(isolate) && Token::IsEqualityOp(op)) {
513
    *expr = right;
514 515 516 517 518 519
    return true;
  }
  return false;
}


520 521 522 523
bool CompareOperation::IsLiteralCompareUndefined(
    Expression** expr, Isolate* isolate) {
  return MatchLiteralCompareUndefined(left_, op_, right_, expr, isolate) ||
      MatchLiteralCompareUndefined(right_, op_, left_, expr, isolate);
524
}
525 526


527 528 529 530 531 532 533
// Check for the pattern: null equals <expression>
static bool MatchLiteralCompareNull(Expression* left,
                                    Token::Value op,
                                    Expression* right,
                                    Expression** expr) {
  if (left->IsNullLiteral() && Token::IsEqualityOp(op)) {
    *expr = right;
534 535 536 537 538 539
    return true;
  }
  return false;
}


540 541 542 543 544 545
bool CompareOperation::IsLiteralCompareNull(Expression** expr) {
  return MatchLiteralCompareNull(left_, op_, right_, expr) ||
      MatchLiteralCompareNull(right_, op_, left_, expr);
}


546 547 548
// ----------------------------------------------------------------------------
// Inlining support

549
bool Declaration::IsInlineable() const {
550 551 552
  return proxy()->var()->IsStackAllocated();
}

553 554
bool FunctionDeclaration::IsInlineable() const {
  return false;
555 556 557
}


558 559 560
// ----------------------------------------------------------------------------
// Recording of type feedback

561 562 563
// TODO(rossberg): all RecordTypeFeedback functions should disappear
// once we use the common type field in the AST consistently.

564 565 566 567 568
void Expression::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
  to_boolean_types_ = oracle->ToBooleanTypes(test_id());
}


569
bool Call::IsUsingCallFeedbackSlot(Isolate* isolate) const {
570
  CallType call_type = GetCallType(isolate);
571
  return (call_type != POSSIBLY_EVAL_CALL);
572 573 574
}


575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
Call::CallType Call::GetCallType(Isolate* isolate) const {
  VariableProxy* proxy = expression()->AsVariableProxy();
  if (proxy != NULL) {
    if (proxy->var()->is_possibly_eval(isolate)) {
      return POSSIBLY_EVAL_CALL;
    } else if (proxy->var()->IsUnallocated()) {
      return GLOBAL_CALL;
    } else if (proxy->var()->IsLookupSlot()) {
      return LOOKUP_SLOT_CALL;
    }
  }

  Property* property = expression()->AsProperty();
  return property != NULL ? PROPERTY_CALL : OTHER_CALL;
}


592
bool Call::ComputeGlobalTarget(Handle<GlobalObject> global,
593
                               LookupResult* lookup) {
594
  target_ = Handle<JSFunction>::null();
595
  cell_ = Handle<Cell>::null();
596
  ASSERT(lookup->IsFound() &&
597 598
         lookup->type() == NORMAL &&
         lookup->holder() == *global);
599
  cell_ = Handle<Cell>(global->GetPropertyCell(lookup));
600 601 602 603
  if (cell_->value()->IsJSFunction()) {
    Handle<JSFunction> candidate(JSFunction::cast(cell_->value()));
    // If the function is in new space we assume it's more likely to
    // change and thus prefer the general IC code.
604
    if (!lookup->isolate()->heap()->InNewSpace(*candidate)) {
605 606
      target_ = candidate;
      return true;
607 608 609 610 611 612
    }
  }
  return false;
}


613
void CallNew::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
614 615 616
  int allocation_site_feedback_slot = FLAG_pretenuring_call_new
      ? AllocationSiteFeedbackSlot()
      : CallNewFeedbackSlot();
617
  allocation_site_ =
618
      oracle->GetCallNewAllocationSite(allocation_site_feedback_slot);
619
  is_monomorphic_ = oracle->CallNewIsMonomorphic(CallNewFeedbackSlot());
620
  if (is_monomorphic_) {
621
    target_ = oracle->GetCallNewTarget(CallNewFeedbackSlot());
622 623
    if (!allocation_site_.is_null()) {
      elements_kind_ = allocation_site_->GetElementsKind();
624
    }
625 626 627 628
  }
}


629
void ObjectLiteral::Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
630
  TypeFeedbackId id = key()->LiteralFeedbackId();
631 632 633 634
  SmallMapList maps;
  oracle->CollectReceiverTypes(id, &maps);
  receiver_type_ = maps.length() == 1 ? maps.at(0)
                                      : Handle<Map>::null();
635 636 637
}


638
// ----------------------------------------------------------------------------
639
// Implementation of AstVisitor
640

641 642 643 644 645 646 647
void AstVisitor::VisitDeclarations(ZoneList<Declaration*>* declarations) {
  for (int i = 0; i < declarations->length(); i++) {
    Visit(declarations->at(i));
  }
}


648
void AstVisitor::VisitStatements(ZoneList<Statement*>* statements) {
649
  for (int i = 0; i < statements->length(); i++) {
650 651 652
    Statement* stmt = statements->at(i);
    Visit(stmt);
    if (stmt->IsJump()) break;
653 654 655 656
  }
}


657
void AstVisitor::VisitExpressions(ZoneList<Expression*>* expressions) {
658 659 660 661 662 663 664 665 666 667 668
  for (int i = 0; i < expressions->length(); i++) {
    // The variable statement visiting code may pass NULL expressions
    // to this code. Maybe this should be handled by introducing an
    // undefined expression or literal?  Revisit this code if this
    // changes
    Expression* expression = expressions->at(i);
    if (expression != NULL) Visit(expression);
  }
}


669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
// ----------------------------------------------------------------------------
// Regular expressions

#define MAKE_ACCEPT(Name)                                            \
  void* RegExp##Name::Accept(RegExpVisitor* visitor, void* data) {   \
    return visitor->Visit##Name(this, data);                         \
  }
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ACCEPT)
#undef MAKE_ACCEPT

#define MAKE_TYPE_CASE(Name)                                         \
  RegExp##Name* RegExpTree::As##Name() {                             \
    return NULL;                                                     \
  }                                                                  \
  bool RegExpTree::Is##Name() { return false; }
684
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
685 686 687 688 689 690 691 692 693 694 695
#undef MAKE_TYPE_CASE

#define MAKE_TYPE_CASE(Name)                                        \
  RegExp##Name* RegExp##Name::As##Name() {                          \
    return this;                                                    \
  }                                                                 \
  bool RegExp##Name::Is##Name() { return true; }
FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
#undef MAKE_TYPE_CASE


696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
static Interval ListCaptureRegisters(ZoneList<RegExpTree*>* children) {
  Interval result = Interval::Empty();
  for (int i = 0; i < children->length(); i++)
    result = result.Union(children->at(i)->CaptureRegisters());
  return result;
}


Interval RegExpAlternative::CaptureRegisters() {
  return ListCaptureRegisters(nodes());
}


Interval RegExpDisjunction::CaptureRegisters() {
  return ListCaptureRegisters(alternatives());
}


Interval RegExpLookahead::CaptureRegisters() {
  return body()->CaptureRegisters();
}


Interval RegExpCapture::CaptureRegisters() {
  Interval self(StartRegister(index()), EndRegister(index()));
  return self.Union(body()->CaptureRegisters());
}


Interval RegExpQuantifier::CaptureRegisters() {
  return body()->CaptureRegisters();
}


730
bool RegExpAssertion::IsAnchoredAtStart() {
731
  return assertion_type() == RegExpAssertion::START_OF_INPUT;
732 733 734
}


735
bool RegExpAssertion::IsAnchoredAtEnd() {
736
  return assertion_type() == RegExpAssertion::END_OF_INPUT;
737 738 739 740
}


bool RegExpAlternative::IsAnchoredAtStart() {
741 742 743
  ZoneList<RegExpTree*>* nodes = this->nodes();
  for (int i = 0; i < nodes->length(); i++) {
    RegExpTree* node = nodes->at(i);
744 745 746 747 748 749 750 751 752 753 754 755
    if (node->IsAnchoredAtStart()) { return true; }
    if (node->max_match() > 0) { return false; }
  }
  return false;
}


bool RegExpAlternative::IsAnchoredAtEnd() {
  ZoneList<RegExpTree*>* nodes = this->nodes();
  for (int i = nodes->length() - 1; i >= 0; i--) {
    RegExpTree* node = nodes->at(i);
    if (node->IsAnchoredAtEnd()) { return true; }
756 757 758
    if (node->max_match() > 0) { return false; }
  }
  return false;
759 760 761
}


762
bool RegExpDisjunction::IsAnchoredAtStart() {
763 764
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  for (int i = 0; i < alternatives->length(); i++) {
765
    if (!alternatives->at(i)->IsAnchoredAtStart())
766 767 768 769 770 771
      return false;
  }
  return true;
}


772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
bool RegExpDisjunction::IsAnchoredAtEnd() {
  ZoneList<RegExpTree*>* alternatives = this->alternatives();
  for (int i = 0; i < alternatives->length(); i++) {
    if (!alternatives->at(i)->IsAnchoredAtEnd())
      return false;
  }
  return true;
}


bool RegExpLookahead::IsAnchoredAtStart() {
  return is_positive() && body()->IsAnchoredAtStart();
}


bool RegExpCapture::IsAnchoredAtStart() {
  return body()->IsAnchoredAtStart();
789 790 791
}


792 793
bool RegExpCapture::IsAnchoredAtEnd() {
  return body()->IsAnchoredAtEnd();
794 795 796
}


797 798 799 800 801
// Convert regular expression trees to a simple sexp representation.
// This representation should be different from the input grammar
// in as many cases as possible, to make it more difficult for incorrect
// parses to look as correct ones which is likely if the input and
// output formats are alike.
802
class RegExpUnparser V8_FINAL : public RegExpVisitor {
803
 public:
804
  RegExpUnparser(OStream& os, Zone* zone) : os_(os), zone_(zone) {}
805
  void VisitCharacterRange(CharacterRange that);
806 807
#define MAKE_CASE(Name) virtual void* Visit##Name(RegExp##Name*,          \
                                                  void* data) V8_OVERRIDE;
808 809 810
  FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE)
#undef MAKE_CASE
 private:
811
  OStream& os_;
812
  Zone* zone_;
813 814 815 816
};


void* RegExpUnparser::VisitDisjunction(RegExpDisjunction* that, void* data) {
817
  os_ << "(|";
818
  for (int i = 0; i <  that->alternatives()->length(); i++) {
819
    os_ << " ";
820 821
    that->alternatives()->at(i)->Accept(this, data);
  }
822
  os_ << ")";
823 824 825 826 827
  return NULL;
}


void* RegExpUnparser::VisitAlternative(RegExpAlternative* that, void* data) {
828
  os_ << "(:";
829
  for (int i = 0; i <  that->nodes()->length(); i++) {
830
    os_ << " ";
831 832
    that->nodes()->at(i)->Accept(this, data);
  }
833
  os_ << ")";
834 835 836 837 838
  return NULL;
}


void RegExpUnparser::VisitCharacterRange(CharacterRange that) {
839
  os_ << AsUC16(that.from());
840
  if (!that.IsSingleton()) {
841
    os_ << "-" << AsUC16(that.to());
842 843 844 845 846 847 848
  }
}



void* RegExpUnparser::VisitCharacterClass(RegExpCharacterClass* that,
                                          void* data) {
849 850
  if (that->is_negated()) os_ << "^";
  os_ << "[";
851
  for (int i = 0; i < that->ranges(zone_)->length(); i++) {
852
    if (i > 0) os_ << " ";
853
    VisitCharacterRange(that->ranges(zone_)->at(i));
854
  }
855
  os_ << "]";
856 857 858 859 860
  return NULL;
}


void* RegExpUnparser::VisitAssertion(RegExpAssertion* that, void* data) {
861
  switch (that->assertion_type()) {
862
    case RegExpAssertion::START_OF_INPUT:
863
      os_ << "@^i";
864 865
      break;
    case RegExpAssertion::END_OF_INPUT:
866
      os_ << "@$i";
867 868
      break;
    case RegExpAssertion::START_OF_LINE:
869
      os_ << "@^l";
870 871
      break;
    case RegExpAssertion::END_OF_LINE:
872
      os_ << "@$l";
873 874
       break;
    case RegExpAssertion::BOUNDARY:
875
      os_ << "@b";
876 877
      break;
    case RegExpAssertion::NON_BOUNDARY:
878
      os_ << "@B";
879 880 881 882 883 884 885
      break;
  }
  return NULL;
}


void* RegExpUnparser::VisitAtom(RegExpAtom* that, void* data) {
886
  os_ << "'";
887 888
  Vector<const uc16> chardata = that->data();
  for (int i = 0; i < chardata.length(); i++) {
889
    os_ << AsUC16(chardata[i]);
890
  }
891
  os_ << "'";
892 893 894 895 896 897
  return NULL;
}


void* RegExpUnparser::VisitText(RegExpText* that, void* data) {
  if (that->elements()->length() == 1) {
898
    that->elements()->at(0).tree()->Accept(this, data);
899
  } else {
900
    os_ << "(!";
901
    for (int i = 0; i < that->elements()->length(); i++) {
902
      os_ << " ";
903
      that->elements()->at(i).tree()->Accept(this, data);
904
    }
905
    os_ << ")";
906 907 908 909 910 911
  }
  return NULL;
}


void* RegExpUnparser::VisitQuantifier(RegExpQuantifier* that, void* data) {
912
  os_ << "(# " << that->min() << " ";
913
  if (that->max() == RegExpTree::kInfinity) {
914
    os_ << "- ";
915
  } else {
916
    os_ << that->max() << " ";
917
  }
918
  os_ << (that->is_greedy() ? "g " : that->is_possessive() ? "p " : "n ");
919
  that->body()->Accept(this, data);
920
  os_ << ")";
921 922 923 924 925
  return NULL;
}


void* RegExpUnparser::VisitCapture(RegExpCapture* that, void* data) {
926
  os_ << "(^ ";
927
  that->body()->Accept(this, data);
928
  os_ << ")";
929 930 931 932 933
  return NULL;
}


void* RegExpUnparser::VisitLookahead(RegExpLookahead* that, void* data) {
934
  os_ << "(-> " << (that->is_positive() ? "+ " : "- ");
935
  that->body()->Accept(this, data);
936
  os_ << ")";
937 938 939 940 941 942
  return NULL;
}


void* RegExpUnparser::VisitBackReference(RegExpBackReference* that,
                                         void* data) {
943
  os_ << "(<- " << that->index() << ")";
944 945 946 947 948
  return NULL;
}


void* RegExpUnparser::VisitEmpty(RegExpEmpty* that, void* data) {
949
  os_ << '%';
950 951 952 953
  return NULL;
}


954 955
OStream& RegExpTree::Print(OStream& os, Zone* zone) {  // NOLINT
  RegExpUnparser unparser(os, zone);
956
  Accept(&unparser, NULL);
957
  return os;
958 959 960
}


961 962
RegExpDisjunction::RegExpDisjunction(ZoneList<RegExpTree*>* alternatives)
    : alternatives_(alternatives) {
963
  ASSERT(alternatives->length() > 1);
964 965 966 967 968 969 970 971 972 973 974
  RegExpTree* first_alternative = alternatives->at(0);
  min_match_ = first_alternative->min_match();
  max_match_ = first_alternative->max_match();
  for (int i = 1; i < alternatives->length(); i++) {
    RegExpTree* alternative = alternatives->at(i);
    min_match_ = Min(min_match_, alternative->min_match());
    max_match_ = Max(max_match_, alternative->max_match());
  }
}


975 976 977 978 979 980 981 982
static int IncreaseBy(int previous, int increase) {
  if (RegExpTree::kInfinity - previous < increase) {
    return RegExpTree::kInfinity;
  } else {
    return previous + increase;
  }
}

983 984
RegExpAlternative::RegExpAlternative(ZoneList<RegExpTree*>* nodes)
    : nodes_(nodes) {
985
  ASSERT(nodes->length() > 1);
986 987 988 989
  min_match_ = 0;
  max_match_ = 0;
  for (int i = 0; i < nodes->length(); i++) {
    RegExpTree* node = nodes->at(i);
990 991
    int node_min_match = node->min_match();
    min_match_ = IncreaseBy(min_match_, node_min_match);
992
    int node_max_match = node->max_match();
993
    max_match_ = IncreaseBy(max_match_, node_max_match);
994 995 996
  }
}

997

998
CaseClause::CaseClause(Zone* zone,
999
                       Expression* label,
1000 1001
                       ZoneList<Statement*>* statements,
                       int pos)
1002
    : Expression(zone, pos),
1003
      label_(label),
1004
      statements_(statements),
1005 1006 1007
      compare_type_(Type::None(zone)),
      compare_id_(AstNode::GetNextId(zone)),
      entry_id_(AstNode::GetNextId(zone)) {
1008
}
1009

1010

1011
#define REGULAR_NODE(NodeType) \
1012 1013 1014
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
  }
1015 1016 1017 1018 1019
#define REGULAR_NODE_WITH_FEEDBACK_SLOTS(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_slot_node(node); \
  }
1020 1021 1022
#define DONT_OPTIMIZE_NODE(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
1023
    set_dont_optimize_reason(k##NodeType); \
1024 1025
    add_flag(kDontSelfOptimize); \
  }
1026 1027 1028 1029 1030 1031 1032 1033
#define DONT_OPTIMIZE_NODE_WITH_FEEDBACK_SLOTS(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_slot_node(node); \
    set_dont_optimize_reason(k##NodeType); \
    add_flag(kDontSelfOptimize); \
  }
#define DONT_SELFOPTIMIZE_NODE(NodeType)                         \
1034 1035 1036 1037
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_flag(kDontSelfOptimize); \
  }
1038 1039 1040 1041 1042 1043
#define DONT_SELFOPTIMIZE_NODE_WITH_FEEDBACK_SLOTS(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
    add_slot_node(node); \
    add_flag(kDontSelfOptimize); \
  }
1044 1045 1046
#define DONT_CACHE_NODE(NodeType) \
  void AstConstructionVisitor::Visit##NodeType(NodeType* node) { \
    increase_node_count(); \
1047
    set_dont_optimize_reason(k##NodeType); \
1048 1049 1050
    add_flag(kDontSelfOptimize); \
    add_flag(kDontCache); \
  }
1051

1052 1053 1054 1055 1056 1057 1058 1059 1060
REGULAR_NODE(VariableDeclaration)
REGULAR_NODE(FunctionDeclaration)
REGULAR_NODE(Block)
REGULAR_NODE(ExpressionStatement)
REGULAR_NODE(EmptyStatement)
REGULAR_NODE(IfStatement)
REGULAR_NODE(ContinueStatement)
REGULAR_NODE(BreakStatement)
REGULAR_NODE(ReturnStatement)
1061
REGULAR_NODE(SwitchStatement)
1062
REGULAR_NODE(CaseClause)
1063 1064
REGULAR_NODE(Conditional)
REGULAR_NODE(Literal)
1065
REGULAR_NODE(ArrayLiteral)
1066
REGULAR_NODE(ObjectLiteral)
1067
REGULAR_NODE(RegExpLiteral)
1068
REGULAR_NODE(FunctionLiteral)
1069 1070 1071 1072 1073 1074 1075
REGULAR_NODE(Assignment)
REGULAR_NODE(Throw)
REGULAR_NODE(UnaryOperation)
REGULAR_NODE(CountOperation)
REGULAR_NODE(BinaryOperation)
REGULAR_NODE(CompareOperation)
REGULAR_NODE(ThisFunction)
1076

1077 1078
REGULAR_NODE_WITH_FEEDBACK_SLOTS(Call)
REGULAR_NODE_WITH_FEEDBACK_SLOTS(CallNew)
1079
REGULAR_NODE_WITH_FEEDBACK_SLOTS(Property)
1080
// In theory, for VariableProxy we'd have to add:
1081 1082
// if (node->var()->IsLookupSlot())
//   set_dont_optimize_reason(kReferenceToAVariableWhichRequiresDynamicLookup);
1083 1084
// But node->var() is usually not bound yet at VariableProxy creation time, and
// LOOKUP variables only result from constructs that cannot be inlined anyway.
1085
REGULAR_NODE_WITH_FEEDBACK_SLOTS(VariableProxy)
1086

1087
// We currently do not optimize any modules.
1088 1089 1090 1091 1092 1093
DONT_OPTIMIZE_NODE(ModuleDeclaration)
DONT_OPTIMIZE_NODE(ImportDeclaration)
DONT_OPTIMIZE_NODE(ExportDeclaration)
DONT_OPTIMIZE_NODE(ModuleVariable)
DONT_OPTIMIZE_NODE(ModulePath)
DONT_OPTIMIZE_NODE(ModuleUrl)
1094
DONT_OPTIMIZE_NODE(ModuleStatement)
1095 1096 1097 1098
DONT_OPTIMIZE_NODE(WithStatement)
DONT_OPTIMIZE_NODE(TryCatchStatement)
DONT_OPTIMIZE_NODE(TryFinallyStatement)
DONT_OPTIMIZE_NODE(DebuggerStatement)
1099
DONT_OPTIMIZE_NODE(NativeFunctionLiteral)
1100

1101 1102
DONT_OPTIMIZE_NODE_WITH_FEEDBACK_SLOTS(Yield)

1103 1104 1105
DONT_SELFOPTIMIZE_NODE(DoWhileStatement)
DONT_SELFOPTIMIZE_NODE(WhileStatement)
DONT_SELFOPTIMIZE_NODE(ForStatement)
1106
DONT_SELFOPTIMIZE_NODE(ForOfStatement)
1107

1108 1109
DONT_SELFOPTIMIZE_NODE_WITH_FEEDBACK_SLOTS(ForInStatement)

1110 1111
DONT_CACHE_NODE(ModuleLiteral)

1112

1113 1114
void AstConstructionVisitor::VisitCallRuntime(CallRuntime* node) {
  increase_node_count();
1115
  add_slot_node(node);
1116
  if (node->is_jsruntime()) {
1117 1118
    // Don't try to optimize JS runtime calls because we bailout on them.
    set_dont_optimize_reason(kCallToAJavaScriptRuntimeFunction);
1119 1120 1121
  }
}

1122 1123 1124
#undef REGULAR_NODE
#undef DONT_OPTIMIZE_NODE
#undef DONT_SELFOPTIMIZE_NODE
1125
#undef DONT_CACHE_NODE
1126

1127 1128

Handle<String> Literal::ToString() {
1129
  if (value_->IsString()) return value_->AsString()->string();
1130
  ASSERT(value_->IsNumber());
1131 1132 1133
  char arr[100];
  Vector<char> buffer(arr, ARRAY_SIZE(arr));
  const char* str;
1134
  if (value()->IsSmi()) {
1135
    // Optimization only, the heap number case would subsume this.
1136
    SNPrintF(buffer, "%d", Smi::cast(*value())->value());
1137 1138
    str = arr;
  } else {
1139
    str = DoubleToCString(value()->Number(), buffer);
1140
  }
1141
  return isolate_->factory()->NewStringFromAsciiChecked(str);
1142 1143 1144
}


1145
} }  // namespace v8::internal