• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
MakeCode(FunctionLiteral * literal,Handle<Script> script,Handle<Context> context,bool is_eval)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 
IsValidJSON(FunctionLiteral * lit)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 
MakeFunction(bool is_global,bool is_eval,Compiler::ValidationState validate,Handle<Script> script,Handle<Context> context,v8::Extension * extension,ScriptDataImpl * pre_data)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   ASSERT_EQ(RelocInfo::kNoPosition, lit->function_token_position());
223   CodeGenerator::SetFunctionInfo(fun, lit, true, script);
224 
225   // Hint to the runtime system used when allocating space for initial
226   // property space by setting the expected number of properties for
227   // the instances of the function.
228   SetExpectedNofPropertiesFromEstimate(fun, lit->expected_property_count());
229 
230 #ifdef ENABLE_DEBUGGER_SUPPORT
231   // Notify debugger
232   Debugger::OnAfterCompile(script, fun);
233 #endif
234 
235   return fun;
236 }
237 
238 
239 static StaticResource<SafeStringInputBuffer> safe_string_input_buffer;
240 
241 
Compile(Handle<String> source,Handle<Object> script_name,int line_offset,int column_offset,v8::Extension * extension,ScriptDataImpl * input_pre_data)242 Handle<JSFunction> Compiler::Compile(Handle<String> source,
243                                      Handle<Object> script_name,
244                                      int line_offset, int column_offset,
245                                      v8::Extension* extension,
246                                      ScriptDataImpl* input_pre_data) {
247   int source_length = source->length();
248   Counters::total_load_size.Increment(source_length);
249   Counters::total_compile_size.Increment(source_length);
250 
251   // The VM is in the COMPILER state until exiting this function.
252   VMState state(COMPILER);
253 
254   // Do a lookup in the compilation cache but not for extensions.
255   Handle<JSFunction> result;
256   if (extension == NULL) {
257     result = CompilationCache::LookupScript(source,
258                                             script_name,
259                                             line_offset,
260                                             column_offset);
261   }
262 
263   if (result.is_null()) {
264     // No cache entry found. Do pre-parsing and compile the script.
265     ScriptDataImpl* pre_data = input_pre_data;
266     if (pre_data == NULL && source_length >= FLAG_min_preparse_length) {
267       Access<SafeStringInputBuffer> buf(&safe_string_input_buffer);
268       buf->Reset(source.location());
269       pre_data = PreParse(source, buf.value(), extension);
270     }
271 
272     // Create a script object describing the script to be compiled.
273     Handle<Script> script = Factory::NewScript(source);
274     if (!script_name.is_null()) {
275       script->set_name(*script_name);
276       script->set_line_offset(Smi::FromInt(line_offset));
277       script->set_column_offset(Smi::FromInt(column_offset));
278     }
279 
280     // Compile the function and add it to the cache.
281     result = MakeFunction(true,
282                           false,
283                           DONT_VALIDATE_JSON,
284                           script,
285                           Handle<Context>::null(),
286                           extension,
287                           pre_data);
288     if (extension == NULL && !result.is_null()) {
289       CompilationCache::PutScript(source, result);
290     }
291 
292     // Get rid of the pre-parsing data (if necessary).
293     if (input_pre_data == NULL && pre_data != NULL) {
294       delete pre_data;
295     }
296   }
297 
298   if (result.is_null()) Top::ReportPendingMessages();
299   return result;
300 }
301 
302 
CompileEval(Handle<String> source,Handle<Context> context,bool is_global,ValidationState validate)303 Handle<JSFunction> Compiler::CompileEval(Handle<String> source,
304                                          Handle<Context> context,
305                                          bool is_global,
306                                          ValidationState validate) {
307   // Note that if validation is required then no path through this
308   // function is allowed to return a value without validating that
309   // the input is legal json.
310 
311   int source_length = source->length();
312   Counters::total_eval_size.Increment(source_length);
313   Counters::total_compile_size.Increment(source_length);
314 
315   // The VM is in the COMPILER state until exiting this function.
316   VMState state(COMPILER);
317 
318   // Do a lookup in the compilation cache; if the entry is not there,
319   // invoke the compiler and add the result to the cache.  If we're
320   // evaluating json we bypass the cache since we can't be sure a
321   // potential value in the cache has been validated.
322   Handle<JSFunction> result;
323   if (validate == DONT_VALIDATE_JSON)
324     result = CompilationCache::LookupEval(source, context, is_global);
325 
326   if (result.is_null()) {
327     // Create a script object describing the script to be compiled.
328     Handle<Script> script = Factory::NewScript(source);
329     result = MakeFunction(is_global,
330                           true,
331                           validate,
332                           script,
333                           context,
334                           NULL,
335                           NULL);
336     if (!result.is_null() && validate != VALIDATE_JSON) {
337       // For json it's unlikely that we'll ever see exactly the same
338       // string again so we don't use the compilation cache.
339       CompilationCache::PutEval(source, context, is_global, result);
340     }
341   }
342 
343   return result;
344 }
345 
346 
CompileLazy(Handle<SharedFunctionInfo> shared,int loop_nesting)347 bool Compiler::CompileLazy(Handle<SharedFunctionInfo> shared,
348                            int loop_nesting) {
349   CompilationZoneScope zone_scope(DELETE_ON_EXIT);
350 
351   // The VM is in the COMPILER state until exiting this function.
352   VMState state(COMPILER);
353 
354   // Make sure we have an initial stack limit.
355   StackGuard guard;
356   PostponeInterruptsScope postpone;
357 
358   // Compute name, source code and script data.
359   Handle<String> name(String::cast(shared->name()));
360   Handle<Script> script(Script::cast(shared->script()));
361 
362   int start_position = shared->start_position();
363   int end_position = shared->end_position();
364   bool is_expression = shared->is_expression();
365   Counters::total_compile_size.Increment(end_position - start_position);
366 
367   // Generate the AST for the lazily compiled function. The AST may be
368   // NULL in case of parser stack overflow.
369   FunctionLiteral* lit = MakeLazyAST(script, name,
370                                      start_position,
371                                      end_position,
372                                      is_expression);
373 
374   // Check for parse errors.
375   if (lit == NULL) {
376     ASSERT(Top::has_pending_exception());
377     return false;
378   }
379 
380   // Update the loop nesting in the function literal.
381   lit->set_loop_nesting(loop_nesting);
382 
383   // Measure how long it takes to do the lazy compilation; only take
384   // the rest of the function into account to avoid overlap with the
385   // lazy parsing statistics.
386   HistogramTimerScope timer(&Counters::compile_lazy);
387 
388   // Compile the code.
389   Handle<Code> code = MakeCode(lit, script, Handle<Context>::null(), false);
390 
391   // Check for stack-overflow exception.
392   if (code.is_null()) {
393     Top::StackOverflow();
394     return false;
395   }
396 
397 #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT
398   // Log the code generation. If source information is available include script
399   // name and line number. Check explicit whether logging is enabled as finding
400   // the line number is not for free.
401   if (Logger::is_logging() || OProfileAgent::is_enabled()) {
402     Handle<String> func_name(name->length() > 0 ?
403                              *name : shared->inferred_name());
404     if (script->name()->IsString()) {
405       int line_num = GetScriptLineNumber(script, start_position) + 1;
406       LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name,
407                           String::cast(script->name()), line_num));
408       OProfileAgent::CreateNativeCodeRegion(*func_name,
409                                             String::cast(script->name()),
410                                             line_num,
411                                             code->instruction_start(),
412                                             code->instruction_size());
413     } else {
414       LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name));
415       OProfileAgent::CreateNativeCodeRegion(*func_name,
416                                             code->instruction_start(),
417                                             code->instruction_size());
418     }
419   }
420 #endif
421 
422   // Update the shared function info with the compiled code.
423   shared->set_code(*code);
424 
425   // Set the expected number of properties for instances.
426   SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count());
427 
428   // Set the optimication hints after performing lazy compilation, as these are
429   // not set when the function is set up as a lazily compiled function.
430   shared->SetThisPropertyAssignmentsInfo(
431       lit->has_only_this_property_assignments(),
432       lit->has_only_simple_this_property_assignments(),
433       *lit->this_property_assignments());
434 
435   // Check the function has compiled code.
436   ASSERT(shared->is_compiled());
437   return true;
438 }
439 
440 
441 } }  // namespace v8::internal
442