blob: b198d962c89c6a7baa57c30c2c35f0ed657695b0 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "prettyprinter.h"
31#include "scopeinfo.h"
32#include "scopes.h"
33
34namespace v8 { namespace internal {
35
36// ----------------------------------------------------------------------------
37// A Zone allocator for use with LocalsMap.
38
39class ZoneAllocator: public Allocator {
40 public:
41 /* nothing to do */
42 virtual ~ZoneAllocator() {}
43
44 virtual void* New(size_t size) { return Zone::New(size); }
45
46 /* ignored - Zone is freed in one fell swoop */
47 virtual void Delete(void* p) {}
48};
49
50
51static ZoneAllocator LocalsMapAllocator;
52
53
54// ----------------------------------------------------------------------------
55// Implementation of LocalsMap
56//
57// Note: We are storing the handle locations as key values in the hash map.
58// When inserting a new variable via Declare(), we rely on the fact that
59// the handle location remains alive for the duration of that variable
60// use. Because a Variable holding a handle with the same location exists
61// this is ensured.
62
63static bool Match(void* key1, void* key2) {
64 String* name1 = *reinterpret_cast<String**>(key1);
65 String* name2 = *reinterpret_cast<String**>(key2);
66 ASSERT(name1->IsSymbol());
67 ASSERT(name2->IsSymbol());
68 return name1 == name2;
69}
70
71
72// Dummy constructor
73LocalsMap::LocalsMap(bool gotta_love_static_overloading) : HashMap() {}
74
75LocalsMap::LocalsMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
76LocalsMap::~LocalsMap() {}
77
78
79Variable* LocalsMap::Declare(Scope* scope,
80 Handle<String> name,
81 Variable::Mode mode,
82 bool is_valid_LHS,
83 bool is_this) {
84 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), true);
85 if (p->value == NULL) {
86 // The variable has not been declared yet -> insert it.
87 ASSERT(p->key == name.location());
88 p->value = new Variable(scope, name, mode, is_valid_LHS, is_this);
89 }
90 return reinterpret_cast<Variable*>(p->value);
91}
92
93
94Variable* LocalsMap::Lookup(Handle<String> name) {
95 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), false);
96 if (p != NULL) {
97 ASSERT(*reinterpret_cast<String**>(p->key) == *name);
98 ASSERT(p->value != NULL);
99 return reinterpret_cast<Variable*>(p->value);
100 }
101 return NULL;
102}
103
104
105// ----------------------------------------------------------------------------
106// Implementation of Scope
107
108
109// Dummy constructor
110Scope::Scope()
111 : inner_scopes_(0),
112 locals_(false),
113 temps_(0),
114 params_(0),
115 nonlocals_(0),
116 unresolved_(0),
117 decls_(0) {
118}
119
120
121Scope::Scope(Scope* outer_scope, Type type)
122 : outer_scope_(outer_scope),
123 inner_scopes_(4),
124 type_(type),
125 scope_name_(Factory::empty_symbol()),
126 locals_(),
127 temps_(4),
128 params_(4),
129 nonlocals_(4),
130 unresolved_(16),
131 decls_(4),
132 receiver_(NULL),
133 function_(NULL),
134 arguments_(NULL),
135 arguments_shadow_(NULL),
136 illegal_redecl_(NULL),
137 scope_inside_with_(false),
138 scope_contains_with_(false),
139 scope_calls_eval_(false),
140 outer_scope_calls_eval_(false),
141 inner_scope_calls_eval_(false),
142 force_eager_compilation_(false),
143 num_stack_slots_(0),
144 num_heap_slots_(0) {
145 // At some point we might want to provide outer scopes to
146 // eval scopes (by walking the stack and reading the scope info).
147 // In that case, the ASSERT below needs to be adjusted.
148 ASSERT((type == GLOBAL_SCOPE || type == EVAL_SCOPE) == (outer_scope == NULL));
149 ASSERT(!HasIllegalRedeclaration());
150}
151
152
153void Scope::Initialize(bool inside_with) {
154 // Add this scope as a new inner scope of the outer scope.
155 if (outer_scope_ != NULL) {
156 outer_scope_->inner_scopes_.Add(this);
157 scope_inside_with_ = outer_scope_->scope_inside_with_ || inside_with;
158 } else {
159 scope_inside_with_ = inside_with;
160 }
161
162 // Declare convenience variables.
163 // Declare and allocate receiver (even for the global scope, and even
164 // if naccesses_ == 0).
165 // NOTE: When loading parameters in the global scope, we must take
166 // care not to access them as properties of the global object, but
167 // instead load them directly from the stack. Currently, the only
168 // such parameter is 'this' which is passed on the stack when
169 // invoking scripts
170 { Variable* var =
171 locals_.Declare(this, Factory::this_symbol(), Variable::VAR, false, true);
172 var->rewrite_ = new Slot(var, Slot::PARAMETER, -1);
173 receiver_ = new VariableProxy(Factory::this_symbol(), true, false);
174 receiver_->BindTo(var);
175 }
176
177 if (is_function_scope()) {
178 // Declare 'arguments' variable which exists in all functions.
179 // Note that it may never be accessed, in which case it won't
180 // be allocated during variable allocation.
181 Declare(Factory::arguments_symbol(), Variable::VAR);
182 }
183}
184
185
186
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000187Variable* Scope::LookupLocal(Handle<String> name) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000188 return locals_.Lookup(name);
189}
190
191
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000192Variable* Scope::Lookup(Handle<String> name) {
193 for (Scope* scope = this;
194 scope != NULL;
195 scope = scope->outer_scope()) {
196 Variable* var = scope->LookupLocal(name);
197 if (var != NULL) return var;
198 }
199 return NULL;
200}
201
202
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000203Variable* Scope::DeclareFunctionVar(Handle<String> name) {
204 ASSERT(is_function_scope() && function_ == NULL);
205 function_ = new Variable(this, name, Variable::CONST, true, false);
206 return function_;
207}
208
209
210Variable* Scope::Declare(Handle<String> name, Variable::Mode mode) {
211 // DYNAMIC variables are introduces during variable allocation,
212 // INTERNAL variables are allocated explicitly, and TEMPORARY
213 // variables are allocated via NewTemporary().
214 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
215 return locals_.Declare(this, name, mode, true, false);
216}
217
218
219void Scope::AddParameter(Variable* var) {
220 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000221 ASSERT(LookupLocal(var->name()) == var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222 params_.Add(var);
223}
224
225
226VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
227 // Note that we must not share the unresolved variables with
228 // the same name because they may be removed selectively via
229 // RemoveUnresolved().
230 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
231 unresolved_.Add(proxy);
232 return proxy;
233}
234
235
236void Scope::RemoveUnresolved(VariableProxy* var) {
237 // Most likely (always?) any variable we want to remove
238 // was just added before, so we search backwards.
239 for (int i = unresolved_.length(); i-- > 0;) {
240 if (unresolved_[i] == var) {
241 unresolved_.Remove(i);
242 return;
243 }
244 }
245}
246
247
248VariableProxy* Scope::NewTemporary(Handle<String> name) {
249 Variable* var = new Variable(this, name, Variable::TEMPORARY, true, false);
250 VariableProxy* tmp = new VariableProxy(name, false, false);
251 tmp->BindTo(var);
252 temps_.Add(var);
253 return tmp;
254}
255
256
257void Scope::AddDeclaration(Declaration* declaration) {
258 decls_.Add(declaration);
259}
260
261
262void Scope::SetIllegalRedeclaration(Expression* expression) {
263 // Only set the illegal redeclaration expression the
264 // first time the function is called.
265 if (!HasIllegalRedeclaration()) {
266 illegal_redecl_ = expression;
267 }
268 ASSERT(HasIllegalRedeclaration());
269}
270
271
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000272void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000273 ASSERT(HasIllegalRedeclaration());
274 illegal_redecl_->Accept(visitor);
275}
276
277
278template<class Allocator>
279void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
280 // Collect variables in this scope.
281 // Note that the function_ variable - if present - is not
282 // collected here but handled separately in ScopeInfo
283 // which is the current user of this function).
284 for (int i = 0; i < temps_.length(); i++) {
285 Variable* var = temps_[i];
286 if (var->var_uses()->is_used()) {
287 locals->Add(var);
288 }
289 }
290 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
291 Variable* var = reinterpret_cast<Variable*>(p->value);
292 if (var->var_uses()->is_used()) {
293 locals->Add(var);
294 }
295 }
296}
297
298
299// Make sure the method gets instantiated by the template system.
300template void Scope::CollectUsedVariables(
301 List<Variable*, FreeStoreAllocationPolicy>* locals);
302template void Scope::CollectUsedVariables(
303 List<Variable*, PreallocatedStorage>* locals);
304
305
306void Scope::AllocateVariables() {
307 ASSERT(outer_scope_ == NULL); // eval or global scopes only
308
309 // 1) Propagate scope information.
310 // If we are in an eval scope, we may have other outer scopes about
311 // which we don't know anything at this point. Thus we must be conservative
312 // and assume they may invoke eval themselves. Eventually we could capture
313 // this information in the ScopeInfo and then use it here (by traversing
314 // the call chain stack, at compile time).
315 PropagateScopeInfo(is_eval_scope());
316
317 // 2) Resolve variables.
318 Scope* global_scope = NULL;
319 if (is_global_scope()) global_scope = this;
320 ResolveVariablesRecursively(global_scope);
321
322 // 3) Allocate variables.
323 AllocateVariablesRecursively();
324}
325
326
327bool Scope::SupportsEval() const {
328 return scope_calls_eval_ || inner_scope_calls_eval_;
329}
330
331
332bool Scope::AllowsLazyCompilation() const {
333 return !force_eager_compilation_ && HasTrivialOuterContext();
334}
335
336
337bool Scope::HasTrivialContext() const {
338 // A function scope has a trivial context if it always is the global
339 // context. We iteratively scan out the context chain to see if
340 // there is anything that makes this scope non-trivial; otherwise we
341 // return true.
342 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
343 if (scope->is_eval_scope()) return false;
344 if (scope->scope_inside_with_) return false;
345 if (scope->num_heap_slots_ > 0) return false;
346 }
347 return true;
348}
349
350
351bool Scope::HasTrivialOuterContext() const {
352 Scope* outer = outer_scope_;
353 if (outer == NULL) return true;
354 // Note that the outer context may be trivial in general, but the current
355 // scope may be inside a 'with' statement in which case the outer context
356 // for this scope is not trivial.
357 return !scope_inside_with_ && outer->HasTrivialContext();
358}
359
360
361int Scope::ContextChainLength(Scope* scope) {
362 int n = 0;
363 for (Scope* s = this; s != scope; s = s->outer_scope_) {
364 ASSERT(s != NULL); // scope must be in the scope chain
365 if (s->num_heap_slots() > 0) n++;
366 }
367 return n;
368}
369
370
371#ifdef DEBUG
372static const char* Header(Scope::Type type) {
373 switch (type) {
374 case Scope::EVAL_SCOPE: return "eval";
375 case Scope::FUNCTION_SCOPE: return "function";
376 case Scope::GLOBAL_SCOPE: return "global";
377 }
378 UNREACHABLE();
379 return NULL;
380}
381
382
383static void Indent(int n, const char* str) {
384 PrintF("%*s%s", n, "", str);
385}
386
387
388static void PrintName(Handle<String> name) {
389 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
390 PrintF("%s", *s);
391}
392
393
394static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
395 if (var->var_uses()->is_used() || var->rewrite() != NULL) {
396 Indent(indent, Variable::Mode2String(var->mode()));
397 PrintF(" ");
398 PrintName(var->name());
399 PrintF("; // ");
400 if (var->rewrite() != NULL) PrintF("%s, ", printer->Print(var->rewrite()));
401 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access, ");
402 PrintF("var ");
403 var->var_uses()->Print();
404 PrintF(", obj ");
405 var->obj_uses()->Print();
406 PrintF("\n");
407 }
408}
409
410
411void Scope::Print(int n) {
412 int n0 = (n > 0 ? n : 0);
413 int n1 = n0 + 2; // indentation
414
415 // Print header.
416 Indent(n0, Header(type_));
417 if (scope_name_->length() > 0) {
418 PrintF(" ");
419 PrintName(scope_name_);
420 }
421
422 // Print parameters, if any.
423 if (is_function_scope()) {
424 PrintF(" (");
425 for (int i = 0; i < params_.length(); i++) {
426 if (i > 0) PrintF(", ");
427 PrintName(params_[i]->name());
428 }
429 PrintF(")");
430 }
431
432 PrintF(" {\n");
433
434 // Function name, if any (named function literals, only).
435 if (function_ != NULL) {
436 Indent(n1, "// (local) function name: ");
437 PrintName(function_->name());
438 PrintF("\n");
439 }
440
441 // Scope info.
442 if (HasTrivialOuterContext()) {
443 Indent(n1, "// scope has trivial outer context\n");
444 }
445 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
446 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
447 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
448 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
449 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
450 if (num_stack_slots_ > 0) { Indent(n1, "// ");
451 PrintF("%d stack slots\n", num_stack_slots_); }
452 if (num_heap_slots_ > 0) { Indent(n1, "// ");
453 PrintF("%d heap slots\n", num_heap_slots_); }
454
455 // Print locals.
456 PrettyPrinter printer;
457 Indent(n1, "// function var\n");
458 if (function_ != NULL) {
459 PrintVar(&printer, n1, function_);
460 }
461
462 Indent(n1, "// temporary vars\n");
463 for (int i = 0; i < temps_.length(); i++) {
464 PrintVar(&printer, n1, temps_[i]);
465 }
466
467 Indent(n1, "// local vars\n");
468 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
469 Variable* var = reinterpret_cast<Variable*>(p->value);
470 PrintVar(&printer, n1, var);
471 }
472
473 Indent(n1, "// nonlocal vars\n");
474 for (int i = 0; i < nonlocals_.length(); i++)
475 PrintVar(&printer, n1, nonlocals_[i]);
476
477 // Print inner scopes (disable by providing negative n).
478 if (n >= 0) {
479 for (int i = 0; i < inner_scopes_.length(); i++) {
480 PrintF("\n");
481 inner_scopes_[i]->Print(n1);
482 }
483 }
484
485 Indent(n0, "}\n");
486}
487#endif // DEBUG
488
489
490Variable* Scope::NonLocal(Handle<String> name) {
491 // Space optimization: reuse existing non-local with the same name.
492 for (int i = 0; i < nonlocals_.length(); i++) {
493 Variable* var = nonlocals_[i];
494 if (var->name().is_identical_to(name)) {
495 ASSERT(var->mode() == Variable::DYNAMIC);
496 return var;
497 }
498 }
499
500 // Otherwise create a new new-local and add it to the list.
501 Variable* var = new Variable(
502 NULL /* we don't know the scope */,
503 name, Variable::DYNAMIC, true, false);
504 nonlocals_.Add(var);
505
506 // Allocate it by giving it a dynamic lookup.
507 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
508
509 return var;
510}
511
512
513// Lookup a variable starting with this scope. The result is either
514// the statically resolved (local!) variable belonging to an outer scope,
515// or NULL. It may be NULL because a) we couldn't find a variable, or b)
516// because the variable is just a guess (and may be shadowed by another
517// variable that is introduced dynamically via an 'eval' call or a 'with'
518// statement).
519Variable* Scope::LookupRecursive(Handle<String> name, bool inner_lookup) {
520 // If we find a variable, but the current scope calls 'eval', the found
521 // variable may not be the correct one (the 'eval' may introduce a
522 // property with the same name). In that case, remember that the variable
523 // found is just a guess.
524 bool guess = scope_calls_eval_;
525
526 // Try to find the variable in this scope.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000527 Variable* var = LookupLocal(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528
529 if (var != NULL) {
530 // We found a variable. If this is not an inner lookup, we are done.
531 // (Even if there is an 'eval' in this scope which introduces the
532 // same variable again, the resulting variable remains the same.
533 // Note that enclosing 'with' statements are handled at the call site.)
534 if (!inner_lookup)
535 return var;
536
537 } else {
538 // We did not find a variable locally. Check against the function variable,
539 // if any. We can do this for all scopes, since the function variable is
540 // only present - if at all - for function scopes.
541 //
542 // This lookup corresponds to a lookup in the "intermediate" scope sitting
543 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
544 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000545 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000546 if (function_ != NULL && function_->name().is_identical_to(name)) {
547 var = function_;
548
549 } else if (outer_scope_ != NULL) {
550 var = outer_scope_->LookupRecursive(name, true /* inner lookup */);
551 // We may have found a variable in an outer scope. However, if
552 // the current scope is inside a 'with', the actual variable may
553 // be a property introduced via the 'with' statement. Then, the
554 // variable we may have found is just a guess.
555 if (scope_inside_with_)
556 guess = true;
557 }
558
559 // If we did not find a variable, we are done.
560 if (var == NULL)
561 return NULL;
562 }
563
564 ASSERT(var != NULL);
565
566 // If this is a lookup from an inner scope, mark the variable.
567 if (inner_lookup)
568 var->is_accessed_from_inner_scope_ = true;
569
570 // If the variable we have found is just a guess, invalidate the result.
571 if (guess)
572 var = NULL;
573
574 return var;
575}
576
577
578void Scope::ResolveVariable(Scope* global_scope, VariableProxy* proxy) {
579 ASSERT(global_scope == NULL || global_scope->is_global_scope());
580
581 // If the proxy is already resolved there's nothing to do
582 // (functions and consts may be resolved by the parser).
583 if (proxy->var() != NULL) return;
584
585 // Otherwise, try to resolve the variable.
586 Variable* var = LookupRecursive(proxy->name(), false);
587
588 if (proxy->inside_with()) {
589 // If we are inside a local 'with' statement, all bets are off
590 // and we cannot resolve the proxy to a local variable even if
591 // we found an outer matching variable.
592 // Note that we must do a lookup anyway, because if we find one,
593 // we must mark that variable as potentially accessed from this
594 // inner scope (the property may not be in the 'with' object).
595 var = NonLocal(proxy->name());
596
597 } else {
598 // We are not inside a local 'with' statement.
599
600 if (var == NULL) {
601 // We did not find the variable. We have a global variable
602 // if we are in the global scope (we know already that we
603 // are outside a 'with' statement) or if there is no way
604 // that the variable might be introduced dynamically (through
605 // a local or outer eval() call, or an outer 'with' statement),
606 // or we don't know about the outer scope (because we are
607 // in an eval scope).
608 if (!is_global_scope() &&
609 (is_eval_scope() || outer_scope_calls_eval_ ||
610 scope_calls_eval_ || scope_inside_with_)) {
611 // We must look up the variable at runtime, and we don't
612 // know anything else.
613 var = NonLocal(proxy->name());
614
615 } else {
616 // We must have a global variable.
617 ASSERT(global_scope != NULL);
618 var = new Variable(global_scope, proxy->name(),
619 Variable::DYNAMIC, true, false);
620 // Ideally we simply rewrite these variables into property
621 // accesses. Unfortunately, we cannot do this here at the
622 // moment because then we can't differentiate between
623 // global variable ('x') and global property ('this.x') access.
624 // If 'x' doesn't exist, the former leads to an error, while the
625 // latter returns undefined. Sigh...
626 // var->rewrite_ = new Property(new Literal(env_->global()),
627 // new Literal(proxy->name()));
628 }
629 }
630 }
631
632 proxy->BindTo(var);
633}
634
635
636void Scope::ResolveVariablesRecursively(Scope* global_scope) {
637 ASSERT(global_scope == NULL || global_scope->is_global_scope());
638
639 // Resolve unresolved variables for this scope.
640 for (int i = 0; i < unresolved_.length(); i++) {
641 ResolveVariable(global_scope, unresolved_[i]);
642 }
643
644 // Resolve unresolved variables for inner scopes.
645 for (int i = 0; i < inner_scopes_.length(); i++) {
646 inner_scopes_[i]->ResolveVariablesRecursively(global_scope);
647 }
648}
649
650
651bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval) {
652 if (outer_scope_calls_eval) {
653 outer_scope_calls_eval_ = true;
654 }
655
656 bool b = scope_calls_eval_ || outer_scope_calls_eval_;
657 for (int i = 0; i < inner_scopes_.length(); i++) {
658 Scope* inner_scope = inner_scopes_[i];
659 if (inner_scope->PropagateScopeInfo(b)) {
660 inner_scope_calls_eval_ = true;
661 }
662 if (inner_scope->force_eager_compilation_) {
663 force_eager_compilation_ = true;
664 }
665 }
666
667 return scope_calls_eval_ || inner_scope_calls_eval_;
668}
669
670
671bool Scope::MustAllocate(Variable* var) {
672 // Give var a read/write use if there is a chance it might be
673 // accessed via an eval() call, or if it is a global variable.
674 // This is only possible if the variable has a visible name.
675 if ((var->is_this() || var->name()->length() > 0) &&
676 (var->is_accessed_from_inner_scope_ ||
677 scope_calls_eval_ || inner_scope_calls_eval_ ||
678 scope_contains_with_ || var->is_global())) {
679 var->var_uses()->RecordAccess(1);
680 }
681 return var->var_uses()->is_used();
682}
683
684
685bool Scope::MustAllocateInContext(Variable* var) {
686 // If var is accessed from an inner scope, or if there is a
687 // possibility that it might be accessed from the current or
688 // an inner scope (through an eval() call), it must be allocated
689 // in the context.
690 // Exceptions: Global variables and temporary variables must
691 // never be allocated in the (FixedArray part of the) context.
692 return
693 var->mode() != Variable::TEMPORARY &&
694 (var->is_accessed_from_inner_scope_ ||
695 scope_calls_eval_ || inner_scope_calls_eval_ ||
696 scope_contains_with_ || var->is_global());
697}
698
699
700bool Scope::HasArgumentsParameter() {
701 for (int i = 0; i < params_.length(); i++) {
702 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
703 return true;
704 }
705 return false;
706}
707
708
709void Scope::AllocateStackSlot(Variable* var) {
710 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
711}
712
713
714void Scope::AllocateHeapSlot(Variable* var) {
715 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
716}
717
718
719void Scope::AllocateParameterLocals() {
720 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000721 Variable* arguments = LookupLocal(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
723 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
724 // 'arguments' is used. Unless there is also a parameter called
725 // 'arguments', we must be conservative and access all parameters via
726 // the arguments object: The i'th parameter is rewritten into
727 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
728 // (new) value is always assigned to it via the function
729 // invocation. Then 'arguments' denotes that specific parameter value
730 // and cannot be used to access the parameters, which is why we don't
731 // need to rewrite in that case.
732 //
733 // (*) Instead of having a parameter called 'arguments', we may have an
734 // assignment to 'arguments' in the function body, at some arbitrary
735 // point in time (possibly through an 'eval()' call!). After that
736 // assignment any re-write of parameters would be invalid (was bug
737 // 881452). Thus, we introduce a shadow '.arguments'
738 // variable which also points to the arguments object. For rewrites we
739 // use '.arguments' which remains valid even if we assign to
740 // 'arguments'. To summarize: If we need to rewrite, we allocate an
741 // 'arguments' object dynamically upon function invocation. The compiler
742 // introduces 2 local variables 'arguments' and '.arguments', both of
743 // which originally point to the arguments object that was
744 // allocated. All parameters are rewritten into property accesses via
745 // the '.arguments' variable. Thus, any changes to properties of
746 // 'arguments' are reflected in the variables and vice versa. If the
747 // 'arguments' variable is changed, '.arguments' still points to the
748 // correct arguments object and the rewrites still work.
749
750 // We are using 'arguments'. Tell the code generator that is needs to
751 // allocate the arguments object by setting 'arguments_'.
752 arguments_ = new VariableProxy(Factory::arguments_symbol(), false, false);
753 arguments_->BindTo(arguments);
754
755 // We also need the '.arguments' shadow variable. Declare it and create
756 // and bind the corresponding proxy. It's ok to declare it only now
757 // because it's a local variable that is allocated after the parameters
758 // have been allocated.
759 //
760 // Note: This is "almost" at temporary variable but we cannot use
761 // NewTemporary() because the mode needs to be INTERNAL since this
762 // variable may be allocated in the heap-allocated context (temporaries
763 // are never allocated in the context).
764 Variable* arguments_shadow =
765 new Variable(this, Factory::arguments_shadow_symbol(),
766 Variable::INTERNAL, true, false);
767 arguments_shadow_ =
768 new VariableProxy(Factory::arguments_shadow_symbol(), false, false);
769 arguments_shadow_->BindTo(arguments_shadow);
770 temps_.Add(arguments_shadow);
771
772 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
773 for (int i = 0; i < params_.length(); i++) {
774 Variable* var = params_[i];
775 ASSERT(var->scope() == this);
776 if (MustAllocate(var)) {
777 if (MustAllocateInContext(var)) {
778 // It is ok to set this only now, because arguments is a local
779 // variable that is allocated after the parameters have been
780 // allocated.
781 arguments_shadow->is_accessed_from_inner_scope_ = true;
782 }
783 var->rewrite_ =
784 new Property(arguments_shadow_,
785 new Literal(Handle<Object>(Smi::FromInt(i))),
ager@chromium.org236ad962008-09-25 09:45:57 +0000786 RelocInfo::kNoPosition);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000787 arguments_shadow->var_uses()->RecordUses(var->var_uses());
788 }
789 }
790
791 } else {
792 // The arguments object is not used, so we can access parameters directly.
793 // The same parameter may occur multiple times in the parameters_ list.
794 // If it does, and if it is not copied into the context object, it must
795 // receive the highest parameter index for that parameter; thus iteration
796 // order is relevant!
797 for (int i = 0; i < params_.length(); i++) {
798 Variable* var = params_[i];
799 ASSERT(var->scope() == this);
800 if (MustAllocate(var)) {
801 if (MustAllocateInContext(var)) {
802 ASSERT(var->rewrite_ == NULL ||
803 (var->slot() != NULL && var->slot()->type() == Slot::CONTEXT));
804 if (var->rewrite_ == NULL) {
805 // Only set the heap allocation if the parameter has not
806 // been allocated yet.
807 AllocateHeapSlot(var);
808 }
809 } else {
810 ASSERT(var->rewrite_ == NULL ||
811 (var->slot() != NULL &&
812 var->slot()->type() == Slot::PARAMETER));
813 // Set the parameter index always, even if the parameter
814 // was seen before! (We need to access the actual parameter
815 // supplied for the last occurrence of a multiply declared
816 // parameter.)
817 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
818 }
819 }
820 }
821 }
822}
823
824
825void Scope::AllocateNonParameterLocal(Variable* var) {
826 ASSERT(var->scope() == this);
827 ASSERT(var->rewrite_ == NULL ||
828 (!var->IsVariable(Factory::result_symbol())) ||
829 (var->slot() == NULL || var->slot()->type() != Slot::LOCAL));
830 if (MustAllocate(var) && var->rewrite_ == NULL) {
831 if (MustAllocateInContext(var)) {
832 AllocateHeapSlot(var);
833 } else {
834 AllocateStackSlot(var);
835 }
836 }
837}
838
839
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000840void Scope::AllocateNonParameterLocals() {
841 // Each variable occurs exactly once in the locals_ list; all
842 // variables that have no rewrite yet are non-parameter locals.
843
844 // Sort them according to use such that the locals with more uses
845 // get allocated first.
846 if (FLAG_usage_computation) {
847 // This is currently not implemented.
848 }
849
850 for (int i = 0; i < temps_.length(); i++) {
851 AllocateNonParameterLocal(temps_[i]);
852 }
853
854 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
855 Variable* var = reinterpret_cast<Variable*>(p->value);
856 AllocateNonParameterLocal(var);
857 }
858
859 // Note: For now, function_ must be allocated at the very end. If
860 // it gets allocated in the context, it must be the last slot in the
861 // context, because of the current ScopeInfo implementation (see
862 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
863 if (function_ != NULL) {
864 AllocateNonParameterLocal(function_);
865 }
866}
867
868
869void Scope::AllocateVariablesRecursively() {
870 // The number of slots required for variables.
871 num_stack_slots_ = 0;
872 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
873
874 // Allocate variables for inner scopes.
875 for (int i = 0; i < inner_scopes_.length(); i++) {
876 inner_scopes_[i]->AllocateVariablesRecursively();
877 }
878
879 // Allocate variables for this scope.
880 // Parameters must be allocated first, if any.
881 if (is_function_scope()) AllocateParameterLocals();
882 AllocateNonParameterLocals();
883
884 // Allocate context if necessary.
885 bool must_have_local_context = false;
886 if (scope_calls_eval_ || scope_contains_with_) {
887 // The context for the eval() call or 'with' statement in this scope.
888 // Unless we are in the global or an eval scope, we need a local
889 // context even if we didn't statically allocate any locals in it,
890 // and the compiler will access the context variable. If we are
891 // not in an inner scope, the scope is provided from the outside.
892 must_have_local_context = is_function_scope();
893 }
894
895 // If we didn't allocate any locals in the local context, then we only
896 // need the minimal number of slots if we must have a local context.
897 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
898 !must_have_local_context) {
899 num_heap_slots_ = 0;
900 }
901
902 // Allocation done.
903 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
904}
905
906} } // namespace v8::internal