blob: ac870fb13848d61c70b61c0694d6c407b7a64464 [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. 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 "prettyprinter.h"
34#include "scopeinfo.h"
35#include "scopes.h"
36#include "runtime.h"
37
38namespace v8 { namespace internal {
39
40DEFINE_bool(optimize_locals, true,
41 "optimize locals by allocating them in registers");
42DEFINE_bool(trace, false, "trace function calls");
43DECLARE_bool(debug_info);
44DECLARE_bool(debug_code);
45DECLARE_bool(optimize_locals);
46
47#ifdef DEBUG
48DECLARE_bool(gc_greedy);
49DEFINE_bool(trace_codegen, false,
50 "print name of functions for which code is generated");
51DEFINE_bool(print_code, false, "print generated code");
52DEFINE_bool(print_builtin_code, false, "print generated code for builtins");
53DEFINE_bool(print_source, false, "pretty print source code");
54DEFINE_bool(print_builtin_source, false,
55 "pretty print source code for builtins");
56DEFINE_bool(print_ast, false, "print source AST");
57DEFINE_bool(print_builtin_ast, false, "print source AST for builtins");
58DEFINE_bool(trace_calls, false, "trace calls");
59DEFINE_bool(trace_builtin_calls, false, "trace builtins calls");
60DEFINE_string(stop_at, "", "function name where to insert a breakpoint");
61#endif // DEBUG
62
63
64DEFINE_bool(check_stack, true,
65 "check stack for overflow, interrupt, breakpoint");
66
67
68class ArmCodeGenerator;
69
70
71// -----------------------------------------------------------------------------
72// Reference support
73
74// A reference is a C++ stack-allocated object that keeps an ECMA
75// reference on the execution stack while in scope. For variables
76// the reference is empty, indicating that it isn't necessary to
77// store state on the stack for keeping track of references to those.
78// For properties, we keep either one (named) or two (indexed) values
79// on the execution stack to represent the reference.
80
81class Reference BASE_EMBEDDED {
82 public:
83 enum Type { ILLEGAL = -1, EMPTY = 0, NAMED = 1, KEYED = 2 };
84 Reference(ArmCodeGenerator* cgen, Expression* expression);
85 ~Reference();
86
87 Expression* expression() const { return expression_; }
88 Type type() const { return type_; }
89 void set_type(Type value) {
90 ASSERT(type_ == ILLEGAL);
91 type_ = value;
92 }
93 int size() const { return type_; }
94
95 bool is_illegal() const { return type_ == ILLEGAL; }
96
97 private:
98 ArmCodeGenerator* cgen_;
99 Expression* expression_;
100 Type type_;
101};
102
103
104// -----------------------------------------------------------------------------
105// Code generation state
106
107class CodeGenState BASE_EMBEDDED {
108 public:
109 enum AccessType {
110 UNDEFINED,
111 LOAD,
112 LOAD_TYPEOF_EXPR,
113 STORE,
114 INIT_CONST
115 };
116
117 CodeGenState()
118 : access_(UNDEFINED),
119 ref_(NULL),
120 true_target_(NULL),
121 false_target_(NULL) {
122 }
123
124 CodeGenState(AccessType access,
125 Reference* ref,
126 Label* true_target,
127 Label* false_target)
128 : access_(access),
129 ref_(ref),
130 true_target_(true_target),
131 false_target_(false_target) {
132 }
133
134 AccessType access() const { return access_; }
135 Reference* ref() const { return ref_; }
136 Label* true_target() const { return true_target_; }
137 Label* false_target() const { return false_target_; }
138
139 private:
140 AccessType access_;
141 Reference* ref_;
142 Label* true_target_;
143 Label* false_target_;
144};
145
146
147// -----------------------------------------------------------------------------
148// ArmCodeGenerator
149
150class ArmCodeGenerator: public CodeGenerator {
151 public:
152 static Handle<Code> MakeCode(FunctionLiteral* fun,
153 Handle<Script> script,
154 bool is_eval);
155
156 MacroAssembler* masm() { return masm_; }
157
158 private:
159 // Assembler
160 MacroAssembler* masm_; // to generate code
161
162 // Code generation state
163 Scope* scope_;
164 Condition cc_reg_;
165 CodeGenState* state_;
166 RegList reg_locals_; // the list of registers used to hold locals
167 int num_reg_locals_; // the number of registers holding locals
168 int break_stack_height_;
169
170 // Labels
171 Label function_return_;
172
173 // Construction/destruction
174 ArmCodeGenerator(int buffer_size,
175 Handle<Script> script,
176 bool is_eval);
177
178 virtual ~ArmCodeGenerator() { delete masm_; }
179
180 // Main code generation function
181 void GenCode(FunctionLiteral* fun);
182
183 // The following are used by class Reference.
184 void LoadReference(Reference* ref);
185 void UnloadReference(Reference* ref);
186 friend class Reference;
187
188 // State
189 bool has_cc() const { return cc_reg_ != al; }
190 CodeGenState::AccessType access() const { return state_->access(); }
191 Reference* ref() const { return state_->ref(); }
192 bool is_referenced() const { return state_->ref() != NULL; }
193 Label* true_target() const { return state_->true_target(); }
194 Label* false_target() const { return state_->false_target(); }
195
196
197 // Expressions
198 MemOperand GlobalObject() const {
199 return ContextOperand(cp, Context::GLOBAL_INDEX);
200 }
201
202 MemOperand ContextOperand(Register context, int index) const {
203 return MemOperand(context, Context::SlotOffset(index));
204 }
205
206 MemOperand ParameterOperand(int index) const {
207 // index -2 corresponds to the activated closure, -1 corresponds
208 // to the receiver
209 ASSERT(-2 <= index && index < scope_->num_parameters());
210 int offset = JavaScriptFrameConstants::kParam0Offset - index * kPointerSize;
211 return MemOperand(pp, offset);
212 }
213
214 MemOperand FunctionOperand() const { return ParameterOperand(-2); }
215
216 Register SlotRegister(int slot_index);
217 MemOperand SlotOperand(Slot* slot, Register tmp);
218
219 void LoadCondition(Expression* x, CodeGenState::AccessType access,
220 Label* true_target, Label* false_target, bool force_cc);
221 void Load(Expression* x,
222 CodeGenState::AccessType access = CodeGenState::LOAD);
223 void LoadGlobal();
224
225 // Special code for typeof expressions: Unfortunately, we must
226 // be careful when loading the expression in 'typeof'
227 // expressions. We are not allowed to throw reference errors for
228 // non-existing properties of the global object, so we must make it
229 // look like an explicit property access, instead of an access
230 // through the context chain.
231 void LoadTypeofExpression(Expression* x);
232
233 // References
234 void AccessReference(Reference* ref, CodeGenState::AccessType access);
235
236 void GetValue(Reference* ref) { AccessReference(ref, CodeGenState::LOAD); }
237 void SetValue(Reference* ref) { AccessReference(ref, CodeGenState::STORE); }
238 void InitConst(Reference* ref) {
239 AccessReference(ref, CodeGenState::INIT_CONST);
240 }
241
242 void ToBoolean(Register reg, Label* true_target, Label* false_target);
243
244
245 // Access property from the reference (must be at the TOS).
246 void AccessReferenceProperty(Expression* key,
247 CodeGenState::AccessType access);
248
249 void GenericOperation(Token::Value op);
250 void Comparison(Condition cc, bool strict = false);
251
252 void SmiOperation(Token::Value op, Handle<Object> value, bool reversed);
253
254 void CallWithArguments(ZoneList<Expression*>* arguments, int position);
255
256 // Declare global variables and functions in the given array of
257 // name/value pairs.
258 virtual void DeclareGlobals(Handle<FixedArray> pairs);
259
260 // Instantiate the function boilerplate.
261 void InstantiateBoilerplate(Handle<JSFunction> boilerplate);
262
263 // Control flow
264 void Branch(bool if_true, Label* L);
265 void CheckStack();
266 void CleanStack(int num_bytes);
267
268 // Node visitors
269#define DEF_VISIT(type) \
270 virtual void Visit##type(type* node);
271 NODE_LIST(DEF_VISIT)
272#undef DEF_VISIT
273
274 void RecordStatementPosition(Node* node);
275
276 // Activation frames
277 void EnterJSFrame(int argc, RegList callee_saved); // preserves r1
278 void ExitJSFrame(RegList callee_saved,
279 ExitJSFlag flag = RETURN); // preserves r0-r2
280
281 virtual void GenerateShiftDownAndTailCall(ZoneList<Expression*>* args);
282 virtual void GenerateSetThisFunction(ZoneList<Expression*>* args);
283 virtual void GenerateGetThisFunction(ZoneList<Expression*>* args);
284 virtual void GenerateSetThis(ZoneList<Expression*>* args);
285 virtual void GenerateGetArgumentsLength(ZoneList<Expression*>* args);
286 virtual void GenerateSetArgumentsLength(ZoneList<Expression*>* args);
287 virtual void GenerateTailCallWithArguments(ZoneList<Expression*>* args);
288 virtual void GenerateSetArgument(ZoneList<Expression*>* args);
289 virtual void GenerateSquashFrame(ZoneList<Expression*>* args);
290 virtual void GenerateExpandFrame(ZoneList<Expression*>* args);
291 virtual void GenerateIsSmi(ZoneList<Expression*>* args);
292 virtual void GenerateIsArray(ZoneList<Expression*>* args);
293
294 virtual void GenerateArgumentsLength(ZoneList<Expression*>* args);
295 virtual void GenerateArgumentsAccess(ZoneList<Expression*>* args);
296
297 virtual void GenerateValueOf(ZoneList<Expression*>* args);
298 virtual void GenerateSetValueOf(ZoneList<Expression*>* args);
299};
300
301
302// -----------------------------------------------------------------------------
303// ArmCodeGenerator implementation
304
305#define __ masm_->
306
307
308Handle<Code> ArmCodeGenerator::MakeCode(FunctionLiteral* flit,
309 Handle<Script> script,
310 bool is_eval) {
311#ifdef DEBUG
312 bool print_source = false;
313 bool print_ast = false;
314 bool print_code = false;
315 const char* ftype;
316
317 if (Bootstrapper::IsActive()) {
318 print_source = FLAG_print_builtin_source;
319 print_ast = FLAG_print_builtin_ast;
320 print_code = FLAG_print_builtin_code;
321 ftype = "builtin";
322 } else {
323 print_source = FLAG_print_source;
324 print_ast = FLAG_print_ast;
325 print_code = FLAG_print_code;
326 ftype = "user-defined";
327 }
328
329 if (FLAG_trace_codegen || print_source || print_ast) {
330 PrintF("*** Generate code for %s function: ", ftype);
331 flit->name()->ShortPrint();
332 PrintF(" ***\n");
333 }
334
335 if (print_source) {
336 PrintF("--- Source from AST ---\n%s\n", PrettyPrinter().PrintProgram(flit));
337 }
338
339 if (print_ast) {
340 PrintF("--- AST ---\n%s\n", AstPrinter().PrintProgram(flit));
341 }
342#endif // DEBUG
343
344 // Generate code.
345 const int initial_buffer_size = 4 * KB;
346 ArmCodeGenerator cgen(initial_buffer_size, script, is_eval);
347 cgen.GenCode(flit);
348 if (cgen.HasStackOverflow()) {
kasper.lund212ac232008-07-16 07:07:30 +0000349 ASSERT(!Top::has_pending_exception());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350 return Handle<Code>::null();
351 }
352
353 // Process any deferred code.
354 cgen.ProcessDeferred();
355
356 // Allocate and install the code.
357 CodeDesc desc;
358 cgen.masm()->GetCode(&desc);
359 ScopeInfo<> sinfo(flit->scope());
360 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
361 Handle<Code> code = Factory::NewCode(desc, &sinfo, flags);
362
363 // Add unresolved entries in the code to the fixup list.
364 Bootstrapper::AddFixup(*code, cgen.masm());
365
366#ifdef DEBUG
367 if (print_code) {
368 // Print the source code if available.
369 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
370 PrintF("--- Raw source ---\n");
371 StringInputBuffer stream(String::cast(script->source()));
372 stream.Seek(flit->start_position());
373 // flit->end_position() points to the last character in the stream. We
374 // need to compensate by adding one to calculate the length.
375 int source_len = flit->end_position() - flit->start_position() + 1;
376 for (int i = 0; i < source_len; i++) {
377 if (stream.has_more()) PrintF("%c", stream.GetNext());
378 }
379 PrintF("\n\n");
380 }
381 PrintF("--- Code ---\n");
382 code->Print();
383 }
384#endif // DEBUG
385
386 return code;
387}
388
389
390ArmCodeGenerator::ArmCodeGenerator(int buffer_size,
391 Handle<Script> script,
392 bool is_eval)
393 : CodeGenerator(is_eval, script),
394 masm_(new MacroAssembler(NULL, buffer_size)),
395 scope_(NULL),
396 cc_reg_(al),
397 state_(NULL),
398 break_stack_height_(0) {
399}
400
401
402// Calling conventions:
403
404// r0: always contains top-of-stack (TOS), but in case of a call it's
405// the number of arguments
406// fp: frame pointer
407// sp: stack pointer
408// pp: caller's parameter pointer
409// cp: callee's context
410
411void ArmCodeGenerator::GenCode(FunctionLiteral* fun) {
412 Scope* scope = fun->scope();
413 ZoneList<Statement*>* body = fun->body();
414
415 // Initialize state.
416 { CodeGenState state;
417 state_ = &state;
418 scope_ = scope;
419 cc_reg_ = al;
420 if (FLAG_optimize_locals) {
421 num_reg_locals_ = scope->num_stack_slots() < kNumJSCalleeSaved
422 ? scope->num_stack_slots()
423 : kNumJSCalleeSaved;
424 reg_locals_ = JSCalleeSavedList(num_reg_locals_);
425 } else {
426 num_reg_locals_ = 0;
427 reg_locals_ = 0;
428 }
429
430 // Entry
431 // stack: function, receiver, arguments, return address
432 // r0: number of arguments
433 // sp: stack pointer
434 // fp: frame pointer
435 // pp: caller's parameter pointer
436 // cp: callee's context
437
438 { Comment cmnt(masm_, "[ enter JS frame");
439 EnterJSFrame(scope->num_parameters(), reg_locals_);
440 }
441 // tos: code slot
442#ifdef DEBUG
443 if (strlen(FLAG_stop_at) > 0 &&
444 fun->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
445 __ bkpt(0); // not supported before v5, but illegal instruction works too
446 }
447#endif
448
449 // Allocate space for locals and initialize them.
450 if (scope->num_stack_slots() > num_reg_locals_) {
451 Comment cmnt(masm_, "[ allocate space for locals");
452 // Pushing the first local materializes the code slot on the stack
453 // (formerly stored in tos register r0).
454 __ Push(Operand(Factory::undefined_value()));
455 // The remaining locals are pushed using the fact that r0 (tos)
456 // already contains the undefined value.
457 for (int i = scope->num_stack_slots(); i-- > num_reg_locals_ + 1;) {
458 __ push(r0);
459 }
460 }
461 // Initialize locals allocated in registers
462 if (num_reg_locals_ > 0) {
463 if (scope->num_stack_slots() > num_reg_locals_) {
464 // r0 contains 'undefined'
465 __ mov(SlotRegister(0), Operand(r0));
466 } else {
467 __ mov(SlotRegister(0), Operand(Factory::undefined_value()));
468 }
469 for (int i = num_reg_locals_ - 1; i > 0; i--) {
470 __ mov(SlotRegister(i), Operand(SlotRegister(0)));
471 }
472 }
473
474 if (scope->num_heap_slots() > 0) {
475 // Allocate local context.
476 // Get outer context and create a new context based on it.
477 __ Push(FunctionOperand());
478 __ CallRuntime(Runtime::kNewContext, 2);
479 // Update context local.
480 __ str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
481 }
482
483 // TODO(1241774): Improve this code!!!
484 // 1) only needed if we have a context
485 // 2) no need to recompute context ptr every single time
486 // 3) don't copy parameter operand code from SlotOperand!
487 {
488 Comment cmnt2(masm_, "[ copy context parameters into .context");
489
490 // Note that iteration order is relevant here! If we have the same
491 // parameter twice (e.g., function (x, y, x)), and that parameter
492 // needs to be copied into the context, it must be the last argument
493 // passed to the parameter that needs to be copied. This is a rare
494 // case so we don't check for it, instead we rely on the copying
495 // order: such a parameter is copied repeatedly into the same
496 // context location and thus the last value is what is seen inside
497 // the function.
498 for (int i = 0; i < scope->num_parameters(); i++) {
499 Variable* par = scope->parameter(i);
500 Slot* slot = par->slot();
501 if (slot != NULL && slot->type() == Slot::CONTEXT) {
502 ASSERT(!scope->is_global_scope()); // no parameters in global scope
503 int parameter_offset =
504 JavaScriptFrameConstants::kParam0Offset - i * kPointerSize;
505 __ ldr(r1, MemOperand(pp, parameter_offset));
506 // Loads r2 with context; used below in RecordWrite.
507 __ str(r1, SlotOperand(slot, r2));
508 // Load the offset into r3.
509 int slot_offset =
510 FixedArray::kHeaderSize + slot->index() * kPointerSize;
511 __ mov(r3, Operand(slot_offset));
512 __ RecordWrite(r2, r3, r1);
513 }
514 }
515 }
516
517 // Store the arguments object.
518 // This must happen after context initialization because
519 // the arguments array may be stored in the context!
520 if (scope->arguments() != NULL) {
521 ASSERT(scope->arguments_shadow() != NULL);
522 Comment cmnt(masm_, "[ allocate arguments object");
523 {
524 Reference target(this, scope->arguments());
525 __ Push(FunctionOperand());
526 __ CallRuntime(Runtime::kNewArguments, 1);
527 SetValue(&target);
528 }
529 // The value of arguments must also be stored in .arguments.
530 // TODO(1241813): This code can probably be improved by fusing it with
531 // the code that stores the arguments object above.
532 {
533 Reference target(this, scope->arguments_shadow());
534 Load(scope->arguments());
535 SetValue(&target);
536 }
537 }
538
539 // Generate code to 'execute' declarations and initialize
540 // functions (source elements). In case of an illegal
541 // redeclaration we need to handle that instead of processing the
542 // declarations.
543 if (scope->HasIllegalRedeclaration()) {
544 Comment cmnt(masm_, "[ illegal redeclarations");
545 scope->VisitIllegalRedeclaration(this);
546 } else {
547 Comment cmnt(masm_, "[ declarations");
548 ProcessDeclarations(scope->declarations());
kasper.lund212ac232008-07-16 07:07:30 +0000549 // Bail out if a stack-overflow exception occured when
550 // processing declarations.
551 if (HasStackOverflow()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000552 }
553
554 if (FLAG_trace) __ CallRuntime(Runtime::kTraceEnter, 1);
555 CheckStack();
556
557 // Compile the body of the function in a vanilla state. Don't
558 // bother compiling all the code if the scope has an illegal
559 // redeclaration.
560 if (!scope->HasIllegalRedeclaration()) {
561 Comment cmnt(masm_, "[ function body");
562#ifdef DEBUG
563 bool is_builtin = Bootstrapper::IsActive();
564 bool should_trace =
565 is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
566 if (should_trace) __ CallRuntime(Runtime::kDebugTrace, 1);
567#endif
568 VisitStatements(body);
569 }
570
571 state_ = NULL;
572 }
573
574 // exit
575 // r0: result
576 // sp: stack pointer
577 // fp: frame pointer
578 // pp: parameter pointer
579 // cp: callee's context
580 __ Push(Operand(Factory::undefined_value()));
581 __ bind(&function_return_);
582 if (FLAG_trace) __ CallRuntime(Runtime::kTraceExit, 1);
583 ExitJSFrame(reg_locals_);
584
585 // Code generation state must be reset.
586 scope_ = NULL;
587 ASSERT(!has_cc());
588 ASSERT(state_ == NULL);
589}
590
591
592Register ArmCodeGenerator::SlotRegister(int slot_index) {
593 Register reg;
594 reg.code_ = JSCalleeSavedCode(slot_index);
595 return reg;
596}
597
598
599MemOperand ArmCodeGenerator::SlotOperand(Slot* slot, Register tmp) {
600 // Currently, this assertion will fail if we try to assign to
601 // a constant variable that is constant because it is read-only
602 // (such as the variable referring to a named function expression).
603 // We need to implement assignments to read-only variables.
604 // Ideally, we should do this during AST generation (by converting
605 // such assignments into expression statements); however, in general
606 // we may not be able to make the decision until past AST generation,
607 // that is when the entire program is known.
608 ASSERT(slot != NULL);
609 int index = slot->index();
610 switch (slot->type()) {
611 case Slot::PARAMETER:
612 return ParameterOperand(index);
613
614 case Slot::LOCAL: {
615 ASSERT(0 <= index &&
616 index < scope_->num_stack_slots() &&
617 index >= num_reg_locals_);
618 int local_offset = JavaScriptFrameConstants::kLocal0Offset -
619 (index - num_reg_locals_) * kPointerSize;
620 return MemOperand(fp, local_offset);
621 }
622
623 case Slot::CONTEXT: {
624 // Follow the context chain if necessary.
625 ASSERT(!tmp.is(cp)); // do not overwrite context register
626 Register context = cp;
627 int chain_length = scope_->ContextChainLength(slot->var()->scope());
628 for (int i = chain_length; i-- > 0;) {
629 // Load the closure.
630 // (All contexts, even 'with' contexts, have a closure,
631 // and it is the same for all contexts inside a function.
632 // There is no need to go to the function context first.)
633 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
634 // Load the function context (which is the incoming, outer context).
635 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
636 context = tmp;
637 }
638 // We may have a 'with' context now. Get the function context.
639 // (In fact this mov may never be the needed, since the scope analysis
640 // may not permit a direct context access in this case and thus we are
641 // always at a function context. However it is safe to dereference be-
642 // cause the function context of a function context is itself. Before
643 // deleting this mov we should try to create a counter-example first,
644 // though...)
645 __ ldr(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
646 return ContextOperand(tmp, index);
647 }
648
649 default:
650 UNREACHABLE();
651 return MemOperand(r0, 0);
652 }
653}
654
655
656// Loads a value on TOS. If it is a boolean value, the result may have been
657// (partially) translated into branches, or it may have set the condition code
658// register. If force_cc is set, the value is forced to set the condition code
659// register and no value is pushed. If the condition code register was set,
660// has_cc() is true and cc_reg_ contains the condition to test for 'true'.
661void ArmCodeGenerator::LoadCondition(Expression* x,
662 CodeGenState::AccessType access,
663 Label* true_target,
664 Label* false_target,
665 bool force_cc) {
666 ASSERT(access == CodeGenState::LOAD ||
667 access == CodeGenState::LOAD_TYPEOF_EXPR);
668 ASSERT(!has_cc() && !is_referenced());
669
670 CodeGenState* old_state = state_;
671 CodeGenState new_state(access, NULL, true_target, false_target);
672 state_ = &new_state;
673 Visit(x);
674 state_ = old_state;
675 if (force_cc && !has_cc()) {
676 // Pop the TOS from the stack and convert it to a boolean in the
677 // condition code register.
678 __ mov(r1, Operand(r0));
679 __ pop(r0);
680 ToBoolean(r1, true_target, false_target);
681 }
682 ASSERT(has_cc() || !force_cc);
683}
684
685
686void ArmCodeGenerator::Load(Expression* x, CodeGenState::AccessType access) {
687 ASSERT(access == CodeGenState::LOAD ||
688 access == CodeGenState::LOAD_TYPEOF_EXPR);
689
690 Label true_target;
691 Label false_target;
692 LoadCondition(x, access, &true_target, &false_target, false);
693
694 if (has_cc()) {
695 // convert cc_reg_ into a bool
696 Label loaded, materialize_true;
697 __ b(cc_reg_, &materialize_true);
698 __ Push(Operand(Factory::false_value()));
699 __ b(&loaded);
700 __ bind(&materialize_true);
701 __ Push(Operand(Factory::true_value()));
702 __ bind(&loaded);
703 cc_reg_ = al;
704 }
705
706 if (true_target.is_linked() || false_target.is_linked()) {
707 // we have at least one condition value
708 // that has been "translated" into a branch,
709 // thus it needs to be loaded explicitly again
710 Label loaded;
711 __ b(&loaded); // don't lose current TOS
712 bool both = true_target.is_linked() && false_target.is_linked();
713 // reincarnate "true", if necessary
714 if (true_target.is_linked()) {
715 __ bind(&true_target);
716 __ Push(Operand(Factory::true_value()));
717 }
718 // if both "true" and "false" need to be reincarnated,
719 // jump across code for "false"
720 if (both)
721 __ b(&loaded);
722 // reincarnate "false", if necessary
723 if (false_target.is_linked()) {
724 __ bind(&false_target);
725 __ Push(Operand(Factory::false_value()));
726 }
727 // everything is loaded at this point
728 __ bind(&loaded);
729 }
730 ASSERT(!has_cc());
731}
732
733
734void ArmCodeGenerator::LoadGlobal() {
735 __ Push(GlobalObject());
736}
737
738
739// TODO(1241834): Get rid of this function in favor of just using Load, now
740// that we have the LOAD_TYPEOF_EXPR access type. => Need to handle
741// global variables w/o reference errors elsewhere.
742void ArmCodeGenerator::LoadTypeofExpression(Expression* x) {
743 Variable* variable = x->AsVariableProxy()->AsVariable();
744 if (variable != NULL && !variable->is_this() && variable->is_global()) {
745 // NOTE: This is somewhat nasty. We force the compiler to load
746 // the variable as if through '<global>.<variable>' to make sure we
747 // do not get reference errors.
748 Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
749 Literal key(variable->name());
750 // TODO(1241834): Fetch the position from the variable instead of using
751 // no position.
752 Property property(&global, &key, kNoPosition);
753 Load(&property);
754 } else {
755 Load(x, CodeGenState::LOAD_TYPEOF_EXPR);
756 }
757}
758
759
760Reference::Reference(ArmCodeGenerator* cgen, Expression* expression)
761 : cgen_(cgen), expression_(expression), type_(ILLEGAL) {
762 cgen->LoadReference(this);
763}
764
765
766Reference::~Reference() {
767 cgen_->UnloadReference(this);
768}
769
770
771void ArmCodeGenerator::LoadReference(Reference* ref) {
772 Expression* e = ref->expression();
773 Property* property = e->AsProperty();
774 Variable* var = e->AsVariableProxy()->AsVariable();
775
776 if (property != NULL) {
777 Load(property->obj());
778 // Used a named reference if the key is a literal symbol.
779 // We don't use a named reference if they key is a string that can be
780 // legally parsed as an integer. This is because, otherwise we don't
781 // get into the slow case code that handles [] on String objects.
782 Literal* literal = property->key()->AsLiteral();
783 uint32_t dummy;
784 if (literal != NULL && literal->handle()->IsSymbol() &&
785 !String::cast(*(literal->handle()))->AsArrayIndex(&dummy)) {
786 ref->set_type(Reference::NAMED);
787 } else {
788 Load(property->key());
789 ref->set_type(Reference::KEYED);
790 }
791 } else if (var != NULL) {
792 if (var->is_global()) {
793 // global variable
794 LoadGlobal();
795 ref->set_type(Reference::NAMED);
796 } else {
797 // local variable
798 ref->set_type(Reference::EMPTY);
799 }
800 } else {
801 Load(e);
802 __ CallRuntime(Runtime::kThrowReferenceError, 1);
803 }
804}
805
806
807void ArmCodeGenerator::UnloadReference(Reference* ref) {
808 int size = ref->size();
809 if (size <= 0) {
810 // Do nothing. No popping is necessary.
811 } else {
812 __ add(sp, sp, Operand(size * kPointerSize));
813 }
814}
815
816
817void ArmCodeGenerator::AccessReference(Reference* ref,
818 CodeGenState::AccessType access) {
819 ASSERT(!has_cc());
820 ASSERT(ref->type() != Reference::ILLEGAL);
821 CodeGenState* old_state = state_;
822 CodeGenState new_state(access, ref, true_target(), false_target());
823 state_ = &new_state;
824 Visit(ref->expression());
825 state_ = old_state;
826}
827
828
829// ECMA-262, section 9.2, page 30: ToBoolean(). Convert the given
830// register to a boolean in the condition code register. The code
831// may jump to 'false_target' in case the register converts to 'false'.
832void ArmCodeGenerator::ToBoolean(Register reg,
833 Label* true_target,
834 Label* false_target) {
835 // Note: The generated code snippet cannot change 'reg'.
836 // Only the condition code should be set.
837
838 // Fast case checks
839
840 // Check if reg is 'false'.
841 __ cmp(reg, Operand(Factory::false_value()));
842 __ b(eq, false_target);
843
844 // Check if reg is 'true'.
845 __ cmp(reg, Operand(Factory::true_value()));
846 __ b(eq, true_target);
847
848 // Check if reg is 'undefined'.
849 __ cmp(reg, Operand(Factory::undefined_value()));
850 __ b(eq, false_target);
851
852 // Check if reg is a smi.
853 __ cmp(reg, Operand(Smi::FromInt(0)));
854 __ b(eq, false_target);
855 __ tst(reg, Operand(kSmiTagMask));
856 __ b(eq, true_target);
857
858 // Slow case: call the runtime.
859 __ push(r0);
860 if (r0.is(reg)) {
861 __ CallRuntime(Runtime::kToBool, 1);
862 } else {
863 __ mov(r0, Operand(reg));
864 __ CallRuntime(Runtime::kToBool, 1);
865 }
866 // Convert result (r0) to condition code
867 __ cmp(r0, Operand(Factory::false_value()));
868 __ pop(r0);
869
870 cc_reg_ = ne;
871}
872
873
874#undef __
875#define __ masm->
876
877
878class GetPropertyStub : public CodeStub {
879 public:
880 GetPropertyStub() { }
881
882 private:
883 Major MajorKey() { return GetProperty; }
884 int MinorKey() { return 0; }
885 void Generate(MacroAssembler* masm);
886
887 const char* GetName() { return "GetPropertyStub"; }
888};
889
890
891void GetPropertyStub::Generate(MacroAssembler* masm) {
892 Label slow, fast;
893 // Get the object from the stack.
894 __ ldr(r1, MemOperand(sp, 1 * kPointerSize)); // 1 ~ key
895 // Check that the key is a smi.
896 __ tst(r0, Operand(kSmiTagMask));
897 __ b(ne, &slow);
898 __ mov(r0, Operand(r0, ASR, kSmiTagSize));
899 // Check that the object isn't a smi.
900 __ tst(r1, Operand(kSmiTagMask));
901 __ b(eq, &slow);
902 // Check that the object is some kind of JS object.
903 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset));
904 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
905 __ cmp(r2, Operand(JS_OBJECT_TYPE));
906 __ b(lt, &slow);
907
908 // Check if the object is a value-wrapper object. In that case we
909 // enter the runtime system to make sure that indexing into string
910 // objects work as intended.
911 __ cmp(r2, Operand(JS_VALUE_TYPE));
912 __ b(eq, &slow);
913
914 // Get the elements array of the object.
915 __ ldr(r1, FieldMemOperand(r1, JSObject::kElementsOffset));
916 // Check that the object is in fast mode (not dictionary).
917 __ ldr(r3, FieldMemOperand(r1, HeapObject::kMapOffset));
918 __ cmp(r3, Operand(Factory::hash_table_map()));
919 __ b(eq, &slow);
920 // Check that the key (index) is within bounds.
921 __ ldr(r3, FieldMemOperand(r1, Array::kLengthOffset));
922 __ cmp(r0, Operand(r3));
923 __ b(lo, &fast);
924
925 // Slow case: Push extra copies of the arguments (2).
926 __ bind(&slow);
927 __ ldm(ia, sp, r0.bit() | r1.bit());
928 __ stm(db_w, sp, r0.bit() | r1.bit());
929 // Do tail-call to runtime routine.
930 __ mov(r0, Operand(1)); // not counting receiver
931 __ JumpToBuiltin(ExternalReference(Runtime::kGetProperty));
932
933 // Fast case: Do the load.
934 __ bind(&fast);
935 __ add(r3, r1, Operand(Array::kHeaderSize - kHeapObjectTag));
936 __ ldr(r0, MemOperand(r3, r0, LSL, kPointerSizeLog2));
937 __ cmp(r0, Operand(Factory::the_hole_value()));
938 // In case the loaded value is the_hole we have to consult GetProperty
939 // to ensure the prototype chain is searched.
940 __ b(eq, &slow);
941
942 masm->StubReturn(1);
943}
944
945
946class SetPropertyStub : public CodeStub {
947 public:
948 SetPropertyStub() { }
949
950 private:
951 Major MajorKey() { return SetProperty; }
952 int MinorKey() { return 0; }
953 void Generate(MacroAssembler* masm);
954
955 const char* GetName() { return "GetPropertyStub"; }
956};
957
958
959void SetPropertyStub::Generate(MacroAssembler* masm) {
960 Label slow, fast, array, extra, exit;
961 // Get the key and the object from the stack.
962 __ ldm(ia, sp, r1.bit() | r3.bit()); // r0 == value, r1 == key, r3 == object
963 // Check that the key is a smi.
964 __ tst(r1, Operand(kSmiTagMask));
965 __ b(ne, &slow);
966 // Check that the object isn't a smi.
967 __ tst(r3, Operand(kSmiTagMask));
968 __ b(eq, &slow);
969 // Get the type of the object from its map.
970 __ ldr(r2, FieldMemOperand(r3, HeapObject::kMapOffset));
971 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
972 // Check if the object is a JS array or not.
973 __ cmp(r2, Operand(JS_ARRAY_TYPE));
974 __ b(eq, &array);
975 // Check that the object is some kind of JS object.
976 __ cmp(r2, Operand(JS_OBJECT_TYPE));
977 __ b(lt, &slow);
978
979
980 // Object case: Check key against length in the elements array.
981 __ ldr(r3, FieldMemOperand(r3, JSObject::kElementsOffset));
982 // Check that the object is in fast mode (not dictionary).
983 __ ldr(r2, FieldMemOperand(r3, HeapObject::kMapOffset));
984 __ cmp(r2, Operand(Factory::hash_table_map()));
985 __ b(eq, &slow);
986 // Untag the key (for checking against untagged length in the fixed array).
987 __ mov(r1, Operand(r1, ASR, kSmiTagSize));
988 // Compute address to store into and check array bounds.
989 __ add(r2, r3, Operand(Array::kHeaderSize - kHeapObjectTag));
990 __ add(r2, r2, Operand(r1, LSL, kPointerSizeLog2));
991 __ ldr(ip, FieldMemOperand(r3, Array::kLengthOffset));
992 __ cmp(r1, Operand(ip));
993 __ b(lo, &fast);
994
995
996 // Slow case: Push extra copies of the arguments (3).
997 // r0 == value
998 __ bind(&slow);
999 __ ldm(ia, sp, r1.bit() | r3.bit()); // r0 == value, r1 == key, r3 == object
1000 __ stm(db_w, sp, r0.bit() | r1.bit() | r3.bit());
1001 // Do tail-call to runtime routine.
1002 __ mov(r0, Operand(2)); // not counting receiver
1003 __ JumpToBuiltin(ExternalReference(Runtime::kSetProperty));
1004
1005
1006 // Extra capacity case: Check if there is extra capacity to
1007 // perform the store and update the length. Used for adding one
1008 // element to the array by writing to array[array.length].
1009 // r0 == value, r1 == key, r2 == elements, r3 == object
1010 __ bind(&extra);
1011 __ b(ne, &slow); // do not leave holes in the array
1012 __ mov(r1, Operand(r1, ASR, kSmiTagSize)); // untag
1013 __ ldr(ip, FieldMemOperand(r2, Array::kLengthOffset));
1014 __ cmp(r1, Operand(ip));
1015 __ b(hs, &slow);
1016 __ mov(r1, Operand(r1, LSL, kSmiTagSize)); // restore tag
1017 __ add(r1, r1, Operand(1 << kSmiTagSize)); // and increment
1018 __ str(r1, FieldMemOperand(r3, JSArray::kLengthOffset));
1019 __ mov(r3, Operand(r2));
1020 // NOTE: Computing the address to store into must take the fact
1021 // that the key has been incremented into account.
1022 int displacement = Array::kHeaderSize - kHeapObjectTag -
1023 ((1 << kSmiTagSize) * 2);
1024 __ add(r2, r2, Operand(displacement));
1025 __ add(r2, r2, Operand(r1, LSL, kPointerSizeLog2 - kSmiTagSize));
1026 __ b(&fast);
1027
1028
1029 // Array case: Get the length and the elements array from the JS
1030 // array. Check that the array is in fast mode; if it is the
1031 // length is always a smi.
1032 // r0 == value, r3 == object
1033 __ bind(&array);
1034 __ ldr(r2, FieldMemOperand(r3, JSObject::kElementsOffset));
1035 __ ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
1036 __ cmp(r1, Operand(Factory::hash_table_map()));
1037 __ b(eq, &slow);
1038
1039 // Check the key against the length in the array, compute the
1040 // address to store into and fall through to fast case.
1041 __ ldr(r1, MemOperand(sp));
1042 // r0 == value, r1 == key, r2 == elements, r3 == object.
1043 __ ldr(ip, FieldMemOperand(r3, JSArray::kLengthOffset));
1044 __ cmp(r1, Operand(ip));
1045 __ b(hs, &extra);
1046 __ mov(r3, Operand(r2));
1047 __ add(r2, r2, Operand(Array::kHeaderSize - kHeapObjectTag));
1048 __ add(r2, r2, Operand(r1, LSL, kPointerSizeLog2 - kSmiTagSize));
1049
1050
1051 // Fast case: Do the store.
1052 // r0 == value, r2 == address to store into, r3 == elements
1053 __ bind(&fast);
1054 __ str(r0, MemOperand(r2));
1055 // Skip write barrier if the written value is a smi.
1056 __ tst(r0, Operand(kSmiTagMask));
1057 __ b(eq, &exit);
1058 // Update write barrier for the elements array address.
1059 __ sub(r1, r2, Operand(r3));
1060 __ RecordWrite(r3, r1, r2);
1061 __ bind(&exit);
1062 masm->StubReturn(1);
1063}
1064
1065
1066void GenericOpStub::Generate(MacroAssembler* masm) {
1067 switch (op_) {
1068 case Token::ADD: {
1069 Label slow, exit;
1070 // fast path
1071 // Get x (y is on TOS, i.e., r0).
1072 __ ldr(r1, MemOperand(sp, 0 * kPointerSize));
1073 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
1074 __ add(r0, r1, Operand(r0), SetCC); // add y optimistically
1075 // go slow-path in case of overflow
1076 __ b(vs, &slow);
1077 // go slow-path in case of non-smi operands
1078 ASSERT(kSmiTag == 0); // adjust code below
1079 __ tst(r2, Operand(kSmiTagMask));
1080 __ b(eq, &exit);
1081 // slow path
1082 __ bind(&slow);
1083 __ sub(r0, r0, Operand(r1)); // revert optimistic add
1084 __ push(r0);
1085 __ mov(r0, Operand(1)); // set number of arguments
1086 __ InvokeBuiltin("ADD", 1, JUMP_JS);
1087 // done
1088 __ bind(&exit);
1089 break;
1090 }
1091
1092 case Token::SUB: {
1093 Label slow, exit;
1094 // fast path
1095 __ ldr(r1, MemOperand(sp, 0 * kPointerSize)); // get x
1096 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
1097 __ sub(r3, r1, Operand(r0), SetCC); // subtract y optimistically
1098 // go slow-path in case of overflow
1099 __ b(vs, &slow);
1100 // go slow-path in case of non-smi operands
1101 ASSERT(kSmiTag == 0); // adjust code below
1102 __ tst(r2, Operand(kSmiTagMask));
1103 __ mov(r0, Operand(r3), LeaveCC, eq); // conditionally set r0 to result
1104 __ b(eq, &exit);
1105 // slow path
1106 __ bind(&slow);
1107 __ push(r0);
1108 __ mov(r0, Operand(1)); // set number of arguments
1109 __ InvokeBuiltin("SUB", 1, JUMP_JS);
1110 // done
1111 __ bind(&exit);
1112 break;
1113 }
1114
1115 case Token::MUL: {
1116 Label slow, exit;
1117 __ ldr(r1, MemOperand(sp, 0 * kPointerSize)); // get x
1118 // tag check
1119 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
1120 ASSERT(kSmiTag == 0); // adjust code below
1121 __ tst(r2, Operand(kSmiTagMask));
1122 __ b(ne, &slow);
1123 // remove tag from one operand (but keep sign), so that result is smi
1124 __ mov(ip, Operand(r0, ASR, kSmiTagSize));
1125 // do multiplication
1126 __ smull(r3, r2, r1, ip); // r3 = lower 32 bits of ip*r1
1127 // go slow on overflows (overflow bit is not set)
1128 __ mov(ip, Operand(r3, ASR, 31));
1129 __ cmp(ip, Operand(r2)); // no overflow if higher 33 bits are identical
1130 __ b(ne, &slow);
1131 // go slow on zero result to handle -0
1132 __ tst(r3, Operand(r3));
1133 __ mov(r0, Operand(r3), LeaveCC, ne);
1134 __ b(ne, &exit);
1135 // slow case
1136 __ bind(&slow);
1137 __ push(r0);
1138 __ mov(r0, Operand(1)); // set number of arguments
1139 __ InvokeBuiltin("MUL", 1, JUMP_JS);
1140 // done
1141 __ bind(&exit);
1142 break;
1143 }
1144 default: UNREACHABLE();
1145 }
1146 masm->StubReturn(2);
1147}
1148
1149
1150class SmiOpStub : public CodeStub {
1151 public:
1152 SmiOpStub(Token::Value op, bool reversed)
1153 : op_(op), reversed_(reversed) {}
1154
1155 private:
1156 Token::Value op_;
1157 bool reversed_;
1158
1159 Major MajorKey() { return SmiOp; }
1160 int MinorKey() {
1161 return (op_ == Token::ADD ? 2 : 0) | (reversed_ ? 1 : 0);
1162 }
1163 void Generate(MacroAssembler* masm);
1164 void GenerateShared(MacroAssembler* masm);
1165
1166 const char* GetName() { return "SmiOpStub"; }
1167
1168#ifdef DEBUG
1169 void Print() {
1170 PrintF("SmiOpStub (token %s), (reversed %s)\n",
1171 Token::String(op_), reversed_ ? "true" : "false");
1172 }
1173#endif
1174};
1175
1176
1177void SmiOpStub::Generate(MacroAssembler* masm) {
1178 switch (op_) {
1179 case Token::ADD: {
1180 if (!reversed_) {
1181 __ sub(r0, r0, Operand(r1)); // revert optimistic add
1182 __ push(r0);
1183 __ push(r1);
1184 __ mov(r0, Operand(1)); // set number of arguments
1185 __ InvokeBuiltin("ADD", 1, JUMP_JS);
1186 } else {
1187 __ sub(r0, r0, Operand(r1)); // revert optimistic add
1188 __ push(r1); // reversed
1189 __ push(r0);
1190 __ mov(r0, Operand(1)); // set number of arguments
1191 __ InvokeBuiltin("ADD", 1, JUMP_JS);
1192 }
1193 break;
1194 }
1195 case Token::SUB: {
1196 if (!reversed_) {
1197 __ push(r0);
1198 __ push(r1);
1199 __ mov(r0, Operand(1)); // set number of arguments
1200 __ InvokeBuiltin("SUB", 1, JUMP_JS);
1201 } else {
1202 __ push(r1);
1203 __ push(r0);
1204 __ mov(r0, Operand(1)); // set number of arguments
1205 __ InvokeBuiltin("SUB", 1, JUMP_JS);
1206 }
1207 break;
1208 }
1209 default: UNREACHABLE();
1210 }
1211}
1212
1213void StackCheckStub::Generate(MacroAssembler* masm) {
1214 Label within_limit;
1215 __ mov(ip, Operand(ExternalReference::address_of_stack_guard_limit()));
1216 __ ldr(ip, MemOperand(ip));
1217 __ cmp(sp, Operand(ip));
1218 __ b(hs, &within_limit);
1219 // Do tail-call to runtime routine.
1220 __ push(r0);
1221 __ mov(r0, Operand(0)); // not counting receiver (i.e. flushed TOS)
1222 __ JumpToBuiltin(ExternalReference(Runtime::kStackGuard));
1223 __ bind(&within_limit);
1224
1225 masm->StubReturn(1);
1226}
1227
1228
1229void UnarySubStub::Generate(MacroAssembler* masm) {
1230 Label undo;
1231 Label slow;
1232 Label done;
1233
1234 // Enter runtime system if the value is not a smi.
1235 __ tst(r0, Operand(kSmiTagMask));
1236 __ b(ne, &slow);
1237
1238 // Enter runtime system if the value of the expression is zero
1239 // to make sure that we switch between 0 and -0.
1240 __ cmp(r0, Operand(0));
1241 __ b(eq, &slow);
1242
1243 // The value of the expression is a smi that is not zero. Try
1244 // optimistic subtraction '0 - value'.
1245 __ rsb(r1, r0, Operand(0), SetCC);
1246 __ b(vs, &slow);
1247
1248 // If result is a smi we are done.
1249 __ tst(r1, Operand(kSmiTagMask));
1250 __ mov(r0, Operand(r1), LeaveCC, eq); // conditionally set r0 to result
1251 __ b(eq, &done);
1252
1253 // Enter runtime system.
1254 __ bind(&slow);
1255 __ push(r0);
1256 __ mov(r0, Operand(0)); // set number of arguments
1257 __ InvokeBuiltin("UNARY_MINUS", 0, JUMP_JS);
1258
1259 __ bind(&done);
1260 masm->StubReturn(1);
1261}
1262
1263
1264class InvokeBuiltinStub : public CodeStub {
1265 public:
1266 enum Kind { Inc, Dec, ToNumber };
1267 InvokeBuiltinStub(Kind kind, int argc) : kind_(kind), argc_(argc) { }
1268
1269 private:
1270 Kind kind_;
1271 int argc_;
1272
1273 Major MajorKey() { return InvokeBuiltin; }
1274 int MinorKey() { return (argc_ << 3) | static_cast<int>(kind_); }
1275 void Generate(MacroAssembler* masm);
1276
1277 const char* GetName() { return "InvokeBuiltinStub"; }
1278
1279#ifdef DEBUG
1280 void Print() {
1281 PrintF("InvokeBuiltinStub (kind %d, argc, %d)\n",
1282 static_cast<int>(kind_),
1283 argc_);
1284 }
1285#endif
1286};
1287
1288
1289void InvokeBuiltinStub::Generate(MacroAssembler* masm) {
1290 __ push(r0);
1291 __ mov(r0, Operand(0)); // set number of arguments
1292 switch (kind_) {
1293 case ToNumber: __ InvokeBuiltin("TO_NUMBER", 0, JUMP_JS); break;
1294 case Inc: __ InvokeBuiltin("INC", 0, JUMP_JS); break;
1295 case Dec: __ InvokeBuiltin("DEC", 0, JUMP_JS); break;
1296 default: UNREACHABLE();
1297 }
1298 masm->StubReturn(argc_);
1299}
1300
1301
1302class JSExitStub : public CodeStub {
1303 public:
1304 enum Kind { Inc, Dec, ToNumber };
1305
1306 JSExitStub(int num_callee_saved, RegList callee_saved, ExitJSFlag flag)
1307 : num_callee_saved_(num_callee_saved),
1308 callee_saved_(callee_saved),
1309 flag_(flag) { }
1310
1311 private:
1312 int num_callee_saved_;
1313 RegList callee_saved_;
1314 ExitJSFlag flag_;
1315
1316 Major MajorKey() { return JSExit; }
1317 int MinorKey() { return (num_callee_saved_ << 3) | static_cast<int>(flag_); }
1318 void Generate(MacroAssembler* masm);
1319
1320 const char* GetName() { return "JSExitStub"; }
1321
1322#ifdef DEBUG
1323 void Print() {
1324 PrintF("JSExitStub (num_callee_saved %d, flag %d)\n",
1325 num_callee_saved_,
1326 static_cast<int>(flag_));
1327 }
1328#endif
1329};
1330
1331
1332void JSExitStub::Generate(MacroAssembler* masm) {
1333 __ ExitJSFrame(flag_, callee_saved_);
1334 masm->StubReturn(1);
1335}
1336
1337
1338
1339void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
1340 // r0 holds exception
1341 ASSERT(StackHandlerConstants::kSize == 6 * kPointerSize); // adjust this code
1342 if (FLAG_optimize_locals) {
1343 // Locals are allocated in callee-saved registers, so we need to restore
1344 // saved callee-saved registers by unwinding the stack
1345 static JSCalleeSavedBuffer regs;
1346 intptr_t arg0 = reinterpret_cast<intptr_t>(&regs);
1347 __ push(r0);
1348 __ mov(r0, Operand(arg0)); // exception in r0 (TOS) is pushed, r0 == arg0
1349 // Do not push a second C entry frame, but call directly
1350 __ Call(FUNCTION_ADDR(StackFrameIterator::RestoreCalleeSavedForTopHandler),
1351 runtime_entry); // passing r0
1352 // Frame::RestoreJSCalleeSaved returns arg0 (TOS)
1353 __ mov(r1, Operand(r0));
1354 __ pop(r0); // r1 holds arg0, r0 holds exception
1355 __ ldm(ia, r1, kJSCalleeSaved); // restore callee-saved registers
1356 }
1357 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
1358 __ ldr(sp, MemOperand(r3));
1359 __ pop(r2); // pop next in chain
1360 __ str(r2, MemOperand(r3));
1361 // restore parameter- and frame-pointer and pop state.
1362 __ ldm(ia_w, sp, r3.bit() | pp.bit() | fp.bit());
1363 // Before returning we restore the context from the frame pointer if not NULL.
1364 // The frame pointer is NULL in the exception handler of a JS entry frame.
1365 __ cmp(fp, Operand(0));
1366 // Set cp to NULL if fp is NULL.
1367 __ mov(cp, Operand(0), LeaveCC, eq);
1368 // Restore cp otherwise.
1369 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
1370 if (kDebug && FLAG_debug_code) __ mov(lr, Operand(pc));
1371 __ pop(pc);
1372}
1373
1374
1375void CEntryStub::GenerateThrowOutOfMemory(MacroAssembler* masm) {
1376 // Fetch top stack handler.
1377 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
1378 __ ldr(r3, MemOperand(r3));
1379
1380 // Unwind the handlers until the ENTRY handler is found.
1381 Label loop, done;
1382 __ bind(&loop);
1383 // Load the type of the current stack handler.
1384 const int kStateOffset = StackHandlerConstants::kAddressDisplacement +
1385 StackHandlerConstants::kStateOffset;
1386 __ ldr(r2, MemOperand(r3, kStateOffset));
1387 __ cmp(r2, Operand(StackHandler::ENTRY));
1388 __ b(eq, &done);
1389 // Fetch the next handler in the list.
1390 const int kNextOffset = StackHandlerConstants::kAddressDisplacement +
1391 StackHandlerConstants::kNextOffset;
1392 __ ldr(r3, MemOperand(r3, kNextOffset));
1393 __ jmp(&loop);
1394 __ bind(&done);
1395
1396 // Set the top handler address to next handler past the current ENTRY handler.
1397 __ ldr(r0, MemOperand(r3, kNextOffset));
1398 __ mov(r2, Operand(ExternalReference(Top::k_handler_address)));
1399 __ str(r0, MemOperand(r2));
1400
1401 // Set external caught exception to false.
1402 __ mov(r0, Operand(false));
1403 ExternalReference external_caught(Top::k_external_caught_exception_address);
1404 __ mov(r2, Operand(external_caught));
1405 __ str(r0, MemOperand(r2));
1406
1407 // Set pending exception and TOS to out of memory exception.
1408 Failure* out_of_memory = Failure::OutOfMemoryException();
1409 __ mov(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
1410 __ mov(r2, Operand(ExternalReference(Top::k_pending_exception_address)));
1411 __ str(r0, MemOperand(r2));
1412
1413 // Restore the stack to the address of the ENTRY handler
1414 __ mov(sp, Operand(r3));
1415
1416 // restore parameter- and frame-pointer and pop state.
1417 __ ldm(ia_w, sp, r3.bit() | pp.bit() | fp.bit());
1418 // Before returning we restore the context from the frame pointer if not NULL.
1419 // The frame pointer is NULL in the exception handler of a JS entry frame.
1420 __ cmp(fp, Operand(0));
1421 // Set cp to NULL if fp is NULL.
1422 __ mov(cp, Operand(0), LeaveCC, eq);
1423 // Restore cp otherwise.
1424 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
1425 if (kDebug && FLAG_debug_code) __ mov(lr, Operand(pc));
1426 __ pop(pc);
1427}
1428
1429
1430void CEntryStub::GenerateCore(MacroAssembler* masm,
1431 Label* throw_normal_exception,
1432 Label* throw_out_of_memory_exception,
1433 bool do_gc,
1434 bool do_restore) {
1435 // r0: result parameter for PerformGC, if any
1436 // r4: number of arguments (C callee-saved)
1437 // r5: pointer to builtin function (C callee-saved)
1438
1439 if (do_gc) {
1440 __ Call(FUNCTION_ADDR(Runtime::PerformGC), runtime_entry); // passing r0
1441 }
1442
1443 // call C built-in
1444 __ mov(r0, Operand(r4)); // a0 = argc
1445 __ add(r1, fp, Operand(r4, LSL, kPointerSizeLog2));
1446 __ add(r1, r1, Operand(ExitFrameConstants::kPPDisplacement)); // a1 = argv
1447
1448 // TODO(1242173): To let the GC traverse the return address of the exit
1449 // frames, we need to know where the return address is. Right now,
1450 // we push it on the stack to be able to find it again, but we never
1451 // restore from it in case of changes, which makes it impossible to
1452 // support moving the C entry code stub. This should be fixed, but currently
1453 // this is OK because the CEntryStub gets generated so early in the V8 boot
1454 // sequence that it is not moving ever.
1455 __ add(lr, pc, Operand(4)); // compute return address: (pc + 8) + 4
1456 __ push(lr);
1457#if !defined(__arm__)
1458 // Notify the simulator of the transition to C code.
1459 __ swi(assembler::arm::call_rt_r5);
1460#else /* !defined(__arm__) */
1461 __ mov(pc, Operand(r5));
1462#endif /* !defined(__arm__) */
1463 // result is in r0 or r0:r1 - do not destroy these registers!
1464
1465 // check for failure result
1466 Label failure_returned;
1467 ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
1468 // Lower 2 bits of r2 are 0 iff r0 has failure tag.
1469 __ add(r2, r0, Operand(1));
1470 __ tst(r2, Operand(kFailureTagMask));
1471 __ b(eq, &failure_returned);
1472
1473 // clear top frame
1474 __ mov(r3, Operand(0));
1475 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
1476 __ str(r3, MemOperand(ip));
1477
1478 // Restore the memory copy of the registers by digging them out from
1479 // the stack.
1480 if (do_restore) {
1481 // Ok to clobber r2 and r3.
1482 const int kCallerSavedSize = kNumJSCallerSaved * kPointerSize;
1483 const int kOffset = ExitFrameConstants::kDebugMarkOffset - kCallerSavedSize;
1484 __ add(r3, fp, Operand(kOffset));
1485 __ CopyRegistersFromStackToMemory(r3, r2, kJSCallerSaved);
1486 }
1487
1488 // Exit C frame and return
1489 // r0:r1: result
1490 // sp: stack pointer
1491 // fp: frame pointer
1492 // pp: caller's parameter pointer pp (restored as C callee-saved)
1493
1494 // Restore current context from top and clear it in debug mode.
1495 __ mov(r3, Operand(Top::context_address()));
1496 __ ldr(cp, MemOperand(r3));
1497 __ mov(sp, Operand(fp)); // respect ABI stack constraint
1498 __ ldm(ia, sp, kJSCalleeSaved | pp.bit() | fp.bit() | sp.bit() | pc.bit());
1499
1500 // check if we should retry or throw exception
1501 Label retry;
1502 __ bind(&failure_returned);
1503 ASSERT(Failure::RETRY_AFTER_GC == 0);
1504 __ tst(r0, Operand(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
1505 __ b(eq, &retry);
1506
1507 Label continue_exception;
1508 // If the returned failure is EXCEPTION then promote Top::pending_exception().
1509 __ cmp(r0, Operand(reinterpret_cast<int32_t>(Failure::Exception())));
1510 __ b(ne, &continue_exception);
1511
1512 // Retrieve the pending exception and clear the variable.
1513 __ mov(ip, Operand(Factory::the_hole_value().location()));
1514 __ ldr(r3, MemOperand(ip));
1515 __ mov(ip, Operand(Top::pending_exception_address()));
1516 __ ldr(r0, MemOperand(ip));
1517 __ str(r3, MemOperand(ip));
1518
1519 __ bind(&continue_exception);
1520 // Special handling of out of memory exception.
1521 Failure* out_of_memory = Failure::OutOfMemoryException();
1522 __ cmp(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
1523 __ b(eq, throw_out_of_memory_exception);
1524
1525 // Handle normal exception.
1526 __ jmp(throw_normal_exception);
1527
1528 __ bind(&retry); // pass last failure (r0) as parameter (r0) when retrying
1529}
1530
1531
1532void CEntryStub::GenerateBody(MacroAssembler* masm, bool is_debug_break) {
1533 // Called from JavaScript; parameters are on stack as if calling JS function
1534 // r0: number of arguments
1535 // r1: pointer to builtin function
1536 // fp: frame pointer (restored after C call)
1537 // sp: stack pointer (restored as callee's pp after C call)
1538 // cp: current context (C callee-saved)
1539 // pp: caller's parameter pointer pp (C callee-saved)
1540
1541 // NOTE: Invocations of builtins may return failure objects
1542 // instead of a proper result. The builtin entry handles
1543 // this by performing a garbage collection and retrying the
1544 // builtin once.
1545
1546 // Enter C frame
1547 // Compute parameter pointer before making changes and save it as ip register
1548 // so that it is restored as sp register on exit, thereby popping the args.
1549 // ip = sp + kPointerSize*(args_len+1); // +1 for receiver
1550 __ add(ip, sp, Operand(r0, LSL, kPointerSizeLog2));
1551 __ add(ip, ip, Operand(kPointerSize));
1552
1553 // all JS callee-saved are saved and traversed by GC; push in reverse order:
1554 // JS callee-saved, caller_pp, caller_fp, sp_on_exit (ip==pp), caller_pc
1555 __ stm(db_w, sp, kJSCalleeSaved | pp.bit() | fp.bit() | ip.bit() | lr.bit());
1556 __ mov(fp, Operand(sp)); // setup new frame pointer
1557
1558 // Store the current context in top.
1559 __ mov(ip, Operand(Top::context_address()));
1560 __ str(cp, MemOperand(ip));
1561
1562 // remember top frame
1563 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
1564 __ str(fp, MemOperand(ip));
1565
1566 // Push debug marker.
1567 __ mov(ip, Operand(is_debug_break ? 1 : 0));
1568 __ push(ip);
1569
1570 if (is_debug_break) {
1571 // Save the state of all registers to the stack from the memory location.
1572 // Use sp as base to push.
1573 __ CopyRegistersFromMemoryToStack(sp, kJSCallerSaved);
1574 }
1575
1576 // move number of arguments (argc) into callee-saved register
1577 __ mov(r4, Operand(r0));
1578
1579 // move pointer to builtin function into callee-saved register
1580 __ mov(r5, Operand(r1));
1581
1582 // r0: result parameter for PerformGC, if any (setup below)
1583 // r4: number of arguments
1584 // r5: pointer to builtin function (C callee-saved)
1585
1586 Label entry;
1587 __ bind(&entry);
1588
1589 Label throw_out_of_memory_exception;
1590 Label throw_normal_exception;
1591
1592#ifdef DEBUG
1593 if (FLAG_gc_greedy) {
1594 Failure* failure = Failure::RetryAfterGC(0, NEW_SPACE);
1595 __ mov(r0, Operand(reinterpret_cast<intptr_t>(failure)));
1596 }
1597 GenerateCore(masm,
1598 &throw_normal_exception,
1599 &throw_out_of_memory_exception,
1600 FLAG_gc_greedy,
1601 is_debug_break);
1602#else
1603 GenerateCore(masm,
1604 &throw_normal_exception,
1605 &throw_out_of_memory_exception,
1606 false,
1607 is_debug_break);
1608#endif
1609 GenerateCore(masm,
1610 &throw_normal_exception,
1611 &throw_out_of_memory_exception,
1612 true,
1613 is_debug_break);
1614
1615 __ bind(&throw_out_of_memory_exception);
1616 GenerateThrowOutOfMemory(masm);
1617 // control flow for generated will not return.
1618
1619 __ bind(&throw_normal_exception);
1620 GenerateThrowTOS(masm);
1621}
1622
1623
1624void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
1625 // r0: code entry
1626 // r1: function
1627 // r2: receiver
1628 // r3: argc
1629 // [sp+0]: argv
1630
1631 Label invoke, exit;
1632
1633 // Called from C, so do not pop argc and args on exit (preserve sp)
1634 // No need to save register-passed args
1635 // Save callee-saved registers (incl. cp, pp, and fp), sp, and lr
1636 __ mov(ip, Operand(sp));
1637 __ stm(db_w, sp, kCalleeSaved | ip.bit() | lr.bit());
1638
1639 // Setup frame pointer
1640 __ mov(fp, Operand(sp));
1641
1642 // Add constructor mark.
1643 __ mov(ip, Operand(is_construct ? 1 : 0));
1644 __ push(ip);
1645
1646 // Move arguments into registers expected by Builtins::JSEntryTrampoline
1647 // preserve r0-r3, set r4, r5-r7 may be clobbered
1648
1649 // Get address of argv, see stm above.
1650 __ add(r4, sp, Operand((kNumCalleeSaved + 3)*kPointerSize));
1651 __ ldr(r4, MemOperand(r4)); // argv
1652
1653 // Save copies of the top frame descriptors on the stack.
1654 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
1655 __ ldr(r6, MemOperand(ip));
1656 __ stm(db_w, sp, r6.bit());
1657
1658 // Call a faked try-block that does the invoke.
1659 __ bl(&invoke);
1660
1661 // Caught exception: Store result (exception) in the pending
1662 // exception field in the JSEnv and return a failure sentinel.
1663 __ mov(ip, Operand(Top::pending_exception_address()));
1664 __ str(r0, MemOperand(ip));
1665 __ mov(r0, Operand(Handle<Failure>(Failure::Exception())));
1666 __ b(&exit);
1667
1668 // Invoke: Link this frame into the handler chain.
1669 __ bind(&invoke);
1670 // Must preserve r0-r3, r5-r7 are available.
1671 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
1672 // If an exception not caught by another handler occurs, this handler returns
1673 // control to the code after the bl(&invoke) above, which restores all
1674 // kCalleeSaved registers (including cp, pp and fp) to their saved values
1675 // before returning a failure to C.
1676
1677 // Clear any pending exceptions.
1678 __ mov(ip, Operand(ExternalReference::the_hole_value_location()));
1679 __ ldr(r5, MemOperand(ip));
1680 __ mov(ip, Operand(Top::pending_exception_address()));
1681 __ str(r5, MemOperand(ip));
1682
1683 // Invoke the function by calling through JS entry trampoline builtin.
1684 // Notice that we cannot store a reference to the trampoline code directly in
1685 // this stub, because runtime stubs are not traversed when doing GC.
1686
1687 // Expected registers by Builtins::JSEntryTrampoline
1688 // r0: code entry
1689 // r1: function
1690 // r2: receiver
1691 // r3: argc
1692 // r4: argv
1693 if (is_construct) {
1694 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
1695 __ mov(ip, Operand(construct_entry));
1696 } else {
1697 ExternalReference entry(Builtins::JSEntryTrampoline);
1698 __ mov(ip, Operand(entry));
1699 }
1700 __ ldr(ip, MemOperand(ip)); // deref address
1701
1702 // Branch and link to JSEntryTrampoline
1703 __ mov(lr, Operand(pc));
1704 __ add(pc, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
1705
1706 // Unlink this frame from the handler chain. When reading the
1707 // address of the next handler, there is no need to use the address
1708 // displacement since the current stack pointer (sp) points directly
1709 // to the stack handler.
1710 __ ldr(r3, MemOperand(sp, StackHandlerConstants::kNextOffset));
1711 __ mov(ip, Operand(ExternalReference(Top::k_handler_address)));
1712 __ str(r3, MemOperand(ip));
1713 // No need to restore registers
1714 __ add(sp, sp, Operand(StackHandlerConstants::kSize));
1715
1716 __ bind(&exit); // r0 holds result
1717 // Restore the top frame descriptors from the stack.
1718 __ ldm(ia_w, sp, r3.bit());
1719 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
1720 __ str(r3, MemOperand(ip));
1721
1722 // Remove constructor mark.
1723 __ add(sp, sp, Operand(kPointerSize));
1724
1725 // Restore callee-saved registers, sp, and return.
1726#ifdef DEBUG
1727 if (FLAG_debug_code) __ mov(lr, Operand(pc));
1728#endif
1729 __ ldm(ia, sp, kCalleeSaved | sp.bit() | pc.bit());
1730}
1731
1732
1733class ArgumentsAccessStub: public CodeStub {
1734 public:
1735 explicit ArgumentsAccessStub(bool is_length) : is_length_(is_length) { }
1736
1737 private:
1738 bool is_length_;
1739
1740 Major MajorKey() { return ArgumentsAccess; }
1741 int MinorKey() { return is_length_ ? 1 : 0; }
1742 void Generate(MacroAssembler* masm);
1743
1744 const char* GetName() { return "ArgumentsAccessStub"; }
1745
1746#ifdef DEBUG
1747 void Print() {
1748 PrintF("ArgumentsAccessStub (is_length %s)\n",
1749 is_length_ ? "true" : "false");
1750 }
1751#endif
1752};
1753
1754
1755void ArgumentsAccessStub::Generate(MacroAssembler* masm) {
1756 if (is_length_) {
1757 __ ldr(r0, MemOperand(fp, JavaScriptFrameConstants::kArgsLengthOffset));
1758 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
1759 __ Ret();
1760 } else {
1761 // Check that the key is a smi.
1762 Label slow;
1763 __ tst(r0, Operand(kSmiTagMask));
1764 __ b(ne, &slow);
1765
1766 // Get the actual number of arguments passed and do bounds
1767 // check. Use unsigned comparison to get negative check for free.
1768 __ ldr(r1, MemOperand(fp, JavaScriptFrameConstants::kArgsLengthOffset));
1769 __ cmp(r0, Operand(r1, LSL, kSmiTagSize));
1770 __ b(hs, &slow);
1771
1772 // Load the argument directly from the stack and return.
1773 __ sub(r1, pp, Operand(r0, LSL, kPointerSizeLog2 - kSmiTagSize));
1774 __ ldr(r0, MemOperand(r1, JavaScriptFrameConstants::kParam0Offset));
1775 __ Ret();
1776
1777 // Slow-case: Handle non-smi or out-of-bounds access to arguments
1778 // by calling the runtime system.
1779 __ bind(&slow);
1780 __ push(r0);
1781 __ mov(r0, Operand(0)); // not counting receiver
1782 __ JumpToBuiltin(ExternalReference(Runtime::kGetArgumentsProperty));
1783 }
1784}
1785
1786
1787#undef __
1788#define __ masm_->
1789
1790
1791void ArmCodeGenerator::AccessReferenceProperty(
1792 Expression* key,
1793 CodeGenState::AccessType access) {
1794 Reference::Type type = ref()->type();
1795 ASSERT(type != Reference::ILLEGAL);
1796
1797 // TODO(1241834): Make sure that this is sufficient. If there is a chance
1798 // that reference errors can be thrown below, we must distinguish
1799 // between the 2 kinds of loads (typeof expression loads must not
1800 // throw a reference errror).
1801 bool is_load = (access == CodeGenState::LOAD ||
1802 access == CodeGenState::LOAD_TYPEOF_EXPR);
1803
1804 if (type == Reference::NAMED) {
1805 // Compute the name of the property.
1806 Literal* literal = key->AsLiteral();
1807 Handle<String> name(String::cast(*literal->handle()));
1808
1809 // Loading adds a value to the stack; push the TOS to prepare.
1810 if (is_load) __ push(r0);
1811
1812 // Setup the name register.
1813 __ mov(r2, Operand(name));
1814
1815 // Call the appropriate IC code.
1816 if (is_load) {
1817 Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
1818 Variable* var = ref()->expression()->AsVariableProxy()->AsVariable();
1819 if (var != NULL) {
1820 ASSERT(var->is_global());
1821 __ Call(ic, code_target_context);
1822 } else {
1823 __ Call(ic, code_target);
1824 }
1825 } else {
1826 Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Initialize));
1827 __ Call(ic, code_target);
1828 }
1829 return;
1830 }
1831
1832 // Access keyed property.
1833 ASSERT(type == Reference::KEYED);
1834
1835 if (is_load) {
1836 __ push(r0); // empty tos
1837 // TODO(1224671): Implement inline caching for keyed loads as on ia32.
1838 GetPropertyStub stub;
1839 __ CallStub(&stub);
1840 } else {
1841 SetPropertyStub stub;
1842 __ CallStub(&stub);
1843 }
1844}
1845
1846
1847void ArmCodeGenerator::GenericOperation(Token::Value op) {
1848 // Stub is entered with a call: 'return address' is in lr.
1849 switch (op) {
1850 case Token::ADD: // fall through.
1851 case Token::SUB: // fall through.
1852 case Token::MUL: {
1853 GenericOpStub stub(op);
1854 __ CallStub(&stub);
1855 break;
1856 }
1857
1858 case Token::DIV: {
1859 __ push(r0);
1860 __ mov(r0, Operand(1)); // set number of arguments
1861 __ InvokeBuiltin("DIV", 1, CALL_JS);
1862 break;
1863 }
1864
1865 case Token::MOD: {
1866 __ push(r0);
1867 __ mov(r0, Operand(1)); // set number of arguments
1868 __ InvokeBuiltin("MOD", 1, CALL_JS);
1869 break;
1870 }
1871
1872 case Token::BIT_OR:
1873 case Token::BIT_AND:
1874 case Token::BIT_XOR: {
1875 Label slow, exit;
1876 __ pop(r1); // get x
1877 // tag check
1878 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
1879 ASSERT(kSmiTag == 0); // adjust code below
1880 __ tst(r2, Operand(kSmiTagMask));
1881 __ b(ne, &slow);
1882 switch (op) {
1883 case Token::BIT_OR: __ orr(r0, r0, Operand(r1)); break;
1884 case Token::BIT_AND: __ and_(r0, r0, Operand(r1)); break;
1885 case Token::BIT_XOR: __ eor(r0, r0, Operand(r1)); break;
1886 default: UNREACHABLE();
1887 }
1888 __ b(&exit);
1889 __ bind(&slow);
1890 __ push(r1); // restore stack
1891 __ push(r0);
1892 __ mov(r0, Operand(1)); // 1 argument (not counting receiver).
1893 switch (op) {
1894 case Token::BIT_OR: __ InvokeBuiltin("BIT_OR", 1, CALL_JS); break;
1895 case Token::BIT_AND: __ InvokeBuiltin("BIT_AND", 1, CALL_JS); break;
1896 case Token::BIT_XOR: __ InvokeBuiltin("BIT_XOR", 1, CALL_JS); break;
1897 default: UNREACHABLE();
1898 }
1899 __ bind(&exit);
1900 break;
1901 }
1902
1903 case Token::SHL:
1904 case Token::SHR:
1905 case Token::SAR: {
1906 Label slow, exit;
1907 __ mov(r1, Operand(r0)); // get y
1908 __ pop(r0); // get x
1909 // tag check
1910 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
1911 ASSERT(kSmiTag == 0); // adjust code below
1912 __ tst(r2, Operand(kSmiTagMask));
1913 __ b(ne, &slow);
1914 // get copies of operands
1915 __ mov(r3, Operand(r0));
1916 __ mov(r2, Operand(r1));
1917 // remove tags from operands (but keep sign)
1918 __ mov(r3, Operand(r3, ASR, kSmiTagSize));
1919 __ mov(r2, Operand(r2, ASR, kSmiTagSize));
1920 // use only the 5 least significant bits of the shift count
1921 __ and_(r2, r2, Operand(0x1f));
1922 // perform operation
1923 switch (op) {
1924 case Token::SAR:
1925 __ mov(r3, Operand(r3, ASR, r2));
1926 // no checks of result necessary
1927 break;
1928
1929 case Token::SHR:
1930 __ mov(r3, Operand(r3, LSR, r2));
1931 // check that the *unsigned* result fits in a smi
1932 // neither of the two high-order bits can be set:
1933 // - 0x80000000: high bit would be lost when smi tagging
1934 // - 0x40000000: this number would convert to negative when
1935 // smi tagging these two cases can only happen with shifts
1936 // by 0 or 1 when handed a valid smi
1937 __ and_(r2, r3, Operand(0xc0000000), SetCC);
1938 __ b(ne, &slow);
1939 break;
1940
1941 case Token::SHL:
1942 __ mov(r3, Operand(r3, LSL, r2));
1943 // check that the *signed* result fits in a smi
1944 __ add(r2, r3, Operand(0x40000000), SetCC);
1945 __ b(mi, &slow);
1946 break;
1947
1948 default: UNREACHABLE();
1949 }
1950 // tag result and store it in TOS (r0)
1951 ASSERT(kSmiTag == 0); // adjust code below
1952 __ mov(r0, Operand(r3, LSL, kSmiTagSize));
1953 __ b(&exit);
1954 // slow case
1955 __ bind(&slow);
1956 __ push(r0); // restore stack
1957 __ mov(r0, Operand(r1));
1958 __ Push(Operand(1)); // 1 argument (not counting receiver).
1959 switch (op) {
1960 case Token::SAR: __ InvokeBuiltin("SAR", 1, CALL_JS); break;
1961 case Token::SHR: __ InvokeBuiltin("SHR", 1, CALL_JS); break;
1962 case Token::SHL: __ InvokeBuiltin("SHL", 1, CALL_JS); break;
1963 default: UNREACHABLE();
1964 }
1965 __ bind(&exit);
1966 break;
1967 }
1968
1969 case Token::COMMA:
1970 // simply discard left value
1971 __ add(sp, sp, Operand(kPointerSize));
1972 break;
1973
1974 default:
1975 // Other cases should have been handled before this point.
1976 UNREACHABLE();
1977 break;
1978 }
1979}
1980
1981
1982
1983
1984void ArmCodeGenerator::SmiOperation(Token::Value op,
1985 Handle<Object> value,
1986 bool reversed) {
1987 // NOTE: This is an attempt to inline (a bit) more of the code for
1988 // some possible smi operations (like + and -) when (at least) one
1989 // of the operands is a literal smi. With this optimization, the
1990 // performance of the system is increased by ~15%, and the generated
1991 // code size is increased by ~1% (measured on a combination of
1992 // different benchmarks).
1993
1994 ASSERT(value->IsSmi());
1995
1996 Label exit;
1997
1998 switch (op) {
1999 case Token::ADD: {
2000 Label slow;
2001
2002 __ mov(r1, Operand(value));
2003 __ add(r0, r0, Operand(r1), SetCC);
2004 __ b(vs, &slow);
2005 __ tst(r0, Operand(kSmiTagMask));
2006 __ b(eq, &exit);
2007 __ bind(&slow);
2008
2009 SmiOpStub stub(Token::ADD, reversed);
2010 __ CallStub(&stub);
2011 break;
2012 }
2013
2014 case Token::SUB: {
2015 Label slow;
2016
2017 __ mov(r1, Operand(value));
2018 if (!reversed) {
2019 __ sub(r2, r0, Operand(r1), SetCC);
2020 } else {
2021 __ rsb(r2, r0, Operand(r1), SetCC);
2022 }
2023 __ b(vs, &slow);
2024 __ tst(r2, Operand(kSmiTagMask));
2025 __ mov(r0, Operand(r2), LeaveCC, eq); // conditionally set r0 to result
2026 __ b(eq, &exit);
2027
2028 __ bind(&slow);
2029
2030 SmiOpStub stub(Token::SUB, reversed);
2031 __ CallStub(&stub);
2032 break;
2033 }
2034
2035 default:
2036 if (!reversed) {
2037 __ Push(Operand(value));
2038 } else {
2039 __ mov(ip, Operand(value));
2040 __ push(ip);
2041 }
2042 GenericOperation(op);
2043 break;
2044 }
2045
2046 __ bind(&exit);
2047}
2048
2049
2050void ArmCodeGenerator::Comparison(Condition cc, bool strict) {
2051 // Strict only makes sense for equality comparisons.
2052 ASSERT(!strict || cc == eq);
2053
2054 Label exit, smi;
2055 __ pop(r1);
2056 __ orr(r2, r0, Operand(r1));
2057 __ tst(r2, Operand(kSmiTagMask));
2058 __ b(eq, &smi);
2059
2060 // Perform non-smi comparison by runtime call.
2061 __ push(r1);
2062
2063 // Figure out which native to call and setup the arguments.
2064 const char* native;
2065 int argc;
2066 if (cc == eq) {
2067 native = strict ? "STRICT_EQUALS" : "EQUALS";
2068 argc = 1;
2069 } else {
2070 native = "COMPARE";
2071 int ncr; // NaN compare result
2072 if (cc == lt || cc == le) {
2073 ncr = GREATER;
2074 } else {
2075 ASSERT(cc == gt || cc == ge); // remaining cases
2076 ncr = LESS;
2077 }
2078 __ Push(Operand(Smi::FromInt(ncr)));
2079 argc = 2;
2080 }
2081
2082 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
2083 // tagged as a small integer.
2084 __ Push(Operand(argc));
2085 __ InvokeBuiltin(native, argc, CALL_JS);
2086 __ cmp(r0, Operand(0));
2087 __ b(&exit);
2088
2089 // test smi equality by pointer comparison.
2090 __ bind(&smi);
2091 __ cmp(r1, Operand(r0));
2092
2093 __ bind(&exit);
2094 __ pop(r0); // be careful not to destroy the cc register
2095 cc_reg_ = cc;
2096}
2097
2098
2099// Call the function just below TOS on the stack with the given
2100// arguments. The receiver is the TOS.
2101void ArmCodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
2102 int position) {
2103 Label fast, slow, exit;
2104
2105 // Push the arguments ("left-to-right") on the stack.
2106 for (int i = 0; i < args->length(); i++) Load(args->at(i));
2107
2108 // Push the number of arguments.
2109 __ Push(Operand(args->length()));
2110
2111 // Get the function to call from the stack.
2112 // +1 ~ receiver.
2113 __ ldr(r1, MemOperand(sp, (args->length() + 1) * kPointerSize));
2114
2115 // Check that the function really is a JavaScript function.
2116 __ tst(r1, Operand(kSmiTagMask));
2117 __ b(eq, &slow);
2118 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset)); // get the map
2119 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
2120 __ cmp(r2, Operand(JS_FUNCTION_TYPE));
2121 __ b(eq, &fast);
2122
2123 __ RecordPosition(position);
2124
2125 // Slow-case: Non-function called.
2126 __ bind(&slow);
2127 __ InvokeBuiltin("CALL_NON_FUNCTION", 0, CALL_JS);
2128 __ b(&exit);
2129
2130 // Fast-case: Get the code from the function, call the first
2131 // instruction in it, and pop function.
2132 __ bind(&fast);
2133 __ ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
2134 __ ldr(r1, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
2135 __ ldr(r1, MemOperand(r1, SharedFunctionInfo::kCodeOffset - kHeapObjectTag));
2136 __ add(r1, r1, Operand(Code::kHeaderSize - kHeapObjectTag));
2137 __ Call(r1);
2138
2139 // Restore context and pop function from the stack.
2140 __ bind(&exit);
2141 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
2142 __ add(sp, sp, Operand(kPointerSize)); // discard
2143}
2144
2145
2146void ArmCodeGenerator::Branch(bool if_true, Label* L) {
2147 ASSERT(has_cc());
2148 Condition cc = if_true ? cc_reg_ : NegateCondition(cc_reg_);
2149 __ b(cc, L);
2150 cc_reg_ = al;
2151}
2152
2153
2154void ArmCodeGenerator::CheckStack() {
2155 if (FLAG_check_stack) {
2156 Comment cmnt(masm_, "[ check stack");
2157 StackCheckStub stub;
2158 __ CallStub(&stub);
2159 }
2160}
2161
2162
2163void ArmCodeGenerator::VisitBlock(Block* node) {
2164 Comment cmnt(masm_, "[ Block");
2165 if (FLAG_debug_info) RecordStatementPosition(node);
2166 node->set_break_stack_height(break_stack_height_);
2167 VisitStatements(node->statements());
2168 __ bind(node->break_target());
2169}
2170
2171
2172void ArmCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
2173 __ Push(Operand(pairs));
2174 __ Push(Operand(cp));
2175 __ Push(Operand(Smi::FromInt(is_eval() ? 1 : 0)));
2176 __ CallRuntime(Runtime::kDeclareGlobals, 3);
2177
2178 // Get rid of return value.
2179 __ pop(r0);
2180}
2181
2182
2183void ArmCodeGenerator::VisitDeclaration(Declaration* node) {
2184 Comment cmnt(masm_, "[ Declaration");
2185 Variable* var = node->proxy()->var();
2186 ASSERT(var != NULL); // must have been resolved
2187 Slot* slot = var->slot();
2188
2189 // If it was not possible to allocate the variable at compile time,
2190 // we need to "declare" it at runtime to make sure it actually
2191 // exists in the local context.
2192 if (slot != NULL && slot->type() == Slot::LOOKUP) {
2193 // Variables with a "LOOKUP" slot were introduced as non-locals
2194 // during variable resolution and must have mode DYNAMIC.
2195 ASSERT(var->mode() == Variable::DYNAMIC);
2196 // For now, just do a runtime call.
2197 __ Push(Operand(cp));
2198 __ Push(Operand(var->name()));
2199 // Declaration nodes are always declared in only two modes.
2200 ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
2201 PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
2202 __ Push(Operand(Smi::FromInt(attr)));
2203 // Push initial value, if any.
2204 // Note: For variables we must not push an initial value (such as
2205 // 'undefined') because we may have a (legal) redeclaration and we
2206 // must not destroy the current value.
2207 if (node->mode() == Variable::CONST) {
2208 __ Push(Operand(Factory::the_hole_value()));
2209 } else if (node->fun() != NULL) {
2210 Load(node->fun());
2211 } else {
2212 __ Push(Operand(0)); // no initial value!
2213 }
2214 __ CallRuntime(Runtime::kDeclareContextSlot, 5);
2215 // DeclareContextSlot pops the assigned value by accepting an
2216 // extra argument and returning the TOS; no need to explicitly pop
2217 // here.
2218 return;
2219 }
2220
2221 ASSERT(!var->is_global());
2222
2223 // If we have a function or a constant, we need to initialize the variable.
2224 Expression* val = NULL;
2225 if (node->mode() == Variable::CONST) {
2226 val = new Literal(Factory::the_hole_value());
2227 } else {
2228 val = node->fun(); // NULL if we don't have a function
2229 }
2230
2231 if (val != NULL) {
2232 // Set initial value.
2233 Reference target(this, node->proxy());
2234 Load(val);
2235 SetValue(&target);
2236 // Get rid of the assigned value (declarations are statements).
2237 __ pop(r0); // Pop(no_reg);
2238 }
2239}
2240
2241
2242void ArmCodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
2243 Comment cmnt(masm_, "[ ExpressionStatement");
2244 if (FLAG_debug_info) RecordStatementPosition(node);
2245 Expression* expression = node->expression();
2246 expression->MarkAsStatement();
2247 Load(expression);
2248 __ pop(r0); // __ Pop(no_reg)
2249}
2250
2251
2252void ArmCodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
2253 Comment cmnt(masm_, "// EmptyStatement");
2254 // nothing to do
2255}
2256
2257
2258void ArmCodeGenerator::VisitIfStatement(IfStatement* node) {
2259 Comment cmnt(masm_, "[ IfStatement");
2260 // Generate different code depending on which
2261 // parts of the if statement are present or not.
2262 bool has_then_stm = node->HasThenStatement();
2263 bool has_else_stm = node->HasElseStatement();
2264
2265 if (FLAG_debug_info) RecordStatementPosition(node);
2266
2267 Label exit;
2268 if (has_then_stm && has_else_stm) {
2269 Label then;
2270 Label else_;
2271 // if (cond)
2272 LoadCondition(node->condition(), CodeGenState::LOAD, &then, &else_, true);
2273 Branch(false, &else_);
2274 // then
2275 __ bind(&then);
2276 Visit(node->then_statement());
2277 __ b(&exit);
2278 // else
2279 __ bind(&else_);
2280 Visit(node->else_statement());
2281
2282 } else if (has_then_stm) {
2283 ASSERT(!has_else_stm);
2284 Label then;
2285 // if (cond)
2286 LoadCondition(node->condition(), CodeGenState::LOAD, &then, &exit, true);
2287 Branch(false, &exit);
2288 // then
2289 __ bind(&then);
2290 Visit(node->then_statement());
2291
2292 } else if (has_else_stm) {
2293 ASSERT(!has_then_stm);
2294 Label else_;
2295 // if (!cond)
2296 LoadCondition(node->condition(), CodeGenState::LOAD, &exit, &else_, true);
2297 Branch(true, &exit);
2298 // else
2299 __ bind(&else_);
2300 Visit(node->else_statement());
2301
2302 } else {
2303 ASSERT(!has_then_stm && !has_else_stm);
2304 // if (cond)
2305 LoadCondition(node->condition(), CodeGenState::LOAD, &exit, &exit, false);
2306 if (has_cc()) {
2307 cc_reg_ = al;
2308 } else {
2309 __ pop(r0); // __ Pop(no_reg)
2310 }
2311 }
2312
2313 // end
2314 __ bind(&exit);
2315}
2316
2317
2318void ArmCodeGenerator::CleanStack(int num_bytes) {
2319 ASSERT(num_bytes >= 0);
2320 if (num_bytes > 0) {
2321 __ add(sp, sp, Operand(num_bytes - kPointerSize));
2322 __ pop(r0);
2323 }
2324}
2325
2326
2327void ArmCodeGenerator::VisitContinueStatement(ContinueStatement* node) {
2328 Comment cmnt(masm_, "[ ContinueStatement");
2329 if (FLAG_debug_info) RecordStatementPosition(node);
2330 CleanStack(break_stack_height_ - node->target()->break_stack_height());
2331 __ b(node->target()->continue_target());
2332}
2333
2334
2335void ArmCodeGenerator::VisitBreakStatement(BreakStatement* node) {
2336 Comment cmnt(masm_, "[ BreakStatement");
2337 if (FLAG_debug_info) RecordStatementPosition(node);
2338 CleanStack(break_stack_height_ - node->target()->break_stack_height());
2339 __ b(node->target()->break_target());
2340}
2341
2342
2343void ArmCodeGenerator::VisitReturnStatement(ReturnStatement* node) {
2344 Comment cmnt(masm_, "[ ReturnStatement");
2345 if (FLAG_debug_info) RecordStatementPosition(node);
2346 Load(node->expression());
2347 __ b(&function_return_);
2348}
2349
2350
2351void ArmCodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
2352 Comment cmnt(masm_, "[ WithEnterStatement");
2353 if (FLAG_debug_info) RecordStatementPosition(node);
2354 Load(node->expression());
2355 __ CallRuntime(Runtime::kPushContext, 2);
2356 // Update context local.
2357 __ str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
2358}
2359
2360
2361void ArmCodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
2362 Comment cmnt(masm_, "[ WithExitStatement");
2363 // Pop context.
2364 __ ldr(cp, ContextOperand(cp, Context::PREVIOUS_INDEX));
2365 // Update context local.
2366 __ str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
2367}
2368
2369
2370void ArmCodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
2371 Comment cmnt(masm_, "[ SwitchStatement");
2372 if (FLAG_debug_info) RecordStatementPosition(node);
2373 node->set_break_stack_height(break_stack_height_);
2374
2375 Load(node->tag());
2376
2377 Label next, fall_through, default_case;
2378 ZoneList<CaseClause*>* cases = node->cases();
2379 int length = cases->length();
2380
2381 for (int i = 0; i < length; i++) {
2382 CaseClause* clause = cases->at(i);
2383
2384 Comment cmnt(masm_, "[ case clause");
2385
2386 if (clause->is_default()) {
2387 // Bind the default case label, so we can branch to it when we
2388 // have compared against all other cases.
2389 ASSERT(default_case.is_unused()); // at most one default clause
2390
2391 // If the default case is the first (but not only) case, we have
2392 // to jump past it for now. Once we're done with the remaining
2393 // clauses, we'll branch back here. If it isn't the first case,
2394 // we jump past it by avoiding to chain it into the next chain.
2395 if (length > 1) {
2396 if (i == 0) __ b(&next);
2397 __ bind(&default_case);
2398 }
2399
2400 } else {
2401 __ bind(&next);
2402 next.Unuse();
2403 __ push(r0); // duplicate TOS
2404 Load(clause->label());
2405 Comparison(eq, true);
2406 Branch(false, &next);
2407 __ pop(r0); // __ Pop(no_reg)
2408 }
2409
2410 // Generate code for the body.
2411 __ bind(&fall_through);
2412 fall_through.Unuse();
2413 VisitStatements(clause->statements());
2414 __ b(&fall_through);
2415 }
2416
2417 __ bind(&next);
2418 __ pop(r0); // __ Pop(no_reg)
2419 if (default_case.is_bound()) __ b(&default_case);
2420
2421 __ bind(&fall_through);
2422 __ bind(node->break_target());
2423}
2424
2425
2426void ArmCodeGenerator::VisitLoopStatement(LoopStatement* node) {
2427 Comment cmnt(masm_, "[ LoopStatement");
2428 if (FLAG_debug_info) RecordStatementPosition(node);
2429 node->set_break_stack_height(break_stack_height_);
2430
2431 // simple condition analysis
2432 enum { ALWAYS_TRUE, ALWAYS_FALSE, DONT_KNOW } info = DONT_KNOW;
2433 if (node->cond() == NULL) {
2434 ASSERT(node->type() == LoopStatement::FOR_LOOP);
2435 info = ALWAYS_TRUE;
2436 } else {
2437 Literal* lit = node->cond()->AsLiteral();
2438 if (lit != NULL) {
2439 if (lit->IsTrue()) {
2440 info = ALWAYS_TRUE;
2441 } else if (lit->IsFalse()) {
2442 info = ALWAYS_FALSE;
2443 }
2444 }
2445 }
2446
2447 Label loop, entry;
2448
2449 // init
2450 if (node->init() != NULL) {
2451 ASSERT(node->type() == LoopStatement::FOR_LOOP);
2452 Visit(node->init());
2453 }
2454 if (node->type() != LoopStatement::DO_LOOP && info != ALWAYS_TRUE) {
2455 __ b(&entry);
2456 }
2457
2458 // body
2459 __ bind(&loop);
2460 Visit(node->body());
2461
2462 // next
2463 __ bind(node->continue_target());
2464 if (node->next() != NULL) {
2465 // Record source position of the statement as this code which is after the
2466 // code for the body actually belongs to the loop statement and not the
2467 // body.
2468 if (FLAG_debug_info) __ RecordPosition(node->statement_pos());
2469 ASSERT(node->type() == LoopStatement::FOR_LOOP);
2470 Visit(node->next());
2471 }
2472
2473 // cond
2474 __ bind(&entry);
2475 switch (info) {
2476 case ALWAYS_TRUE:
2477 CheckStack(); // TODO(1222600): ignore if body contains calls.
2478 __ b(&loop);
2479 break;
2480 case ALWAYS_FALSE:
2481 break;
2482 case DONT_KNOW:
2483 CheckStack(); // TODO(1222600): ignore if body contains calls.
2484 LoadCondition(node->cond(),
2485 CodeGenState::LOAD,
2486 &loop,
2487 node->break_target(),
2488 true);
2489 Branch(true, &loop);
2490 break;
2491 }
2492
2493 // exit
2494 __ bind(node->break_target());
2495}
2496
2497
2498void ArmCodeGenerator::VisitForInStatement(ForInStatement* node) {
2499 Comment cmnt(masm_, "[ ForInStatement");
2500 if (FLAG_debug_info) RecordStatementPosition(node);
2501
2502 // We keep stuff on the stack while the body is executing.
2503 // Record it, so that a break/continue crossing this statement
2504 // can restore the stack.
2505 const int kForInStackSize = 5 * kPointerSize;
2506 break_stack_height_ += kForInStackSize;
2507 node->set_break_stack_height(break_stack_height_);
2508
2509 Label loop, next, entry, cleanup, exit, primitive, jsobject;
2510 Label filter_key, end_del_check, fixed_array, non_string;
2511
2512 // Get the object to enumerate over (converted to JSObject).
2513 Load(node->enumerable());
2514
2515 // Both SpiderMonkey and kjs ignore null and undefined in contrast
2516 // to the specification. 12.6.4 mandates a call to ToObject.
2517 __ cmp(r0, Operand(Factory::undefined_value()));
2518 __ b(eq, &exit);
2519 __ cmp(r0, Operand(Factory::null_value()));
2520 __ b(eq, &exit);
2521
2522 // Stack layout in body:
2523 // [iteration counter (Smi)]
2524 // [length of array]
2525 // [FixedArray]
2526 // [Map or 0]
2527 // [Object]
2528
2529 // Check if enumerable is already a JSObject
2530 __ tst(r0, Operand(kSmiTagMask));
2531 __ b(eq, &primitive);
2532 __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
2533 __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
2534 __ cmp(r1, Operand(JS_OBJECT_TYPE));
2535 __ b(hs, &jsobject);
2536
2537 __ bind(&primitive);
2538 __ Push(Operand(0));
2539 __ InvokeBuiltin("TO_OBJECT", 0, CALL_JS);
2540
2541
2542 __ bind(&jsobject);
2543
2544 // Get the set of properties (as a FixedArray or Map).
2545 __ push(r0); // duplicate the object being enumerated
2546 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
2547
2548 // If we got a Map, we can do a fast modification check.
2549 // Otherwise, we got a FixedArray, and we have to do a slow check.
2550 __ mov(r2, Operand(r0));
2551 __ ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
2552 __ cmp(r1, Operand(Factory::meta_map()));
2553 __ b(ne, &fixed_array);
2554
2555 // Get enum cache
2556 __ mov(r1, Operand(r0));
2557 __ ldr(r1, FieldMemOperand(r1, Map::kInstanceDescriptorsOffset));
2558 __ ldr(r1, FieldMemOperand(r1, DescriptorArray::kEnumerationIndexOffset));
2559 __ ldr(r2,
2560 FieldMemOperand(r1, DescriptorArray::kEnumCacheBridgeCacheOffset));
2561
2562 __ Push(Operand(r2));
2563 __ Push(FieldMemOperand(r2, FixedArray::kLengthOffset));
2564 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
2565 __ Push(Operand(Smi::FromInt(0)));
2566 __ b(&entry);
2567
2568
2569 __ bind(&fixed_array);
2570
2571 __ mov(r1, Operand(Smi::FromInt(0)));
2572 __ push(r1); // insert 0 in place of Map
2573
2574 // Push the length of the array and the initial index onto the stack.
2575 __ Push(FieldMemOperand(r0, FixedArray::kLengthOffset));
2576 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
2577 __ Push(Operand(Smi::FromInt(0)));
2578 __ b(&entry);
2579
2580 // Body.
2581 __ bind(&loop);
2582 Visit(node->body());
2583
2584 // Next.
2585 __ bind(node->continue_target());
2586 __ bind(&next);
2587 __ add(r0, r0, Operand(Smi::FromInt(1)));
2588
2589 // Condition.
2590 __ bind(&entry);
2591
2592 __ ldr(ip, MemOperand(sp, 0));
2593 __ cmp(r0, Operand(ip));
2594 __ b(hs, &cleanup);
2595
2596 // Get the i'th entry of the array.
2597 __ ldr(r2, MemOperand(sp, kPointerSize));
2598 __ add(r2, r2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
2599 __ ldr(r3, MemOperand(r2, r0, LSL, kPointerSizeLog2 - kSmiTagSize));
2600
2601 // Get Map or 0.
2602 __ ldr(r2, MemOperand(sp, 2 * kPointerSize));
2603 // Check if this (still) matches the map of the enumerable.
2604 // If not, we have to filter the key.
2605 __ ldr(r1, MemOperand(sp, 3 * kPointerSize));
2606 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
2607 __ cmp(r1, Operand(r2));
2608 __ b(eq, &end_del_check);
2609
2610 // Convert the entry to a string (or null if it isn't a property anymore).
2611 __ Push(MemOperand(sp, 4 * kPointerSize)); // push enumerable
2612 __ Push(Operand(r3)); // push entry
2613 __ Push(Operand(1));
2614 __ InvokeBuiltin("FILTER_KEY", 1, CALL_JS);
2615 __ mov(r3, Operand(r0));
2616 __ pop(r0);
2617
2618 // If the property has been removed while iterating, we just skip it.
2619 __ cmp(r3, Operand(Factory::null_value()));
2620 __ b(eq, &next);
2621
2622
2623 __ bind(&end_del_check);
2624
2625 // Store the entry in the 'each' expression and take another spin in the loop.
2626 __ Push(Operand(r3));
2627 { Reference each(this, node->each());
2628 if (!each.is_illegal()) {
2629 if (each.size() > 0) __ Push(MemOperand(sp, kPointerSize * each.size()));
2630 SetValue(&each);
2631 if (each.size() > 0) __ pop(r0);
2632 }
2633 }
2634 __ pop(r0);
2635 CheckStack(); // TODO(1222600): ignore if body contains calls.
2636 __ jmp(&loop);
2637
2638 // Cleanup.
2639 __ bind(&cleanup);
2640 __ bind(node->break_target());
2641 __ add(sp, sp, Operand(4 * kPointerSize));
2642
2643 // Exit.
2644 __ bind(&exit);
2645 __ pop(r0);
2646
2647 break_stack_height_ -= kForInStackSize;
2648}
2649
2650
2651void ArmCodeGenerator::VisitTryCatch(TryCatch* node) {
2652 Comment cmnt(masm_, "[ TryCatch");
2653
2654 Label try_block, exit;
2655
2656 __ push(r0);
2657 __ bl(&try_block);
2658
2659
2660 // --- Catch block ---
2661
2662 // Store the caught exception in the catch variable.
2663 { Reference ref(this, node->catch_var());
2664 // Load the exception to the top of the stack.
2665 __ Push(MemOperand(sp, ref.size() * kPointerSize));
2666 SetValue(&ref);
2667 }
2668
2669 // Remove the exception from the stack.
2670 __ add(sp, sp, Operand(kPointerSize));
2671
2672 // Restore TOS register caching.
2673 __ pop(r0);
2674
2675 VisitStatements(node->catch_block()->statements());
2676 __ b(&exit);
2677
2678
2679 // --- Try block ---
2680 __ bind(&try_block);
2681
2682 __ PushTryHandler(IN_JAVASCRIPT, TRY_CATCH_HANDLER);
2683
2684 // Introduce shadow labels for all escapes from the try block,
2685 // including returns. We should probably try to unify the escaping
2686 // labels and the return label.
2687 int nof_escapes = node->escaping_labels()->length();
2688 List<LabelShadow*> shadows(1 + nof_escapes);
2689 shadows.Add(new LabelShadow(&function_return_));
2690 for (int i = 0; i < nof_escapes; i++) {
2691 shadows.Add(new LabelShadow(node->escaping_labels()->at(i)));
2692 }
2693
2694 // Generate code for the statements in the try block.
2695 VisitStatements(node->try_block()->statements());
2696
2697 // Stop the introduced shadowing and count the number of required unlinks.
2698 int nof_unlinks = 0;
2699 for (int i = 0; i <= nof_escapes; i++) {
2700 shadows[i]->StopShadowing();
2701 if (shadows[i]->is_linked()) nof_unlinks++;
2702 }
2703
2704 // Unlink from try chain.
2705 // TOS contains code slot
2706 const int kNextOffset = StackHandlerConstants::kNextOffset +
2707 StackHandlerConstants::kAddressDisplacement;
2708 __ ldr(r1, MemOperand(sp, kNextOffset)); // read next_sp
2709 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
2710 __ str(r1, MemOperand(r3));
2711 ASSERT(StackHandlerConstants::kCodeOffset == 0); // first field is code
2712 __ add(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
2713 // Code slot popped.
2714 __ pop(r0); // restore TOS
2715 if (nof_unlinks > 0) __ b(&exit);
2716
2717 // Generate unlink code for all used shadow labels.
2718 for (int i = 0; i <= nof_escapes; i++) {
2719 if (shadows[i]->is_linked()) {
2720 // Unlink from try chain; be careful not to destroy the TOS.
2721 __ bind(shadows[i]);
2722
2723 bool is_return = (shadows[i]->shadowed() == &function_return_);
2724 if (!is_return) {
2725 // Break/continue case. TOS is the code slot of the handler.
2726 __ push(r0); // flush TOS
2727 }
2728
2729 // Reload sp from the top handler, because some statements that we
2730 // break from (eg, for...in) may have left stuff on the stack.
2731 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
2732 __ ldr(sp, MemOperand(r3));
2733
2734 __ ldr(r1, MemOperand(sp, kNextOffset));
2735 __ str(r1, MemOperand(r3));
2736 ASSERT(StackHandlerConstants::kCodeOffset == 0); // first field is code
2737 __ add(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
2738 // Code slot popped.
2739
2740 if (!is_return) {
2741 __ pop(r0); // restore TOS
2742 }
2743
2744 __ b(shadows[i]->shadowed());
2745 }
2746 }
2747
2748 __ bind(&exit);
2749}
2750
2751
2752void ArmCodeGenerator::VisitTryFinally(TryFinally* node) {
2753 Comment cmnt(masm_, "[ TryFinally");
2754
2755 // State: Used to keep track of reason for entering the finally
2756 // block. Should probably be extended to hold information for
2757 // break/continue from within the try block.
2758 enum { FALLING, THROWING, JUMPING };
2759
2760 Label exit, unlink, try_block, finally_block;
2761
2762 __ push(r0);
2763 __ bl(&try_block);
2764
2765 // In case of thrown exceptions, this is where we continue.
2766 __ mov(r2, Operand(Smi::FromInt(THROWING)));
2767 __ b(&finally_block);
2768
2769
2770 // --- Try block ---
2771 __ bind(&try_block);
2772
2773 __ PushTryHandler(IN_JAVASCRIPT, TRY_FINALLY_HANDLER);
2774
2775 // Introduce shadow labels for all escapes from the try block,
2776 // including returns. We should probably try to unify the escaping
2777 // labels and the return label.
2778 int nof_escapes = node->escaping_labels()->length();
2779 List<LabelShadow*> shadows(1 + nof_escapes);
2780 shadows.Add(new LabelShadow(&function_return_));
2781 for (int i = 0; i < nof_escapes; i++) {
2782 shadows.Add(new LabelShadow(node->escaping_labels()->at(i)));
2783 }
2784
2785 // Generate code for the statements in the try block.
2786 VisitStatements(node->try_block()->statements());
2787
2788 // Stop the introduced shadowing and count the number of required
2789 // unlinks.
2790 int nof_unlinks = 0;
2791 for (int i = 0; i <= nof_escapes; i++) {
2792 shadows[i]->StopShadowing();
2793 if (shadows[i]->is_linked()) nof_unlinks++;
2794 }
2795
2796 // Set the state on the stack to FALLING.
2797 __ Push(Operand(Factory::undefined_value())); // fake TOS
2798 __ mov(r2, Operand(Smi::FromInt(FALLING)));
2799 if (nof_unlinks > 0) __ b(&unlink);
2800
2801 // Generate code that sets the state for all used shadow labels.
2802 for (int i = 0; i <= nof_escapes; i++) {
2803 if (shadows[i]->is_linked()) {
2804 __ bind(shadows[i]);
2805 if (shadows[i]->shadowed() != &function_return_) {
2806 // Fake TOS for break and continue (not return).
2807 __ Push(Operand(Factory::undefined_value()));
2808 }
2809 __ mov(r2, Operand(Smi::FromInt(JUMPING + i)));
2810 __ b(&unlink);
2811 }
2812 }
2813
2814 // Unlink from try chain; be careful not to destroy the TOS.
2815 __ bind(&unlink);
2816
2817 // Reload sp from the top handler, because some statements that we
2818 // break from (eg, for...in) may have left stuff on the stack.
2819 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
2820 __ ldr(sp, MemOperand(r3));
2821 const int kNextOffset = StackHandlerConstants::kNextOffset +
2822 StackHandlerConstants::kAddressDisplacement;
2823 __ ldr(r1, MemOperand(sp, kNextOffset));
2824 __ str(r1, MemOperand(r3));
2825 ASSERT(StackHandlerConstants::kCodeOffset == 0); // first field is code
2826 __ add(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
2827 // Code slot popped.
2828
2829
2830 // --- Finally block ---
2831 __ bind(&finally_block);
2832
2833 // Push the state on the stack. If necessary move the state to a
2834 // local variable to avoid having extra values on the stack while
2835 // evaluating the finally block.
2836 __ Push(Operand(r2));
2837 if (node->finally_var() != NULL) {
2838 Reference target(this, node->finally_var());
2839 SetValue(&target);
2840 ASSERT(target.size() == 0); // no extra stuff on the stack
2841 __ pop(r0);
2842 }
2843
2844 // Generate code for the statements in the finally block.
2845 VisitStatements(node->finally_block()->statements());
2846
2847 // Get the state from the stack - or the local variable - and
2848 // restore the TOS register.
2849 if (node->finally_var() != NULL) {
2850 Reference target(this, node->finally_var());
2851 GetValue(&target);
2852 }
2853 __ Pop(r2);
2854
2855 // Generate code that jumps to the right destination for all used
2856 // shadow labels.
2857 for (int i = 0; i <= nof_escapes; i++) {
2858 if (shadows[i]->is_bound()) {
2859 __ cmp(r2, Operand(Smi::FromInt(JUMPING + i)));
2860 if (shadows[i]->shadowed() != &function_return_) {
2861 Label next;
2862 __ b(ne, &next);
2863 __ pop(r0); // pop faked TOS
2864 __ b(shadows[i]->shadowed());
2865 __ bind(&next);
2866 } else {
2867 __ b(eq, shadows[i]->shadowed());
2868 }
2869 }
2870 }
2871
2872 // Check if we need to rethrow the exception.
2873 __ cmp(r2, Operand(Smi::FromInt(THROWING)));
2874 __ b(ne, &exit);
2875
2876 // Rethrow exception.
2877 __ CallRuntime(Runtime::kReThrow, 1);
2878
2879 // Done.
2880 __ bind(&exit);
2881 __ pop(r0); // restore TOS caching.
2882}
2883
2884
2885void ArmCodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
2886 Comment cmnt(masm_, "[ DebuggerStatament");
2887 if (FLAG_debug_info) RecordStatementPosition(node);
2888 __ CallRuntime(Runtime::kDebugBreak, 1);
2889}
2890
2891
2892void ArmCodeGenerator::InstantiateBoilerplate(Handle<JSFunction> boilerplate) {
2893 ASSERT(boilerplate->IsBoilerplate());
2894
2895 // Push the boilerplate on the stack.
2896 __ Push(Operand(boilerplate));
2897
2898 // Create a new closure.
2899 __ Push(Operand(cp));
2900 __ CallRuntime(Runtime::kNewClosure, 2);
2901}
2902
2903
2904void ArmCodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
2905 Comment cmnt(masm_, "[ FunctionLiteral");
2906
2907 // Build the function boilerplate and instantiate it.
2908 Handle<JSFunction> boilerplate = BuildBoilerplate(node);
kasper.lund212ac232008-07-16 07:07:30 +00002909 // Check for stack-overflow exception.
2910 if (HasStackOverflow()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002911 InstantiateBoilerplate(boilerplate);
2912}
2913
2914
2915void ArmCodeGenerator::VisitFunctionBoilerplateLiteral(
2916 FunctionBoilerplateLiteral* node) {
2917 Comment cmnt(masm_, "[ FunctionBoilerplateLiteral");
2918 InstantiateBoilerplate(node->boilerplate());
2919}
2920
2921
2922void ArmCodeGenerator::VisitConditional(Conditional* node) {
2923 Comment cmnt(masm_, "[ Conditional");
2924 Label then, else_, exit;
2925 LoadCondition(node->condition(), CodeGenState::LOAD, &then, &else_, true);
2926 Branch(false, &else_);
2927 __ bind(&then);
2928 Load(node->then_expression(), access());
2929 __ b(&exit);
2930 __ bind(&else_);
2931 Load(node->else_expression(), access());
2932 __ bind(&exit);
2933}
2934
2935
2936void ArmCodeGenerator::VisitSlot(Slot* node) {
2937 Comment cmnt(masm_, "[ Slot");
2938
2939 if (node->type() == Slot::LOOKUP) {
2940 ASSERT(node->var()->mode() == Variable::DYNAMIC);
2941
2942 // For now, just do a runtime call.
2943 __ Push(Operand(cp));
2944 __ Push(Operand(node->var()->name()));
2945
2946 switch (access()) {
2947 case CodeGenState::UNDEFINED:
2948 UNREACHABLE();
2949 break;
2950
2951 case CodeGenState::LOAD:
2952 __ CallRuntime(Runtime::kLoadContextSlot, 2);
2953 // result (TOS) is the value that was loaded
2954 break;
2955
2956 case CodeGenState::LOAD_TYPEOF_EXPR:
2957 __ CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
2958 // result (TOS) is the value that was loaded
2959 break;
2960
2961 case CodeGenState::STORE:
2962 // Storing a variable must keep the (new) value on the stack. This
2963 // is necessary for compiling assignment expressions.
2964 __ CallRuntime(Runtime::kStoreContextSlot, 3);
2965 // result (TOS) is the value that was stored
2966 break;
2967
2968 case CodeGenState::INIT_CONST:
2969 // Same as STORE but ignores attribute (e.g. READ_ONLY) of
2970 // context slot so that we can initialize const properties
2971 // (introduced via eval("const foo = (some expr);")). Also,
2972 // uses the current function context instead of the top
2973 // context.
2974 //
2975 // Note that we must declare the foo upon entry of eval(),
2976 // via a context slot declaration, but we cannot initialize
2977 // it at the same time, because the const declaration may
2978 // be at the end of the eval code (sigh...) and the const
2979 // variable may have been used before (where its value is
2980 // 'undefined'). Thus, we can only do the initialization
2981 // when we actually encounter the expression and when the
2982 // expression operands are defined and valid, and thus we
2983 // need the split into 2 operations: declaration of the
2984 // context slot followed by initialization.
2985 __ CallRuntime(Runtime::kInitializeConstContextSlot, 3);
2986 break;
2987 }
2988
2989 } else {
2990 // Note: We would like to keep the assert below, but it fires because
2991 // of some nasty code in LoadTypeofExpression() which should be removed...
2992 // ASSERT(node->var()->mode() != Variable::DYNAMIC);
2993
2994 switch (access()) {
2995 case CodeGenState::UNDEFINED:
2996 UNREACHABLE();
2997 break;
2998
2999 case CodeGenState::LOAD: // fall through
3000 case CodeGenState::LOAD_TYPEOF_EXPR:
3001 // Special handling for locals allocated in registers.
3002 if (FLAG_optimize_locals && node->type() == Slot::LOCAL &&
3003 node->index() < num_reg_locals_) {
3004 __ Push(Operand(SlotRegister(node->index())));
3005 } else {
3006 __ Push(SlotOperand(node, r2));
3007 }
3008 if (node->var()->mode() == Variable::CONST) {
3009 // Const slots may contain 'the hole' value (the constant hasn't
3010 // been initialized yet) which needs to be converted into the
3011 // 'undefined' value.
3012 Comment cmnt(masm_, "[ Unhole const");
3013 __ cmp(r0, Operand(Factory::the_hole_value()));
3014 __ mov(r0, Operand(Factory::undefined_value()), LeaveCC, eq);
3015 }
3016 break;
3017
3018 case CodeGenState::INIT_CONST: {
3019 ASSERT(node->var()->mode() == Variable::CONST);
3020 // Only the first const initialization must be executed (the slot
3021 // still contains 'the hole' value). When the assignment is executed,
3022 // the code is identical to a normal store (see below).
3023 { Comment cmnt(masm_, "[ Init const");
3024 Label L;
3025 if (FLAG_optimize_locals && node->type() == Slot::LOCAL &&
3026 node->index() < num_reg_locals_) {
3027 __ mov(r2, Operand(SlotRegister(node->index())));
3028 } else {
3029 __ ldr(r2, SlotOperand(node, r2));
3030 }
3031 __ cmp(r2, Operand(Factory::the_hole_value()));
3032 __ b(ne, &L);
3033 // We must execute the store.
3034 if (FLAG_optimize_locals && node->type() == Slot::LOCAL &&
3035 node->index() < num_reg_locals_) {
3036 __ mov(SlotRegister(node->index()), Operand(r0));
3037 } else {
3038 // r2 may be loaded with context; used below in RecordWrite.
3039 __ str(r0, SlotOperand(node, r2));
3040 }
3041 if (node->type() == Slot::CONTEXT) {
3042 // Skip write barrier if the written value is a smi.
3043 Label exit;
3044 __ tst(r0, Operand(kSmiTagMask));
3045 __ b(eq, &exit);
3046 // r2 is loaded with context when calling SlotOperand above.
3047 int offset = FixedArray::kHeaderSize + node->index() * kPointerSize;
3048 __ mov(r3, Operand(offset));
3049 __ RecordWrite(r2, r3, r1);
3050 __ bind(&exit);
3051 }
3052 __ bind(&L);
3053 }
3054 break;
3055 }
3056
3057 case CodeGenState::STORE: {
3058 // Storing a variable must keep the (new) value on the stack. This
3059 // is necessary for compiling assignment expressions.
3060 // Special handling for locals allocated in registers.
3061 //
3062 // Note: We will reach here even with node->var()->mode() ==
3063 // Variable::CONST because of const declarations which will
3064 // initialize consts to 'the hole' value and by doing so, end
3065 // up calling this code.
3066 if (FLAG_optimize_locals && node->type() == Slot::LOCAL &&
3067 node->index() < num_reg_locals_) {
3068 __ mov(SlotRegister(node->index()), Operand(r0));
3069 } else {
3070 // r2 may be loaded with context; used below in RecordWrite.
3071 __ str(r0, SlotOperand(node, r2));
3072 }
3073 if (node->type() == Slot::CONTEXT) {
3074 // Skip write barrier if the written value is a smi.
3075 Label exit;
3076 __ tst(r0, Operand(kSmiTagMask));
3077 __ b(eq, &exit);
3078 // r2 is loaded with context when calling SlotOperand above.
3079 int offset = FixedArray::kHeaderSize + node->index() * kPointerSize;
3080 __ mov(r3, Operand(offset));
3081 __ RecordWrite(r2, r3, r1);
3082 __ bind(&exit);
3083 }
3084 break;
3085 }
3086 }
3087 }
3088}
3089
3090
3091void ArmCodeGenerator::VisitVariableProxy(VariableProxy* proxy_node) {
3092 Comment cmnt(masm_, "[ VariableProxy");
3093 Variable* node = proxy_node->var();
3094
3095 Expression* x = node->rewrite();
3096 if (x != NULL) {
3097 Visit(x);
3098 return;
3099 }
3100
3101 ASSERT(node->is_global());
3102 if (is_referenced()) {
3103 if (node->AsProperty() != NULL) {
3104 __ RecordPosition(node->AsProperty()->position());
3105 }
3106 AccessReferenceProperty(new Literal(node->name()), access());
3107
3108 } else {
3109 // All stores are through references.
3110 ASSERT(access() != CodeGenState::STORE);
3111 Reference property(this, proxy_node);
3112 GetValue(&property);
3113 }
3114}
3115
3116
3117void ArmCodeGenerator::VisitLiteral(Literal* node) {
3118 Comment cmnt(masm_, "[ Literal");
3119 __ Push(Operand(node->handle()));
3120}
3121
3122
3123void ArmCodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
3124 Comment cmnt(masm_, "[ RexExp Literal");
3125
3126 // Retrieve the literal array and check the allocated entry.
3127
3128 // Load the function of this activation.
3129 __ ldr(r1, MemOperand(pp, 0));
3130
3131 // Load the literals array of the function.
3132 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
3133
3134 // Load the literal at the ast saved index.
3135 int literal_offset =
3136 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
3137 __ ldr(r2, FieldMemOperand(r1, literal_offset));
3138
3139 Label done;
3140 __ cmp(r2, Operand(Factory::undefined_value()));
3141 __ b(ne, &done);
3142
3143 // If the entry is undefined we call the runtime system to computed
3144 // the literal.
3145 __ Push(Operand(r1)); // literal array (0)
3146 __ Push(Operand(Smi::FromInt(node->literal_index()))); // literal index (1)
3147 __ Push(Operand(node->pattern())); // RegExp pattern (2)
3148 __ Push(Operand(node->flags())); // RegExp flags (3)
3149 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
3150 __ Pop(r2);
3151 __ bind(&done);
3152
3153 // Push the literal.
3154 __ Push(Operand(r2));
3155}
3156
3157
3158// This deferred code stub will be used for creating the boilerplate
3159// by calling Runtime_CreateObjectLiteral.
3160// Each created boilerplate is stored in the JSFunction and they are
3161// therefore context dependent.
3162class ObjectLiteralDeferred: public DeferredCode {
3163 public:
3164 ObjectLiteralDeferred(CodeGenerator* generator, ObjectLiteral* node)
3165 : DeferredCode(generator), node_(node) {
3166 set_comment("[ ObjectLiteralDeferred");
3167 }
3168 virtual void Generate();
3169 private:
3170 ObjectLiteral* node_;
3171};
3172
3173
3174void ObjectLiteralDeferred::Generate() {
3175 // If the entry is undefined we call the runtime system to computed
3176 // the literal.
3177
3178 // Literal array (0).
3179 __ Push(Operand(r1));
3180 // Literal index (1).
3181 __ Push(Operand(Smi::FromInt(node_->literal_index())));
3182 // Constant properties (2).
3183 __ Push(Operand(node_->constant_properties()));
3184 __ CallRuntime(Runtime::kCreateObjectLiteralBoilerplate, 3);
3185 __ Pop(r2);
3186}
3187
3188
3189void ArmCodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
3190 Comment cmnt(masm_, "[ ObjectLiteral");
3191
3192 ObjectLiteralDeferred* deferred = new ObjectLiteralDeferred(this, node);
3193
3194 // Retrieve the literal array and check the allocated entry.
3195
3196 // Load the function of this activation.
3197 __ ldr(r1, MemOperand(pp, 0));
3198
3199 // Load the literals array of the function.
3200 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
3201
3202 // Load the literal at the ast saved index.
3203 int literal_offset =
3204 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
3205 __ ldr(r2, FieldMemOperand(r1, literal_offset));
3206
3207 // Check whether we need to materialize the object literal boilerplate.
3208 // If so, jump to the deferred code.
3209 __ cmp(r2, Operand(Factory::undefined_value()));
3210 __ b(eq, deferred->enter());
3211 __ bind(deferred->exit());
3212
3213 // Push the object literal boilerplate.
3214 __ Push(Operand(r2));
3215 // Clone the boilerplate object.
3216 __ CallRuntime(Runtime::kCloneObjectLiteralBoilerplate, 1);
3217
3218 for (int i = 0; i < node->properties()->length(); i++) {
3219 ObjectLiteral::Property* property = node->properties()->at(i);
3220 Literal* key = property->key();
3221 Expression* value = property->value();
3222 switch (property->kind()) {
3223 case ObjectLiteral::Property::CONSTANT: break;
3224 case ObjectLiteral::Property::COMPUTED: // fall through
3225 case ObjectLiteral::Property::PROTOTYPE: {
3226 // Save a copy of the resulting object on the stack.
3227 __ push(r0);
3228 Load(key);
3229 Load(value);
3230 __ CallRuntime(Runtime::kSetProperty, 3);
3231 // Restore the result object from the stack.
3232 __ pop(r0);
3233 break;
3234 }
3235 case ObjectLiteral::Property::SETTER: {
3236 __ push(r0);
3237 Load(key);
3238 __ Push(Operand(Smi::FromInt(1)));
3239 Load(value);
3240 __ CallRuntime(Runtime::kDefineAccessor, 4);
3241 __ pop(r0);
3242 break;
3243 }
3244 case ObjectLiteral::Property::GETTER: {
3245 __ push(r0);
3246 Load(key);
3247 __ Push(Operand(Smi::FromInt(0)));
3248 Load(value);
3249 __ CallRuntime(Runtime::kDefineAccessor, 4);
3250 __ pop(r0);
3251 break;
3252 }
3253 }
3254 }
3255}
3256
3257
3258void ArmCodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
3259 Comment cmnt(masm_, "[ ArrayLiteral");
3260 // Load the resulting object.
3261 Load(node->result());
3262 for (int i = 0; i < node->values()->length(); i++) {
3263 Expression* value = node->values()->at(i);
3264
3265 // If value is literal the property value is already
3266 // set in the boilerplate object.
3267 if (value->AsLiteral() == NULL) {
3268 // The property must be set by generated code.
3269 Load(value);
3270
3271 // Fetch the object literal
3272 __ ldr(r1, MemOperand(sp, 0));
3273 // Get the elements array.
3274 __ ldr(r1, FieldMemOperand(r1, JSObject::kElementsOffset));
3275
3276 // Write to the indexed properties array.
3277 int offset = i * kPointerSize + Array::kHeaderSize;
3278 __ str(r0, FieldMemOperand(r1, offset));
3279
3280 // Update the write barrier for the array address.
3281 __ mov(r3, Operand(offset));
3282 __ RecordWrite(r1, r3, r2);
3283
3284 __ pop(r0);
3285 }
3286 }
3287}
3288
3289
3290void ArmCodeGenerator::VisitAssignment(Assignment* node) {
3291 Comment cmnt(masm_, "[ Assignment");
3292
3293 if (FLAG_debug_info) RecordStatementPosition(node);
3294 Reference target(this, node->target());
3295 if (target.is_illegal()) return;
3296
3297 if (node->op() == Token::ASSIGN ||
3298 node->op() == Token::INIT_VAR ||
3299 node->op() == Token::INIT_CONST) {
3300 Load(node->value());
3301
3302 } else {
3303 GetValue(&target);
3304 Literal* literal = node->value()->AsLiteral();
3305 if (literal != NULL && literal->handle()->IsSmi()) {
3306 SmiOperation(node->binary_op(), literal->handle(), false);
3307 } else {
3308 Load(node->value());
3309 GenericOperation(node->binary_op());
3310 }
3311 }
3312
3313 Variable* var = node->target()->AsVariableProxy()->AsVariable();
3314 if (var != NULL &&
3315 (var->mode() == Variable::CONST) &&
3316 node->op() != Token::INIT_VAR && node->op() != Token::INIT_CONST) {
3317 // Assignment ignored - leave the value on the stack.
3318 } else {
3319 __ RecordPosition(node->position());
3320 if (node->op() == Token::INIT_CONST) {
3321 // Dynamic constant initializations must use the function context
3322 // and initialize the actual constant declared. Dynamic variable
3323 // initializations are simply assignments and use SetValue.
3324 InitConst(&target);
3325 } else {
3326 SetValue(&target);
3327 }
3328 }
3329}
3330
3331
3332void ArmCodeGenerator::VisitThrow(Throw* node) {
3333 Comment cmnt(masm_, "[ Throw");
3334
3335 Load(node->exception());
3336 __ RecordPosition(node->position());
3337 __ CallRuntime(Runtime::kThrow, 1);
3338}
3339
3340
3341void ArmCodeGenerator::VisitProperty(Property* node) {
3342 Comment cmnt(masm_, "[ Property");
3343 if (is_referenced()) {
3344 __ RecordPosition(node->position());
3345 AccessReferenceProperty(node->key(), access());
3346 } else {
3347 // All stores are through references.
3348 ASSERT(access() != CodeGenState::STORE);
3349 Reference property(this, node);
3350 __ RecordPosition(node->position());
3351 GetValue(&property);
3352 }
3353}
3354
3355
3356void ArmCodeGenerator::VisitCall(Call* node) {
3357 Comment cmnt(masm_, "[ Call");
3358
3359 ZoneList<Expression*>* args = node->arguments();
3360
3361 if (FLAG_debug_info) RecordStatementPosition(node);
3362 // Standard function call.
3363
3364 // Check if the function is a variable or a property.
3365 Expression* function = node->expression();
3366 Variable* var = function->AsVariableProxy()->AsVariable();
3367 Property* property = function->AsProperty();
3368
3369 // ------------------------------------------------------------------------
3370 // Fast-case: Use inline caching.
3371 // ---
3372 // According to ECMA-262, section 11.2.3, page 44, the function to call
3373 // must be resolved after the arguments have been evaluated. The IC code
3374 // automatically handles this by loading the arguments before the function
3375 // is resolved in cache misses (this also holds for megamorphic calls).
3376 // ------------------------------------------------------------------------
3377
3378 if (var != NULL && !var->is_this() && var->is_global()) {
3379 // ----------------------------------
3380 // JavaScript example: 'foo(1, 2, 3)' // foo is global
3381 // ----------------------------------
3382
3383 // Push the name of the function and the receiver onto the stack.
3384 __ Push(Operand(var->name()));
3385 LoadGlobal();
3386
3387 // Load the arguments.
3388 for (int i = 0; i < args->length(); i++) Load(args->at(i));
3389 __ Push(Operand(args->length()));
3390
3391 // Setup the receiver register and call the IC initialization code.
3392 Handle<Code> stub = ComputeCallInitialize(args->length());
3393 __ ldr(r1, GlobalObject());
3394 __ RecordPosition(node->position());
3395 __ Call(stub, code_target_context);
3396 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
3397
3398 // Remove the function from the stack.
3399 __ add(sp, sp, Operand(kPointerSize));
3400
3401 } else if (var != NULL && var->slot() != NULL &&
3402 var->slot()->type() == Slot::LOOKUP) {
3403 // ----------------------------------
3404 // JavaScript example: 'with (obj) foo(1, 2, 3)' // foo is in obj
3405 // ----------------------------------
3406
3407 // Load the function
3408 __ Push(Operand(cp));
3409 __ Push(Operand(var->name()));
3410 __ CallRuntime(Runtime::kLoadContextSlot, 2);
3411 // r0: slot value; r1: receiver
3412
3413 // Load the receiver.
3414 __ push(r0);
3415 __ mov(r0, Operand(r1));
3416
3417 // Call the function.
3418 CallWithArguments(args, node->position());
3419
3420 } else if (property != NULL) {
3421 // Check if the key is a literal string.
3422 Literal* literal = property->key()->AsLiteral();
3423
3424 if (literal != NULL && literal->handle()->IsSymbol()) {
3425 // ------------------------------------------------------------------
3426 // JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
3427 // ------------------------------------------------------------------
3428
3429 // Push the name of the function and the receiver onto the stack.
3430 __ Push(Operand(literal->handle()));
3431 Load(property->obj());
3432
3433 // Load the arguments.
3434 for (int i = 0; i < args->length(); i++) Load(args->at(i));
3435 __ Push(Operand(args->length()));
3436
3437 // Set the receiver register and call the IC initialization code.
3438 Handle<Code> stub = ComputeCallInitialize(args->length());
3439 __ ldr(r1, MemOperand(sp, args->length() * kPointerSize));
3440 __ RecordPosition(node->position());
3441 __ Call(stub, code_target);
3442 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
3443
3444 // Remove the function from the stack.
3445 __ add(sp, sp, Operand(kPointerSize));
3446
3447 } else {
3448 // -------------------------------------------
3449 // JavaScript example: 'array[index](1, 2, 3)'
3450 // -------------------------------------------
3451
3452 // Load the function to call from the property through a reference.
3453 Reference ref(this, property);
3454 GetValue(&ref);
3455
3456 // Pass receiver to called function.
3457 __ Push(MemOperand(sp, ref.size() * kPointerSize));
3458
3459 // Call the function.
3460 CallWithArguments(args, node->position());
3461 }
3462
3463 } else {
3464 // ----------------------------------
3465 // JavaScript example: 'foo(1, 2, 3)' // foo is not global
3466 // ----------------------------------
3467
3468 // Load the function.
3469 Load(function);
3470
3471 // Pass the global object as the receiver.
3472 LoadGlobal();
3473
3474 // Call the function.
3475 CallWithArguments(args, node->position());
3476 }
3477}
3478
3479
3480void ArmCodeGenerator::VisitCallNew(CallNew* node) {
3481 Comment cmnt(masm_, "[ CallNew");
3482
3483 // According to ECMA-262, section 11.2.2, page 44, the function
3484 // expression in new calls must be evaluated before the
3485 // arguments. This is different from ordinary calls, where the
3486 // actual function to call is resolved after the arguments have been
3487 // evaluated.
3488
3489 // Compute function to call and use the global object as the
3490 // receiver.
3491 Load(node->expression());
3492 LoadGlobal();
3493
3494 // Push the arguments ("left-to-right") on the stack.
3495 ZoneList<Expression*>* args = node->arguments();
3496 for (int i = 0; i < args->length(); i++) Load(args->at(i));
3497
3498 // Push the number of arguments.
3499 __ Push(Operand(args->length()));
3500
3501 // Call the construct call builtin that handles allocation and
3502 // constructor invocation.
3503 __ RecordPosition(position);
3504 __ Call(Handle<Code>(Builtins::builtin(Builtins::JSConstructCall)),
3505 js_construct_call);
3506 __ add(sp, sp, Operand(kPointerSize)); // discard
3507}
3508
3509
3510void ArmCodeGenerator::GenerateSetThisFunction(ZoneList<Expression*>* args) {
3511 ASSERT(args->length() == 1);
3512 Load(args->at(0));
3513 __ str(r0, MemOperand(pp, JavaScriptFrameConstants::kFunctionOffset));
3514}
3515
3516
3517void ArmCodeGenerator::GenerateGetThisFunction(ZoneList<Expression*>* args) {
3518 ASSERT(args->length() == 0);
3519 __ Push(MemOperand(pp, JavaScriptFrameConstants::kFunctionOffset));
3520}
3521
3522
3523void ArmCodeGenerator::GenerateSetThis(ZoneList<Expression*>* args) {
3524 ASSERT(args->length() == 1);
3525 Load(args->at(0));
3526 __ str(r0, MemOperand(pp, JavaScriptFrameConstants::kReceiverOffset));
3527}
3528
3529
3530void ArmCodeGenerator::GenerateSetArgumentsLength(ZoneList<Expression*>* args) {
3531 ASSERT(args->length() == 1);
3532 Load(args->at(0));
3533 __ mov(r0, Operand(r0, LSR, kSmiTagSize));
3534 __ str(r0, MemOperand(fp, JavaScriptFrameConstants::kArgsLengthOffset));
3535 __ mov(r0, Operand(Smi::FromInt(0)));
3536}
3537
3538
3539void ArmCodeGenerator::GenerateGetArgumentsLength(ZoneList<Expression*>* args) {
3540 ASSERT(args->length() == 1);
3541 __ push(r0);
3542 __ ldr(r0, MemOperand(fp, JavaScriptFrameConstants::kArgsLengthOffset));
3543 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
3544}
3545
3546
3547void ArmCodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
3548 ASSERT(args->length() == 1);
3549 Label leave;
3550 Load(args->at(0));
3551 // r0 contains object.
3552 // if (object->IsSmi()) return TOS.
3553 __ tst(r0, Operand(kSmiTagMask));
3554 __ b(eq, &leave);
3555 // It is a heap object - get map.
3556 __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
3557 __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
3558 // if (!object->IsJSValue()) return TOS.
3559 __ cmp(r1, Operand(JS_VALUE_TYPE));
3560 __ b(ne, &leave);
3561 // Load the value.
3562 __ ldr(r0, FieldMemOperand(r0, JSValue::kValueOffset));
3563 __ bind(&leave);
3564}
3565
3566
3567void ArmCodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
3568 ASSERT(args->length() == 2);
3569 Label leave;
3570 Load(args->at(0)); // Load the object.
3571 Load(args->at(1)); // Load the value.
3572 __ pop(r1);
3573 // r0 contains value.
3574 // r1 contains object.
3575 // if (object->IsSmi()) return object.
3576 __ tst(r1, Operand(kSmiTagMask));
3577 __ b(eq, &leave);
3578 // It is a heap object - get map.
3579 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset));
3580 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
3581 // if (!object->IsJSValue()) return object.
3582 __ cmp(r2, Operand(JS_VALUE_TYPE));
3583 __ b(ne, &leave);
3584 // Store the value.
3585 __ str(r0, FieldMemOperand(r1, JSValue::kValueOffset));
3586 // Update the write barrier.
3587 __ mov(r2, Operand(JSValue::kValueOffset - kHeapObjectTag));
3588 __ RecordWrite(r1, r2, r3);
3589 // Leave.
3590 __ bind(&leave);
3591}
3592
3593
3594void ArmCodeGenerator::GenerateTailCallWithArguments(
3595 ZoneList<Expression*>* args) {
3596 // r0 = number of arguments (smi)
3597 ASSERT(args->length() == 1);
3598 Load(args->at(0));
3599 __ mov(r0, Operand(r0, LSR, kSmiTagSize));
3600
3601 // r1 = new function (previously written to stack)
3602 __ ldr(r1, MemOperand(pp, JavaScriptFrameConstants::kFunctionOffset));
3603
3604 // Reset parameter pointer and frame pointer to previous frame
3605 ExitJSFrame(reg_locals_, DO_NOT_RETURN);
3606
3607 // Jump (tail-call) to the function in register r1.
3608 __ ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
3609 __ ldr(r1, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
3610 __ ldr(r1, FieldMemOperand(r1, SharedFunctionInfo::kCodeOffset));
3611 __ add(pc, r1, Operand(Code::kHeaderSize - kHeapObjectTag));
3612 return;
3613}
3614
3615
3616void ArmCodeGenerator::GenerateSetArgument(ZoneList<Expression*>* args) {
3617 ASSERT(args->length() == 3);
3618 // r1 = args[i]
3619 Comment cmnt(masm_, "[ GenerateSetArgument");
3620 Load(args->at(1));
3621 __ mov(r1, Operand(r0));
3622 // r0 = i
3623 Load(args->at(0));
3624#if defined(DEBUG)
3625 { Label L;
3626 __ tst(r0, Operand(kSmiTagMask));
3627 __ b(eq, &L);
3628 __ stop("SMI expected");
3629 __ bind(&L);
3630 }
3631#endif // defined(DEBUG)
3632 __ add(r2, pp, Operand(JavaScriptFrameConstants::kParam0Offset));
3633 __ str(r1,
3634 MemOperand(r2, r0, LSL, kPointerSizeLog2 - kSmiTagSize, NegOffset));
3635 __ pop(r0);
3636}
3637
3638
3639void ArmCodeGenerator::GenerateSquashFrame(ZoneList<Expression*>* args) {
3640 ASSERT(args->length() == 2);
3641 // Load r1 with old number of arguments, r0 with new number, r1 > r0.
3642 Load(args->at(0));
3643 __ mov(r1, Operand(r0, LSR, kSmiTagSize));
3644 Load(args->at(1));
3645 __ mov(r0, Operand(r0, LSR, kSmiTagSize));
3646 // r1 = number of words to move stack.
3647 __ sub(r1, r1, Operand(r0));
3648 // r2 is source.
3649 __ add(r2, fp, Operand(StandardFrameConstants::kCallerPCOffset));
3650 // Move down frame pointer fp.
3651 __ add(fp, fp, Operand(r1, LSL, kPointerSizeLog2));
3652 // r1 is destination.
3653 __ add(r1, fp, Operand(StandardFrameConstants::kCallerPCOffset));
3654
3655 Label move;
3656 __ bind(&move);
3657 __ ldr(r3, MemOperand(r2, -kPointerSize, PostIndex));
3658 __ str(r3, MemOperand(r1, -kPointerSize, PostIndex));
3659 __ cmp(r2, Operand(sp));
3660 __ b(ne, &move);
3661 __ ldr(r3, MemOperand(r2));
3662 __ str(r3, MemOperand(r1));
3663
3664 // Move down stack pointer esp.
3665 __ mov(sp, Operand(r1));
3666 // Balance stack and put something GC-able in r0.
3667 __ pop(r0);
3668}
3669
3670
3671void ArmCodeGenerator::GenerateExpandFrame(ZoneList<Expression*>* args) {
3672 ASSERT(args->length() == 2);
3673 // Load r1 with new number of arguments, r0 with old number (as Smi), r1 > r0.
3674 Load(args->at(1));
3675 __ mov(r1, Operand(r0, LSR, kSmiTagSize));
3676 Load(args->at(0));
3677 // r1 = number of words to move stack.
3678 __ sub(r1, r1, Operand(r0, LSR, kSmiTagSize));
3679 Label end_of_expand_frame;
3680 if (FLAG_check_stack) {
3681 Label not_too_big;
3682 __ sub(r2, sp, Operand(r1, LSL, kPointerSizeLog2));
3683 __ mov(ip, Operand(ExternalReference::address_of_stack_guard_limit()));
3684 __ ldr(ip, MemOperand(ip));
3685 __ cmp(r2, Operand(ip));
3686 __ b(gt, &not_too_big);
3687 __ pop(r0);
3688 __ mov(r0, Operand(Factory::false_value()));
3689 __ b(&end_of_expand_frame);
3690 __ bind(&not_too_big);
3691 }
3692 // r3 is source.
3693 __ mov(r3, Operand(sp));
3694 // r0 is copy limit + 1 word
3695 __ add(r0, fp,
3696 Operand(StandardFrameConstants::kCallerPCOffset + kPointerSize));
3697 // Move up frame pointer fp.
3698 __ sub(fp, fp, Operand(r1, LSL, kPointerSizeLog2));
3699 // Move up stack pointer sp.
3700 __ sub(sp, sp, Operand(r1, LSL, kPointerSizeLog2));
3701 // r1 is destination (r1 = source - r1).
3702 __ mov(r2, Operand(0));
3703 __ sub(r2, r2, Operand(r1, LSL, kPointerSizeLog2));
3704 __ add(r1, r3, Operand(r2));
3705
3706 Label move;
3707 __ bind(&move);
3708 __ ldr(r2, MemOperand(r3, kPointerSize, PostIndex));
3709 __ str(r2, MemOperand(r1, kPointerSize, PostIndex));
3710 __ cmp(r3, Operand(r0));
3711 __ b(ne, &move);
3712
3713 // Balance stack and put success value in top of stack
3714 __ pop(r0);
3715 __ mov(r0, Operand(Factory::true_value()));
3716 __ bind(&end_of_expand_frame);
3717}
3718
3719
3720void ArmCodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
3721 ASSERT(args->length() == 1);
3722 Load(args->at(0));
3723 __ tst(r0, Operand(kSmiTagMask));
3724 __ pop(r0);
3725 cc_reg_ = eq;
3726}
3727
3728
3729// This is used in the implementation of apply on ia32 but it is not
3730// used on ARM yet.
3731void ArmCodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
3732 __ int3();
3733 cc_reg_ = eq;
3734}
3735
3736
3737void ArmCodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
3738 ASSERT(args->length() == 0);
3739
3740 // Flush the TOS cache and seed the result with the formal
3741 // parameters count, which will be used in case no arguments adaptor
3742 // frame is found below the current frame.
3743 __ push(r0);
3744 __ mov(r0, Operand(Smi::FromInt(scope_->num_parameters())));
3745
3746 // Call the shared stub to get to the arguments.length.
3747 ArgumentsAccessStub stub(true);
3748 __ CallStub(&stub);
3749}
3750
3751
3752void ArmCodeGenerator::GenerateArgumentsAccess(ZoneList<Expression*>* args) {
3753 ASSERT(args->length() == 1);
3754
3755 // Load the key onto the stack and set register r1 to the formal
3756 // parameters count for the currently executing function.
3757 Load(args->at(0));
3758 __ mov(r1, Operand(Smi::FromInt(scope_->num_parameters())));
3759
3760 // Call the shared stub to get to arguments[key].
3761 ArgumentsAccessStub stub(false);
3762 __ CallStub(&stub);
3763}
3764
3765
3766void ArmCodeGenerator::GenerateShiftDownAndTailCall(
3767 ZoneList<Expression*>* args) {
3768 // r0 = number of arguments
3769 ASSERT(args->length() == 1);
3770 Load(args->at(0));
3771 __ mov(r0, Operand(r0, LSR, kSmiTagSize));
3772
3773 // Get the 'this' function and exit the frame without returning.
3774 __ ldr(r1, MemOperand(pp, JavaScriptFrameConstants::kFunctionOffset));
3775 ExitJSFrame(reg_locals_, DO_NOT_RETURN);
3776 // return address in lr
3777
3778 // Move arguments one element down the stack.
3779 Label move;
3780 Label moved;
3781 __ sub(r2, r0, Operand(0), SetCC);
3782 __ b(eq, &moved);
3783 __ bind(&move);
3784 __ sub(ip, r2, Operand(1));
3785 __ ldr(r3, MemOperand(sp, ip, LSL, kPointerSizeLog2));
3786 __ str(r3, MemOperand(sp, r2, LSL, kPointerSizeLog2));
3787 __ sub(r2, r2, Operand(1), SetCC);
3788 __ b(ne, &move);
3789 __ bind(&moved);
3790
3791 // Remove the TOS (copy of last argument)
3792 __ add(sp, sp, Operand(kPointerSize));
3793
3794 // Jump (tail-call) to the function in register r1.
3795 __ ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
3796 __ ldr(r1, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
3797 __ ldr(r1, FieldMemOperand(r1, SharedFunctionInfo::kCodeOffset));
3798 __ add(pc, r1, Operand(Code::kHeaderSize - kHeapObjectTag));
3799 return;
3800}
3801
3802
3803void ArmCodeGenerator::VisitCallRuntime(CallRuntime* node) {
3804 if (CheckForInlineRuntimeCall(node))
3805 return;
3806
3807 ZoneList<Expression*>* args = node->arguments();
3808 Comment cmnt(masm_, "[ CallRuntime");
3809 Runtime::Function* function = node->function();
3810
3811 if (function == NULL) {
3812 // Prepare stack for calling JS runtime function.
3813 __ Push(Operand(node->name()));
3814 // Push the builtins object found in the current global object.
3815 __ ldr(r1, GlobalObject());
3816 __ Push(FieldMemOperand(r1, GlobalObject::kBuiltinsOffset));
3817 }
3818
3819 // Push the arguments ("left-to-right").
3820 for (int i = 0; i < args->length(); i++) Load(args->at(i));
3821
3822 if (function != NULL) {
3823 // Call the C runtime function.
3824 __ CallRuntime(function, args->length());
3825 } else {
3826 // Call the JS runtime function.
3827 __ Push(Operand(args->length()));
3828 __ ldr(r1, MemOperand(sp, args->length() * kPointerSize));
3829 Handle<Code> stub = ComputeCallInitialize(args->length());
3830 __ Call(stub, code_target);
3831 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
3832 __ add(sp, sp, Operand(kPointerSize));
3833 }
3834}
3835
3836
3837void ArmCodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
3838 Comment cmnt(masm_, "[ UnaryOperation");
3839
3840 Token::Value op = node->op();
3841
3842 if (op == Token::NOT) {
3843 LoadCondition(node->expression(),
3844 CodeGenState::LOAD,
3845 false_target(),
3846 true_target(),
3847 true);
3848 cc_reg_ = NegateCondition(cc_reg_);
3849
3850 } else if (op == Token::DELETE) {
3851 Property* property = node->expression()->AsProperty();
3852 if (property != NULL) {
3853 Load(property->obj());
3854 Load(property->key());
3855 __ Push(Operand(1)); // not counting receiver
3856 __ InvokeBuiltin("DELETE", 1, CALL_JS);
3857 return;
3858 }
3859
3860 Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
3861 if (variable != NULL) {
3862 Slot* slot = variable->slot();
3863 if (variable->is_global()) {
3864 LoadGlobal();
3865 __ Push(Operand(variable->name()));
3866 __ Push(Operand(1)); // not counting receiver
3867 __ InvokeBuiltin("DELETE", 1, CALL_JS);
3868 return;
3869
3870 } else if (slot != NULL && slot->type() == Slot::LOOKUP) {
3871 // lookup the context holding the named variable
3872 __ Push(Operand(cp));
3873 __ Push(Operand(variable->name()));
3874 __ CallRuntime(Runtime::kLookupContext, 2);
3875 // r0: context
3876 __ Push(Operand(variable->name()));
3877 __ Push(Operand(1)); // not counting receiver
3878 __ InvokeBuiltin("DELETE", 1, CALL_JS);
3879 return;
3880 }
3881
3882 // Default: Result of deleting non-global, not dynamically
3883 // introduced variables is false.
3884 __ Push(Operand(Factory::false_value()));
3885
3886 } else {
3887 // Default: Result of deleting expressions is true.
3888 Load(node->expression()); // may have side-effects
3889 __ mov(r0, Operand(Factory::true_value()));
3890 }
3891
3892 } else if (op == Token::TYPEOF) {
3893 // Special case for loading the typeof expression; see comment on
3894 // LoadTypeofExpression().
3895 LoadTypeofExpression(node->expression());
3896 __ CallRuntime(Runtime::kTypeof, 1);
3897
3898 } else {
3899 Load(node->expression());
3900 switch (op) {
3901 case Token::NOT:
3902 case Token::DELETE:
3903 case Token::TYPEOF:
3904 UNREACHABLE(); // handled above
3905 break;
3906
3907 case Token::SUB: {
3908 UnarySubStub stub;
3909 __ CallStub(&stub);
3910 break;
3911 }
3912
3913 case Token::BIT_NOT: {
3914 // smi check
3915 Label smi_label;
3916 Label continue_label;
3917 __ tst(r0, Operand(kSmiTagMask));
3918 __ b(eq, &smi_label);
3919
3920 __ Push(Operand(0)); // not counting receiver
3921 __ InvokeBuiltin("BIT_NOT", 0, CALL_JS);
3922
3923 __ b(&continue_label);
3924 __ bind(&smi_label);
3925 __ mvn(r0, Operand(r0));
3926 __ bic(r0, r0, Operand(kSmiTagMask)); // bit-clear inverted smi-tag
3927 __ bind(&continue_label);
3928 break;
3929 }
3930
3931 case Token::VOID:
3932 // since the stack top is cached in r0, popping and then
3933 // pushing a value can be done by just writing to r0.
3934 __ mov(r0, Operand(Factory::undefined_value()));
3935 break;
3936
3937 case Token::ADD:
3938 __ Push(Operand(0)); // not counting receiver
3939 __ InvokeBuiltin("TO_NUMBER", 0, CALL_JS);
3940 break;
3941
3942 default:
3943 UNREACHABLE();
3944 }
3945 }
3946}
3947
3948
3949void ArmCodeGenerator::VisitCountOperation(CountOperation* node) {
3950 Comment cmnt(masm_, "[ CountOperation");
3951
3952 bool is_postfix = node->is_postfix();
3953 bool is_increment = node->op() == Token::INC;
3954
3955 Variable* var = node->expression()->AsVariableProxy()->AsVariable();
3956 bool is_const = (var != NULL && var->mode() == Variable::CONST);
3957
3958 // Postfix: Make room for the result.
3959 if (is_postfix) __ Push(Operand(0));
3960
3961 { Reference target(this, node->expression());
3962 if (target.is_illegal()) return;
3963 GetValue(&target);
3964
3965 Label slow, exit;
3966
3967 // Load the value (1) into register r1.
3968 __ mov(r1, Operand(Smi::FromInt(1)));
3969
3970 // Check for smi operand.
3971 __ tst(r0, Operand(kSmiTagMask));
3972 __ b(ne, &slow);
3973
3974 // Postfix: Store the old value as the result.
3975 if (is_postfix) __ str(r0, MemOperand(sp, target.size() * kPointerSize));
3976
3977 // Perform optimistic increment/decrement.
3978 if (is_increment) {
3979 __ add(r0, r0, Operand(r1), SetCC);
3980 } else {
3981 __ sub(r0, r0, Operand(r1), SetCC);
3982 }
3983
3984 // If the increment/decrement didn't overflow, we're done.
3985 __ b(vc, &exit);
3986
3987 // Revert optimistic increment/decrement.
3988 if (is_increment) {
3989 __ sub(r0, r0, Operand(r1));
3990 } else {
3991 __ add(r0, r0, Operand(r1));
3992 }
3993
3994 // Slow case: Convert to number.
3995 __ bind(&slow);
3996
3997 // Postfix: Convert the operand to a number and store it as the result.
3998 if (is_postfix) {
3999 InvokeBuiltinStub stub(InvokeBuiltinStub::ToNumber, 2);
4000 __ CallStub(&stub);
4001 // Store to result (on the stack).
4002 __ str(r0, MemOperand(sp, target.size() * kPointerSize));
4003 }
4004
4005 // Compute the new value by calling the right JavaScript native.
4006 if (is_increment) {
4007 InvokeBuiltinStub stub(InvokeBuiltinStub::Inc, 1);
4008 __ CallStub(&stub);
4009 } else {
4010 InvokeBuiltinStub stub(InvokeBuiltinStub::Dec, 1);
4011 __ CallStub(&stub);
4012 }
4013
4014 // Store the new value in the target if not const.
4015 __ bind(&exit);
4016 if (!is_const) SetValue(&target);
4017 }
4018
4019 // Postfix: Discard the new value and use the old.
4020 if (is_postfix) __ pop(r0);
4021}
4022
4023
4024void ArmCodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
4025 Comment cmnt(masm_, "[ BinaryOperation");
4026 Token::Value op = node->op();
4027
4028 // According to ECMA-262 section 11.11, page 58, the binary logical
4029 // operators must yield the result of one of the two expressions
4030 // before any ToBoolean() conversions. This means that the value
4031 // produced by a && or || operator is not necessarily a boolean.
4032
4033 // NOTE: If the left hand side produces a materialized value (not in
4034 // the CC register), we force the right hand side to do the
4035 // same. This is necessary because we may have to branch to the exit
4036 // after evaluating the left hand side (due to the shortcut
4037 // semantics), but the compiler must (statically) know if the result
4038 // of compiling the binary operation is materialized or not.
4039
4040 if (op == Token::AND) {
4041 Label is_true;
4042 LoadCondition(node->left(),
4043 CodeGenState::LOAD,
4044 &is_true,
4045 false_target(),
4046 false);
4047 if (has_cc()) {
4048 Branch(false, false_target());
4049
4050 // Evaluate right side expression.
4051 __ bind(&is_true);
4052 LoadCondition(node->right(),
4053 CodeGenState::LOAD,
4054 true_target(),
4055 false_target(),
4056 false);
4057
4058 } else {
4059 Label pop_and_continue, exit;
4060
4061 // Avoid popping the result if it converts to 'false' using the
4062 // standard ToBoolean() conversion as described in ECMA-262,
4063 // section 9.2, page 30.
4064 ToBoolean(r0, &pop_and_continue, &exit);
4065 Branch(false, &exit);
4066
4067 // Pop the result of evaluating the first part.
4068 __ bind(&pop_and_continue);
4069 __ pop(r0);
4070
4071 // Evaluate right side expression.
4072 __ bind(&is_true);
4073 Load(node->right());
4074
4075 // Exit (always with a materialized value).
4076 __ bind(&exit);
4077 }
4078
4079 } else if (op == Token::OR) {
4080 Label is_false;
4081 LoadCondition(node->left(),
4082 CodeGenState::LOAD,
4083 true_target(),
4084 &is_false,
4085 false);
4086 if (has_cc()) {
4087 Branch(true, true_target());
4088
4089 // Evaluate right side expression.
4090 __ bind(&is_false);
4091 LoadCondition(node->right(),
4092 CodeGenState::LOAD,
4093 true_target(),
4094 false_target(),
4095 false);
4096
4097 } else {
4098 Label pop_and_continue, exit;
4099
4100 // Avoid popping the result if it converts to 'true' using the
4101 // standard ToBoolean() conversion as described in ECMA-262,
4102 // section 9.2, page 30.
4103 ToBoolean(r0, &exit, &pop_and_continue);
4104 Branch(true, &exit);
4105
4106 // Pop the result of evaluating the first part.
4107 __ bind(&pop_and_continue);
4108 __ pop(r0);
4109
4110 // Evaluate right side expression.
4111 __ bind(&is_false);
4112 Load(node->right());
4113
4114 // Exit (always with a materialized value).
4115 __ bind(&exit);
4116 }
4117
4118 } else {
4119 // Optimize for the case where (at least) one of the expressions
4120 // is a literal small integer.
4121 Literal* lliteral = node->left()->AsLiteral();
4122 Literal* rliteral = node->right()->AsLiteral();
4123
4124 if (rliteral != NULL && rliteral->handle()->IsSmi()) {
4125 Load(node->left());
4126 SmiOperation(node->op(), rliteral->handle(), false);
4127
4128 } else if (lliteral != NULL && lliteral->handle()->IsSmi()) {
4129 Load(node->right());
4130 SmiOperation(node->op(), lliteral->handle(), true);
4131
4132 } else {
4133 Load(node->left());
4134 Load(node->right());
4135 GenericOperation(node->op());
4136 }
4137 }
4138}
4139
4140
4141void ArmCodeGenerator::VisitThisFunction(ThisFunction* node) {
4142 __ Push(FunctionOperand());
4143}
4144
4145
4146void ArmCodeGenerator::VisitCompareOperation(CompareOperation* node) {
4147 Comment cmnt(masm_, "[ CompareOperation");
4148
4149 // Get the expressions from the node.
4150 Expression* left = node->left();
4151 Expression* right = node->right();
4152 Token::Value op = node->op();
4153
4154 // NOTE: To make null checks efficient, we check if either left or
4155 // right is the literal 'null'. If so, we optimize the code by
4156 // inlining a null check instead of calling the (very) general
4157 // runtime routine for checking equality.
4158
4159 bool left_is_null =
4160 left->AsLiteral() != NULL && left->AsLiteral()->IsNull();
4161 bool right_is_null =
4162 right->AsLiteral() != NULL && right->AsLiteral()->IsNull();
4163
4164 if (op == Token::EQ || op == Token::EQ_STRICT) {
4165 // The 'null' value is only equal to 'null' or 'undefined'.
4166 if (left_is_null || right_is_null) {
4167 Load(left_is_null ? right : left);
4168 Label exit, undetectable;
4169 __ cmp(r0, Operand(Factory::null_value()));
4170
4171 // The 'null' value is only equal to 'undefined' if using
4172 // non-strict comparisons.
4173 if (op != Token::EQ_STRICT) {
4174 __ b(eq, &exit);
4175 __ cmp(r0, Operand(Factory::undefined_value()));
4176
4177 // NOTE: it can be undetectable object.
4178 __ b(eq, &exit);
4179 __ tst(r0, Operand(kSmiTagMask));
4180
4181 __ b(ne, &undetectable);
4182 __ pop(r0);
4183 __ b(false_target());
4184
4185 __ bind(&undetectable);
4186 __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
4187 __ ldrb(r2, FieldMemOperand(r1, Map::kBitFieldOffset));
4188 __ and_(r2, r2, Operand(1 << Map::kIsUndetectable));
4189 __ cmp(r2, Operand(1 << Map::kIsUndetectable));
4190 }
4191
4192 __ bind(&exit);
4193 __ pop(r0);
4194
4195 cc_reg_ = eq;
4196 return;
4197 }
4198 }
4199
4200
4201 // NOTE: To make typeof testing for natives implemented in
4202 // JavaScript really efficient, we generate special code for
4203 // expressions of the form: 'typeof <expression> == <string>'.
4204
4205 UnaryOperation* operation = left->AsUnaryOperation();
4206 if ((op == Token::EQ || op == Token::EQ_STRICT) &&
4207 (operation != NULL && operation->op() == Token::TYPEOF) &&
4208 (right->AsLiteral() != NULL &&
4209 right->AsLiteral()->handle()->IsString())) {
4210 Handle<String> check(String::cast(*right->AsLiteral()->handle()));
4211
4212 // Load the operand, move it to register r1, and restore TOS.
4213 LoadTypeofExpression(operation->expression());
4214 __ mov(r1, Operand(r0));
4215 __ pop(r0);
4216
4217 if (check->Equals(Heap::number_symbol())) {
4218 __ tst(r1, Operand(kSmiTagMask));
4219 __ b(eq, true_target());
4220 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
4221 __ cmp(r1, Operand(Factory::heap_number_map()));
4222 cc_reg_ = eq;
4223
4224 } else if (check->Equals(Heap::string_symbol())) {
4225 __ tst(r1, Operand(kSmiTagMask));
4226 __ b(eq, false_target());
4227
4228 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
4229
4230 // NOTE: it might be an undetectable string object
4231 __ ldrb(r2, FieldMemOperand(r1, Map::kBitFieldOffset));
4232 __ and_(r2, r2, Operand(1 << Map::kIsUndetectable));
4233 __ cmp(r2, Operand(1 << Map::kIsUndetectable));
4234 __ b(eq, false_target());
4235
4236 __ ldrb(r2, FieldMemOperand(r1, Map::kInstanceTypeOffset));
4237 __ cmp(r2, Operand(FIRST_NONSTRING_TYPE));
4238 cc_reg_ = lt;
4239
4240 } else if (check->Equals(Heap::boolean_symbol())) {
4241 __ cmp(r1, Operand(Factory::true_value()));
4242 __ b(eq, true_target());
4243 __ cmp(r1, Operand(Factory::false_value()));
4244 cc_reg_ = eq;
4245
4246 } else if (check->Equals(Heap::undefined_symbol())) {
4247 __ cmp(r1, Operand(Factory::undefined_value()));
4248 __ b(eq, true_target());
4249
4250 __ tst(r1, Operand(kSmiTagMask));
4251 __ b(eq, false_target());
4252
4253 // NOTE: it can be undetectable object.
4254 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
4255 __ ldrb(r2, FieldMemOperand(r1, Map::kBitFieldOffset));
4256 __ and_(r2, r2, Operand(1 << Map::kIsUndetectable));
4257 __ cmp(r2, Operand(1 << Map::kIsUndetectable));
4258
4259 cc_reg_ = eq;
4260
4261 } else if (check->Equals(Heap::function_symbol())) {
4262 __ tst(r1, Operand(kSmiTagMask));
4263 __ b(eq, false_target());
4264 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
4265 __ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
4266 __ cmp(r1, Operand(JS_FUNCTION_TYPE));
4267 cc_reg_ = eq;
4268
4269 } else if (check->Equals(Heap::object_symbol())) {
4270 __ tst(r1, Operand(kSmiTagMask));
4271 __ b(eq, false_target());
4272
4273 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset));
4274 __ cmp(r1, Operand(Factory::null_value()));
4275 __ b(eq, true_target());
4276
4277 // NOTE: it might be an undetectable object.
4278 __ ldrb(r1, FieldMemOperand(r2, Map::kBitFieldOffset));
4279 __ and_(r1, r1, Operand(1 << Map::kIsUndetectable));
4280 __ cmp(r1, Operand(1 << Map::kIsUndetectable));
4281 __ b(eq, false_target());
4282
4283 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
4284 __ cmp(r2, Operand(FIRST_JS_OBJECT_TYPE));
4285 __ b(lt, false_target());
4286 __ cmp(r2, Operand(LAST_JS_OBJECT_TYPE));
4287 cc_reg_ = le;
4288
4289 } else {
4290 // Uncommon case: Typeof testing against a string literal that
4291 // is never returned from the typeof operator.
4292 __ b(false_target());
4293 }
4294 return;
4295 }
4296
4297 Load(left);
4298 Load(right);
4299 switch (op) {
4300 case Token::EQ:
4301 Comparison(eq, false);
4302 break;
4303
4304 case Token::LT:
4305 Comparison(lt);
4306 break;
4307
4308 case Token::GT:
4309 Comparison(gt);
4310 break;
4311
4312 case Token::LTE:
4313 Comparison(le);
4314 break;
4315
4316 case Token::GTE:
4317 Comparison(ge);
4318 break;
4319
4320 case Token::EQ_STRICT:
4321 Comparison(eq, true);
4322 break;
4323
4324 case Token::IN:
4325 __ Push(Operand(1)); // not counting receiver
4326 __ InvokeBuiltin("IN", 1, CALL_JS);
4327 break;
4328
4329 case Token::INSTANCEOF:
4330 __ Push(Operand(1)); // not counting receiver
4331 __ InvokeBuiltin("INSTANCE_OF", 1, CALL_JS);
4332 break;
4333
4334 default:
4335 UNREACHABLE();
4336 }
4337}
4338
4339
4340void ArmCodeGenerator::RecordStatementPosition(Node* node) {
4341 if (FLAG_debug_info) {
4342 int statement_pos = node->statement_pos();
4343 if (statement_pos == kNoPosition) return;
4344 __ RecordStatementPosition(statement_pos);
4345 }
4346}
4347
4348
4349void ArmCodeGenerator::EnterJSFrame(int argc, RegList callee_saved) {
4350 __ EnterJSFrame(argc, callee_saved);
4351}
4352
4353
4354void ArmCodeGenerator::ExitJSFrame(RegList callee_saved, ExitJSFlag flag) {
4355 // The JavaScript debugger expects ExitJSFrame to be implemented as a stub,
4356 // so that a breakpoint can be inserted at the end of a function.
4357 int num_callee_saved = NumRegs(callee_saved);
4358
4359 // We support a fixed number of register variable configurations
4360 ASSERT(num_callee_saved <= 5 &&
4361 JSCalleeSavedList(num_callee_saved) == callee_saved);
4362
4363 JSExitStub stub(num_callee_saved, callee_saved, flag);
4364 __ CallJSExitStub(&stub);
4365}
4366
4367
4368#undef __
4369
4370
4371// -----------------------------------------------------------------------------
4372// CodeGenerator interface
4373
4374// MakeCode() is just a wrapper for CodeGenerator::MakeCode()
4375// so we don't have to expose the entire CodeGenerator class in
4376// the .h file.
4377Handle<Code> CodeGenerator::MakeCode(FunctionLiteral* fun,
4378 Handle<Script> script,
4379 bool is_eval) {
4380 Handle<Code> code = ArmCodeGenerator::MakeCode(fun, script, is_eval);
4381 if (!code.is_null()) {
4382 Counters::total_compiled_code_size.Increment(code->instruction_size());
4383 }
4384 return code;
4385}
4386
4387
4388} } // namespace v8::internal