• 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 "codegen-inl.h"
32 #include "debug.h"
33 #include "oprofile-agent.h"
34 #include "prettyprinter.h"
35 #include "register-allocator-inl.h"
36 #include "rewriter.h"
37 #include "runtime.h"
38 #include "scopeinfo.h"
39 #include "stub-cache.h"
40 
41 namespace v8 {
42 namespace internal {
43 
44 
45 CodeGenerator* CodeGeneratorScope::top_ = NULL;
46 
47 
DeferredCode()48 DeferredCode::DeferredCode()
49     : masm_(CodeGeneratorScope::Current()->masm()),
50       statement_position_(masm_->current_statement_position()),
51       position_(masm_->current_position()) {
52   ASSERT(statement_position_ != RelocInfo::kNoPosition);
53   ASSERT(position_ != RelocInfo::kNoPosition);
54 
55   CodeGeneratorScope::Current()->AddDeferred(this);
56 #ifdef DEBUG
57   comment_ = "";
58 #endif
59 
60   // Copy the register locations from the code generator's frame.
61   // These are the registers that will be spilled on entry to the
62   // deferred code and restored on exit.
63   VirtualFrame* frame = CodeGeneratorScope::Current()->frame();
64   int sp_offset = frame->fp_relative(frame->stack_pointer_);
65   for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
66     int loc = frame->register_location(i);
67     if (loc == VirtualFrame::kIllegalIndex) {
68       registers_[i] = kIgnore;
69     } else if (frame->elements_[loc].is_synced()) {
70       // Needs to be restored on exit but not saved on entry.
71       registers_[i] = frame->fp_relative(loc) | kSyncedFlag;
72     } else {
73       int offset = frame->fp_relative(loc);
74       registers_[i] = (offset < sp_offset) ? kPush : offset;
75     }
76   }
77 }
78 
79 
ProcessDeferred()80 void CodeGenerator::ProcessDeferred() {
81   while (!deferred_.is_empty()) {
82     DeferredCode* code = deferred_.RemoveLast();
83     ASSERT(masm_ == code->masm());
84     // Record position of deferred code stub.
85     masm_->RecordStatementPosition(code->statement_position());
86     if (code->position() != RelocInfo::kNoPosition) {
87       masm_->RecordPosition(code->position());
88     }
89     // Generate the code.
90     Comment cmnt(masm_, code->comment());
91     masm_->bind(code->entry_label());
92     code->SaveRegisters();
93     code->Generate();
94     code->RestoreRegisters();
95     masm_->jmp(code->exit_label());
96   }
97 }
98 
99 
SetFrame(VirtualFrame * new_frame,RegisterFile * non_frame_registers)100 void CodeGenerator::SetFrame(VirtualFrame* new_frame,
101                              RegisterFile* non_frame_registers) {
102   RegisterFile saved_counts;
103   if (has_valid_frame()) {
104     frame_->DetachFromCodeGenerator();
105     // The remaining register reference counts are the non-frame ones.
106     allocator_->SaveTo(&saved_counts);
107   }
108 
109   if (new_frame != NULL) {
110     // Restore the non-frame register references that go with the new frame.
111     allocator_->RestoreFrom(non_frame_registers);
112     new_frame->AttachToCodeGenerator();
113   }
114 
115   frame_ = new_frame;
116   saved_counts.CopyTo(non_frame_registers);
117 }
118 
119 
DeleteFrame()120 void CodeGenerator::DeleteFrame() {
121   if (has_valid_frame()) {
122     frame_->DetachFromCodeGenerator();
123     frame_ = NULL;
124   }
125 }
126 
127 
128 // Generate the code. Takes a function literal, generates code for it, assemble
129 // all the pieces into a Code object. This function is only to be called by
130 // the compiler.cc code.
MakeCode(FunctionLiteral * flit,Handle<Script> script,bool is_eval)131 Handle<Code> CodeGenerator::MakeCode(FunctionLiteral* flit,
132                                      Handle<Script> script,
133                                      bool is_eval) {
134 #ifdef ENABLE_DISASSEMBLER
135   bool print_code = Bootstrapper::IsActive()
136       ? FLAG_print_builtin_code
137       : FLAG_print_code;
138 #endif
139 
140 #ifdef DEBUG
141   bool print_source = false;
142   bool print_ast = false;
143   const char* ftype;
144 
145   if (Bootstrapper::IsActive()) {
146     print_source = FLAG_print_builtin_source;
147     print_ast = FLAG_print_builtin_ast;
148     ftype = "builtin";
149   } else {
150     print_source = FLAG_print_source;
151     print_ast = FLAG_print_ast;
152     ftype = "user-defined";
153   }
154 
155   if (FLAG_trace_codegen || print_source || print_ast) {
156     PrintF("*** Generate code for %s function: ", ftype);
157     flit->name()->ShortPrint();
158     PrintF(" ***\n");
159   }
160 
161   if (print_source) {
162     PrintF("--- Source from AST ---\n%s\n", PrettyPrinter().PrintProgram(flit));
163   }
164 
165   if (print_ast) {
166     PrintF("--- AST ---\n%s\n", AstPrinter().PrintProgram(flit));
167   }
168 #endif  // DEBUG
169 
170   // Generate code.
171   const int initial_buffer_size = 4 * KB;
172   CodeGenerator cgen(initial_buffer_size, script, is_eval);
173   CodeGeneratorScope scope(&cgen);
174   cgen.GenCode(flit);
175   if (cgen.HasStackOverflow()) {
176     ASSERT(!Top::has_pending_exception());
177     return Handle<Code>::null();
178   }
179 
180   // Allocate and install the code.  Time the rest of this function as
181   // code creation.
182   HistogramTimerScope timer(&Counters::code_creation);
183   CodeDesc desc;
184   cgen.masm()->GetCode(&desc);
185   ZoneScopeInfo sinfo(flit->scope());
186   InLoopFlag in_loop = (cgen.loop_nesting() != 0) ? IN_LOOP : NOT_IN_LOOP;
187   Code::Flags flags = Code::ComputeFlags(Code::FUNCTION, in_loop);
188   Handle<Code> code = Factory::NewCode(desc,
189                                        &sinfo,
190                                        flags,
191                                        cgen.masm()->CodeObject());
192 
193   // Add unresolved entries in the code to the fixup list.
194   Bootstrapper::AddFixup(*code, cgen.masm());
195 
196 #ifdef ENABLE_DISASSEMBLER
197   if (print_code) {
198     // Print the source code if available.
199     if (!script->IsUndefined() && !script->source()->IsUndefined()) {
200       PrintF("--- Raw source ---\n");
201       StringInputBuffer stream(String::cast(script->source()));
202       stream.Seek(flit->start_position());
203       // flit->end_position() points to the last character in the stream. We
204       // need to compensate by adding one to calculate the length.
205       int source_len = flit->end_position() - flit->start_position() + 1;
206       for (int i = 0; i < source_len; i++) {
207         if (stream.has_more()) PrintF("%c", stream.GetNext());
208       }
209       PrintF("\n\n");
210     }
211     PrintF("--- Code ---\n");
212     code->Disassemble(*flit->name()->ToCString());
213   }
214 #endif  // ENABLE_DISASSEMBLER
215 
216   if (!code.is_null()) {
217     Counters::total_compiled_code_size.Increment(code->instruction_size());
218   }
219 
220   return code;
221 }
222 
223 
224 #ifdef ENABLE_LOGGING_AND_PROFILING
225 
ShouldGenerateLog(Expression * type)226 bool CodeGenerator::ShouldGenerateLog(Expression* type) {
227   ASSERT(type != NULL);
228   if (!Logger::is_logging()) return false;
229   Handle<String> name = Handle<String>::cast(type->AsLiteral()->handle());
230   if (FLAG_log_regexp) {
231     static Vector<const char> kRegexp = CStrVector("regexp");
232     if (name->IsEqualTo(kRegexp))
233       return true;
234   }
235   return false;
236 }
237 
238 #endif
239 
240 
241 // Sets the function info on a function.
242 // The start_position points to the first '(' character after the function name
243 // in the full script source. When counting characters in the script source the
244 // the first character is number 0 (not 1).
SetFunctionInfo(Handle<JSFunction> fun,FunctionLiteral * lit,bool is_toplevel,Handle<Script> script)245 void CodeGenerator::SetFunctionInfo(Handle<JSFunction> fun,
246                                     FunctionLiteral* lit,
247                                     bool is_toplevel,
248                                     Handle<Script> script) {
249   fun->shared()->set_length(lit->num_parameters());
250   fun->shared()->set_formal_parameter_count(lit->num_parameters());
251   fun->shared()->set_script(*script);
252   fun->shared()->set_function_token_position(lit->function_token_position());
253   fun->shared()->set_start_position(lit->start_position());
254   fun->shared()->set_end_position(lit->end_position());
255   fun->shared()->set_is_expression(lit->is_expression());
256   fun->shared()->set_is_toplevel(is_toplevel);
257   fun->shared()->set_inferred_name(*lit->inferred_name());
258   fun->shared()->SetThisPropertyAssignmentsInfo(
259       lit->has_only_this_property_assignments(),
260       lit->has_only_simple_this_property_assignments(),
261       *lit->this_property_assignments());
262 }
263 
264 
ComputeLazyCompile(int argc)265 static Handle<Code> ComputeLazyCompile(int argc) {
266   CALL_HEAP_FUNCTION(StubCache::ComputeLazyCompile(argc), Code);
267 }
268 
269 
BuildBoilerplate(FunctionLiteral * node)270 Handle<JSFunction> CodeGenerator::BuildBoilerplate(FunctionLiteral* node) {
271 #ifdef DEBUG
272   // We should not try to compile the same function literal more than
273   // once.
274   node->mark_as_compiled();
275 #endif
276 
277   // Determine if the function can be lazily compiled. This is
278   // necessary to allow some of our builtin JS files to be lazily
279   // compiled. These builtins cannot be handled lazily by the parser,
280   // since we have to know if a function uses the special natives
281   // syntax, which is something the parser records.
282   bool allow_lazy = node->AllowsLazyCompilation();
283 
284   // Generate code
285   Handle<Code> code;
286   if (FLAG_lazy && allow_lazy) {
287     code = ComputeLazyCompile(node->num_parameters());
288   } else {
289     // The bodies of function literals have not yet been visited by
290     // the AST optimizer/analyzer.
291     if (!Rewriter::Optimize(node)) {
292       return Handle<JSFunction>::null();
293     }
294 
295     code = MakeCode(node, script_, false);
296 
297     // Check for stack-overflow exception.
298     if (code.is_null()) {
299       SetStackOverflow();
300       return Handle<JSFunction>::null();
301     }
302 
303     // Function compilation complete.
304     LOG(CodeCreateEvent(Logger::FUNCTION_TAG, *code, *node->name()));
305 
306 #ifdef ENABLE_OPROFILE_AGENT
307     OProfileAgent::CreateNativeCodeRegion(*node->name(),
308                                           code->instruction_start(),
309                                           code->instruction_size());
310 #endif
311   }
312 
313   // Create a boilerplate function.
314   Handle<JSFunction> function =
315       Factory::NewFunctionBoilerplate(node->name(),
316                                       node->materialized_literal_count(),
317                                       node->contains_array_literal(),
318                                       code);
319   CodeGenerator::SetFunctionInfo(function, node, false, script_);
320 
321 #ifdef ENABLE_DEBUGGER_SUPPORT
322   // Notify debugger that a new function has been added.
323   Debugger::OnNewFunction(function);
324 #endif
325 
326   // Set the expected number of properties for instances and return
327   // the resulting function.
328   SetExpectedNofPropertiesFromEstimate(function,
329                                        node->expected_property_count());
330   return function;
331 }
332 
333 
ComputeCallInitialize(int argc,InLoopFlag in_loop)334 Handle<Code> CodeGenerator::ComputeCallInitialize(
335     int argc,
336     InLoopFlag in_loop) {
337   if (in_loop == IN_LOOP) {
338     // Force the creation of the corresponding stub outside loops,
339     // because it may be used when clearing the ICs later - it is
340     // possible for a series of IC transitions to lose the in-loop
341     // information, and the IC clearing code can't generate a stub
342     // that it needs so we need to ensure it is generated already.
343     ComputeCallInitialize(argc, NOT_IN_LOOP);
344   }
345   CALL_HEAP_FUNCTION(StubCache::ComputeCallInitialize(argc, in_loop), Code);
346 }
347 
348 
ProcessDeclarations(ZoneList<Declaration * > * declarations)349 void CodeGenerator::ProcessDeclarations(ZoneList<Declaration*>* declarations) {
350   int length = declarations->length();
351   int globals = 0;
352   for (int i = 0; i < length; i++) {
353     Declaration* node = declarations->at(i);
354     Variable* var = node->proxy()->var();
355     Slot* slot = var->slot();
356 
357     // If it was not possible to allocate the variable at compile
358     // time, we need to "declare" it at runtime to make sure it
359     // actually exists in the local context.
360     if ((slot != NULL && slot->type() == Slot::LOOKUP) || !var->is_global()) {
361       VisitDeclaration(node);
362     } else {
363       // Count global variables and functions for later processing
364       globals++;
365     }
366   }
367 
368   // Return in case of no declared global functions or variables.
369   if (globals == 0) return;
370 
371   // Compute array of global variable and function declarations.
372   Handle<FixedArray> array = Factory::NewFixedArray(2 * globals, TENURED);
373   for (int j = 0, i = 0; i < length; i++) {
374     Declaration* node = declarations->at(i);
375     Variable* var = node->proxy()->var();
376     Slot* slot = var->slot();
377 
378     if ((slot != NULL && slot->type() == Slot::LOOKUP) || !var->is_global()) {
379       // Skip - already processed.
380     } else {
381       array->set(j++, *(var->name()));
382       if (node->fun() == NULL) {
383         if (var->mode() == Variable::CONST) {
384           // In case this is const property use the hole.
385           array->set_the_hole(j++);
386         } else {
387           array->set_undefined(j++);
388         }
389       } else {
390         Handle<JSFunction> function = BuildBoilerplate(node->fun());
391         // Check for stack-overflow exception.
392         if (HasStackOverflow()) return;
393         array->set(j++, *function);
394       }
395     }
396   }
397 
398   // Invoke the platform-dependent code generator to do the actual
399   // declaration the global variables and functions.
400   DeclareGlobals(array);
401 }
402 
403 
404 
405 // Special cases: These 'runtime calls' manipulate the current
406 // frame and are only used 1 or two places, so we generate them
407 // inline instead of generating calls to them.  They are used
408 // for implementing Function.prototype.call() and
409 // Function.prototype.apply().
410 CodeGenerator::InlineRuntimeLUT CodeGenerator::kInlineRuntimeLUT[] = {
411   {&CodeGenerator::GenerateIsSmi, "_IsSmi"},
412   {&CodeGenerator::GenerateIsNonNegativeSmi, "_IsNonNegativeSmi"},
413   {&CodeGenerator::GenerateIsArray, "_IsArray"},
414   {&CodeGenerator::GenerateIsConstructCall, "_IsConstructCall"},
415   {&CodeGenerator::GenerateArgumentsLength, "_ArgumentsLength"},
416   {&CodeGenerator::GenerateArgumentsAccess, "_Arguments"},
417   {&CodeGenerator::GenerateClassOf, "_ClassOf"},
418   {&CodeGenerator::GenerateValueOf, "_ValueOf"},
419   {&CodeGenerator::GenerateSetValueOf, "_SetValueOf"},
420   {&CodeGenerator::GenerateFastCharCodeAt, "_FastCharCodeAt"},
421   {&CodeGenerator::GenerateObjectEquals, "_ObjectEquals"},
422   {&CodeGenerator::GenerateLog, "_Log"},
423   {&CodeGenerator::GenerateRandomPositiveSmi, "_RandomPositiveSmi"},
424   {&CodeGenerator::GenerateMathSin, "_Math_sin"},
425   {&CodeGenerator::GenerateMathCos, "_Math_cos"}
426 };
427 
428 
FindInlineRuntimeLUT(Handle<String> name)429 CodeGenerator::InlineRuntimeLUT* CodeGenerator::FindInlineRuntimeLUT(
430     Handle<String> name) {
431   const int entries_count =
432       sizeof(kInlineRuntimeLUT) / sizeof(InlineRuntimeLUT);
433   for (int i = 0; i < entries_count; i++) {
434     InlineRuntimeLUT* entry = &kInlineRuntimeLUT[i];
435     if (name->IsEqualTo(CStrVector(entry->name))) {
436       return entry;
437     }
438   }
439   return NULL;
440 }
441 
442 
CheckForInlineRuntimeCall(CallRuntime * node)443 bool CodeGenerator::CheckForInlineRuntimeCall(CallRuntime* node) {
444   ZoneList<Expression*>* args = node->arguments();
445   Handle<String> name = node->name();
446   if (name->length() > 0 && name->Get(0) == '_') {
447     InlineRuntimeLUT* entry = FindInlineRuntimeLUT(name);
448     if (entry != NULL) {
449       ((*this).*(entry->method))(args);
450       return true;
451     }
452   }
453   return false;
454 }
455 
456 
PatchInlineRuntimeEntry(Handle<String> name,const CodeGenerator::InlineRuntimeLUT & new_entry,CodeGenerator::InlineRuntimeLUT * old_entry)457 bool CodeGenerator::PatchInlineRuntimeEntry(Handle<String> name,
458     const CodeGenerator::InlineRuntimeLUT& new_entry,
459     CodeGenerator::InlineRuntimeLUT* old_entry) {
460   InlineRuntimeLUT* entry = FindInlineRuntimeLUT(name);
461   if (entry == NULL) return false;
462   if (old_entry != NULL) {
463     old_entry->name = entry->name;
464     old_entry->method = entry->method;
465   }
466   entry->name = new_entry.name;
467   entry->method = new_entry.method;
468   return true;
469 }
470 
471 
CodeForFunctionPosition(FunctionLiteral * fun)472 void CodeGenerator::CodeForFunctionPosition(FunctionLiteral* fun) {
473   if (FLAG_debug_info) {
474     int pos = fun->start_position();
475     if (pos != RelocInfo::kNoPosition) {
476       masm()->RecordStatementPosition(pos);
477       masm()->RecordPosition(pos);
478     }
479   }
480 }
481 
482 
CodeForReturnPosition(FunctionLiteral * fun)483 void CodeGenerator::CodeForReturnPosition(FunctionLiteral* fun) {
484   if (FLAG_debug_info) {
485     int pos = fun->end_position();
486     if (pos != RelocInfo::kNoPosition) {
487       masm()->RecordStatementPosition(pos);
488       masm()->RecordPosition(pos);
489     }
490   }
491 }
492 
493 
CodeForStatementPosition(AstNode * node)494 void CodeGenerator::CodeForStatementPosition(AstNode* node) {
495   if (FLAG_debug_info) {
496     int pos = node->statement_pos();
497     if (pos != RelocInfo::kNoPosition) {
498       masm()->RecordStatementPosition(pos);
499       masm()->RecordPosition(pos);
500     }
501   }
502 }
503 
504 
CodeForSourcePosition(int pos)505 void CodeGenerator::CodeForSourcePosition(int pos) {
506   if (FLAG_debug_info) {
507     if (pos != RelocInfo::kNoPosition) {
508       masm()->RecordPosition(pos);
509     }
510   }
511 }
512 
513 
GetName()514 const char* RuntimeStub::GetName() {
515   return Runtime::FunctionForId(id_)->stub_name;
516 }
517 
518 
Generate(MacroAssembler * masm)519 void RuntimeStub::Generate(MacroAssembler* masm) {
520   masm->TailCallRuntime(ExternalReference(id_), num_arguments_);
521 }
522 
523 
Generate(MacroAssembler * masm)524 void ArgumentsAccessStub::Generate(MacroAssembler* masm) {
525   switch (type_) {
526     case READ_LENGTH: GenerateReadLength(masm); break;
527     case READ_ELEMENT: GenerateReadElement(masm); break;
528     case NEW_OBJECT: GenerateNewObject(masm); break;
529   }
530 }
531 
532 
533 } }  // namespace v8::internal
534