blob: 1eb0932eb6e1a5f9f3cb4cb8503fe16be8c9c68b [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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#ifndef V8_ARM_CODEGEN_ARM_H_
29#define V8_ARM_CODEGEN_ARM_H_
30
31namespace v8 {
32namespace internal {
33
34// Forward declarations
35class DeferredCode;
36class RegisterAllocator;
37class RegisterFile;
38
39enum InitState { CONST_INIT, NOT_CONST_INIT };
40enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
41
42
43// -------------------------------------------------------------------------
44// Reference support
45
46// A reference is a C++ stack-allocated object that keeps an ECMA
47// reference on the execution stack while in scope. For variables
48// the reference is empty, indicating that it isn't necessary to
49// store state on the stack for keeping track of references to those.
50// For properties, we keep either one (named) or two (indexed) values
51// on the execution stack to represent the reference.
52
53class Reference BASE_EMBEDDED {
54 public:
55 // The values of the types is important, see size().
56 enum Type { ILLEGAL = -1, SLOT = 0, NAMED = 1, KEYED = 2 };
57 Reference(CodeGenerator* cgen, Expression* expression);
58 ~Reference();
59
60 Expression* expression() const { return expression_; }
61 Type type() const { return type_; }
62 void set_type(Type value) {
63 ASSERT(type_ == ILLEGAL);
64 type_ = value;
65 }
66
67 // The size the reference takes up on the stack.
68 int size() const { return (type_ == ILLEGAL) ? 0 : type_; }
69
70 bool is_illegal() const { return type_ == ILLEGAL; }
71 bool is_slot() const { return type_ == SLOT; }
72 bool is_property() const { return type_ == NAMED || type_ == KEYED; }
73
74 // Return the name. Only valid for named property references.
75 Handle<String> GetName();
76
77 // Generate code to push the value of the reference on top of the
78 // expression stack. The reference is expected to be already on top of
79 // the expression stack, and it is left in place with its value above it.
80 void GetValue(TypeofState typeof_state);
81
82 // Generate code to push the value of a reference on top of the expression
83 // stack and then spill the stack frame. This function is used temporarily
84 // while the code generator is being transformed.
85 inline void GetValueAndSpill(TypeofState typeof_state);
86
87 // Generate code to store the value on top of the expression stack in the
88 // reference. The reference is expected to be immediately below the value
89 // on the expression stack. The stored value is left in place (with the
90 // reference intact below it) to support chained assignments.
91 void SetValue(InitState init_state);
92
93 private:
94 CodeGenerator* cgen_;
95 Expression* expression_;
96 Type type_;
97};
98
99
100// -------------------------------------------------------------------------
101// Code generation state
102
103// The state is passed down the AST by the code generator (and back up, in
104// the form of the state of the label pair). It is threaded through the
105// call stack. Constructing a state implicitly pushes it on the owning code
106// generator's stack of states, and destroying one implicitly pops it.
107
108class CodeGenState BASE_EMBEDDED {
109 public:
110 // Create an initial code generator state. Destroying the initial state
111 // leaves the code generator with a NULL state.
112 explicit CodeGenState(CodeGenerator* owner);
113
114 // Create a code generator state based on a code generator's current
115 // state. The new state has its own typeof state and pair of branch
116 // labels.
117 CodeGenState(CodeGenerator* owner,
118 TypeofState typeof_state,
119 JumpTarget* true_target,
120 JumpTarget* false_target);
121
122 // Destroy a code generator state and restore the owning code generator's
123 // previous state.
124 ~CodeGenState();
125
126 TypeofState typeof_state() const { return typeof_state_; }
127 JumpTarget* true_target() const { return true_target_; }
128 JumpTarget* false_target() const { return false_target_; }
129
130 private:
131 CodeGenerator* owner_;
132 TypeofState typeof_state_;
133 JumpTarget* true_target_;
134 JumpTarget* false_target_;
135 CodeGenState* previous_;
136};
137
138
139// -------------------------------------------------------------------------
140// CodeGenerator
141
142class CodeGenerator: public AstVisitor {
143 public:
144 // Takes a function literal, generates code for it. This function should only
145 // be called by compiler.cc.
146 static Handle<Code> MakeCode(FunctionLiteral* fun,
147 Handle<Script> script,
148 bool is_eval);
149
150#ifdef ENABLE_LOGGING_AND_PROFILING
151 static bool ShouldGenerateLog(Expression* type);
152#endif
153
154 static void SetFunctionInfo(Handle<JSFunction> fun,
155 FunctionLiteral* lit,
156 bool is_toplevel,
157 Handle<Script> script);
158
159 // Accessors
160 MacroAssembler* masm() { return masm_; }
161
162 VirtualFrame* frame() const { return frame_; }
163
164 bool has_valid_frame() const { return frame_ != NULL; }
165
166 // Set the virtual frame to be new_frame, with non-frame register
167 // reference counts given by non_frame_registers. The non-frame
168 // register reference counts of the old frame are returned in
169 // non_frame_registers.
170 void SetFrame(VirtualFrame* new_frame, RegisterFile* non_frame_registers);
171
172 void DeleteFrame();
173
174 RegisterAllocator* allocator() const { return allocator_; }
175
176 CodeGenState* state() { return state_; }
177 void set_state(CodeGenState* state) { state_ = state; }
178
179 void AddDeferred(DeferredCode* code) { deferred_.Add(code); }
180
181 static const int kUnknownIntValue = -1;
182
183 // Number of instructions used for the JS return sequence. The constant is
184 // used by the debugger to patch the JS return sequence.
185 static const int kJSReturnSequenceLength = 4;
186
187 private:
188 // Construction/Destruction
189 CodeGenerator(int buffer_size, Handle<Script> script, bool is_eval);
190 virtual ~CodeGenerator() { delete masm_; }
191
192 // Accessors
193 Scope* scope() const { return scope_; }
194
195 // Generating deferred code.
196 void ProcessDeferred();
197
198 bool is_eval() { return is_eval_; }
199
200 // State
201 bool has_cc() const { return cc_reg_ != al; }
202 TypeofState typeof_state() const { return state_->typeof_state(); }
203 JumpTarget* true_target() const { return state_->true_target(); }
204 JumpTarget* false_target() const { return state_->false_target(); }
205
206 // We don't track loop nesting level on ARM yet.
207 int loop_nesting() const { return 0; }
208
209 // Node visitors.
210 void VisitStatements(ZoneList<Statement*>* statements);
211
212#define DEF_VISIT(type) \
213 void Visit##type(type* node);
214 AST_NODE_LIST(DEF_VISIT)
215#undef DEF_VISIT
216
217 // Visit a statement and then spill the virtual frame if control flow can
218 // reach the end of the statement (ie, it does not exit via break,
219 // continue, return, or throw). This function is used temporarily while
220 // the code generator is being transformed.
221 inline void VisitAndSpill(Statement* statement);
222
223 // Visit a list of statements and then spill the virtual frame if control
224 // flow can reach the end of the list.
225 inline void VisitStatementsAndSpill(ZoneList<Statement*>* statements);
226
227 // Main code generation function
228 void GenCode(FunctionLiteral* fun);
229
230 // The following are used by class Reference.
231 void LoadReference(Reference* ref);
232 void UnloadReference(Reference* ref);
233
234 MemOperand ContextOperand(Register context, int index) const {
235 return MemOperand(context, Context::SlotOffset(index));
236 }
237
238 MemOperand SlotOperand(Slot* slot, Register tmp);
239
240 MemOperand ContextSlotOperandCheckExtensions(Slot* slot,
241 Register tmp,
242 Register tmp2,
243 JumpTarget* slow);
244
245 // Expressions
246 MemOperand GlobalObject() const {
247 return ContextOperand(cp, Context::GLOBAL_INDEX);
248 }
249
250 void LoadCondition(Expression* x,
251 TypeofState typeof_state,
252 JumpTarget* true_target,
253 JumpTarget* false_target,
254 bool force_cc);
255 void Load(Expression* x, TypeofState typeof_state = NOT_INSIDE_TYPEOF);
256 void LoadGlobal();
257 void LoadGlobalReceiver(Register scratch);
258
259 // Generate code to push the value of an expression on top of the frame
260 // and then spill the frame fully to memory. This function is used
261 // temporarily while the code generator is being transformed.
262 inline void LoadAndSpill(Expression* expression,
263 TypeofState typeof_state = NOT_INSIDE_TYPEOF);
264
265 // Call LoadCondition and then spill the virtual frame unless control flow
266 // cannot reach the end of the expression (ie, by emitting only
267 // unconditional jumps to the control targets).
268 inline void LoadConditionAndSpill(Expression* expression,
269 TypeofState typeof_state,
270 JumpTarget* true_target,
271 JumpTarget* false_target,
272 bool force_control);
273
274 // Read a value from a slot and leave it on top of the expression stack.
275 void LoadFromSlot(Slot* slot, TypeofState typeof_state);
276 void LoadFromGlobalSlotCheckExtensions(Slot* slot,
277 TypeofState typeof_state,
278 Register tmp,
279 Register tmp2,
280 JumpTarget* slow);
281
282 // Special code for typeof expressions: Unfortunately, we must
283 // be careful when loading the expression in 'typeof'
284 // expressions. We are not allowed to throw reference errors for
285 // non-existing properties of the global object, so we must make it
286 // look like an explicit property access, instead of an access
287 // through the context chain.
288 void LoadTypeofExpression(Expression* x);
289
290 void ToBoolean(JumpTarget* true_target, JumpTarget* false_target);
291
292 void GenericBinaryOperation(Token::Value op,
293 OverwriteMode overwrite_mode,
294 int known_rhs = kUnknownIntValue);
295 void Comparison(Condition cc,
296 Expression* left,
297 Expression* right,
298 bool strict = false);
299
300 void SmiOperation(Token::Value op,
301 Handle<Object> value,
302 bool reversed,
303 OverwriteMode mode);
304
305 void CallWithArguments(ZoneList<Expression*>* arguments, int position);
306
307 // Control flow
308 void Branch(bool if_true, JumpTarget* target);
309 void CheckStack();
310
311 struct InlineRuntimeLUT {
312 void (CodeGenerator::*method)(ZoneList<Expression*>*);
313 const char* name;
314 };
315
316 static InlineRuntimeLUT* FindInlineRuntimeLUT(Handle<String> name);
317 bool CheckForInlineRuntimeCall(CallRuntime* node);
318 static bool PatchInlineRuntimeEntry(Handle<String> name,
319 const InlineRuntimeLUT& new_entry,
320 InlineRuntimeLUT* old_entry);
321
322 Handle<JSFunction> BuildBoilerplate(FunctionLiteral* node);
323 void ProcessDeclarations(ZoneList<Declaration*>* declarations);
324
325 Handle<Code> ComputeCallInitialize(int argc, InLoopFlag in_loop);
326
327 // Declare global variables and functions in the given array of
328 // name/value pairs.
329 void DeclareGlobals(Handle<FixedArray> pairs);
330
331 // Instantiate the function boilerplate.
332 void InstantiateBoilerplate(Handle<JSFunction> boilerplate);
333
334 // Support for type checks.
335 void GenerateIsSmi(ZoneList<Expression*>* args);
336 void GenerateIsNonNegativeSmi(ZoneList<Expression*>* args);
337 void GenerateIsArray(ZoneList<Expression*>* args);
338
339 // Support for construct call checks.
340 void GenerateIsConstructCall(ZoneList<Expression*>* args);
341
342 // Support for arguments.length and arguments[?].
343 void GenerateArgumentsLength(ZoneList<Expression*>* args);
344 void GenerateArgumentsAccess(ZoneList<Expression*>* args);
345
346 // Support for accessing the class and value fields of an object.
347 void GenerateClassOf(ZoneList<Expression*>* args);
348 void GenerateValueOf(ZoneList<Expression*>* args);
349 void GenerateSetValueOf(ZoneList<Expression*>* args);
350
351 // Fast support for charCodeAt(n).
352 void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
353
354 // Fast support for object equality testing.
355 void GenerateObjectEquals(ZoneList<Expression*>* args);
356
357 void GenerateLog(ZoneList<Expression*>* args);
358
359 // Fast support for Math.random().
360 void GenerateRandomPositiveSmi(ZoneList<Expression*>* args);
361
362 // Fast support for Math.sin and Math.cos.
363 enum MathOp { SIN, COS };
364 void GenerateFastMathOp(MathOp op, ZoneList<Expression*>* args);
365 inline void GenerateMathSin(ZoneList<Expression*>* args);
366 inline void GenerateMathCos(ZoneList<Expression*>* args);
367
368 // Methods used to indicate which source code is generated for. Source
369 // positions are collected by the assembler and emitted with the relocation
370 // information.
371 void CodeForFunctionPosition(FunctionLiteral* fun);
372 void CodeForReturnPosition(FunctionLiteral* fun);
373 void CodeForStatementPosition(Statement* node);
374 void CodeForSourcePosition(int pos);
375
376#ifdef DEBUG
377 // True if the registers are valid for entry to a block.
378 bool HasValidEntryRegisters();
379#endif
380
381 bool is_eval_; // Tells whether code is generated for eval.
382
383 Handle<Script> script_;
384 List<DeferredCode*> deferred_;
385
386 // Assembler
387 MacroAssembler* masm_; // to generate code
388
389 // Code generation state
390 Scope* scope_;
391 VirtualFrame* frame_;
392 RegisterAllocator* allocator_;
393 Condition cc_reg_;
394 CodeGenState* state_;
395
396 // Jump targets
397 BreakTarget function_return_;
398
399 // True if the function return is shadowed (ie, jumping to the target
400 // function_return_ does not jump to the true function return, but rather
401 // to some unlinking code).
402 bool function_return_is_shadowed_;
403
404 static InlineRuntimeLUT kInlineRuntimeLUT[];
405
406 friend class VirtualFrame;
407 friend class JumpTarget;
408 friend class Reference;
409
410 DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
411};
412
413
414class GenericBinaryOpStub : public CodeStub {
415 public:
416 GenericBinaryOpStub(Token::Value op,
417 OverwriteMode mode,
418 int constant_rhs = CodeGenerator::kUnknownIntValue)
419 : op_(op),
420 mode_(mode),
421 constant_rhs_(constant_rhs),
422 specialized_on_rhs_(RhsIsOneWeWantToOptimizeFor(op, constant_rhs)) { }
423
424 private:
425 Token::Value op_;
426 OverwriteMode mode_;
427 int constant_rhs_;
428 bool specialized_on_rhs_;
429
430 static const int kMaxKnownRhs = 0x40000000;
431
432 // Minor key encoding in 16 bits.
433 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
434 class OpBits: public BitField<Token::Value, 2, 6> {};
435 class KnownIntBits: public BitField<int, 8, 8> {};
436
437 Major MajorKey() { return GenericBinaryOp; }
438 int MinorKey() {
439 // Encode the parameters in a unique 16 bit value.
440 return OpBits::encode(op_)
441 | ModeBits::encode(mode_)
442 | KnownIntBits::encode(MinorKeyForKnownInt());
443 }
444
445 void Generate(MacroAssembler* masm);
446 void HandleNonSmiBitwiseOp(MacroAssembler* masm);
447
448 static bool RhsIsOneWeWantToOptimizeFor(Token::Value op, int constant_rhs) {
449 if (constant_rhs == CodeGenerator::kUnknownIntValue) return false;
450 if (op == Token::DIV) return constant_rhs >= 2 && constant_rhs <= 3;
451 if (op == Token::MOD) {
452 if (constant_rhs <= 1) return false;
453 if (constant_rhs <= 10) return true;
454 if (constant_rhs <= kMaxKnownRhs && IsPowerOf2(constant_rhs)) return true;
455 return false;
456 }
457 return false;
458 }
459
460 int MinorKeyForKnownInt() {
461 if (!specialized_on_rhs_) return 0;
462 if (constant_rhs_ <= 10) return constant_rhs_ + 1;
463 ASSERT(IsPowerOf2(constant_rhs_));
464 int key = 12;
465 int d = constant_rhs_;
466 while ((d & 1) == 0) {
467 key++;
468 d >>= 1;
469 }
470 return key;
471 }
472
473 const char* GetName() {
474 switch (op_) {
475 case Token::ADD: return "GenericBinaryOpStub_ADD";
476 case Token::SUB: return "GenericBinaryOpStub_SUB";
477 case Token::MUL: return "GenericBinaryOpStub_MUL";
478 case Token::DIV: return "GenericBinaryOpStub_DIV";
479 case Token::MOD: return "GenericBinaryOpStub_MOD";
480 case Token::BIT_OR: return "GenericBinaryOpStub_BIT_OR";
481 case Token::BIT_AND: return "GenericBinaryOpStub_BIT_AND";
482 case Token::BIT_XOR: return "GenericBinaryOpStub_BIT_XOR";
483 case Token::SAR: return "GenericBinaryOpStub_SAR";
484 case Token::SHL: return "GenericBinaryOpStub_SHL";
485 case Token::SHR: return "GenericBinaryOpStub_SHR";
486 default: return "GenericBinaryOpStub";
487 }
488 }
489
490#ifdef DEBUG
491 void Print() {
492 if (!specialized_on_rhs_) {
493 PrintF("GenericBinaryOpStub (%s)\n", Token::String(op_));
494 } else {
495 PrintF("GenericBinaryOpStub (%s by %d)\n",
496 Token::String(op_),
497 constant_rhs_);
498 }
499 }
500#endif
501};
502
503
504} } // namespace v8::internal
505
506#endif // V8_ARM_CODEGEN_ARM_H_