Upgrade v8 to 1.3.4
[platform/upstream/nodejs.git] / deps / v8 / src / compiler.cc
1 // Copyright 2009 the V8 project authors. All rights reserved.
2 // 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 "bootstrapper.h"
31 #include "cfg.h"
32 #include "codegen-inl.h"
33 #include "compilation-cache.h"
34 #include "compiler.h"
35 #include "debug.h"
36 #include "oprofile-agent.h"
37 #include "rewriter.h"
38 #include "scopes.h"
39 #include "usage-analyzer.h"
40
41 namespace v8 {
42 namespace internal {
43
44 static Handle<Code> MakeCode(FunctionLiteral* literal,
45                              Handle<Script> script,
46                              Handle<Context> context,
47                              bool is_eval) {
48   ASSERT(literal != NULL);
49
50   // Rewrite the AST by introducing .result assignments where needed.
51   if (!Rewriter::Process(literal) || !AnalyzeVariableUsage(literal)) {
52     // Signal a stack overflow by returning a null handle.  The stack
53     // overflow exception will be thrown by the caller.
54     return Handle<Code>::null();
55   }
56
57   {
58     // Compute top scope and allocate variables. For lazy compilation
59     // the top scope only contains the single lazily compiled function,
60     // so this doesn't re-allocate variables repeatedly.
61     HistogramTimerScope timer(&Counters::variable_allocation);
62     Scope* top = literal->scope();
63     while (top->outer_scope() != NULL) top = top->outer_scope();
64     top->AllocateVariables(context);
65   }
66
67 #ifdef DEBUG
68   if (Bootstrapper::IsActive() ?
69       FLAG_print_builtin_scopes :
70       FLAG_print_scopes) {
71     literal->scope()->Print();
72   }
73 #endif
74
75   // Optimize the AST.
76   if (!Rewriter::Optimize(literal)) {
77     // Signal a stack overflow by returning a null handle.  The stack
78     // overflow exception will be thrown by the caller.
79     return Handle<Code>::null();
80   }
81
82   if (FLAG_multipass) {
83     CfgGlobals scope(literal);
84     Cfg* cfg = Cfg::Build();
85 #ifdef DEBUG
86     if (FLAG_print_cfg && cfg != NULL) {
87       SmartPointer<char> name = literal->name()->ToCString();
88       PrintF("Function \"%s\":\n", *name);
89       cfg->Print();
90       PrintF("\n");
91     }
92 #endif
93     if (cfg != NULL) {
94       return cfg->Compile(script);
95     }
96   }
97
98   // Generate code and return it.
99   Handle<Code> result = CodeGenerator::MakeCode(literal, script, is_eval);
100   return result;
101 }
102
103
104 static bool IsValidJSON(FunctionLiteral* lit) {
105   if (lit->body()->length() != 1)
106     return false;
107   Statement* stmt = lit->body()->at(0);
108   if (stmt->AsExpressionStatement() == NULL)
109     return false;
110   Expression* expr = stmt->AsExpressionStatement()->expression();
111   return expr->IsValidJSON();
112 }
113
114
115 static Handle<JSFunction> MakeFunction(bool is_global,
116                                        bool is_eval,
117                                        Compiler::ValidationState validate,
118                                        Handle<Script> script,
119                                        Handle<Context> context,
120                                        v8::Extension* extension,
121                                        ScriptDataImpl* pre_data) {
122   CompilationZoneScope zone_scope(DELETE_ON_EXIT);
123
124   // Make sure we have an initial stack limit.
125   StackGuard guard;
126   PostponeInterruptsScope postpone;
127
128   ASSERT(!i::Top::global_context().is_null());
129   script->set_context_data((*i::Top::global_context())->data());
130
131 #ifdef ENABLE_DEBUGGER_SUPPORT
132   bool is_json = (validate == Compiler::VALIDATE_JSON);
133   if (is_eval || is_json) {
134     script->set_compilation_type(
135         is_json ? Smi::FromInt(Script::COMPILATION_TYPE_JSON) :
136                                Smi::FromInt(Script::COMPILATION_TYPE_EVAL));
137     // For eval scripts add information on the function from which eval was
138     // called.
139     if (is_eval) {
140       JavaScriptFrameIterator it;
141       script->set_eval_from_function(it.frame()->function());
142       int offset = it.frame()->pc() - it.frame()->code()->instruction_start();
143       script->set_eval_from_instructions_offset(Smi::FromInt(offset));
144     }
145   }
146
147   // Notify debugger
148   Debugger::OnBeforeCompile(script);
149 #endif
150
151   // Only allow non-global compiles for eval.
152   ASSERT(is_eval || is_global);
153
154   // Build AST.
155   FunctionLiteral* lit = MakeAST(is_global, script, extension, pre_data);
156
157   // Check for parse errors.
158   if (lit == NULL) {
159     ASSERT(Top::has_pending_exception());
160     return Handle<JSFunction>::null();
161   }
162
163   // When parsing JSON we do an ordinary parse and then afterwards
164   // check the AST to ensure it was well-formed.  If not we give a
165   // syntax error.
166   if (validate == Compiler::VALIDATE_JSON && !IsValidJSON(lit)) {
167     HandleScope scope;
168     Handle<JSArray> args = Factory::NewJSArray(1);
169     Handle<Object> source(script->source());
170     SetElement(args, 0, source);
171     Handle<Object> result = Factory::NewSyntaxError("invalid_json", args);
172     Top::Throw(*result, NULL);
173     return Handle<JSFunction>::null();
174   }
175
176   // Measure how long it takes to do the compilation; only take the
177   // rest of the function into account to avoid overlap with the
178   // parsing statistics.
179   HistogramTimer* rate = is_eval
180       ? &Counters::compile_eval
181       : &Counters::compile;
182   HistogramTimerScope timer(rate);
183
184   // Compile the code.
185   Handle<Code> code = MakeCode(lit, script, context, is_eval);
186
187   // Check for stack-overflow exceptions.
188   if (code.is_null()) {
189     Top::StackOverflow();
190     return Handle<JSFunction>::null();
191   }
192
193 #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT
194   // Log the code generation for the script. Check explicit whether logging is
195   // to avoid allocating when not required.
196   if (Logger::is_logging() || OProfileAgent::is_enabled()) {
197     if (script->name()->IsString()) {
198       SmartPointer<char> data =
199           String::cast(script->name())->ToCString(DISALLOW_NULLS);
200       LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG,
201                           *code, *data));
202       OProfileAgent::CreateNativeCodeRegion(*data,
203                                             code->instruction_start(),
204                                             code->instruction_size());
205     } else {
206       LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG,
207                           *code, ""));
208       OProfileAgent::CreateNativeCodeRegion(is_eval ? "Eval" : "Script",
209                                             code->instruction_start(),
210                                             code->instruction_size());
211     }
212   }
213 #endif
214
215   // Allocate function.
216   Handle<JSFunction> fun =
217       Factory::NewFunctionBoilerplate(lit->name(),
218                                       lit->materialized_literal_count(),
219                                       lit->contains_array_literal(),
220                                       code);
221
222   CodeGenerator::SetFunctionInfo(fun, lit->scope()->num_parameters(),
223                                  RelocInfo::kNoPosition,
224                                  lit->start_position(), lit->end_position(),
225                                  lit->is_expression(), true, script,
226                                  lit->inferred_name());
227
228   // Hint to the runtime system used when allocating space for initial
229   // property space by setting the expected number of properties for
230   // the instances of the function.
231   SetExpectedNofPropertiesFromEstimate(fun, lit->expected_property_count());
232
233 #ifdef ENABLE_DEBUGGER_SUPPORT
234   // Notify debugger
235   Debugger::OnAfterCompile(script, fun);
236 #endif
237
238   return fun;
239 }
240
241
242 static StaticResource<SafeStringInputBuffer> safe_string_input_buffer;
243
244
245 Handle<JSFunction> Compiler::Compile(Handle<String> source,
246                                      Handle<Object> script_name,
247                                      int line_offset, int column_offset,
248                                      v8::Extension* extension,
249                                      ScriptDataImpl* input_pre_data) {
250   int source_length = source->length();
251   Counters::total_load_size.Increment(source_length);
252   Counters::total_compile_size.Increment(source_length);
253
254   // The VM is in the COMPILER state until exiting this function.
255   VMState state(COMPILER);
256
257   // Do a lookup in the compilation cache but not for extensions.
258   Handle<JSFunction> result;
259   if (extension == NULL) {
260     result = CompilationCache::LookupScript(source,
261                                             script_name,
262                                             line_offset,
263                                             column_offset);
264   }
265
266   if (result.is_null()) {
267     // No cache entry found. Do pre-parsing and compile the script.
268     ScriptDataImpl* pre_data = input_pre_data;
269     if (pre_data == NULL && source_length >= FLAG_min_preparse_length) {
270       Access<SafeStringInputBuffer> buf(&safe_string_input_buffer);
271       buf->Reset(source.location());
272       pre_data = PreParse(buf.value(), extension);
273     }
274
275     // Create a script object describing the script to be compiled.
276     Handle<Script> script = Factory::NewScript(source);
277     if (!script_name.is_null()) {
278       script->set_name(*script_name);
279       script->set_line_offset(Smi::FromInt(line_offset));
280       script->set_column_offset(Smi::FromInt(column_offset));
281     }
282
283     // Compile the function and add it to the cache.
284     result = MakeFunction(true,
285                           false,
286                           DONT_VALIDATE_JSON,
287                           script,
288                           Handle<Context>::null(),
289                           extension,
290                           pre_data);
291     if (extension == NULL && !result.is_null()) {
292       CompilationCache::PutScript(source, result);
293     }
294
295     // Get rid of the pre-parsing data (if necessary).
296     if (input_pre_data == NULL && pre_data != NULL) {
297       delete pre_data;
298     }
299   }
300
301   if (result.is_null()) Top::ReportPendingMessages();
302   return result;
303 }
304
305
306 Handle<JSFunction> Compiler::CompileEval(Handle<String> source,
307                                          Handle<Context> context,
308                                          bool is_global,
309                                          ValidationState validate) {
310   // Note that if validation is required then no path through this
311   // function is allowed to return a value without validating that
312   // the input is legal json.
313
314   int source_length = source->length();
315   Counters::total_eval_size.Increment(source_length);
316   Counters::total_compile_size.Increment(source_length);
317
318   // The VM is in the COMPILER state until exiting this function.
319   VMState state(COMPILER);
320
321   // Do a lookup in the compilation cache; if the entry is not there,
322   // invoke the compiler and add the result to the cache.  If we're
323   // evaluating json we bypass the cache since we can't be sure a
324   // potential value in the cache has been validated.
325   Handle<JSFunction> result;
326   if (validate == DONT_VALIDATE_JSON)
327     result = CompilationCache::LookupEval(source, context, is_global);
328
329   if (result.is_null()) {
330     // Create a script object describing the script to be compiled.
331     Handle<Script> script = Factory::NewScript(source);
332     result = MakeFunction(is_global,
333                           true,
334                           validate,
335                           script,
336                           context,
337                           NULL,
338                           NULL);
339     if (!result.is_null() && validate != VALIDATE_JSON) {
340       // For json it's unlikely that we'll ever see exactly the same
341       // string again so we don't use the compilation cache.
342       CompilationCache::PutEval(source, context, is_global, result);
343     }
344   }
345
346   return result;
347 }
348
349
350 bool Compiler::CompileLazy(Handle<SharedFunctionInfo> shared,
351                            int loop_nesting) {
352   CompilationZoneScope zone_scope(DELETE_ON_EXIT);
353
354   // The VM is in the COMPILER state until exiting this function.
355   VMState state(COMPILER);
356
357   // Make sure we have an initial stack limit.
358   StackGuard guard;
359   PostponeInterruptsScope postpone;
360
361   // Compute name, source code and script data.
362   Handle<String> name(String::cast(shared->name()));
363   Handle<Script> script(Script::cast(shared->script()));
364
365   int start_position = shared->start_position();
366   int end_position = shared->end_position();
367   bool is_expression = shared->is_expression();
368   Counters::total_compile_size.Increment(end_position - start_position);
369
370   // Generate the AST for the lazily compiled function. The AST may be
371   // NULL in case of parser stack overflow.
372   FunctionLiteral* lit = MakeLazyAST(script, name,
373                                      start_position,
374                                      end_position,
375                                      is_expression);
376
377   // Check for parse errors.
378   if (lit == NULL) {
379     ASSERT(Top::has_pending_exception());
380     return false;
381   }
382
383   // Update the loop nesting in the function literal.
384   lit->set_loop_nesting(loop_nesting);
385
386   // Measure how long it takes to do the lazy compilation; only take
387   // the rest of the function into account to avoid overlap with the
388   // lazy parsing statistics.
389   HistogramTimerScope timer(&Counters::compile_lazy);
390
391   // Compile the code.
392   Handle<Code> code = MakeCode(lit, script, Handle<Context>::null(), false);
393
394   // Check for stack-overflow exception.
395   if (code.is_null()) {
396     Top::StackOverflow();
397     return false;
398   }
399
400 #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT
401   // Log the code generation. If source information is available include script
402   // name and line number. Check explicit whether logging is enabled as finding
403   // the line number is not for free.
404   if (Logger::is_logging() || OProfileAgent::is_enabled()) {
405     Handle<String> func_name(name->length() > 0 ?
406                              *name : shared->inferred_name());
407     if (script->name()->IsString()) {
408       int line_num = GetScriptLineNumber(script, start_position) + 1;
409       LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name,
410                           String::cast(script->name()), line_num));
411       OProfileAgent::CreateNativeCodeRegion(*func_name,
412                                             String::cast(script->name()),
413                                             line_num,
414                                             code->instruction_start(),
415                                             code->instruction_size());
416     } else {
417       LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name));
418       OProfileAgent::CreateNativeCodeRegion(*func_name,
419                                             code->instruction_start(),
420                                             code->instruction_size());
421     }
422   }
423 #endif
424
425   // Update the shared function info with the compiled code.
426   shared->set_code(*code);
427
428   // Set the expected number of properties for instances.
429   SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count());
430
431   // Check the function has compiled code.
432   ASSERT(shared->is_compiled());
433   return true;
434 }
435
436
437 } }  // namespace v8::internal