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