scopeinfo.cc 18.8 KB
Newer Older
1
// Copyright 2011 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

#include <stdlib.h>

7
#include "src/v8.h"
8

9 10
#include "src/scopeinfo.h"
#include "src/scopes.h"
11

12 13
namespace v8 {
namespace internal {
14 15


16 17
Handle<ScopeInfo> ScopeInfo::Create(Isolate* isolate, Zone* zone,
                                    Scope* scope) {
18
  // Collect stack and context locals.
19 20
  ZoneList<Variable*> stack_locals(scope->StackLocalCount(), zone);
  ZoneList<Variable*> context_locals(scope->ContextLocalCount(), zone);
21 22 23 24
  scope->CollectStackAndContextLocals(&stack_locals, &context_locals);
  const int stack_local_count = stack_locals.length();
  const int context_local_count = context_locals.length();
  // Make sure we allocate the correct amount.
25 26
  DCHECK(scope->StackLocalCount() == stack_local_count);
  DCHECK(scope->ContextLocalCount() == context_local_count);
27

28 29 30 31
  // Determine use and location of the function variable if it is present.
  FunctionVariableInfo function_name_info;
  VariableMode function_variable_mode;
  if (scope->is_function_scope() && scope->function() != NULL) {
32
    Variable* var = scope->function()->proxy()->var();
33 34 35 36 37
    if (!var->is_used()) {
      function_name_info = UNUSED;
    } else if (var->IsContextSlot()) {
      function_name_info = CONTEXT;
    } else {
38
      DCHECK(var->IsStackLocal());
39
      function_name_info = STACK;
40
    }
41
    function_variable_mode = var->mode();
42
  } else {
43 44
    function_name_info = NONE;
    function_variable_mode = VAR;
45 46
  }

47 48 49 50 51 52
  const bool has_function_name = function_name_info != NONE;
  const int parameter_count = scope->num_parameters();
  const int length = kVariablePartIndex
      + parameter_count + stack_local_count + 2 * context_local_count
      + (has_function_name ? 2 : 0);

53
  Factory* factory = isolate->factory();
54
  Handle<ScopeInfo> scope_info = factory->NewScopeInfo(length);
55 56

  // Encode the flags.
57
  int flags = ScopeTypeField::encode(scope->scope_type()) |
58 59 60 61 62 63
              CallsEvalField::encode(scope->calls_eval()) |
              StrictModeField::encode(scope->strict_mode()) |
              FunctionVariableField::encode(function_name_info) |
              FunctionVariableMode::encode(function_variable_mode) |
              AsmModuleField::encode(scope->asm_module()) |
              AsmFunctionField::encode(scope->asm_function());
64 65 66 67 68 69 70
  scope_info->SetFlags(flags);
  scope_info->SetParameterCount(parameter_count);
  scope_info->SetStackLocalCount(stack_local_count);
  scope_info->SetContextLocalCount(context_local_count);

  int index = kVariablePartIndex;
  // Add parameters.
71
  DCHECK(index == scope_info->ParameterEntriesIndex());
72 73
  for (int i = 0; i < parameter_count; ++i) {
    scope_info->set(index++, *scope->parameter(i)->name());
74 75
  }

76 77 78
  // Add stack locals' names. We are assuming that the stack locals'
  // slots are allocated in increasing order, so we can simply add
  // them to the ScopeInfo object.
79
  DCHECK(index == scope_info->StackLocalEntriesIndex());
80
  for (int i = 0; i < stack_local_count; ++i) {
81
    DCHECK(stack_locals[i]->index() == i);
82 83
    scope_info->set(index++, *stack_locals[i]->name());
  }
84

85 86 87 88 89 90
  // Due to usage analysis, context-allocated locals are not necessarily in
  // increasing order: Some of them may be parameters which are allocated before
  // the non-parameter locals. When the non-parameter locals are sorted
  // according to usage, the allocated slot indices may not be in increasing
  // order with the variable list anymore. Thus, we first need to sort them by
  // context slot index before adding them to the ScopeInfo object.
91
  context_locals.Sort(&Variable::CompareIndex);
92 93

  // Add context locals' names.
94
  DCHECK(index == scope_info->ContextLocalNameEntriesIndex());
95 96 97
  for (int i = 0; i < context_local_count; ++i) {
    scope_info->set(index++, *context_locals[i]->name());
  }
98

99
  // Add context locals' info.
100
  DCHECK(index == scope_info->ContextLocalInfoEntriesIndex());
101
  for (int i = 0; i < context_local_count; ++i) {
102
    Variable* var = context_locals[i];
103 104 105 106
    uint32_t value =
        ContextLocalMode::encode(var->mode()) |
        ContextLocalInitFlag::encode(var->initialization_flag()) |
        ContextLocalMaybeAssignedFlag::encode(var->maybe_assigned());
107
    scope_info->set(index++, Smi::FromInt(value));
108
  }
109

110
  // If present, add the function variable name and its index.
111
  DCHECK(index == scope_info->FunctionNameEntryIndex());
112
  if (has_function_name) {
113 114
    int var_index = scope->function()->proxy()->var()->index();
    scope_info->set(index++, *scope->function()->proxy()->name());
115
    scope_info->set(index++, Smi::FromInt(var_index));
116
    DCHECK(function_name_info != STACK ||
117 118
           (var_index == scope_info->StackLocalCount() &&
            var_index == scope_info->StackSlotCount() - 1));
119
    DCHECK(function_name_info != CONTEXT ||
120 121
           var_index == scope_info->ContextLength() - 1);
  }
122

123 124 125 126
  DCHECK(index == scope_info->length());
  DCHECK(scope->num_parameters() == scope_info->ParameterCount());
  DCHECK(scope->num_stack_slots() == scope_info->StackSlotCount());
  DCHECK(scope->num_heap_slots() == scope_info->ContextLength() ||
127 128
         (scope->num_heap_slots() == kVariablePartIndex &&
          scope_info->ContextLength() == 0));
129
  return scope_info;
130 131 132
}


133 134
ScopeInfo* ScopeInfo::Empty(Isolate* isolate) {
  return reinterpret_cast<ScopeInfo*>(isolate->heap()->empty_fixed_array());
135 136 137
}


138
ScopeType ScopeInfo::scope_type() {
139
  DCHECK(length() > 0);
140
  return ScopeTypeField::decode(Flags());
141 142 143
}


144 145
bool ScopeInfo::CallsEval() {
  return length() > 0 && CallsEvalField::decode(Flags());
146 147 148
}


149 150
StrictMode ScopeInfo::strict_mode() {
  return length() > 0 ? StrictModeField::decode(Flags()) : SLOPPY;
151 152 153
}


154 155
int ScopeInfo::LocalCount() {
  return StackLocalCount() + ContextLocalCount();
156 157 158
}


159 160 161 162 163 164 165
int ScopeInfo::StackSlotCount() {
  if (length() > 0) {
    bool function_name_stack_slot =
        FunctionVariableField::decode(Flags()) == STACK;
    return StackLocalCount() + (function_name_stack_slot ? 1 : 0);
  }
  return 0;
166 167 168
}


169 170 171 172 173
int ScopeInfo::ContextLength() {
  if (length() > 0) {
    int context_locals = ContextLocalCount();
    bool function_name_context_slot =
        FunctionVariableField::decode(Flags()) == CONTEXT;
174 175 176 177 178
    bool has_context = context_locals > 0 || function_name_context_slot ||
                       scope_type() == WITH_SCOPE ||
                       (scope_type() == ARROW_SCOPE && CallsEval()) ||
                       (scope_type() == FUNCTION_SCOPE && CallsEval()) ||
                       scope_type() == MODULE_SCOPE;
179 180 181 182
    if (has_context) {
      return Context::MIN_CONTEXT_SLOTS + context_locals +
          (function_name_context_slot ? 1 : 0);
    }
183
  }
184
  return 0;
185 186 187
}


188 189 190
bool ScopeInfo::HasFunctionName() {
  if (length() > 0) {
    return NONE != FunctionVariableField::decode(Flags());
191
  } else {
192
    return false;
193
  }
194 195 196
}


197 198 199 200 201
bool ScopeInfo::HasHeapAllocatedLocals() {
  if (length() > 0) {
    return ContextLocalCount() > 0;
  } else {
    return false;
202 203 204 205
  }
}


206
bool ScopeInfo::HasContext() {
207
  return ContextLength() > 0;
208 209 210
}


211
String* ScopeInfo::FunctionName() {
212
  DCHECK(HasFunctionName());
213
  return String::cast(get(FunctionNameEntryIndex()));
214 215 216
}


217
String* ScopeInfo::ParameterName(int var) {
218
  DCHECK(0 <= var && var < ParameterCount());
219 220
  int info_index = ParameterEntriesIndex() + var;
  return String::cast(get(info_index));
221 222 223
}


224
String* ScopeInfo::LocalName(int var) {
225 226
  DCHECK(0 <= var && var < LocalCount());
  DCHECK(StackLocalEntriesIndex() + StackLocalCount() ==
227 228 229
         ContextLocalNameEntriesIndex());
  int info_index = StackLocalEntriesIndex() + var;
  return String::cast(get(info_index));
230 231 232
}


233
String* ScopeInfo::StackLocalName(int var) {
234
  DCHECK(0 <= var && var < StackLocalCount());
235 236
  int info_index = StackLocalEntriesIndex() + var;
  return String::cast(get(info_index));
237 238 239
}


240
String* ScopeInfo::ContextLocalName(int var) {
241
  DCHECK(0 <= var && var < ContextLocalCount());
242 243
  int info_index = ContextLocalNameEntriesIndex() + var;
  return String::cast(get(info_index));
244 245 246
}


247
VariableMode ScopeInfo::ContextLocalMode(int var) {
248
  DCHECK(0 <= var && var < ContextLocalCount());
249 250 251 252 253 254 255
  int info_index = ContextLocalInfoEntriesIndex() + var;
  int value = Smi::cast(get(info_index))->value();
  return ContextLocalMode::decode(value);
}


InitializationFlag ScopeInfo::ContextLocalInitFlag(int var) {
256
  DCHECK(0 <= var && var < ContextLocalCount());
257 258 259
  int info_index = ContextLocalInfoEntriesIndex() + var;
  int value = Smi::cast(get(info_index))->value();
  return ContextLocalInitFlag::decode(value);
260 261 262
}


263
MaybeAssignedFlag ScopeInfo::ContextLocalMaybeAssignedFlag(int var) {
264
  DCHECK(0 <= var && var < ContextLocalCount());
265 266 267 268 269 270
  int info_index = ContextLocalInfoEntriesIndex() + var;
  int value = Smi::cast(get(info_index))->value();
  return ContextLocalMaybeAssignedFlag::decode(value);
}


271
bool ScopeInfo::LocalIsSynthetic(int var) {
272
  DCHECK(0 <= var && var < LocalCount());
273 274 275 276 277 278 279 280 281
  // There's currently no flag stored on the ScopeInfo to indicate that a
  // variable is a compiler-introduced temporary. However, to avoid conflict
  // with user declarations, the current temporaries like .generator_object and
  // .result start with a dot, so we can use that as a flag. It's a hack!
  Handle<String> name(LocalName(var));
  return name->length() > 0 && name->Get(0) == '.';
}


282
int ScopeInfo::StackSlotIndex(String* name) {
283
  DCHECK(name->IsInternalizedString());
284
  if (length() > 0) {
285 286 287 288 289 290
    int start = StackLocalEntriesIndex();
    int end = StackLocalEntriesIndex() + StackLocalCount();
    for (int i = start; i < end; ++i) {
      if (name == get(i)) {
        return i - start;
      }
291 292 293 294 295
    }
  }
  return -1;
}

296

297
int ScopeInfo::ContextSlotIndex(Handle<ScopeInfo> scope_info,
298 299 300
                                Handle<String> name, VariableMode* mode,
                                InitializationFlag* init_flag,
                                MaybeAssignedFlag* maybe_assigned_flag) {
301 302 303
  DCHECK(name->IsInternalizedString());
  DCHECK(mode != NULL);
  DCHECK(init_flag != NULL);
304 305 306
  if (scope_info->length() > 0) {
    ContextSlotCache* context_slot_cache =
        scope_info->GetIsolate()->context_slot_cache();
307 308
    int result = context_slot_cache->Lookup(*scope_info, *name, mode, init_flag,
                                            maybe_assigned_flag);
309
    if (result != ContextSlotCache::kNotFound) {
310
      DCHECK(result < scope_info->ContextLength());
311 312 313
      return result;
    }

314 315 316
    int start = scope_info->ContextLocalNameEntriesIndex();
    int end = scope_info->ContextLocalNameEntriesIndex() +
        scope_info->ContextLocalCount();
317
    for (int i = start; i < end; ++i) {
318
      if (*name == scope_info->get(i)) {
319
        int var = i - start;
320 321
        *mode = scope_info->ContextLocalMode(var);
        *init_flag = scope_info->ContextLocalInitFlag(var);
322
        *maybe_assigned_flag = scope_info->ContextLocalMaybeAssignedFlag(var);
323
        result = Context::MIN_CONTEXT_SLOTS + var;
324 325
        context_slot_cache->Update(scope_info, name, *mode, *init_flag,
                                   *maybe_assigned_flag, result);
326
        DCHECK(result < scope_info->ContextLength());
327
        return result;
328 329
      }
    }
330 331 332
    // Cache as not found. Mode, init flag and maybe assigned flag don't matter.
    context_slot_cache->Update(scope_info, name, INTERNAL, kNeedsInitialization,
                               kNotAssigned, -1);
333 334 335 336 337
  }
  return -1;
}


338
int ScopeInfo::ParameterIndex(String* name) {
339
  DCHECK(name->IsInternalizedString());
340
  if (length() > 0) {
341 342 343 344 345
    // We must read parameters from the end since for
    // multiply declared parameters the value of the
    // last declaration of that parameter is used
    // inside a function (and thus we need to look
    // at the last index). Was bug# 1110337.
346 347 348 349 350 351
    int start = ParameterEntriesIndex();
    int end = ParameterEntriesIndex() + ParameterCount();
    for (int i = end - 1; i >= start; --i) {
      if (name == get(i)) {
        return i - start;
      }
352 353 354 355 356 357
    }
  }
  return -1;
}


358
int ScopeInfo::FunctionContextSlotIndex(String* name, VariableMode* mode) {
359 360
  DCHECK(name->IsInternalizedString());
  DCHECK(mode != NULL);
361
  if (length() > 0) {
362 363 364 365
    if (FunctionVariableField::decode(Flags()) == CONTEXT &&
        FunctionName() == name) {
      *mode = FunctionVariableMode::decode(Flags());
      return Smi::cast(get(FunctionNameEntryIndex() + 1))->value();
366 367 368 369 370 371
    }
  }
  return -1;
}


372 373 374 375 376
bool ScopeInfo::CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
                                               Handle<Context> context,
                                               Handle<JSObject> scope_object) {
  Isolate* isolate = scope_info->GetIsolate();
  int local_count = scope_info->ContextLocalCount();
377 378
  if (local_count == 0) return true;
  // Fill all context locals to the context extension.
379
  int first_context_var = scope_info->StackLocalCount();
380
  int start = scope_info->ContextLocalNameEntriesIndex();
381 382 383
  for (int i = 0; i < local_count; ++i) {
    if (scope_info->LocalIsSynthetic(first_context_var + i)) continue;
    int context_index = Context::MIN_CONTEXT_SLOTS + i;
384 385 386
    Handle<Object> value = Handle<Object>(context->get(context_index), isolate);
    // Do not reflect variables under TDZ in scope object.
    if (value->IsTheHole()) continue;
387
    RETURN_ON_EXCEPTION_VALUE(
388 389 390 391
        isolate, Runtime::DefineObjectProperty(
                     scope_object,
                     Handle<String>(String::cast(scope_info->get(i + start))),
                     value, ::NONE),
392
        false);
393 394 395 396 397
  }
  return true;
}


398
int ScopeInfo::ParameterEntriesIndex() {
399
  DCHECK(length() > 0);
400 401 402 403 404 405 406 407 408 409 410 411 412 413
  return kVariablePartIndex;
}


int ScopeInfo::StackLocalEntriesIndex() {
  return ParameterEntriesIndex() + ParameterCount();
}


int ScopeInfo::ContextLocalNameEntriesIndex() {
  return StackLocalEntriesIndex() + StackLocalCount();
}


414
int ScopeInfo::ContextLocalInfoEntriesIndex() {
415 416 417 418 419
  return ContextLocalNameEntriesIndex() + ContextLocalCount();
}


int ScopeInfo::FunctionNameEntryIndex() {
420
  return ContextLocalInfoEntriesIndex() + ContextLocalCount();
421 422 423
}


424
int ContextSlotCache::Hash(Object* data, String* name) {
425 426
  // Uses only lower 32 bits if pointers are larger.
  uintptr_t addr_hash =
427
      static_cast<uint32_t>(reinterpret_cast<uintptr_t>(data)) >> 2;
428
  return static_cast<int>((addr_hash ^ name->Hash()) % kLength);
429 430 431
}


432 433 434
int ContextSlotCache::Lookup(Object* data, String* name, VariableMode* mode,
                             InitializationFlag* init_flag,
                             MaybeAssignedFlag* maybe_assigned_flag) {
435
  int index = Hash(data, name);
436
  Key& key = keys_[index];
437
  if ((key.data == data) && key.name->Equals(name)) {
438 439
    Value result(values_[index]);
    if (mode != NULL) *mode = result.mode();
440
    if (init_flag != NULL) *init_flag = result.initialization_flag();
441 442
    if (maybe_assigned_flag != NULL)
      *maybe_assigned_flag = result.maybe_assigned_flag();
443 444 445 446 447 448
    return result.index() + kNotFound;
  }
  return kNotFound;
}


449 450 451
void ContextSlotCache::Update(Handle<Object> data, Handle<String> name,
                              VariableMode mode, InitializationFlag init_flag,
                              MaybeAssignedFlag maybe_assigned_flag,
452
                              int slot_index) {
453
  DisallowHeapAllocation no_gc;
454
  Handle<String> internalized_name;
455
  DCHECK(slot_index > kNotFound);
456 457 458
  if (StringTable::InternalizeStringIfExists(name->GetIsolate(), name).
      ToHandle(&internalized_name)) {
    int index = Hash(*data, *internalized_name);
459
    Key& key = keys_[index];
460
    key.data = *data;
461
    key.name = *internalized_name;
462
    // Please note value only takes a uint as index.
463 464
    values_[index] = Value(mode, init_flag, maybe_assigned_flag,
                           slot_index - kNotFound).raw();
465
#ifdef DEBUG
466
    ValidateEntry(data, name, mode, init_flag, maybe_assigned_flag, slot_index);
467 468 469 470 471 472
#endif
  }
}


void ContextSlotCache::Clear() {
473
  for (int index = 0; index < kLength; index++) keys_[index].data = NULL;
474 475 476
}


477
#ifdef DEBUG
478

479
void ContextSlotCache::ValidateEntry(Handle<Object> data, Handle<String> name,
480
                                     VariableMode mode,
481
                                     InitializationFlag init_flag,
482
                                     MaybeAssignedFlag maybe_assigned_flag,
483
                                     int slot_index) {
484
  DisallowHeapAllocation no_gc;
485 486 487
  Handle<String> internalized_name;
  if (StringTable::InternalizeStringIfExists(name->GetIsolate(), name).
      ToHandle(&internalized_name)) {
488
    int index = Hash(*data, *name);
489
    Key& key = keys_[index];
490 491
    DCHECK(key.data == *data);
    DCHECK(key.name->Equals(*name));
492
    Value result(values_[index]);
493 494 495 496
    DCHECK(result.mode() == mode);
    DCHECK(result.initialization_flag() == init_flag);
    DCHECK(result.maybe_assigned_flag() == maybe_assigned_flag);
    DCHECK(result.index() + kNotFound == slot_index);
497 498 499 500
  }
}


501 502
static void PrintList(const char* list_name,
                      int nof_internal_slots,
503 504 505 506
                      int start,
                      int end,
                      ScopeInfo* scope_info) {
  if (start < end) {
507 508 509 510
    PrintF("\n  // %s\n", list_name);
    if (nof_internal_slots > 0) {
      PrintF("  %2d - %2d [internal slots]\n", 0 , nof_internal_slots - 1);
    }
511 512 513
    for (int i = nof_internal_slots; start < end; ++i, ++start) {
      PrintF("  %2d ", i);
      String::cast(scope_info->get(start))->ShortPrint();
514 515 516 517 518 519
      PrintF("\n");
    }
  }
}


520
void ScopeInfo::Print() {
521
  PrintF("ScopeInfo ");
522 523 524
  if (HasFunctionName()) {
    FunctionName()->ShortPrint();
  } else {
525
    PrintF("/* no function name */");
526
  }
527 528
  PrintF("{");

529 530 531 532 533 534 535 536 537 538 539 540 541
  PrintList("parameters", 0,
            ParameterEntriesIndex(),
            ParameterEntriesIndex() + ParameterCount(),
            this);
  PrintList("stack slots", 0,
            StackLocalEntriesIndex(),
            StackLocalEntriesIndex() + StackLocalCount(),
            this);
  PrintList("context slots",
            Context::MIN_CONTEXT_SLOTS,
            ContextLocalNameEntriesIndex(),
            ContextLocalNameEntriesIndex() + ContextLocalCount(),
            this);
542 543 544 545 546

  PrintF("}\n");
}
#endif  // DEBUG

547 548 549 550 551 552 553 554 555 556 557

//---------------------------------------------------------------------------
// ModuleInfo.

Handle<ModuleInfo> ModuleInfo::Create(
    Isolate* isolate, Interface* interface, Scope* scope) {
  Handle<ModuleInfo> info = Allocate(isolate, interface->Length());
  info->set_host_index(interface->Index());
  int i = 0;
  for (Interface::Iterator it = interface->iterator();
       !it.done(); it.Advance(), ++i) {
558
    Variable* var = scope->LookupLocal(it.name());
559
    info->set_name(i, *(it.name()->string()));
560
    info->set_mode(i, var->mode());
561
    DCHECK((var->mode() == MODULE) == (it.interface()->IsModule()));
562
    if (var->mode() == MODULE) {
563 564
      DCHECK(it.interface()->IsFrozen());
      DCHECK(it.interface()->Index() >= 0);
565 566
      info->set_index(i, it.interface()->Index());
    } else {
567
      DCHECK(var->index() >= 0);
568 569 570
      info->set_index(i, var->index());
    }
  }
571
  DCHECK(i == info->length());
572 573 574
  return info;
}

575
} }  // namespace v8::internal