v8  3.14.5(node0.10.28)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
rewriter.cc
Go to the documentation of this file.
1 // Copyright 2012 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 "rewriter.h"
31 
32 #include "ast.h"
33 #include "compiler.h"
34 #include "scopes.h"
35 
36 namespace v8 {
37 namespace internal {
38 
39 class Processor: public AstVisitor {
40  public:
41  Processor(Variable* result, Zone* zone)
42  : result_(result),
43  result_assigned_(false),
44  is_set_(false),
45  in_try_(false),
46  factory_(isolate(), zone) { }
47 
48  virtual ~Processor() { }
49 
50  void Process(ZoneList<Statement*>* statements);
51  bool result_assigned() const { return result_assigned_; }
52 
54  return &factory_;
55  }
56 
57  private:
58  Variable* result_;
59 
60  // We are not tracking result usage via the result_'s use
61  // counts (we leave the accurate computation to the
62  // usage analyzer). Instead we simple remember if
63  // there was ever an assignment to result_.
64  bool result_assigned_;
65 
66  // To avoid storing to .result all the time, we eliminate some of
67  // the stores by keeping track of whether or not we're sure .result
68  // will be overwritten anyway. This is a bit more tricky than what I
69  // was hoping for
70  bool is_set_;
71  bool in_try_;
72 
74 
75  Expression* SetResult(Expression* value) {
76  result_assigned_ = true;
77  VariableProxy* result_proxy = factory()->NewVariableProxy(result_);
78  return factory()->NewAssignment(
79  Token::ASSIGN, result_proxy, value, RelocInfo::kNoPosition);
80  }
81 
82  // Node visitors.
83 #define DEF_VISIT(type) \
84  virtual void Visit##type(type* node);
86 #undef DEF_VISIT
87 
88  void VisitIterationStatement(IterationStatement* stmt);
89 };
90 
91 
93  for (int i = statements->length() - 1; i >= 0; --i) {
94  Visit(statements->at(i));
95  }
96 }
97 
98 
99 void Processor::VisitBlock(Block* node) {
100  // An initializer block is the rewritten form of a variable declaration
101  // with initialization expressions. The initializer block contains the
102  // list of assignments corresponding to the initialization expressions.
103  // While unclear from the spec (ECMA-262, 3rd., 12.2), the value of
104  // a variable declaration with initialization expression is 'undefined'
105  // with some JS VMs: For instance, using smjs, print(eval('var x = 7'))
106  // returns 'undefined'. To obtain the same behavior with v8, we need
107  // to prevent rewriting in that case.
108  if (!node->is_initializer_block()) Process(node->statements());
109 }
110 
111 
112 void Processor::VisitExpressionStatement(ExpressionStatement* node) {
113  // Rewrite : <x>; -> .result = <x>;
114  if (!is_set_ && !node->expression()->IsThrow()) {
115  node->set_expression(SetResult(node->expression()));
116  if (!in_try_) is_set_ = true;
117  }
118 }
119 
120 
121 void Processor::VisitIfStatement(IfStatement* node) {
122  // Rewrite both then and else parts (reversed).
123  bool save = is_set_;
124  Visit(node->else_statement());
125  bool set_after_then = is_set_;
126  is_set_ = save;
127  Visit(node->then_statement());
128  is_set_ = is_set_ && set_after_then;
129 }
130 
131 
132 void Processor::VisitIterationStatement(IterationStatement* node) {
133  // Rewrite the body.
134  bool set_after_loop = is_set_;
135  Visit(node->body());
136  is_set_ = is_set_ && set_after_loop;
137 }
138 
139 
140 void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
141  VisitIterationStatement(node);
142 }
143 
144 
145 void Processor::VisitWhileStatement(WhileStatement* node) {
146  VisitIterationStatement(node);
147 }
148 
149 
150 void Processor::VisitForStatement(ForStatement* node) {
151  VisitIterationStatement(node);
152 }
153 
154 
155 void Processor::VisitForInStatement(ForInStatement* node) {
156  VisitIterationStatement(node);
157 }
158 
159 
160 void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
161  // Rewrite both try and catch blocks (reversed order).
162  bool set_after_catch = is_set_;
163  Visit(node->catch_block());
164  is_set_ = is_set_ && set_after_catch;
165  bool save = in_try_;
166  in_try_ = true;
167  Visit(node->try_block());
168  in_try_ = save;
169 }
170 
171 
172 void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
173  // Rewrite both try and finally block (reversed order).
174  Visit(node->finally_block());
175  bool save = in_try_;
176  in_try_ = true;
177  Visit(node->try_block());
178  in_try_ = save;
179 }
180 
181 
182 void Processor::VisitSwitchStatement(SwitchStatement* node) {
183  // Rewrite statements in all case clauses in reversed order.
184  ZoneList<CaseClause*>* clauses = node->cases();
185  bool set_after_switch = is_set_;
186  for (int i = clauses->length() - 1; i >= 0; --i) {
187  CaseClause* clause = clauses->at(i);
188  Process(clause->statements());
189  }
190  is_set_ = is_set_ && set_after_switch;
191 }
192 
193 
194 void Processor::VisitContinueStatement(ContinueStatement* node) {
195  is_set_ = false;
196 }
197 
198 
199 void Processor::VisitBreakStatement(BreakStatement* node) {
200  is_set_ = false;
201 }
202 
203 
204 void Processor::VisitWithStatement(WithStatement* node) {
205  bool set_after_body = is_set_;
206  Visit(node->statement());
207  is_set_ = is_set_ && set_after_body;
208 }
209 
210 
211 // Do nothing:
212 void Processor::VisitVariableDeclaration(VariableDeclaration* node) {}
213 void Processor::VisitFunctionDeclaration(FunctionDeclaration* node) {}
214 void Processor::VisitModuleDeclaration(ModuleDeclaration* node) {}
215 void Processor::VisitImportDeclaration(ImportDeclaration* node) {}
216 void Processor::VisitExportDeclaration(ExportDeclaration* node) {}
217 void Processor::VisitModuleLiteral(ModuleLiteral* node) {}
218 void Processor::VisitModuleVariable(ModuleVariable* node) {}
219 void Processor::VisitModulePath(ModulePath* node) {}
220 void Processor::VisitModuleUrl(ModuleUrl* node) {}
221 void Processor::VisitEmptyStatement(EmptyStatement* node) {}
222 void Processor::VisitReturnStatement(ReturnStatement* node) {}
223 void Processor::VisitDebuggerStatement(DebuggerStatement* node) {}
224 
225 
226 // Expressions are never visited yet.
227 #define DEF_VISIT(type) \
228  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
230 #undef DEF_VISIT
231 
232 
233 // Assumes code has been parsed. Mutates the AST, so the AST should not
234 // continue to be used in the case of failure.
236  FunctionLiteral* function = info->function();
237  ASSERT(function != NULL);
238  Scope* scope = function->scope();
239  ASSERT(scope != NULL);
240  if (!scope->is_global_scope() && !scope->is_eval_scope()) return true;
241 
242  ZoneList<Statement*>* body = function->body();
243  if (!body->is_empty()) {
244  Variable* result = scope->NewTemporary(
245  info->isolate()->factory()->result_symbol());
246  Processor processor(result, info->zone());
247  processor.Process(body);
248  if (processor.HasStackOverflow()) return false;
249 
250  if (processor.result_assigned()) {
251  ASSERT(function->end_position() != RelocInfo::kNoPosition);
252  // Set the position of the assignment statement one character past the
253  // source code, such that it definitely is not in the source code range
254  // of an immediate inner scope. For example in
255  // eval('with ({x:1}) x = 1');
256  // the end position of the function generated for executing the eval code
257  // coincides with the end of the with scope which is the position of '1'.
258  int position = function->end_position();
259  VariableProxy* result_proxy = processor.factory()->NewVariableProxy(
260  result->name(), false, Interface::NewValue(), position);
261  result_proxy->BindTo(result);
262  Statement* result_statement =
263  processor.factory()->NewReturnStatement(result_proxy);
264  result_statement->set_statement_pos(position);
265  body->Add(result_statement, info->zone());
266  }
267  }
268 
269  return true;
270 }
271 
272 
273 } } // namespace v8::internal
bool is_global_scope() const
Definition: scopes.h:278
#define DEF_VISIT(type)
Definition: rewriter.cc:227
AstNodeFactory< AstNullVisitor > * factory()
Definition: rewriter.cc:53
Processor(Variable *result, Zone *zone)
Definition: rewriter.cc:41
bool result_assigned() const
Definition: rewriter.cc:51
#define ASSERT(condition)
Definition: checks.h:270
Variable * NewTemporary(Handle< String > name)
Definition: scopes.cc:518
void Process(ZoneList< Statement * > *statements)
Definition: rewriter.cc:92
Factory * factory()
Definition: isolate.h:992
Handle< String > name() const
Definition: variables.h:96
static Interface * NewValue()
Definition: interface.h:66
bool is_eval_scope() const
Definition: scopes.h:275
FunctionLiteral * function() const
Definition: compiler.h:66
ZoneList< Statement * > * statements()
Definition: ast.h:416
activate correct semantics for inheriting readonliness false
Definition: flags.cc:141
#define AST_NODE_LIST(V)
Definition: ast.h:115
void set_statement_pos(int statement_pos)
Definition: ast.h:254
void BindTo(Variable *var)
Definition: ast.cc:103
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
Definition: flags.cc:301
bool is_initializer_block() const
Definition: ast.h:417
#define EXPRESSION_NODE_LIST(V)
Definition: ast.h:94
static bool Rewrite(CompilationInfo *info)
Definition: rewriter.cc:235