blob: cdd32f30f857956f96e88920b098ca5df6c5fde2 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "bootstrapper.h"
31#include "codegen-inl.h"
32#include "debug.h"
33#include "parser.h"
34#include "register-allocator-inl.h"
35#include "runtime.h"
36#include "scopes.h"
37
38
39namespace v8 {
40namespace internal {
41
42#define __ ACCESS_MASM(masm_)
43
44static void EmitIdenticalObjectComparison(MacroAssembler* masm,
45 Label* slow,
46 Condition cc);
47static void EmitSmiNonsmiComparison(MacroAssembler* masm,
48 Label* rhs_not_nan,
49 Label* slow,
50 bool strict);
51static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc);
52static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm);
53static void MultiplyByKnownInt(MacroAssembler* masm,
54 Register source,
55 Register destination,
56 int known_int);
57static bool IsEasyToMultiplyBy(int x);
58
59
60
61// -------------------------------------------------------------------------
62// Platform-specific DeferredCode functions.
63
64void DeferredCode::SaveRegisters() {
65 for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
66 int action = registers_[i];
67 if (action == kPush) {
68 __ push(RegisterAllocator::ToRegister(i));
69 } else if (action != kIgnore && (action & kSyncedFlag) == 0) {
70 __ str(RegisterAllocator::ToRegister(i), MemOperand(fp, action));
71 }
72 }
73}
74
75
76void DeferredCode::RestoreRegisters() {
77 // Restore registers in reverse order due to the stack.
78 for (int i = RegisterAllocator::kNumRegisters - 1; i >= 0; i--) {
79 int action = registers_[i];
80 if (action == kPush) {
81 __ pop(RegisterAllocator::ToRegister(i));
82 } else if (action != kIgnore) {
83 action &= ~kSyncedFlag;
84 __ ldr(RegisterAllocator::ToRegister(i), MemOperand(fp, action));
85 }
86 }
87}
88
89
90// -------------------------------------------------------------------------
91// CodeGenState implementation.
92
93CodeGenState::CodeGenState(CodeGenerator* owner)
94 : owner_(owner),
95 typeof_state_(NOT_INSIDE_TYPEOF),
96 true_target_(NULL),
97 false_target_(NULL),
98 previous_(NULL) {
99 owner_->set_state(this);
100}
101
102
103CodeGenState::CodeGenState(CodeGenerator* owner,
104 TypeofState typeof_state,
105 JumpTarget* true_target,
106 JumpTarget* false_target)
107 : owner_(owner),
108 typeof_state_(typeof_state),
109 true_target_(true_target),
110 false_target_(false_target),
111 previous_(owner->state()) {
112 owner_->set_state(this);
113}
114
115
116CodeGenState::~CodeGenState() {
117 ASSERT(owner_->state() == this);
118 owner_->set_state(previous_);
119}
120
121
122// -------------------------------------------------------------------------
123// CodeGenerator implementation
124
125CodeGenerator::CodeGenerator(int buffer_size, Handle<Script> script,
126 bool is_eval)
127 : is_eval_(is_eval),
128 script_(script),
129 deferred_(8),
130 masm_(new MacroAssembler(NULL, buffer_size)),
131 scope_(NULL),
132 frame_(NULL),
133 allocator_(NULL),
134 cc_reg_(al),
135 state_(NULL),
136 function_return_is_shadowed_(false) {
137}
138
139
140// Calling conventions:
141// fp: caller's frame pointer
142// sp: stack pointer
143// r1: called JS function
144// cp: callee's context
145
146void CodeGenerator::GenCode(FunctionLiteral* fun) {
147 ZoneList<Statement*>* body = fun->body();
148
149 // Initialize state.
150 ASSERT(scope_ == NULL);
151 scope_ = fun->scope();
152 ASSERT(allocator_ == NULL);
153 RegisterAllocator register_allocator(this);
154 allocator_ = &register_allocator;
155 ASSERT(frame_ == NULL);
156 frame_ = new VirtualFrame();
157 cc_reg_ = al;
158 {
159 CodeGenState state(this);
160
161 // Entry:
162 // Stack: receiver, arguments
163 // lr: return address
164 // fp: caller's frame pointer
165 // sp: stack pointer
166 // r1: called JS function
167 // cp: callee's context
168 allocator_->Initialize();
169 frame_->Enter();
170 // tos: code slot
171#ifdef DEBUG
172 if (strlen(FLAG_stop_at) > 0 &&
173 fun->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
174 frame_->SpillAll();
175 __ stop("stop-at");
176 }
177#endif
178
179 // Allocate space for locals and initialize them. This also checks
180 // for stack overflow.
181 frame_->AllocateStackSlots();
182 // Initialize the function return target after the locals are set
183 // up, because it needs the expected frame height from the frame.
184 function_return_.set_direction(JumpTarget::BIDIRECTIONAL);
185 function_return_is_shadowed_ = false;
186
187 VirtualFrame::SpilledScope spilled_scope;
188 if (scope_->num_heap_slots() > 0) {
189 // Allocate local context.
190 // Get outer context and create a new context based on it.
191 __ ldr(r0, frame_->Function());
192 frame_->EmitPush(r0);
193 frame_->CallRuntime(Runtime::kNewContext, 1); // r0 holds the result
194
195#ifdef DEBUG
196 JumpTarget verified_true;
197 __ cmp(r0, Operand(cp));
198 verified_true.Branch(eq);
199 __ stop("NewContext: r0 is expected to be the same as cp");
200 verified_true.Bind();
201#endif
202 // Update context local.
203 __ str(cp, frame_->Context());
204 }
205
206 // TODO(1241774): Improve this code:
207 // 1) only needed if we have a context
208 // 2) no need to recompute context ptr every single time
209 // 3) don't copy parameter operand code from SlotOperand!
210 {
211 Comment cmnt2(masm_, "[ copy context parameters into .context");
212
213 // Note that iteration order is relevant here! If we have the same
214 // parameter twice (e.g., function (x, y, x)), and that parameter
215 // needs to be copied into the context, it must be the last argument
216 // passed to the parameter that needs to be copied. This is a rare
217 // case so we don't check for it, instead we rely on the copying
218 // order: such a parameter is copied repeatedly into the same
219 // context location and thus the last value is what is seen inside
220 // the function.
221 for (int i = 0; i < scope_->num_parameters(); i++) {
222 Variable* par = scope_->parameter(i);
223 Slot* slot = par->slot();
224 if (slot != NULL && slot->type() == Slot::CONTEXT) {
225 ASSERT(!scope_->is_global_scope()); // no parameters in global scope
226 __ ldr(r1, frame_->ParameterAt(i));
227 // Loads r2 with context; used below in RecordWrite.
228 __ str(r1, SlotOperand(slot, r2));
229 // Load the offset into r3.
230 int slot_offset =
231 FixedArray::kHeaderSize + slot->index() * kPointerSize;
232 __ mov(r3, Operand(slot_offset));
233 __ RecordWrite(r2, r3, r1);
234 }
235 }
236 }
237
238 // Store the arguments object. This must happen after context
239 // initialization because the arguments object may be stored in the
240 // context.
241 if (scope_->arguments() != NULL) {
242 ASSERT(scope_->arguments_shadow() != NULL);
243 Comment cmnt(masm_, "[ allocate arguments object");
244 { Reference shadow_ref(this, scope_->arguments_shadow());
245 { Reference arguments_ref(this, scope_->arguments());
246 ArgumentsAccessStub stub(ArgumentsAccessStub::NEW_OBJECT);
247 __ ldr(r2, frame_->Function());
248 // The receiver is below the arguments, the return address,
249 // and the frame pointer on the stack.
250 const int kReceiverDisplacement = 2 + scope_->num_parameters();
251 __ add(r1, fp, Operand(kReceiverDisplacement * kPointerSize));
252 __ mov(r0, Operand(Smi::FromInt(scope_->num_parameters())));
253 frame_->Adjust(3);
254 __ stm(db_w, sp, r0.bit() | r1.bit() | r2.bit());
255 frame_->CallStub(&stub, 3);
256 frame_->EmitPush(r0);
257 arguments_ref.SetValue(NOT_CONST_INIT);
258 }
259 shadow_ref.SetValue(NOT_CONST_INIT);
260 }
261 frame_->Drop(); // Value is no longer needed.
262 }
263
264 // Generate code to 'execute' declarations and initialize functions
265 // (source elements). In case of an illegal redeclaration we need to
266 // handle that instead of processing the declarations.
267 if (scope_->HasIllegalRedeclaration()) {
268 Comment cmnt(masm_, "[ illegal redeclarations");
269 scope_->VisitIllegalRedeclaration(this);
270 } else {
271 Comment cmnt(masm_, "[ declarations");
272 ProcessDeclarations(scope_->declarations());
273 // Bail out if a stack-overflow exception occurred when processing
274 // declarations.
275 if (HasStackOverflow()) return;
276 }
277
278 if (FLAG_trace) {
279 frame_->CallRuntime(Runtime::kTraceEnter, 0);
280 // Ignore the return value.
281 }
282
283 // Compile the body of the function in a vanilla state. Don't
284 // bother compiling all the code if the scope has an illegal
285 // redeclaration.
286 if (!scope_->HasIllegalRedeclaration()) {
287 Comment cmnt(masm_, "[ function body");
288#ifdef DEBUG
289 bool is_builtin = Bootstrapper::IsActive();
290 bool should_trace =
291 is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
292 if (should_trace) {
293 frame_->CallRuntime(Runtime::kDebugTrace, 0);
294 // Ignore the return value.
295 }
296#endif
297 VisitStatementsAndSpill(body);
298 }
299 }
300
301 // Generate the return sequence if necessary.
302 if (has_valid_frame() || function_return_.is_linked()) {
303 if (!function_return_.is_linked()) {
304 CodeForReturnPosition(fun);
305 }
306 // exit
307 // r0: result
308 // sp: stack pointer
309 // fp: frame pointer
310 // cp: callee's context
311 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
312
313 function_return_.Bind();
314 if (FLAG_trace) {
315 // Push the return value on the stack as the parameter.
316 // Runtime::TraceExit returns the parameter as it is.
317 frame_->EmitPush(r0);
318 frame_->CallRuntime(Runtime::kTraceExit, 1);
319 }
320
321 // Add a label for checking the size of the code used for returning.
322 Label check_exit_codesize;
323 masm_->bind(&check_exit_codesize);
324
325 // Tear down the frame which will restore the caller's frame pointer and
326 // the link register.
327 frame_->Exit();
328
329 // Here we use masm_-> instead of the __ macro to avoid the code coverage
330 // tool from instrumenting as we rely on the code size here.
331 masm_->add(sp, sp, Operand((scope_->num_parameters() + 1) * kPointerSize));
332 masm_->Jump(lr);
333
334 // Check that the size of the code used for returning matches what is
335 // expected by the debugger.
336 ASSERT_EQ(kJSReturnSequenceLength,
337 masm_->InstructionsGeneratedSince(&check_exit_codesize));
338 }
339
340 // Code generation state must be reset.
341 ASSERT(!has_cc());
342 ASSERT(state_ == NULL);
343 ASSERT(!function_return_is_shadowed_);
344 function_return_.Unuse();
345 DeleteFrame();
346
347 // Process any deferred code using the register allocator.
348 if (!HasStackOverflow()) {
349 ProcessDeferred();
350 }
351
352 allocator_ = NULL;
353 scope_ = NULL;
354}
355
356
357MemOperand CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
358 // Currently, this assertion will fail if we try to assign to
359 // a constant variable that is constant because it is read-only
360 // (such as the variable referring to a named function expression).
361 // We need to implement assignments to read-only variables.
362 // Ideally, we should do this during AST generation (by converting
363 // such assignments into expression statements); however, in general
364 // we may not be able to make the decision until past AST generation,
365 // that is when the entire program is known.
366 ASSERT(slot != NULL);
367 int index = slot->index();
368 switch (slot->type()) {
369 case Slot::PARAMETER:
370 return frame_->ParameterAt(index);
371
372 case Slot::LOCAL:
373 return frame_->LocalAt(index);
374
375 case Slot::CONTEXT: {
376 // Follow the context chain if necessary.
377 ASSERT(!tmp.is(cp)); // do not overwrite context register
378 Register context = cp;
379 int chain_length = scope()->ContextChainLength(slot->var()->scope());
380 for (int i = 0; i < chain_length; i++) {
381 // Load the closure.
382 // (All contexts, even 'with' contexts, have a closure,
383 // and it is the same for all contexts inside a function.
384 // There is no need to go to the function context first.)
385 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
386 // Load the function context (which is the incoming, outer context).
387 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
388 context = tmp;
389 }
390 // We may have a 'with' context now. Get the function context.
391 // (In fact this mov may never be the needed, since the scope analysis
392 // may not permit a direct context access in this case and thus we are
393 // always at a function context. However it is safe to dereference be-
394 // cause the function context of a function context is itself. Before
395 // deleting this mov we should try to create a counter-example first,
396 // though...)
397 __ ldr(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
398 return ContextOperand(tmp, index);
399 }
400
401 default:
402 UNREACHABLE();
403 return MemOperand(r0, 0);
404 }
405}
406
407
408MemOperand CodeGenerator::ContextSlotOperandCheckExtensions(
409 Slot* slot,
410 Register tmp,
411 Register tmp2,
412 JumpTarget* slow) {
413 ASSERT(slot->type() == Slot::CONTEXT);
414 Register context = cp;
415
416 for (Scope* s = scope(); s != slot->var()->scope(); s = s->outer_scope()) {
417 if (s->num_heap_slots() > 0) {
418 if (s->calls_eval()) {
419 // Check that extension is NULL.
420 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
421 __ tst(tmp2, tmp2);
422 slow->Branch(ne);
423 }
424 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
425 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
426 context = tmp;
427 }
428 }
429 // Check that last extension is NULL.
430 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
431 __ tst(tmp2, tmp2);
432 slow->Branch(ne);
433 __ ldr(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
434 return ContextOperand(tmp, slot->index());
435}
436
437
438// Loads a value on TOS. If it is a boolean value, the result may have been
439// (partially) translated into branches, or it may have set the condition
440// code register. If force_cc is set, the value is forced to set the
441// condition code register and no value is pushed. If the condition code
442// register was set, has_cc() is true and cc_reg_ contains the condition to
443// test for 'true'.
444void CodeGenerator::LoadCondition(Expression* x,
445 TypeofState typeof_state,
446 JumpTarget* true_target,
447 JumpTarget* false_target,
448 bool force_cc) {
449 ASSERT(!has_cc());
450 int original_height = frame_->height();
451
452 { CodeGenState new_state(this, typeof_state, true_target, false_target);
453 Visit(x);
454
455 // If we hit a stack overflow, we may not have actually visited
456 // the expression. In that case, we ensure that we have a
457 // valid-looking frame state because we will continue to generate
458 // code as we unwind the C++ stack.
459 //
460 // It's possible to have both a stack overflow and a valid frame
461 // state (eg, a subexpression overflowed, visiting it returned
462 // with a dummied frame state, and visiting this expression
463 // returned with a normal-looking state).
464 if (HasStackOverflow() &&
465 has_valid_frame() &&
466 !has_cc() &&
467 frame_->height() == original_height) {
468 true_target->Jump();
469 }
470 }
471 if (force_cc && frame_ != NULL && !has_cc()) {
472 // Convert the TOS value to a boolean in the condition code register.
473 ToBoolean(true_target, false_target);
474 }
475 ASSERT(!force_cc || !has_valid_frame() || has_cc());
476 ASSERT(!has_valid_frame() ||
477 (has_cc() && frame_->height() == original_height) ||
478 (!has_cc() && frame_->height() == original_height + 1));
479}
480
481
482void CodeGenerator::Load(Expression* x, TypeofState typeof_state) {
483#ifdef DEBUG
484 int original_height = frame_->height();
485#endif
486 JumpTarget true_target;
487 JumpTarget false_target;
488 LoadCondition(x, typeof_state, &true_target, &false_target, false);
489
490 if (has_cc()) {
491 // Convert cc_reg_ into a boolean value.
492 JumpTarget loaded;
493 JumpTarget materialize_true;
494 materialize_true.Branch(cc_reg_);
495 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
496 frame_->EmitPush(r0);
497 loaded.Jump();
498 materialize_true.Bind();
499 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
500 frame_->EmitPush(r0);
501 loaded.Bind();
502 cc_reg_ = al;
503 }
504
505 if (true_target.is_linked() || false_target.is_linked()) {
506 // We have at least one condition value that has been "translated"
507 // into a branch, thus it needs to be loaded explicitly.
508 JumpTarget loaded;
509 if (frame_ != NULL) {
510 loaded.Jump(); // Don't lose the current TOS.
511 }
512 bool both = true_target.is_linked() && false_target.is_linked();
513 // Load "true" if necessary.
514 if (true_target.is_linked()) {
515 true_target.Bind();
516 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
517 frame_->EmitPush(r0);
518 }
519 // If both "true" and "false" need to be loaded jump across the code for
520 // "false".
521 if (both) {
522 loaded.Jump();
523 }
524 // Load "false" if necessary.
525 if (false_target.is_linked()) {
526 false_target.Bind();
527 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
528 frame_->EmitPush(r0);
529 }
530 // A value is loaded on all paths reaching this point.
531 loaded.Bind();
532 }
533 ASSERT(has_valid_frame());
534 ASSERT(!has_cc());
535 ASSERT(frame_->height() == original_height + 1);
536}
537
538
539void CodeGenerator::LoadGlobal() {
540 VirtualFrame::SpilledScope spilled_scope;
541 __ ldr(r0, GlobalObject());
542 frame_->EmitPush(r0);
543}
544
545
546void CodeGenerator::LoadGlobalReceiver(Register scratch) {
547 VirtualFrame::SpilledScope spilled_scope;
548 __ ldr(scratch, ContextOperand(cp, Context::GLOBAL_INDEX));
549 __ ldr(scratch,
550 FieldMemOperand(scratch, GlobalObject::kGlobalReceiverOffset));
551 frame_->EmitPush(scratch);
552}
553
554
555// TODO(1241834): Get rid of this function in favor of just using Load, now
556// that we have the INSIDE_TYPEOF typeof state. => Need to handle global
557// variables w/o reference errors elsewhere.
558void CodeGenerator::LoadTypeofExpression(Expression* x) {
559 VirtualFrame::SpilledScope spilled_scope;
560 Variable* variable = x->AsVariableProxy()->AsVariable();
561 if (variable != NULL && !variable->is_this() && variable->is_global()) {
562 // NOTE: This is somewhat nasty. We force the compiler to load
563 // the variable as if through '<global>.<variable>' to make sure we
564 // do not get reference errors.
565 Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
566 Literal key(variable->name());
567 // TODO(1241834): Fetch the position from the variable instead of using
568 // no position.
569 Property property(&global, &key, RelocInfo::kNoPosition);
570 LoadAndSpill(&property);
571 } else {
572 LoadAndSpill(x, INSIDE_TYPEOF);
573 }
574}
575
576
577Reference::Reference(CodeGenerator* cgen, Expression* expression)
578 : cgen_(cgen), expression_(expression), type_(ILLEGAL) {
579 cgen->LoadReference(this);
580}
581
582
583Reference::~Reference() {
584 cgen_->UnloadReference(this);
585}
586
587
588void CodeGenerator::LoadReference(Reference* ref) {
589 VirtualFrame::SpilledScope spilled_scope;
590 Comment cmnt(masm_, "[ LoadReference");
591 Expression* e = ref->expression();
592 Property* property = e->AsProperty();
593 Variable* var = e->AsVariableProxy()->AsVariable();
594
595 if (property != NULL) {
596 // The expression is either a property or a variable proxy that rewrites
597 // to a property.
598 LoadAndSpill(property->obj());
599 // We use a named reference if the key is a literal symbol, unless it is
600 // a string that can be legally parsed as an integer. This is because
601 // otherwise we will not get into the slow case code that handles [] on
602 // String objects.
603 Literal* literal = property->key()->AsLiteral();
604 uint32_t dummy;
605 if (literal != NULL &&
606 literal->handle()->IsSymbol() &&
607 !String::cast(*(literal->handle()))->AsArrayIndex(&dummy)) {
608 ref->set_type(Reference::NAMED);
609 } else {
610 LoadAndSpill(property->key());
611 ref->set_type(Reference::KEYED);
612 }
613 } else if (var != NULL) {
614 // The expression is a variable proxy that does not rewrite to a
615 // property. Global variables are treated as named property references.
616 if (var->is_global()) {
617 LoadGlobal();
618 ref->set_type(Reference::NAMED);
619 } else {
620 ASSERT(var->slot() != NULL);
621 ref->set_type(Reference::SLOT);
622 }
623 } else {
624 // Anything else is a runtime error.
625 LoadAndSpill(e);
626 frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
627 }
628}
629
630
631void CodeGenerator::UnloadReference(Reference* ref) {
632 VirtualFrame::SpilledScope spilled_scope;
633 // Pop a reference from the stack while preserving TOS.
634 Comment cmnt(masm_, "[ UnloadReference");
635 int size = ref->size();
636 if (size > 0) {
637 frame_->EmitPop(r0);
638 frame_->Drop(size);
639 frame_->EmitPush(r0);
640 }
641}
642
643
644// ECMA-262, section 9.2, page 30: ToBoolean(). Convert the given
645// register to a boolean in the condition code register. The code
646// may jump to 'false_target' in case the register converts to 'false'.
647void CodeGenerator::ToBoolean(JumpTarget* true_target,
648 JumpTarget* false_target) {
649 VirtualFrame::SpilledScope spilled_scope;
650 // Note: The generated code snippet does not change stack variables.
651 // Only the condition code should be set.
652 frame_->EmitPop(r0);
653
654 // Fast case checks
655
656 // Check if the value is 'false'.
657 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
658 __ cmp(r0, ip);
659 false_target->Branch(eq);
660
661 // Check if the value is 'true'.
662 __ LoadRoot(ip, Heap::kTrueValueRootIndex);
663 __ cmp(r0, ip);
664 true_target->Branch(eq);
665
666 // Check if the value is 'undefined'.
667 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
668 __ cmp(r0, ip);
669 false_target->Branch(eq);
670
671 // Check if the value is a smi.
672 __ cmp(r0, Operand(Smi::FromInt(0)));
673 false_target->Branch(eq);
674 __ tst(r0, Operand(kSmiTagMask));
675 true_target->Branch(eq);
676
677 // Slow case: call the runtime.
678 frame_->EmitPush(r0);
679 frame_->CallRuntime(Runtime::kToBool, 1);
680 // Convert the result (r0) to a condition code.
681 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
682 __ cmp(r0, ip);
683
684 cc_reg_ = ne;
685}
686
687
688void CodeGenerator::GenericBinaryOperation(Token::Value op,
689 OverwriteMode overwrite_mode,
690 int constant_rhs) {
691 VirtualFrame::SpilledScope spilled_scope;
692 // sp[0] : y
693 // sp[1] : x
694 // result : r0
695
696 // Stub is entered with a call: 'return address' is in lr.
697 switch (op) {
698 case Token::ADD: // fall through.
699 case Token::SUB: // fall through.
700 case Token::MUL:
701 case Token::DIV:
702 case Token::MOD:
703 case Token::BIT_OR:
704 case Token::BIT_AND:
705 case Token::BIT_XOR:
706 case Token::SHL:
707 case Token::SHR:
708 case Token::SAR: {
709 frame_->EmitPop(r0); // r0 : y
710 frame_->EmitPop(r1); // r1 : x
711 GenericBinaryOpStub stub(op, overwrite_mode, constant_rhs);
712 frame_->CallStub(&stub, 0);
713 break;
714 }
715
716 case Token::COMMA:
717 frame_->EmitPop(r0);
718 // simply discard left value
719 frame_->Drop();
720 break;
721
722 default:
723 // Other cases should have been handled before this point.
724 UNREACHABLE();
725 break;
726 }
727}
728
729
730class DeferredInlineSmiOperation: public DeferredCode {
731 public:
732 DeferredInlineSmiOperation(Token::Value op,
733 int value,
734 bool reversed,
735 OverwriteMode overwrite_mode)
736 : op_(op),
737 value_(value),
738 reversed_(reversed),
739 overwrite_mode_(overwrite_mode) {
740 set_comment("[ DeferredInlinedSmiOperation");
741 }
742
743 virtual void Generate();
744
745 private:
746 Token::Value op_;
747 int value_;
748 bool reversed_;
749 OverwriteMode overwrite_mode_;
750};
751
752
753void DeferredInlineSmiOperation::Generate() {
754 switch (op_) {
755 case Token::ADD: {
756 // Revert optimistic add.
757 if (reversed_) {
758 __ sub(r0, r0, Operand(Smi::FromInt(value_)));
759 __ mov(r1, Operand(Smi::FromInt(value_)));
760 } else {
761 __ sub(r1, r0, Operand(Smi::FromInt(value_)));
762 __ mov(r0, Operand(Smi::FromInt(value_)));
763 }
764 break;
765 }
766
767 case Token::SUB: {
768 // Revert optimistic sub.
769 if (reversed_) {
770 __ rsb(r0, r0, Operand(Smi::FromInt(value_)));
771 __ mov(r1, Operand(Smi::FromInt(value_)));
772 } else {
773 __ add(r1, r0, Operand(Smi::FromInt(value_)));
774 __ mov(r0, Operand(Smi::FromInt(value_)));
775 }
776 break;
777 }
778
779 // For these operations there is no optimistic operation that needs to be
780 // reverted.
781 case Token::MUL:
782 case Token::MOD:
783 case Token::BIT_OR:
784 case Token::BIT_XOR:
785 case Token::BIT_AND: {
786 if (reversed_) {
787 __ mov(r1, Operand(Smi::FromInt(value_)));
788 } else {
789 __ mov(r1, Operand(r0));
790 __ mov(r0, Operand(Smi::FromInt(value_)));
791 }
792 break;
793 }
794
795 case Token::SHL:
796 case Token::SHR:
797 case Token::SAR: {
798 if (!reversed_) {
799 __ mov(r1, Operand(r0));
800 __ mov(r0, Operand(Smi::FromInt(value_)));
801 } else {
802 UNREACHABLE(); // Should have been handled in SmiOperation.
803 }
804 break;
805 }
806
807 default:
808 // Other cases should have been handled before this point.
809 UNREACHABLE();
810 break;
811 }
812
813 GenericBinaryOpStub stub(op_, overwrite_mode_, value_);
814 __ CallStub(&stub);
815}
816
817
818static bool PopCountLessThanEqual2(unsigned int x) {
819 x &= x - 1;
820 return (x & (x - 1)) == 0;
821}
822
823
824// Returns the index of the lowest bit set.
825static int BitPosition(unsigned x) {
826 int bit_posn = 0;
827 while ((x & 0xf) == 0) {
828 bit_posn += 4;
829 x >>= 4;
830 }
831 while ((x & 1) == 0) {
832 bit_posn++;
833 x >>= 1;
834 }
835 return bit_posn;
836}
837
838
839void CodeGenerator::SmiOperation(Token::Value op,
840 Handle<Object> value,
841 bool reversed,
842 OverwriteMode mode) {
843 VirtualFrame::SpilledScope spilled_scope;
844 // NOTE: This is an attempt to inline (a bit) more of the code for
845 // some possible smi operations (like + and -) when (at least) one
846 // of the operands is a literal smi. With this optimization, the
847 // performance of the system is increased by ~15%, and the generated
848 // code size is increased by ~1% (measured on a combination of
849 // different benchmarks).
850
851 // sp[0] : operand
852
853 int int_value = Smi::cast(*value)->value();
854
855 JumpTarget exit;
856 frame_->EmitPop(r0);
857
858 bool something_to_inline = true;
859 switch (op) {
860 case Token::ADD: {
861 DeferredCode* deferred =
862 new DeferredInlineSmiOperation(op, int_value, reversed, mode);
863
864 __ add(r0, r0, Operand(value), SetCC);
865 deferred->Branch(vs);
866 __ tst(r0, Operand(kSmiTagMask));
867 deferred->Branch(ne);
868 deferred->BindExit();
869 break;
870 }
871
872 case Token::SUB: {
873 DeferredCode* deferred =
874 new DeferredInlineSmiOperation(op, int_value, reversed, mode);
875
876 if (reversed) {
877 __ rsb(r0, r0, Operand(value), SetCC);
878 } else {
879 __ sub(r0, r0, Operand(value), SetCC);
880 }
881 deferred->Branch(vs);
882 __ tst(r0, Operand(kSmiTagMask));
883 deferred->Branch(ne);
884 deferred->BindExit();
885 break;
886 }
887
888
889 case Token::BIT_OR:
890 case Token::BIT_XOR:
891 case Token::BIT_AND: {
892 DeferredCode* deferred =
893 new DeferredInlineSmiOperation(op, int_value, reversed, mode);
894 __ tst(r0, Operand(kSmiTagMask));
895 deferred->Branch(ne);
896 switch (op) {
897 case Token::BIT_OR: __ orr(r0, r0, Operand(value)); break;
898 case Token::BIT_XOR: __ eor(r0, r0, Operand(value)); break;
899 case Token::BIT_AND: __ and_(r0, r0, Operand(value)); break;
900 default: UNREACHABLE();
901 }
902 deferred->BindExit();
903 break;
904 }
905
906 case Token::SHL:
907 case Token::SHR:
908 case Token::SAR: {
909 if (reversed) {
910 something_to_inline = false;
911 break;
912 }
913 int shift_value = int_value & 0x1f; // least significant 5 bits
914 DeferredCode* deferred =
915 new DeferredInlineSmiOperation(op, shift_value, false, mode);
916 __ tst(r0, Operand(kSmiTagMask));
917 deferred->Branch(ne);
918 __ mov(r2, Operand(r0, ASR, kSmiTagSize)); // remove tags
919 switch (op) {
920 case Token::SHL: {
921 if (shift_value != 0) {
922 __ mov(r2, Operand(r2, LSL, shift_value));
923 }
924 // check that the *unsigned* result fits in a smi
925 __ add(r3, r2, Operand(0x40000000), SetCC);
926 deferred->Branch(mi);
927 break;
928 }
929 case Token::SHR: {
930 // LSR by immediate 0 means shifting 32 bits.
931 if (shift_value != 0) {
932 __ mov(r2, Operand(r2, LSR, shift_value));
933 }
934 // check that the *unsigned* result fits in a smi
935 // neither of the two high-order bits can be set:
936 // - 0x80000000: high bit would be lost when smi tagging
937 // - 0x40000000: this number would convert to negative when
938 // smi tagging these two cases can only happen with shifts
939 // by 0 or 1 when handed a valid smi
940 __ and_(r3, r2, Operand(0xc0000000), SetCC);
941 deferred->Branch(ne);
942 break;
943 }
944 case Token::SAR: {
945 if (shift_value != 0) {
946 // ASR by immediate 0 means shifting 32 bits.
947 __ mov(r2, Operand(r2, ASR, shift_value));
948 }
949 break;
950 }
951 default: UNREACHABLE();
952 }
953 __ mov(r0, Operand(r2, LSL, kSmiTagSize));
954 deferred->BindExit();
955 break;
956 }
957
958 case Token::MOD: {
959 if (reversed || int_value < 2 || !IsPowerOf2(int_value)) {
960 something_to_inline = false;
961 break;
962 }
963 DeferredCode* deferred =
964 new DeferredInlineSmiOperation(op, int_value, reversed, mode);
965 unsigned mask = (0x80000000u | kSmiTagMask);
966 __ tst(r0, Operand(mask));
967 deferred->Branch(ne); // Go to deferred code on non-Smis and negative.
968 mask = (int_value << kSmiTagSize) - 1;
969 __ and_(r0, r0, Operand(mask));
970 deferred->BindExit();
971 break;
972 }
973
974 case Token::MUL: {
975 if (!IsEasyToMultiplyBy(int_value)) {
976 something_to_inline = false;
977 break;
978 }
979 DeferredCode* deferred =
980 new DeferredInlineSmiOperation(op, int_value, reversed, mode);
981 unsigned max_smi_that_wont_overflow = Smi::kMaxValue / int_value;
982 max_smi_that_wont_overflow <<= kSmiTagSize;
983 unsigned mask = 0x80000000u;
984 while ((mask & max_smi_that_wont_overflow) == 0) {
985 mask |= mask >> 1;
986 }
987 mask |= kSmiTagMask;
988 // This does a single mask that checks for a too high value in a
989 // conservative way and for a non-Smi. It also filters out negative
990 // numbers, unfortunately, but since this code is inline we prefer
991 // brevity to comprehensiveness.
992 __ tst(r0, Operand(mask));
993 deferred->Branch(ne);
994 MultiplyByKnownInt(masm_, r0, r0, int_value);
995 deferred->BindExit();
996 break;
997 }
998
999 default:
1000 something_to_inline = false;
1001 break;
1002 }
1003
1004 if (!something_to_inline) {
1005 if (!reversed) {
1006 frame_->EmitPush(r0);
1007 __ mov(r0, Operand(value));
1008 frame_->EmitPush(r0);
1009 GenericBinaryOperation(op, mode, int_value);
1010 } else {
1011 __ mov(ip, Operand(value));
1012 frame_->EmitPush(ip);
1013 frame_->EmitPush(r0);
1014 GenericBinaryOperation(op, mode, kUnknownIntValue);
1015 }
1016 }
1017
1018 exit.Bind();
1019}
1020
1021
1022void CodeGenerator::Comparison(Condition cc,
1023 Expression* left,
1024 Expression* right,
1025 bool strict) {
1026 if (left != NULL) LoadAndSpill(left);
1027 if (right != NULL) LoadAndSpill(right);
1028
1029 VirtualFrame::SpilledScope spilled_scope;
1030 // sp[0] : y
1031 // sp[1] : x
1032 // result : cc register
1033
1034 // Strict only makes sense for equality comparisons.
1035 ASSERT(!strict || cc == eq);
1036
1037 JumpTarget exit;
1038 JumpTarget smi;
1039 // Implement '>' and '<=' by reversal to obtain ECMA-262 conversion order.
1040 if (cc == gt || cc == le) {
1041 cc = ReverseCondition(cc);
1042 frame_->EmitPop(r1);
1043 frame_->EmitPop(r0);
1044 } else {
1045 frame_->EmitPop(r0);
1046 frame_->EmitPop(r1);
1047 }
1048 __ orr(r2, r0, Operand(r1));
1049 __ tst(r2, Operand(kSmiTagMask));
1050 smi.Branch(eq);
1051
1052 // Perform non-smi comparison by stub.
1053 // CompareStub takes arguments in r0 and r1, returns <0, >0 or 0 in r0.
1054 // We call with 0 args because there are 0 on the stack.
1055 CompareStub stub(cc, strict);
1056 frame_->CallStub(&stub, 0);
1057 __ cmp(r0, Operand(0));
1058 exit.Jump();
1059
1060 // Do smi comparisons by pointer comparison.
1061 smi.Bind();
1062 __ cmp(r1, Operand(r0));
1063
1064 exit.Bind();
1065 cc_reg_ = cc;
1066}
1067
1068
1069class CallFunctionStub: public CodeStub {
1070 public:
1071 CallFunctionStub(int argc, InLoopFlag in_loop)
1072 : argc_(argc), in_loop_(in_loop) {}
1073
1074 void Generate(MacroAssembler* masm);
1075
1076 private:
1077 int argc_;
1078 InLoopFlag in_loop_;
1079
1080#if defined(DEBUG)
1081 void Print() { PrintF("CallFunctionStub (argc %d)\n", argc_); }
1082#endif // defined(DEBUG)
1083
1084 Major MajorKey() { return CallFunction; }
1085 int MinorKey() { return argc_; }
1086 InLoopFlag InLoop() { return in_loop_; }
1087};
1088
1089
1090// Call the function on the stack with the given arguments.
1091void CodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
1092 int position) {
1093 VirtualFrame::SpilledScope spilled_scope;
1094 // Push the arguments ("left-to-right") on the stack.
1095 int arg_count = args->length();
1096 for (int i = 0; i < arg_count; i++) {
1097 LoadAndSpill(args->at(i));
1098 }
1099
1100 // Record the position for debugging purposes.
1101 CodeForSourcePosition(position);
1102
1103 // Use the shared code stub to call the function.
1104 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
1105 CallFunctionStub call_function(arg_count, in_loop);
1106 frame_->CallStub(&call_function, arg_count + 1);
1107
1108 // Restore context and pop function from the stack.
1109 __ ldr(cp, frame_->Context());
1110 frame_->Drop(); // discard the TOS
1111}
1112
1113
1114void CodeGenerator::Branch(bool if_true, JumpTarget* target) {
1115 VirtualFrame::SpilledScope spilled_scope;
1116 ASSERT(has_cc());
1117 Condition cc = if_true ? cc_reg_ : NegateCondition(cc_reg_);
1118 target->Branch(cc);
1119 cc_reg_ = al;
1120}
1121
1122
1123void CodeGenerator::CheckStack() {
1124 VirtualFrame::SpilledScope spilled_scope;
1125 if (FLAG_check_stack) {
1126 Comment cmnt(masm_, "[ check stack");
1127 __ LoadRoot(ip, Heap::kStackLimitRootIndex);
1128 // Put the lr setup instruction in the delay slot. kInstrSize is added to
1129 // the implicit 8 byte offset that always applies to operations with pc and
1130 // gives a return address 12 bytes down.
1131 masm_->add(lr, pc, Operand(Assembler::kInstrSize));
1132 masm_->cmp(sp, Operand(ip));
1133 StackCheckStub stub;
1134 // Call the stub if lower.
1135 masm_->mov(pc,
1136 Operand(reinterpret_cast<intptr_t>(stub.GetCode().location()),
1137 RelocInfo::CODE_TARGET),
1138 LeaveCC,
1139 lo);
1140 }
1141}
1142
1143
1144void CodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
1145#ifdef DEBUG
1146 int original_height = frame_->height();
1147#endif
1148 VirtualFrame::SpilledScope spilled_scope;
1149 for (int i = 0; frame_ != NULL && i < statements->length(); i++) {
1150 VisitAndSpill(statements->at(i));
1151 }
1152 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1153}
1154
1155
1156void CodeGenerator::VisitBlock(Block* node) {
1157#ifdef DEBUG
1158 int original_height = frame_->height();
1159#endif
1160 VirtualFrame::SpilledScope spilled_scope;
1161 Comment cmnt(masm_, "[ Block");
1162 CodeForStatementPosition(node);
1163 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1164 VisitStatementsAndSpill(node->statements());
1165 if (node->break_target()->is_linked()) {
1166 node->break_target()->Bind();
1167 }
1168 node->break_target()->Unuse();
1169 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1170}
1171
1172
1173void CodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
1174 VirtualFrame::SpilledScope spilled_scope;
1175 __ mov(r0, Operand(pairs));
1176 frame_->EmitPush(r0);
1177 frame_->EmitPush(cp);
1178 __ mov(r0, Operand(Smi::FromInt(is_eval() ? 1 : 0)));
1179 frame_->EmitPush(r0);
1180 frame_->CallRuntime(Runtime::kDeclareGlobals, 3);
1181 // The result is discarded.
1182}
1183
1184
1185void CodeGenerator::VisitDeclaration(Declaration* node) {
1186#ifdef DEBUG
1187 int original_height = frame_->height();
1188#endif
1189 VirtualFrame::SpilledScope spilled_scope;
1190 Comment cmnt(masm_, "[ Declaration");
1191 Variable* var = node->proxy()->var();
1192 ASSERT(var != NULL); // must have been resolved
1193 Slot* slot = var->slot();
1194
1195 // If it was not possible to allocate the variable at compile time,
1196 // we need to "declare" it at runtime to make sure it actually
1197 // exists in the local context.
1198 if (slot != NULL && slot->type() == Slot::LOOKUP) {
1199 // Variables with a "LOOKUP" slot were introduced as non-locals
1200 // during variable resolution and must have mode DYNAMIC.
1201 ASSERT(var->is_dynamic());
1202 // For now, just do a runtime call.
1203 frame_->EmitPush(cp);
1204 __ mov(r0, Operand(var->name()));
1205 frame_->EmitPush(r0);
1206 // Declaration nodes are always declared in only two modes.
1207 ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
1208 PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
1209 __ mov(r0, Operand(Smi::FromInt(attr)));
1210 frame_->EmitPush(r0);
1211 // Push initial value, if any.
1212 // Note: For variables we must not push an initial value (such as
1213 // 'undefined') because we may have a (legal) redeclaration and we
1214 // must not destroy the current value.
1215 if (node->mode() == Variable::CONST) {
1216 __ LoadRoot(r0, Heap::kTheHoleValueRootIndex);
1217 frame_->EmitPush(r0);
1218 } else if (node->fun() != NULL) {
1219 LoadAndSpill(node->fun());
1220 } else {
1221 __ mov(r0, Operand(0)); // no initial value!
1222 frame_->EmitPush(r0);
1223 }
1224 frame_->CallRuntime(Runtime::kDeclareContextSlot, 4);
1225 // Ignore the return value (declarations are statements).
1226 ASSERT(frame_->height() == original_height);
1227 return;
1228 }
1229
1230 ASSERT(!var->is_global());
1231
1232 // If we have a function or a constant, we need to initialize the variable.
1233 Expression* val = NULL;
1234 if (node->mode() == Variable::CONST) {
1235 val = new Literal(Factory::the_hole_value());
1236 } else {
1237 val = node->fun(); // NULL if we don't have a function
1238 }
1239
1240 if (val != NULL) {
1241 {
1242 // Set initial value.
1243 Reference target(this, node->proxy());
1244 LoadAndSpill(val);
1245 target.SetValue(NOT_CONST_INIT);
1246 // The reference is removed from the stack (preserving TOS) when
1247 // it goes out of scope.
1248 }
1249 // Get rid of the assigned value (declarations are statements).
1250 frame_->Drop();
1251 }
1252 ASSERT(frame_->height() == original_height);
1253}
1254
1255
1256void CodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
1257#ifdef DEBUG
1258 int original_height = frame_->height();
1259#endif
1260 VirtualFrame::SpilledScope spilled_scope;
1261 Comment cmnt(masm_, "[ ExpressionStatement");
1262 CodeForStatementPosition(node);
1263 Expression* expression = node->expression();
1264 expression->MarkAsStatement();
1265 LoadAndSpill(expression);
1266 frame_->Drop();
1267 ASSERT(frame_->height() == original_height);
1268}
1269
1270
1271void CodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
1272#ifdef DEBUG
1273 int original_height = frame_->height();
1274#endif
1275 VirtualFrame::SpilledScope spilled_scope;
1276 Comment cmnt(masm_, "// EmptyStatement");
1277 CodeForStatementPosition(node);
1278 // nothing to do
1279 ASSERT(frame_->height() == original_height);
1280}
1281
1282
1283void CodeGenerator::VisitIfStatement(IfStatement* node) {
1284#ifdef DEBUG
1285 int original_height = frame_->height();
1286#endif
1287 VirtualFrame::SpilledScope spilled_scope;
1288 Comment cmnt(masm_, "[ IfStatement");
1289 // Generate different code depending on which parts of the if statement
1290 // are present or not.
1291 bool has_then_stm = node->HasThenStatement();
1292 bool has_else_stm = node->HasElseStatement();
1293
1294 CodeForStatementPosition(node);
1295
1296 JumpTarget exit;
1297 if (has_then_stm && has_else_stm) {
1298 Comment cmnt(masm_, "[ IfThenElse");
1299 JumpTarget then;
1300 JumpTarget else_;
1301 // if (cond)
1302 LoadConditionAndSpill(node->condition(), NOT_INSIDE_TYPEOF,
1303 &then, &else_, true);
1304 if (frame_ != NULL) {
1305 Branch(false, &else_);
1306 }
1307 // then
1308 if (frame_ != NULL || then.is_linked()) {
1309 then.Bind();
1310 VisitAndSpill(node->then_statement());
1311 }
1312 if (frame_ != NULL) {
1313 exit.Jump();
1314 }
1315 // else
1316 if (else_.is_linked()) {
1317 else_.Bind();
1318 VisitAndSpill(node->else_statement());
1319 }
1320
1321 } else if (has_then_stm) {
1322 Comment cmnt(masm_, "[ IfThen");
1323 ASSERT(!has_else_stm);
1324 JumpTarget then;
1325 // if (cond)
1326 LoadConditionAndSpill(node->condition(), NOT_INSIDE_TYPEOF,
1327 &then, &exit, true);
1328 if (frame_ != NULL) {
1329 Branch(false, &exit);
1330 }
1331 // then
1332 if (frame_ != NULL || then.is_linked()) {
1333 then.Bind();
1334 VisitAndSpill(node->then_statement());
1335 }
1336
1337 } else if (has_else_stm) {
1338 Comment cmnt(masm_, "[ IfElse");
1339 ASSERT(!has_then_stm);
1340 JumpTarget else_;
1341 // if (!cond)
1342 LoadConditionAndSpill(node->condition(), NOT_INSIDE_TYPEOF,
1343 &exit, &else_, true);
1344 if (frame_ != NULL) {
1345 Branch(true, &exit);
1346 }
1347 // else
1348 if (frame_ != NULL || else_.is_linked()) {
1349 else_.Bind();
1350 VisitAndSpill(node->else_statement());
1351 }
1352
1353 } else {
1354 Comment cmnt(masm_, "[ If");
1355 ASSERT(!has_then_stm && !has_else_stm);
1356 // if (cond)
1357 LoadConditionAndSpill(node->condition(), NOT_INSIDE_TYPEOF,
1358 &exit, &exit, false);
1359 if (frame_ != NULL) {
1360 if (has_cc()) {
1361 cc_reg_ = al;
1362 } else {
1363 frame_->Drop();
1364 }
1365 }
1366 }
1367
1368 // end
1369 if (exit.is_linked()) {
1370 exit.Bind();
1371 }
1372 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1373}
1374
1375
1376void CodeGenerator::VisitContinueStatement(ContinueStatement* node) {
1377 VirtualFrame::SpilledScope spilled_scope;
1378 Comment cmnt(masm_, "[ ContinueStatement");
1379 CodeForStatementPosition(node);
1380 node->target()->continue_target()->Jump();
1381}
1382
1383
1384void CodeGenerator::VisitBreakStatement(BreakStatement* node) {
1385 VirtualFrame::SpilledScope spilled_scope;
1386 Comment cmnt(masm_, "[ BreakStatement");
1387 CodeForStatementPosition(node);
1388 node->target()->break_target()->Jump();
1389}
1390
1391
1392void CodeGenerator::VisitReturnStatement(ReturnStatement* node) {
1393 VirtualFrame::SpilledScope spilled_scope;
1394 Comment cmnt(masm_, "[ ReturnStatement");
1395
1396 CodeForStatementPosition(node);
1397 LoadAndSpill(node->expression());
1398 if (function_return_is_shadowed_) {
1399 frame_->EmitPop(r0);
1400 function_return_.Jump();
1401 } else {
1402 // Pop the result from the frame and prepare the frame for
1403 // returning thus making it easier to merge.
1404 frame_->EmitPop(r0);
1405 frame_->PrepareForReturn();
1406
1407 function_return_.Jump();
1408 }
1409}
1410
1411
1412void CodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
1413#ifdef DEBUG
1414 int original_height = frame_->height();
1415#endif
1416 VirtualFrame::SpilledScope spilled_scope;
1417 Comment cmnt(masm_, "[ WithEnterStatement");
1418 CodeForStatementPosition(node);
1419 LoadAndSpill(node->expression());
1420 if (node->is_catch_block()) {
1421 frame_->CallRuntime(Runtime::kPushCatchContext, 1);
1422 } else {
1423 frame_->CallRuntime(Runtime::kPushContext, 1);
1424 }
1425#ifdef DEBUG
1426 JumpTarget verified_true;
1427 __ cmp(r0, Operand(cp));
1428 verified_true.Branch(eq);
1429 __ stop("PushContext: r0 is expected to be the same as cp");
1430 verified_true.Bind();
1431#endif
1432 // Update context local.
1433 __ str(cp, frame_->Context());
1434 ASSERT(frame_->height() == original_height);
1435}
1436
1437
1438void CodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
1439#ifdef DEBUG
1440 int original_height = frame_->height();
1441#endif
1442 VirtualFrame::SpilledScope spilled_scope;
1443 Comment cmnt(masm_, "[ WithExitStatement");
1444 CodeForStatementPosition(node);
1445 // Pop context.
1446 __ ldr(cp, ContextOperand(cp, Context::PREVIOUS_INDEX));
1447 // Update context local.
1448 __ str(cp, frame_->Context());
1449 ASSERT(frame_->height() == original_height);
1450}
1451
1452
1453void CodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
1454#ifdef DEBUG
1455 int original_height = frame_->height();
1456#endif
1457 VirtualFrame::SpilledScope spilled_scope;
1458 Comment cmnt(masm_, "[ SwitchStatement");
1459 CodeForStatementPosition(node);
1460 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1461
1462 LoadAndSpill(node->tag());
1463
1464 JumpTarget next_test;
1465 JumpTarget fall_through;
1466 JumpTarget default_entry;
1467 JumpTarget default_exit(JumpTarget::BIDIRECTIONAL);
1468 ZoneList<CaseClause*>* cases = node->cases();
1469 int length = cases->length();
1470 CaseClause* default_clause = NULL;
1471
1472 for (int i = 0; i < length; i++) {
1473 CaseClause* clause = cases->at(i);
1474 if (clause->is_default()) {
1475 // Remember the default clause and compile it at the end.
1476 default_clause = clause;
1477 continue;
1478 }
1479
1480 Comment cmnt(masm_, "[ Case clause");
1481 // Compile the test.
1482 next_test.Bind();
1483 next_test.Unuse();
1484 // Duplicate TOS.
1485 __ ldr(r0, frame_->Top());
1486 frame_->EmitPush(r0);
1487 Comparison(eq, NULL, clause->label(), true);
1488 Branch(false, &next_test);
1489
1490 // Before entering the body from the test, remove the switch value from
1491 // the stack.
1492 frame_->Drop();
1493
1494 // Label the body so that fall through is enabled.
1495 if (i > 0 && cases->at(i - 1)->is_default()) {
1496 default_exit.Bind();
1497 } else {
1498 fall_through.Bind();
1499 fall_through.Unuse();
1500 }
1501 VisitStatementsAndSpill(clause->statements());
1502
1503 // If control flow can fall through from the body, jump to the next body
1504 // or the end of the statement.
1505 if (frame_ != NULL) {
1506 if (i < length - 1 && cases->at(i + 1)->is_default()) {
1507 default_entry.Jump();
1508 } else {
1509 fall_through.Jump();
1510 }
1511 }
1512 }
1513
1514 // The final "test" removes the switch value.
1515 next_test.Bind();
1516 frame_->Drop();
1517
1518 // If there is a default clause, compile it.
1519 if (default_clause != NULL) {
1520 Comment cmnt(masm_, "[ Default clause");
1521 default_entry.Bind();
1522 VisitStatementsAndSpill(default_clause->statements());
1523 // If control flow can fall out of the default and there is a case after
1524 // it, jup to that case's body.
1525 if (frame_ != NULL && default_exit.is_bound()) {
1526 default_exit.Jump();
1527 }
1528 }
1529
1530 if (fall_through.is_linked()) {
1531 fall_through.Bind();
1532 }
1533
1534 if (node->break_target()->is_linked()) {
1535 node->break_target()->Bind();
1536 }
1537 node->break_target()->Unuse();
1538 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1539}
1540
1541
1542void CodeGenerator::VisitLoopStatement(LoopStatement* node) {
1543#ifdef DEBUG
1544 int original_height = frame_->height();
1545#endif
1546 VirtualFrame::SpilledScope spilled_scope;
1547 Comment cmnt(masm_, "[ LoopStatement");
1548 CodeForStatementPosition(node);
1549 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1550
1551 // Simple condition analysis. ALWAYS_TRUE and ALWAYS_FALSE represent a
1552 // known result for the test expression, with no side effects.
1553 enum { ALWAYS_TRUE, ALWAYS_FALSE, DONT_KNOW } info = DONT_KNOW;
1554 if (node->cond() == NULL) {
1555 ASSERT(node->type() == LoopStatement::FOR_LOOP);
1556 info = ALWAYS_TRUE;
1557 } else {
1558 Literal* lit = node->cond()->AsLiteral();
1559 if (lit != NULL) {
1560 if (lit->IsTrue()) {
1561 info = ALWAYS_TRUE;
1562 } else if (lit->IsFalse()) {
1563 info = ALWAYS_FALSE;
1564 }
1565 }
1566 }
1567
1568 switch (node->type()) {
1569 case LoopStatement::DO_LOOP: {
1570 JumpTarget body(JumpTarget::BIDIRECTIONAL);
1571
1572 // Label the top of the loop for the backward CFG edge. If the test
1573 // is always true we can use the continue target, and if the test is
1574 // always false there is no need.
1575 if (info == ALWAYS_TRUE) {
1576 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
1577 node->continue_target()->Bind();
1578 } else if (info == ALWAYS_FALSE) {
1579 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1580 } else {
1581 ASSERT(info == DONT_KNOW);
1582 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1583 body.Bind();
1584 }
1585
1586 CheckStack(); // TODO(1222600): ignore if body contains calls.
1587 VisitAndSpill(node->body());
1588
1589 // Compile the test.
1590 if (info == ALWAYS_TRUE) {
1591 if (has_valid_frame()) {
1592 // If control can fall off the end of the body, jump back to the
1593 // top.
1594 node->continue_target()->Jump();
1595 }
1596 } else if (info == ALWAYS_FALSE) {
1597 // If we have a continue in the body, we only have to bind its jump
1598 // target.
1599 if (node->continue_target()->is_linked()) {
1600 node->continue_target()->Bind();
1601 }
1602 } else {
1603 ASSERT(info == DONT_KNOW);
1604 // We have to compile the test expression if it can be reached by
1605 // control flow falling out of the body or via continue.
1606 if (node->continue_target()->is_linked()) {
1607 node->continue_target()->Bind();
1608 }
1609 if (has_valid_frame()) {
1610 LoadConditionAndSpill(node->cond(), NOT_INSIDE_TYPEOF,
1611 &body, node->break_target(), true);
1612 if (has_valid_frame()) {
1613 // A invalid frame here indicates that control did not
1614 // fall out of the test expression.
1615 Branch(true, &body);
1616 }
1617 }
1618 }
1619 break;
1620 }
1621
1622 case LoopStatement::WHILE_LOOP: {
1623 // If the test is never true and has no side effects there is no need
1624 // to compile the test or body.
1625 if (info == ALWAYS_FALSE) break;
1626
1627 // Label the top of the loop with the continue target for the backward
1628 // CFG edge.
1629 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
1630 node->continue_target()->Bind();
1631
1632 if (info == DONT_KNOW) {
1633 JumpTarget body;
1634 LoadConditionAndSpill(node->cond(), NOT_INSIDE_TYPEOF,
1635 &body, node->break_target(), true);
1636 if (has_valid_frame()) {
1637 // A NULL frame indicates that control did not fall out of the
1638 // test expression.
1639 Branch(false, node->break_target());
1640 }
1641 if (has_valid_frame() || body.is_linked()) {
1642 body.Bind();
1643 }
1644 }
1645
1646 if (has_valid_frame()) {
1647 CheckStack(); // TODO(1222600): ignore if body contains calls.
1648 VisitAndSpill(node->body());
1649
1650 // If control flow can fall out of the body, jump back to the top.
1651 if (has_valid_frame()) {
1652 node->continue_target()->Jump();
1653 }
1654 }
1655 break;
1656 }
1657
1658 case LoopStatement::FOR_LOOP: {
1659 JumpTarget loop(JumpTarget::BIDIRECTIONAL);
1660
1661 if (node->init() != NULL) {
1662 VisitAndSpill(node->init());
1663 }
1664
1665 // There is no need to compile the test or body.
1666 if (info == ALWAYS_FALSE) break;
1667
1668 // If there is no update statement, label the top of the loop with the
1669 // continue target, otherwise with the loop target.
1670 if (node->next() == NULL) {
1671 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
1672 node->continue_target()->Bind();
1673 } else {
1674 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1675 loop.Bind();
1676 }
1677
1678 // If the test is always true, there is no need to compile it.
1679 if (info == DONT_KNOW) {
1680 JumpTarget body;
1681 LoadConditionAndSpill(node->cond(), NOT_INSIDE_TYPEOF,
1682 &body, node->break_target(), true);
1683 if (has_valid_frame()) {
1684 Branch(false, node->break_target());
1685 }
1686 if (has_valid_frame() || body.is_linked()) {
1687 body.Bind();
1688 }
1689 }
1690
1691 if (has_valid_frame()) {
1692 CheckStack(); // TODO(1222600): ignore if body contains calls.
1693 VisitAndSpill(node->body());
1694
1695 if (node->next() == NULL) {
1696 // If there is no update statement and control flow can fall out
1697 // of the loop, jump directly to the continue label.
1698 if (has_valid_frame()) {
1699 node->continue_target()->Jump();
1700 }
1701 } else {
1702 // If there is an update statement and control flow can reach it
1703 // via falling out of the body of the loop or continuing, we
1704 // compile the update statement.
1705 if (node->continue_target()->is_linked()) {
1706 node->continue_target()->Bind();
1707 }
1708 if (has_valid_frame()) {
1709 // Record source position of the statement as this code which is
1710 // after the code for the body actually belongs to the loop
1711 // statement and not the body.
1712 CodeForStatementPosition(node);
1713 VisitAndSpill(node->next());
1714 loop.Jump();
1715 }
1716 }
1717 }
1718 break;
1719 }
1720 }
1721
1722 if (node->break_target()->is_linked()) {
1723 node->break_target()->Bind();
1724 }
1725 node->continue_target()->Unuse();
1726 node->break_target()->Unuse();
1727 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1728}
1729
1730
1731void CodeGenerator::VisitForInStatement(ForInStatement* node) {
1732#ifdef DEBUG
1733 int original_height = frame_->height();
1734#endif
1735 VirtualFrame::SpilledScope spilled_scope;
1736 Comment cmnt(masm_, "[ ForInStatement");
1737 CodeForStatementPosition(node);
1738
1739 JumpTarget primitive;
1740 JumpTarget jsobject;
1741 JumpTarget fixed_array;
1742 JumpTarget entry(JumpTarget::BIDIRECTIONAL);
1743 JumpTarget end_del_check;
1744 JumpTarget exit;
1745
1746 // Get the object to enumerate over (converted to JSObject).
1747 LoadAndSpill(node->enumerable());
1748
1749 // Both SpiderMonkey and kjs ignore null and undefined in contrast
1750 // to the specification. 12.6.4 mandates a call to ToObject.
1751 frame_->EmitPop(r0);
1752 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
1753 __ cmp(r0, ip);
1754 exit.Branch(eq);
1755 __ LoadRoot(ip, Heap::kNullValueRootIndex);
1756 __ cmp(r0, ip);
1757 exit.Branch(eq);
1758
1759 // Stack layout in body:
1760 // [iteration counter (Smi)]
1761 // [length of array]
1762 // [FixedArray]
1763 // [Map or 0]
1764 // [Object]
1765
1766 // Check if enumerable is already a JSObject
1767 __ tst(r0, Operand(kSmiTagMask));
1768 primitive.Branch(eq);
1769 __ CompareObjectType(r0, r1, r1, FIRST_JS_OBJECT_TYPE);
1770 jsobject.Branch(hs);
1771
1772 primitive.Bind();
1773 frame_->EmitPush(r0);
1774 Result arg_count(r0);
1775 __ mov(r0, Operand(0));
1776 frame_->InvokeBuiltin(Builtins::TO_OBJECT, CALL_JS, &arg_count, 1);
1777
1778 jsobject.Bind();
1779 // Get the set of properties (as a FixedArray or Map).
1780 frame_->EmitPush(r0); // duplicate the object being enumerated
1781 frame_->EmitPush(r0);
1782 frame_->CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1783
1784 // If we got a Map, we can do a fast modification check.
1785 // Otherwise, we got a FixedArray, and we have to do a slow check.
1786 __ mov(r2, Operand(r0));
1787 __ ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
1788 __ LoadRoot(ip, Heap::kMetaMapRootIndex);
1789 __ cmp(r1, ip);
1790 fixed_array.Branch(ne);
1791
1792 // Get enum cache
1793 __ mov(r1, Operand(r0));
1794 __ ldr(r1, FieldMemOperand(r1, Map::kInstanceDescriptorsOffset));
1795 __ ldr(r1, FieldMemOperand(r1, DescriptorArray::kEnumerationIndexOffset));
1796 __ ldr(r2,
1797 FieldMemOperand(r1, DescriptorArray::kEnumCacheBridgeCacheOffset));
1798
1799 frame_->EmitPush(r0); // map
1800 frame_->EmitPush(r2); // enum cache bridge cache
1801 __ ldr(r0, FieldMemOperand(r2, FixedArray::kLengthOffset));
1802 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
1803 frame_->EmitPush(r0);
1804 __ mov(r0, Operand(Smi::FromInt(0)));
1805 frame_->EmitPush(r0);
1806 entry.Jump();
1807
1808 fixed_array.Bind();
1809 __ mov(r1, Operand(Smi::FromInt(0)));
1810 frame_->EmitPush(r1); // insert 0 in place of Map
1811 frame_->EmitPush(r0);
1812
1813 // Push the length of the array and the initial index onto the stack.
1814 __ ldr(r0, FieldMemOperand(r0, FixedArray::kLengthOffset));
1815 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
1816 frame_->EmitPush(r0);
1817 __ mov(r0, Operand(Smi::FromInt(0))); // init index
1818 frame_->EmitPush(r0);
1819
1820 // Condition.
1821 entry.Bind();
1822 // sp[0] : index
1823 // sp[1] : array/enum cache length
1824 // sp[2] : array or enum cache
1825 // sp[3] : 0 or map
1826 // sp[4] : enumerable
1827 // Grab the current frame's height for the break and continue
1828 // targets only after all the state is pushed on the frame.
1829 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1830 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1831
1832 __ ldr(r0, frame_->ElementAt(0)); // load the current count
1833 __ ldr(r1, frame_->ElementAt(1)); // load the length
1834 __ cmp(r0, Operand(r1)); // compare to the array length
1835 node->break_target()->Branch(hs);
1836
1837 __ ldr(r0, frame_->ElementAt(0));
1838
1839 // Get the i'th entry of the array.
1840 __ ldr(r2, frame_->ElementAt(2));
1841 __ add(r2, r2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
1842 __ ldr(r3, MemOperand(r2, r0, LSL, kPointerSizeLog2 - kSmiTagSize));
1843
1844 // Get Map or 0.
1845 __ ldr(r2, frame_->ElementAt(3));
1846 // Check if this (still) matches the map of the enumerable.
1847 // If not, we have to filter the key.
1848 __ ldr(r1, frame_->ElementAt(4));
1849 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
1850 __ cmp(r1, Operand(r2));
1851 end_del_check.Branch(eq);
1852
1853 // Convert the entry to a string (or null if it isn't a property anymore).
1854 __ ldr(r0, frame_->ElementAt(4)); // push enumerable
1855 frame_->EmitPush(r0);
1856 frame_->EmitPush(r3); // push entry
1857 Result arg_count_reg(r0);
1858 __ mov(r0, Operand(1));
1859 frame_->InvokeBuiltin(Builtins::FILTER_KEY, CALL_JS, &arg_count_reg, 2);
1860 __ mov(r3, Operand(r0));
1861
1862 // If the property has been removed while iterating, we just skip it.
1863 __ LoadRoot(ip, Heap::kNullValueRootIndex);
1864 __ cmp(r3, ip);
1865 node->continue_target()->Branch(eq);
1866
1867 end_del_check.Bind();
1868 // Store the entry in the 'each' expression and take another spin in the
1869 // loop. r3: i'th entry of the enum cache (or string there of)
1870 frame_->EmitPush(r3); // push entry
1871 { Reference each(this, node->each());
1872 if (!each.is_illegal()) {
1873 if (each.size() > 0) {
1874 __ ldr(r0, frame_->ElementAt(each.size()));
1875 frame_->EmitPush(r0);
1876 }
1877 // If the reference was to a slot we rely on the convenient property
1878 // that it doesn't matter whether a value (eg, r3 pushed above) is
1879 // right on top of or right underneath a zero-sized reference.
1880 each.SetValue(NOT_CONST_INIT);
1881 if (each.size() > 0) {
1882 // It's safe to pop the value lying on top of the reference before
1883 // unloading the reference itself (which preserves the top of stack,
1884 // ie, now the topmost value of the non-zero sized reference), since
1885 // we will discard the top of stack after unloading the reference
1886 // anyway.
1887 frame_->EmitPop(r0);
1888 }
1889 }
1890 }
1891 // Discard the i'th entry pushed above or else the remainder of the
1892 // reference, whichever is currently on top of the stack.
1893 frame_->Drop();
1894
1895 // Body.
1896 CheckStack(); // TODO(1222600): ignore if body contains calls.
1897 VisitAndSpill(node->body());
1898
1899 // Next. Reestablish a spilled frame in case we are coming here via
1900 // a continue in the body.
1901 node->continue_target()->Bind();
1902 frame_->SpillAll();
1903 frame_->EmitPop(r0);
1904 __ add(r0, r0, Operand(Smi::FromInt(1)));
1905 frame_->EmitPush(r0);
1906 entry.Jump();
1907
1908 // Cleanup. No need to spill because VirtualFrame::Drop is safe for
1909 // any frame.
1910 node->break_target()->Bind();
1911 frame_->Drop(5);
1912
1913 // Exit.
1914 exit.Bind();
1915 node->continue_target()->Unuse();
1916 node->break_target()->Unuse();
1917 ASSERT(frame_->height() == original_height);
1918}
1919
1920
1921void CodeGenerator::VisitTryCatch(TryCatch* node) {
1922#ifdef DEBUG
1923 int original_height = frame_->height();
1924#endif
1925 VirtualFrame::SpilledScope spilled_scope;
1926 Comment cmnt(masm_, "[ TryCatch");
1927 CodeForStatementPosition(node);
1928
1929 JumpTarget try_block;
1930 JumpTarget exit;
1931
1932 try_block.Call();
1933 // --- Catch block ---
1934 frame_->EmitPush(r0);
1935
1936 // Store the caught exception in the catch variable.
1937 { Reference ref(this, node->catch_var());
1938 ASSERT(ref.is_slot());
1939 // Here we make use of the convenient property that it doesn't matter
1940 // whether a value is immediately on top of or underneath a zero-sized
1941 // reference.
1942 ref.SetValue(NOT_CONST_INIT);
1943 }
1944
1945 // Remove the exception from the stack.
1946 frame_->Drop();
1947
1948 VisitStatementsAndSpill(node->catch_block()->statements());
1949 if (frame_ != NULL) {
1950 exit.Jump();
1951 }
1952
1953
1954 // --- Try block ---
1955 try_block.Bind();
1956
1957 frame_->PushTryHandler(TRY_CATCH_HANDLER);
1958 int handler_height = frame_->height();
1959
1960 // Shadow the labels for all escapes from the try block, including
1961 // returns. During shadowing, the original label is hidden as the
1962 // LabelShadow and operations on the original actually affect the
1963 // shadowing label.
1964 //
1965 // We should probably try to unify the escaping labels and the return
1966 // label.
1967 int nof_escapes = node->escaping_targets()->length();
1968 List<ShadowTarget*> shadows(1 + nof_escapes);
1969
1970 // Add the shadow target for the function return.
1971 static const int kReturnShadowIndex = 0;
1972 shadows.Add(new ShadowTarget(&function_return_));
1973 bool function_return_was_shadowed = function_return_is_shadowed_;
1974 function_return_is_shadowed_ = true;
1975 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
1976
1977 // Add the remaining shadow targets.
1978 for (int i = 0; i < nof_escapes; i++) {
1979 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
1980 }
1981
1982 // Generate code for the statements in the try block.
1983 VisitStatementsAndSpill(node->try_block()->statements());
1984
1985 // Stop the introduced shadowing and count the number of required unlinks.
1986 // After shadowing stops, the original labels are unshadowed and the
1987 // LabelShadows represent the formerly shadowing labels.
1988 bool has_unlinks = false;
1989 for (int i = 0; i < shadows.length(); i++) {
1990 shadows[i]->StopShadowing();
1991 has_unlinks = has_unlinks || shadows[i]->is_linked();
1992 }
1993 function_return_is_shadowed_ = function_return_was_shadowed;
1994
1995 // Get an external reference to the handler address.
1996 ExternalReference handler_address(Top::k_handler_address);
1997
1998 // If we can fall off the end of the try block, unlink from try chain.
1999 if (has_valid_frame()) {
2000 // The next handler address is on top of the frame. Unlink from
2001 // the handler list and drop the rest of this handler from the
2002 // frame.
2003 ASSERT(StackHandlerConstants::kNextOffset == 0);
2004 frame_->EmitPop(r1);
2005 __ mov(r3, Operand(handler_address));
2006 __ str(r1, MemOperand(r3));
2007 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2008 if (has_unlinks) {
2009 exit.Jump();
2010 }
2011 }
2012
2013 // Generate unlink code for the (formerly) shadowing labels that have been
2014 // jumped to. Deallocate each shadow target.
2015 for (int i = 0; i < shadows.length(); i++) {
2016 if (shadows[i]->is_linked()) {
2017 // Unlink from try chain;
2018 shadows[i]->Bind();
2019 // Because we can be jumping here (to spilled code) from unspilled
2020 // code, we need to reestablish a spilled frame at this block.
2021 frame_->SpillAll();
2022
2023 // Reload sp from the top handler, because some statements that we
2024 // break from (eg, for...in) may have left stuff on the stack.
2025 __ mov(r3, Operand(handler_address));
2026 __ ldr(sp, MemOperand(r3));
2027 frame_->Forget(frame_->height() - handler_height);
2028
2029 ASSERT(StackHandlerConstants::kNextOffset == 0);
2030 frame_->EmitPop(r1);
2031 __ str(r1, MemOperand(r3));
2032 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2033
2034 if (!function_return_is_shadowed_ && i == kReturnShadowIndex) {
2035 frame_->PrepareForReturn();
2036 }
2037 shadows[i]->other_target()->Jump();
2038 }
2039 }
2040
2041 exit.Bind();
2042 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2043}
2044
2045
2046void CodeGenerator::VisitTryFinally(TryFinally* node) {
2047#ifdef DEBUG
2048 int original_height = frame_->height();
2049#endif
2050 VirtualFrame::SpilledScope spilled_scope;
2051 Comment cmnt(masm_, "[ TryFinally");
2052 CodeForStatementPosition(node);
2053
2054 // State: Used to keep track of reason for entering the finally
2055 // block. Should probably be extended to hold information for
2056 // break/continue from within the try block.
2057 enum { FALLING, THROWING, JUMPING };
2058
2059 JumpTarget try_block;
2060 JumpTarget finally_block;
2061
2062 try_block.Call();
2063
2064 frame_->EmitPush(r0); // save exception object on the stack
2065 // In case of thrown exceptions, this is where we continue.
2066 __ mov(r2, Operand(Smi::FromInt(THROWING)));
2067 finally_block.Jump();
2068
2069 // --- Try block ---
2070 try_block.Bind();
2071
2072 frame_->PushTryHandler(TRY_FINALLY_HANDLER);
2073 int handler_height = frame_->height();
2074
2075 // Shadow the labels for all escapes from the try block, including
2076 // returns. Shadowing hides the original label as the LabelShadow and
2077 // operations on the original actually affect the shadowing label.
2078 //
2079 // We should probably try to unify the escaping labels and the return
2080 // label.
2081 int nof_escapes = node->escaping_targets()->length();
2082 List<ShadowTarget*> shadows(1 + nof_escapes);
2083
2084 // Add the shadow target for the function return.
2085 static const int kReturnShadowIndex = 0;
2086 shadows.Add(new ShadowTarget(&function_return_));
2087 bool function_return_was_shadowed = function_return_is_shadowed_;
2088 function_return_is_shadowed_ = true;
2089 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
2090
2091 // Add the remaining shadow targets.
2092 for (int i = 0; i < nof_escapes; i++) {
2093 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
2094 }
2095
2096 // Generate code for the statements in the try block.
2097 VisitStatementsAndSpill(node->try_block()->statements());
2098
2099 // Stop the introduced shadowing and count the number of required unlinks.
2100 // After shadowing stops, the original labels are unshadowed and the
2101 // LabelShadows represent the formerly shadowing labels.
2102 int nof_unlinks = 0;
2103 for (int i = 0; i < shadows.length(); i++) {
2104 shadows[i]->StopShadowing();
2105 if (shadows[i]->is_linked()) nof_unlinks++;
2106 }
2107 function_return_is_shadowed_ = function_return_was_shadowed;
2108
2109 // Get an external reference to the handler address.
2110 ExternalReference handler_address(Top::k_handler_address);
2111
2112 // If we can fall off the end of the try block, unlink from the try
2113 // chain and set the state on the frame to FALLING.
2114 if (has_valid_frame()) {
2115 // The next handler address is on top of the frame.
2116 ASSERT(StackHandlerConstants::kNextOffset == 0);
2117 frame_->EmitPop(r1);
2118 __ mov(r3, Operand(handler_address));
2119 __ str(r1, MemOperand(r3));
2120 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2121
2122 // Fake a top of stack value (unneeded when FALLING) and set the
2123 // state in r2, then jump around the unlink blocks if any.
2124 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
2125 frame_->EmitPush(r0);
2126 __ mov(r2, Operand(Smi::FromInt(FALLING)));
2127 if (nof_unlinks > 0) {
2128 finally_block.Jump();
2129 }
2130 }
2131
2132 // Generate code to unlink and set the state for the (formerly)
2133 // shadowing targets that have been jumped to.
2134 for (int i = 0; i < shadows.length(); i++) {
2135 if (shadows[i]->is_linked()) {
2136 // If we have come from the shadowed return, the return value is
2137 // in (a non-refcounted reference to) r0. We must preserve it
2138 // until it is pushed.
2139 //
2140 // Because we can be jumping here (to spilled code) from
2141 // unspilled code, we need to reestablish a spilled frame at
2142 // this block.
2143 shadows[i]->Bind();
2144 frame_->SpillAll();
2145
2146 // Reload sp from the top handler, because some statements that
2147 // we break from (eg, for...in) may have left stuff on the
2148 // stack.
2149 __ mov(r3, Operand(handler_address));
2150 __ ldr(sp, MemOperand(r3));
2151 frame_->Forget(frame_->height() - handler_height);
2152
2153 // Unlink this handler and drop it from the frame. The next
2154 // handler address is currently on top of the frame.
2155 ASSERT(StackHandlerConstants::kNextOffset == 0);
2156 frame_->EmitPop(r1);
2157 __ str(r1, MemOperand(r3));
2158 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2159
2160 if (i == kReturnShadowIndex) {
2161 // If this label shadowed the function return, materialize the
2162 // return value on the stack.
2163 frame_->EmitPush(r0);
2164 } else {
2165 // Fake TOS for targets that shadowed breaks and continues.
2166 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
2167 frame_->EmitPush(r0);
2168 }
2169 __ mov(r2, Operand(Smi::FromInt(JUMPING + i)));
2170 if (--nof_unlinks > 0) {
2171 // If this is not the last unlink block, jump around the next.
2172 finally_block.Jump();
2173 }
2174 }
2175 }
2176
2177 // --- Finally block ---
2178 finally_block.Bind();
2179
2180 // Push the state on the stack.
2181 frame_->EmitPush(r2);
2182
2183 // We keep two elements on the stack - the (possibly faked) result
2184 // and the state - while evaluating the finally block.
2185 //
2186 // Generate code for the statements in the finally block.
2187 VisitStatementsAndSpill(node->finally_block()->statements());
2188
2189 if (has_valid_frame()) {
2190 // Restore state and return value or faked TOS.
2191 frame_->EmitPop(r2);
2192 frame_->EmitPop(r0);
2193 }
2194
2195 // Generate code to jump to the right destination for all used
2196 // formerly shadowing targets. Deallocate each shadow target.
2197 for (int i = 0; i < shadows.length(); i++) {
2198 if (has_valid_frame() && shadows[i]->is_bound()) {
2199 JumpTarget* original = shadows[i]->other_target();
2200 __ cmp(r2, Operand(Smi::FromInt(JUMPING + i)));
2201 if (!function_return_is_shadowed_ && i == kReturnShadowIndex) {
2202 JumpTarget skip;
2203 skip.Branch(ne);
2204 frame_->PrepareForReturn();
2205 original->Jump();
2206 skip.Bind();
2207 } else {
2208 original->Branch(eq);
2209 }
2210 }
2211 }
2212
2213 if (has_valid_frame()) {
2214 // Check if we need to rethrow the exception.
2215 JumpTarget exit;
2216 __ cmp(r2, Operand(Smi::FromInt(THROWING)));
2217 exit.Branch(ne);
2218
2219 // Rethrow exception.
2220 frame_->EmitPush(r0);
2221 frame_->CallRuntime(Runtime::kReThrow, 1);
2222
2223 // Done.
2224 exit.Bind();
2225 }
2226 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2227}
2228
2229
2230void CodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
2231#ifdef DEBUG
2232 int original_height = frame_->height();
2233#endif
2234 VirtualFrame::SpilledScope spilled_scope;
2235 Comment cmnt(masm_, "[ DebuggerStatament");
2236 CodeForStatementPosition(node);
2237#ifdef ENABLE_DEBUGGER_SUPPORT
2238 frame_->CallRuntime(Runtime::kDebugBreak, 0);
2239#endif
2240 // Ignore the return value.
2241 ASSERT(frame_->height() == original_height);
2242}
2243
2244
2245void CodeGenerator::InstantiateBoilerplate(Handle<JSFunction> boilerplate) {
2246 VirtualFrame::SpilledScope spilled_scope;
2247 ASSERT(boilerplate->IsBoilerplate());
2248
2249 // Push the boilerplate on the stack.
2250 __ mov(r0, Operand(boilerplate));
2251 frame_->EmitPush(r0);
2252
2253 // Create a new closure.
2254 frame_->EmitPush(cp);
2255 frame_->CallRuntime(Runtime::kNewClosure, 2);
2256 frame_->EmitPush(r0);
2257}
2258
2259
2260void CodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
2261#ifdef DEBUG
2262 int original_height = frame_->height();
2263#endif
2264 VirtualFrame::SpilledScope spilled_scope;
2265 Comment cmnt(masm_, "[ FunctionLiteral");
2266
2267 // Build the function boilerplate and instantiate it.
2268 Handle<JSFunction> boilerplate = BuildBoilerplate(node);
2269 // Check for stack-overflow exception.
2270 if (HasStackOverflow()) {
2271 ASSERT(frame_->height() == original_height);
2272 return;
2273 }
2274 InstantiateBoilerplate(boilerplate);
2275 ASSERT(frame_->height() == original_height + 1);
2276}
2277
2278
2279void CodeGenerator::VisitFunctionBoilerplateLiteral(
2280 FunctionBoilerplateLiteral* node) {
2281#ifdef DEBUG
2282 int original_height = frame_->height();
2283#endif
2284 VirtualFrame::SpilledScope spilled_scope;
2285 Comment cmnt(masm_, "[ FunctionBoilerplateLiteral");
2286 InstantiateBoilerplate(node->boilerplate());
2287 ASSERT(frame_->height() == original_height + 1);
2288}
2289
2290
2291void CodeGenerator::VisitConditional(Conditional* node) {
2292#ifdef DEBUG
2293 int original_height = frame_->height();
2294#endif
2295 VirtualFrame::SpilledScope spilled_scope;
2296 Comment cmnt(masm_, "[ Conditional");
2297 JumpTarget then;
2298 JumpTarget else_;
2299 LoadConditionAndSpill(node->condition(), NOT_INSIDE_TYPEOF,
2300 &then, &else_, true);
2301 if (has_valid_frame()) {
2302 Branch(false, &else_);
2303 }
2304 if (has_valid_frame() || then.is_linked()) {
2305 then.Bind();
2306 LoadAndSpill(node->then_expression(), typeof_state());
2307 }
2308 if (else_.is_linked()) {
2309 JumpTarget exit;
2310 if (has_valid_frame()) exit.Jump();
2311 else_.Bind();
2312 LoadAndSpill(node->else_expression(), typeof_state());
2313 if (exit.is_linked()) exit.Bind();
2314 }
2315 ASSERT(frame_->height() == original_height + 1);
2316}
2317
2318
2319void CodeGenerator::LoadFromSlot(Slot* slot, TypeofState typeof_state) {
2320 VirtualFrame::SpilledScope spilled_scope;
2321 if (slot->type() == Slot::LOOKUP) {
2322 ASSERT(slot->var()->is_dynamic());
2323
2324 JumpTarget slow;
2325 JumpTarget done;
2326
2327 // Generate fast-case code for variables that might be shadowed by
2328 // eval-introduced variables. Eval is used a lot without
2329 // introducing variables. In those cases, we do not want to
2330 // perform a runtime call for all variables in the scope
2331 // containing the eval.
2332 if (slot->var()->mode() == Variable::DYNAMIC_GLOBAL) {
2333 LoadFromGlobalSlotCheckExtensions(slot, typeof_state, r1, r2, &slow);
2334 // If there was no control flow to slow, we can exit early.
2335 if (!slow.is_linked()) {
2336 frame_->EmitPush(r0);
2337 return;
2338 }
2339
2340 done.Jump();
2341
2342 } else if (slot->var()->mode() == Variable::DYNAMIC_LOCAL) {
2343 Slot* potential_slot = slot->var()->local_if_not_shadowed()->slot();
2344 // Only generate the fast case for locals that rewrite to slots.
2345 // This rules out argument loads.
2346 if (potential_slot != NULL) {
2347 __ ldr(r0,
2348 ContextSlotOperandCheckExtensions(potential_slot,
2349 r1,
2350 r2,
2351 &slow));
2352 if (potential_slot->var()->mode() == Variable::CONST) {
2353 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
2354 __ cmp(r0, ip);
2355 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex, eq);
2356 }
2357 // There is always control flow to slow from
2358 // ContextSlotOperandCheckExtensions so we have to jump around
2359 // it.
2360 done.Jump();
2361 }
2362 }
2363
2364 slow.Bind();
2365 frame_->EmitPush(cp);
2366 __ mov(r0, Operand(slot->var()->name()));
2367 frame_->EmitPush(r0);
2368
2369 if (typeof_state == INSIDE_TYPEOF) {
2370 frame_->CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
2371 } else {
2372 frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
2373 }
2374
2375 done.Bind();
2376 frame_->EmitPush(r0);
2377
2378 } else {
2379 // Note: We would like to keep the assert below, but it fires because of
2380 // some nasty code in LoadTypeofExpression() which should be removed...
2381 // ASSERT(!slot->var()->is_dynamic());
2382
2383 // Special handling for locals allocated in registers.
2384 __ ldr(r0, SlotOperand(slot, r2));
2385 frame_->EmitPush(r0);
2386 if (slot->var()->mode() == Variable::CONST) {
2387 // Const slots may contain 'the hole' value (the constant hasn't been
2388 // initialized yet) which needs to be converted into the 'undefined'
2389 // value.
2390 Comment cmnt(masm_, "[ Unhole const");
2391 frame_->EmitPop(r0);
2392 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
2393 __ cmp(r0, ip);
2394 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex, eq);
2395 frame_->EmitPush(r0);
2396 }
2397 }
2398}
2399
2400
2401void CodeGenerator::LoadFromGlobalSlotCheckExtensions(Slot* slot,
2402 TypeofState typeof_state,
2403 Register tmp,
2404 Register tmp2,
2405 JumpTarget* slow) {
2406 // Check that no extension objects have been created by calls to
2407 // eval from the current scope to the global scope.
2408 Register context = cp;
2409 Scope* s = scope();
2410 while (s != NULL) {
2411 if (s->num_heap_slots() > 0) {
2412 if (s->calls_eval()) {
2413 // Check that extension is NULL.
2414 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
2415 __ tst(tmp2, tmp2);
2416 slow->Branch(ne);
2417 }
2418 // Load next context in chain.
2419 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
2420 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
2421 context = tmp;
2422 }
2423 // If no outer scope calls eval, we do not need to check more
2424 // context extensions.
2425 if (!s->outer_scope_calls_eval() || s->is_eval_scope()) break;
2426 s = s->outer_scope();
2427 }
2428
2429 if (s->is_eval_scope()) {
2430 Label next, fast;
2431 if (!context.is(tmp)) {
2432 __ mov(tmp, Operand(context));
2433 }
2434 __ bind(&next);
2435 // Terminate at global context.
2436 __ ldr(tmp2, FieldMemOperand(tmp, HeapObject::kMapOffset));
2437 __ LoadRoot(ip, Heap::kGlobalContextMapRootIndex);
2438 __ cmp(tmp2, ip);
2439 __ b(eq, &fast);
2440 // Check that extension is NULL.
2441 __ ldr(tmp2, ContextOperand(tmp, Context::EXTENSION_INDEX));
2442 __ tst(tmp2, tmp2);
2443 slow->Branch(ne);
2444 // Load next context in chain.
2445 __ ldr(tmp, ContextOperand(tmp, Context::CLOSURE_INDEX));
2446 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
2447 __ b(&next);
2448 __ bind(&fast);
2449 }
2450
2451 // All extension objects were empty and it is safe to use a global
2452 // load IC call.
2453 Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
2454 // Load the global object.
2455 LoadGlobal();
2456 // Setup the name register.
2457 Result name(r2);
2458 __ mov(r2, Operand(slot->var()->name()));
2459 // Call IC stub.
2460 if (typeof_state == INSIDE_TYPEOF) {
2461 frame_->CallCodeObject(ic, RelocInfo::CODE_TARGET, &name, 0);
2462 } else {
2463 frame_->CallCodeObject(ic, RelocInfo::CODE_TARGET_CONTEXT, &name, 0);
2464 }
2465
2466 // Drop the global object. The result is in r0.
2467 frame_->Drop();
2468}
2469
2470
2471void CodeGenerator::VisitSlot(Slot* node) {
2472#ifdef DEBUG
2473 int original_height = frame_->height();
2474#endif
2475 VirtualFrame::SpilledScope spilled_scope;
2476 Comment cmnt(masm_, "[ Slot");
2477 LoadFromSlot(node, typeof_state());
2478 ASSERT(frame_->height() == original_height + 1);
2479}
2480
2481
2482void CodeGenerator::VisitVariableProxy(VariableProxy* node) {
2483#ifdef DEBUG
2484 int original_height = frame_->height();
2485#endif
2486 VirtualFrame::SpilledScope spilled_scope;
2487 Comment cmnt(masm_, "[ VariableProxy");
2488
2489 Variable* var = node->var();
2490 Expression* expr = var->rewrite();
2491 if (expr != NULL) {
2492 Visit(expr);
2493 } else {
2494 ASSERT(var->is_global());
2495 Reference ref(this, node);
2496 ref.GetValueAndSpill(typeof_state());
2497 }
2498 ASSERT(frame_->height() == original_height + 1);
2499}
2500
2501
2502void CodeGenerator::VisitLiteral(Literal* node) {
2503#ifdef DEBUG
2504 int original_height = frame_->height();
2505#endif
2506 VirtualFrame::SpilledScope spilled_scope;
2507 Comment cmnt(masm_, "[ Literal");
2508 __ mov(r0, Operand(node->handle()));
2509 frame_->EmitPush(r0);
2510 ASSERT(frame_->height() == original_height + 1);
2511}
2512
2513
2514void CodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
2515#ifdef DEBUG
2516 int original_height = frame_->height();
2517#endif
2518 VirtualFrame::SpilledScope spilled_scope;
2519 Comment cmnt(masm_, "[ RexExp Literal");
2520
2521 // Retrieve the literal array and check the allocated entry.
2522
2523 // Load the function of this activation.
2524 __ ldr(r1, frame_->Function());
2525
2526 // Load the literals array of the function.
2527 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
2528
2529 // Load the literal at the ast saved index.
2530 int literal_offset =
2531 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
2532 __ ldr(r2, FieldMemOperand(r1, literal_offset));
2533
2534 JumpTarget done;
2535 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
2536 __ cmp(r2, ip);
2537 done.Branch(ne);
2538
2539 // If the entry is undefined we call the runtime system to computed
2540 // the literal.
2541 frame_->EmitPush(r1); // literal array (0)
2542 __ mov(r0, Operand(Smi::FromInt(node->literal_index())));
2543 frame_->EmitPush(r0); // literal index (1)
2544 __ mov(r0, Operand(node->pattern())); // RegExp pattern (2)
2545 frame_->EmitPush(r0);
2546 __ mov(r0, Operand(node->flags())); // RegExp flags (3)
2547 frame_->EmitPush(r0);
2548 frame_->CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
2549 __ mov(r2, Operand(r0));
2550
2551 done.Bind();
2552 // Push the literal.
2553 frame_->EmitPush(r2);
2554 ASSERT(frame_->height() == original_height + 1);
2555}
2556
2557
2558// This deferred code stub will be used for creating the boilerplate
2559// by calling Runtime_CreateObjectLiteralBoilerplate.
2560// Each created boilerplate is stored in the JSFunction and they are
2561// therefore context dependent.
2562class DeferredObjectLiteral: public DeferredCode {
2563 public:
2564 explicit DeferredObjectLiteral(ObjectLiteral* node) : node_(node) {
2565 set_comment("[ DeferredObjectLiteral");
2566 }
2567
2568 virtual void Generate();
2569
2570 private:
2571 ObjectLiteral* node_;
2572};
2573
2574
2575void DeferredObjectLiteral::Generate() {
2576 // Argument is passed in r1.
2577
2578 // If the entry is undefined we call the runtime system to compute
2579 // the literal.
2580 // Literal array (0).
2581 __ push(r1);
2582 // Literal index (1).
2583 __ mov(r0, Operand(Smi::FromInt(node_->literal_index())));
2584 __ push(r0);
2585 // Constant properties (2).
2586 __ mov(r0, Operand(node_->constant_properties()));
2587 __ push(r0);
2588 __ CallRuntime(Runtime::kCreateObjectLiteralBoilerplate, 3);
2589 __ mov(r2, Operand(r0));
2590 // Result is returned in r2.
2591}
2592
2593
2594void CodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
2595#ifdef DEBUG
2596 int original_height = frame_->height();
2597#endif
2598 VirtualFrame::SpilledScope spilled_scope;
2599 Comment cmnt(masm_, "[ ObjectLiteral");
2600
2601 DeferredObjectLiteral* deferred = new DeferredObjectLiteral(node);
2602
2603 // Retrieve the literal array and check the allocated entry.
2604
2605 // Load the function of this activation.
2606 __ ldr(r1, frame_->Function());
2607
2608 // Load the literals array of the function.
2609 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
2610
2611 // Load the literal at the ast saved index.
2612 int literal_offset =
2613 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
2614 __ ldr(r2, FieldMemOperand(r1, literal_offset));
2615
2616 // Check whether we need to materialize the object literal boilerplate.
2617 // If so, jump to the deferred code.
2618 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
2619 __ cmp(r2, Operand(ip));
2620 deferred->Branch(eq);
2621 deferred->BindExit();
2622
2623 // Push the object literal boilerplate.
2624 frame_->EmitPush(r2);
2625
2626 // Clone the boilerplate object.
2627 Runtime::FunctionId clone_function_id = Runtime::kCloneLiteralBoilerplate;
2628 if (node->depth() == 1) {
2629 clone_function_id = Runtime::kCloneShallowLiteralBoilerplate;
2630 }
2631 frame_->CallRuntime(clone_function_id, 1);
2632 frame_->EmitPush(r0); // save the result
2633 // r0: cloned object literal
2634
2635 for (int i = 0; i < node->properties()->length(); i++) {
2636 ObjectLiteral::Property* property = node->properties()->at(i);
2637 Literal* key = property->key();
2638 Expression* value = property->value();
2639 switch (property->kind()) {
2640 case ObjectLiteral::Property::CONSTANT:
2641 break;
2642 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
2643 if (CompileTimeValue::IsCompileTimeValue(property->value())) break;
2644 // else fall through
2645 case ObjectLiteral::Property::COMPUTED: // fall through
2646 case ObjectLiteral::Property::PROTOTYPE: {
2647 frame_->EmitPush(r0); // dup the result
2648 LoadAndSpill(key);
2649 LoadAndSpill(value);
2650 frame_->CallRuntime(Runtime::kSetProperty, 3);
2651 // restore r0
2652 __ ldr(r0, frame_->Top());
2653 break;
2654 }
2655 case ObjectLiteral::Property::SETTER: {
2656 frame_->EmitPush(r0);
2657 LoadAndSpill(key);
2658 __ mov(r0, Operand(Smi::FromInt(1)));
2659 frame_->EmitPush(r0);
2660 LoadAndSpill(value);
2661 frame_->CallRuntime(Runtime::kDefineAccessor, 4);
2662 __ ldr(r0, frame_->Top());
2663 break;
2664 }
2665 case ObjectLiteral::Property::GETTER: {
2666 frame_->EmitPush(r0);
2667 LoadAndSpill(key);
2668 __ mov(r0, Operand(Smi::FromInt(0)));
2669 frame_->EmitPush(r0);
2670 LoadAndSpill(value);
2671 frame_->CallRuntime(Runtime::kDefineAccessor, 4);
2672 __ ldr(r0, frame_->Top());
2673 break;
2674 }
2675 }
2676 }
2677 ASSERT(frame_->height() == original_height + 1);
2678}
2679
2680
2681// This deferred code stub will be used for creating the boilerplate
2682// by calling Runtime_CreateArrayLiteralBoilerplate.
2683// Each created boilerplate is stored in the JSFunction and they are
2684// therefore context dependent.
2685class DeferredArrayLiteral: public DeferredCode {
2686 public:
2687 explicit DeferredArrayLiteral(ArrayLiteral* node) : node_(node) {
2688 set_comment("[ DeferredArrayLiteral");
2689 }
2690
2691 virtual void Generate();
2692
2693 private:
2694 ArrayLiteral* node_;
2695};
2696
2697
2698void DeferredArrayLiteral::Generate() {
2699 // Argument is passed in r1.
2700
2701 // If the entry is undefined we call the runtime system to computed
2702 // the literal.
2703 // Literal array (0).
2704 __ push(r1);
2705 // Literal index (1).
2706 __ mov(r0, Operand(Smi::FromInt(node_->literal_index())));
2707 __ push(r0);
2708 // Constant properties (2).
2709 __ mov(r0, Operand(node_->literals()));
2710 __ push(r0);
2711 __ CallRuntime(Runtime::kCreateArrayLiteralBoilerplate, 3);
2712 __ mov(r2, Operand(r0));
2713 // Result is returned in r2.
2714}
2715
2716
2717void CodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
2718#ifdef DEBUG
2719 int original_height = frame_->height();
2720#endif
2721 VirtualFrame::SpilledScope spilled_scope;
2722 Comment cmnt(masm_, "[ ArrayLiteral");
2723
2724 DeferredArrayLiteral* deferred = new DeferredArrayLiteral(node);
2725
2726 // Retrieve the literal array and check the allocated entry.
2727
2728 // Load the function of this activation.
2729 __ ldr(r1, frame_->Function());
2730
2731 // Load the literals array of the function.
2732 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
2733
2734 // Load the literal at the ast saved index.
2735 int literal_offset =
2736 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
2737 __ ldr(r2, FieldMemOperand(r1, literal_offset));
2738
2739 // Check whether we need to materialize the object literal boilerplate.
2740 // If so, jump to the deferred code.
2741 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
2742 __ cmp(r2, Operand(ip));
2743 deferred->Branch(eq);
2744 deferred->BindExit();
2745
2746 // Push the object literal boilerplate.
2747 frame_->EmitPush(r2);
2748
2749 // Clone the boilerplate object.
2750 Runtime::FunctionId clone_function_id = Runtime::kCloneLiteralBoilerplate;
2751 if (node->depth() == 1) {
2752 clone_function_id = Runtime::kCloneShallowLiteralBoilerplate;
2753 }
2754 frame_->CallRuntime(clone_function_id, 1);
2755 frame_->EmitPush(r0); // save the result
2756 // r0: cloned object literal
2757
2758 // Generate code to set the elements in the array that are not
2759 // literals.
2760 for (int i = 0; i < node->values()->length(); i++) {
2761 Expression* value = node->values()->at(i);
2762
2763 // If value is a literal the property value is already set in the
2764 // boilerplate object.
2765 if (value->AsLiteral() != NULL) continue;
2766 // If value is a materialized literal the property value is already set
2767 // in the boilerplate object if it is simple.
2768 if (CompileTimeValue::IsCompileTimeValue(value)) continue;
2769
2770 // The property must be set by generated code.
2771 LoadAndSpill(value);
2772 frame_->EmitPop(r0);
2773
2774 // Fetch the object literal.
2775 __ ldr(r1, frame_->Top());
2776 // Get the elements array.
2777 __ ldr(r1, FieldMemOperand(r1, JSObject::kElementsOffset));
2778
2779 // Write to the indexed properties array.
2780 int offset = i * kPointerSize + FixedArray::kHeaderSize;
2781 __ str(r0, FieldMemOperand(r1, offset));
2782
2783 // Update the write barrier for the array address.
2784 __ mov(r3, Operand(offset));
2785 __ RecordWrite(r1, r3, r2);
2786 }
2787 ASSERT(frame_->height() == original_height + 1);
2788}
2789
2790
2791void CodeGenerator::VisitCatchExtensionObject(CatchExtensionObject* node) {
2792#ifdef DEBUG
2793 int original_height = frame_->height();
2794#endif
2795 VirtualFrame::SpilledScope spilled_scope;
2796 // Call runtime routine to allocate the catch extension object and
2797 // assign the exception value to the catch variable.
2798 Comment cmnt(masm_, "[ CatchExtensionObject");
2799 LoadAndSpill(node->key());
2800 LoadAndSpill(node->value());
2801 frame_->CallRuntime(Runtime::kCreateCatchExtensionObject, 2);
2802 frame_->EmitPush(r0);
2803 ASSERT(frame_->height() == original_height + 1);
2804}
2805
2806
2807void CodeGenerator::VisitAssignment(Assignment* node) {
2808#ifdef DEBUG
2809 int original_height = frame_->height();
2810#endif
2811 VirtualFrame::SpilledScope spilled_scope;
2812 Comment cmnt(masm_, "[ Assignment");
2813
2814 { Reference target(this, node->target());
2815 if (target.is_illegal()) {
2816 // Fool the virtual frame into thinking that we left the assignment's
2817 // value on the frame.
2818 __ mov(r0, Operand(Smi::FromInt(0)));
2819 frame_->EmitPush(r0);
2820 ASSERT(frame_->height() == original_height + 1);
2821 return;
2822 }
2823
2824 if (node->op() == Token::ASSIGN ||
2825 node->op() == Token::INIT_VAR ||
2826 node->op() == Token::INIT_CONST) {
2827 LoadAndSpill(node->value());
2828
2829 } else {
2830 // +=, *= and similar binary assignments.
2831 // Get the old value of the lhs.
2832 target.GetValueAndSpill(NOT_INSIDE_TYPEOF);
2833 Literal* literal = node->value()->AsLiteral();
2834 bool overwrite =
2835 (node->value()->AsBinaryOperation() != NULL &&
2836 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
2837 if (literal != NULL && literal->handle()->IsSmi()) {
2838 SmiOperation(node->binary_op(),
2839 literal->handle(),
2840 false,
2841 overwrite ? OVERWRITE_RIGHT : NO_OVERWRITE);
2842 frame_->EmitPush(r0);
2843
2844 } else {
2845 LoadAndSpill(node->value());
2846 GenericBinaryOperation(node->binary_op(),
2847 overwrite ? OVERWRITE_RIGHT : NO_OVERWRITE);
2848 frame_->EmitPush(r0);
2849 }
2850 }
2851
2852 Variable* var = node->target()->AsVariableProxy()->AsVariable();
2853 if (var != NULL &&
2854 (var->mode() == Variable::CONST) &&
2855 node->op() != Token::INIT_VAR && node->op() != Token::INIT_CONST) {
2856 // Assignment ignored - leave the value on the stack.
2857
2858 } else {
2859 CodeForSourcePosition(node->position());
2860 if (node->op() == Token::INIT_CONST) {
2861 // Dynamic constant initializations must use the function context
2862 // and initialize the actual constant declared. Dynamic variable
2863 // initializations are simply assignments and use SetValue.
2864 target.SetValue(CONST_INIT);
2865 } else {
2866 target.SetValue(NOT_CONST_INIT);
2867 }
2868 }
2869 }
2870 ASSERT(frame_->height() == original_height + 1);
2871}
2872
2873
2874void CodeGenerator::VisitThrow(Throw* node) {
2875#ifdef DEBUG
2876 int original_height = frame_->height();
2877#endif
2878 VirtualFrame::SpilledScope spilled_scope;
2879 Comment cmnt(masm_, "[ Throw");
2880
2881 LoadAndSpill(node->exception());
2882 CodeForSourcePosition(node->position());
2883 frame_->CallRuntime(Runtime::kThrow, 1);
2884 frame_->EmitPush(r0);
2885 ASSERT(frame_->height() == original_height + 1);
2886}
2887
2888
2889void CodeGenerator::VisitProperty(Property* node) {
2890#ifdef DEBUG
2891 int original_height = frame_->height();
2892#endif
2893 VirtualFrame::SpilledScope spilled_scope;
2894 Comment cmnt(masm_, "[ Property");
2895
2896 { Reference property(this, node);
2897 property.GetValueAndSpill(typeof_state());
2898 }
2899 ASSERT(frame_->height() == original_height + 1);
2900}
2901
2902
2903void CodeGenerator::VisitCall(Call* node) {
2904#ifdef DEBUG
2905 int original_height = frame_->height();
2906#endif
2907 VirtualFrame::SpilledScope spilled_scope;
2908 Comment cmnt(masm_, "[ Call");
2909
2910 Expression* function = node->expression();
2911 ZoneList<Expression*>* args = node->arguments();
2912
2913 // Standard function call.
2914 // Check if the function is a variable or a property.
2915 Variable* var = function->AsVariableProxy()->AsVariable();
2916 Property* property = function->AsProperty();
2917
2918 // ------------------------------------------------------------------------
2919 // Fast-case: Use inline caching.
2920 // ---
2921 // According to ECMA-262, section 11.2.3, page 44, the function to call
2922 // must be resolved after the arguments have been evaluated. The IC code
2923 // automatically handles this by loading the arguments before the function
2924 // is resolved in cache misses (this also holds for megamorphic calls).
2925 // ------------------------------------------------------------------------
2926
2927 if (var != NULL && var->is_possibly_eval()) {
2928 // ----------------------------------
2929 // JavaScript example: 'eval(arg)' // eval is not known to be shadowed
2930 // ----------------------------------
2931
2932 // In a call to eval, we first call %ResolvePossiblyDirectEval to
2933 // resolve the function we need to call and the receiver of the
2934 // call. Then we call the resolved function using the given
2935 // arguments.
2936 // Prepare stack for call to resolved function.
2937 LoadAndSpill(function);
2938 __ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
2939 frame_->EmitPush(r2); // Slot for receiver
2940 int arg_count = args->length();
2941 for (int i = 0; i < arg_count; i++) {
2942 LoadAndSpill(args->at(i));
2943 }
2944
2945 // Prepare stack for call to ResolvePossiblyDirectEval.
2946 __ ldr(r1, MemOperand(sp, arg_count * kPointerSize + kPointerSize));
2947 frame_->EmitPush(r1);
2948 if (arg_count > 0) {
2949 __ ldr(r1, MemOperand(sp, arg_count * kPointerSize));
2950 frame_->EmitPush(r1);
2951 } else {
2952 frame_->EmitPush(r2);
2953 }
2954
2955 // Resolve the call.
2956 frame_->CallRuntime(Runtime::kResolvePossiblyDirectEval, 2);
2957
2958 // Touch up stack with the right values for the function and the receiver.
2959 __ ldr(r1, FieldMemOperand(r0, FixedArray::kHeaderSize));
2960 __ str(r1, MemOperand(sp, (arg_count + 1) * kPointerSize));
2961 __ ldr(r1, FieldMemOperand(r0, FixedArray::kHeaderSize + kPointerSize));
2962 __ str(r1, MemOperand(sp, arg_count * kPointerSize));
2963
2964 // Call the function.
2965 CodeForSourcePosition(node->position());
2966
2967 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
2968 CallFunctionStub call_function(arg_count, in_loop);
2969 frame_->CallStub(&call_function, arg_count + 1);
2970
2971 __ ldr(cp, frame_->Context());
2972 // Remove the function from the stack.
2973 frame_->Drop();
2974 frame_->EmitPush(r0);
2975
2976 } else if (var != NULL && !var->is_this() && var->is_global()) {
2977 // ----------------------------------
2978 // JavaScript example: 'foo(1, 2, 3)' // foo is global
2979 // ----------------------------------
2980
2981 // Push the name of the function and the receiver onto the stack.
2982 __ mov(r0, Operand(var->name()));
2983 frame_->EmitPush(r0);
2984
2985 // Pass the global object as the receiver and let the IC stub
2986 // patch the stack to use the global proxy as 'this' in the
2987 // invoked function.
2988 LoadGlobal();
2989
2990 // Load the arguments.
2991 int arg_count = args->length();
2992 for (int i = 0; i < arg_count; i++) {
2993 LoadAndSpill(args->at(i));
2994 }
2995
2996 // Setup the receiver register and call the IC initialization code.
2997 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
2998 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
2999 CodeForSourcePosition(node->position());
3000 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET_CONTEXT,
3001 arg_count + 1);
3002 __ ldr(cp, frame_->Context());
3003 // Remove the function from the stack.
3004 frame_->Drop();
3005 frame_->EmitPush(r0);
3006
3007 } else if (var != NULL && var->slot() != NULL &&
3008 var->slot()->type() == Slot::LOOKUP) {
3009 // ----------------------------------
3010 // JavaScript example: 'with (obj) foo(1, 2, 3)' // foo is in obj
3011 // ----------------------------------
3012
3013 // Load the function
3014 frame_->EmitPush(cp);
3015 __ mov(r0, Operand(var->name()));
3016 frame_->EmitPush(r0);
3017 frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
3018 // r0: slot value; r1: receiver
3019
3020 // Load the receiver.
3021 frame_->EmitPush(r0); // function
3022 frame_->EmitPush(r1); // receiver
3023
3024 // Call the function.
3025 CallWithArguments(args, node->position());
3026 frame_->EmitPush(r0);
3027
3028 } else if (property != NULL) {
3029 // Check if the key is a literal string.
3030 Literal* literal = property->key()->AsLiteral();
3031
3032 if (literal != NULL && literal->handle()->IsSymbol()) {
3033 // ------------------------------------------------------------------
3034 // JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
3035 // ------------------------------------------------------------------
3036
3037 // Push the name of the function and the receiver onto the stack.
3038 __ mov(r0, Operand(literal->handle()));
3039 frame_->EmitPush(r0);
3040 LoadAndSpill(property->obj());
3041
3042 // Load the arguments.
3043 int arg_count = args->length();
3044 for (int i = 0; i < arg_count; i++) {
3045 LoadAndSpill(args->at(i));
3046 }
3047
3048 // Set the receiver register and call the IC initialization code.
3049 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
3050 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
3051 CodeForSourcePosition(node->position());
3052 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET, arg_count + 1);
3053 __ ldr(cp, frame_->Context());
3054
3055 // Remove the function from the stack.
3056 frame_->Drop();
3057
3058 frame_->EmitPush(r0); // push after get rid of function from the stack
3059
3060 } else {
3061 // -------------------------------------------
3062 // JavaScript example: 'array[index](1, 2, 3)'
3063 // -------------------------------------------
3064
3065 // Load the function to call from the property through a reference.
3066 Reference ref(this, property);
3067 ref.GetValueAndSpill(NOT_INSIDE_TYPEOF); // receiver
3068
3069 // Pass receiver to called function.
3070 if (property->is_synthetic()) {
3071 LoadGlobalReceiver(r0);
3072 } else {
3073 __ ldr(r0, frame_->ElementAt(ref.size()));
3074 frame_->EmitPush(r0);
3075 }
3076
3077 // Call the function.
3078 CallWithArguments(args, node->position());
3079 frame_->EmitPush(r0);
3080 }
3081
3082 } else {
3083 // ----------------------------------
3084 // JavaScript example: 'foo(1, 2, 3)' // foo is not global
3085 // ----------------------------------
3086
3087 // Load the function.
3088 LoadAndSpill(function);
3089
3090 // Pass the global proxy as the receiver.
3091 LoadGlobalReceiver(r0);
3092
3093 // Call the function.
3094 CallWithArguments(args, node->position());
3095 frame_->EmitPush(r0);
3096 }
3097 ASSERT(frame_->height() == original_height + 1);
3098}
3099
3100
3101void CodeGenerator::VisitCallNew(CallNew* node) {
3102#ifdef DEBUG
3103 int original_height = frame_->height();
3104#endif
3105 VirtualFrame::SpilledScope spilled_scope;
3106 Comment cmnt(masm_, "[ CallNew");
3107
3108 // According to ECMA-262, section 11.2.2, page 44, the function
3109 // expression in new calls must be evaluated before the
3110 // arguments. This is different from ordinary calls, where the
3111 // actual function to call is resolved after the arguments have been
3112 // evaluated.
3113
3114 // Compute function to call and use the global object as the
3115 // receiver. There is no need to use the global proxy here because
3116 // it will always be replaced with a newly allocated object.
3117 LoadAndSpill(node->expression());
3118 LoadGlobal();
3119
3120 // Push the arguments ("left-to-right") on the stack.
3121 ZoneList<Expression*>* args = node->arguments();
3122 int arg_count = args->length();
3123 for (int i = 0; i < arg_count; i++) {
3124 LoadAndSpill(args->at(i));
3125 }
3126
3127 // r0: the number of arguments.
3128 Result num_args(r0);
3129 __ mov(r0, Operand(arg_count));
3130
3131 // Load the function into r1 as per calling convention.
3132 Result function(r1);
3133 __ ldr(r1, frame_->ElementAt(arg_count + 1));
3134
3135 // Call the construct call builtin that handles allocation and
3136 // constructor invocation.
3137 CodeForSourcePosition(node->position());
3138 Handle<Code> ic(Builtins::builtin(Builtins::JSConstructCall));
3139 frame_->CallCodeObject(ic,
3140 RelocInfo::CONSTRUCT_CALL,
3141 &num_args,
3142 &function,
3143 arg_count + 1);
3144
3145 // Discard old TOS value and push r0 on the stack (same as Pop(), push(r0)).
3146 __ str(r0, frame_->Top());
3147 ASSERT(frame_->height() == original_height + 1);
3148}
3149
3150
3151void CodeGenerator::GenerateClassOf(ZoneList<Expression*>* args) {
3152 VirtualFrame::SpilledScope spilled_scope;
3153 ASSERT(args->length() == 1);
3154 JumpTarget leave, null, function, non_function_constructor;
3155
3156 // Load the object into r0.
3157 LoadAndSpill(args->at(0));
3158 frame_->EmitPop(r0);
3159
3160 // If the object is a smi, we return null.
3161 __ tst(r0, Operand(kSmiTagMask));
3162 null.Branch(eq);
3163
3164 // Check that the object is a JS object but take special care of JS
3165 // functions to make sure they have 'Function' as their class.
3166 __ CompareObjectType(r0, r0, r1, FIRST_JS_OBJECT_TYPE);
3167 null.Branch(lt);
3168
3169 // As long as JS_FUNCTION_TYPE is the last instance type and it is
3170 // right after LAST_JS_OBJECT_TYPE, we can avoid checking for
3171 // LAST_JS_OBJECT_TYPE.
3172 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
3173 ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
3174 __ cmp(r1, Operand(JS_FUNCTION_TYPE));
3175 function.Branch(eq);
3176
3177 // Check if the constructor in the map is a function.
3178 __ ldr(r0, FieldMemOperand(r0, Map::kConstructorOffset));
3179 __ CompareObjectType(r0, r1, r1, JS_FUNCTION_TYPE);
3180 non_function_constructor.Branch(ne);
3181
3182 // The r0 register now contains the constructor function. Grab the
3183 // instance class name from there.
3184 __ ldr(r0, FieldMemOperand(r0, JSFunction::kSharedFunctionInfoOffset));
3185 __ ldr(r0, FieldMemOperand(r0, SharedFunctionInfo::kInstanceClassNameOffset));
3186 frame_->EmitPush(r0);
3187 leave.Jump();
3188
3189 // Functions have class 'Function'.
3190 function.Bind();
3191 __ mov(r0, Operand(Factory::function_class_symbol()));
3192 frame_->EmitPush(r0);
3193 leave.Jump();
3194
3195 // Objects with a non-function constructor have class 'Object'.
3196 non_function_constructor.Bind();
3197 __ mov(r0, Operand(Factory::Object_symbol()));
3198 frame_->EmitPush(r0);
3199 leave.Jump();
3200
3201 // Non-JS objects have class null.
3202 null.Bind();
3203 __ LoadRoot(r0, Heap::kNullValueRootIndex);
3204 frame_->EmitPush(r0);
3205
3206 // All done.
3207 leave.Bind();
3208}
3209
3210
3211void CodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
3212 VirtualFrame::SpilledScope spilled_scope;
3213 ASSERT(args->length() == 1);
3214 JumpTarget leave;
3215 LoadAndSpill(args->at(0));
3216 frame_->EmitPop(r0); // r0 contains object.
3217 // if (object->IsSmi()) return the object.
3218 __ tst(r0, Operand(kSmiTagMask));
3219 leave.Branch(eq);
3220 // It is a heap object - get map. If (!object->IsJSValue()) return the object.
3221 __ CompareObjectType(r0, r1, r1, JS_VALUE_TYPE);
3222 leave.Branch(ne);
3223 // Load the value.
3224 __ ldr(r0, FieldMemOperand(r0, JSValue::kValueOffset));
3225 leave.Bind();
3226 frame_->EmitPush(r0);
3227}
3228
3229
3230void CodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
3231 VirtualFrame::SpilledScope spilled_scope;
3232 ASSERT(args->length() == 2);
3233 JumpTarget leave;
3234 LoadAndSpill(args->at(0)); // Load the object.
3235 LoadAndSpill(args->at(1)); // Load the value.
3236 frame_->EmitPop(r0); // r0 contains value
3237 frame_->EmitPop(r1); // r1 contains object
3238 // if (object->IsSmi()) return object.
3239 __ tst(r1, Operand(kSmiTagMask));
3240 leave.Branch(eq);
3241 // It is a heap object - get map. If (!object->IsJSValue()) return the object.
3242 __ CompareObjectType(r1, r2, r2, JS_VALUE_TYPE);
3243 leave.Branch(ne);
3244 // Store the value.
3245 __ str(r0, FieldMemOperand(r1, JSValue::kValueOffset));
3246 // Update the write barrier.
3247 __ mov(r2, Operand(JSValue::kValueOffset - kHeapObjectTag));
3248 __ RecordWrite(r1, r2, r3);
3249 // Leave.
3250 leave.Bind();
3251 frame_->EmitPush(r0);
3252}
3253
3254
3255void CodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
3256 VirtualFrame::SpilledScope spilled_scope;
3257 ASSERT(args->length() == 1);
3258 LoadAndSpill(args->at(0));
3259 frame_->EmitPop(r0);
3260 __ tst(r0, Operand(kSmiTagMask));
3261 cc_reg_ = eq;
3262}
3263
3264
3265void CodeGenerator::GenerateLog(ZoneList<Expression*>* args) {
3266 VirtualFrame::SpilledScope spilled_scope;
3267 // See comment in CodeGenerator::GenerateLog in codegen-ia32.cc.
3268 ASSERT_EQ(args->length(), 3);
3269#ifdef ENABLE_LOGGING_AND_PROFILING
3270 if (ShouldGenerateLog(args->at(0))) {
3271 LoadAndSpill(args->at(1));
3272 LoadAndSpill(args->at(2));
3273 __ CallRuntime(Runtime::kLog, 2);
3274 }
3275#endif
3276 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
3277 frame_->EmitPush(r0);
3278}
3279
3280
3281void CodeGenerator::GenerateIsNonNegativeSmi(ZoneList<Expression*>* args) {
3282 VirtualFrame::SpilledScope spilled_scope;
3283 ASSERT(args->length() == 1);
3284 LoadAndSpill(args->at(0));
3285 frame_->EmitPop(r0);
3286 __ tst(r0, Operand(kSmiTagMask | 0x80000000u));
3287 cc_reg_ = eq;
3288}
3289
3290
3291// This should generate code that performs a charCodeAt() call or returns
3292// undefined in order to trigger the slow case, Runtime_StringCharCodeAt.
3293// It is not yet implemented on ARM, so it always goes to the slow case.
3294void CodeGenerator::GenerateFastCharCodeAt(ZoneList<Expression*>* args) {
3295 VirtualFrame::SpilledScope spilled_scope;
3296 ASSERT(args->length() == 2);
3297 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
3298 frame_->EmitPush(r0);
3299}
3300
3301
3302void CodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
3303 VirtualFrame::SpilledScope spilled_scope;
3304 ASSERT(args->length() == 1);
3305 LoadAndSpill(args->at(0));
3306 JumpTarget answer;
3307 // We need the CC bits to come out as not_equal in the case where the
3308 // object is a smi. This can't be done with the usual test opcode so
3309 // we use XOR to get the right CC bits.
3310 frame_->EmitPop(r0);
3311 __ and_(r1, r0, Operand(kSmiTagMask));
3312 __ eor(r1, r1, Operand(kSmiTagMask), SetCC);
3313 answer.Branch(ne);
3314 // It is a heap object - get the map. Check if the object is a JS array.
3315 __ CompareObjectType(r0, r1, r1, JS_ARRAY_TYPE);
3316 answer.Bind();
3317 cc_reg_ = eq;
3318}
3319
3320
3321void CodeGenerator::GenerateIsConstructCall(ZoneList<Expression*>* args) {
3322 VirtualFrame::SpilledScope spilled_scope;
3323 ASSERT(args->length() == 0);
3324
3325 // Get the frame pointer for the calling frame.
3326 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
3327
3328 // Skip the arguments adaptor frame if it exists.
3329 Label check_frame_marker;
3330 __ ldr(r1, MemOperand(r2, StandardFrameConstants::kContextOffset));
3331 __ cmp(r1, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3332 __ b(ne, &check_frame_marker);
3333 __ ldr(r2, MemOperand(r2, StandardFrameConstants::kCallerFPOffset));
3334
3335 // Check the marker in the calling frame.
3336 __ bind(&check_frame_marker);
3337 __ ldr(r1, MemOperand(r2, StandardFrameConstants::kMarkerOffset));
3338 __ cmp(r1, Operand(Smi::FromInt(StackFrame::CONSTRUCT)));
3339 cc_reg_ = eq;
3340}
3341
3342
3343void CodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
3344 VirtualFrame::SpilledScope spilled_scope;
3345 ASSERT(args->length() == 0);
3346
3347 // Seed the result with the formal parameters count, which will be used
3348 // in case no arguments adaptor frame is found below the current frame.
3349 __ mov(r0, Operand(Smi::FromInt(scope_->num_parameters())));
3350
3351 // Call the shared stub to get to the arguments.length.
3352 ArgumentsAccessStub stub(ArgumentsAccessStub::READ_LENGTH);
3353 frame_->CallStub(&stub, 0);
3354 frame_->EmitPush(r0);
3355}
3356
3357
3358void CodeGenerator::GenerateArgumentsAccess(ZoneList<Expression*>* args) {
3359 VirtualFrame::SpilledScope spilled_scope;
3360 ASSERT(args->length() == 1);
3361
3362 // Satisfy contract with ArgumentsAccessStub:
3363 // Load the key into r1 and the formal parameters count into r0.
3364 LoadAndSpill(args->at(0));
3365 frame_->EmitPop(r1);
3366 __ mov(r0, Operand(Smi::FromInt(scope_->num_parameters())));
3367
3368 // Call the shared stub to get to arguments[key].
3369 ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT);
3370 frame_->CallStub(&stub, 0);
3371 frame_->EmitPush(r0);
3372}
3373
3374
3375void CodeGenerator::GenerateRandomPositiveSmi(ZoneList<Expression*>* args) {
3376 VirtualFrame::SpilledScope spilled_scope;
3377 ASSERT(args->length() == 0);
3378 __ Call(ExternalReference::random_positive_smi_function().address(),
3379 RelocInfo::RUNTIME_ENTRY);
3380 frame_->EmitPush(r0);
3381}
3382
3383
3384void CodeGenerator::GenerateFastMathOp(MathOp op, ZoneList<Expression*>* args) {
3385 VirtualFrame::SpilledScope spilled_scope;
3386 LoadAndSpill(args->at(0));
3387 switch (op) {
3388 case SIN:
3389 frame_->CallRuntime(Runtime::kMath_sin, 1);
3390 break;
3391 case COS:
3392 frame_->CallRuntime(Runtime::kMath_cos, 1);
3393 break;
3394 }
3395 frame_->EmitPush(r0);
3396}
3397
3398
3399void CodeGenerator::GenerateObjectEquals(ZoneList<Expression*>* args) {
3400 VirtualFrame::SpilledScope spilled_scope;
3401 ASSERT(args->length() == 2);
3402
3403 // Load the two objects into registers and perform the comparison.
3404 LoadAndSpill(args->at(0));
3405 LoadAndSpill(args->at(1));
3406 frame_->EmitPop(r0);
3407 frame_->EmitPop(r1);
3408 __ cmp(r0, Operand(r1));
3409 cc_reg_ = eq;
3410}
3411
3412
3413void CodeGenerator::VisitCallRuntime(CallRuntime* node) {
3414#ifdef DEBUG
3415 int original_height = frame_->height();
3416#endif
3417 VirtualFrame::SpilledScope spilled_scope;
3418 if (CheckForInlineRuntimeCall(node)) {
3419 ASSERT((has_cc() && frame_->height() == original_height) ||
3420 (!has_cc() && frame_->height() == original_height + 1));
3421 return;
3422 }
3423
3424 ZoneList<Expression*>* args = node->arguments();
3425 Comment cmnt(masm_, "[ CallRuntime");
3426 Runtime::Function* function = node->function();
3427
3428 if (function == NULL) {
3429 // Prepare stack for calling JS runtime function.
3430 __ mov(r0, Operand(node->name()));
3431 frame_->EmitPush(r0);
3432 // Push the builtins object found in the current global object.
3433 __ ldr(r1, GlobalObject());
3434 __ ldr(r0, FieldMemOperand(r1, GlobalObject::kBuiltinsOffset));
3435 frame_->EmitPush(r0);
3436 }
3437
3438 // Push the arguments ("left-to-right").
3439 int arg_count = args->length();
3440 for (int i = 0; i < arg_count; i++) {
3441 LoadAndSpill(args->at(i));
3442 }
3443
3444 if (function == NULL) {
3445 // Call the JS runtime function.
3446 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
3447 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
3448 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET, arg_count + 1);
3449 __ ldr(cp, frame_->Context());
3450 frame_->Drop();
3451 frame_->EmitPush(r0);
3452 } else {
3453 // Call the C runtime function.
3454 frame_->CallRuntime(function, arg_count);
3455 frame_->EmitPush(r0);
3456 }
3457 ASSERT(frame_->height() == original_height + 1);
3458}
3459
3460
3461void CodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
3462#ifdef DEBUG
3463 int original_height = frame_->height();
3464#endif
3465 VirtualFrame::SpilledScope spilled_scope;
3466 Comment cmnt(masm_, "[ UnaryOperation");
3467
3468 Token::Value op = node->op();
3469
3470 if (op == Token::NOT) {
3471 LoadConditionAndSpill(node->expression(),
3472 NOT_INSIDE_TYPEOF,
3473 false_target(),
3474 true_target(),
3475 true);
3476 // LoadCondition may (and usually does) leave a test and branch to
3477 // be emitted by the caller. In that case, negate the condition.
3478 if (has_cc()) cc_reg_ = NegateCondition(cc_reg_);
3479
3480 } else if (op == Token::DELETE) {
3481 Property* property = node->expression()->AsProperty();
3482 Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
3483 if (property != NULL) {
3484 LoadAndSpill(property->obj());
3485 LoadAndSpill(property->key());
3486 Result arg_count(r0);
3487 __ mov(r0, Operand(1)); // not counting receiver
3488 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, &arg_count, 2);
3489
3490 } else if (variable != NULL) {
3491 Slot* slot = variable->slot();
3492 if (variable->is_global()) {
3493 LoadGlobal();
3494 __ mov(r0, Operand(variable->name()));
3495 frame_->EmitPush(r0);
3496 Result arg_count(r0);
3497 __ mov(r0, Operand(1)); // not counting receiver
3498 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, &arg_count, 2);
3499
3500 } else if (slot != NULL && slot->type() == Slot::LOOKUP) {
3501 // lookup the context holding the named variable
3502 frame_->EmitPush(cp);
3503 __ mov(r0, Operand(variable->name()));
3504 frame_->EmitPush(r0);
3505 frame_->CallRuntime(Runtime::kLookupContext, 2);
3506 // r0: context
3507 frame_->EmitPush(r0);
3508 __ mov(r0, Operand(variable->name()));
3509 frame_->EmitPush(r0);
3510 Result arg_count(r0);
3511 __ mov(r0, Operand(1)); // not counting receiver
3512 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, &arg_count, 2);
3513
3514 } else {
3515 // Default: Result of deleting non-global, not dynamically
3516 // introduced variables is false.
3517 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
3518 }
3519
3520 } else {
3521 // Default: Result of deleting expressions is true.
3522 LoadAndSpill(node->expression()); // may have side-effects
3523 frame_->Drop();
3524 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
3525 }
3526 frame_->EmitPush(r0);
3527
3528 } else if (op == Token::TYPEOF) {
3529 // Special case for loading the typeof expression; see comment on
3530 // LoadTypeofExpression().
3531 LoadTypeofExpression(node->expression());
3532 frame_->CallRuntime(Runtime::kTypeof, 1);
3533 frame_->EmitPush(r0); // r0 has result
3534
3535 } else {
3536 LoadAndSpill(node->expression());
3537 frame_->EmitPop(r0);
3538 switch (op) {
3539 case Token::NOT:
3540 case Token::DELETE:
3541 case Token::TYPEOF:
3542 UNREACHABLE(); // handled above
3543 break;
3544
3545 case Token::SUB: {
3546 bool overwrite =
3547 (node->expression()->AsBinaryOperation() != NULL &&
3548 node->expression()->AsBinaryOperation()->ResultOverwriteAllowed());
3549 UnarySubStub stub(overwrite);
3550 frame_->CallStub(&stub, 0);
3551 break;
3552 }
3553
3554 case Token::BIT_NOT: {
3555 // smi check
3556 JumpTarget smi_label;
3557 JumpTarget continue_label;
3558 __ tst(r0, Operand(kSmiTagMask));
3559 smi_label.Branch(eq);
3560
3561 frame_->EmitPush(r0);
3562 Result arg_count(r0);
3563 __ mov(r0, Operand(0)); // not counting receiver
3564 frame_->InvokeBuiltin(Builtins::BIT_NOT, CALL_JS, &arg_count, 1);
3565
3566 continue_label.Jump();
3567 smi_label.Bind();
3568 __ mvn(r0, Operand(r0));
3569 __ bic(r0, r0, Operand(kSmiTagMask)); // bit-clear inverted smi-tag
3570 continue_label.Bind();
3571 break;
3572 }
3573
3574 case Token::VOID:
3575 // since the stack top is cached in r0, popping and then
3576 // pushing a value can be done by just writing to r0.
3577 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
3578 break;
3579
3580 case Token::ADD: {
3581 // Smi check.
3582 JumpTarget continue_label;
3583 __ tst(r0, Operand(kSmiTagMask));
3584 continue_label.Branch(eq);
3585 frame_->EmitPush(r0);
3586 Result arg_count(r0);
3587 __ mov(r0, Operand(0)); // not counting receiver
3588 frame_->InvokeBuiltin(Builtins::TO_NUMBER, CALL_JS, &arg_count, 1);
3589 continue_label.Bind();
3590 break;
3591 }
3592 default:
3593 UNREACHABLE();
3594 }
3595 frame_->EmitPush(r0); // r0 has result
3596 }
3597 ASSERT(!has_valid_frame() ||
3598 (has_cc() && frame_->height() == original_height) ||
3599 (!has_cc() && frame_->height() == original_height + 1));
3600}
3601
3602
3603void CodeGenerator::VisitCountOperation(CountOperation* node) {
3604#ifdef DEBUG
3605 int original_height = frame_->height();
3606#endif
3607 VirtualFrame::SpilledScope spilled_scope;
3608 Comment cmnt(masm_, "[ CountOperation");
3609
3610 bool is_postfix = node->is_postfix();
3611 bool is_increment = node->op() == Token::INC;
3612
3613 Variable* var = node->expression()->AsVariableProxy()->AsVariable();
3614 bool is_const = (var != NULL && var->mode() == Variable::CONST);
3615
3616 // Postfix: Make room for the result.
3617 if (is_postfix) {
3618 __ mov(r0, Operand(0));
3619 frame_->EmitPush(r0);
3620 }
3621
3622 { Reference target(this, node->expression());
3623 if (target.is_illegal()) {
3624 // Spoof the virtual frame to have the expected height (one higher
3625 // than on entry).
3626 if (!is_postfix) {
3627 __ mov(r0, Operand(Smi::FromInt(0)));
3628 frame_->EmitPush(r0);
3629 }
3630 ASSERT(frame_->height() == original_height + 1);
3631 return;
3632 }
3633 target.GetValueAndSpill(NOT_INSIDE_TYPEOF);
3634 frame_->EmitPop(r0);
3635
3636 JumpTarget slow;
3637 JumpTarget exit;
3638
3639 // Load the value (1) into register r1.
3640 __ mov(r1, Operand(Smi::FromInt(1)));
3641
3642 // Check for smi operand.
3643 __ tst(r0, Operand(kSmiTagMask));
3644 slow.Branch(ne);
3645
3646 // Postfix: Store the old value as the result.
3647 if (is_postfix) {
3648 __ str(r0, frame_->ElementAt(target.size()));
3649 }
3650
3651 // Perform optimistic increment/decrement.
3652 if (is_increment) {
3653 __ add(r0, r0, Operand(r1), SetCC);
3654 } else {
3655 __ sub(r0, r0, Operand(r1), SetCC);
3656 }
3657
3658 // If the increment/decrement didn't overflow, we're done.
3659 exit.Branch(vc);
3660
3661 // Revert optimistic increment/decrement.
3662 if (is_increment) {
3663 __ sub(r0, r0, Operand(r1));
3664 } else {
3665 __ add(r0, r0, Operand(r1));
3666 }
3667
3668 // Slow case: Convert to number.
3669 slow.Bind();
3670 {
3671 // Convert the operand to a number.
3672 frame_->EmitPush(r0);
3673 Result arg_count(r0);
3674 __ mov(r0, Operand(0));
3675 frame_->InvokeBuiltin(Builtins::TO_NUMBER, CALL_JS, &arg_count, 1);
3676 }
3677 if (is_postfix) {
3678 // Postfix: store to result (on the stack).
3679 __ str(r0, frame_->ElementAt(target.size()));
3680 }
3681
3682 // Compute the new value.
3683 __ mov(r1, Operand(Smi::FromInt(1)));
3684 frame_->EmitPush(r0);
3685 frame_->EmitPush(r1);
3686 if (is_increment) {
3687 frame_->CallRuntime(Runtime::kNumberAdd, 2);
3688 } else {
3689 frame_->CallRuntime(Runtime::kNumberSub, 2);
3690 }
3691
3692 // Store the new value in the target if not const.
3693 exit.Bind();
3694 frame_->EmitPush(r0);
3695 if (!is_const) target.SetValue(NOT_CONST_INIT);
3696 }
3697
3698 // Postfix: Discard the new value and use the old.
3699 if (is_postfix) frame_->EmitPop(r0);
3700 ASSERT(frame_->height() == original_height + 1);
3701}
3702
3703
3704void CodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
3705#ifdef DEBUG
3706 int original_height = frame_->height();
3707#endif
3708 VirtualFrame::SpilledScope spilled_scope;
3709 Comment cmnt(masm_, "[ BinaryOperation");
3710 Token::Value op = node->op();
3711
3712 // According to ECMA-262 section 11.11, page 58, the binary logical
3713 // operators must yield the result of one of the two expressions
3714 // before any ToBoolean() conversions. This means that the value
3715 // produced by a && or || operator is not necessarily a boolean.
3716
3717 // NOTE: If the left hand side produces a materialized value (not in
3718 // the CC register), we force the right hand side to do the
3719 // same. This is necessary because we may have to branch to the exit
3720 // after evaluating the left hand side (due to the shortcut
3721 // semantics), but the compiler must (statically) know if the result
3722 // of compiling the binary operation is materialized or not.
3723
3724 if (op == Token::AND) {
3725 JumpTarget is_true;
3726 LoadConditionAndSpill(node->left(),
3727 NOT_INSIDE_TYPEOF,
3728 &is_true,
3729 false_target(),
3730 false);
3731 if (has_valid_frame() && !has_cc()) {
3732 // The left-hand side result is on top of the virtual frame.
3733 JumpTarget pop_and_continue;
3734 JumpTarget exit;
3735
3736 __ ldr(r0, frame_->Top()); // Duplicate the stack top.
3737 frame_->EmitPush(r0);
3738 // Avoid popping the result if it converts to 'false' using the
3739 // standard ToBoolean() conversion as described in ECMA-262,
3740 // section 9.2, page 30.
3741 ToBoolean(&pop_and_continue, &exit);
3742 Branch(false, &exit);
3743
3744 // Pop the result of evaluating the first part.
3745 pop_and_continue.Bind();
3746 frame_->EmitPop(r0);
3747
3748 // Evaluate right side expression.
3749 is_true.Bind();
3750 LoadAndSpill(node->right());
3751
3752 // Exit (always with a materialized value).
3753 exit.Bind();
3754 } else if (has_cc() || is_true.is_linked()) {
3755 // The left-hand side is either (a) partially compiled to
3756 // control flow with a final branch left to emit or (b) fully
3757 // compiled to control flow and possibly true.
3758 if (has_cc()) {
3759 Branch(false, false_target());
3760 }
3761 is_true.Bind();
3762 LoadConditionAndSpill(node->right(),
3763 NOT_INSIDE_TYPEOF,
3764 true_target(),
3765 false_target(),
3766 false);
3767 } else {
3768 // Nothing to do.
3769 ASSERT(!has_valid_frame() && !has_cc() && !is_true.is_linked());
3770 }
3771
3772 } else if (op == Token::OR) {
3773 JumpTarget is_false;
3774 LoadConditionAndSpill(node->left(),
3775 NOT_INSIDE_TYPEOF,
3776 true_target(),
3777 &is_false,
3778 false);
3779 if (has_valid_frame() && !has_cc()) {
3780 // The left-hand side result is on top of the virtual frame.
3781 JumpTarget pop_and_continue;
3782 JumpTarget exit;
3783
3784 __ ldr(r0, frame_->Top());
3785 frame_->EmitPush(r0);
3786 // Avoid popping the result if it converts to 'true' using the
3787 // standard ToBoolean() conversion as described in ECMA-262,
3788 // section 9.2, page 30.
3789 ToBoolean(&exit, &pop_and_continue);
3790 Branch(true, &exit);
3791
3792 // Pop the result of evaluating the first part.
3793 pop_and_continue.Bind();
3794 frame_->EmitPop(r0);
3795
3796 // Evaluate right side expression.
3797 is_false.Bind();
3798 LoadAndSpill(node->right());
3799
3800 // Exit (always with a materialized value).
3801 exit.Bind();
3802 } else if (has_cc() || is_false.is_linked()) {
3803 // The left-hand side is either (a) partially compiled to
3804 // control flow with a final branch left to emit or (b) fully
3805 // compiled to control flow and possibly false.
3806 if (has_cc()) {
3807 Branch(true, true_target());
3808 }
3809 is_false.Bind();
3810 LoadConditionAndSpill(node->right(),
3811 NOT_INSIDE_TYPEOF,
3812 true_target(),
3813 false_target(),
3814 false);
3815 } else {
3816 // Nothing to do.
3817 ASSERT(!has_valid_frame() && !has_cc() && !is_false.is_linked());
3818 }
3819
3820 } else {
3821 // Optimize for the case where (at least) one of the expressions
3822 // is a literal small integer.
3823 Literal* lliteral = node->left()->AsLiteral();
3824 Literal* rliteral = node->right()->AsLiteral();
3825 // NOTE: The code below assumes that the slow cases (calls to runtime)
3826 // never return a constant/immutable object.
3827 bool overwrite_left =
3828 (node->left()->AsBinaryOperation() != NULL &&
3829 node->left()->AsBinaryOperation()->ResultOverwriteAllowed());
3830 bool overwrite_right =
3831 (node->right()->AsBinaryOperation() != NULL &&
3832 node->right()->AsBinaryOperation()->ResultOverwriteAllowed());
3833
3834 if (rliteral != NULL && rliteral->handle()->IsSmi()) {
3835 LoadAndSpill(node->left());
3836 SmiOperation(node->op(),
3837 rliteral->handle(),
3838 false,
3839 overwrite_right ? OVERWRITE_RIGHT : NO_OVERWRITE);
3840
3841 } else if (lliteral != NULL && lliteral->handle()->IsSmi()) {
3842 LoadAndSpill(node->right());
3843 SmiOperation(node->op(),
3844 lliteral->handle(),
3845 true,
3846 overwrite_left ? OVERWRITE_LEFT : NO_OVERWRITE);
3847
3848 } else {
3849 OverwriteMode overwrite_mode = NO_OVERWRITE;
3850 if (overwrite_left) {
3851 overwrite_mode = OVERWRITE_LEFT;
3852 } else if (overwrite_right) {
3853 overwrite_mode = OVERWRITE_RIGHT;
3854 }
3855 LoadAndSpill(node->left());
3856 LoadAndSpill(node->right());
3857 GenericBinaryOperation(node->op(), overwrite_mode);
3858 }
3859 frame_->EmitPush(r0);
3860 }
3861 ASSERT(!has_valid_frame() ||
3862 (has_cc() && frame_->height() == original_height) ||
3863 (!has_cc() && frame_->height() == original_height + 1));
3864}
3865
3866
3867void CodeGenerator::VisitThisFunction(ThisFunction* node) {
3868#ifdef DEBUG
3869 int original_height = frame_->height();
3870#endif
3871 VirtualFrame::SpilledScope spilled_scope;
3872 __ ldr(r0, frame_->Function());
3873 frame_->EmitPush(r0);
3874 ASSERT(frame_->height() == original_height + 1);
3875}
3876
3877
3878void CodeGenerator::VisitCompareOperation(CompareOperation* node) {
3879#ifdef DEBUG
3880 int original_height = frame_->height();
3881#endif
3882 VirtualFrame::SpilledScope spilled_scope;
3883 Comment cmnt(masm_, "[ CompareOperation");
3884
3885 // Get the expressions from the node.
3886 Expression* left = node->left();
3887 Expression* right = node->right();
3888 Token::Value op = node->op();
3889
3890 // To make null checks efficient, we check if either left or right is the
3891 // literal 'null'. If so, we optimize the code by inlining a null check
3892 // instead of calling the (very) general runtime routine for checking
3893 // equality.
3894 if (op == Token::EQ || op == Token::EQ_STRICT) {
3895 bool left_is_null =
3896 left->AsLiteral() != NULL && left->AsLiteral()->IsNull();
3897 bool right_is_null =
3898 right->AsLiteral() != NULL && right->AsLiteral()->IsNull();
3899 // The 'null' value can only be equal to 'null' or 'undefined'.
3900 if (left_is_null || right_is_null) {
3901 LoadAndSpill(left_is_null ? right : left);
3902 frame_->EmitPop(r0);
3903 __ LoadRoot(ip, Heap::kNullValueRootIndex);
3904 __ cmp(r0, ip);
3905
3906 // The 'null' value is only equal to 'undefined' if using non-strict
3907 // comparisons.
3908 if (op != Token::EQ_STRICT) {
3909 true_target()->Branch(eq);
3910
3911 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
3912 __ cmp(r0, Operand(ip));
3913 true_target()->Branch(eq);
3914
3915 __ tst(r0, Operand(kSmiTagMask));
3916 false_target()->Branch(eq);
3917
3918 // It can be an undetectable object.
3919 __ ldr(r0, FieldMemOperand(r0, HeapObject::kMapOffset));
3920 __ ldrb(r0, FieldMemOperand(r0, Map::kBitFieldOffset));
3921 __ and_(r0, r0, Operand(1 << Map::kIsUndetectable));
3922 __ cmp(r0, Operand(1 << Map::kIsUndetectable));
3923 }
3924
3925 cc_reg_ = eq;
3926 ASSERT(has_cc() && frame_->height() == original_height);
3927 return;
3928 }
3929 }
3930
3931 // To make typeof testing for natives implemented in JavaScript really
3932 // efficient, we generate special code for expressions of the form:
3933 // 'typeof <expression> == <string>'.
3934 UnaryOperation* operation = left->AsUnaryOperation();
3935 if ((op == Token::EQ || op == Token::EQ_STRICT) &&
3936 (operation != NULL && operation->op() == Token::TYPEOF) &&
3937 (right->AsLiteral() != NULL &&
3938 right->AsLiteral()->handle()->IsString())) {
3939 Handle<String> check(String::cast(*right->AsLiteral()->handle()));
3940
3941 // Load the operand, move it to register r1.
3942 LoadTypeofExpression(operation->expression());
3943 frame_->EmitPop(r1);
3944
3945 if (check->Equals(Heap::number_symbol())) {
3946 __ tst(r1, Operand(kSmiTagMask));
3947 true_target()->Branch(eq);
3948 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
3949 __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex);
3950 __ cmp(r1, ip);
3951 cc_reg_ = eq;
3952
3953 } else if (check->Equals(Heap::string_symbol())) {
3954 __ tst(r1, Operand(kSmiTagMask));
3955 false_target()->Branch(eq);
3956
3957 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
3958
3959 // It can be an undetectable string object.
3960 __ ldrb(r2, FieldMemOperand(r1, Map::kBitFieldOffset));
3961 __ and_(r2, r2, Operand(1 << Map::kIsUndetectable));
3962 __ cmp(r2, Operand(1 << Map::kIsUndetectable));
3963 false_target()->Branch(eq);
3964
3965 __ ldrb(r2, FieldMemOperand(r1, Map::kInstanceTypeOffset));
3966 __ cmp(r2, Operand(FIRST_NONSTRING_TYPE));
3967 cc_reg_ = lt;
3968
3969 } else if (check->Equals(Heap::boolean_symbol())) {
3970 __ LoadRoot(ip, Heap::kTrueValueRootIndex);
3971 __ cmp(r1, ip);
3972 true_target()->Branch(eq);
3973 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
3974 __ cmp(r1, ip);
3975 cc_reg_ = eq;
3976
3977 } else if (check->Equals(Heap::undefined_symbol())) {
3978 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
3979 __ cmp(r1, ip);
3980 true_target()->Branch(eq);
3981
3982 __ tst(r1, Operand(kSmiTagMask));
3983 false_target()->Branch(eq);
3984
3985 // It can be an undetectable object.
3986 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
3987 __ ldrb(r2, FieldMemOperand(r1, Map::kBitFieldOffset));
3988 __ and_(r2, r2, Operand(1 << Map::kIsUndetectable));
3989 __ cmp(r2, Operand(1 << Map::kIsUndetectable));
3990
3991 cc_reg_ = eq;
3992
3993 } else if (check->Equals(Heap::function_symbol())) {
3994 __ tst(r1, Operand(kSmiTagMask));
3995 false_target()->Branch(eq);
3996 __ CompareObjectType(r1, r1, r1, JS_FUNCTION_TYPE);
3997 cc_reg_ = eq;
3998
3999 } else if (check->Equals(Heap::object_symbol())) {
4000 __ tst(r1, Operand(kSmiTagMask));
4001 false_target()->Branch(eq);
4002
4003 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset));
4004 __ LoadRoot(ip, Heap::kNullValueRootIndex);
4005 __ cmp(r1, ip);
4006 true_target()->Branch(eq);
4007
4008 // It can be an undetectable object.
4009 __ ldrb(r1, FieldMemOperand(r2, Map::kBitFieldOffset));
4010 __ and_(r1, r1, Operand(1 << Map::kIsUndetectable));
4011 __ cmp(r1, Operand(1 << Map::kIsUndetectable));
4012 false_target()->Branch(eq);
4013
4014 __ ldrb(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
4015 __ cmp(r2, Operand(FIRST_JS_OBJECT_TYPE));
4016 false_target()->Branch(lt);
4017 __ cmp(r2, Operand(LAST_JS_OBJECT_TYPE));
4018 cc_reg_ = le;
4019
4020 } else {
4021 // Uncommon case: typeof testing against a string literal that is
4022 // never returned from the typeof operator.
4023 false_target()->Jump();
4024 }
4025 ASSERT(!has_valid_frame() ||
4026 (has_cc() && frame_->height() == original_height));
4027 return;
4028 }
4029
4030 switch (op) {
4031 case Token::EQ:
4032 Comparison(eq, left, right, false);
4033 break;
4034
4035 case Token::LT:
4036 Comparison(lt, left, right);
4037 break;
4038
4039 case Token::GT:
4040 Comparison(gt, left, right);
4041 break;
4042
4043 case Token::LTE:
4044 Comparison(le, left, right);
4045 break;
4046
4047 case Token::GTE:
4048 Comparison(ge, left, right);
4049 break;
4050
4051 case Token::EQ_STRICT:
4052 Comparison(eq, left, right, true);
4053 break;
4054
4055 case Token::IN: {
4056 LoadAndSpill(left);
4057 LoadAndSpill(right);
4058 Result arg_count(r0);
4059 __ mov(r0, Operand(1)); // not counting receiver
4060 frame_->InvokeBuiltin(Builtins::IN, CALL_JS, &arg_count, 2);
4061 frame_->EmitPush(r0);
4062 break;
4063 }
4064
4065 case Token::INSTANCEOF: {
4066 LoadAndSpill(left);
4067 LoadAndSpill(right);
4068 InstanceofStub stub;
4069 frame_->CallStub(&stub, 2);
4070 // At this point if instanceof succeeded then r0 == 0.
4071 __ tst(r0, Operand(r0));
4072 cc_reg_ = eq;
4073 break;
4074 }
4075
4076 default:
4077 UNREACHABLE();
4078 }
4079 ASSERT((has_cc() && frame_->height() == original_height) ||
4080 (!has_cc() && frame_->height() == original_height + 1));
4081}
4082
4083
4084#ifdef DEBUG
4085bool CodeGenerator::HasValidEntryRegisters() { return true; }
4086#endif
4087
4088
4089#undef __
4090#define __ ACCESS_MASM(masm)
4091
4092
4093Handle<String> Reference::GetName() {
4094 ASSERT(type_ == NAMED);
4095 Property* property = expression_->AsProperty();
4096 if (property == NULL) {
4097 // Global variable reference treated as a named property reference.
4098 VariableProxy* proxy = expression_->AsVariableProxy();
4099 ASSERT(proxy->AsVariable() != NULL);
4100 ASSERT(proxy->AsVariable()->is_global());
4101 return proxy->name();
4102 } else {
4103 Literal* raw_name = property->key()->AsLiteral();
4104 ASSERT(raw_name != NULL);
4105 return Handle<String>(String::cast(*raw_name->handle()));
4106 }
4107}
4108
4109
4110void Reference::GetValue(TypeofState typeof_state) {
4111 ASSERT(cgen_->HasValidEntryRegisters());
4112 ASSERT(!is_illegal());
4113 ASSERT(!cgen_->has_cc());
4114 MacroAssembler* masm = cgen_->masm();
4115 Property* property = expression_->AsProperty();
4116 if (property != NULL) {
4117 cgen_->CodeForSourcePosition(property->position());
4118 }
4119
4120 switch (type_) {
4121 case SLOT: {
4122 Comment cmnt(masm, "[ Load from Slot");
4123 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
4124 ASSERT(slot != NULL);
4125 cgen_->LoadFromSlot(slot, typeof_state);
4126 break;
4127 }
4128
4129 case NAMED: {
4130 // TODO(1241834): Make sure that this it is safe to ignore the
4131 // distinction between expressions in a typeof and not in a typeof. If
4132 // there is a chance that reference errors can be thrown below, we
4133 // must distinguish between the two kinds of loads (typeof expression
4134 // loads must not throw a reference error).
4135 VirtualFrame* frame = cgen_->frame();
4136 Comment cmnt(masm, "[ Load from named Property");
4137 Handle<String> name(GetName());
4138 Variable* var = expression_->AsVariableProxy()->AsVariable();
4139 Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
4140 // Setup the name register.
4141 Result name_reg(r2);
4142 __ mov(r2, Operand(name));
4143 ASSERT(var == NULL || var->is_global());
4144 RelocInfo::Mode rmode = (var == NULL)
4145 ? RelocInfo::CODE_TARGET
4146 : RelocInfo::CODE_TARGET_CONTEXT;
4147 frame->CallCodeObject(ic, rmode, &name_reg, 0);
4148 frame->EmitPush(r0);
4149 break;
4150 }
4151
4152 case KEYED: {
4153 // TODO(1241834): Make sure that this it is safe to ignore the
4154 // distinction between expressions in a typeof and not in a typeof.
4155
4156 // TODO(181): Implement inlined version of array indexing once
4157 // loop nesting is properly tracked on ARM.
4158 VirtualFrame* frame = cgen_->frame();
4159 Comment cmnt(masm, "[ Load from keyed Property");
4160 ASSERT(property != NULL);
4161 Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize));
4162 Variable* var = expression_->AsVariableProxy()->AsVariable();
4163 ASSERT(var == NULL || var->is_global());
4164 RelocInfo::Mode rmode = (var == NULL)
4165 ? RelocInfo::CODE_TARGET
4166 : RelocInfo::CODE_TARGET_CONTEXT;
4167 frame->CallCodeObject(ic, rmode, 0);
4168 frame->EmitPush(r0);
4169 break;
4170 }
4171
4172 default:
4173 UNREACHABLE();
4174 }
4175}
4176
4177
4178void Reference::SetValue(InitState init_state) {
4179 ASSERT(!is_illegal());
4180 ASSERT(!cgen_->has_cc());
4181 MacroAssembler* masm = cgen_->masm();
4182 VirtualFrame* frame = cgen_->frame();
4183 Property* property = expression_->AsProperty();
4184 if (property != NULL) {
4185 cgen_->CodeForSourcePosition(property->position());
4186 }
4187
4188 switch (type_) {
4189 case SLOT: {
4190 Comment cmnt(masm, "[ Store to Slot");
4191 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
4192 ASSERT(slot != NULL);
4193 if (slot->type() == Slot::LOOKUP) {
4194 ASSERT(slot->var()->is_dynamic());
4195
4196 // For now, just do a runtime call.
4197 frame->EmitPush(cp);
4198 __ mov(r0, Operand(slot->var()->name()));
4199 frame->EmitPush(r0);
4200
4201 if (init_state == CONST_INIT) {
4202 // Same as the case for a normal store, but ignores attribute
4203 // (e.g. READ_ONLY) of context slot so that we can initialize
4204 // const properties (introduced via eval("const foo = (some
4205 // expr);")). Also, uses the current function context instead of
4206 // the top context.
4207 //
4208 // Note that we must declare the foo upon entry of eval(), via a
4209 // context slot declaration, but we cannot initialize it at the
4210 // same time, because the const declaration may be at the end of
4211 // the eval code (sigh...) and the const variable may have been
4212 // used before (where its value is 'undefined'). Thus, we can only
4213 // do the initialization when we actually encounter the expression
4214 // and when the expression operands are defined and valid, and
4215 // thus we need the split into 2 operations: declaration of the
4216 // context slot followed by initialization.
4217 frame->CallRuntime(Runtime::kInitializeConstContextSlot, 3);
4218 } else {
4219 frame->CallRuntime(Runtime::kStoreContextSlot, 3);
4220 }
4221 // Storing a variable must keep the (new) value on the expression
4222 // stack. This is necessary for compiling assignment expressions.
4223 frame->EmitPush(r0);
4224
4225 } else {
4226 ASSERT(!slot->var()->is_dynamic());
4227
4228 JumpTarget exit;
4229 if (init_state == CONST_INIT) {
4230 ASSERT(slot->var()->mode() == Variable::CONST);
4231 // Only the first const initialization must be executed (the slot
4232 // still contains 'the hole' value). When the assignment is
4233 // executed, the code is identical to a normal store (see below).
4234 Comment cmnt(masm, "[ Init const");
4235 __ ldr(r2, cgen_->SlotOperand(slot, r2));
4236 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
4237 __ cmp(r2, ip);
4238 exit.Branch(ne);
4239 }
4240
4241 // We must execute the store. Storing a variable must keep the
4242 // (new) value on the stack. This is necessary for compiling
4243 // assignment expressions.
4244 //
4245 // Note: We will reach here even with slot->var()->mode() ==
4246 // Variable::CONST because of const declarations which will
4247 // initialize consts to 'the hole' value and by doing so, end up
4248 // calling this code. r2 may be loaded with context; used below in
4249 // RecordWrite.
4250 frame->EmitPop(r0);
4251 __ str(r0, cgen_->SlotOperand(slot, r2));
4252 frame->EmitPush(r0);
4253 if (slot->type() == Slot::CONTEXT) {
4254 // Skip write barrier if the written value is a smi.
4255 __ tst(r0, Operand(kSmiTagMask));
4256 exit.Branch(eq);
4257 // r2 is loaded with context when calling SlotOperand above.
4258 int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
4259 __ mov(r3, Operand(offset));
4260 __ RecordWrite(r2, r3, r1);
4261 }
4262 // If we definitely did not jump over the assignment, we do not need
4263 // to bind the exit label. Doing so can defeat peephole
4264 // optimization.
4265 if (init_state == CONST_INIT || slot->type() == Slot::CONTEXT) {
4266 exit.Bind();
4267 }
4268 }
4269 break;
4270 }
4271
4272 case NAMED: {
4273 Comment cmnt(masm, "[ Store to named Property");
4274 // Call the appropriate IC code.
4275 Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Initialize));
4276 Handle<String> name(GetName());
4277
4278 Result value(r0);
4279 frame->EmitPop(r0);
4280
4281 // Setup the name register.
4282 Result property_name(r2);
4283 __ mov(r2, Operand(name));
4284 frame->CallCodeObject(ic,
4285 RelocInfo::CODE_TARGET,
4286 &value,
4287 &property_name,
4288 0);
4289 frame->EmitPush(r0);
4290 break;
4291 }
4292
4293 case KEYED: {
4294 Comment cmnt(masm, "[ Store to keyed Property");
4295 Property* property = expression_->AsProperty();
4296 ASSERT(property != NULL);
4297 cgen_->CodeForSourcePosition(property->position());
4298
4299 // Call IC code.
4300 Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Initialize));
4301 // TODO(1222589): Make the IC grab the values from the stack.
4302 Result value(r0);
4303 frame->EmitPop(r0); // value
4304 frame->CallCodeObject(ic, RelocInfo::CODE_TARGET, &value, 0);
4305 frame->EmitPush(r0);
4306 break;
4307 }
4308
4309 default:
4310 UNREACHABLE();
4311 }
4312}
4313
4314
4315// Count leading zeros in a 32 bit word. On ARM5 and later it uses the clz
4316// instruction. On pre-ARM5 hardware this routine gives the wrong answer for 0
4317// (31 instead of 32).
4318static void CountLeadingZeros(
4319 MacroAssembler* masm,
4320 Register source,
4321 Register scratch,
4322 Register zeros) {
4323#ifdef CAN_USE_ARMV5_INSTRUCTIONS
4324 __ clz(zeros, source); // This instruction is only supported after ARM5.
4325#else
4326 __ mov(zeros, Operand(0));
4327 __ mov(scratch, source);
4328 // Top 16.
4329 __ tst(scratch, Operand(0xffff0000));
4330 __ add(zeros, zeros, Operand(16), LeaveCC, eq);
4331 __ mov(scratch, Operand(scratch, LSL, 16), LeaveCC, eq);
4332 // Top 8.
4333 __ tst(scratch, Operand(0xff000000));
4334 __ add(zeros, zeros, Operand(8), LeaveCC, eq);
4335 __ mov(scratch, Operand(scratch, LSL, 8), LeaveCC, eq);
4336 // Top 4.
4337 __ tst(scratch, Operand(0xf0000000));
4338 __ add(zeros, zeros, Operand(4), LeaveCC, eq);
4339 __ mov(scratch, Operand(scratch, LSL, 4), LeaveCC, eq);
4340 // Top 2.
4341 __ tst(scratch, Operand(0xc0000000));
4342 __ add(zeros, zeros, Operand(2), LeaveCC, eq);
4343 __ mov(scratch, Operand(scratch, LSL, 2), LeaveCC, eq);
4344 // Top bit.
4345 __ tst(scratch, Operand(0x80000000u));
4346 __ add(zeros, zeros, Operand(1), LeaveCC, eq);
4347#endif
4348}
4349
4350
4351// Takes a Smi and converts to an IEEE 64 bit floating point value in two
4352// registers. The format is 1 sign bit, 11 exponent bits (biased 1023) and
4353// 52 fraction bits (20 in the first word, 32 in the second). Zeros is a
4354// scratch register. Destroys the source register. No GC occurs during this
4355// stub so you don't have to set up the frame.
4356class ConvertToDoubleStub : public CodeStub {
4357 public:
4358 ConvertToDoubleStub(Register result_reg_1,
4359 Register result_reg_2,
4360 Register source_reg,
4361 Register scratch_reg)
4362 : result1_(result_reg_1),
4363 result2_(result_reg_2),
4364 source_(source_reg),
4365 zeros_(scratch_reg) { }
4366
4367 private:
4368 Register result1_;
4369 Register result2_;
4370 Register source_;
4371 Register zeros_;
4372
4373 // Minor key encoding in 16 bits.
4374 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
4375 class OpBits: public BitField<Token::Value, 2, 14> {};
4376
4377 Major MajorKey() { return ConvertToDouble; }
4378 int MinorKey() {
4379 // Encode the parameters in a unique 16 bit value.
4380 return result1_.code() +
4381 (result2_.code() << 4) +
4382 (source_.code() << 8) +
4383 (zeros_.code() << 12);
4384 }
4385
4386 void Generate(MacroAssembler* masm);
4387
4388 const char* GetName() { return "ConvertToDoubleStub"; }
4389
4390#ifdef DEBUG
4391 void Print() { PrintF("ConvertToDoubleStub\n"); }
4392#endif
4393};
4394
4395
4396void ConvertToDoubleStub::Generate(MacroAssembler* masm) {
4397#ifndef BIG_ENDIAN_FLOATING_POINT
4398 Register exponent = result1_;
4399 Register mantissa = result2_;
4400#else
4401 Register exponent = result2_;
4402 Register mantissa = result1_;
4403#endif
4404 Label not_special;
4405 // Convert from Smi to integer.
4406 __ mov(source_, Operand(source_, ASR, kSmiTagSize));
4407 // Move sign bit from source to destination. This works because the sign bit
4408 // in the exponent word of the double has the same position and polarity as
4409 // the 2's complement sign bit in a Smi.
4410 ASSERT(HeapNumber::kSignMask == 0x80000000u);
4411 __ and_(exponent, source_, Operand(HeapNumber::kSignMask), SetCC);
4412 // Subtract from 0 if source was negative.
4413 __ rsb(source_, source_, Operand(0), LeaveCC, ne);
4414 __ cmp(source_, Operand(1));
4415 __ b(gt, &not_special);
4416
4417 // We have -1, 0 or 1, which we treat specially.
4418 __ cmp(source_, Operand(0));
4419 // For 1 or -1 we need to or in the 0 exponent (biased to 1023).
4420 static const uint32_t exponent_word_for_1 =
4421 HeapNumber::kExponentBias << HeapNumber::kExponentShift;
4422 __ orr(exponent, exponent, Operand(exponent_word_for_1), LeaveCC, ne);
4423 // 1, 0 and -1 all have 0 for the second word.
4424 __ mov(mantissa, Operand(0));
4425 __ Ret();
4426
4427 __ bind(&not_special);
4428 // Count leading zeros. Uses result2 for a scratch register on pre-ARM5.
4429 // Gets the wrong answer for 0, but we already checked for that case above.
4430 CountLeadingZeros(masm, source_, mantissa, zeros_);
4431 // Compute exponent and or it into the exponent register.
4432 // We use result2 as a scratch register here.
4433 __ rsb(mantissa, zeros_, Operand(31 + HeapNumber::kExponentBias));
4434 __ orr(exponent,
4435 exponent,
4436 Operand(mantissa, LSL, HeapNumber::kExponentShift));
4437 // Shift up the source chopping the top bit off.
4438 __ add(zeros_, zeros_, Operand(1));
4439 // This wouldn't work for 1.0 or -1.0 as the shift would be 32 which means 0.
4440 __ mov(source_, Operand(source_, LSL, zeros_));
4441 // Compute lower part of fraction (last 12 bits).
4442 __ mov(mantissa, Operand(source_, LSL, HeapNumber::kMantissaBitsInTopWord));
4443 // And the top (top 20 bits).
4444 __ orr(exponent,
4445 exponent,
4446 Operand(source_, LSR, 32 - HeapNumber::kMantissaBitsInTopWord));
4447 __ Ret();
4448}
4449
4450
4451// This stub can convert a signed int32 to a heap number (double). It does
4452// not work for int32s that are in Smi range! No GC occurs during this stub
4453// so you don't have to set up the frame.
4454class WriteInt32ToHeapNumberStub : public CodeStub {
4455 public:
4456 WriteInt32ToHeapNumberStub(Register the_int,
4457 Register the_heap_number,
4458 Register scratch)
4459 : the_int_(the_int),
4460 the_heap_number_(the_heap_number),
4461 scratch_(scratch) { }
4462
4463 private:
4464 Register the_int_;
4465 Register the_heap_number_;
4466 Register scratch_;
4467
4468 // Minor key encoding in 16 bits.
4469 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
4470 class OpBits: public BitField<Token::Value, 2, 14> {};
4471
4472 Major MajorKey() { return WriteInt32ToHeapNumber; }
4473 int MinorKey() {
4474 // Encode the parameters in a unique 16 bit value.
4475 return the_int_.code() +
4476 (the_heap_number_.code() << 4) +
4477 (scratch_.code() << 8);
4478 }
4479
4480 void Generate(MacroAssembler* masm);
4481
4482 const char* GetName() { return "WriteInt32ToHeapNumberStub"; }
4483
4484#ifdef DEBUG
4485 void Print() { PrintF("WriteInt32ToHeapNumberStub\n"); }
4486#endif
4487};
4488
4489
4490// See comment for class.
4491void WriteInt32ToHeapNumberStub::Generate(MacroAssembler *masm) {
4492 Label max_negative_int;
4493 // the_int_ has the answer which is a signed int32 but not a Smi.
4494 // We test for the special value that has a different exponent. This test
4495 // has the neat side effect of setting the flags according to the sign.
4496 ASSERT(HeapNumber::kSignMask == 0x80000000u);
4497 __ cmp(the_int_, Operand(0x80000000u));
4498 __ b(eq, &max_negative_int);
4499 // Set up the correct exponent in scratch_. All non-Smi int32s have the same.
4500 // A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased).
4501 uint32_t non_smi_exponent =
4502 (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
4503 __ mov(scratch_, Operand(non_smi_exponent));
4504 // Set the sign bit in scratch_ if the value was negative.
4505 __ orr(scratch_, scratch_, Operand(HeapNumber::kSignMask), LeaveCC, cs);
4506 // Subtract from 0 if the value was negative.
4507 __ rsb(the_int_, the_int_, Operand(0), LeaveCC, cs);
4508 // We should be masking the implict first digit of the mantissa away here,
4509 // but it just ends up combining harmlessly with the last digit of the
4510 // exponent that happens to be 1. The sign bit is 0 so we shift 10 to get
4511 // the most significant 1 to hit the last bit of the 12 bit sign and exponent.
4512 ASSERT(((1 << HeapNumber::kExponentShift) & non_smi_exponent) != 0);
4513 const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
4514 __ orr(scratch_, scratch_, Operand(the_int_, LSR, shift_distance));
4515 __ str(scratch_, FieldMemOperand(the_heap_number_,
4516 HeapNumber::kExponentOffset));
4517 __ mov(scratch_, Operand(the_int_, LSL, 32 - shift_distance));
4518 __ str(scratch_, FieldMemOperand(the_heap_number_,
4519 HeapNumber::kMantissaOffset));
4520 __ Ret();
4521
4522 __ bind(&max_negative_int);
4523 // The max negative int32 is stored as a positive number in the mantissa of
4524 // a double because it uses a sign bit instead of using two's complement.
4525 // The actual mantissa bits stored are all 0 because the implicit most
4526 // significant 1 bit is not stored.
4527 non_smi_exponent += 1 << HeapNumber::kExponentShift;
4528 __ mov(ip, Operand(HeapNumber::kSignMask | non_smi_exponent));
4529 __ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kExponentOffset));
4530 __ mov(ip, Operand(0));
4531 __ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kMantissaOffset));
4532 __ Ret();
4533}
4534
4535
4536// Handle the case where the lhs and rhs are the same object.
4537// Equality is almost reflexive (everything but NaN), so this is a test
4538// for "identity and not NaN".
4539static void EmitIdenticalObjectComparison(MacroAssembler* masm,
4540 Label* slow,
4541 Condition cc) {
4542 Label not_identical;
4543 __ cmp(r0, Operand(r1));
4544 __ b(ne, &not_identical);
4545
4546 Register exp_mask_reg = r5;
4547 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
4548
4549 // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
4550 // so we do the second best thing - test it ourselves.
4551 Label heap_number, return_equal;
4552 // They are both equal and they are not both Smis so both of them are not
4553 // Smis. If it's not a heap number, then return equal.
4554 if (cc == lt || cc == gt) {
4555 __ CompareObjectType(r0, r4, r4, FIRST_JS_OBJECT_TYPE);
4556 __ b(ge, slow);
4557 } else {
4558 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
4559 __ b(eq, &heap_number);
4560 // Comparing JS objects with <=, >= is complicated.
4561 if (cc != eq) {
4562 __ cmp(r4, Operand(FIRST_JS_OBJECT_TYPE));
4563 __ b(ge, slow);
4564 }
4565 }
4566 __ bind(&return_equal);
4567 if (cc == lt) {
4568 __ mov(r0, Operand(GREATER)); // Things aren't less than themselves.
4569 } else if (cc == gt) {
4570 __ mov(r0, Operand(LESS)); // Things aren't greater than themselves.
4571 } else {
4572 __ mov(r0, Operand(0)); // Things are <=, >=, ==, === themselves.
4573 }
4574 __ mov(pc, Operand(lr)); // Return.
4575
4576 // For less and greater we don't have to check for NaN since the result of
4577 // x < x is false regardless. For the others here is some code to check
4578 // for NaN.
4579 if (cc != lt && cc != gt) {
4580 __ bind(&heap_number);
4581 // It is a heap number, so return non-equal if it's NaN and equal if it's
4582 // not NaN.
4583 // The representation of NaN values has all exponent bits (52..62) set,
4584 // and not all mantissa bits (0..51) clear.
4585 // Read top bits of double representation (second word of value).
4586 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
4587 // Test that exponent bits are all set.
4588 __ and_(r3, r2, Operand(exp_mask_reg));
4589 __ cmp(r3, Operand(exp_mask_reg));
4590 __ b(ne, &return_equal);
4591
4592 // Shift out flag and all exponent bits, retaining only mantissa.
4593 __ mov(r2, Operand(r2, LSL, HeapNumber::kNonMantissaBitsInTopWord));
4594 // Or with all low-bits of mantissa.
4595 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
4596 __ orr(r0, r3, Operand(r2), SetCC);
4597 // For equal we already have the right value in r0: Return zero (equal)
4598 // if all bits in mantissa are zero (it's an Infinity) and non-zero if not
4599 // (it's a NaN). For <= and >= we need to load r0 with the failing value
4600 // if it's a NaN.
4601 if (cc != eq) {
4602 // All-zero means Infinity means equal.
4603 __ mov(pc, Operand(lr), LeaveCC, eq); // Return equal
4604 if (cc == le) {
4605 __ mov(r0, Operand(GREATER)); // NaN <= NaN should fail.
4606 } else {
4607 __ mov(r0, Operand(LESS)); // NaN >= NaN should fail.
4608 }
4609 }
4610 __ mov(pc, Operand(lr)); // Return.
4611 }
4612 // No fall through here.
4613
4614 __ bind(&not_identical);
4615}
4616
4617
4618// See comment at call site.
4619static void EmitSmiNonsmiComparison(MacroAssembler* masm,
4620 Label* rhs_not_nan,
4621 Label* slow,
4622 bool strict) {
4623 Label lhs_is_smi;
4624 __ tst(r0, Operand(kSmiTagMask));
4625 __ b(eq, &lhs_is_smi);
4626
4627 // Rhs is a Smi. Check whether the non-smi is a heap number.
4628 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
4629 if (strict) {
4630 // If lhs was not a number and rhs was a Smi then strict equality cannot
4631 // succeed. Return non-equal (r0 is already not zero)
4632 __ mov(pc, Operand(lr), LeaveCC, ne); // Return.
4633 } else {
4634 // Smi compared non-strictly with a non-Smi non-heap-number. Call
4635 // the runtime.
4636 __ b(ne, slow);
4637 }
4638
4639 // Rhs is a smi, lhs is a number.
4640 __ push(lr);
4641 __ mov(r7, Operand(r1));
4642 ConvertToDoubleStub stub1(r3, r2, r7, r6);
4643 __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET);
4644 // r3 and r2 are rhs as double.
4645 __ ldr(r1, FieldMemOperand(r0, HeapNumber::kValueOffset + kPointerSize));
4646 __ ldr(r0, FieldMemOperand(r0, HeapNumber::kValueOffset));
4647 // We now have both loaded as doubles but we can skip the lhs nan check
4648 // since it's a Smi.
4649 __ pop(lr);
4650 __ jmp(rhs_not_nan);
4651
4652 __ bind(&lhs_is_smi);
4653 // Lhs is a Smi. Check whether the non-smi is a heap number.
4654 __ CompareObjectType(r1, r4, r4, HEAP_NUMBER_TYPE);
4655 if (strict) {
4656 // If lhs was not a number and rhs was a Smi then strict equality cannot
4657 // succeed. Return non-equal.
4658 __ mov(r0, Operand(1), LeaveCC, ne); // Non-zero indicates not equal.
4659 __ mov(pc, Operand(lr), LeaveCC, ne); // Return.
4660 } else {
4661 // Smi compared non-strictly with a non-Smi non-heap-number. Call
4662 // the runtime.
4663 __ b(ne, slow);
4664 }
4665
4666 // Lhs is a smi, rhs is a number.
4667 // r0 is Smi and r1 is heap number.
4668 __ push(lr);
4669 __ ldr(r2, FieldMemOperand(r1, HeapNumber::kValueOffset));
4670 __ ldr(r3, FieldMemOperand(r1, HeapNumber::kValueOffset + kPointerSize));
4671 __ mov(r7, Operand(r0));
4672 ConvertToDoubleStub stub2(r1, r0, r7, r6);
4673 __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET);
4674 __ pop(lr);
4675 // Fall through to both_loaded_as_doubles.
4676}
4677
4678
4679void EmitNanCheck(MacroAssembler* masm, Label* rhs_not_nan, Condition cc) {
4680 bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset);
4681 Register lhs_exponent = exp_first ? r0 : r1;
4682 Register rhs_exponent = exp_first ? r2 : r3;
4683 Register lhs_mantissa = exp_first ? r1 : r0;
4684 Register rhs_mantissa = exp_first ? r3 : r2;
4685 Label one_is_nan, neither_is_nan;
4686
4687 Register exp_mask_reg = r5;
4688
4689 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
4690 __ and_(r4, rhs_exponent, Operand(exp_mask_reg));
4691 __ cmp(r4, Operand(exp_mask_reg));
4692 __ b(ne, rhs_not_nan);
4693 __ mov(r4,
4694 Operand(rhs_exponent, LSL, HeapNumber::kNonMantissaBitsInTopWord),
4695 SetCC);
4696 __ b(ne, &one_is_nan);
4697 __ cmp(rhs_mantissa, Operand(0));
4698 __ b(ne, &one_is_nan);
4699
4700 __ bind(rhs_not_nan);
4701 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
4702 __ and_(r4, lhs_exponent, Operand(exp_mask_reg));
4703 __ cmp(r4, Operand(exp_mask_reg));
4704 __ b(ne, &neither_is_nan);
4705 __ mov(r4,
4706 Operand(lhs_exponent, LSL, HeapNumber::kNonMantissaBitsInTopWord),
4707 SetCC);
4708 __ b(ne, &one_is_nan);
4709 __ cmp(lhs_mantissa, Operand(0));
4710 __ b(eq, &neither_is_nan);
4711
4712 __ bind(&one_is_nan);
4713 // NaN comparisons always fail.
4714 // Load whatever we need in r0 to make the comparison fail.
4715 if (cc == lt || cc == le) {
4716 __ mov(r0, Operand(GREATER));
4717 } else {
4718 __ mov(r0, Operand(LESS));
4719 }
4720 __ mov(pc, Operand(lr)); // Return.
4721
4722 __ bind(&neither_is_nan);
4723}
4724
4725
4726// See comment at call site.
4727static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc) {
4728 bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset);
4729 Register lhs_exponent = exp_first ? r0 : r1;
4730 Register rhs_exponent = exp_first ? r2 : r3;
4731 Register lhs_mantissa = exp_first ? r1 : r0;
4732 Register rhs_mantissa = exp_first ? r3 : r2;
4733
4734 // r0, r1, r2, r3 have the two doubles. Neither is a NaN.
4735 if (cc == eq) {
4736 // Doubles are not equal unless they have the same bit pattern.
4737 // Exception: 0 and -0.
4738 __ cmp(lhs_mantissa, Operand(rhs_mantissa));
4739 __ orr(r0, lhs_mantissa, Operand(rhs_mantissa), LeaveCC, ne);
4740 // Return non-zero if the numbers are unequal.
4741 __ mov(pc, Operand(lr), LeaveCC, ne);
4742
4743 __ sub(r0, lhs_exponent, Operand(rhs_exponent), SetCC);
4744 // If exponents are equal then return 0.
4745 __ mov(pc, Operand(lr), LeaveCC, eq);
4746
4747 // Exponents are unequal. The only way we can return that the numbers
4748 // are equal is if one is -0 and the other is 0. We already dealt
4749 // with the case where both are -0 or both are 0.
4750 // We start by seeing if the mantissas (that are equal) or the bottom
4751 // 31 bits of the rhs exponent are non-zero. If so we return not
4752 // equal.
4753 __ orr(r4, rhs_mantissa, Operand(rhs_exponent, LSL, kSmiTagSize), SetCC);
4754 __ mov(r0, Operand(r4), LeaveCC, ne);
4755 __ mov(pc, Operand(lr), LeaveCC, ne); // Return conditionally.
4756 // Now they are equal if and only if the lhs exponent is zero in its
4757 // low 31 bits.
4758 __ mov(r0, Operand(lhs_exponent, LSL, kSmiTagSize));
4759 __ mov(pc, Operand(lr));
4760 } else {
4761 // Call a native function to do a comparison between two non-NaNs.
4762 // Call C routine that may not cause GC or other trouble.
4763 __ mov(r5, Operand(ExternalReference::compare_doubles()));
4764 __ Jump(r5); // Tail call.
4765 }
4766}
4767
4768
4769// See comment at call site.
4770static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm) {
4771 // If either operand is a JSObject or an oddball value, then they are
4772 // not equal since their pointers are different.
4773 // There is no test for undetectability in strict equality.
4774 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
4775 Label first_non_object;
4776 // Get the type of the first operand into r2 and compare it with
4777 // FIRST_JS_OBJECT_TYPE.
4778 __ CompareObjectType(r0, r2, r2, FIRST_JS_OBJECT_TYPE);
4779 __ b(lt, &first_non_object);
4780
4781 // Return non-zero (r0 is not zero)
4782 Label return_not_equal;
4783 __ bind(&return_not_equal);
4784 __ mov(pc, Operand(lr)); // Return.
4785
4786 __ bind(&first_non_object);
4787 // Check for oddballs: true, false, null, undefined.
4788 __ cmp(r2, Operand(ODDBALL_TYPE));
4789 __ b(eq, &return_not_equal);
4790
4791 __ CompareObjectType(r1, r3, r3, FIRST_JS_OBJECT_TYPE);
4792 __ b(ge, &return_not_equal);
4793
4794 // Check for oddballs: true, false, null, undefined.
4795 __ cmp(r3, Operand(ODDBALL_TYPE));
4796 __ b(eq, &return_not_equal);
4797}
4798
4799
4800// See comment at call site.
4801static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm,
4802 Label* both_loaded_as_doubles,
4803 Label* not_heap_numbers,
4804 Label* slow) {
4805 __ CompareObjectType(r0, r2, r2, HEAP_NUMBER_TYPE);
4806 __ b(ne, not_heap_numbers);
4807 __ CompareObjectType(r1, r3, r3, HEAP_NUMBER_TYPE);
4808 __ b(ne, slow); // First was a heap number, second wasn't. Go slow case.
4809
4810 // Both are heap numbers. Load them up then jump to the code we have
4811 // for that.
4812 __ ldr(r2, FieldMemOperand(r1, HeapNumber::kValueOffset));
4813 __ ldr(r3, FieldMemOperand(r1, HeapNumber::kValueOffset + kPointerSize));
4814 __ ldr(r1, FieldMemOperand(r0, HeapNumber::kValueOffset + kPointerSize));
4815 __ ldr(r0, FieldMemOperand(r0, HeapNumber::kValueOffset));
4816 __ jmp(both_loaded_as_doubles);
4817}
4818
4819
4820// Fast negative check for symbol-to-symbol equality.
4821static void EmitCheckForSymbols(MacroAssembler* masm, Label* slow) {
4822 // r2 is object type of r0.
4823 __ tst(r2, Operand(kIsNotStringMask));
4824 __ b(ne, slow);
4825 __ tst(r2, Operand(kIsSymbolMask));
4826 __ b(eq, slow);
4827 __ CompareObjectType(r1, r3, r3, FIRST_NONSTRING_TYPE);
4828 __ b(ge, slow);
4829 __ tst(r3, Operand(kIsSymbolMask));
4830 __ b(eq, slow);
4831
4832 // Both are symbols. We already checked they weren't the same pointer
4833 // so they are not equal.
4834 __ mov(r0, Operand(1)); // Non-zero indicates not equal.
4835 __ mov(pc, Operand(lr)); // Return.
4836}
4837
4838
4839// On entry r0 and r1 are the things to be compared. On exit r0 is 0,
4840// positive or negative to indicate the result of the comparison.
4841void CompareStub::Generate(MacroAssembler* masm) {
4842 Label slow; // Call builtin.
4843 Label not_smis, both_loaded_as_doubles, rhs_not_nan;
4844
4845 // NOTICE! This code is only reached after a smi-fast-case check, so
4846 // it is certain that at least one operand isn't a smi.
4847
4848 // Handle the case where the objects are identical. Either returns the answer
4849 // or goes to slow. Only falls through if the objects were not identical.
4850 EmitIdenticalObjectComparison(masm, &slow, cc_);
4851
4852 // If either is a Smi (we know that not both are), then they can only
4853 // be strictly equal if the other is a HeapNumber.
4854 ASSERT_EQ(0, kSmiTag);
4855 ASSERT_EQ(0, Smi::FromInt(0));
4856 __ and_(r2, r0, Operand(r1));
4857 __ tst(r2, Operand(kSmiTagMask));
4858 __ b(ne, &not_smis);
4859 // One operand is a smi. EmitSmiNonsmiComparison generates code that can:
4860 // 1) Return the answer.
4861 // 2) Go to slow.
4862 // 3) Fall through to both_loaded_as_doubles.
4863 // 4) Jump to rhs_not_nan.
4864 // In cases 3 and 4 we have found out we were dealing with a number-number
4865 // comparison and the numbers have been loaded into r0, r1, r2, r3 as doubles.
4866 EmitSmiNonsmiComparison(masm, &rhs_not_nan, &slow, strict_);
4867
4868 __ bind(&both_loaded_as_doubles);
4869 // r0, r1, r2, r3 are the double representations of the left hand side
4870 // and the right hand side.
4871
4872 // Checks for NaN in the doubles we have loaded. Can return the answer or
4873 // fall through if neither is a NaN. Also binds rhs_not_nan.
4874 EmitNanCheck(masm, &rhs_not_nan, cc_);
4875
4876 // Compares two doubles in r0, r1, r2, r3 that are not NaNs. Returns the
4877 // answer. Never falls through.
4878 EmitTwoNonNanDoubleComparison(masm, cc_);
4879
4880 __ bind(&not_smis);
4881 // At this point we know we are dealing with two different objects,
4882 // and neither of them is a Smi. The objects are in r0 and r1.
4883 if (strict_) {
4884 // This returns non-equal for some object types, or falls through if it
4885 // was not lucky.
4886 EmitStrictTwoHeapObjectCompare(masm);
4887 }
4888
4889 Label check_for_symbols;
4890 // Check for heap-number-heap-number comparison. Can jump to slow case,
4891 // or load both doubles into r0, r1, r2, r3 and jump to the code that handles
4892 // that case. If the inputs are not doubles then jumps to check_for_symbols.
4893 // In this case r2 will contain the type of r0.
4894 EmitCheckForTwoHeapNumbers(masm,
4895 &both_loaded_as_doubles,
4896 &check_for_symbols,
4897 &slow);
4898
4899 __ bind(&check_for_symbols);
4900 if (cc_ == eq) {
4901 // Either jumps to slow or returns the answer. Assumes that r2 is the type
4902 // of r0 on entry.
4903 EmitCheckForSymbols(masm, &slow);
4904 }
4905
4906 __ bind(&slow);
4907 __ push(lr);
4908 __ push(r1);
4909 __ push(r0);
4910 // Figure out which native to call and setup the arguments.
4911 Builtins::JavaScript native;
4912 int arg_count = 1; // Not counting receiver.
4913 if (cc_ == eq) {
4914 native = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
4915 } else {
4916 native = Builtins::COMPARE;
4917 int ncr; // NaN compare result
4918 if (cc_ == lt || cc_ == le) {
4919 ncr = GREATER;
4920 } else {
4921 ASSERT(cc_ == gt || cc_ == ge); // remaining cases
4922 ncr = LESS;
4923 }
4924 arg_count++;
4925 __ mov(r0, Operand(Smi::FromInt(ncr)));
4926 __ push(r0);
4927 }
4928
4929 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
4930 // tagged as a small integer.
4931 __ mov(r0, Operand(arg_count));
4932 __ InvokeBuiltin(native, CALL_JS);
4933 __ cmp(r0, Operand(0));
4934 __ pop(pc);
4935}
4936
4937
4938// Allocates a heap number or jumps to the label if the young space is full and
4939// a scavenge is needed.
4940static void AllocateHeapNumber(
4941 MacroAssembler* masm,
4942 Label* need_gc, // Jump here if young space is full.
4943 Register result, // The tagged address of the new heap number.
4944 Register scratch1, // A scratch register.
4945 Register scratch2) { // Another scratch register.
4946 // Allocate an object in the heap for the heap number and tag it as a heap
4947 // object.
4948 __ AllocateInNewSpace(HeapNumber::kSize / kPointerSize,
4949 result,
4950 scratch1,
4951 scratch2,
4952 need_gc,
4953 TAG_OBJECT);
4954
4955 // Get heap number map and store it in the allocated object.
4956 __ LoadRoot(scratch1, Heap::kHeapNumberMapRootIndex);
4957 __ str(scratch1, FieldMemOperand(result, HeapObject::kMapOffset));
4958}
4959
4960
4961// We fall into this code if the operands were Smis, but the result was
4962// not (eg. overflow). We branch into this code (to the not_smi label) if
4963// the operands were not both Smi. The operands are in r0 and r1. In order
4964// to call the C-implemented binary fp operation routines we need to end up
4965// with the double precision floating point operands in r0 and r1 (for the
4966// value in r1) and r2 and r3 (for the value in r0).
4967static void HandleBinaryOpSlowCases(MacroAssembler* masm,
4968 Label* not_smi,
4969 const Builtins::JavaScript& builtin,
4970 Token::Value operation,
4971 OverwriteMode mode) {
4972 Label slow, slow_pop_2_first, do_the_call;
4973 Label r0_is_smi, r1_is_smi, finished_loading_r0, finished_loading_r1;
4974 // Smi-smi case (overflow).
4975 // Since both are Smis there is no heap number to overwrite, so allocate.
4976 // The new heap number is in r5. r6 and r7 are scratch.
4977 AllocateHeapNumber(masm, &slow, r5, r6, r7);
4978 // Write Smi from r0 to r3 and r2 in double format. r6 is scratch.
4979 __ mov(r7, Operand(r0));
4980 ConvertToDoubleStub stub1(r3, r2, r7, r6);
4981 __ push(lr);
4982 __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET);
4983 // Write Smi from r1 to r1 and r0 in double format. r6 is scratch.
4984 __ mov(r7, Operand(r1));
4985 ConvertToDoubleStub stub2(r1, r0, r7, r6);
4986 __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET);
4987 __ pop(lr);
4988 __ jmp(&do_the_call); // Tail call. No return.
4989
4990 // We jump to here if something goes wrong (one param is not a number of any
4991 // sort or new-space allocation fails).
4992 __ bind(&slow);
4993 __ push(r1);
4994 __ push(r0);
4995 __ mov(r0, Operand(1)); // Set number of arguments.
4996 __ InvokeBuiltin(builtin, JUMP_JS); // Tail call. No return.
4997
4998 // We branch here if at least one of r0 and r1 is not a Smi.
4999 __ bind(not_smi);
5000 if (mode == NO_OVERWRITE) {
5001 // In the case where there is no chance of an overwritable float we may as
5002 // well do the allocation immediately while r0 and r1 are untouched.
5003 AllocateHeapNumber(masm, &slow, r5, r6, r7);
5004 }
5005
5006 // Move r0 to a double in r2-r3.
5007 __ tst(r0, Operand(kSmiTagMask));
5008 __ b(eq, &r0_is_smi); // It's a Smi so don't check it's a heap number.
5009 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
5010 __ b(ne, &slow);
5011 if (mode == OVERWRITE_RIGHT) {
5012 __ mov(r5, Operand(r0)); // Overwrite this heap number.
5013 }
5014 // Calling convention says that second double is in r2 and r3.
5015 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kValueOffset));
5016 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kValueOffset + 4));
5017 __ jmp(&finished_loading_r0);
5018 __ bind(&r0_is_smi);
5019 if (mode == OVERWRITE_RIGHT) {
5020 // We can't overwrite a Smi so get address of new heap number into r5.
5021 AllocateHeapNumber(masm, &slow, r5, r6, r7);
5022 }
5023 // Write Smi from r0 to r3 and r2 in double format.
5024 __ mov(r7, Operand(r0));
5025 ConvertToDoubleStub stub3(r3, r2, r7, r6);
5026 __ push(lr);
5027 __ Call(stub3.GetCode(), RelocInfo::CODE_TARGET);
5028 __ pop(lr);
5029 __ bind(&finished_loading_r0);
5030
5031 // Move r1 to a double in r0-r1.
5032 __ tst(r1, Operand(kSmiTagMask));
5033 __ b(eq, &r1_is_smi); // It's a Smi so don't check it's a heap number.
5034 __ CompareObjectType(r1, r4, r4, HEAP_NUMBER_TYPE);
5035 __ b(ne, &slow);
5036 if (mode == OVERWRITE_LEFT) {
5037 __ mov(r5, Operand(r1)); // Overwrite this heap number.
5038 }
5039 // Calling convention says that first double is in r0 and r1.
5040 __ ldr(r0, FieldMemOperand(r1, HeapNumber::kValueOffset));
5041 __ ldr(r1, FieldMemOperand(r1, HeapNumber::kValueOffset + 4));
5042 __ jmp(&finished_loading_r1);
5043 __ bind(&r1_is_smi);
5044 if (mode == OVERWRITE_LEFT) {
5045 // We can't overwrite a Smi so get address of new heap number into r5.
5046 AllocateHeapNumber(masm, &slow, r5, r6, r7);
5047 }
5048 // Write Smi from r1 to r1 and r0 in double format.
5049 __ mov(r7, Operand(r1));
5050 ConvertToDoubleStub stub4(r1, r0, r7, r6);
5051 __ push(lr);
5052 __ Call(stub4.GetCode(), RelocInfo::CODE_TARGET);
5053 __ pop(lr);
5054 __ bind(&finished_loading_r1);
5055
5056 __ bind(&do_the_call);
5057 // r0: Left value (least significant part of mantissa).
5058 // r1: Left value (sign, exponent, top of mantissa).
5059 // r2: Right value (least significant part of mantissa).
5060 // r3: Right value (sign, exponent, top of mantissa).
5061 // r5: Address of heap number for result.
5062 __ push(lr); // For later.
5063 __ push(r5); // Address of heap number that is answer.
5064 __ AlignStack(0);
5065 // Call C routine that may not cause GC or other trouble.
5066 __ mov(r5, Operand(ExternalReference::double_fp_operation(operation)));
5067 __ Call(r5);
5068 __ pop(r4); // Address of heap number.
5069 __ cmp(r4, Operand(Smi::FromInt(0)));
5070 __ pop(r4, eq); // Conditional pop instruction to get rid of alignment push.
5071 // Store answer in the overwritable heap number.
5072#if !defined(USE_ARM_EABI)
5073 // Double returned in fp coprocessor register 0 and 1, encoded as register
5074 // cr8. Offsets must be divisible by 4 for coprocessor so we need to
5075 // substract the tag from r4.
5076 __ sub(r5, r4, Operand(kHeapObjectTag));
5077 __ stc(p1, cr8, MemOperand(r5, HeapNumber::kValueOffset));
5078#else
5079 // Double returned in registers 0 and 1.
5080 __ str(r0, FieldMemOperand(r4, HeapNumber::kValueOffset));
5081 __ str(r1, FieldMemOperand(r4, HeapNumber::kValueOffset + 4));
5082#endif
5083 __ mov(r0, Operand(r4));
5084 // And we are done.
5085 __ pop(pc);
5086}
5087
5088
5089// Tries to get a signed int32 out of a double precision floating point heap
5090// number. Rounds towards 0. Fastest for doubles that are in the ranges
5091// -0x7fffffff to -0x40000000 or 0x40000000 to 0x7fffffff. This corresponds
5092// almost to the range of signed int32 values that are not Smis. Jumps to the
5093// label 'slow' if the double isn't in the range -0x80000000.0 to 0x80000000.0
5094// (excluding the endpoints).
5095static void GetInt32(MacroAssembler* masm,
5096 Register source,
5097 Register dest,
5098 Register scratch,
5099 Register scratch2,
5100 Label* slow) {
5101 Label right_exponent, done;
5102 // Get exponent word.
5103 __ ldr(scratch, FieldMemOperand(source, HeapNumber::kExponentOffset));
5104 // Get exponent alone in scratch2.
5105 __ and_(scratch2, scratch, Operand(HeapNumber::kExponentMask));
5106 // Load dest with zero. We use this either for the final shift or
5107 // for the answer.
5108 __ mov(dest, Operand(0));
5109 // Check whether the exponent matches a 32 bit signed int that is not a Smi.
5110 // A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased). This is
5111 // the exponent that we are fastest at and also the highest exponent we can
5112 // handle here.
5113 const uint32_t non_smi_exponent =
5114 (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
5115 __ cmp(scratch2, Operand(non_smi_exponent));
5116 // If we have a match of the int32-but-not-Smi exponent then skip some logic.
5117 __ b(eq, &right_exponent);
5118 // If the exponent is higher than that then go to slow case. This catches
5119 // numbers that don't fit in a signed int32, infinities and NaNs.
5120 __ b(gt, slow);
5121
5122 // We know the exponent is smaller than 30 (biased). If it is less than
5123 // 0 (biased) then the number is smaller in magnitude than 1.0 * 2^0, ie
5124 // it rounds to zero.
5125 const uint32_t zero_exponent =
5126 (HeapNumber::kExponentBias + 0) << HeapNumber::kExponentShift;
5127 __ sub(scratch2, scratch2, Operand(zero_exponent), SetCC);
5128 // Dest already has a Smi zero.
5129 __ b(lt, &done);
5130 // We have a shifted exponent between 0 and 30 in scratch2.
5131 __ mov(dest, Operand(scratch2, LSR, HeapNumber::kExponentShift));
5132 // We now have the exponent in dest. Subtract from 30 to get
5133 // how much to shift down.
5134 __ rsb(dest, dest, Operand(30));
5135
5136 __ bind(&right_exponent);
5137 // Get the top bits of the mantissa.
5138 __ and_(scratch2, scratch, Operand(HeapNumber::kMantissaMask));
5139 // Put back the implicit 1.
5140 __ orr(scratch2, scratch2, Operand(1 << HeapNumber::kExponentShift));
5141 // Shift up the mantissa bits to take up the space the exponent used to take.
5142 // We just orred in the implicit bit so that took care of one and we want to
5143 // leave the sign bit 0 so we subtract 2 bits from the shift distance.
5144 const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
5145 __ mov(scratch2, Operand(scratch2, LSL, shift_distance));
5146 // Put sign in zero flag.
5147 __ tst(scratch, Operand(HeapNumber::kSignMask));
5148 // Get the second half of the double. For some exponents we don't actually
5149 // need this because the bits get shifted out again, but it's probably slower
5150 // to test than just to do it.
5151 __ ldr(scratch, FieldMemOperand(source, HeapNumber::kMantissaOffset));
5152 // Shift down 22 bits to get the last 10 bits.
5153 __ orr(scratch, scratch2, Operand(scratch, LSR, 32 - shift_distance));
5154 // Move down according to the exponent.
5155 __ mov(dest, Operand(scratch, LSR, dest));
5156 // Fix sign if sign bit was set.
5157 __ rsb(dest, dest, Operand(0), LeaveCC, ne);
5158 __ bind(&done);
5159}
5160
5161
5162// For bitwise ops where the inputs are not both Smis we here try to determine
5163// whether both inputs are either Smis or at least heap numbers that can be
5164// represented by a 32 bit signed value. We truncate towards zero as required
5165// by the ES spec. If this is the case we do the bitwise op and see if the
5166// result is a Smi. If so, great, otherwise we try to find a heap number to
5167// write the answer into (either by allocating or by overwriting).
5168// On entry the operands are in r0 and r1. On exit the answer is in r0.
5169void GenericBinaryOpStub::HandleNonSmiBitwiseOp(MacroAssembler* masm) {
5170 Label slow, result_not_a_smi;
5171 Label r0_is_smi, r1_is_smi;
5172 Label done_checking_r0, done_checking_r1;
5173
5174 __ tst(r1, Operand(kSmiTagMask));
5175 __ b(eq, &r1_is_smi); // It's a Smi so don't check it's a heap number.
5176 __ CompareObjectType(r1, r4, r4, HEAP_NUMBER_TYPE);
5177 __ b(ne, &slow);
5178 GetInt32(masm, r1, r3, r4, r5, &slow);
5179 __ jmp(&done_checking_r1);
5180 __ bind(&r1_is_smi);
5181 __ mov(r3, Operand(r1, ASR, 1));
5182 __ bind(&done_checking_r1);
5183
5184 __ tst(r0, Operand(kSmiTagMask));
5185 __ b(eq, &r0_is_smi); // It's a Smi so don't check it's a heap number.
5186 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
5187 __ b(ne, &slow);
5188 GetInt32(masm, r0, r2, r4, r5, &slow);
5189 __ jmp(&done_checking_r0);
5190 __ bind(&r0_is_smi);
5191 __ mov(r2, Operand(r0, ASR, 1));
5192 __ bind(&done_checking_r0);
5193
5194 // r0 and r1: Original operands (Smi or heap numbers).
5195 // r2 and r3: Signed int32 operands.
5196 switch (op_) {
5197 case Token::BIT_OR: __ orr(r2, r2, Operand(r3)); break;
5198 case Token::BIT_XOR: __ eor(r2, r2, Operand(r3)); break;
5199 case Token::BIT_AND: __ and_(r2, r2, Operand(r3)); break;
5200 case Token::SAR:
5201 // Use only the 5 least significant bits of the shift count.
5202 __ and_(r2, r2, Operand(0x1f));
5203 __ mov(r2, Operand(r3, ASR, r2));
5204 break;
5205 case Token::SHR:
5206 // Use only the 5 least significant bits of the shift count.
5207 __ and_(r2, r2, Operand(0x1f));
5208 __ mov(r2, Operand(r3, LSR, r2), SetCC);
5209 // SHR is special because it is required to produce a positive answer.
5210 // The code below for writing into heap numbers isn't capable of writing
5211 // the register as an unsigned int so we go to slow case if we hit this
5212 // case.
5213 __ b(mi, &slow);
5214 break;
5215 case Token::SHL:
5216 // Use only the 5 least significant bits of the shift count.
5217 __ and_(r2, r2, Operand(0x1f));
5218 __ mov(r2, Operand(r3, LSL, r2));
5219 break;
5220 default: UNREACHABLE();
5221 }
5222 // check that the *signed* result fits in a smi
5223 __ add(r3, r2, Operand(0x40000000), SetCC);
5224 __ b(mi, &result_not_a_smi);
5225 __ mov(r0, Operand(r2, LSL, kSmiTagSize));
5226 __ Ret();
5227
5228 Label have_to_allocate, got_a_heap_number;
5229 __ bind(&result_not_a_smi);
5230 switch (mode_) {
5231 case OVERWRITE_RIGHT: {
5232 __ tst(r0, Operand(kSmiTagMask));
5233 __ b(eq, &have_to_allocate);
5234 __ mov(r5, Operand(r0));
5235 break;
5236 }
5237 case OVERWRITE_LEFT: {
5238 __ tst(r1, Operand(kSmiTagMask));
5239 __ b(eq, &have_to_allocate);
5240 __ mov(r5, Operand(r1));
5241 break;
5242 }
5243 case NO_OVERWRITE: {
5244 // Get a new heap number in r5. r6 and r7 are scratch.
5245 AllocateHeapNumber(masm, &slow, r5, r6, r7);
5246 }
5247 default: break;
5248 }
5249 __ bind(&got_a_heap_number);
5250 // r2: Answer as signed int32.
5251 // r5: Heap number to write answer into.
5252
5253 // Nothing can go wrong now, so move the heap number to r0, which is the
5254 // result.
5255 __ mov(r0, Operand(r5));
5256
5257 // Tail call that writes the int32 in r2 to the heap number in r0, using
5258 // r3 as scratch. r0 is preserved and returned.
5259 WriteInt32ToHeapNumberStub stub(r2, r0, r3);
5260 __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
5261
5262 if (mode_ != NO_OVERWRITE) {
5263 __ bind(&have_to_allocate);
5264 // Get a new heap number in r5. r6 and r7 are scratch.
5265 AllocateHeapNumber(masm, &slow, r5, r6, r7);
5266 __ jmp(&got_a_heap_number);
5267 }
5268
5269 // If all else failed then we go to the runtime system.
5270 __ bind(&slow);
5271 __ push(r1); // restore stack
5272 __ push(r0);
5273 __ mov(r0, Operand(1)); // 1 argument (not counting receiver).
5274 switch (op_) {
5275 case Token::BIT_OR:
5276 __ InvokeBuiltin(Builtins::BIT_OR, JUMP_JS);
5277 break;
5278 case Token::BIT_AND:
5279 __ InvokeBuiltin(Builtins::BIT_AND, JUMP_JS);
5280 break;
5281 case Token::BIT_XOR:
5282 __ InvokeBuiltin(Builtins::BIT_XOR, JUMP_JS);
5283 break;
5284 case Token::SAR:
5285 __ InvokeBuiltin(Builtins::SAR, JUMP_JS);
5286 break;
5287 case Token::SHR:
5288 __ InvokeBuiltin(Builtins::SHR, JUMP_JS);
5289 break;
5290 case Token::SHL:
5291 __ InvokeBuiltin(Builtins::SHL, JUMP_JS);
5292 break;
5293 default:
5294 UNREACHABLE();
5295 }
5296}
5297
5298
5299// Can we multiply by x with max two shifts and an add.
5300// This answers yes to all integers from 2 to 10.
5301static bool IsEasyToMultiplyBy(int x) {
5302 if (x < 2) return false; // Avoid special cases.
5303 if (x > (Smi::kMaxValue + 1) >> 2) return false; // Almost always overflows.
5304 if (IsPowerOf2(x)) return true; // Simple shift.
5305 if (PopCountLessThanEqual2(x)) return true; // Shift and add and shift.
5306 if (IsPowerOf2(x + 1)) return true; // Patterns like 11111.
5307 return false;
5308}
5309
5310
5311// Can multiply by anything that IsEasyToMultiplyBy returns true for.
5312// Source and destination may be the same register. This routine does
5313// not set carry and overflow the way a mul instruction would.
5314static void MultiplyByKnownInt(MacroAssembler* masm,
5315 Register source,
5316 Register destination,
5317 int known_int) {
5318 if (IsPowerOf2(known_int)) {
5319 __ mov(destination, Operand(source, LSL, BitPosition(known_int)));
5320 } else if (PopCountLessThanEqual2(known_int)) {
5321 int first_bit = BitPosition(known_int);
5322 int second_bit = BitPosition(known_int ^ (1 << first_bit));
5323 __ add(destination, source, Operand(source, LSL, second_bit - first_bit));
5324 if (first_bit != 0) {
5325 __ mov(destination, Operand(destination, LSL, first_bit));
5326 }
5327 } else {
5328 ASSERT(IsPowerOf2(known_int + 1)); // Patterns like 1111.
5329 int the_bit = BitPosition(known_int + 1);
5330 __ rsb(destination, source, Operand(source, LSL, the_bit));
5331 }
5332}
5333
5334
5335// This function (as opposed to MultiplyByKnownInt) takes the known int in a
5336// a register for the cases where it doesn't know a good trick, and may deliver
5337// a result that needs shifting.
5338static void MultiplyByKnownInt2(
5339 MacroAssembler* masm,
5340 Register result,
5341 Register source,
5342 Register known_int_register, // Smi tagged.
5343 int known_int,
5344 int* required_shift) { // Including Smi tag shift
5345 switch (known_int) {
5346 case 3:
5347 __ add(result, source, Operand(source, LSL, 1));
5348 *required_shift = 1;
5349 break;
5350 case 5:
5351 __ add(result, source, Operand(source, LSL, 2));
5352 *required_shift = 1;
5353 break;
5354 case 6:
5355 __ add(result, source, Operand(source, LSL, 1));
5356 *required_shift = 2;
5357 break;
5358 case 7:
5359 __ rsb(result, source, Operand(source, LSL, 3));
5360 *required_shift = 1;
5361 break;
5362 case 9:
5363 __ add(result, source, Operand(source, LSL, 3));
5364 *required_shift = 1;
5365 break;
5366 case 10:
5367 __ add(result, source, Operand(source, LSL, 2));
5368 *required_shift = 2;
5369 break;
5370 default:
5371 ASSERT(!IsPowerOf2(known_int)); // That would be very inefficient.
5372 __ mul(result, source, known_int_register);
5373 *required_shift = 0;
5374 }
5375}
5376
5377
5378void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
5379 // r1 : x
5380 // r0 : y
5381 // result : r0
5382
5383 // All ops need to know whether we are dealing with two Smis. Set up r2 to
5384 // tell us that.
5385 __ orr(r2, r1, Operand(r0)); // r2 = x | y;
5386
5387 switch (op_) {
5388 case Token::ADD: {
5389 Label not_smi;
5390 // Fast path.
5391 ASSERT(kSmiTag == 0); // Adjust code below.
5392 __ tst(r2, Operand(kSmiTagMask));
5393 __ b(ne, &not_smi);
5394 __ add(r0, r1, Operand(r0), SetCC); // Add y optimistically.
5395 // Return if no overflow.
5396 __ Ret(vc);
5397 __ sub(r0, r0, Operand(r1)); // Revert optimistic add.
5398
5399 HandleBinaryOpSlowCases(masm,
5400 &not_smi,
5401 Builtins::ADD,
5402 Token::ADD,
5403 mode_);
5404 break;
5405 }
5406
5407 case Token::SUB: {
5408 Label not_smi;
5409 // Fast path.
5410 ASSERT(kSmiTag == 0); // Adjust code below.
5411 __ tst(r2, Operand(kSmiTagMask));
5412 __ b(ne, &not_smi);
5413 __ sub(r0, r1, Operand(r0), SetCC); // Subtract y optimistically.
5414 // Return if no overflow.
5415 __ Ret(vc);
5416 __ sub(r0, r1, Operand(r0)); // Revert optimistic subtract.
5417
5418 HandleBinaryOpSlowCases(masm,
5419 &not_smi,
5420 Builtins::SUB,
5421 Token::SUB,
5422 mode_);
5423 break;
5424 }
5425
5426 case Token::MUL: {
5427 Label not_smi, slow;
5428 ASSERT(kSmiTag == 0); // adjust code below
5429 __ tst(r2, Operand(kSmiTagMask));
5430 __ b(ne, &not_smi);
5431 // Remove tag from one operand (but keep sign), so that result is Smi.
5432 __ mov(ip, Operand(r0, ASR, kSmiTagSize));
5433 // Do multiplication
5434 __ smull(r3, r2, r1, ip); // r3 = lower 32 bits of ip*r1.
5435 // Go slow on overflows (overflow bit is not set).
5436 __ mov(ip, Operand(r3, ASR, 31));
5437 __ cmp(ip, Operand(r2)); // no overflow if higher 33 bits are identical
5438 __ b(ne, &slow);
5439 // Go slow on zero result to handle -0.
5440 __ tst(r3, Operand(r3));
5441 __ mov(r0, Operand(r3), LeaveCC, ne);
5442 __ Ret(ne);
5443 // We need -0 if we were multiplying a negative number with 0 to get 0.
5444 // We know one of them was zero.
5445 __ add(r2, r0, Operand(r1), SetCC);
5446 __ mov(r0, Operand(Smi::FromInt(0)), LeaveCC, pl);
5447 __ Ret(pl); // Return Smi 0 if the non-zero one was positive.
5448 // Slow case. We fall through here if we multiplied a negative number
5449 // with 0, because that would mean we should produce -0.
5450 __ bind(&slow);
5451
5452 HandleBinaryOpSlowCases(masm,
5453 &not_smi,
5454 Builtins::MUL,
5455 Token::MUL,
5456 mode_);
5457 break;
5458 }
5459
5460 case Token::DIV:
5461 case Token::MOD: {
5462 Label not_smi;
5463 if (specialized_on_rhs_) {
5464 Label smi_is_unsuitable;
5465 __ BranchOnNotSmi(r1, &not_smi);
5466 if (IsPowerOf2(constant_rhs_)) {
5467 if (op_ == Token::MOD) {
5468 __ and_(r0,
5469 r1,
5470 Operand(0x80000000u | ((constant_rhs_ << kSmiTagSize) - 1)),
5471 SetCC);
5472 // We now have the answer, but if the input was negative we also
5473 // have the sign bit. Our work is done if the result is
5474 // positive or zero:
5475 __ Ret(pl);
5476 // A mod of a negative left hand side must return a negative number.
5477 // Unfortunately if the answer is 0 then we must return -0. And we
5478 // already optimistically trashed r0 so we may need to restore it.
5479 __ eor(r0, r0, Operand(0x80000000u), SetCC);
5480 // Next two instructions are conditional on the answer being -0.
5481 __ mov(r0, Operand(Smi::FromInt(constant_rhs_)), LeaveCC, eq);
5482 __ b(eq, &smi_is_unsuitable);
5483 // We need to subtract the dividend. Eg. -3 % 4 == -3.
5484 __ sub(r0, r0, Operand(Smi::FromInt(constant_rhs_)));
5485 } else {
5486 ASSERT(op_ == Token::DIV);
5487 __ tst(r1,
5488 Operand(0x80000000u | ((constant_rhs_ << kSmiTagSize) - 1)));
5489 __ b(ne, &smi_is_unsuitable); // Go slow on negative or remainder.
5490 int shift = 0;
5491 int d = constant_rhs_;
5492 while ((d & 1) == 0) {
5493 d >>= 1;
5494 shift++;
5495 }
5496 __ mov(r0, Operand(r1, LSR, shift));
5497 __ bic(r0, r0, Operand(kSmiTagMask));
5498 }
5499 } else {
5500 // Not a power of 2.
5501 __ tst(r1, Operand(0x80000000u));
5502 __ b(ne, &smi_is_unsuitable);
5503 // Find a fixed point reciprocal of the divisor so we can divide by
5504 // multiplying.
5505 double divisor = 1.0 / constant_rhs_;
5506 int shift = 32;
5507 double scale = 4294967296.0; // 1 << 32.
5508 uint32_t mul;
5509 // Maximise the precision of the fixed point reciprocal.
5510 while (true) {
5511 mul = static_cast<uint32_t>(scale * divisor);
5512 if (mul >= 0x7fffffff) break;
5513 scale *= 2.0;
5514 shift++;
5515 }
5516 mul++;
5517 __ mov(r2, Operand(mul));
5518 __ umull(r3, r2, r2, r1);
5519 __ mov(r2, Operand(r2, LSR, shift - 31));
5520 // r2 is r1 / rhs. r2 is not Smi tagged.
5521 // r0 is still the known rhs. r0 is Smi tagged.
5522 // r1 is still the unkown lhs. r1 is Smi tagged.
5523 int required_r4_shift = 0; // Including the Smi tag shift of 1.
5524 // r4 = r2 * r0.
5525 MultiplyByKnownInt2(masm,
5526 r4,
5527 r2,
5528 r0,
5529 constant_rhs_,
5530 &required_r4_shift);
5531 // r4 << required_r4_shift is now the Smi tagged rhs * (r1 / rhs).
5532 if (op_ == Token::DIV) {
5533 __ sub(r3, r1, Operand(r4, LSL, required_r4_shift), SetCC);
5534 __ b(ne, &smi_is_unsuitable); // There was a remainder.
5535 __ mov(r0, Operand(r2, LSL, kSmiTagSize));
5536 } else {
5537 ASSERT(op_ == Token::MOD);
5538 __ sub(r0, r1, Operand(r4, LSL, required_r4_shift));
5539 }
5540 }
5541 __ Ret();
5542 __ bind(&smi_is_unsuitable);
5543 } else {
5544 __ jmp(&not_smi);
5545 }
5546 HandleBinaryOpSlowCases(masm,
5547 &not_smi,
5548 op_ == Token::MOD ? Builtins::MOD : Builtins::DIV,
5549 op_,
5550 mode_);
5551 break;
5552 }
5553
5554 case Token::BIT_OR:
5555 case Token::BIT_AND:
5556 case Token::BIT_XOR:
5557 case Token::SAR:
5558 case Token::SHR:
5559 case Token::SHL: {
5560 Label slow;
5561 ASSERT(kSmiTag == 0); // adjust code below
5562 __ tst(r2, Operand(kSmiTagMask));
5563 __ b(ne, &slow);
5564 switch (op_) {
5565 case Token::BIT_OR: __ orr(r0, r0, Operand(r1)); break;
5566 case Token::BIT_AND: __ and_(r0, r0, Operand(r1)); break;
5567 case Token::BIT_XOR: __ eor(r0, r0, Operand(r1)); break;
5568 case Token::SAR:
5569 // Remove tags from right operand.
5570 __ mov(r2, Operand(r0, ASR, kSmiTagSize)); // y
5571 // Use only the 5 least significant bits of the shift count.
5572 __ and_(r2, r2, Operand(0x1f));
5573 __ mov(r0, Operand(r1, ASR, r2));
5574 // Smi tag result.
5575 __ bic(r0, r0, Operand(kSmiTagMask));
5576 break;
5577 case Token::SHR:
5578 // Remove tags from operands. We can't do this on a 31 bit number
5579 // because then the 0s get shifted into bit 30 instead of bit 31.
5580 __ mov(r3, Operand(r1, ASR, kSmiTagSize)); // x
5581 __ mov(r2, Operand(r0, ASR, kSmiTagSize)); // y
5582 // Use only the 5 least significant bits of the shift count.
5583 __ and_(r2, r2, Operand(0x1f));
5584 __ mov(r3, Operand(r3, LSR, r2));
5585 // Unsigned shift is not allowed to produce a negative number, so
5586 // check the sign bit and the sign bit after Smi tagging.
5587 __ tst(r3, Operand(0xc0000000));
5588 __ b(ne, &slow);
5589 // Smi tag result.
5590 __ mov(r0, Operand(r3, LSL, kSmiTagSize));
5591 break;
5592 case Token::SHL:
5593 // Remove tags from operands.
5594 __ mov(r3, Operand(r1, ASR, kSmiTagSize)); // x
5595 __ mov(r2, Operand(r0, ASR, kSmiTagSize)); // y
5596 // Use only the 5 least significant bits of the shift count.
5597 __ and_(r2, r2, Operand(0x1f));
5598 __ mov(r3, Operand(r3, LSL, r2));
5599 // Check that the signed result fits in a Smi.
5600 __ add(r2, r3, Operand(0x40000000), SetCC);
5601 __ b(mi, &slow);
5602 __ mov(r0, Operand(r3, LSL, kSmiTagSize));
5603 break;
5604 default: UNREACHABLE();
5605 }
5606 __ Ret();
5607 __ bind(&slow);
5608 HandleNonSmiBitwiseOp(masm);
5609 break;
5610 }
5611
5612 default: UNREACHABLE();
5613 }
5614 // This code should be unreachable.
5615 __ stop("Unreachable");
5616}
5617
5618
5619void StackCheckStub::Generate(MacroAssembler* masm) {
5620 // Do tail-call to runtime routine. Runtime routines expect at least one
5621 // argument, so give it a Smi.
5622 __ mov(r0, Operand(Smi::FromInt(0)));
5623 __ push(r0);
5624 __ TailCallRuntime(ExternalReference(Runtime::kStackGuard), 1, 1);
5625
5626 __ StubReturn(1);
5627}
5628
5629
5630void UnarySubStub::Generate(MacroAssembler* masm) {
5631 Label undo;
5632 Label slow;
5633 Label not_smi;
5634
5635 // Enter runtime system if the value is not a smi.
5636 __ tst(r0, Operand(kSmiTagMask));
5637 __ b(ne, &not_smi);
5638
5639 // Enter runtime system if the value of the expression is zero
5640 // to make sure that we switch between 0 and -0.
5641 __ cmp(r0, Operand(0));
5642 __ b(eq, &slow);
5643
5644 // The value of the expression is a smi that is not zero. Try
5645 // optimistic subtraction '0 - value'.
5646 __ rsb(r1, r0, Operand(0), SetCC);
5647 __ b(vs, &slow);
5648
5649 __ mov(r0, Operand(r1)); // Set r0 to result.
5650 __ StubReturn(1);
5651
5652 // Enter runtime system.
5653 __ bind(&slow);
5654 __ push(r0);
5655 __ mov(r0, Operand(0)); // Set number of arguments.
5656 __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_JS);
5657
5658 __ bind(&not_smi);
5659 __ CompareObjectType(r0, r1, r1, HEAP_NUMBER_TYPE);
5660 __ b(ne, &slow);
5661 // r0 is a heap number. Get a new heap number in r1.
5662 if (overwrite_) {
5663 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
5664 __ eor(r2, r2, Operand(HeapNumber::kSignMask)); // Flip sign.
5665 __ str(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
5666 } else {
5667 AllocateHeapNumber(masm, &slow, r1, r2, r3);
5668 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
5669 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
5670 __ str(r3, FieldMemOperand(r1, HeapNumber::kMantissaOffset));
5671 __ eor(r2, r2, Operand(HeapNumber::kSignMask)); // Flip sign.
5672 __ str(r2, FieldMemOperand(r1, HeapNumber::kExponentOffset));
5673 __ mov(r0, Operand(r1));
5674 }
5675 __ StubReturn(1);
5676}
5677
5678
5679int CEntryStub::MinorKey() {
5680 ASSERT(result_size_ <= 2);
5681 // Result returned in r0 or r0+r1 by default.
5682 return 0;
5683}
5684
5685
5686void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
5687 // r0 holds the exception.
5688
5689 // Adjust this code if not the case.
5690 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
5691
5692 // Drop the sp to the top of the handler.
5693 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
5694 __ ldr(sp, MemOperand(r3));
5695
5696 // Restore the next handler and frame pointer, discard handler state.
5697 ASSERT(StackHandlerConstants::kNextOffset == 0);
5698 __ pop(r2);
5699 __ str(r2, MemOperand(r3));
5700 ASSERT(StackHandlerConstants::kFPOffset == 2 * kPointerSize);
5701 __ ldm(ia_w, sp, r3.bit() | fp.bit()); // r3: discarded state.
5702
5703 // Before returning we restore the context from the frame pointer if
5704 // not NULL. The frame pointer is NULL in the exception handler of a
5705 // JS entry frame.
5706 __ cmp(fp, Operand(0));
5707 // Set cp to NULL if fp is NULL.
5708 __ mov(cp, Operand(0), LeaveCC, eq);
5709 // Restore cp otherwise.
5710 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
5711#ifdef DEBUG
5712 if (FLAG_debug_code) {
5713 __ mov(lr, Operand(pc));
5714 }
5715#endif
5716 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
5717 __ pop(pc);
5718}
5719
5720
5721void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
5722 UncatchableExceptionType type) {
5723 // Adjust this code if not the case.
5724 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
5725
5726 // Drop sp to the top stack handler.
5727 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
5728 __ ldr(sp, MemOperand(r3));
5729
5730 // Unwind the handlers until the ENTRY handler is found.
5731 Label loop, done;
5732 __ bind(&loop);
5733 // Load the type of the current stack handler.
5734 const int kStateOffset = StackHandlerConstants::kStateOffset;
5735 __ ldr(r2, MemOperand(sp, kStateOffset));
5736 __ cmp(r2, Operand(StackHandler::ENTRY));
5737 __ b(eq, &done);
5738 // Fetch the next handler in the list.
5739 const int kNextOffset = StackHandlerConstants::kNextOffset;
5740 __ ldr(sp, MemOperand(sp, kNextOffset));
5741 __ jmp(&loop);
5742 __ bind(&done);
5743
5744 // Set the top handler address to next handler past the current ENTRY handler.
5745 ASSERT(StackHandlerConstants::kNextOffset == 0);
5746 __ pop(r2);
5747 __ str(r2, MemOperand(r3));
5748
5749 if (type == OUT_OF_MEMORY) {
5750 // Set external caught exception to false.
5751 ExternalReference external_caught(Top::k_external_caught_exception_address);
5752 __ mov(r0, Operand(false));
5753 __ mov(r2, Operand(external_caught));
5754 __ str(r0, MemOperand(r2));
5755
5756 // Set pending exception and r0 to out of memory exception.
5757 Failure* out_of_memory = Failure::OutOfMemoryException();
5758 __ mov(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
5759 __ mov(r2, Operand(ExternalReference(Top::k_pending_exception_address)));
5760 __ str(r0, MemOperand(r2));
5761 }
5762
5763 // Stack layout at this point. See also StackHandlerConstants.
5764 // sp -> state (ENTRY)
5765 // fp
5766 // lr
5767
5768 // Discard handler state (r2 is not used) and restore frame pointer.
5769 ASSERT(StackHandlerConstants::kFPOffset == 2 * kPointerSize);
5770 __ ldm(ia_w, sp, r2.bit() | fp.bit()); // r2: discarded state.
5771 // Before returning we restore the context from the frame pointer if
5772 // not NULL. The frame pointer is NULL in the exception handler of a
5773 // JS entry frame.
5774 __ cmp(fp, Operand(0));
5775 // Set cp to NULL if fp is NULL.
5776 __ mov(cp, Operand(0), LeaveCC, eq);
5777 // Restore cp otherwise.
5778 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
5779#ifdef DEBUG
5780 if (FLAG_debug_code) {
5781 __ mov(lr, Operand(pc));
5782 }
5783#endif
5784 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
5785 __ pop(pc);
5786}
5787
5788
5789void CEntryStub::GenerateCore(MacroAssembler* masm,
5790 Label* throw_normal_exception,
5791 Label* throw_termination_exception,
5792 Label* throw_out_of_memory_exception,
5793 StackFrame::Type frame_type,
5794 bool do_gc,
5795 bool always_allocate) {
5796 // r0: result parameter for PerformGC, if any
5797 // r4: number of arguments including receiver (C callee-saved)
5798 // r5: pointer to builtin function (C callee-saved)
5799 // r6: pointer to the first argument (C callee-saved)
5800
5801 if (do_gc) {
5802 // Passing r0.
5803 ExternalReference gc_reference = ExternalReference::perform_gc_function();
5804 __ Call(gc_reference.address(), RelocInfo::RUNTIME_ENTRY);
5805 }
5806
5807 ExternalReference scope_depth =
5808 ExternalReference::heap_always_allocate_scope_depth();
5809 if (always_allocate) {
5810 __ mov(r0, Operand(scope_depth));
5811 __ ldr(r1, MemOperand(r0));
5812 __ add(r1, r1, Operand(1));
5813 __ str(r1, MemOperand(r0));
5814 }
5815
5816 // Call C built-in.
5817 // r0 = argc, r1 = argv
5818 __ mov(r0, Operand(r4));
5819 __ mov(r1, Operand(r6));
5820
5821 // TODO(1242173): To let the GC traverse the return address of the exit
5822 // frames, we need to know where the return address is. Right now,
5823 // we push it on the stack to be able to find it again, but we never
5824 // restore from it in case of changes, which makes it impossible to
5825 // support moving the C entry code stub. This should be fixed, but currently
5826 // this is OK because the CEntryStub gets generated so early in the V8 boot
5827 // sequence that it is not moving ever.
5828 masm->add(lr, pc, Operand(4)); // compute return address: (pc + 8) + 4
5829 masm->push(lr);
5830 masm->Jump(r5);
5831
5832 if (always_allocate) {
5833 // It's okay to clobber r2 and r3 here. Don't mess with r0 and r1
5834 // though (contain the result).
5835 __ mov(r2, Operand(scope_depth));
5836 __ ldr(r3, MemOperand(r2));
5837 __ sub(r3, r3, Operand(1));
5838 __ str(r3, MemOperand(r2));
5839 }
5840
5841 // check for failure result
5842 Label failure_returned;
5843 ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
5844 // Lower 2 bits of r2 are 0 iff r0 has failure tag.
5845 __ add(r2, r0, Operand(1));
5846 __ tst(r2, Operand(kFailureTagMask));
5847 __ b(eq, &failure_returned);
5848
5849 // Exit C frame and return.
5850 // r0:r1: result
5851 // sp: stack pointer
5852 // fp: frame pointer
5853 __ LeaveExitFrame(frame_type);
5854
5855 // check if we should retry or throw exception
5856 Label retry;
5857 __ bind(&failure_returned);
5858 ASSERT(Failure::RETRY_AFTER_GC == 0);
5859 __ tst(r0, Operand(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
5860 __ b(eq, &retry);
5861
5862 // Special handling of out of memory exceptions.
5863 Failure* out_of_memory = Failure::OutOfMemoryException();
5864 __ cmp(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
5865 __ b(eq, throw_out_of_memory_exception);
5866
5867 // Retrieve the pending exception and clear the variable.
5868 __ mov(ip, Operand(ExternalReference::the_hole_value_location()));
5869 __ ldr(r3, MemOperand(ip));
5870 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
5871 __ ldr(r0, MemOperand(ip));
5872 __ str(r3, MemOperand(ip));
5873
5874 // Special handling of termination exceptions which are uncatchable
5875 // by javascript code.
5876 __ cmp(r0, Operand(Factory::termination_exception()));
5877 __ b(eq, throw_termination_exception);
5878
5879 // Handle normal exception.
5880 __ jmp(throw_normal_exception);
5881
5882 __ bind(&retry); // pass last failure (r0) as parameter (r0) when retrying
5883}
5884
5885
5886void CEntryStub::GenerateBody(MacroAssembler* masm, bool is_debug_break) {
5887 // Called from JavaScript; parameters are on stack as if calling JS function
5888 // r0: number of arguments including receiver
5889 // r1: pointer to builtin function
5890 // fp: frame pointer (restored after C call)
5891 // sp: stack pointer (restored as callee's sp after C call)
5892 // cp: current context (C callee-saved)
5893
5894 // NOTE: Invocations of builtins may return failure objects
5895 // instead of a proper result. The builtin entry handles
5896 // this by performing a garbage collection and retrying the
5897 // builtin once.
5898
5899 StackFrame::Type frame_type = is_debug_break
5900 ? StackFrame::EXIT_DEBUG
5901 : StackFrame::EXIT;
5902
5903 // Enter the exit frame that transitions from JavaScript to C++.
5904 __ EnterExitFrame(frame_type);
5905
5906 // r4: number of arguments (C callee-saved)
5907 // r5: pointer to builtin function (C callee-saved)
5908 // r6: pointer to first argument (C callee-saved)
5909
5910 Label throw_normal_exception;
5911 Label throw_termination_exception;
5912 Label throw_out_of_memory_exception;
5913
5914 // Call into the runtime system.
5915 GenerateCore(masm,
5916 &throw_normal_exception,
5917 &throw_termination_exception,
5918 &throw_out_of_memory_exception,
5919 frame_type,
5920 false,
5921 false);
5922
5923 // Do space-specific GC and retry runtime call.
5924 GenerateCore(masm,
5925 &throw_normal_exception,
5926 &throw_termination_exception,
5927 &throw_out_of_memory_exception,
5928 frame_type,
5929 true,
5930 false);
5931
5932 // Do full GC and retry runtime call one final time.
5933 Failure* failure = Failure::InternalError();
5934 __ mov(r0, Operand(reinterpret_cast<int32_t>(failure)));
5935 GenerateCore(masm,
5936 &throw_normal_exception,
5937 &throw_termination_exception,
5938 &throw_out_of_memory_exception,
5939 frame_type,
5940 true,
5941 true);
5942
5943 __ bind(&throw_out_of_memory_exception);
5944 GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
5945
5946 __ bind(&throw_termination_exception);
5947 GenerateThrowUncatchable(masm, TERMINATION);
5948
5949 __ bind(&throw_normal_exception);
5950 GenerateThrowTOS(masm);
5951}
5952
5953
5954void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
5955 // r0: code entry
5956 // r1: function
5957 // r2: receiver
5958 // r3: argc
5959 // [sp+0]: argv
5960
5961 Label invoke, exit;
5962
5963 // Called from C, so do not pop argc and args on exit (preserve sp)
5964 // No need to save register-passed args
5965 // Save callee-saved registers (incl. cp and fp), sp, and lr
5966 __ stm(db_w, sp, kCalleeSaved | lr.bit());
5967
5968 // Get address of argv, see stm above.
5969 // r0: code entry
5970 // r1: function
5971 // r2: receiver
5972 // r3: argc
5973 __ add(r4, sp, Operand((kNumCalleeSaved + 1)*kPointerSize));
5974 __ ldr(r4, MemOperand(r4)); // argv
5975
5976 // Push a frame with special values setup to mark it as an entry frame.
5977 // r0: code entry
5978 // r1: function
5979 // r2: receiver
5980 // r3: argc
5981 // r4: argv
5982 __ mov(r8, Operand(-1)); // Push a bad frame pointer to fail if it is used.
5983 int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
5984 __ mov(r7, Operand(Smi::FromInt(marker)));
5985 __ mov(r6, Operand(Smi::FromInt(marker)));
5986 __ mov(r5, Operand(ExternalReference(Top::k_c_entry_fp_address)));
5987 __ ldr(r5, MemOperand(r5));
5988 __ stm(db_w, sp, r5.bit() | r6.bit() | r7.bit() | r8.bit());
5989
5990 // Setup frame pointer for the frame to be pushed.
5991 __ add(fp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
5992
5993 // Call a faked try-block that does the invoke.
5994 __ bl(&invoke);
5995
5996 // Caught exception: Store result (exception) in the pending
5997 // exception field in the JSEnv and return a failure sentinel.
5998 // Coming in here the fp will be invalid because the PushTryHandler below
5999 // sets it to 0 to signal the existence of the JSEntry frame.
6000 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
6001 __ str(r0, MemOperand(ip));
6002 __ mov(r0, Operand(reinterpret_cast<int32_t>(Failure::Exception())));
6003 __ b(&exit);
6004
6005 // Invoke: Link this frame into the handler chain.
6006 __ bind(&invoke);
6007 // Must preserve r0-r4, r5-r7 are available.
6008 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
6009 // If an exception not caught by another handler occurs, this handler
6010 // returns control to the code after the bl(&invoke) above, which
6011 // restores all kCalleeSaved registers (including cp and fp) to their
6012 // saved values before returning a failure to C.
6013
6014 // Clear any pending exceptions.
6015 __ mov(ip, Operand(ExternalReference::the_hole_value_location()));
6016 __ ldr(r5, MemOperand(ip));
6017 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
6018 __ str(r5, MemOperand(ip));
6019
6020 // Invoke the function by calling through JS entry trampoline builtin.
6021 // Notice that we cannot store a reference to the trampoline code directly in
6022 // this stub, because runtime stubs are not traversed when doing GC.
6023
6024 // Expected registers by Builtins::JSEntryTrampoline
6025 // r0: code entry
6026 // r1: function
6027 // r2: receiver
6028 // r3: argc
6029 // r4: argv
6030 if (is_construct) {
6031 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
6032 __ mov(ip, Operand(construct_entry));
6033 } else {
6034 ExternalReference entry(Builtins::JSEntryTrampoline);
6035 __ mov(ip, Operand(entry));
6036 }
6037 __ ldr(ip, MemOperand(ip)); // deref address
6038
6039 // Branch and link to JSEntryTrampoline. We don't use the double underscore
6040 // macro for the add instruction because we don't want the coverage tool
6041 // inserting instructions here after we read the pc.
6042 __ mov(lr, Operand(pc));
6043 masm->add(pc, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
6044
6045 // Unlink this frame from the handler chain. When reading the
6046 // address of the next handler, there is no need to use the address
6047 // displacement since the current stack pointer (sp) points directly
6048 // to the stack handler.
6049 __ ldr(r3, MemOperand(sp, StackHandlerConstants::kNextOffset));
6050 __ mov(ip, Operand(ExternalReference(Top::k_handler_address)));
6051 __ str(r3, MemOperand(ip));
6052 // No need to restore registers
6053 __ add(sp, sp, Operand(StackHandlerConstants::kSize));
6054
6055
6056 __ bind(&exit); // r0 holds result
6057 // Restore the top frame descriptors from the stack.
6058 __ pop(r3);
6059 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
6060 __ str(r3, MemOperand(ip));
6061
6062 // Reset the stack to the callee saved registers.
6063 __ add(sp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
6064
6065 // Restore callee-saved registers and return.
6066#ifdef DEBUG
6067 if (FLAG_debug_code) {
6068 __ mov(lr, Operand(pc));
6069 }
6070#endif
6071 __ ldm(ia_w, sp, kCalleeSaved | pc.bit());
6072}
6073
6074
6075// This stub performs an instanceof, calling the builtin function if
6076// necessary. Uses r1 for the object, r0 for the function that it may
6077// be an instance of (these are fetched from the stack).
6078void InstanceofStub::Generate(MacroAssembler* masm) {
6079 // Get the object - slow case for smis (we may need to throw an exception
6080 // depending on the rhs).
6081 Label slow, loop, is_instance, is_not_instance;
6082 __ ldr(r0, MemOperand(sp, 1 * kPointerSize));
6083 __ BranchOnSmi(r0, &slow);
6084
6085 // Check that the left hand is a JS object and put map in r3.
6086 __ CompareObjectType(r0, r3, r2, FIRST_JS_OBJECT_TYPE);
6087 __ b(lt, &slow);
6088 __ cmp(r2, Operand(LAST_JS_OBJECT_TYPE));
6089 __ b(gt, &slow);
6090
6091 // Get the prototype of the function (r4 is result, r2 is scratch).
6092 __ ldr(r1, MemOperand(sp, 0 * kPointerSize));
6093 __ TryGetFunctionPrototype(r1, r4, r2, &slow);
6094
6095 // Check that the function prototype is a JS object.
6096 __ BranchOnSmi(r4, &slow);
6097 __ CompareObjectType(r4, r5, r5, FIRST_JS_OBJECT_TYPE);
6098 __ b(lt, &slow);
6099 __ cmp(r5, Operand(LAST_JS_OBJECT_TYPE));
6100 __ b(gt, &slow);
6101
6102 // Register mapping: r3 is object map and r4 is function prototype.
6103 // Get prototype of object into r2.
6104 __ ldr(r2, FieldMemOperand(r3, Map::kPrototypeOffset));
6105
6106 // Loop through the prototype chain looking for the function prototype.
6107 __ bind(&loop);
6108 __ cmp(r2, Operand(r4));
6109 __ b(eq, &is_instance);
6110 __ LoadRoot(ip, Heap::kNullValueRootIndex);
6111 __ cmp(r2, ip);
6112 __ b(eq, &is_not_instance);
6113 __ ldr(r2, FieldMemOperand(r2, HeapObject::kMapOffset));
6114 __ ldr(r2, FieldMemOperand(r2, Map::kPrototypeOffset));
6115 __ jmp(&loop);
6116
6117 __ bind(&is_instance);
6118 __ mov(r0, Operand(Smi::FromInt(0)));
6119 __ pop();
6120 __ pop();
6121 __ mov(pc, Operand(lr)); // Return.
6122
6123 __ bind(&is_not_instance);
6124 __ mov(r0, Operand(Smi::FromInt(1)));
6125 __ pop();
6126 __ pop();
6127 __ mov(pc, Operand(lr)); // Return.
6128
6129 // Slow-case. Tail call builtin.
6130 __ bind(&slow);
6131 __ mov(r0, Operand(1)); // Arg count without receiver.
6132 __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_JS);
6133}
6134
6135
6136void ArgumentsAccessStub::GenerateReadLength(MacroAssembler* masm) {
6137 // Check if the calling frame is an arguments adaptor frame.
6138 Label adaptor;
6139 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
6140 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
6141 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6142 __ b(eq, &adaptor);
6143
6144 // Nothing to do: The formal number of parameters has already been
6145 // passed in register r0 by calling function. Just return it.
6146 __ Jump(lr);
6147
6148 // Arguments adaptor case: Read the arguments length from the
6149 // adaptor frame and return it.
6150 __ bind(&adaptor);
6151 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
6152 __ Jump(lr);
6153}
6154
6155
6156void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
6157 // The displacement is the offset of the last parameter (if any)
6158 // relative to the frame pointer.
6159 static const int kDisplacement =
6160 StandardFrameConstants::kCallerSPOffset - kPointerSize;
6161
6162 // Check that the key is a smi.
6163 Label slow;
6164 __ BranchOnNotSmi(r1, &slow);
6165
6166 // Check if the calling frame is an arguments adaptor frame.
6167 Label adaptor;
6168 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
6169 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
6170 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6171 __ b(eq, &adaptor);
6172
6173 // Check index against formal parameters count limit passed in
6174 // through register eax. Use unsigned comparison to get negative
6175 // check for free.
6176 __ cmp(r1, r0);
6177 __ b(cs, &slow);
6178
6179 // Read the argument from the stack and return it.
6180 __ sub(r3, r0, r1);
6181 __ add(r3, fp, Operand(r3, LSL, kPointerSizeLog2 - kSmiTagSize));
6182 __ ldr(r0, MemOperand(r3, kDisplacement));
6183 __ Jump(lr);
6184
6185 // Arguments adaptor case: Check index against actual arguments
6186 // limit found in the arguments adaptor frame. Use unsigned
6187 // comparison to get negative check for free.
6188 __ bind(&adaptor);
6189 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
6190 __ cmp(r1, r0);
6191 __ b(cs, &slow);
6192
6193 // Read the argument from the adaptor frame and return it.
6194 __ sub(r3, r0, r1);
6195 __ add(r3, r2, Operand(r3, LSL, kPointerSizeLog2 - kSmiTagSize));
6196 __ ldr(r0, MemOperand(r3, kDisplacement));
6197 __ Jump(lr);
6198
6199 // Slow-case: Handle non-smi or out-of-bounds access to arguments
6200 // by calling the runtime system.
6201 __ bind(&slow);
6202 __ push(r1);
6203 __ TailCallRuntime(ExternalReference(Runtime::kGetArgumentsProperty), 1, 1);
6204}
6205
6206
6207void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
6208 // Check if the calling frame is an arguments adaptor frame.
6209 Label runtime;
6210 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
6211 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
6212 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6213 __ b(ne, &runtime);
6214
6215 // Patch the arguments.length and the parameters pointer.
6216 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
6217 __ str(r0, MemOperand(sp, 0 * kPointerSize));
6218 __ add(r3, r2, Operand(r0, LSL, kPointerSizeLog2 - kSmiTagSize));
6219 __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
6220 __ str(r3, MemOperand(sp, 1 * kPointerSize));
6221
6222 // Do the runtime call to allocate the arguments object.
6223 __ bind(&runtime);
6224 __ TailCallRuntime(ExternalReference(Runtime::kNewArgumentsFast), 3, 1);
6225}
6226
6227
6228void CallFunctionStub::Generate(MacroAssembler* masm) {
6229 Label slow;
6230 // Get the function to call from the stack.
6231 // function, receiver [, arguments]
6232 __ ldr(r1, MemOperand(sp, (argc_ + 1) * kPointerSize));
6233
6234 // Check that the function is really a JavaScript function.
6235 // r1: pushed function (to be verified)
6236 __ BranchOnSmi(r1, &slow);
6237 // Get the map of the function object.
6238 __ CompareObjectType(r1, r2, r2, JS_FUNCTION_TYPE);
6239 __ b(ne, &slow);
6240
6241 // Fast-case: Invoke the function now.
6242 // r1: pushed function
6243 ParameterCount actual(argc_);
6244 __ InvokeFunction(r1, actual, JUMP_FUNCTION);
6245
6246 // Slow-case: Non-function called.
6247 __ bind(&slow);
6248 __ mov(r0, Operand(argc_)); // Setup the number of arguments.
6249 __ mov(r2, Operand(0));
6250 __ GetBuiltinEntry(r3, Builtins::CALL_NON_FUNCTION);
6251 __ Jump(Handle<Code>(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline)),
6252 RelocInfo::CODE_TARGET);
6253}
6254
6255
6256int CompareStub::MinorKey() {
6257 // Encode the two parameters in a unique 16 bit value.
6258 ASSERT(static_cast<unsigned>(cc_) >> 28 < (1 << 15));
6259 return (static_cast<unsigned>(cc_) >> 27) | (strict_ ? 1 : 0);
6260}
6261
6262
6263#undef __
6264
6265} } // namespace v8::internal