blob: 20fbfa35c283e1c428a4a41c66dd1b195663803f [file] [log] [blame]
Leon Clarked91b9f72010-01-27 17:25:45 +00001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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
Leon Clarkef7060e22010-06-03 12:02:55 +010030#if defined(V8_TARGET_ARCH_IA32)
31
Steve Blocka7e24c12009-10-30 11:49:00 +000032#include "bootstrapper.h"
33#include "codegen-inl.h"
Steve Blockd0582a62009-12-15 09:54:21 +000034#include "compiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000035#include "debug.h"
36#include "ic-inl.h"
37#include "parser.h"
Leon Clarkee46be812010-01-19 14:06:41 +000038#include "regexp-macro-assembler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000039#include "register-allocator-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000040#include "scopes.h"
Steve Block6ded16b2010-05-10 14:33:55 +010041#include "virtual-frame-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43namespace v8 {
44namespace internal {
45
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010046#define __ ACCESS_MASM(masm)
Steve Blocka7e24c12009-10-30 11:49:00 +000047
48// -------------------------------------------------------------------------
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010049// Platform-specific FrameRegisterState functions.
Steve Blocka7e24c12009-10-30 11:49:00 +000050
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010051void FrameRegisterState::Save(MacroAssembler* masm) const {
Steve Blocka7e24c12009-10-30 11:49:00 +000052 for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
53 int action = registers_[i];
54 if (action == kPush) {
55 __ push(RegisterAllocator::ToRegister(i));
56 } else if (action != kIgnore && (action & kSyncedFlag) == 0) {
57 __ mov(Operand(ebp, action), RegisterAllocator::ToRegister(i));
58 }
59 }
60}
61
62
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010063void FrameRegisterState::Restore(MacroAssembler* masm) const {
Steve Blocka7e24c12009-10-30 11:49:00 +000064 // Restore registers in reverse order due to the stack.
65 for (int i = RegisterAllocator::kNumRegisters - 1; i >= 0; i--) {
66 int action = registers_[i];
67 if (action == kPush) {
68 __ pop(RegisterAllocator::ToRegister(i));
69 } else if (action != kIgnore) {
70 action &= ~kSyncedFlag;
71 __ mov(RegisterAllocator::ToRegister(i), Operand(ebp, action));
72 }
73 }
74}
75
76
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010077#undef __
78#define __ ACCESS_MASM(masm_)
79
80// -------------------------------------------------------------------------
81// Platform-specific DeferredCode functions.
82
83void DeferredCode::SaveRegisters() {
84 frame_state_.Save(masm_);
85}
86
87
88void DeferredCode::RestoreRegisters() {
89 frame_state_.Restore(masm_);
90}
91
92
93// -------------------------------------------------------------------------
94// Platform-specific RuntimeCallHelper functions.
95
96void VirtualFrameRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
97 frame_state_->Save(masm);
98}
99
100
101void VirtualFrameRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
102 frame_state_->Restore(masm);
103}
104
105
106void ICRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
107 masm->EnterInternalFrame();
108}
109
110
111void ICRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
112 masm->LeaveInternalFrame();
113}
114
115
Steve Blocka7e24c12009-10-30 11:49:00 +0000116// -------------------------------------------------------------------------
117// CodeGenState implementation.
118
119CodeGenState::CodeGenState(CodeGenerator* owner)
120 : owner_(owner),
Steve Blocka7e24c12009-10-30 11:49:00 +0000121 destination_(NULL),
122 previous_(NULL) {
123 owner_->set_state(this);
124}
125
126
127CodeGenState::CodeGenState(CodeGenerator* owner,
Steve Blocka7e24c12009-10-30 11:49:00 +0000128 ControlDestination* destination)
129 : owner_(owner),
Steve Blocka7e24c12009-10-30 11:49:00 +0000130 destination_(destination),
131 previous_(owner->state()) {
132 owner_->set_state(this);
133}
134
135
136CodeGenState::~CodeGenState() {
137 ASSERT(owner_->state() == this);
138 owner_->set_state(previous_);
139}
140
141
142// -------------------------------------------------------------------------
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100143// CodeGenerator implementation.
Steve Blocka7e24c12009-10-30 11:49:00 +0000144
Andrei Popescu31002712010-02-23 13:46:05 +0000145CodeGenerator::CodeGenerator(MacroAssembler* masm)
146 : deferred_(8),
Leon Clarke4515c472010-02-03 11:58:03 +0000147 masm_(masm),
Andrei Popescu31002712010-02-23 13:46:05 +0000148 info_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +0000149 frame_(NULL),
150 allocator_(NULL),
151 state_(NULL),
152 loop_nesting_(0),
Steve Block6ded16b2010-05-10 14:33:55 +0100153 in_safe_int32_mode_(false),
154 safe_int32_mode_enabled_(true),
Steve Blocka7e24c12009-10-30 11:49:00 +0000155 function_return_is_shadowed_(false),
156 in_spilled_code_(false) {
157}
158
159
160// Calling conventions:
161// ebp: caller's frame pointer
162// esp: stack pointer
163// edi: called JS function
164// esi: callee's context
165
Andrei Popescu402d9372010-02-26 13:31:12 +0000166void CodeGenerator::Generate(CompilationInfo* info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000167 // Record the position for debugging purposes.
Andrei Popescu31002712010-02-23 13:46:05 +0000168 CodeForFunctionPosition(info->function());
Steve Block6ded16b2010-05-10 14:33:55 +0100169 Comment cmnt(masm_, "[ function compiled by virtual frame code generator");
Steve Blocka7e24c12009-10-30 11:49:00 +0000170
171 // Initialize state.
Andrei Popescu31002712010-02-23 13:46:05 +0000172 info_ = info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000173 ASSERT(allocator_ == NULL);
174 RegisterAllocator register_allocator(this);
175 allocator_ = &register_allocator;
176 ASSERT(frame_ == NULL);
177 frame_ = new VirtualFrame();
178 set_in_spilled_code(false);
179
180 // Adjust for function-level loop nesting.
Steve Block6ded16b2010-05-10 14:33:55 +0100181 ASSERT_EQ(0, loop_nesting_);
182 loop_nesting_ = info->loop_nesting();
Steve Blocka7e24c12009-10-30 11:49:00 +0000183
184 JumpTarget::set_compiling_deferred_code(false);
185
186#ifdef DEBUG
187 if (strlen(FLAG_stop_at) > 0 &&
Andrei Popescu31002712010-02-23 13:46:05 +0000188 info->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000189 frame_->SpillAll();
190 __ int3();
191 }
192#endif
193
194 // New scope to get automatic timing calculation.
Steve Block6ded16b2010-05-10 14:33:55 +0100195 { HistogramTimerScope codegen_timer(&Counters::code_generation);
Steve Blocka7e24c12009-10-30 11:49:00 +0000196 CodeGenState state(this);
197
198 // Entry:
199 // Stack: receiver, arguments, return address.
200 // ebp: caller's frame pointer
201 // esp: stack pointer
202 // edi: called JS function
203 // esi: callee's context
204 allocator_->Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +0000205
Andrei Popescu402d9372010-02-26 13:31:12 +0000206 if (info->mode() == CompilationInfo::PRIMARY) {
Leon Clarke4515c472010-02-03 11:58:03 +0000207 frame_->Enter();
208
209 // Allocate space for locals and initialize them.
210 frame_->AllocateStackSlots();
211
212 // Allocate the local context if needed.
Andrei Popescu31002712010-02-23 13:46:05 +0000213 int heap_slots = scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
Leon Clarke4515c472010-02-03 11:58:03 +0000214 if (heap_slots > 0) {
215 Comment cmnt(masm_, "[ allocate local context");
216 // Allocate local context.
217 // Get outer context and create a new context based on it.
218 frame_->PushFunction();
219 Result context;
220 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
221 FastNewContextStub stub(heap_slots);
222 context = frame_->CallStub(&stub, 1);
223 } else {
224 context = frame_->CallRuntime(Runtime::kNewContext, 1);
225 }
226
227 // Update context local.
228 frame_->SaveContextRegister();
229
230 // Verify that the runtime call result and esi agree.
231 if (FLAG_debug_code) {
232 __ cmp(context.reg(), Operand(esi));
233 __ Assert(equal, "Runtime::NewContext should end up in esi");
234 }
235 }
236
237 // TODO(1241774): Improve this code:
238 // 1) only needed if we have a context
239 // 2) no need to recompute context ptr every single time
240 // 3) don't copy parameter operand code from SlotOperand!
241 {
242 Comment cmnt2(masm_, "[ copy context parameters into .context");
Leon Clarke4515c472010-02-03 11:58:03 +0000243 // Note that iteration order is relevant here! If we have the same
244 // parameter twice (e.g., function (x, y, x)), and that parameter
245 // needs to be copied into the context, it must be the last argument
246 // passed to the parameter that needs to be copied. This is a rare
247 // case so we don't check for it, instead we rely on the copying
248 // order: such a parameter is copied repeatedly into the same
249 // context location and thus the last value is what is seen inside
250 // the function.
Andrei Popescu31002712010-02-23 13:46:05 +0000251 for (int i = 0; i < scope()->num_parameters(); i++) {
252 Variable* par = scope()->parameter(i);
Leon Clarke4515c472010-02-03 11:58:03 +0000253 Slot* slot = par->slot();
254 if (slot != NULL && slot->type() == Slot::CONTEXT) {
255 // The use of SlotOperand below is safe in unspilled code
256 // because the slot is guaranteed to be a context slot.
257 //
258 // There are no parameters in the global scope.
Andrei Popescu31002712010-02-23 13:46:05 +0000259 ASSERT(!scope()->is_global_scope());
Leon Clarke4515c472010-02-03 11:58:03 +0000260 frame_->PushParameterAt(i);
261 Result value = frame_->Pop();
262 value.ToRegister();
263
264 // SlotOperand loads context.reg() with the context object
265 // stored to, used below in RecordWrite.
266 Result context = allocator_->Allocate();
267 ASSERT(context.is_valid());
268 __ mov(SlotOperand(slot, context.reg()), value.reg());
269 int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
270 Result scratch = allocator_->Allocate();
271 ASSERT(scratch.is_valid());
272 frame_->Spill(context.reg());
273 frame_->Spill(value.reg());
274 __ RecordWrite(context.reg(), offset, value.reg(), scratch.reg());
275 }
276 }
277 }
278
279 // Store the arguments object. This must happen after context
280 // initialization because the arguments object may be stored in
281 // the context.
282 if (ArgumentsMode() != NO_ARGUMENTS_ALLOCATION) {
283 StoreArgumentsObject(true);
284 }
285
286 // Initialize ThisFunction reference if present.
Andrei Popescu31002712010-02-23 13:46:05 +0000287 if (scope()->is_function_scope() && scope()->function() != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +0000288 frame_->Push(Factory::the_hole_value());
Andrei Popescu31002712010-02-23 13:46:05 +0000289 StoreToSlot(scope()->function()->slot(), NOT_CONST_INIT);
Leon Clarke4515c472010-02-03 11:58:03 +0000290 }
291 } else {
292 // When used as the secondary compiler for splitting, ebp, esi,
293 // and edi have been pushed on the stack. Adjust the virtual
294 // frame to match this state.
295 frame_->Adjust(3);
296 allocator_->Unuse(edi);
Andrei Popescu402d9372010-02-26 13:31:12 +0000297
298 // Bind all the bailout labels to the beginning of the function.
299 List<CompilationInfo::Bailout*>* bailouts = info->bailouts();
300 for (int i = 0; i < bailouts->length(); i++) {
301 __ bind(bailouts->at(i)->label());
302 }
Leon Clarke4515c472010-02-03 11:58:03 +0000303 }
304
Steve Blocka7e24c12009-10-30 11:49:00 +0000305 // Initialize the function return target after the locals are set
306 // up, because it needs the expected frame height from the frame.
307 function_return_.set_direction(JumpTarget::BIDIRECTIONAL);
308 function_return_is_shadowed_ = false;
309
Steve Blocka7e24c12009-10-30 11:49:00 +0000310 // Generate code to 'execute' declarations and initialize functions
311 // (source elements). In case of an illegal redeclaration we need to
312 // handle that instead of processing the declarations.
Andrei Popescu31002712010-02-23 13:46:05 +0000313 if (scope()->HasIllegalRedeclaration()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000314 Comment cmnt(masm_, "[ illegal redeclarations");
Andrei Popescu31002712010-02-23 13:46:05 +0000315 scope()->VisitIllegalRedeclaration(this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 } else {
317 Comment cmnt(masm_, "[ declarations");
Andrei Popescu31002712010-02-23 13:46:05 +0000318 ProcessDeclarations(scope()->declarations());
Steve Blocka7e24c12009-10-30 11:49:00 +0000319 // Bail out if a stack-overflow exception occurred when processing
320 // declarations.
321 if (HasStackOverflow()) return;
322 }
323
324 if (FLAG_trace) {
325 frame_->CallRuntime(Runtime::kTraceEnter, 0);
326 // Ignore the return value.
327 }
328 CheckStack();
329
330 // Compile the body of the function in a vanilla state. Don't
331 // bother compiling all the code if the scope has an illegal
332 // redeclaration.
Andrei Popescu31002712010-02-23 13:46:05 +0000333 if (!scope()->HasIllegalRedeclaration()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000334 Comment cmnt(masm_, "[ function body");
335#ifdef DEBUG
336 bool is_builtin = Bootstrapper::IsActive();
337 bool should_trace =
338 is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
339 if (should_trace) {
340 frame_->CallRuntime(Runtime::kDebugTrace, 0);
341 // Ignore the return value.
342 }
343#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000344 VisitStatements(info->function()->body());
Steve Blocka7e24c12009-10-30 11:49:00 +0000345
346 // Handle the return from the function.
347 if (has_valid_frame()) {
348 // If there is a valid frame, control flow can fall off the end of
349 // the body. In that case there is an implicit return statement.
350 ASSERT(!function_return_is_shadowed_);
Andrei Popescu31002712010-02-23 13:46:05 +0000351 CodeForReturnPosition(info->function());
Steve Blocka7e24c12009-10-30 11:49:00 +0000352 frame_->PrepareForReturn();
353 Result undefined(Factory::undefined_value());
354 if (function_return_.is_bound()) {
355 function_return_.Jump(&undefined);
356 } else {
357 function_return_.Bind(&undefined);
358 GenerateReturnSequence(&undefined);
359 }
360 } else if (function_return_.is_linked()) {
361 // If the return target has dangling jumps to it, then we have not
362 // yet generated the return sequence. This can happen when (a)
363 // control does not flow off the end of the body so we did not
364 // compile an artificial return statement just above, and (b) there
365 // are return statements in the body but (c) they are all shadowed.
366 Result return_value;
367 function_return_.Bind(&return_value);
368 GenerateReturnSequence(&return_value);
369 }
370 }
371 }
372
373 // Adjust for function-level loop nesting.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100374 ASSERT_EQ(loop_nesting_, info->loop_nesting());
Steve Block6ded16b2010-05-10 14:33:55 +0100375 loop_nesting_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000376
377 // Code generation state must be reset.
378 ASSERT(state_ == NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000379 ASSERT(!function_return_is_shadowed_);
380 function_return_.Unuse();
381 DeleteFrame();
382
383 // Process any deferred code using the register allocator.
384 if (!HasStackOverflow()) {
385 HistogramTimerScope deferred_timer(&Counters::deferred_code_generation);
386 JumpTarget::set_compiling_deferred_code(true);
387 ProcessDeferred();
388 JumpTarget::set_compiling_deferred_code(false);
389 }
390
391 // There is no need to delete the register allocator, it is a
392 // stack-allocated local.
393 allocator_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000394}
395
396
397Operand CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
398 // Currently, this assertion will fail if we try to assign to
399 // a constant variable that is constant because it is read-only
400 // (such as the variable referring to a named function expression).
401 // We need to implement assignments to read-only variables.
402 // Ideally, we should do this during AST generation (by converting
403 // such assignments into expression statements); however, in general
404 // we may not be able to make the decision until past AST generation,
405 // that is when the entire program is known.
406 ASSERT(slot != NULL);
407 int index = slot->index();
408 switch (slot->type()) {
409 case Slot::PARAMETER:
410 return frame_->ParameterAt(index);
411
412 case Slot::LOCAL:
413 return frame_->LocalAt(index);
414
415 case Slot::CONTEXT: {
416 // Follow the context chain if necessary.
417 ASSERT(!tmp.is(esi)); // do not overwrite context register
418 Register context = esi;
419 int chain_length = scope()->ContextChainLength(slot->var()->scope());
420 for (int i = 0; i < chain_length; i++) {
421 // Load the closure.
422 // (All contexts, even 'with' contexts, have a closure,
423 // and it is the same for all contexts inside a function.
424 // There is no need to go to the function context first.)
425 __ mov(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
426 // Load the function context (which is the incoming, outer context).
427 __ mov(tmp, FieldOperand(tmp, JSFunction::kContextOffset));
428 context = tmp;
429 }
430 // We may have a 'with' context now. Get the function context.
431 // (In fact this mov may never be the needed, since the scope analysis
432 // may not permit a direct context access in this case and thus we are
433 // always at a function context. However it is safe to dereference be-
434 // cause the function context of a function context is itself. Before
435 // deleting this mov we should try to create a counter-example first,
436 // though...)
437 __ mov(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
438 return ContextOperand(tmp, index);
439 }
440
441 default:
442 UNREACHABLE();
443 return Operand(eax);
444 }
445}
446
447
448Operand CodeGenerator::ContextSlotOperandCheckExtensions(Slot* slot,
449 Result tmp,
450 JumpTarget* slow) {
451 ASSERT(slot->type() == Slot::CONTEXT);
452 ASSERT(tmp.is_register());
453 Register context = esi;
454
455 for (Scope* s = scope(); s != slot->var()->scope(); s = s->outer_scope()) {
456 if (s->num_heap_slots() > 0) {
457 if (s->calls_eval()) {
458 // Check that extension is NULL.
459 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
460 Immediate(0));
461 slow->Branch(not_equal, not_taken);
462 }
463 __ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
464 __ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
465 context = tmp.reg();
466 }
467 }
468 // Check that last extension is NULL.
469 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
470 slow->Branch(not_equal, not_taken);
471 __ mov(tmp.reg(), ContextOperand(context, Context::FCONTEXT_INDEX));
472 return ContextOperand(tmp.reg(), slot->index());
473}
474
475
476// Emit code to load the value of an expression to the top of the
477// frame. If the expression is boolean-valued it may be compiled (or
478// partially compiled) into control flow to the control destination.
479// If force_control is true, control flow is forced.
Steve Block6ded16b2010-05-10 14:33:55 +0100480void CodeGenerator::LoadCondition(Expression* expr,
Steve Blocka7e24c12009-10-30 11:49:00 +0000481 ControlDestination* dest,
482 bool force_control) {
483 ASSERT(!in_spilled_code());
484 int original_height = frame_->height();
485
Steve Blockd0582a62009-12-15 09:54:21 +0000486 { CodeGenState new_state(this, dest);
Steve Block6ded16b2010-05-10 14:33:55 +0100487 Visit(expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000488
489 // If we hit a stack overflow, we may not have actually visited
490 // the expression. In that case, we ensure that we have a
491 // valid-looking frame state because we will continue to generate
492 // code as we unwind the C++ stack.
493 //
494 // It's possible to have both a stack overflow and a valid frame
495 // state (eg, a subexpression overflowed, visiting it returned
496 // with a dummied frame state, and visiting this expression
497 // returned with a normal-looking state).
498 if (HasStackOverflow() &&
499 !dest->is_used() &&
500 frame_->height() == original_height) {
501 dest->Goto(true);
502 }
503 }
504
505 if (force_control && !dest->is_used()) {
506 // Convert the TOS value into flow to the control destination.
507 ToBoolean(dest);
508 }
509
510 ASSERT(!(force_control && !dest->is_used()));
511 ASSERT(dest->is_used() || frame_->height() == original_height + 1);
512}
513
514
Steve Blockd0582a62009-12-15 09:54:21 +0000515void CodeGenerator::LoadAndSpill(Expression* expression) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000516 ASSERT(in_spilled_code());
517 set_in_spilled_code(false);
Steve Blockd0582a62009-12-15 09:54:21 +0000518 Load(expression);
Steve Blocka7e24c12009-10-30 11:49:00 +0000519 frame_->SpillAll();
520 set_in_spilled_code(true);
521}
522
523
Steve Block6ded16b2010-05-10 14:33:55 +0100524void CodeGenerator::LoadInSafeInt32Mode(Expression* expr,
525 BreakTarget* unsafe_bailout) {
526 set_unsafe_bailout(unsafe_bailout);
527 set_in_safe_int32_mode(true);
528 Load(expr);
529 Result value = frame_->Pop();
530 ASSERT(frame_->HasNoUntaggedInt32Elements());
531 if (expr->GuaranteedSmiResult()) {
532 ConvertInt32ResultToSmi(&value);
533 } else {
534 ConvertInt32ResultToNumber(&value);
535 }
536 set_in_safe_int32_mode(false);
537 set_unsafe_bailout(NULL);
538 frame_->Push(&value);
539}
540
541
542void CodeGenerator::LoadWithSafeInt32ModeDisabled(Expression* expr) {
543 set_safe_int32_mode_enabled(false);
544 Load(expr);
545 set_safe_int32_mode_enabled(true);
546}
547
548
549void CodeGenerator::ConvertInt32ResultToSmi(Result* value) {
550 ASSERT(value->is_untagged_int32());
551 if (value->is_register()) {
552 __ add(value->reg(), Operand(value->reg()));
553 } else {
554 ASSERT(value->is_constant());
555 ASSERT(value->handle()->IsSmi());
556 }
557 value->set_untagged_int32(false);
558 value->set_type_info(TypeInfo::Smi());
559}
560
561
562void CodeGenerator::ConvertInt32ResultToNumber(Result* value) {
563 ASSERT(value->is_untagged_int32());
564 if (value->is_register()) {
565 Register val = value->reg();
566 JumpTarget done;
567 __ add(val, Operand(val));
568 done.Branch(no_overflow, value);
569 __ sar(val, 1);
570 // If there was an overflow, bits 30 and 31 of the original number disagree.
571 __ xor_(val, 0x80000000u);
572 if (CpuFeatures::IsSupported(SSE2)) {
573 CpuFeatures::Scope fscope(SSE2);
574 __ cvtsi2sd(xmm0, Operand(val));
575 } else {
576 // Move val to ST[0] in the FPU
577 // Push and pop are safe with respect to the virtual frame because
578 // all synced elements are below the actual stack pointer.
579 __ push(val);
580 __ fild_s(Operand(esp, 0));
581 __ pop(val);
582 }
583 Result scratch = allocator_->Allocate();
584 ASSERT(scratch.is_register());
585 Label allocation_failed;
586 __ AllocateHeapNumber(val, scratch.reg(),
587 no_reg, &allocation_failed);
588 VirtualFrame* clone = new VirtualFrame(frame_);
589 scratch.Unuse();
590 if (CpuFeatures::IsSupported(SSE2)) {
591 CpuFeatures::Scope fscope(SSE2);
592 __ movdbl(FieldOperand(val, HeapNumber::kValueOffset), xmm0);
593 } else {
594 __ fstp_d(FieldOperand(val, HeapNumber::kValueOffset));
595 }
596 done.Jump(value);
597
598 // Establish the virtual frame, cloned from where AllocateHeapNumber
599 // jumped to allocation_failed.
600 RegisterFile empty_regs;
601 SetFrame(clone, &empty_regs);
602 __ bind(&allocation_failed);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100603 if (!CpuFeatures::IsSupported(SSE2)) {
604 // Pop the value from the floating point stack.
605 __ fstp(0);
606 }
Steve Block6ded16b2010-05-10 14:33:55 +0100607 unsafe_bailout_->Jump();
608
609 done.Bind(value);
610 } else {
611 ASSERT(value->is_constant());
612 }
613 value->set_untagged_int32(false);
614 value->set_type_info(TypeInfo::Integer32());
615}
616
617
Steve Blockd0582a62009-12-15 09:54:21 +0000618void CodeGenerator::Load(Expression* expr) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000619#ifdef DEBUG
620 int original_height = frame_->height();
621#endif
622 ASSERT(!in_spilled_code());
Steve Blocka7e24c12009-10-30 11:49:00 +0000623
Steve Block6ded16b2010-05-10 14:33:55 +0100624 // If the expression should be a side-effect-free 32-bit int computation,
625 // compile that SafeInt32 path, and a bailout path.
626 if (!in_safe_int32_mode() &&
627 safe_int32_mode_enabled() &&
628 expr->side_effect_free() &&
629 expr->num_bit_ops() > 2 &&
630 CpuFeatures::IsSupported(SSE2)) {
631 BreakTarget unsafe_bailout;
632 JumpTarget done;
633 unsafe_bailout.set_expected_height(frame_->height());
634 LoadInSafeInt32Mode(expr, &unsafe_bailout);
635 done.Jump();
636
637 if (unsafe_bailout.is_linked()) {
638 unsafe_bailout.Bind();
639 LoadWithSafeInt32ModeDisabled(expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000640 }
Steve Block6ded16b2010-05-10 14:33:55 +0100641 done.Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +0000642 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100643 JumpTarget true_target;
644 JumpTarget false_target;
Steve Block6ded16b2010-05-10 14:33:55 +0100645 ControlDestination dest(&true_target, &false_target, true);
646 LoadCondition(expr, &dest, false);
647
648 if (dest.false_was_fall_through()) {
649 // The false target was just bound.
Steve Blocka7e24c12009-10-30 11:49:00 +0000650 JumpTarget loaded;
Steve Block6ded16b2010-05-10 14:33:55 +0100651 frame_->Push(Factory::false_value());
652 // There may be dangling jumps to the true target.
Steve Blocka7e24c12009-10-30 11:49:00 +0000653 if (true_target.is_linked()) {
Steve Block6ded16b2010-05-10 14:33:55 +0100654 loaded.Jump();
Steve Blocka7e24c12009-10-30 11:49:00 +0000655 true_target.Bind();
656 frame_->Push(Factory::true_value());
Steve Block6ded16b2010-05-10 14:33:55 +0100657 loaded.Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +0000658 }
Steve Block6ded16b2010-05-10 14:33:55 +0100659
660 } else if (dest.is_used()) {
661 // There is true, and possibly false, control flow (with true as
662 // the fall through).
663 JumpTarget loaded;
664 frame_->Push(Factory::true_value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000665 if (false_target.is_linked()) {
Steve Block6ded16b2010-05-10 14:33:55 +0100666 loaded.Jump();
Steve Blocka7e24c12009-10-30 11:49:00 +0000667 false_target.Bind();
668 frame_->Push(Factory::false_value());
Steve Block6ded16b2010-05-10 14:33:55 +0100669 loaded.Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +0000670 }
Steve Block6ded16b2010-05-10 14:33:55 +0100671
672 } else {
673 // We have a valid value on top of the frame, but we still may
674 // have dangling jumps to the true and false targets from nested
675 // subexpressions (eg, the left subexpressions of the
676 // short-circuited boolean operators).
677 ASSERT(has_valid_frame());
678 if (true_target.is_linked() || false_target.is_linked()) {
679 JumpTarget loaded;
680 loaded.Jump(); // Don't lose the current TOS.
681 if (true_target.is_linked()) {
682 true_target.Bind();
683 frame_->Push(Factory::true_value());
684 if (false_target.is_linked()) {
685 loaded.Jump();
686 }
687 }
688 if (false_target.is_linked()) {
689 false_target.Bind();
690 frame_->Push(Factory::false_value());
691 }
692 loaded.Bind();
693 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000694 }
695 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000696 ASSERT(has_valid_frame());
697 ASSERT(frame_->height() == original_height + 1);
698}
699
700
701void CodeGenerator::LoadGlobal() {
702 if (in_spilled_code()) {
703 frame_->EmitPush(GlobalObject());
704 } else {
705 Result temp = allocator_->Allocate();
706 __ mov(temp.reg(), GlobalObject());
707 frame_->Push(&temp);
708 }
709}
710
711
712void CodeGenerator::LoadGlobalReceiver() {
713 Result temp = allocator_->Allocate();
714 Register reg = temp.reg();
715 __ mov(reg, GlobalObject());
716 __ mov(reg, FieldOperand(reg, GlobalObject::kGlobalReceiverOffset));
717 frame_->Push(&temp);
718}
719
720
Steve Blockd0582a62009-12-15 09:54:21 +0000721void CodeGenerator::LoadTypeofExpression(Expression* expr) {
722 // Special handling of identifiers as subexpressions of typeof.
723 Variable* variable = expr->AsVariableProxy()->AsVariable();
Steve Blocka7e24c12009-10-30 11:49:00 +0000724 if (variable != NULL && !variable->is_this() && variable->is_global()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000725 // For a global variable we build the property reference
726 // <global>.<variable> and perform a (regular non-contextual) property
727 // load to make sure we do not get reference errors.
Steve Blocka7e24c12009-10-30 11:49:00 +0000728 Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
729 Literal key(variable->name());
Steve Blocka7e24c12009-10-30 11:49:00 +0000730 Property property(&global, &key, RelocInfo::kNoPosition);
Steve Blockd0582a62009-12-15 09:54:21 +0000731 Reference ref(this, &property);
732 ref.GetValue();
733 } else if (variable != NULL && variable->slot() != NULL) {
734 // For a variable that rewrites to a slot, we signal it is the immediate
735 // subexpression of a typeof.
Leon Clarkef7060e22010-06-03 12:02:55 +0100736 LoadFromSlotCheckForArguments(variable->slot(), INSIDE_TYPEOF);
Steve Blocka7e24c12009-10-30 11:49:00 +0000737 } else {
Steve Blockd0582a62009-12-15 09:54:21 +0000738 // Anything else can be handled normally.
739 Load(expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000740 }
741}
742
743
Andrei Popescu31002712010-02-23 13:46:05 +0000744ArgumentsAllocationMode CodeGenerator::ArgumentsMode() {
745 if (scope()->arguments() == NULL) return NO_ARGUMENTS_ALLOCATION;
746 ASSERT(scope()->arguments_shadow() != NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000747 // We don't want to do lazy arguments allocation for functions that
748 // have heap-allocated contexts, because it interfers with the
749 // uninitialized const tracking in the context objects.
Andrei Popescu31002712010-02-23 13:46:05 +0000750 return (scope()->num_heap_slots() > 0)
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 ? EAGER_ARGUMENTS_ALLOCATION
752 : LAZY_ARGUMENTS_ALLOCATION;
753}
754
755
756Result CodeGenerator::StoreArgumentsObject(bool initial) {
757 ArgumentsAllocationMode mode = ArgumentsMode();
758 ASSERT(mode != NO_ARGUMENTS_ALLOCATION);
759
760 Comment cmnt(masm_, "[ store arguments object");
761 if (mode == LAZY_ARGUMENTS_ALLOCATION && initial) {
762 // When using lazy arguments allocation, we store the hole value
763 // as a sentinel indicating that the arguments object hasn't been
764 // allocated yet.
765 frame_->Push(Factory::the_hole_value());
766 } else {
767 ArgumentsAccessStub stub(ArgumentsAccessStub::NEW_OBJECT);
768 frame_->PushFunction();
769 frame_->PushReceiverSlotAddress();
Andrei Popescu31002712010-02-23 13:46:05 +0000770 frame_->Push(Smi::FromInt(scope()->num_parameters()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000771 Result result = frame_->CallStub(&stub, 3);
772 frame_->Push(&result);
773 }
774
Andrei Popescu31002712010-02-23 13:46:05 +0000775 Variable* arguments = scope()->arguments()->var();
776 Variable* shadow = scope()->arguments_shadow()->var();
Leon Clarkee46be812010-01-19 14:06:41 +0000777 ASSERT(arguments != NULL && arguments->slot() != NULL);
778 ASSERT(shadow != NULL && shadow->slot() != NULL);
779 JumpTarget done;
780 bool skip_arguments = false;
781 if (mode == LAZY_ARGUMENTS_ALLOCATION && !initial) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100782 // We have to skip storing into the arguments slot if it has
783 // already been written to. This can happen if the a function
784 // has a local variable named 'arguments'.
Leon Clarkef7060e22010-06-03 12:02:55 +0100785 LoadFromSlot(arguments->slot(), NOT_INSIDE_TYPEOF);
786 Result probe = frame_->Pop();
Leon Clarkee46be812010-01-19 14:06:41 +0000787 if (probe.is_constant()) {
788 // We have to skip updating the arguments object if it has
789 // been assigned a proper value.
790 skip_arguments = !probe.handle()->IsTheHole();
791 } else {
792 __ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
793 probe.Unuse();
794 done.Branch(not_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +0000795 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000796 }
Leon Clarkee46be812010-01-19 14:06:41 +0000797 if (!skip_arguments) {
798 StoreToSlot(arguments->slot(), NOT_CONST_INIT);
799 if (mode == LAZY_ARGUMENTS_ALLOCATION) done.Bind();
800 }
801 StoreToSlot(shadow->slot(), NOT_CONST_INIT);
Steve Blocka7e24c12009-10-30 11:49:00 +0000802 return frame_->Pop();
803}
804
Leon Clarked91b9f72010-01-27 17:25:45 +0000805//------------------------------------------------------------------------------
806// CodeGenerator implementation of variables, lookups, and stores.
Steve Blocka7e24c12009-10-30 11:49:00 +0000807
Leon Clarked91b9f72010-01-27 17:25:45 +0000808Reference::Reference(CodeGenerator* cgen,
809 Expression* expression,
810 bool persist_after_get)
811 : cgen_(cgen),
812 expression_(expression),
813 type_(ILLEGAL),
814 persist_after_get_(persist_after_get) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000815 cgen->LoadReference(this);
816}
817
818
819Reference::~Reference() {
Leon Clarked91b9f72010-01-27 17:25:45 +0000820 ASSERT(is_unloaded() || is_illegal());
Steve Blocka7e24c12009-10-30 11:49:00 +0000821}
822
823
824void CodeGenerator::LoadReference(Reference* ref) {
825 // References are loaded from both spilled and unspilled code. Set the
826 // state to unspilled to allow that (and explicitly spill after
827 // construction at the construction sites).
828 bool was_in_spilled_code = in_spilled_code_;
829 in_spilled_code_ = false;
830
831 Comment cmnt(masm_, "[ LoadReference");
832 Expression* e = ref->expression();
833 Property* property = e->AsProperty();
834 Variable* var = e->AsVariableProxy()->AsVariable();
835
836 if (property != NULL) {
837 // The expression is either a property or a variable proxy that rewrites
838 // to a property.
839 Load(property->obj());
Leon Clarkee46be812010-01-19 14:06:41 +0000840 if (property->key()->IsPropertyName()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000841 ref->set_type(Reference::NAMED);
842 } else {
843 Load(property->key());
844 ref->set_type(Reference::KEYED);
845 }
846 } else if (var != NULL) {
847 // The expression is a variable proxy that does not rewrite to a
848 // property. Global variables are treated as named property references.
849 if (var->is_global()) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000850 // If eax is free, the register allocator prefers it. Thus the code
851 // generator will load the global object into eax, which is where
852 // LoadIC wants it. Most uses of Reference call LoadIC directly
853 // after the reference is created.
854 frame_->Spill(eax);
Steve Blocka7e24c12009-10-30 11:49:00 +0000855 LoadGlobal();
856 ref->set_type(Reference::NAMED);
857 } else {
858 ASSERT(var->slot() != NULL);
859 ref->set_type(Reference::SLOT);
860 }
861 } else {
862 // Anything else is a runtime error.
863 Load(e);
864 frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
865 }
866
867 in_spilled_code_ = was_in_spilled_code;
868}
869
870
Steve Blocka7e24c12009-10-30 11:49:00 +0000871// ECMA-262, section 9.2, page 30: ToBoolean(). Pop the top of stack and
872// convert it to a boolean in the condition code register or jump to
873// 'false_target'/'true_target' as appropriate.
874void CodeGenerator::ToBoolean(ControlDestination* dest) {
875 Comment cmnt(masm_, "[ ToBoolean");
876
877 // The value to convert should be popped from the frame.
878 Result value = frame_->Pop();
879 value.ToRegister();
Steve Blocka7e24c12009-10-30 11:49:00 +0000880
Steve Block6ded16b2010-05-10 14:33:55 +0100881 if (value.is_integer32()) { // Also takes Smi case.
882 Comment cmnt(masm_, "ONLY_INTEGER_32");
Andrei Popescu402d9372010-02-26 13:31:12 +0000883 if (FLAG_debug_code) {
Steve Block6ded16b2010-05-10 14:33:55 +0100884 Label ok;
885 __ AbortIfNotNumber(value.reg());
886 __ test(value.reg(), Immediate(kSmiTagMask));
887 __ j(zero, &ok);
888 __ fldz();
889 __ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
890 __ FCmp();
891 __ j(not_zero, &ok);
892 __ Abort("Smi was wrapped in HeapNumber in output from bitop");
893 __ bind(&ok);
894 }
895 // In the integer32 case there are no Smis hidden in heap numbers, so we
896 // need only test for Smi zero.
897 __ test(value.reg(), Operand(value.reg()));
898 dest->false_target()->Branch(zero);
899 value.Unuse();
900 dest->Split(not_zero);
901 } else if (value.is_number()) {
902 Comment cmnt(masm_, "ONLY_NUMBER");
903 // Fast case if TypeInfo indicates only numbers.
904 if (FLAG_debug_code) {
905 __ AbortIfNotNumber(value.reg());
Andrei Popescu402d9372010-02-26 13:31:12 +0000906 }
907 // Smi => false iff zero.
908 ASSERT(kSmiTag == 0);
909 __ test(value.reg(), Operand(value.reg()));
910 dest->false_target()->Branch(zero);
911 __ test(value.reg(), Immediate(kSmiTagMask));
912 dest->true_target()->Branch(zero);
913 __ fldz();
914 __ fld_d(FieldOperand(value.reg(), HeapNumber::kValueOffset));
915 __ FCmp();
916 value.Unuse();
917 dest->Split(not_zero);
918 } else {
919 // Fast case checks.
920 // 'false' => false.
921 __ cmp(value.reg(), Factory::false_value());
922 dest->false_target()->Branch(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +0000923
Andrei Popescu402d9372010-02-26 13:31:12 +0000924 // 'true' => true.
925 __ cmp(value.reg(), Factory::true_value());
926 dest->true_target()->Branch(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +0000927
Andrei Popescu402d9372010-02-26 13:31:12 +0000928 // 'undefined' => false.
929 __ cmp(value.reg(), Factory::undefined_value());
930 dest->false_target()->Branch(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +0000931
Andrei Popescu402d9372010-02-26 13:31:12 +0000932 // Smi => false iff zero.
933 ASSERT(kSmiTag == 0);
934 __ test(value.reg(), Operand(value.reg()));
935 dest->false_target()->Branch(zero);
936 __ test(value.reg(), Immediate(kSmiTagMask));
937 dest->true_target()->Branch(zero);
Steve Blocka7e24c12009-10-30 11:49:00 +0000938
Andrei Popescu402d9372010-02-26 13:31:12 +0000939 // Call the stub for all other cases.
940 frame_->Push(&value); // Undo the Pop() from above.
941 ToBooleanStub stub;
942 Result temp = frame_->CallStub(&stub, 1);
943 // Convert the result to a condition code.
944 __ test(temp.reg(), Operand(temp.reg()));
945 temp.Unuse();
946 dest->Split(not_equal);
947 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000948}
949
950
951class FloatingPointHelper : public AllStatic {
952 public:
Leon Clarked91b9f72010-01-27 17:25:45 +0000953
954 enum ArgLocation {
955 ARGS_ON_STACK,
956 ARGS_IN_REGISTERS
957 };
958
Steve Blocka7e24c12009-10-30 11:49:00 +0000959 // Code pattern for loading a floating point value. Input value must
960 // be either a smi or a heap number object (fp value). Requirements:
961 // operand in register number. Returns operand as floating point number
962 // on FPU stack.
963 static void LoadFloatOperand(MacroAssembler* masm, Register number);
Steve Block6ded16b2010-05-10 14:33:55 +0100964
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 // Code pattern for loading floating point values. Input values must
966 // be either smi or heap number objects (fp values). Requirements:
Leon Clarked91b9f72010-01-27 17:25:45 +0000967 // operand_1 on TOS+1 or in edx, operand_2 on TOS+2 or in eax.
968 // Returns operands as floating point numbers on FPU stack.
969 static void LoadFloatOperands(MacroAssembler* masm,
970 Register scratch,
971 ArgLocation arg_location = ARGS_ON_STACK);
972
973 // Similar to LoadFloatOperand but assumes that both operands are smis.
974 // Expects operands in edx, eax.
975 static void LoadFloatSmis(MacroAssembler* masm, Register scratch);
976
Steve Blocka7e24c12009-10-30 11:49:00 +0000977 // Test if operands are smi or number objects (fp). Requirements:
978 // operand_1 in eax, operand_2 in edx; falls through on float
979 // operands, jumps to the non_float label otherwise.
980 static void CheckFloatOperands(MacroAssembler* masm,
981 Label* non_float,
982 Register scratch);
Steve Block6ded16b2010-05-10 14:33:55 +0100983
Leon Clarkee46be812010-01-19 14:06:41 +0000984 // Takes the operands in edx and eax and loads them as integers in eax
985 // and ecx.
986 static void LoadAsIntegers(MacroAssembler* masm,
Steve Block6ded16b2010-05-10 14:33:55 +0100987 TypeInfo type_info,
Leon Clarkee46be812010-01-19 14:06:41 +0000988 bool use_sse3,
989 Label* operand_conversion_failure);
Steve Block6ded16b2010-05-10 14:33:55 +0100990 static void LoadNumbersAsIntegers(MacroAssembler* masm,
991 TypeInfo type_info,
992 bool use_sse3,
993 Label* operand_conversion_failure);
994 static void LoadUnknownsAsIntegers(MacroAssembler* masm,
995 bool use_sse3,
996 Label* operand_conversion_failure);
997
Andrei Popescu402d9372010-02-26 13:31:12 +0000998 // Test if operands are smis or heap numbers and load them
999 // into xmm0 and xmm1 if they are. Operands are in edx and eax.
1000 // Leaves operands unchanged.
1001 static void LoadSSE2Operands(MacroAssembler* masm);
Steve Block6ded16b2010-05-10 14:33:55 +01001002
Steve Blocka7e24c12009-10-30 11:49:00 +00001003 // Test if operands are numbers (smi or HeapNumber objects), and load
1004 // them into xmm0 and xmm1 if they are. Jump to label not_numbers if
1005 // either operand is not a number. Operands are in edx and eax.
1006 // Leaves operands unchanged.
Leon Clarked91b9f72010-01-27 17:25:45 +00001007 static void LoadSSE2Operands(MacroAssembler* masm, Label* not_numbers);
1008
1009 // Similar to LoadSSE2Operands but assumes that both operands are smis.
1010 // Expects operands in edx, eax.
1011 static void LoadSSE2Smis(MacroAssembler* masm, Register scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +00001012};
1013
1014
1015const char* GenericBinaryOpStub::GetName() {
Leon Clarkee46be812010-01-19 14:06:41 +00001016 if (name_ != NULL) return name_;
1017 const int kMaxNameLength = 100;
1018 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
1019 if (name_ == NULL) return "OOM";
1020 const char* op_name = Token::Name(op_);
1021 const char* overwrite_name;
1022 switch (mode_) {
1023 case NO_OVERWRITE: overwrite_name = "Alloc"; break;
1024 case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break;
1025 case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break;
1026 default: overwrite_name = "UnknownOverwrite"; break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001027 }
Leon Clarkee46be812010-01-19 14:06:41 +00001028
1029 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
Steve Block6ded16b2010-05-10 14:33:55 +01001030 "GenericBinaryOpStub_%s_%s%s_%s%s_%s_%s",
Leon Clarkee46be812010-01-19 14:06:41 +00001031 op_name,
1032 overwrite_name,
1033 (flags_ & NO_SMI_CODE_IN_STUB) ? "_NoSmiInStub" : "",
1034 args_in_registers_ ? "RegArgs" : "StackArgs",
Andrei Popescu402d9372010-02-26 13:31:12 +00001035 args_reversed_ ? "_R" : "",
Steve Block6ded16b2010-05-10 14:33:55 +01001036 static_operands_type_.ToString(),
1037 BinaryOpIC::GetName(runtime_operands_type_));
Leon Clarkee46be812010-01-19 14:06:41 +00001038 return name_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001039}
1040
1041
1042// Call the specialized stub for a binary operation.
1043class DeferredInlineBinaryOperation: public DeferredCode {
1044 public:
1045 DeferredInlineBinaryOperation(Token::Value op,
1046 Register dst,
1047 Register left,
1048 Register right,
Steve Block6ded16b2010-05-10 14:33:55 +01001049 TypeInfo left_info,
1050 TypeInfo right_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001051 OverwriteMode mode)
Steve Block6ded16b2010-05-10 14:33:55 +01001052 : op_(op), dst_(dst), left_(left), right_(right),
1053 left_info_(left_info), right_info_(right_info), mode_(mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001054 set_comment("[ DeferredInlineBinaryOperation");
1055 }
1056
1057 virtual void Generate();
1058
1059 private:
1060 Token::Value op_;
1061 Register dst_;
1062 Register left_;
1063 Register right_;
Steve Block6ded16b2010-05-10 14:33:55 +01001064 TypeInfo left_info_;
1065 TypeInfo right_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001066 OverwriteMode mode_;
1067};
1068
1069
1070void DeferredInlineBinaryOperation::Generate() {
Leon Clarkee46be812010-01-19 14:06:41 +00001071 Label done;
1072 if (CpuFeatures::IsSupported(SSE2) && ((op_ == Token::ADD) ||
1073 (op_ ==Token::SUB) ||
1074 (op_ == Token::MUL) ||
1075 (op_ == Token::DIV))) {
1076 CpuFeatures::Scope use_sse2(SSE2);
1077 Label call_runtime, after_alloc_failure;
1078 Label left_smi, right_smi, load_right, do_op;
Steve Block6ded16b2010-05-10 14:33:55 +01001079 if (!left_info_.IsSmi()) {
1080 __ test(left_, Immediate(kSmiTagMask));
1081 __ j(zero, &left_smi);
1082 if (!left_info_.IsNumber()) {
1083 __ cmp(FieldOperand(left_, HeapObject::kMapOffset),
1084 Factory::heap_number_map());
1085 __ j(not_equal, &call_runtime);
1086 }
1087 __ movdbl(xmm0, FieldOperand(left_, HeapNumber::kValueOffset));
1088 if (mode_ == OVERWRITE_LEFT) {
1089 __ mov(dst_, left_);
1090 }
1091 __ jmp(&load_right);
Leon Clarkee46be812010-01-19 14:06:41 +00001092
Steve Block6ded16b2010-05-10 14:33:55 +01001093 __ bind(&left_smi);
1094 } else {
1095 if (FLAG_debug_code) __ AbortIfNotSmi(left_);
1096 }
Leon Clarkee46be812010-01-19 14:06:41 +00001097 __ SmiUntag(left_);
1098 __ cvtsi2sd(xmm0, Operand(left_));
1099 __ SmiTag(left_);
1100 if (mode_ == OVERWRITE_LEFT) {
1101 Label alloc_failure;
1102 __ push(left_);
1103 __ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
1104 __ pop(left_);
1105 }
1106
1107 __ bind(&load_right);
Steve Block6ded16b2010-05-10 14:33:55 +01001108 if (!right_info_.IsSmi()) {
1109 __ test(right_, Immediate(kSmiTagMask));
1110 __ j(zero, &right_smi);
1111 if (!right_info_.IsNumber()) {
1112 __ cmp(FieldOperand(right_, HeapObject::kMapOffset),
1113 Factory::heap_number_map());
1114 __ j(not_equal, &call_runtime);
1115 }
1116 __ movdbl(xmm1, FieldOperand(right_, HeapNumber::kValueOffset));
1117 if (mode_ == OVERWRITE_RIGHT) {
1118 __ mov(dst_, right_);
1119 } else if (mode_ == NO_OVERWRITE) {
1120 Label alloc_failure;
1121 __ push(left_);
1122 __ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
1123 __ pop(left_);
1124 }
1125 __ jmp(&do_op);
Leon Clarkee46be812010-01-19 14:06:41 +00001126
Steve Block6ded16b2010-05-10 14:33:55 +01001127 __ bind(&right_smi);
1128 } else {
1129 if (FLAG_debug_code) __ AbortIfNotSmi(right_);
1130 }
Leon Clarkee46be812010-01-19 14:06:41 +00001131 __ SmiUntag(right_);
1132 __ cvtsi2sd(xmm1, Operand(right_));
1133 __ SmiTag(right_);
1134 if (mode_ == OVERWRITE_RIGHT || mode_ == NO_OVERWRITE) {
1135 Label alloc_failure;
1136 __ push(left_);
1137 __ AllocateHeapNumber(dst_, left_, no_reg, &after_alloc_failure);
1138 __ pop(left_);
1139 }
1140
1141 __ bind(&do_op);
1142 switch (op_) {
1143 case Token::ADD: __ addsd(xmm0, xmm1); break;
1144 case Token::SUB: __ subsd(xmm0, xmm1); break;
1145 case Token::MUL: __ mulsd(xmm0, xmm1); break;
1146 case Token::DIV: __ divsd(xmm0, xmm1); break;
1147 default: UNREACHABLE();
1148 }
1149 __ movdbl(FieldOperand(dst_, HeapNumber::kValueOffset), xmm0);
1150 __ jmp(&done);
1151
1152 __ bind(&after_alloc_failure);
1153 __ pop(left_);
1154 __ bind(&call_runtime);
1155 }
Steve Block6ded16b2010-05-10 14:33:55 +01001156 GenericBinaryOpStub stub(op_,
1157 mode_,
1158 NO_SMI_CODE_IN_STUB,
1159 TypeInfo::Combine(left_info_, right_info_));
Steve Block3ce2e202009-11-05 08:53:23 +00001160 stub.GenerateCall(masm_, left_, right_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001161 if (!dst_.is(eax)) __ mov(dst_, eax);
Leon Clarkee46be812010-01-19 14:06:41 +00001162 __ bind(&done);
Steve Blocka7e24c12009-10-30 11:49:00 +00001163}
1164
1165
Steve Block6ded16b2010-05-10 14:33:55 +01001166static TypeInfo CalculateTypeInfo(TypeInfo operands_type,
1167 Token::Value op,
1168 const Result& right,
1169 const Result& left) {
1170 // Set TypeInfo of result according to the operation performed.
1171 // Rely on the fact that smis have a 31 bit payload on ia32.
1172 ASSERT(kSmiValueSize == 31);
1173 switch (op) {
1174 case Token::COMMA:
1175 return right.type_info();
1176 case Token::OR:
1177 case Token::AND:
1178 // Result type can be either of the two input types.
1179 return operands_type;
1180 case Token::BIT_AND: {
1181 // Anding with positive Smis will give you a Smi.
1182 if (right.is_constant() && right.handle()->IsSmi() &&
1183 Smi::cast(*right.handle())->value() >= 0) {
1184 return TypeInfo::Smi();
1185 } else if (left.is_constant() && left.handle()->IsSmi() &&
1186 Smi::cast(*left.handle())->value() >= 0) {
1187 return TypeInfo::Smi();
1188 }
1189 return (operands_type.IsSmi())
1190 ? TypeInfo::Smi()
1191 : TypeInfo::Integer32();
1192 }
1193 case Token::BIT_OR: {
1194 // Oring with negative Smis will give you a Smi.
1195 if (right.is_constant() && right.handle()->IsSmi() &&
1196 Smi::cast(*right.handle())->value() < 0) {
1197 return TypeInfo::Smi();
1198 } else if (left.is_constant() && left.handle()->IsSmi() &&
1199 Smi::cast(*left.handle())->value() < 0) {
1200 return TypeInfo::Smi();
1201 }
1202 return (operands_type.IsSmi())
1203 ? TypeInfo::Smi()
1204 : TypeInfo::Integer32();
1205 }
1206 case Token::BIT_XOR:
1207 // Result is always a 32 bit integer. Smi property of inputs is preserved.
1208 return (operands_type.IsSmi())
1209 ? TypeInfo::Smi()
1210 : TypeInfo::Integer32();
1211 case Token::SAR:
1212 if (left.is_smi()) return TypeInfo::Smi();
1213 // Result is a smi if we shift by a constant >= 1, otherwise an integer32.
1214 // Shift amount is masked with 0x1F (ECMA standard 11.7.2).
1215 return (right.is_constant() && right.handle()->IsSmi()
1216 && (Smi::cast(*right.handle())->value() & 0x1F) >= 1)
1217 ? TypeInfo::Smi()
1218 : TypeInfo::Integer32();
1219 case Token::SHR:
1220 // Result is a smi if we shift by a constant >= 2, an integer32 if
1221 // we shift by 1, and an unsigned 32-bit integer if we shift by 0.
1222 if (right.is_constant() && right.handle()->IsSmi()) {
1223 int shift_amount = Smi::cast(*right.handle())->value() & 0x1F;
1224 if (shift_amount > 1) {
1225 return TypeInfo::Smi();
1226 } else if (shift_amount > 0) {
1227 return TypeInfo::Integer32();
1228 }
1229 }
1230 return TypeInfo::Number();
1231 case Token::ADD:
1232 if (operands_type.IsSmi()) {
1233 // The Integer32 range is big enough to take the sum of any two Smis.
1234 return TypeInfo::Integer32();
1235 } else if (operands_type.IsNumber()) {
1236 return TypeInfo::Number();
1237 } else if (left.type_info().IsString() || right.type_info().IsString()) {
1238 return TypeInfo::String();
1239 } else {
1240 return TypeInfo::Unknown();
1241 }
1242 case Token::SHL:
1243 return TypeInfo::Integer32();
1244 case Token::SUB:
1245 // The Integer32 range is big enough to take the difference of any two
1246 // Smis.
1247 return (operands_type.IsSmi()) ?
1248 TypeInfo::Integer32() :
1249 TypeInfo::Number();
1250 case Token::MUL:
1251 case Token::DIV:
1252 case Token::MOD:
1253 // Result is always a number.
1254 return TypeInfo::Number();
1255 default:
1256 UNREACHABLE();
1257 }
1258 UNREACHABLE();
1259 return TypeInfo::Unknown();
1260}
1261
1262
1263void CodeGenerator::GenericBinaryOperation(BinaryOperation* expr,
Steve Blocka7e24c12009-10-30 11:49:00 +00001264 OverwriteMode overwrite_mode) {
1265 Comment cmnt(masm_, "[ BinaryOperation");
Steve Block6ded16b2010-05-10 14:33:55 +01001266 Token::Value op = expr->op();
Steve Blocka7e24c12009-10-30 11:49:00 +00001267 Comment cmnt_token(masm_, Token::String(op));
1268
1269 if (op == Token::COMMA) {
1270 // Simply discard left value.
1271 frame_->Nip(1);
1272 return;
1273 }
1274
Steve Blocka7e24c12009-10-30 11:49:00 +00001275 Result right = frame_->Pop();
1276 Result left = frame_->Pop();
1277
1278 if (op == Token::ADD) {
Steve Block6ded16b2010-05-10 14:33:55 +01001279 const bool left_is_string = left.type_info().IsString();
1280 const bool right_is_string = right.type_info().IsString();
1281 // Make sure constant strings have string type info.
1282 ASSERT(!(left.is_constant() && left.handle()->IsString()) ||
1283 left_is_string);
1284 ASSERT(!(right.is_constant() && right.handle()->IsString()) ||
1285 right_is_string);
Steve Blocka7e24c12009-10-30 11:49:00 +00001286 if (left_is_string || right_is_string) {
1287 frame_->Push(&left);
1288 frame_->Push(&right);
1289 Result answer;
1290 if (left_is_string) {
1291 if (right_is_string) {
Steve Block6ded16b2010-05-10 14:33:55 +01001292 StringAddStub stub(NO_STRING_CHECK_IN_STUB);
1293 answer = frame_->CallStub(&stub, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00001294 } else {
1295 answer =
1296 frame_->InvokeBuiltin(Builtins::STRING_ADD_LEFT, CALL_FUNCTION, 2);
1297 }
1298 } else if (right_is_string) {
1299 answer =
1300 frame_->InvokeBuiltin(Builtins::STRING_ADD_RIGHT, CALL_FUNCTION, 2);
1301 }
Steve Block6ded16b2010-05-10 14:33:55 +01001302 answer.set_type_info(TypeInfo::String());
Steve Blocka7e24c12009-10-30 11:49:00 +00001303 frame_->Push(&answer);
1304 return;
1305 }
1306 // Neither operand is known to be a string.
1307 }
1308
Andrei Popescu402d9372010-02-26 13:31:12 +00001309 bool left_is_smi_constant = left.is_constant() && left.handle()->IsSmi();
1310 bool left_is_non_smi_constant = left.is_constant() && !left.handle()->IsSmi();
1311 bool right_is_smi_constant = right.is_constant() && right.handle()->IsSmi();
1312 bool right_is_non_smi_constant =
1313 right.is_constant() && !right.handle()->IsSmi();
Steve Blocka7e24c12009-10-30 11:49:00 +00001314
Andrei Popescu402d9372010-02-26 13:31:12 +00001315 if (left_is_smi_constant && right_is_smi_constant) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001316 // Compute the constant result at compile time, and leave it on the frame.
1317 int left_int = Smi::cast(*left.handle())->value();
1318 int right_int = Smi::cast(*right.handle())->value();
1319 if (FoldConstantSmis(op, left_int, right_int)) return;
1320 }
1321
Andrei Popescu402d9372010-02-26 13:31:12 +00001322 // Get number type of left and right sub-expressions.
Steve Block6ded16b2010-05-10 14:33:55 +01001323 TypeInfo operands_type =
1324 TypeInfo::Combine(left.type_info(), right.type_info());
1325
1326 TypeInfo result_type = CalculateTypeInfo(operands_type, op, right, left);
Andrei Popescu402d9372010-02-26 13:31:12 +00001327
Leon Clarked91b9f72010-01-27 17:25:45 +00001328 Result answer;
Andrei Popescu402d9372010-02-26 13:31:12 +00001329 if (left_is_non_smi_constant || right_is_non_smi_constant) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001330 // Go straight to the slow case, with no smi code.
Andrei Popescu402d9372010-02-26 13:31:12 +00001331 GenericBinaryOpStub stub(op,
1332 overwrite_mode,
1333 NO_SMI_CODE_IN_STUB,
1334 operands_type);
Leon Clarked91b9f72010-01-27 17:25:45 +00001335 answer = stub.GenerateCall(masm_, frame_, &left, &right);
Andrei Popescu402d9372010-02-26 13:31:12 +00001336 } else if (right_is_smi_constant) {
Steve Block6ded16b2010-05-10 14:33:55 +01001337 answer = ConstantSmiBinaryOperation(expr, &left, right.handle(),
1338 false, overwrite_mode);
Andrei Popescu402d9372010-02-26 13:31:12 +00001339 } else if (left_is_smi_constant) {
Steve Block6ded16b2010-05-10 14:33:55 +01001340 answer = ConstantSmiBinaryOperation(expr, &right, left.handle(),
1341 true, overwrite_mode);
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001342 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00001343 // Set the flags based on the operation, type and loop nesting level.
1344 // Bit operations always assume they likely operate on Smis. Still only
1345 // generate the inline Smi check code if this operation is part of a loop.
1346 // For all other operations only inline the Smi check code for likely smis
1347 // if the operation is part of a loop.
Steve Block6ded16b2010-05-10 14:33:55 +01001348 if (loop_nesting() > 0 &&
1349 (Token::IsBitOp(op) ||
1350 operands_type.IsInteger32() ||
1351 expr->type()->IsLikelySmi())) {
1352 answer = LikelySmiBinaryOperation(expr, &left, &right, overwrite_mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00001353 } else {
Andrei Popescu402d9372010-02-26 13:31:12 +00001354 GenericBinaryOpStub stub(op,
1355 overwrite_mode,
1356 NO_GENERIC_BINARY_FLAGS,
1357 operands_type);
Leon Clarked91b9f72010-01-27 17:25:45 +00001358 answer = stub.GenerateCall(masm_, frame_, &left, &right);
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001359 }
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001360 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001361
Steve Block6ded16b2010-05-10 14:33:55 +01001362 answer.set_type_info(result_type);
Leon Clarked91b9f72010-01-27 17:25:45 +00001363 frame_->Push(&answer);
Steve Blocka7e24c12009-10-30 11:49:00 +00001364}
1365
1366
1367bool CodeGenerator::FoldConstantSmis(Token::Value op, int left, int right) {
1368 Object* answer_object = Heap::undefined_value();
1369 switch (op) {
1370 case Token::ADD:
1371 if (Smi::IsValid(left + right)) {
1372 answer_object = Smi::FromInt(left + right);
1373 }
1374 break;
1375 case Token::SUB:
1376 if (Smi::IsValid(left - right)) {
1377 answer_object = Smi::FromInt(left - right);
1378 }
1379 break;
1380 case Token::MUL: {
1381 double answer = static_cast<double>(left) * right;
1382 if (answer >= Smi::kMinValue && answer <= Smi::kMaxValue) {
1383 // If the product is zero and the non-zero factor is negative,
1384 // the spec requires us to return floating point negative zero.
1385 if (answer != 0 || (left >= 0 && right >= 0)) {
1386 answer_object = Smi::FromInt(static_cast<int>(answer));
1387 }
1388 }
1389 }
1390 break;
1391 case Token::DIV:
1392 case Token::MOD:
1393 break;
1394 case Token::BIT_OR:
1395 answer_object = Smi::FromInt(left | right);
1396 break;
1397 case Token::BIT_AND:
1398 answer_object = Smi::FromInt(left & right);
1399 break;
1400 case Token::BIT_XOR:
1401 answer_object = Smi::FromInt(left ^ right);
1402 break;
1403
1404 case Token::SHL: {
1405 int shift_amount = right & 0x1F;
1406 if (Smi::IsValid(left << shift_amount)) {
1407 answer_object = Smi::FromInt(left << shift_amount);
1408 }
1409 break;
1410 }
1411 case Token::SHR: {
1412 int shift_amount = right & 0x1F;
1413 unsigned int unsigned_left = left;
1414 unsigned_left >>= shift_amount;
1415 if (unsigned_left <= static_cast<unsigned int>(Smi::kMaxValue)) {
1416 answer_object = Smi::FromInt(unsigned_left);
1417 }
1418 break;
1419 }
1420 case Token::SAR: {
1421 int shift_amount = right & 0x1F;
1422 unsigned int unsigned_left = left;
1423 if (left < 0) {
1424 // Perform arithmetic shift of a negative number by
1425 // complementing number, logical shifting, complementing again.
1426 unsigned_left = ~unsigned_left;
1427 unsigned_left >>= shift_amount;
1428 unsigned_left = ~unsigned_left;
1429 } else {
1430 unsigned_left >>= shift_amount;
1431 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001432 ASSERT(Smi::IsValid(static_cast<int32_t>(unsigned_left)));
1433 answer_object = Smi::FromInt(static_cast<int32_t>(unsigned_left));
Steve Blocka7e24c12009-10-30 11:49:00 +00001434 break;
1435 }
1436 default:
1437 UNREACHABLE();
1438 break;
1439 }
1440 if (answer_object == Heap::undefined_value()) {
1441 return false;
1442 }
1443 frame_->Push(Handle<Object>(answer_object));
1444 return true;
1445}
1446
1447
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001448void CodeGenerator::JumpIfNotBothSmiUsingTypeInfo(Register left,
1449 Register right,
1450 Register scratch,
1451 TypeInfo left_info,
1452 TypeInfo right_info,
1453 DeferredCode* deferred) {
1454 if (left.is(right)) {
1455 if (!left_info.IsSmi()) {
1456 __ test(left, Immediate(kSmiTagMask));
1457 deferred->Branch(not_zero);
1458 } else {
1459 if (FLAG_debug_code) __ AbortIfNotSmi(left);
1460 }
1461 } else if (!left_info.IsSmi()) {
1462 if (!right_info.IsSmi()) {
1463 __ mov(scratch, left);
1464 __ or_(scratch, Operand(right));
1465 __ test(scratch, Immediate(kSmiTagMask));
1466 deferred->Branch(not_zero);
1467 } else {
1468 __ test(left, Immediate(kSmiTagMask));
1469 deferred->Branch(not_zero);
1470 if (FLAG_debug_code) __ AbortIfNotSmi(right);
1471 }
1472 } else {
1473 if (FLAG_debug_code) __ AbortIfNotSmi(left);
1474 if (!right_info.IsSmi()) {
1475 __ test(right, Immediate(kSmiTagMask));
1476 deferred->Branch(not_zero);
1477 } else {
1478 if (FLAG_debug_code) __ AbortIfNotSmi(right);
1479 }
1480 }
1481}
Steve Block6ded16b2010-05-10 14:33:55 +01001482
1483
Steve Blocka7e24c12009-10-30 11:49:00 +00001484// Implements a binary operation using a deferred code object and some
1485// inline code to operate on smis quickly.
Steve Block6ded16b2010-05-10 14:33:55 +01001486Result CodeGenerator::LikelySmiBinaryOperation(BinaryOperation* expr,
Leon Clarked91b9f72010-01-27 17:25:45 +00001487 Result* left,
1488 Result* right,
1489 OverwriteMode overwrite_mode) {
Kristian Monsen25f61362010-05-21 11:50:48 +01001490 // Copy the type info because left and right may be overwritten.
1491 TypeInfo left_type_info = left->type_info();
1492 TypeInfo right_type_info = right->type_info();
Steve Block6ded16b2010-05-10 14:33:55 +01001493 Token::Value op = expr->op();
Leon Clarked91b9f72010-01-27 17:25:45 +00001494 Result answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00001495 // Special handling of div and mod because they use fixed registers.
1496 if (op == Token::DIV || op == Token::MOD) {
1497 // We need eax as the quotient register, edx as the remainder
1498 // register, neither left nor right in eax or edx, and left copied
1499 // to eax.
1500 Result quotient;
1501 Result remainder;
1502 bool left_is_in_eax = false;
1503 // Step 1: get eax for quotient.
1504 if ((left->is_register() && left->reg().is(eax)) ||
1505 (right->is_register() && right->reg().is(eax))) {
1506 // One or both is in eax. Use a fresh non-edx register for
1507 // them.
1508 Result fresh = allocator_->Allocate();
1509 ASSERT(fresh.is_valid());
1510 if (fresh.reg().is(edx)) {
1511 remainder = fresh;
1512 fresh = allocator_->Allocate();
1513 ASSERT(fresh.is_valid());
1514 }
1515 if (left->is_register() && left->reg().is(eax)) {
1516 quotient = *left;
1517 *left = fresh;
1518 left_is_in_eax = true;
1519 }
1520 if (right->is_register() && right->reg().is(eax)) {
1521 quotient = *right;
1522 *right = fresh;
1523 }
1524 __ mov(fresh.reg(), eax);
1525 } else {
1526 // Neither left nor right is in eax.
1527 quotient = allocator_->Allocate(eax);
1528 }
1529 ASSERT(quotient.is_register() && quotient.reg().is(eax));
1530 ASSERT(!(left->is_register() && left->reg().is(eax)));
1531 ASSERT(!(right->is_register() && right->reg().is(eax)));
1532
1533 // Step 2: get edx for remainder if necessary.
1534 if (!remainder.is_valid()) {
1535 if ((left->is_register() && left->reg().is(edx)) ||
1536 (right->is_register() && right->reg().is(edx))) {
1537 Result fresh = allocator_->Allocate();
1538 ASSERT(fresh.is_valid());
1539 if (left->is_register() && left->reg().is(edx)) {
1540 remainder = *left;
1541 *left = fresh;
1542 }
1543 if (right->is_register() && right->reg().is(edx)) {
1544 remainder = *right;
1545 *right = fresh;
1546 }
1547 __ mov(fresh.reg(), edx);
1548 } else {
1549 // Neither left nor right is in edx.
1550 remainder = allocator_->Allocate(edx);
1551 }
1552 }
1553 ASSERT(remainder.is_register() && remainder.reg().is(edx));
1554 ASSERT(!(left->is_register() && left->reg().is(edx)));
1555 ASSERT(!(right->is_register() && right->reg().is(edx)));
1556
1557 left->ToRegister();
1558 right->ToRegister();
1559 frame_->Spill(eax);
1560 frame_->Spill(edx);
1561
1562 // Check that left and right are smi tagged.
1563 DeferredInlineBinaryOperation* deferred =
1564 new DeferredInlineBinaryOperation(op,
1565 (op == Token::DIV) ? eax : edx,
1566 left->reg(),
1567 right->reg(),
Kristian Monsen25f61362010-05-21 11:50:48 +01001568 left_type_info,
1569 right_type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001570 overwrite_mode);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001571 JumpIfNotBothSmiUsingTypeInfo(left->reg(), right->reg(), edx,
1572 left_type_info, right_type_info, deferred);
1573 if (!left_is_in_eax) {
1574 __ mov(eax, left->reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001575 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001576 // Sign extend eax into edx:eax.
1577 __ cdq();
1578 // Check for 0 divisor.
1579 __ test(right->reg(), Operand(right->reg()));
1580 deferred->Branch(zero);
1581 // Divide edx:eax by the right operand.
1582 __ idiv(right->reg());
1583
1584 // Complete the operation.
1585 if (op == Token::DIV) {
1586 // Check for negative zero result. If result is zero, and divisor
1587 // is negative, return a floating point negative zero. The
1588 // virtual frame is unchanged in this block, so local control flow
Steve Block6ded16b2010-05-10 14:33:55 +01001589 // can use a Label rather than a JumpTarget. If the context of this
1590 // expression will treat -0 like 0, do not do this test.
1591 if (!expr->no_negative_zero()) {
1592 Label non_zero_result;
1593 __ test(left->reg(), Operand(left->reg()));
1594 __ j(not_zero, &non_zero_result);
1595 __ test(right->reg(), Operand(right->reg()));
1596 deferred->Branch(negative);
1597 __ bind(&non_zero_result);
1598 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001599 // Check for the corner case of dividing the most negative smi by
1600 // -1. We cannot use the overflow flag, since it is not set by
1601 // idiv instruction.
1602 ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
1603 __ cmp(eax, 0x40000000);
1604 deferred->Branch(equal);
1605 // Check that the remainder is zero.
1606 __ test(edx, Operand(edx));
1607 deferred->Branch(not_zero);
1608 // Tag the result and store it in the quotient register.
Leon Clarkee46be812010-01-19 14:06:41 +00001609 __ SmiTag(eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00001610 deferred->BindExit();
1611 left->Unuse();
1612 right->Unuse();
Leon Clarked91b9f72010-01-27 17:25:45 +00001613 answer = quotient;
Steve Blocka7e24c12009-10-30 11:49:00 +00001614 } else {
1615 ASSERT(op == Token::MOD);
1616 // Check for a negative zero result. If the result is zero, and
1617 // the dividend is negative, return a floating point negative
1618 // zero. The frame is unchanged in this block, so local control
1619 // flow can use a Label rather than a JumpTarget.
Steve Block6ded16b2010-05-10 14:33:55 +01001620 if (!expr->no_negative_zero()) {
1621 Label non_zero_result;
1622 __ test(edx, Operand(edx));
1623 __ j(not_zero, &non_zero_result, taken);
1624 __ test(left->reg(), Operand(left->reg()));
1625 deferred->Branch(negative);
1626 __ bind(&non_zero_result);
1627 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001628 deferred->BindExit();
1629 left->Unuse();
1630 right->Unuse();
Leon Clarked91b9f72010-01-27 17:25:45 +00001631 answer = remainder;
Steve Blocka7e24c12009-10-30 11:49:00 +00001632 }
Leon Clarked91b9f72010-01-27 17:25:45 +00001633 ASSERT(answer.is_valid());
1634 return answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00001635 }
1636
1637 // Special handling of shift operations because they use fixed
1638 // registers.
1639 if (op == Token::SHL || op == Token::SHR || op == Token::SAR) {
1640 // Move left out of ecx if necessary.
1641 if (left->is_register() && left->reg().is(ecx)) {
1642 *left = allocator_->Allocate();
1643 ASSERT(left->is_valid());
1644 __ mov(left->reg(), ecx);
1645 }
1646 right->ToRegister(ecx);
1647 left->ToRegister();
1648 ASSERT(left->is_register() && !left->reg().is(ecx));
1649 ASSERT(right->is_register() && right->reg().is(ecx));
1650
1651 // We will modify right, it must be spilled.
1652 frame_->Spill(ecx);
1653
1654 // Use a fresh answer register to avoid spilling the left operand.
Leon Clarked91b9f72010-01-27 17:25:45 +00001655 answer = allocator_->Allocate();
Steve Blocka7e24c12009-10-30 11:49:00 +00001656 ASSERT(answer.is_valid());
1657 // Check that both operands are smis using the answer register as a
1658 // temporary.
1659 DeferredInlineBinaryOperation* deferred =
1660 new DeferredInlineBinaryOperation(op,
1661 answer.reg(),
1662 left->reg(),
1663 ecx,
Kristian Monsen25f61362010-05-21 11:50:48 +01001664 left_type_info,
1665 right_type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001666 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00001667
Steve Block6ded16b2010-05-10 14:33:55 +01001668 Label do_op, left_nonsmi;
1669 // If right is a smi we make a fast case if left is either a smi
1670 // or a heapnumber.
Kristian Monsen25f61362010-05-21 11:50:48 +01001671 if (CpuFeatures::IsSupported(SSE2) && right_type_info.IsSmi()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001672 CpuFeatures::Scope use_sse2(SSE2);
1673 __ mov(answer.reg(), left->reg());
1674 // Fast case - both are actually smis.
Kristian Monsen25f61362010-05-21 11:50:48 +01001675 if (!left_type_info.IsSmi()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001676 __ test(answer.reg(), Immediate(kSmiTagMask));
1677 __ j(not_zero, &left_nonsmi);
1678 } else {
1679 if (FLAG_debug_code) __ AbortIfNotSmi(left->reg());
1680 }
1681 if (FLAG_debug_code) __ AbortIfNotSmi(right->reg());
1682 __ SmiUntag(answer.reg());
1683 __ jmp(&do_op);
1684
1685 __ bind(&left_nonsmi);
1686 // Branch if not a heapnumber.
1687 __ cmp(FieldOperand(answer.reg(), HeapObject::kMapOffset),
1688 Factory::heap_number_map());
1689 deferred->Branch(not_equal);
1690
1691 // Load integer value into answer register using truncation.
1692 __ cvttsd2si(answer.reg(),
1693 FieldOperand(answer.reg(), HeapNumber::kValueOffset));
1694 // Branch if we do not fit in a smi.
1695 __ cmp(answer.reg(), 0xc0000000);
1696 deferred->Branch(negative);
1697 } else {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001698 JumpIfNotBothSmiUsingTypeInfo(left->reg(), right->reg(), answer.reg(),
1699 left_type_info, right_type_info, deferred);
Steve Block6ded16b2010-05-10 14:33:55 +01001700
1701 // Untag both operands.
1702 __ mov(answer.reg(), left->reg());
1703 __ SmiUntag(answer.reg());
1704 }
1705
1706 __ bind(&do_op);
Leon Clarkee46be812010-01-19 14:06:41 +00001707 __ SmiUntag(ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +00001708 // Perform the operation.
1709 switch (op) {
1710 case Token::SAR:
Steve Blockd0582a62009-12-15 09:54:21 +00001711 __ sar_cl(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001712 // No checks of result necessary
1713 break;
1714 case Token::SHR: {
1715 Label result_ok;
Steve Blockd0582a62009-12-15 09:54:21 +00001716 __ shr_cl(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001717 // Check that the *unsigned* result fits in a smi. Neither of
1718 // the two high-order bits can be set:
1719 // * 0x80000000: high bit would be lost when smi tagging.
1720 // * 0x40000000: this number would convert to negative when smi
1721 // tagging.
1722 // These two cases can only happen with shifts by 0 or 1 when
1723 // handed a valid smi. If the answer cannot be represented by a
1724 // smi, restore the left and right arguments, and jump to slow
1725 // case. The low bit of the left argument may be lost, but only
1726 // in a case where it is dropped anyway.
1727 __ test(answer.reg(), Immediate(0xc0000000));
1728 __ j(zero, &result_ok);
Leon Clarkee46be812010-01-19 14:06:41 +00001729 __ SmiTag(ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +00001730 deferred->Jump();
1731 __ bind(&result_ok);
1732 break;
1733 }
1734 case Token::SHL: {
1735 Label result_ok;
Steve Blockd0582a62009-12-15 09:54:21 +00001736 __ shl_cl(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001737 // Check that the *signed* result fits in a smi.
1738 __ cmp(answer.reg(), 0xc0000000);
1739 __ j(positive, &result_ok);
Leon Clarkee46be812010-01-19 14:06:41 +00001740 __ SmiTag(ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +00001741 deferred->Jump();
1742 __ bind(&result_ok);
1743 break;
1744 }
1745 default:
1746 UNREACHABLE();
1747 }
1748 // Smi-tag the result in answer.
Leon Clarkee46be812010-01-19 14:06:41 +00001749 __ SmiTag(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001750 deferred->BindExit();
1751 left->Unuse();
1752 right->Unuse();
Leon Clarked91b9f72010-01-27 17:25:45 +00001753 ASSERT(answer.is_valid());
1754 return answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00001755 }
1756
1757 // Handle the other binary operations.
1758 left->ToRegister();
1759 right->ToRegister();
1760 // A newly allocated register answer is used to hold the answer. The
1761 // registers containing left and right are not modified so they don't
1762 // need to be spilled in the fast case.
Leon Clarked91b9f72010-01-27 17:25:45 +00001763 answer = allocator_->Allocate();
Steve Blocka7e24c12009-10-30 11:49:00 +00001764 ASSERT(answer.is_valid());
1765
1766 // Perform the smi tag check.
1767 DeferredInlineBinaryOperation* deferred =
1768 new DeferredInlineBinaryOperation(op,
1769 answer.reg(),
1770 left->reg(),
1771 right->reg(),
Kristian Monsen25f61362010-05-21 11:50:48 +01001772 left_type_info,
1773 right_type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001774 overwrite_mode);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001775 JumpIfNotBothSmiUsingTypeInfo(left->reg(), right->reg(), answer.reg(),
1776 left_type_info, right_type_info, deferred);
Steve Block6ded16b2010-05-10 14:33:55 +01001777
Steve Blocka7e24c12009-10-30 11:49:00 +00001778 __ mov(answer.reg(), left->reg());
1779 switch (op) {
1780 case Token::ADD:
Leon Clarked91b9f72010-01-27 17:25:45 +00001781 __ add(answer.reg(), Operand(right->reg()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001782 deferred->Branch(overflow);
1783 break;
1784
1785 case Token::SUB:
Leon Clarked91b9f72010-01-27 17:25:45 +00001786 __ sub(answer.reg(), Operand(right->reg()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001787 deferred->Branch(overflow);
1788 break;
1789
1790 case Token::MUL: {
1791 // If the smi tag is 0 we can just leave the tag on one operand.
1792 ASSERT(kSmiTag == 0); // Adjust code below if not the case.
1793 // Remove smi tag from the left operand (but keep sign).
1794 // Left-hand operand has been copied into answer.
Leon Clarkee46be812010-01-19 14:06:41 +00001795 __ SmiUntag(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00001796 // Do multiplication of smis, leaving result in answer.
1797 __ imul(answer.reg(), Operand(right->reg()));
1798 // Go slow on overflows.
1799 deferred->Branch(overflow);
1800 // Check for negative zero result. If product is zero, and one
1801 // argument is negative, go to slow case. The frame is unchanged
1802 // in this block, so local control flow can use a Label rather
1803 // than a JumpTarget.
Steve Block6ded16b2010-05-10 14:33:55 +01001804 if (!expr->no_negative_zero()) {
1805 Label non_zero_result;
1806 __ test(answer.reg(), Operand(answer.reg()));
1807 __ j(not_zero, &non_zero_result, taken);
1808 __ mov(answer.reg(), left->reg());
1809 __ or_(answer.reg(), Operand(right->reg()));
1810 deferred->Branch(negative);
1811 __ xor_(answer.reg(), Operand(answer.reg())); // Positive 0 is correct.
1812 __ bind(&non_zero_result);
1813 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001814 break;
1815 }
1816
1817 case Token::BIT_OR:
1818 __ or_(answer.reg(), Operand(right->reg()));
1819 break;
1820
1821 case Token::BIT_AND:
1822 __ and_(answer.reg(), Operand(right->reg()));
1823 break;
1824
1825 case Token::BIT_XOR:
1826 __ xor_(answer.reg(), Operand(right->reg()));
1827 break;
1828
1829 default:
1830 UNREACHABLE();
1831 break;
1832 }
1833 deferred->BindExit();
1834 left->Unuse();
1835 right->Unuse();
Leon Clarked91b9f72010-01-27 17:25:45 +00001836 ASSERT(answer.is_valid());
1837 return answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00001838}
1839
1840
1841// Call the appropriate binary operation stub to compute src op value
1842// and leave the result in dst.
1843class DeferredInlineSmiOperation: public DeferredCode {
1844 public:
1845 DeferredInlineSmiOperation(Token::Value op,
1846 Register dst,
1847 Register src,
Steve Block6ded16b2010-05-10 14:33:55 +01001848 TypeInfo type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001849 Smi* value,
1850 OverwriteMode overwrite_mode)
1851 : op_(op),
1852 dst_(dst),
1853 src_(src),
Steve Block6ded16b2010-05-10 14:33:55 +01001854 type_info_(type_info),
Steve Blocka7e24c12009-10-30 11:49:00 +00001855 value_(value),
1856 overwrite_mode_(overwrite_mode) {
Steve Block6ded16b2010-05-10 14:33:55 +01001857 if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
Steve Blocka7e24c12009-10-30 11:49:00 +00001858 set_comment("[ DeferredInlineSmiOperation");
1859 }
1860
1861 virtual void Generate();
1862
1863 private:
1864 Token::Value op_;
1865 Register dst_;
1866 Register src_;
Steve Block6ded16b2010-05-10 14:33:55 +01001867 TypeInfo type_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001868 Smi* value_;
1869 OverwriteMode overwrite_mode_;
1870};
1871
1872
1873void DeferredInlineSmiOperation::Generate() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001874 // For mod we don't generate all the Smi code inline.
1875 GenericBinaryOpStub stub(
1876 op_,
1877 overwrite_mode_,
Steve Block6ded16b2010-05-10 14:33:55 +01001878 (op_ == Token::MOD) ? NO_GENERIC_BINARY_FLAGS : NO_SMI_CODE_IN_STUB,
1879 TypeInfo::Combine(TypeInfo::Smi(), type_info_));
Steve Block3ce2e202009-11-05 08:53:23 +00001880 stub.GenerateCall(masm_, src_, value_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001881 if (!dst_.is(eax)) __ mov(dst_, eax);
1882}
1883
1884
1885// Call the appropriate binary operation stub to compute value op src
1886// and leave the result in dst.
1887class DeferredInlineSmiOperationReversed: public DeferredCode {
1888 public:
1889 DeferredInlineSmiOperationReversed(Token::Value op,
1890 Register dst,
1891 Smi* value,
1892 Register src,
Steve Block6ded16b2010-05-10 14:33:55 +01001893 TypeInfo type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001894 OverwriteMode overwrite_mode)
1895 : op_(op),
1896 dst_(dst),
Steve Block6ded16b2010-05-10 14:33:55 +01001897 type_info_(type_info),
Steve Blocka7e24c12009-10-30 11:49:00 +00001898 value_(value),
1899 src_(src),
1900 overwrite_mode_(overwrite_mode) {
1901 set_comment("[ DeferredInlineSmiOperationReversed");
1902 }
1903
1904 virtual void Generate();
1905
1906 private:
1907 Token::Value op_;
1908 Register dst_;
Steve Block6ded16b2010-05-10 14:33:55 +01001909 TypeInfo type_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001910 Smi* value_;
1911 Register src_;
1912 OverwriteMode overwrite_mode_;
1913};
1914
1915
1916void DeferredInlineSmiOperationReversed::Generate() {
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001917 GenericBinaryOpStub stub(
Steve Block6ded16b2010-05-10 14:33:55 +01001918 op_,
1919 overwrite_mode_,
1920 NO_SMI_CODE_IN_STUB,
1921 TypeInfo::Combine(TypeInfo::Smi(), type_info_));
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001922 stub.GenerateCall(masm_, value_, src_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001923 if (!dst_.is(eax)) __ mov(dst_, eax);
1924}
1925
1926
1927// The result of src + value is in dst. It either overflowed or was not
1928// smi tagged. Undo the speculative addition and call the appropriate
1929// specialized stub for add. The result is left in dst.
1930class DeferredInlineSmiAdd: public DeferredCode {
1931 public:
1932 DeferredInlineSmiAdd(Register dst,
Steve Block6ded16b2010-05-10 14:33:55 +01001933 TypeInfo type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001934 Smi* value,
1935 OverwriteMode overwrite_mode)
Steve Block6ded16b2010-05-10 14:33:55 +01001936 : dst_(dst),
1937 type_info_(type_info),
1938 value_(value),
1939 overwrite_mode_(overwrite_mode) {
1940 if (type_info_.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
Steve Blocka7e24c12009-10-30 11:49:00 +00001941 set_comment("[ DeferredInlineSmiAdd");
1942 }
1943
1944 virtual void Generate();
1945
1946 private:
1947 Register dst_;
Steve Block6ded16b2010-05-10 14:33:55 +01001948 TypeInfo type_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001949 Smi* value_;
1950 OverwriteMode overwrite_mode_;
1951};
1952
1953
1954void DeferredInlineSmiAdd::Generate() {
1955 // Undo the optimistic add operation and call the shared stub.
1956 __ sub(Operand(dst_), Immediate(value_));
Steve Block6ded16b2010-05-10 14:33:55 +01001957 GenericBinaryOpStub igostub(
1958 Token::ADD,
1959 overwrite_mode_,
1960 NO_SMI_CODE_IN_STUB,
1961 TypeInfo::Combine(TypeInfo::Smi(), type_info_));
Steve Block3ce2e202009-11-05 08:53:23 +00001962 igostub.GenerateCall(masm_, dst_, value_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001963 if (!dst_.is(eax)) __ mov(dst_, eax);
1964}
1965
1966
1967// The result of value + src is in dst. It either overflowed or was not
1968// smi tagged. Undo the speculative addition and call the appropriate
1969// specialized stub for add. The result is left in dst.
1970class DeferredInlineSmiAddReversed: public DeferredCode {
1971 public:
1972 DeferredInlineSmiAddReversed(Register dst,
Steve Block6ded16b2010-05-10 14:33:55 +01001973 TypeInfo type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00001974 Smi* value,
1975 OverwriteMode overwrite_mode)
Steve Block6ded16b2010-05-10 14:33:55 +01001976 : dst_(dst),
1977 type_info_(type_info),
1978 value_(value),
1979 overwrite_mode_(overwrite_mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001980 set_comment("[ DeferredInlineSmiAddReversed");
1981 }
1982
1983 virtual void Generate();
1984
1985 private:
1986 Register dst_;
Steve Block6ded16b2010-05-10 14:33:55 +01001987 TypeInfo type_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001988 Smi* value_;
1989 OverwriteMode overwrite_mode_;
1990};
1991
1992
1993void DeferredInlineSmiAddReversed::Generate() {
1994 // Undo the optimistic add operation and call the shared stub.
1995 __ sub(Operand(dst_), Immediate(value_));
Steve Block6ded16b2010-05-10 14:33:55 +01001996 GenericBinaryOpStub igostub(
1997 Token::ADD,
1998 overwrite_mode_,
1999 NO_SMI_CODE_IN_STUB,
2000 TypeInfo::Combine(TypeInfo::Smi(), type_info_));
Steve Block3ce2e202009-11-05 08:53:23 +00002001 igostub.GenerateCall(masm_, value_, dst_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002002 if (!dst_.is(eax)) __ mov(dst_, eax);
2003}
2004
2005
2006// The result of src - value is in dst. It either overflowed or was not
2007// smi tagged. Undo the speculative subtraction and call the
2008// appropriate specialized stub for subtract. The result is left in
2009// dst.
2010class DeferredInlineSmiSub: public DeferredCode {
2011 public:
2012 DeferredInlineSmiSub(Register dst,
Steve Block6ded16b2010-05-10 14:33:55 +01002013 TypeInfo type_info,
Steve Blocka7e24c12009-10-30 11:49:00 +00002014 Smi* value,
2015 OverwriteMode overwrite_mode)
Steve Block6ded16b2010-05-10 14:33:55 +01002016 : dst_(dst),
2017 type_info_(type_info),
2018 value_(value),
2019 overwrite_mode_(overwrite_mode) {
2020 if (type_info.IsSmi()) overwrite_mode_ = NO_OVERWRITE;
Steve Blocka7e24c12009-10-30 11:49:00 +00002021 set_comment("[ DeferredInlineSmiSub");
2022 }
2023
2024 virtual void Generate();
2025
2026 private:
2027 Register dst_;
Steve Block6ded16b2010-05-10 14:33:55 +01002028 TypeInfo type_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002029 Smi* value_;
2030 OverwriteMode overwrite_mode_;
2031};
2032
2033
2034void DeferredInlineSmiSub::Generate() {
2035 // Undo the optimistic sub operation and call the shared stub.
2036 __ add(Operand(dst_), Immediate(value_));
Steve Block6ded16b2010-05-10 14:33:55 +01002037 GenericBinaryOpStub igostub(
2038 Token::SUB,
2039 overwrite_mode_,
2040 NO_SMI_CODE_IN_STUB,
2041 TypeInfo::Combine(TypeInfo::Smi(), type_info_));
Steve Block3ce2e202009-11-05 08:53:23 +00002042 igostub.GenerateCall(masm_, dst_, value_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002043 if (!dst_.is(eax)) __ mov(dst_, eax);
2044}
2045
2046
Kristian Monsen25f61362010-05-21 11:50:48 +01002047Result CodeGenerator::ConstantSmiBinaryOperation(BinaryOperation* expr,
2048 Result* operand,
2049 Handle<Object> value,
2050 bool reversed,
2051 OverwriteMode overwrite_mode) {
2052 // Generate inline code for a binary operation when one of the
2053 // operands is a constant smi. Consumes the argument "operand".
Steve Blocka7e24c12009-10-30 11:49:00 +00002054 if (IsUnsafeSmi(value)) {
2055 Result unsafe_operand(value);
2056 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01002057 return LikelySmiBinaryOperation(expr, &unsafe_operand, operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002058 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002059 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002060 return LikelySmiBinaryOperation(expr, operand, &unsafe_operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002061 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002062 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002063 }
2064
2065 // Get the literal value.
2066 Smi* smi_value = Smi::cast(*value);
2067 int int_value = smi_value->value();
2068
Steve Block6ded16b2010-05-10 14:33:55 +01002069 Token::Value op = expr->op();
Leon Clarked91b9f72010-01-27 17:25:45 +00002070 Result answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00002071 switch (op) {
2072 case Token::ADD: {
2073 operand->ToRegister();
2074 frame_->Spill(operand->reg());
2075
2076 // Optimistically add. Call the specialized add stub if the
2077 // result is not a smi or overflows.
2078 DeferredCode* deferred = NULL;
2079 if (reversed) {
2080 deferred = new DeferredInlineSmiAddReversed(operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002081 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002082 smi_value,
2083 overwrite_mode);
2084 } else {
2085 deferred = new DeferredInlineSmiAdd(operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002086 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002087 smi_value,
2088 overwrite_mode);
2089 }
2090 __ add(Operand(operand->reg()), Immediate(value));
2091 deferred->Branch(overflow);
Steve Block6ded16b2010-05-10 14:33:55 +01002092 if (!operand->type_info().IsSmi()) {
2093 __ test(operand->reg(), Immediate(kSmiTagMask));
2094 deferred->Branch(not_zero);
2095 } else if (FLAG_debug_code) {
2096 __ AbortIfNotSmi(operand->reg());
2097 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002098 deferred->BindExit();
Leon Clarked91b9f72010-01-27 17:25:45 +00002099 answer = *operand;
Steve Blocka7e24c12009-10-30 11:49:00 +00002100 break;
2101 }
2102
2103 case Token::SUB: {
2104 DeferredCode* deferred = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00002105 if (reversed) {
2106 // The reversed case is only hit when the right operand is not a
2107 // constant.
2108 ASSERT(operand->is_register());
2109 answer = allocator()->Allocate();
2110 ASSERT(answer.is_valid());
2111 __ Set(answer.reg(), Immediate(value));
Steve Block6ded16b2010-05-10 14:33:55 +01002112 deferred =
2113 new DeferredInlineSmiOperationReversed(op,
2114 answer.reg(),
2115 smi_value,
2116 operand->reg(),
2117 operand->type_info(),
2118 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002119 __ sub(answer.reg(), Operand(operand->reg()));
2120 } else {
2121 operand->ToRegister();
2122 frame_->Spill(operand->reg());
2123 answer = *operand;
2124 deferred = new DeferredInlineSmiSub(operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002125 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002126 smi_value,
2127 overwrite_mode);
2128 __ sub(Operand(operand->reg()), Immediate(value));
2129 }
2130 deferred->Branch(overflow);
Steve Block6ded16b2010-05-10 14:33:55 +01002131 if (!operand->type_info().IsSmi()) {
2132 __ test(answer.reg(), Immediate(kSmiTagMask));
2133 deferred->Branch(not_zero);
2134 } else if (FLAG_debug_code) {
2135 __ AbortIfNotSmi(operand->reg());
2136 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002137 deferred->BindExit();
2138 operand->Unuse();
Steve Blocka7e24c12009-10-30 11:49:00 +00002139 break;
2140 }
2141
2142 case Token::SAR:
2143 if (reversed) {
2144 Result constant_operand(value);
Steve Block6ded16b2010-05-10 14:33:55 +01002145 answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002146 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002147 } else {
2148 // Only the least significant 5 bits of the shift value are used.
2149 // In the slow case, this masking is done inside the runtime call.
2150 int shift_value = int_value & 0x1f;
2151 operand->ToRegister();
2152 frame_->Spill(operand->reg());
Steve Block6ded16b2010-05-10 14:33:55 +01002153 if (!operand->type_info().IsSmi()) {
2154 DeferredInlineSmiOperation* deferred =
2155 new DeferredInlineSmiOperation(op,
2156 operand->reg(),
2157 operand->reg(),
2158 operand->type_info(),
2159 smi_value,
2160 overwrite_mode);
2161 __ test(operand->reg(), Immediate(kSmiTagMask));
2162 deferred->Branch(not_zero);
2163 if (shift_value > 0) {
2164 __ sar(operand->reg(), shift_value);
2165 __ and_(operand->reg(), ~kSmiTagMask);
2166 }
2167 deferred->BindExit();
2168 } else {
2169 if (FLAG_debug_code) {
2170 __ AbortIfNotSmi(operand->reg());
2171 }
2172 if (shift_value > 0) {
2173 __ sar(operand->reg(), shift_value);
2174 __ and_(operand->reg(), ~kSmiTagMask);
2175 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002176 }
Leon Clarked91b9f72010-01-27 17:25:45 +00002177 answer = *operand;
Steve Blocka7e24c12009-10-30 11:49:00 +00002178 }
2179 break;
2180
2181 case Token::SHR:
2182 if (reversed) {
2183 Result constant_operand(value);
Steve Block6ded16b2010-05-10 14:33:55 +01002184 answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002185 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002186 } else {
2187 // Only the least significant 5 bits of the shift value are used.
2188 // In the slow case, this masking is done inside the runtime call.
2189 int shift_value = int_value & 0x1f;
2190 operand->ToRegister();
Leon Clarked91b9f72010-01-27 17:25:45 +00002191 answer = allocator()->Allocate();
Steve Blocka7e24c12009-10-30 11:49:00 +00002192 ASSERT(answer.is_valid());
2193 DeferredInlineSmiOperation* deferred =
2194 new DeferredInlineSmiOperation(op,
2195 answer.reg(),
2196 operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002197 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002198 smi_value,
2199 overwrite_mode);
Steve Block6ded16b2010-05-10 14:33:55 +01002200 if (!operand->type_info().IsSmi()) {
2201 __ test(operand->reg(), Immediate(kSmiTagMask));
2202 deferred->Branch(not_zero);
2203 } else if (FLAG_debug_code) {
2204 __ AbortIfNotSmi(operand->reg());
2205 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002206 __ mov(answer.reg(), operand->reg());
Leon Clarkee46be812010-01-19 14:06:41 +00002207 __ SmiUntag(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00002208 __ shr(answer.reg(), shift_value);
2209 // A negative Smi shifted right two is in the positive Smi range.
2210 if (shift_value < 2) {
2211 __ test(answer.reg(), Immediate(0xc0000000));
2212 deferred->Branch(not_zero);
2213 }
2214 operand->Unuse();
Leon Clarkee46be812010-01-19 14:06:41 +00002215 __ SmiTag(answer.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00002216 deferred->BindExit();
Steve Blocka7e24c12009-10-30 11:49:00 +00002217 }
2218 break;
2219
2220 case Token::SHL:
2221 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01002222 // Move operand into ecx and also into a second register.
2223 // If operand is already in a register, take advantage of that.
2224 // This lets us modify ecx, but still bail out to deferred code.
Leon Clarkee46be812010-01-19 14:06:41 +00002225 Result right;
2226 Result right_copy_in_ecx;
Steve Block6ded16b2010-05-10 14:33:55 +01002227 TypeInfo right_type_info = operand->type_info();
Leon Clarkee46be812010-01-19 14:06:41 +00002228 operand->ToRegister();
2229 if (operand->reg().is(ecx)) {
2230 right = allocator()->Allocate();
2231 __ mov(right.reg(), ecx);
2232 frame_->Spill(ecx);
2233 right_copy_in_ecx = *operand;
2234 } else {
2235 right_copy_in_ecx = allocator()->Allocate(ecx);
2236 __ mov(ecx, operand->reg());
2237 right = *operand;
2238 }
2239 operand->Unuse();
2240
Leon Clarked91b9f72010-01-27 17:25:45 +00002241 answer = allocator()->Allocate();
Leon Clarkee46be812010-01-19 14:06:41 +00002242 DeferredInlineSmiOperationReversed* deferred =
2243 new DeferredInlineSmiOperationReversed(op,
2244 answer.reg(),
2245 smi_value,
2246 right.reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002247 right_type_info,
Leon Clarkee46be812010-01-19 14:06:41 +00002248 overwrite_mode);
2249 __ mov(answer.reg(), Immediate(int_value));
2250 __ sar(ecx, kSmiTagSize);
Steve Block6ded16b2010-05-10 14:33:55 +01002251 if (!right_type_info.IsSmi()) {
2252 deferred->Branch(carry);
2253 } else if (FLAG_debug_code) {
2254 __ AbortIfNotSmi(right.reg());
2255 }
Leon Clarkee46be812010-01-19 14:06:41 +00002256 __ shl_cl(answer.reg());
2257 __ cmp(answer.reg(), 0xc0000000);
2258 deferred->Branch(sign);
2259 __ SmiTag(answer.reg());
2260
2261 deferred->BindExit();
Steve Blocka7e24c12009-10-30 11:49:00 +00002262 } else {
2263 // Only the least significant 5 bits of the shift value are used.
2264 // In the slow case, this masking is done inside the runtime call.
2265 int shift_value = int_value & 0x1f;
2266 operand->ToRegister();
2267 if (shift_value == 0) {
2268 // Spill operand so it can be overwritten in the slow case.
2269 frame_->Spill(operand->reg());
2270 DeferredInlineSmiOperation* deferred =
2271 new DeferredInlineSmiOperation(op,
2272 operand->reg(),
2273 operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002274 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002275 smi_value,
2276 overwrite_mode);
2277 __ test(operand->reg(), Immediate(kSmiTagMask));
2278 deferred->Branch(not_zero);
2279 deferred->BindExit();
Leon Clarked91b9f72010-01-27 17:25:45 +00002280 answer = *operand;
Steve Blocka7e24c12009-10-30 11:49:00 +00002281 } else {
2282 // Use a fresh temporary for nonzero shift values.
Leon Clarked91b9f72010-01-27 17:25:45 +00002283 answer = allocator()->Allocate();
Steve Blocka7e24c12009-10-30 11:49:00 +00002284 ASSERT(answer.is_valid());
2285 DeferredInlineSmiOperation* deferred =
2286 new DeferredInlineSmiOperation(op,
2287 answer.reg(),
2288 operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002289 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002290 smi_value,
2291 overwrite_mode);
Steve Block6ded16b2010-05-10 14:33:55 +01002292 if (!operand->type_info().IsSmi()) {
2293 __ test(operand->reg(), Immediate(kSmiTagMask));
2294 deferred->Branch(not_zero);
2295 } else if (FLAG_debug_code) {
2296 __ AbortIfNotSmi(operand->reg());
2297 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002298 __ mov(answer.reg(), operand->reg());
2299 ASSERT(kSmiTag == 0); // adjust code if not the case
2300 // We do no shifts, only the Smi conversion, if shift_value is 1.
2301 if (shift_value > 1) {
2302 __ shl(answer.reg(), shift_value - 1);
2303 }
2304 // Convert int result to Smi, checking that it is in int range.
2305 ASSERT(kSmiTagSize == 1); // adjust code if not the case
2306 __ add(answer.reg(), Operand(answer.reg()));
2307 deferred->Branch(overflow);
2308 deferred->BindExit();
2309 operand->Unuse();
Steve Blocka7e24c12009-10-30 11:49:00 +00002310 }
2311 }
2312 break;
2313
2314 case Token::BIT_OR:
2315 case Token::BIT_XOR:
2316 case Token::BIT_AND: {
2317 operand->ToRegister();
2318 frame_->Spill(operand->reg());
2319 DeferredCode* deferred = NULL;
2320 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01002321 deferred =
2322 new DeferredInlineSmiOperationReversed(op,
2323 operand->reg(),
2324 smi_value,
2325 operand->reg(),
2326 operand->type_info(),
2327 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002328 } else {
2329 deferred = new DeferredInlineSmiOperation(op,
2330 operand->reg(),
2331 operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002332 operand->type_info(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002333 smi_value,
2334 overwrite_mode);
2335 }
Steve Block6ded16b2010-05-10 14:33:55 +01002336 if (!operand->type_info().IsSmi()) {
2337 __ test(operand->reg(), Immediate(kSmiTagMask));
2338 deferred->Branch(not_zero);
2339 } else if (FLAG_debug_code) {
2340 __ AbortIfNotSmi(operand->reg());
2341 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002342 if (op == Token::BIT_AND) {
2343 __ and_(Operand(operand->reg()), Immediate(value));
2344 } else if (op == Token::BIT_XOR) {
2345 if (int_value != 0) {
2346 __ xor_(Operand(operand->reg()), Immediate(value));
2347 }
2348 } else {
2349 ASSERT(op == Token::BIT_OR);
2350 if (int_value != 0) {
2351 __ or_(Operand(operand->reg()), Immediate(value));
2352 }
2353 }
2354 deferred->BindExit();
Leon Clarked91b9f72010-01-27 17:25:45 +00002355 answer = *operand;
Steve Blocka7e24c12009-10-30 11:49:00 +00002356 break;
2357 }
2358
Andrei Popescu402d9372010-02-26 13:31:12 +00002359 case Token::DIV:
2360 if (!reversed && int_value == 2) {
2361 operand->ToRegister();
2362 frame_->Spill(operand->reg());
2363
2364 DeferredInlineSmiOperation* deferred =
2365 new DeferredInlineSmiOperation(op,
2366 operand->reg(),
2367 operand->reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01002368 operand->type_info(),
Andrei Popescu402d9372010-02-26 13:31:12 +00002369 smi_value,
2370 overwrite_mode);
2371 // Check that lowest log2(value) bits of operand are zero, and test
2372 // smi tag at the same time.
2373 ASSERT_EQ(0, kSmiTag);
2374 ASSERT_EQ(1, kSmiTagSize);
2375 __ test(operand->reg(), Immediate(3));
2376 deferred->Branch(not_zero); // Branch if non-smi or odd smi.
2377 __ sar(operand->reg(), 1);
2378 deferred->BindExit();
2379 answer = *operand;
2380 } else {
2381 // Cannot fall through MOD to default case, so we duplicate the
2382 // default case here.
2383 Result constant_operand(value);
2384 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01002385 answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
Andrei Popescu402d9372010-02-26 13:31:12 +00002386 overwrite_mode);
2387 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002388 answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
Andrei Popescu402d9372010-02-26 13:31:12 +00002389 overwrite_mode);
2390 }
2391 }
2392 break;
Steve Block6ded16b2010-05-10 14:33:55 +01002393
Steve Blocka7e24c12009-10-30 11:49:00 +00002394 // Generate inline code for mod of powers of 2 and negative powers of 2.
2395 case Token::MOD:
2396 if (!reversed &&
2397 int_value != 0 &&
2398 (IsPowerOf2(int_value) || IsPowerOf2(-int_value))) {
2399 operand->ToRegister();
2400 frame_->Spill(operand->reg());
Steve Block6ded16b2010-05-10 14:33:55 +01002401 DeferredCode* deferred =
2402 new DeferredInlineSmiOperation(op,
2403 operand->reg(),
2404 operand->reg(),
2405 operand->type_info(),
2406 smi_value,
2407 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002408 // Check for negative or non-Smi left hand side.
Steve Block6ded16b2010-05-10 14:33:55 +01002409 __ test(operand->reg(), Immediate(kSmiTagMask | kSmiSignMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00002410 deferred->Branch(not_zero);
2411 if (int_value < 0) int_value = -int_value;
2412 if (int_value == 1) {
2413 __ mov(operand->reg(), Immediate(Smi::FromInt(0)));
2414 } else {
2415 __ and_(operand->reg(), (int_value << kSmiTagSize) - 1);
2416 }
2417 deferred->BindExit();
Leon Clarked91b9f72010-01-27 17:25:45 +00002418 answer = *operand;
Steve Blocka7e24c12009-10-30 11:49:00 +00002419 break;
2420 }
2421 // Fall through if we did not find a power of 2 on the right hand side!
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002422 // The next case must be the default.
Steve Blocka7e24c12009-10-30 11:49:00 +00002423
2424 default: {
2425 Result constant_operand(value);
2426 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01002427 answer = LikelySmiBinaryOperation(expr, &constant_operand, operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002428 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002429 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002430 answer = LikelySmiBinaryOperation(expr, operand, &constant_operand,
Leon Clarked91b9f72010-01-27 17:25:45 +00002431 overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002432 }
2433 break;
2434 }
2435 }
Leon Clarked91b9f72010-01-27 17:25:45 +00002436 ASSERT(answer.is_valid());
2437 return answer;
Steve Blocka7e24c12009-10-30 11:49:00 +00002438}
2439
2440
Leon Clarkee46be812010-01-19 14:06:41 +00002441static bool CouldBeNaN(const Result& result) {
Steve Block6ded16b2010-05-10 14:33:55 +01002442 if (result.type_info().IsSmi()) return false;
2443 if (result.type_info().IsInteger32()) return false;
Leon Clarkee46be812010-01-19 14:06:41 +00002444 if (!result.is_constant()) return true;
2445 if (!result.handle()->IsHeapNumber()) return false;
2446 return isnan(HeapNumber::cast(*result.handle())->value());
2447}
2448
2449
Steve Block6ded16b2010-05-10 14:33:55 +01002450// Convert from signed to unsigned comparison to match the way EFLAGS are set
2451// by FPU and XMM compare instructions.
2452static Condition DoubleCondition(Condition cc) {
2453 switch (cc) {
2454 case less: return below;
2455 case equal: return equal;
2456 case less_equal: return below_equal;
2457 case greater: return above;
2458 case greater_equal: return above_equal;
2459 default: UNREACHABLE();
2460 }
2461 UNREACHABLE();
2462 return equal;
2463}
2464
2465
Leon Clarkee46be812010-01-19 14:06:41 +00002466void CodeGenerator::Comparison(AstNode* node,
2467 Condition cc,
Steve Blocka7e24c12009-10-30 11:49:00 +00002468 bool strict,
2469 ControlDestination* dest) {
2470 // Strict only makes sense for equality comparisons.
2471 ASSERT(!strict || cc == equal);
2472
2473 Result left_side;
2474 Result right_side;
2475 // Implement '>' and '<=' by reversal to obtain ECMA-262 conversion order.
2476 if (cc == greater || cc == less_equal) {
2477 cc = ReverseCondition(cc);
2478 left_side = frame_->Pop();
2479 right_side = frame_->Pop();
2480 } else {
2481 right_side = frame_->Pop();
2482 left_side = frame_->Pop();
2483 }
2484 ASSERT(cc == less || cc == equal || cc == greater_equal);
2485
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002486 // If either side is a constant smi, optimize the comparison.
Leon Clarkee46be812010-01-19 14:06:41 +00002487 bool left_side_constant_smi = false;
2488 bool left_side_constant_null = false;
2489 bool left_side_constant_1_char_string = false;
2490 if (left_side.is_constant()) {
2491 left_side_constant_smi = left_side.handle()->IsSmi();
2492 left_side_constant_null = left_side.handle()->IsNull();
2493 left_side_constant_1_char_string =
2494 (left_side.handle()->IsString() &&
Steve Block6ded16b2010-05-10 14:33:55 +01002495 String::cast(*left_side.handle())->length() == 1 &&
2496 String::cast(*left_side.handle())->IsAsciiRepresentation());
Leon Clarkee46be812010-01-19 14:06:41 +00002497 }
2498 bool right_side_constant_smi = false;
2499 bool right_side_constant_null = false;
2500 bool right_side_constant_1_char_string = false;
2501 if (right_side.is_constant()) {
2502 right_side_constant_smi = right_side.handle()->IsSmi();
2503 right_side_constant_null = right_side.handle()->IsNull();
2504 right_side_constant_1_char_string =
2505 (right_side.handle()->IsString() &&
Steve Block6ded16b2010-05-10 14:33:55 +01002506 String::cast(*right_side.handle())->length() == 1 &&
2507 String::cast(*right_side.handle())->IsAsciiRepresentation());
Leon Clarkee46be812010-01-19 14:06:41 +00002508 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002509
2510 if (left_side_constant_smi || right_side_constant_smi) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002511 bool is_loop_condition = (node->AsExpression() != NULL) &&
2512 node->AsExpression()->is_loop_condition();
2513 ConstantSmiComparison(cc, strict, dest, &left_side, &right_side,
2514 left_side_constant_smi, right_side_constant_smi,
2515 is_loop_condition);
Steve Blocka7e24c12009-10-30 11:49:00 +00002516 } else if (cc == equal &&
2517 (left_side_constant_null || right_side_constant_null)) {
2518 // To make null checks efficient, we check if either the left side or
2519 // the right side is the constant 'null'.
2520 // If so, we optimize the code by inlining a null check instead of
2521 // calling the (very) general runtime routine for checking equality.
2522 Result operand = left_side_constant_null ? right_side : left_side;
2523 right_side.Unuse();
2524 left_side.Unuse();
2525 operand.ToRegister();
2526 __ cmp(operand.reg(), Factory::null_value());
2527 if (strict) {
2528 operand.Unuse();
2529 dest->Split(equal);
2530 } else {
2531 // The 'null' value is only equal to 'undefined' if using non-strict
2532 // comparisons.
2533 dest->true_target()->Branch(equal);
2534 __ cmp(operand.reg(), Factory::undefined_value());
2535 dest->true_target()->Branch(equal);
2536 __ test(operand.reg(), Immediate(kSmiTagMask));
2537 dest->false_target()->Branch(equal);
2538
2539 // It can be an undetectable object.
2540 // Use a scratch register in preference to spilling operand.reg().
2541 Result temp = allocator()->Allocate();
2542 ASSERT(temp.is_valid());
2543 __ mov(temp.reg(),
2544 FieldOperand(operand.reg(), HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002545 __ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
2546 1 << Map::kIsUndetectable);
Steve Blocka7e24c12009-10-30 11:49:00 +00002547 temp.Unuse();
2548 operand.Unuse();
2549 dest->Split(not_zero);
2550 }
Leon Clarkee46be812010-01-19 14:06:41 +00002551 } else if (left_side_constant_1_char_string ||
2552 right_side_constant_1_char_string) {
2553 if (left_side_constant_1_char_string && right_side_constant_1_char_string) {
2554 // Trivial case, comparing two constants.
2555 int left_value = String::cast(*left_side.handle())->Get(0);
2556 int right_value = String::cast(*right_side.handle())->Get(0);
2557 switch (cc) {
2558 case less:
2559 dest->Goto(left_value < right_value);
2560 break;
2561 case equal:
2562 dest->Goto(left_value == right_value);
2563 break;
2564 case greater_equal:
2565 dest->Goto(left_value >= right_value);
2566 break;
2567 default:
2568 UNREACHABLE();
2569 }
2570 } else {
2571 // Only one side is a constant 1 character string.
2572 // If left side is a constant 1-character string, reverse the operands.
2573 // Since one side is a constant string, conversion order does not matter.
2574 if (left_side_constant_1_char_string) {
2575 Result temp = left_side;
2576 left_side = right_side;
2577 right_side = temp;
2578 cc = ReverseCondition(cc);
2579 // This may reintroduce greater or less_equal as the value of cc.
2580 // CompareStub and the inline code both support all values of cc.
2581 }
2582 // Implement comparison against a constant string, inlining the case
2583 // where both sides are strings.
2584 left_side.ToRegister();
2585
2586 // Here we split control flow to the stub call and inlined cases
2587 // before finally splitting it to the control destination. We use
2588 // a jump target and branching to duplicate the virtual frame at
2589 // the first split. We manually handle the off-frame references
2590 // by reconstituting them on the non-fall-through path.
2591 JumpTarget is_not_string, is_string;
2592 Register left_reg = left_side.reg();
2593 Handle<Object> right_val = right_side.handle();
Steve Block6ded16b2010-05-10 14:33:55 +01002594 ASSERT(StringShape(String::cast(*right_val)).IsSymbol());
Leon Clarkee46be812010-01-19 14:06:41 +00002595 __ test(left_side.reg(), Immediate(kSmiTagMask));
2596 is_not_string.Branch(zero, &left_side);
2597 Result temp = allocator_->Allocate();
2598 ASSERT(temp.is_valid());
2599 __ mov(temp.reg(),
2600 FieldOperand(left_side.reg(), HeapObject::kMapOffset));
2601 __ movzx_b(temp.reg(),
2602 FieldOperand(temp.reg(), Map::kInstanceTypeOffset));
2603 // If we are testing for equality then make use of the symbol shortcut.
2604 // Check if the right left hand side has the same type as the left hand
2605 // side (which is always a symbol).
2606 if (cc == equal) {
2607 Label not_a_symbol;
2608 ASSERT(kSymbolTag != 0);
2609 // Ensure that no non-strings have the symbol bit set.
2610 ASSERT(kNotStringTag + kIsSymbolMask > LAST_TYPE);
2611 __ test(temp.reg(), Immediate(kIsSymbolMask)); // Test the symbol bit.
2612 __ j(zero, &not_a_symbol);
2613 // They are symbols, so do identity compare.
2614 __ cmp(left_side.reg(), right_side.handle());
2615 dest->true_target()->Branch(equal);
2616 dest->false_target()->Branch(not_equal);
2617 __ bind(&not_a_symbol);
2618 }
Steve Block6ded16b2010-05-10 14:33:55 +01002619 // Call the compare stub if the left side is not a flat ascii string.
Leon Clarkee46be812010-01-19 14:06:41 +00002620 __ and_(temp.reg(),
2621 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
2622 __ cmp(temp.reg(), kStringTag | kSeqStringTag | kAsciiStringTag);
2623 temp.Unuse();
2624 is_string.Branch(equal, &left_side);
2625
2626 // Setup and call the compare stub.
2627 is_not_string.Bind(&left_side);
2628 CompareStub stub(cc, strict, kCantBothBeNaN);
2629 Result result = frame_->CallStub(&stub, &left_side, &right_side);
2630 result.ToRegister();
2631 __ cmp(result.reg(), 0);
2632 result.Unuse();
2633 dest->true_target()->Branch(cc);
2634 dest->false_target()->Jump();
2635
2636 is_string.Bind(&left_side);
Steve Block6ded16b2010-05-10 14:33:55 +01002637 // left_side is a sequential ASCII string.
Leon Clarkee46be812010-01-19 14:06:41 +00002638 left_side = Result(left_reg);
2639 right_side = Result(right_val);
Leon Clarkee46be812010-01-19 14:06:41 +00002640 // Test string equality and comparison.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002641 Label comparison_done;
Leon Clarkee46be812010-01-19 14:06:41 +00002642 if (cc == equal) {
Leon Clarkee46be812010-01-19 14:06:41 +00002643 __ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Steve Block6ded16b2010-05-10 14:33:55 +01002644 Immediate(Smi::FromInt(1)));
Leon Clarkee46be812010-01-19 14:06:41 +00002645 __ j(not_equal, &comparison_done);
2646 uint8_t char_value =
Steve Block6ded16b2010-05-10 14:33:55 +01002647 static_cast<uint8_t>(String::cast(*right_val)->Get(0));
Leon Clarkee46be812010-01-19 14:06:41 +00002648 __ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
2649 char_value);
Leon Clarkee46be812010-01-19 14:06:41 +00002650 } else {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002651 __ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
2652 Immediate(Smi::FromInt(1)));
2653 // If the length is 0 then the jump is taken and the flags
2654 // correctly represent being less than the one-character string.
2655 __ j(below, &comparison_done);
Steve Block6ded16b2010-05-10 14:33:55 +01002656 // Compare the first character of the string with the
2657 // constant 1-character string.
Leon Clarkee46be812010-01-19 14:06:41 +00002658 uint8_t char_value =
Steve Block6ded16b2010-05-10 14:33:55 +01002659 static_cast<uint8_t>(String::cast(*right_val)->Get(0));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002660 __ cmpb(FieldOperand(left_side.reg(), SeqAsciiString::kHeaderSize),
2661 char_value);
2662 __ j(not_equal, &comparison_done);
Leon Clarkee46be812010-01-19 14:06:41 +00002663 // If the first character is the same then the long string sorts after
2664 // the short one.
2665 __ cmp(FieldOperand(left_side.reg(), String::kLengthOffset),
Steve Block6ded16b2010-05-10 14:33:55 +01002666 Immediate(Smi::FromInt(1)));
Leon Clarkee46be812010-01-19 14:06:41 +00002667 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002668 __ bind(&comparison_done);
Leon Clarkee46be812010-01-19 14:06:41 +00002669 left_side.Unuse();
2670 right_side.Unuse();
2671 dest->Split(cc);
2672 }
2673 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002674 // Neither side is a constant Smi, constant 1-char string or constant null.
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002675 // If either side is a non-smi constant, or known to be a heap number,
2676 // skip the smi check.
Steve Blocka7e24c12009-10-30 11:49:00 +00002677 bool known_non_smi =
2678 (left_side.is_constant() && !left_side.handle()->IsSmi()) ||
Steve Block6ded16b2010-05-10 14:33:55 +01002679 (right_side.is_constant() && !right_side.handle()->IsSmi()) ||
2680 left_side.type_info().IsDouble() ||
2681 right_side.type_info().IsDouble();
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002682
Leon Clarkee46be812010-01-19 14:06:41 +00002683 NaNInformation nan_info =
2684 (CouldBeNaN(left_side) && CouldBeNaN(right_side)) ?
2685 kBothCouldBeNaN :
2686 kCantBothBeNaN;
Steve Block6ded16b2010-05-10 14:33:55 +01002687
2688 // Inline number comparison handling any combination of smi's and heap
2689 // numbers if:
2690 // code is in a loop
2691 // the compare operation is different from equal
2692 // compare is not a for-loop comparison
2693 // The reason for excluding equal is that it will most likely be done
2694 // with smi's (not heap numbers) and the code to comparing smi's is inlined
2695 // separately. The same reason applies for for-loop comparison which will
2696 // also most likely be smi comparisons.
2697 bool is_loop_condition = (node->AsExpression() != NULL)
2698 && node->AsExpression()->is_loop_condition();
2699 bool inline_number_compare =
2700 loop_nesting() > 0 && cc != equal && !is_loop_condition;
2701
2702 // Left and right needed in registers for the following code.
Steve Blocka7e24c12009-10-30 11:49:00 +00002703 left_side.ToRegister();
2704 right_side.ToRegister();
2705
2706 if (known_non_smi) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002707 // Inlined equality check:
2708 // If at least one of the objects is not NaN, then if the objects
2709 // are identical, they are equal.
Steve Block6ded16b2010-05-10 14:33:55 +01002710 if (nan_info == kCantBothBeNaN && cc == equal) {
2711 __ cmp(left_side.reg(), Operand(right_side.reg()));
2712 dest->true_target()->Branch(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +00002713 }
Steve Block6ded16b2010-05-10 14:33:55 +01002714
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002715 // Inlined number comparison:
Steve Block6ded16b2010-05-10 14:33:55 +01002716 if (inline_number_compare) {
2717 GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
2718 }
2719
2720 // End of in-line compare, call out to the compare stub. Don't include
2721 // number comparison in the stub if it was inlined.
2722 CompareStub stub(cc, strict, nan_info, !inline_number_compare);
2723 Result answer = frame_->CallStub(&stub, &left_side, &right_side);
2724 __ test(answer.reg(), Operand(answer.reg()));
Steve Blocka7e24c12009-10-30 11:49:00 +00002725 answer.Unuse();
2726 dest->Split(cc);
2727 } else {
2728 // Here we split control flow to the stub call and inlined cases
2729 // before finally splitting it to the control destination. We use
2730 // a jump target and branching to duplicate the virtual frame at
2731 // the first split. We manually handle the off-frame references
2732 // by reconstituting them on the non-fall-through path.
2733 JumpTarget is_smi;
2734 Register left_reg = left_side.reg();
2735 Register right_reg = right_side.reg();
2736
Steve Block6ded16b2010-05-10 14:33:55 +01002737 // In-line check for comparing two smis.
Steve Blocka7e24c12009-10-30 11:49:00 +00002738 Result temp = allocator_->Allocate();
2739 ASSERT(temp.is_valid());
2740 __ mov(temp.reg(), left_side.reg());
2741 __ or_(temp.reg(), Operand(right_side.reg()));
2742 __ test(temp.reg(), Immediate(kSmiTagMask));
2743 temp.Unuse();
2744 is_smi.Branch(zero, taken);
Steve Block6ded16b2010-05-10 14:33:55 +01002745
2746 // Inline the equality check if both operands can't be a NaN. If both
2747 // objects are the same they are equal.
2748 if (nan_info == kCantBothBeNaN && cc == equal) {
2749 __ cmp(left_side.reg(), Operand(right_side.reg()));
2750 dest->true_target()->Branch(equal);
2751 }
2752
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002753 // Inlined number comparison:
Steve Block6ded16b2010-05-10 14:33:55 +01002754 if (inline_number_compare) {
2755 GenerateInlineNumberComparison(&left_side, &right_side, cc, dest);
2756 }
2757
2758 // End of in-line compare, call out to the compare stub. Don't include
2759 // number comparison in the stub if it was inlined.
2760 CompareStub stub(cc, strict, nan_info, !inline_number_compare);
Steve Blocka7e24c12009-10-30 11:49:00 +00002761 Result answer = frame_->CallStub(&stub, &left_side, &right_side);
Kristian Monsen25f61362010-05-21 11:50:48 +01002762 __ test(answer.reg(), Operand(answer.reg()));
Steve Blocka7e24c12009-10-30 11:49:00 +00002763 answer.Unuse();
2764 dest->true_target()->Branch(cc);
2765 dest->false_target()->Jump();
2766
2767 is_smi.Bind();
2768 left_side = Result(left_reg);
2769 right_side = Result(right_reg);
2770 __ cmp(left_side.reg(), Operand(right_side.reg()));
2771 right_side.Unuse();
2772 left_side.Unuse();
2773 dest->Split(cc);
2774 }
2775 }
2776}
2777
2778
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002779void CodeGenerator::ConstantSmiComparison(Condition cc,
2780 bool strict,
2781 ControlDestination* dest,
2782 Result* left_side,
2783 Result* right_side,
2784 bool left_side_constant_smi,
2785 bool right_side_constant_smi,
2786 bool is_loop_condition) {
2787 if (left_side_constant_smi && right_side_constant_smi) {
2788 // Trivial case, comparing two constants.
2789 int left_value = Smi::cast(*left_side->handle())->value();
2790 int right_value = Smi::cast(*right_side->handle())->value();
2791 switch (cc) {
2792 case less:
2793 dest->Goto(left_value < right_value);
2794 break;
2795 case equal:
2796 dest->Goto(left_value == right_value);
2797 break;
2798 case greater_equal:
2799 dest->Goto(left_value >= right_value);
2800 break;
2801 default:
2802 UNREACHABLE();
2803 }
2804 } else {
2805 // Only one side is a constant Smi.
2806 // If left side is a constant Smi, reverse the operands.
2807 // Since one side is a constant Smi, conversion order does not matter.
2808 if (left_side_constant_smi) {
2809 Result* temp = left_side;
2810 left_side = right_side;
2811 right_side = temp;
2812 cc = ReverseCondition(cc);
2813 // This may re-introduce greater or less_equal as the value of cc.
2814 // CompareStub and the inline code both support all values of cc.
2815 }
2816 // Implement comparison against a constant Smi, inlining the case
2817 // where both sides are Smis.
2818 left_side->ToRegister();
2819 Register left_reg = left_side->reg();
2820 Handle<Object> right_val = right_side->handle();
2821
2822 if (left_side->is_smi()) {
2823 if (FLAG_debug_code) {
2824 __ AbortIfNotSmi(left_reg);
2825 }
2826 // Test smi equality and comparison by signed int comparison.
2827 if (IsUnsafeSmi(right_side->handle())) {
2828 right_side->ToRegister();
2829 __ cmp(left_reg, Operand(right_side->reg()));
2830 } else {
2831 __ cmp(Operand(left_reg), Immediate(right_side->handle()));
2832 }
2833 left_side->Unuse();
2834 right_side->Unuse();
2835 dest->Split(cc);
2836 } else {
2837 // Only the case where the left side could possibly be a non-smi is left.
2838 JumpTarget is_smi;
2839 if (cc == equal) {
2840 // We can do the equality comparison before the smi check.
2841 __ cmp(Operand(left_reg), Immediate(right_side->handle()));
2842 dest->true_target()->Branch(equal);
2843 __ test(left_reg, Immediate(kSmiTagMask));
2844 dest->false_target()->Branch(zero);
2845 } else {
2846 // Do the smi check, then the comparison.
2847 JumpTarget is_not_smi;
2848 __ test(left_reg, Immediate(kSmiTagMask));
2849 is_smi.Branch(zero, left_side, right_side);
2850 }
2851
2852 // Jump or fall through to here if we are comparing a non-smi to a
2853 // constant smi. If the non-smi is a heap number and this is not
2854 // a loop condition, inline the floating point code.
2855 if (!is_loop_condition && CpuFeatures::IsSupported(SSE2)) {
2856 // Right side is a constant smi and left side has been checked
2857 // not to be a smi.
2858 CpuFeatures::Scope use_sse2(SSE2);
2859 JumpTarget not_number;
2860 __ cmp(FieldOperand(left_reg, HeapObject::kMapOffset),
2861 Immediate(Factory::heap_number_map()));
2862 not_number.Branch(not_equal, left_side);
2863 __ movdbl(xmm1,
2864 FieldOperand(left_reg, HeapNumber::kValueOffset));
2865 int value = Smi::cast(*right_val)->value();
2866 if (value == 0) {
2867 __ xorpd(xmm0, xmm0);
2868 } else {
2869 Result temp = allocator()->Allocate();
2870 __ mov(temp.reg(), Immediate(value));
2871 __ cvtsi2sd(xmm0, Operand(temp.reg()));
2872 temp.Unuse();
2873 }
2874 __ ucomisd(xmm1, xmm0);
2875 // Jump to builtin for NaN.
2876 not_number.Branch(parity_even, left_side);
2877 left_side->Unuse();
2878 dest->true_target()->Branch(DoubleCondition(cc));
2879 dest->false_target()->Jump();
2880 not_number.Bind(left_side);
2881 }
2882
2883 // Setup and call the compare stub.
2884 CompareStub stub(cc, strict, kCantBothBeNaN);
2885 Result result = frame_->CallStub(&stub, left_side, right_side);
2886 result.ToRegister();
2887 __ test(result.reg(), Operand(result.reg()));
2888 result.Unuse();
2889 if (cc == equal) {
2890 dest->Split(cc);
2891 } else {
2892 dest->true_target()->Branch(cc);
2893 dest->false_target()->Jump();
2894
2895 // It is important for performance for this case to be at the end.
2896 is_smi.Bind(left_side, right_side);
2897 if (IsUnsafeSmi(right_side->handle())) {
2898 right_side->ToRegister();
2899 __ cmp(left_reg, Operand(right_side->reg()));
2900 } else {
2901 __ cmp(Operand(left_reg), Immediate(right_side->handle()));
2902 }
2903 left_side->Unuse();
2904 right_side->Unuse();
2905 dest->Split(cc);
2906 }
2907 }
2908 }
2909}
2910
2911
Steve Block6ded16b2010-05-10 14:33:55 +01002912// Check that the comparison operand is a number. Jump to not_numbers jump
2913// target passing the left and right result if the operand is not a number.
2914static void CheckComparisonOperand(MacroAssembler* masm_,
2915 Result* operand,
2916 Result* left_side,
2917 Result* right_side,
2918 JumpTarget* not_numbers) {
2919 // Perform check if operand is not known to be a number.
2920 if (!operand->type_info().IsNumber()) {
2921 Label done;
2922 __ test(operand->reg(), Immediate(kSmiTagMask));
2923 __ j(zero, &done);
2924 __ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
2925 Immediate(Factory::heap_number_map()));
2926 not_numbers->Branch(not_equal, left_side, right_side, not_taken);
2927 __ bind(&done);
2928 }
2929}
2930
2931
2932// Load a comparison operand to the FPU stack. This assumes that the operand has
2933// already been checked and is a number.
2934static void LoadComparisonOperand(MacroAssembler* masm_,
2935 Result* operand) {
2936 Label done;
2937 if (operand->type_info().IsDouble()) {
2938 // Operand is known to be a heap number, just load it.
2939 __ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
2940 } else if (operand->type_info().IsSmi()) {
2941 // Operand is known to be a smi. Convert it to double and keep the original
2942 // smi.
2943 __ SmiUntag(operand->reg());
2944 __ push(operand->reg());
2945 __ fild_s(Operand(esp, 0));
2946 __ pop(operand->reg());
2947 __ SmiTag(operand->reg());
2948 } else {
2949 // Operand type not known, check for smi otherwise assume heap number.
2950 Label smi;
2951 __ test(operand->reg(), Immediate(kSmiTagMask));
2952 __ j(zero, &smi);
2953 __ fld_d(FieldOperand(operand->reg(), HeapNumber::kValueOffset));
2954 __ jmp(&done);
2955 __ bind(&smi);
2956 __ SmiUntag(operand->reg());
2957 __ push(operand->reg());
2958 __ fild_s(Operand(esp, 0));
2959 __ pop(operand->reg());
2960 __ SmiTag(operand->reg());
2961 __ jmp(&done);
2962 }
2963 __ bind(&done);
2964}
2965
2966
2967// Load a comparison operand into into a XMM register. Jump to not_numbers jump
2968// target passing the left and right result if the operand is not a number.
2969static void LoadComparisonOperandSSE2(MacroAssembler* masm_,
2970 Result* operand,
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002971 XMMRegister xmm_reg,
Steve Block6ded16b2010-05-10 14:33:55 +01002972 Result* left_side,
2973 Result* right_side,
2974 JumpTarget* not_numbers) {
2975 Label done;
2976 if (operand->type_info().IsDouble()) {
2977 // Operand is known to be a heap number, just load it.
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002978 __ movdbl(xmm_reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01002979 } else if (operand->type_info().IsSmi()) {
2980 // Operand is known to be a smi. Convert it to double and keep the original
2981 // smi.
2982 __ SmiUntag(operand->reg());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002983 __ cvtsi2sd(xmm_reg, Operand(operand->reg()));
Steve Block6ded16b2010-05-10 14:33:55 +01002984 __ SmiTag(operand->reg());
2985 } else {
2986 // Operand type not known, check for smi or heap number.
2987 Label smi;
2988 __ test(operand->reg(), Immediate(kSmiTagMask));
2989 __ j(zero, &smi);
2990 if (!operand->type_info().IsNumber()) {
2991 __ cmp(FieldOperand(operand->reg(), HeapObject::kMapOffset),
2992 Immediate(Factory::heap_number_map()));
2993 not_numbers->Branch(not_equal, left_side, right_side, taken);
2994 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002995 __ movdbl(xmm_reg, FieldOperand(operand->reg(), HeapNumber::kValueOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01002996 __ jmp(&done);
2997
2998 __ bind(&smi);
2999 // Comvert smi to float and keep the original smi.
3000 __ SmiUntag(operand->reg());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003001 __ cvtsi2sd(xmm_reg, Operand(operand->reg()));
Steve Block6ded16b2010-05-10 14:33:55 +01003002 __ SmiTag(operand->reg());
3003 __ jmp(&done);
3004 }
3005 __ bind(&done);
3006}
3007
3008
3009void CodeGenerator::GenerateInlineNumberComparison(Result* left_side,
3010 Result* right_side,
3011 Condition cc,
3012 ControlDestination* dest) {
3013 ASSERT(left_side->is_register());
3014 ASSERT(right_side->is_register());
3015
3016 JumpTarget not_numbers;
3017 if (CpuFeatures::IsSupported(SSE2)) {
3018 CpuFeatures::Scope use_sse2(SSE2);
3019
3020 // Load left and right operand into registers xmm0 and xmm1 and compare.
3021 LoadComparisonOperandSSE2(masm_, left_side, xmm0, left_side, right_side,
3022 &not_numbers);
3023 LoadComparisonOperandSSE2(masm_, right_side, xmm1, left_side, right_side,
3024 &not_numbers);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003025 __ ucomisd(xmm0, xmm1);
Steve Block6ded16b2010-05-10 14:33:55 +01003026 } else {
3027 Label check_right, compare;
3028
3029 // Make sure that both comparison operands are numbers.
3030 CheckComparisonOperand(masm_, left_side, left_side, right_side,
3031 &not_numbers);
3032 CheckComparisonOperand(masm_, right_side, left_side, right_side,
3033 &not_numbers);
3034
3035 // Load right and left operand to FPU stack and compare.
3036 LoadComparisonOperand(masm_, right_side);
3037 LoadComparisonOperand(masm_, left_side);
3038 __ FCmp();
3039 }
3040
3041 // Bail out if a NaN is involved.
3042 not_numbers.Branch(parity_even, left_side, right_side, not_taken);
3043
3044 // Split to destination targets based on comparison.
3045 left_side->Unuse();
3046 right_side->Unuse();
3047 dest->true_target()->Branch(DoubleCondition(cc));
3048 dest->false_target()->Jump();
3049
3050 not_numbers.Bind(left_side, right_side);
3051}
3052
3053
Steve Blocka7e24c12009-10-30 11:49:00 +00003054// Call the function just below TOS on the stack with the given
3055// arguments. The receiver is the TOS.
3056void CodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
Leon Clarkee46be812010-01-19 14:06:41 +00003057 CallFunctionFlags flags,
Steve Blocka7e24c12009-10-30 11:49:00 +00003058 int position) {
3059 // Push the arguments ("left-to-right") on the stack.
3060 int arg_count = args->length();
3061 for (int i = 0; i < arg_count; i++) {
3062 Load(args->at(i));
Leon Clarkef7060e22010-06-03 12:02:55 +01003063 frame_->SpillTop();
Steve Blocka7e24c12009-10-30 11:49:00 +00003064 }
3065
3066 // Record the position for debugging purposes.
3067 CodeForSourcePosition(position);
3068
3069 // Use the shared code stub to call the function.
3070 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
Leon Clarkee46be812010-01-19 14:06:41 +00003071 CallFunctionStub call_function(arg_count, in_loop, flags);
Steve Blocka7e24c12009-10-30 11:49:00 +00003072 Result answer = frame_->CallStub(&call_function, arg_count + 1);
3073 // Restore context and replace function on the stack with the
3074 // result of the stub invocation.
3075 frame_->RestoreContextRegister();
3076 frame_->SetElementAt(0, &answer);
3077}
3078
3079
Leon Clarked91b9f72010-01-27 17:25:45 +00003080void CodeGenerator::CallApplyLazy(Expression* applicand,
Steve Blocka7e24c12009-10-30 11:49:00 +00003081 Expression* receiver,
3082 VariableProxy* arguments,
3083 int position) {
Leon Clarked91b9f72010-01-27 17:25:45 +00003084 // An optimized implementation of expressions of the form
3085 // x.apply(y, arguments).
3086 // If the arguments object of the scope has not been allocated,
3087 // and x.apply is Function.prototype.apply, this optimization
3088 // just copies y and the arguments of the current function on the
3089 // stack, as receiver and arguments, and calls x.
3090 // In the implementation comments, we call x the applicand
3091 // and y the receiver.
Steve Blocka7e24c12009-10-30 11:49:00 +00003092 ASSERT(ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION);
3093 ASSERT(arguments->IsArguments());
3094
Leon Clarked91b9f72010-01-27 17:25:45 +00003095 // Load applicand.apply onto the stack. This will usually
Steve Blocka7e24c12009-10-30 11:49:00 +00003096 // give us a megamorphic load site. Not super, but it works.
Leon Clarked91b9f72010-01-27 17:25:45 +00003097 Load(applicand);
Andrei Popescu402d9372010-02-26 13:31:12 +00003098 frame()->Dup();
Leon Clarked91b9f72010-01-27 17:25:45 +00003099 Handle<String> name = Factory::LookupAsciiSymbol("apply");
3100 frame()->Push(name);
3101 Result answer = frame()->CallLoadIC(RelocInfo::CODE_TARGET);
3102 __ nop();
3103 frame()->Push(&answer);
Steve Blocka7e24c12009-10-30 11:49:00 +00003104
3105 // Load the receiver and the existing arguments object onto the
3106 // expression stack. Avoid allocating the arguments object here.
3107 Load(receiver);
Leon Clarkef7060e22010-06-03 12:02:55 +01003108 LoadFromSlot(scope()->arguments()->var()->slot(), NOT_INSIDE_TYPEOF);
Steve Blocka7e24c12009-10-30 11:49:00 +00003109
3110 // Emit the source position information after having loaded the
3111 // receiver and the arguments.
3112 CodeForSourcePosition(position);
Leon Clarked91b9f72010-01-27 17:25:45 +00003113 // Contents of frame at this point:
3114 // Frame[0]: arguments object of the current function or the hole.
3115 // Frame[1]: receiver
3116 // Frame[2]: applicand.apply
3117 // Frame[3]: applicand.
Steve Blocka7e24c12009-10-30 11:49:00 +00003118
3119 // Check if the arguments object has been lazily allocated
3120 // already. If so, just use that instead of copying the arguments
3121 // from the stack. This also deals with cases where a local variable
3122 // named 'arguments' has been introduced.
3123 frame_->Dup();
3124 Result probe = frame_->Pop();
Leon Clarked91b9f72010-01-27 17:25:45 +00003125 { VirtualFrame::SpilledScope spilled_scope;
3126 Label slow, done;
3127 bool try_lazy = true;
3128 if (probe.is_constant()) {
3129 try_lazy = probe.handle()->IsTheHole();
3130 } else {
3131 __ cmp(Operand(probe.reg()), Immediate(Factory::the_hole_value()));
3132 probe.Unuse();
3133 __ j(not_equal, &slow);
3134 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003135
Leon Clarked91b9f72010-01-27 17:25:45 +00003136 if (try_lazy) {
3137 Label build_args;
3138 // Get rid of the arguments object probe.
3139 frame_->Drop(); // Can be called on a spilled frame.
3140 // Stack now has 3 elements on it.
3141 // Contents of stack at this point:
3142 // esp[0]: receiver
3143 // esp[1]: applicand.apply
3144 // esp[2]: applicand.
Steve Blocka7e24c12009-10-30 11:49:00 +00003145
Leon Clarked91b9f72010-01-27 17:25:45 +00003146 // Check that the receiver really is a JavaScript object.
3147 __ mov(eax, Operand(esp, 0));
3148 __ test(eax, Immediate(kSmiTagMask));
3149 __ j(zero, &build_args);
Steve Blocka7e24c12009-10-30 11:49:00 +00003150 // We allow all JSObjects including JSFunctions. As long as
3151 // JS_FUNCTION_TYPE is the last instance type and it is right
3152 // after LAST_JS_OBJECT_TYPE, we do not have to check the upper
3153 // bound.
3154 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
3155 ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
Leon Clarked91b9f72010-01-27 17:25:45 +00003156 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
3157 __ j(below, &build_args);
Steve Blocka7e24c12009-10-30 11:49:00 +00003158
Leon Clarked91b9f72010-01-27 17:25:45 +00003159 // Check that applicand.apply is Function.prototype.apply.
3160 __ mov(eax, Operand(esp, kPointerSize));
3161 __ test(eax, Immediate(kSmiTagMask));
3162 __ j(zero, &build_args);
3163 __ CmpObjectType(eax, JS_FUNCTION_TYPE, ecx);
3164 __ j(not_equal, &build_args);
3165 __ mov(ecx, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
Leon Clarkeeab96aa2010-01-27 16:31:12 +00003166 Handle<Code> apply_code(Builtins::builtin(Builtins::FunctionApply));
Leon Clarked91b9f72010-01-27 17:25:45 +00003167 __ cmp(FieldOperand(ecx, SharedFunctionInfo::kCodeOffset),
Leon Clarkeeab96aa2010-01-27 16:31:12 +00003168 Immediate(apply_code));
Leon Clarked91b9f72010-01-27 17:25:45 +00003169 __ j(not_equal, &build_args);
3170
3171 // Check that applicand is a function.
3172 __ mov(edi, Operand(esp, 2 * kPointerSize));
3173 __ test(edi, Immediate(kSmiTagMask));
3174 __ j(zero, &build_args);
3175 __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
3176 __ j(not_equal, &build_args);
3177
3178 // Copy the arguments to this function possibly from the
3179 // adaptor frame below it.
3180 Label invoke, adapted;
3181 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3182 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
3183 __ cmp(Operand(ecx),
3184 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3185 __ j(equal, &adapted);
3186
3187 // No arguments adaptor frame. Copy fixed number of arguments.
Andrei Popescu31002712010-02-23 13:46:05 +00003188 __ mov(eax, Immediate(scope()->num_parameters()));
3189 for (int i = 0; i < scope()->num_parameters(); i++) {
Leon Clarked91b9f72010-01-27 17:25:45 +00003190 __ push(frame_->ParameterAt(i));
3191 }
3192 __ jmp(&invoke);
3193
3194 // Arguments adaptor frame present. Copy arguments from there, but
3195 // avoid copying too many arguments to avoid stack overflows.
3196 __ bind(&adapted);
3197 static const uint32_t kArgumentsLimit = 1 * KB;
3198 __ mov(eax, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
3199 __ SmiUntag(eax);
3200 __ mov(ecx, Operand(eax));
3201 __ cmp(eax, kArgumentsLimit);
3202 __ j(above, &build_args);
3203
3204 // Loop through the arguments pushing them onto the execution
3205 // stack. We don't inform the virtual frame of the push, so we don't
3206 // have to worry about getting rid of the elements from the virtual
3207 // frame.
3208 Label loop;
3209 // ecx is a small non-negative integer, due to the test above.
3210 __ test(ecx, Operand(ecx));
3211 __ j(zero, &invoke);
3212 __ bind(&loop);
3213 __ push(Operand(edx, ecx, times_pointer_size, 1 * kPointerSize));
3214 __ dec(ecx);
3215 __ j(not_zero, &loop);
3216
3217 // Invoke the function.
3218 __ bind(&invoke);
3219 ParameterCount actual(eax);
3220 __ InvokeFunction(edi, actual, CALL_FUNCTION);
3221 // Drop applicand.apply and applicand from the stack, and push
3222 // the result of the function call, but leave the spilled frame
3223 // unchanged, with 3 elements, so it is correct when we compile the
3224 // slow-case code.
3225 __ add(Operand(esp), Immediate(2 * kPointerSize));
3226 __ push(eax);
3227 // Stack now has 1 element:
3228 // esp[0]: result
3229 __ jmp(&done);
3230
3231 // Slow-case: Allocate the arguments object since we know it isn't
3232 // there, and fall-through to the slow-case where we call
3233 // applicand.apply.
3234 __ bind(&build_args);
3235 // Stack now has 3 elements, because we have jumped from where:
3236 // esp[0]: receiver
3237 // esp[1]: applicand.apply
3238 // esp[2]: applicand.
3239
3240 // StoreArgumentsObject requires a correct frame, and may modify it.
3241 Result arguments_object = StoreArgumentsObject(false);
3242 frame_->SpillAll();
3243 arguments_object.ToRegister();
3244 frame_->EmitPush(arguments_object.reg());
3245 arguments_object.Unuse();
3246 // Stack and frame now have 4 elements.
3247 __ bind(&slow);
Leon Clarkeeab96aa2010-01-27 16:31:12 +00003248 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003249
Leon Clarked91b9f72010-01-27 17:25:45 +00003250 // Generic computation of x.apply(y, args) with no special optimization.
3251 // Flip applicand.apply and applicand on the stack, so
3252 // applicand looks like the receiver of the applicand.apply call.
3253 // Then process it as a normal function call.
3254 __ mov(eax, Operand(esp, 3 * kPointerSize));
3255 __ mov(ebx, Operand(esp, 2 * kPointerSize));
3256 __ mov(Operand(esp, 2 * kPointerSize), eax);
3257 __ mov(Operand(esp, 3 * kPointerSize), ebx);
Leon Clarkeeab96aa2010-01-27 16:31:12 +00003258
Leon Clarked91b9f72010-01-27 17:25:45 +00003259 CallFunctionStub call_function(2, NOT_IN_LOOP, NO_CALL_FUNCTION_FLAGS);
3260 Result res = frame_->CallStub(&call_function, 3);
3261 // The function and its two arguments have been dropped.
3262 frame_->Drop(1); // Drop the receiver as well.
3263 res.ToRegister();
3264 frame_->EmitPush(res.reg());
3265 // Stack now has 1 element:
3266 // esp[0]: result
3267 if (try_lazy) __ bind(&done);
3268 } // End of spilled scope.
3269 // Restore the context register after a call.
Steve Blocka7e24c12009-10-30 11:49:00 +00003270 frame_->RestoreContextRegister();
3271}
3272
3273
3274class DeferredStackCheck: public DeferredCode {
3275 public:
3276 DeferredStackCheck() {
3277 set_comment("[ DeferredStackCheck");
3278 }
3279
3280 virtual void Generate();
3281};
3282
3283
3284void DeferredStackCheck::Generate() {
3285 StackCheckStub stub;
3286 __ CallStub(&stub);
3287}
3288
3289
3290void CodeGenerator::CheckStack() {
Steve Blockd0582a62009-12-15 09:54:21 +00003291 DeferredStackCheck* deferred = new DeferredStackCheck;
3292 ExternalReference stack_limit =
3293 ExternalReference::address_of_stack_limit();
3294 __ cmp(esp, Operand::StaticVariable(stack_limit));
3295 deferred->Branch(below);
3296 deferred->BindExit();
Steve Blocka7e24c12009-10-30 11:49:00 +00003297}
3298
3299
3300void CodeGenerator::VisitAndSpill(Statement* statement) {
3301 ASSERT(in_spilled_code());
3302 set_in_spilled_code(false);
3303 Visit(statement);
3304 if (frame_ != NULL) {
3305 frame_->SpillAll();
3306 }
3307 set_in_spilled_code(true);
3308}
3309
3310
3311void CodeGenerator::VisitStatementsAndSpill(ZoneList<Statement*>* statements) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003312#ifdef DEBUG
3313 int original_height = frame_->height();
3314#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003315 ASSERT(in_spilled_code());
3316 set_in_spilled_code(false);
3317 VisitStatements(statements);
3318 if (frame_ != NULL) {
3319 frame_->SpillAll();
3320 }
3321 set_in_spilled_code(true);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003322
3323 ASSERT(!has_valid_frame() || frame_->height() == original_height);
Steve Blocka7e24c12009-10-30 11:49:00 +00003324}
3325
3326
3327void CodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003328#ifdef DEBUG
3329 int original_height = frame_->height();
3330#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003331 ASSERT(!in_spilled_code());
3332 for (int i = 0; has_valid_frame() && i < statements->length(); i++) {
3333 Visit(statements->at(i));
3334 }
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003335 ASSERT(!has_valid_frame() || frame_->height() == original_height);
Steve Blocka7e24c12009-10-30 11:49:00 +00003336}
3337
3338
3339void CodeGenerator::VisitBlock(Block* node) {
3340 ASSERT(!in_spilled_code());
3341 Comment cmnt(masm_, "[ Block");
3342 CodeForStatementPosition(node);
3343 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
3344 VisitStatements(node->statements());
3345 if (node->break_target()->is_linked()) {
3346 node->break_target()->Bind();
3347 }
3348 node->break_target()->Unuse();
3349}
3350
3351
3352void CodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
3353 // Call the runtime to declare the globals. The inevitable call
3354 // will sync frame elements to memory anyway, so we do it eagerly to
3355 // allow us to push the arguments directly into place.
3356 frame_->SyncRange(0, frame_->element_count() - 1);
3357
Steve Block3ce2e202009-11-05 08:53:23 +00003358 frame_->EmitPush(esi); // The context is the first argument.
Steve Blocka7e24c12009-10-30 11:49:00 +00003359 frame_->EmitPush(Immediate(pairs));
Steve Blocka7e24c12009-10-30 11:49:00 +00003360 frame_->EmitPush(Immediate(Smi::FromInt(is_eval() ? 1 : 0)));
3361 Result ignored = frame_->CallRuntime(Runtime::kDeclareGlobals, 3);
3362 // Return value is ignored.
3363}
3364
3365
3366void CodeGenerator::VisitDeclaration(Declaration* node) {
3367 Comment cmnt(masm_, "[ Declaration");
3368 Variable* var = node->proxy()->var();
3369 ASSERT(var != NULL); // must have been resolved
3370 Slot* slot = var->slot();
3371
3372 // If it was not possible to allocate the variable at compile time,
3373 // we need to "declare" it at runtime to make sure it actually
3374 // exists in the local context.
3375 if (slot != NULL && slot->type() == Slot::LOOKUP) {
3376 // Variables with a "LOOKUP" slot were introduced as non-locals
3377 // during variable resolution and must have mode DYNAMIC.
3378 ASSERT(var->is_dynamic());
3379 // For now, just do a runtime call. Sync the virtual frame eagerly
3380 // so we can simply push the arguments into place.
3381 frame_->SyncRange(0, frame_->element_count() - 1);
3382 frame_->EmitPush(esi);
3383 frame_->EmitPush(Immediate(var->name()));
3384 // Declaration nodes are always introduced in one of two modes.
3385 ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
3386 PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
3387 frame_->EmitPush(Immediate(Smi::FromInt(attr)));
3388 // Push initial value, if any.
3389 // Note: For variables we must not push an initial value (such as
3390 // 'undefined') because we may have a (legal) redeclaration and we
3391 // must not destroy the current value.
3392 if (node->mode() == Variable::CONST) {
3393 frame_->EmitPush(Immediate(Factory::the_hole_value()));
3394 } else if (node->fun() != NULL) {
3395 Load(node->fun());
3396 } else {
3397 frame_->EmitPush(Immediate(Smi::FromInt(0))); // no initial value!
3398 }
3399 Result ignored = frame_->CallRuntime(Runtime::kDeclareContextSlot, 4);
3400 // Ignore the return value (declarations are statements).
3401 return;
3402 }
3403
3404 ASSERT(!var->is_global());
3405
3406 // If we have a function or a constant, we need to initialize the variable.
3407 Expression* val = NULL;
3408 if (node->mode() == Variable::CONST) {
3409 val = new Literal(Factory::the_hole_value());
3410 } else {
3411 val = node->fun(); // NULL if we don't have a function
3412 }
3413
3414 if (val != NULL) {
3415 {
3416 // Set the initial value.
3417 Reference target(this, node->proxy());
3418 Load(val);
3419 target.SetValue(NOT_CONST_INIT);
3420 // The reference is removed from the stack (preserving TOS) when
3421 // it goes out of scope.
3422 }
3423 // Get rid of the assigned value (declarations are statements).
3424 frame_->Drop();
3425 }
3426}
3427
3428
3429void CodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
3430 ASSERT(!in_spilled_code());
3431 Comment cmnt(masm_, "[ ExpressionStatement");
3432 CodeForStatementPosition(node);
3433 Expression* expression = node->expression();
3434 expression->MarkAsStatement();
3435 Load(expression);
3436 // Remove the lingering expression result from the top of stack.
3437 frame_->Drop();
3438}
3439
3440
3441void CodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
3442 ASSERT(!in_spilled_code());
3443 Comment cmnt(masm_, "// EmptyStatement");
3444 CodeForStatementPosition(node);
3445 // nothing to do
3446}
3447
3448
3449void CodeGenerator::VisitIfStatement(IfStatement* node) {
3450 ASSERT(!in_spilled_code());
3451 Comment cmnt(masm_, "[ IfStatement");
3452 // Generate different code depending on which parts of the if statement
3453 // are present or not.
3454 bool has_then_stm = node->HasThenStatement();
3455 bool has_else_stm = node->HasElseStatement();
3456
3457 CodeForStatementPosition(node);
3458 JumpTarget exit;
3459 if (has_then_stm && has_else_stm) {
3460 JumpTarget then;
3461 JumpTarget else_;
3462 ControlDestination dest(&then, &else_, true);
Steve Blockd0582a62009-12-15 09:54:21 +00003463 LoadCondition(node->condition(), &dest, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00003464
3465 if (dest.false_was_fall_through()) {
3466 // The else target was bound, so we compile the else part first.
3467 Visit(node->else_statement());
3468
3469 // We may have dangling jumps to the then part.
3470 if (then.is_linked()) {
3471 if (has_valid_frame()) exit.Jump();
3472 then.Bind();
3473 Visit(node->then_statement());
3474 }
3475 } else {
3476 // The then target was bound, so we compile the then part first.
3477 Visit(node->then_statement());
3478
3479 if (else_.is_linked()) {
3480 if (has_valid_frame()) exit.Jump();
3481 else_.Bind();
3482 Visit(node->else_statement());
3483 }
3484 }
3485
3486 } else if (has_then_stm) {
3487 ASSERT(!has_else_stm);
3488 JumpTarget then;
3489 ControlDestination dest(&then, &exit, true);
Steve Blockd0582a62009-12-15 09:54:21 +00003490 LoadCondition(node->condition(), &dest, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00003491
3492 if (dest.false_was_fall_through()) {
3493 // The exit label was bound. We may have dangling jumps to the
3494 // then part.
3495 if (then.is_linked()) {
3496 exit.Unuse();
3497 exit.Jump();
3498 then.Bind();
3499 Visit(node->then_statement());
3500 }
3501 } else {
3502 // The then label was bound.
3503 Visit(node->then_statement());
3504 }
3505
3506 } else if (has_else_stm) {
3507 ASSERT(!has_then_stm);
3508 JumpTarget else_;
3509 ControlDestination dest(&exit, &else_, false);
Steve Blockd0582a62009-12-15 09:54:21 +00003510 LoadCondition(node->condition(), &dest, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00003511
3512 if (dest.true_was_fall_through()) {
3513 // The exit label was bound. We may have dangling jumps to the
3514 // else part.
3515 if (else_.is_linked()) {
3516 exit.Unuse();
3517 exit.Jump();
3518 else_.Bind();
3519 Visit(node->else_statement());
3520 }
3521 } else {
3522 // The else label was bound.
3523 Visit(node->else_statement());
3524 }
3525
3526 } else {
3527 ASSERT(!has_then_stm && !has_else_stm);
3528 // We only care about the condition's side effects (not its value
3529 // or control flow effect). LoadCondition is called without
3530 // forcing control flow.
3531 ControlDestination dest(&exit, &exit, true);
Steve Blockd0582a62009-12-15 09:54:21 +00003532 LoadCondition(node->condition(), &dest, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003533 if (!dest.is_used()) {
3534 // We got a value on the frame rather than (or in addition to)
3535 // control flow.
3536 frame_->Drop();
3537 }
3538 }
3539
3540 if (exit.is_linked()) {
3541 exit.Bind();
3542 }
3543}
3544
3545
3546void CodeGenerator::VisitContinueStatement(ContinueStatement* node) {
3547 ASSERT(!in_spilled_code());
3548 Comment cmnt(masm_, "[ ContinueStatement");
3549 CodeForStatementPosition(node);
3550 node->target()->continue_target()->Jump();
3551}
3552
3553
3554void CodeGenerator::VisitBreakStatement(BreakStatement* node) {
3555 ASSERT(!in_spilled_code());
3556 Comment cmnt(masm_, "[ BreakStatement");
3557 CodeForStatementPosition(node);
3558 node->target()->break_target()->Jump();
3559}
3560
3561
3562void CodeGenerator::VisitReturnStatement(ReturnStatement* node) {
3563 ASSERT(!in_spilled_code());
3564 Comment cmnt(masm_, "[ ReturnStatement");
3565
3566 CodeForStatementPosition(node);
3567 Load(node->expression());
3568 Result return_value = frame_->Pop();
Steve Blockd0582a62009-12-15 09:54:21 +00003569 masm()->WriteRecordedPositions();
Steve Blocka7e24c12009-10-30 11:49:00 +00003570 if (function_return_is_shadowed_) {
3571 function_return_.Jump(&return_value);
3572 } else {
3573 frame_->PrepareForReturn();
3574 if (function_return_.is_bound()) {
3575 // If the function return label is already bound we reuse the
3576 // code by jumping to the return site.
3577 function_return_.Jump(&return_value);
3578 } else {
3579 function_return_.Bind(&return_value);
3580 GenerateReturnSequence(&return_value);
3581 }
3582 }
3583}
3584
3585
3586void CodeGenerator::GenerateReturnSequence(Result* return_value) {
3587 // The return value is a live (but not currently reference counted)
3588 // reference to eax. This is safe because the current frame does not
3589 // contain a reference to eax (it is prepared for the return by spilling
3590 // all registers).
3591 if (FLAG_trace) {
3592 frame_->Push(return_value);
3593 *return_value = frame_->CallRuntime(Runtime::kTraceExit, 1);
3594 }
3595 return_value->ToRegister(eax);
3596
3597 // Add a label for checking the size of the code used for returning.
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003598#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00003599 Label check_exit_codesize;
3600 masm_->bind(&check_exit_codesize);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003601#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003602
3603 // Leave the frame and return popping the arguments and the
3604 // receiver.
3605 frame_->Exit();
Andrei Popescu31002712010-02-23 13:46:05 +00003606 masm_->ret((scope()->num_parameters() + 1) * kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003607 DeleteFrame();
3608
3609#ifdef ENABLE_DEBUGGER_SUPPORT
3610 // Check that the size of the code used for returning matches what is
3611 // expected by the debugger.
Steve Blockd0582a62009-12-15 09:54:21 +00003612 ASSERT_EQ(Assembler::kJSReturnSequenceLength,
Steve Blocka7e24c12009-10-30 11:49:00 +00003613 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize));
3614#endif
3615}
3616
3617
3618void CodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
3619 ASSERT(!in_spilled_code());
3620 Comment cmnt(masm_, "[ WithEnterStatement");
3621 CodeForStatementPosition(node);
3622 Load(node->expression());
3623 Result context;
3624 if (node->is_catch_block()) {
3625 context = frame_->CallRuntime(Runtime::kPushCatchContext, 1);
3626 } else {
3627 context = frame_->CallRuntime(Runtime::kPushContext, 1);
3628 }
3629
3630 // Update context local.
3631 frame_->SaveContextRegister();
3632
3633 // Verify that the runtime call result and esi agree.
3634 if (FLAG_debug_code) {
3635 __ cmp(context.reg(), Operand(esi));
3636 __ Assert(equal, "Runtime::NewContext should end up in esi");
3637 }
3638}
3639
3640
3641void CodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
3642 ASSERT(!in_spilled_code());
3643 Comment cmnt(masm_, "[ WithExitStatement");
3644 CodeForStatementPosition(node);
3645 // Pop context.
3646 __ mov(esi, ContextOperand(esi, Context::PREVIOUS_INDEX));
3647 // Update context local.
3648 frame_->SaveContextRegister();
3649}
3650
3651
3652void CodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
3653 ASSERT(!in_spilled_code());
3654 Comment cmnt(masm_, "[ SwitchStatement");
3655 CodeForStatementPosition(node);
3656 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
3657
3658 // Compile the switch value.
3659 Load(node->tag());
3660
3661 ZoneList<CaseClause*>* cases = node->cases();
3662 int length = cases->length();
3663 CaseClause* default_clause = NULL;
3664
3665 JumpTarget next_test;
3666 // Compile the case label expressions and comparisons. Exit early
3667 // if a comparison is unconditionally true. The target next_test is
3668 // bound before the loop in order to indicate control flow to the
3669 // first comparison.
3670 next_test.Bind();
3671 for (int i = 0; i < length && !next_test.is_unused(); i++) {
3672 CaseClause* clause = cases->at(i);
3673 // The default is not a test, but remember it for later.
3674 if (clause->is_default()) {
3675 default_clause = clause;
3676 continue;
3677 }
3678
3679 Comment cmnt(masm_, "[ Case comparison");
3680 // We recycle the same target next_test for each test. Bind it if
3681 // the previous test has not done so and then unuse it for the
3682 // loop.
3683 if (next_test.is_linked()) {
3684 next_test.Bind();
3685 }
3686 next_test.Unuse();
3687
3688 // Duplicate the switch value.
3689 frame_->Dup();
3690
3691 // Compile the label expression.
3692 Load(clause->label());
3693
3694 // Compare and branch to the body if true or the next test if
3695 // false. Prefer the next test as a fall through.
3696 ControlDestination dest(clause->body_target(), &next_test, false);
Leon Clarkee46be812010-01-19 14:06:41 +00003697 Comparison(node, equal, true, &dest);
Steve Blocka7e24c12009-10-30 11:49:00 +00003698
3699 // If the comparison fell through to the true target, jump to the
3700 // actual body.
3701 if (dest.true_was_fall_through()) {
3702 clause->body_target()->Unuse();
3703 clause->body_target()->Jump();
3704 }
3705 }
3706
3707 // If there was control flow to a next test from the last one
3708 // compiled, compile a jump to the default or break target.
3709 if (!next_test.is_unused()) {
3710 if (next_test.is_linked()) {
3711 next_test.Bind();
3712 }
3713 // Drop the switch value.
3714 frame_->Drop();
3715 if (default_clause != NULL) {
3716 default_clause->body_target()->Jump();
3717 } else {
3718 node->break_target()->Jump();
3719 }
3720 }
3721
Steve Blocka7e24c12009-10-30 11:49:00 +00003722 // The last instruction emitted was a jump, either to the default
3723 // clause or the break target, or else to a case body from the loop
3724 // that compiles the tests.
3725 ASSERT(!has_valid_frame());
3726 // Compile case bodies as needed.
3727 for (int i = 0; i < length; i++) {
3728 CaseClause* clause = cases->at(i);
3729
3730 // There are two ways to reach the body: from the corresponding
3731 // test or as the fall through of the previous body.
3732 if (clause->body_target()->is_linked() || has_valid_frame()) {
3733 if (clause->body_target()->is_linked()) {
3734 if (has_valid_frame()) {
3735 // If we have both a jump to the test and a fall through, put
3736 // a jump on the fall through path to avoid the dropping of
3737 // the switch value on the test path. The exception is the
3738 // default which has already had the switch value dropped.
3739 if (clause->is_default()) {
3740 clause->body_target()->Bind();
3741 } else {
3742 JumpTarget body;
3743 body.Jump();
3744 clause->body_target()->Bind();
3745 frame_->Drop();
3746 body.Bind();
3747 }
3748 } else {
3749 // No fall through to worry about.
3750 clause->body_target()->Bind();
3751 if (!clause->is_default()) {
3752 frame_->Drop();
3753 }
3754 }
3755 } else {
3756 // Otherwise, we have only fall through.
3757 ASSERT(has_valid_frame());
3758 }
3759
3760 // We are now prepared to compile the body.
3761 Comment cmnt(masm_, "[ Case body");
3762 VisitStatements(clause->statements());
3763 }
3764 clause->body_target()->Unuse();
3765 }
3766
3767 // We may not have a valid frame here so bind the break target only
3768 // if needed.
3769 if (node->break_target()->is_linked()) {
3770 node->break_target()->Bind();
3771 }
3772 node->break_target()->Unuse();
3773}
3774
3775
Steve Block3ce2e202009-11-05 08:53:23 +00003776void CodeGenerator::VisitDoWhileStatement(DoWhileStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003777 ASSERT(!in_spilled_code());
Steve Block3ce2e202009-11-05 08:53:23 +00003778 Comment cmnt(masm_, "[ DoWhileStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00003779 CodeForStatementPosition(node);
3780 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
Steve Block3ce2e202009-11-05 08:53:23 +00003781 JumpTarget body(JumpTarget::BIDIRECTIONAL);
3782 IncrementLoopNesting();
Steve Blocka7e24c12009-10-30 11:49:00 +00003783
Steve Block3ce2e202009-11-05 08:53:23 +00003784 ConditionAnalysis info = AnalyzeCondition(node->cond());
3785 // Label the top of the loop for the backward jump if necessary.
3786 switch (info) {
3787 case ALWAYS_TRUE:
3788 // Use the continue target.
3789 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
3790 node->continue_target()->Bind();
3791 break;
3792 case ALWAYS_FALSE:
3793 // No need to label it.
3794 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
3795 break;
3796 case DONT_KNOW:
3797 // Continue is the test, so use the backward body target.
3798 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
3799 body.Bind();
3800 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00003801 }
3802
Steve Block3ce2e202009-11-05 08:53:23 +00003803 CheckStack(); // TODO(1222600): ignore if body contains calls.
3804 Visit(node->body());
Steve Blocka7e24c12009-10-30 11:49:00 +00003805
Steve Block3ce2e202009-11-05 08:53:23 +00003806 // Compile the test.
3807 switch (info) {
3808 case ALWAYS_TRUE:
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003809 // If control flow can fall off the end of the body, jump back
3810 // to the top and bind the break target at the exit.
Steve Block3ce2e202009-11-05 08:53:23 +00003811 if (has_valid_frame()) {
3812 node->continue_target()->Jump();
Steve Blocka7e24c12009-10-30 11:49:00 +00003813 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003814 if (node->break_target()->is_linked()) {
3815 node->break_target()->Bind();
3816 }
3817 break;
Steve Block3ce2e202009-11-05 08:53:23 +00003818 case ALWAYS_FALSE:
3819 // We may have had continues or breaks in the body.
3820 if (node->continue_target()->is_linked()) {
3821 node->continue_target()->Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +00003822 }
Steve Block3ce2e202009-11-05 08:53:23 +00003823 if (node->break_target()->is_linked()) {
3824 node->break_target()->Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +00003825 }
Steve Block3ce2e202009-11-05 08:53:23 +00003826 break;
3827 case DONT_KNOW:
3828 // We have to compile the test expression if it can be reached by
3829 // control flow falling out of the body or via continue.
3830 if (node->continue_target()->is_linked()) {
3831 node->continue_target()->Bind();
3832 }
3833 if (has_valid_frame()) {
Steve Blockd0582a62009-12-15 09:54:21 +00003834 Comment cmnt(masm_, "[ DoWhileCondition");
3835 CodeForDoWhileConditionPosition(node);
Steve Block3ce2e202009-11-05 08:53:23 +00003836 ControlDestination dest(&body, node->break_target(), false);
Steve Blockd0582a62009-12-15 09:54:21 +00003837 LoadCondition(node->cond(), &dest, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00003838 }
Steve Block3ce2e202009-11-05 08:53:23 +00003839 if (node->break_target()->is_linked()) {
3840 node->break_target()->Bind();
3841 }
3842 break;
3843 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003844
Steve Block3ce2e202009-11-05 08:53:23 +00003845 DecrementLoopNesting();
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003846 node->continue_target()->Unuse();
3847 node->break_target()->Unuse();
Steve Block3ce2e202009-11-05 08:53:23 +00003848}
Steve Blocka7e24c12009-10-30 11:49:00 +00003849
Steve Block3ce2e202009-11-05 08:53:23 +00003850
3851void CodeGenerator::VisitWhileStatement(WhileStatement* node) {
3852 ASSERT(!in_spilled_code());
3853 Comment cmnt(masm_, "[ WhileStatement");
3854 CodeForStatementPosition(node);
3855
3856 // If the condition is always false and has no side effects, we do not
3857 // need to compile anything.
3858 ConditionAnalysis info = AnalyzeCondition(node->cond());
3859 if (info == ALWAYS_FALSE) return;
3860
3861 // Do not duplicate conditions that may have function literal
3862 // subexpressions. This can cause us to compile the function literal
3863 // twice.
3864 bool test_at_bottom = !node->may_have_function_literal();
3865 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
3866 IncrementLoopNesting();
3867 JumpTarget body;
3868 if (test_at_bottom) {
3869 body.set_direction(JumpTarget::BIDIRECTIONAL);
3870 }
3871
3872 // Based on the condition analysis, compile the test as necessary.
3873 switch (info) {
3874 case ALWAYS_TRUE:
3875 // We will not compile the test expression. Label the top of the
3876 // loop with the continue target.
3877 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
3878 node->continue_target()->Bind();
3879 break;
3880 case DONT_KNOW: {
3881 if (test_at_bottom) {
3882 // Continue is the test at the bottom, no need to label the test
3883 // at the top. The body is a backward target.
3884 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
3885 } else {
3886 // Label the test at the top as the continue target. The body
3887 // is a forward-only target.
3888 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
3889 node->continue_target()->Bind();
3890 }
3891 // Compile the test with the body as the true target and preferred
3892 // fall-through and with the break target as the false target.
3893 ControlDestination dest(&body, node->break_target(), true);
Steve Blockd0582a62009-12-15 09:54:21 +00003894 LoadCondition(node->cond(), &dest, true);
Steve Block3ce2e202009-11-05 08:53:23 +00003895
3896 if (dest.false_was_fall_through()) {
3897 // If we got the break target as fall-through, the test may have
3898 // been unconditionally false (if there are no jumps to the
3899 // body).
3900 if (!body.is_linked()) {
3901 DecrementLoopNesting();
3902 return;
3903 }
3904
3905 // Otherwise, jump around the body on the fall through and then
3906 // bind the body target.
3907 node->break_target()->Unuse();
3908 node->break_target()->Jump();
3909 body.Bind();
3910 }
3911 break;
3912 }
3913 case ALWAYS_FALSE:
3914 UNREACHABLE();
3915 break;
3916 }
3917
3918 CheckStack(); // TODO(1222600): ignore if body contains calls.
3919 Visit(node->body());
3920
3921 // Based on the condition analysis, compile the backward jump as
3922 // necessary.
3923 switch (info) {
3924 case ALWAYS_TRUE:
3925 // The loop body has been labeled with the continue target.
3926 if (has_valid_frame()) {
3927 node->continue_target()->Jump();
3928 }
3929 break;
3930 case DONT_KNOW:
3931 if (test_at_bottom) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003932 // If we have chosen to recompile the test at the bottom,
3933 // then it is the continue target.
Steve Blocka7e24c12009-10-30 11:49:00 +00003934 if (node->continue_target()->is_linked()) {
3935 node->continue_target()->Bind();
3936 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003937 if (has_valid_frame()) {
Steve Block3ce2e202009-11-05 08:53:23 +00003938 // The break target is the fall-through (body is a backward
3939 // jump from here and thus an invalid fall-through).
3940 ControlDestination dest(&body, node->break_target(), false);
Steve Blockd0582a62009-12-15 09:54:21 +00003941 LoadCondition(node->cond(), &dest, true);
Steve Block3ce2e202009-11-05 08:53:23 +00003942 }
3943 } else {
3944 // If we have chosen not to recompile the test at the bottom,
3945 // jump back to the one at the top.
3946 if (has_valid_frame()) {
3947 node->continue_target()->Jump();
Steve Blocka7e24c12009-10-30 11:49:00 +00003948 }
3949 }
Steve Block3ce2e202009-11-05 08:53:23 +00003950 break;
3951 case ALWAYS_FALSE:
3952 UNREACHABLE();
3953 break;
3954 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003955
Steve Block3ce2e202009-11-05 08:53:23 +00003956 // The break target may be already bound (by the condition), or there
3957 // may not be a valid frame. Bind it only if needed.
3958 if (node->break_target()->is_linked()) {
3959 node->break_target()->Bind();
3960 }
3961 DecrementLoopNesting();
3962}
3963
3964
Steve Block6ded16b2010-05-10 14:33:55 +01003965void CodeGenerator::SetTypeForStackSlot(Slot* slot, TypeInfo info) {
3966 ASSERT(slot->type() == Slot::LOCAL || slot->type() == Slot::PARAMETER);
3967 if (slot->type() == Slot::LOCAL) {
3968 frame_->SetTypeForLocalAt(slot->index(), info);
3969 } else {
3970 frame_->SetTypeForParamAt(slot->index(), info);
3971 }
3972 if (FLAG_debug_code && info.IsSmi()) {
3973 if (slot->type() == Slot::LOCAL) {
3974 frame_->PushLocalAt(slot->index());
3975 } else {
3976 frame_->PushParameterAt(slot->index());
3977 }
3978 Result var = frame_->Pop();
3979 var.ToRegister();
3980 __ AbortIfNotSmi(var.reg());
3981 }
3982}
3983
3984
Steve Block3ce2e202009-11-05 08:53:23 +00003985void CodeGenerator::VisitForStatement(ForStatement* node) {
3986 ASSERT(!in_spilled_code());
3987 Comment cmnt(masm_, "[ ForStatement");
3988 CodeForStatementPosition(node);
3989
3990 // Compile the init expression if present.
3991 if (node->init() != NULL) {
3992 Visit(node->init());
3993 }
3994
3995 // If the condition is always false and has no side effects, we do not
3996 // need to compile anything else.
3997 ConditionAnalysis info = AnalyzeCondition(node->cond());
3998 if (info == ALWAYS_FALSE) return;
3999
4000 // Do not duplicate conditions that may have function literal
4001 // subexpressions. This can cause us to compile the function literal
4002 // twice.
4003 bool test_at_bottom = !node->may_have_function_literal();
4004 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
4005 IncrementLoopNesting();
4006
4007 // Target for backward edge if no test at the bottom, otherwise
4008 // unused.
4009 JumpTarget loop(JumpTarget::BIDIRECTIONAL);
4010
4011 // Target for backward edge if there is a test at the bottom,
4012 // otherwise used as target for test at the top.
4013 JumpTarget body;
4014 if (test_at_bottom) {
4015 body.set_direction(JumpTarget::BIDIRECTIONAL);
4016 }
4017
4018 // Based on the condition analysis, compile the test as necessary.
4019 switch (info) {
4020 case ALWAYS_TRUE:
4021 // We will not compile the test expression. Label the top of the
4022 // loop.
4023 if (node->next() == NULL) {
4024 // Use the continue target if there is no update expression.
4025 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
4026 node->continue_target()->Bind();
4027 } else {
4028 // Otherwise use the backward loop target.
4029 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
4030 loop.Bind();
4031 }
4032 break;
4033 case DONT_KNOW: {
4034 if (test_at_bottom) {
4035 // Continue is either the update expression or the test at the
4036 // bottom, no need to label the test at the top.
4037 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
4038 } else if (node->next() == NULL) {
4039 // We are not recompiling the test at the bottom and there is no
4040 // update expression.
4041 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
4042 node->continue_target()->Bind();
4043 } else {
4044 // We are not recompiling the test at the bottom and there is an
4045 // update expression.
4046 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
4047 loop.Bind();
4048 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004049
Steve Block3ce2e202009-11-05 08:53:23 +00004050 // Compile the test with the body as the true target and preferred
4051 // fall-through and with the break target as the false target.
4052 ControlDestination dest(&body, node->break_target(), true);
Steve Blockd0582a62009-12-15 09:54:21 +00004053 LoadCondition(node->cond(), &dest, true);
Steve Block3ce2e202009-11-05 08:53:23 +00004054
4055 if (dest.false_was_fall_through()) {
4056 // If we got the break target as fall-through, the test may have
4057 // been unconditionally false (if there are no jumps to the
4058 // body).
4059 if (!body.is_linked()) {
4060 DecrementLoopNesting();
4061 return;
4062 }
4063
4064 // Otherwise, jump around the body on the fall through and then
4065 // bind the body target.
4066 node->break_target()->Unuse();
4067 node->break_target()->Jump();
4068 body.Bind();
4069 }
4070 break;
4071 }
4072 case ALWAYS_FALSE:
4073 UNREACHABLE();
4074 break;
4075 }
4076
4077 CheckStack(); // TODO(1222600): ignore if body contains calls.
Steve Block6ded16b2010-05-10 14:33:55 +01004078
4079 // We know that the loop index is a smi if it is not modified in the
4080 // loop body and it is checked against a constant limit in the loop
4081 // condition. In this case, we reset the static type information of the
4082 // loop index to smi before compiling the body, the update expression, and
4083 // the bottom check of the loop condition.
4084 if (node->is_fast_smi_loop()) {
4085 // Set number type of the loop variable to smi.
4086 SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
4087 }
4088
Steve Block3ce2e202009-11-05 08:53:23 +00004089 Visit(node->body());
4090
4091 // If there is an update expression, compile it if necessary.
4092 if (node->next() != NULL) {
4093 if (node->continue_target()->is_linked()) {
4094 node->continue_target()->Bind();
4095 }
4096
4097 // Control can reach the update by falling out of the body or by a
4098 // continue.
4099 if (has_valid_frame()) {
4100 // Record the source position of the statement as this code which
4101 // is after the code for the body actually belongs to the loop
4102 // statement and not the body.
4103 CodeForStatementPosition(node);
4104 Visit(node->next());
4105 }
4106 }
4107
Steve Block6ded16b2010-05-10 14:33:55 +01004108 // Set the type of the loop variable to smi before compiling the test
4109 // expression if we are in a fast smi loop condition.
4110 if (node->is_fast_smi_loop() && has_valid_frame()) {
4111 // Set number type of the loop variable to smi.
4112 SetTypeForStackSlot(node->loop_variable()->slot(), TypeInfo::Smi());
4113 }
4114
Steve Block3ce2e202009-11-05 08:53:23 +00004115 // Based on the condition analysis, compile the backward jump as
4116 // necessary.
4117 switch (info) {
4118 case ALWAYS_TRUE:
4119 if (has_valid_frame()) {
4120 if (node->next() == NULL) {
4121 node->continue_target()->Jump();
4122 } else {
4123 loop.Jump();
4124 }
4125 }
4126 break;
4127 case DONT_KNOW:
4128 if (test_at_bottom) {
4129 if (node->continue_target()->is_linked()) {
4130 // We can have dangling jumps to the continue target if there
4131 // was no update expression.
4132 node->continue_target()->Bind();
4133 }
4134 // Control can reach the test at the bottom by falling out of
4135 // the body, by a continue in the body, or from the update
4136 // expression.
4137 if (has_valid_frame()) {
4138 // The break target is the fall-through (body is a backward
4139 // jump from here).
4140 ControlDestination dest(&body, node->break_target(), false);
Steve Blockd0582a62009-12-15 09:54:21 +00004141 LoadCondition(node->cond(), &dest, true);
Steve Block3ce2e202009-11-05 08:53:23 +00004142 }
4143 } else {
4144 // Otherwise, jump back to the test at the top.
Steve Blocka7e24c12009-10-30 11:49:00 +00004145 if (has_valid_frame()) {
4146 if (node->next() == NULL) {
4147 node->continue_target()->Jump();
4148 } else {
4149 loop.Jump();
4150 }
4151 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004152 }
4153 break;
Steve Block3ce2e202009-11-05 08:53:23 +00004154 case ALWAYS_FALSE:
4155 UNREACHABLE();
4156 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00004157 }
4158
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004159 // The break target may be already bound (by the condition), or there
4160 // may not be a valid frame. Bind it only if needed.
Steve Block3ce2e202009-11-05 08:53:23 +00004161 if (node->break_target()->is_linked()) {
4162 node->break_target()->Bind();
4163 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004164 DecrementLoopNesting();
Steve Blocka7e24c12009-10-30 11:49:00 +00004165}
4166
4167
4168void CodeGenerator::VisitForInStatement(ForInStatement* node) {
4169 ASSERT(!in_spilled_code());
4170 VirtualFrame::SpilledScope spilled_scope;
4171 Comment cmnt(masm_, "[ ForInStatement");
4172 CodeForStatementPosition(node);
4173
4174 JumpTarget primitive;
4175 JumpTarget jsobject;
4176 JumpTarget fixed_array;
4177 JumpTarget entry(JumpTarget::BIDIRECTIONAL);
4178 JumpTarget end_del_check;
4179 JumpTarget exit;
4180
4181 // Get the object to enumerate over (converted to JSObject).
4182 LoadAndSpill(node->enumerable());
4183
4184 // Both SpiderMonkey and kjs ignore null and undefined in contrast
4185 // to the specification. 12.6.4 mandates a call to ToObject.
4186 frame_->EmitPop(eax);
4187
4188 // eax: value to be iterated over
4189 __ cmp(eax, Factory::undefined_value());
4190 exit.Branch(equal);
4191 __ cmp(eax, Factory::null_value());
4192 exit.Branch(equal);
4193
4194 // Stack layout in body:
4195 // [iteration counter (smi)] <- slot 0
4196 // [length of array] <- slot 1
4197 // [FixedArray] <- slot 2
4198 // [Map or 0] <- slot 3
4199 // [Object] <- slot 4
4200
4201 // Check if enumerable is already a JSObject
4202 // eax: value to be iterated over
4203 __ test(eax, Immediate(kSmiTagMask));
4204 primitive.Branch(zero);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004205 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +00004206 jsobject.Branch(above_equal);
4207
4208 primitive.Bind();
4209 frame_->EmitPush(eax);
4210 frame_->InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION, 1);
4211 // function call returns the value in eax, which is where we want it below
4212
4213 jsobject.Bind();
4214 // Get the set of properties (as a FixedArray or Map).
4215 // eax: value to be iterated over
Steve Blockd0582a62009-12-15 09:54:21 +00004216 frame_->EmitPush(eax); // Push the object being iterated over.
Steve Blocka7e24c12009-10-30 11:49:00 +00004217
Steve Blockd0582a62009-12-15 09:54:21 +00004218 // Check cache validity in generated code. This is a fast case for
4219 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
4220 // guarantee cache validity, call the runtime system to check cache
4221 // validity or get the property names in a fixed array.
4222 JumpTarget call_runtime;
4223 JumpTarget loop(JumpTarget::BIDIRECTIONAL);
4224 JumpTarget check_prototype;
4225 JumpTarget use_cache;
4226 __ mov(ecx, eax);
4227 loop.Bind();
4228 // Check that there are no elements.
4229 __ mov(edx, FieldOperand(ecx, JSObject::kElementsOffset));
4230 __ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
4231 call_runtime.Branch(not_equal);
4232 // Check that instance descriptors are not empty so that we can
4233 // check for an enum cache. Leave the map in ebx for the subsequent
4234 // prototype load.
4235 __ mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));
4236 __ mov(edx, FieldOperand(ebx, Map::kInstanceDescriptorsOffset));
4237 __ cmp(Operand(edx), Immediate(Factory::empty_descriptor_array()));
4238 call_runtime.Branch(equal);
4239 // Check that there in an enum cache in the non-empty instance
4240 // descriptors. This is the case if the next enumeration index
4241 // field does not contain a smi.
4242 __ mov(edx, FieldOperand(edx, DescriptorArray::kEnumerationIndexOffset));
4243 __ test(edx, Immediate(kSmiTagMask));
4244 call_runtime.Branch(zero);
4245 // For all objects but the receiver, check that the cache is empty.
4246 __ cmp(ecx, Operand(eax));
4247 check_prototype.Branch(equal);
4248 __ mov(edx, FieldOperand(edx, DescriptorArray::kEnumCacheBridgeCacheOffset));
4249 __ cmp(Operand(edx), Immediate(Factory::empty_fixed_array()));
4250 call_runtime.Branch(not_equal);
4251 check_prototype.Bind();
4252 // Load the prototype from the map and loop if non-null.
4253 __ mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
4254 __ cmp(Operand(ecx), Immediate(Factory::null_value()));
4255 loop.Branch(not_equal);
4256 // The enum cache is valid. Load the map of the object being
4257 // iterated over and use the cache for the iteration.
4258 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
4259 use_cache.Jump();
4260
4261 call_runtime.Bind();
4262 // Call the runtime to get the property names for the object.
Steve Blocka7e24c12009-10-30 11:49:00 +00004263 frame_->EmitPush(eax); // push the Object (slot 4) for the runtime call
4264 frame_->CallRuntime(Runtime::kGetPropertyNamesFast, 1);
4265
Steve Blockd0582a62009-12-15 09:54:21 +00004266 // If we got a map from the runtime call, we can do a fast
4267 // modification check. Otherwise, we got a fixed array, and we have
4268 // to do a slow check.
Steve Blocka7e24c12009-10-30 11:49:00 +00004269 // eax: map or fixed array (result from call to
4270 // Runtime::kGetPropertyNamesFast)
4271 __ mov(edx, Operand(eax));
4272 __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
4273 __ cmp(ecx, Factory::meta_map());
4274 fixed_array.Branch(not_equal);
4275
Steve Blockd0582a62009-12-15 09:54:21 +00004276 use_cache.Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +00004277 // Get enum cache
Steve Blockd0582a62009-12-15 09:54:21 +00004278 // eax: map (either the result from a call to
4279 // Runtime::kGetPropertyNamesFast or has been fetched directly from
4280 // the object)
Steve Blocka7e24c12009-10-30 11:49:00 +00004281 __ mov(ecx, Operand(eax));
Steve Blockd0582a62009-12-15 09:54:21 +00004282
Steve Blocka7e24c12009-10-30 11:49:00 +00004283 __ mov(ecx, FieldOperand(ecx, Map::kInstanceDescriptorsOffset));
4284 // Get the bridge array held in the enumeration index field.
4285 __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumerationIndexOffset));
4286 // Get the cache from the bridge array.
4287 __ mov(edx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));
4288
4289 frame_->EmitPush(eax); // <- slot 3
4290 frame_->EmitPush(edx); // <- slot 2
4291 __ mov(eax, FieldOperand(edx, FixedArray::kLengthOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00004292 frame_->EmitPush(eax); // <- slot 1
4293 frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
4294 entry.Jump();
4295
4296 fixed_array.Bind();
4297 // eax: fixed array (result from call to Runtime::kGetPropertyNamesFast)
4298 frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 3
4299 frame_->EmitPush(eax); // <- slot 2
4300
4301 // Push the length of the array and the initial index onto the stack.
4302 __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00004303 frame_->EmitPush(eax); // <- slot 1
4304 frame_->EmitPush(Immediate(Smi::FromInt(0))); // <- slot 0
4305
4306 // Condition.
4307 entry.Bind();
4308 // Grab the current frame's height for the break and continue
4309 // targets only after all the state is pushed on the frame.
4310 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
4311 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
4312
4313 __ mov(eax, frame_->ElementAt(0)); // load the current count
4314 __ cmp(eax, frame_->ElementAt(1)); // compare to the array length
4315 node->break_target()->Branch(above_equal);
4316
4317 // Get the i'th entry of the array.
4318 __ mov(edx, frame_->ElementAt(2));
Kristian Monsen25f61362010-05-21 11:50:48 +01004319 __ mov(ebx, FixedArrayElementOperand(edx, eax));
Steve Blocka7e24c12009-10-30 11:49:00 +00004320
4321 // Get the expected map from the stack or a zero map in the
4322 // permanent slow case eax: current iteration count ebx: i'th entry
4323 // of the enum cache
4324 __ mov(edx, frame_->ElementAt(3));
4325 // Check if the expected map still matches that of the enumerable.
4326 // If not, we have to filter the key.
4327 // eax: current iteration count
4328 // ebx: i'th entry of the enum cache
4329 // edx: expected map value
4330 __ mov(ecx, frame_->ElementAt(4));
4331 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
4332 __ cmp(ecx, Operand(edx));
4333 end_del_check.Branch(equal);
4334
4335 // Convert the entry to a string (or null if it isn't a property anymore).
4336 frame_->EmitPush(frame_->ElementAt(4)); // push enumerable
4337 frame_->EmitPush(ebx); // push entry
4338 frame_->InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION, 2);
4339 __ mov(ebx, Operand(eax));
4340
4341 // If the property has been removed while iterating, we just skip it.
4342 __ cmp(ebx, Factory::null_value());
4343 node->continue_target()->Branch(equal);
4344
4345 end_del_check.Bind();
4346 // Store the entry in the 'each' expression and take another spin in the
4347 // loop. edx: i'th entry of the enum cache (or string there of)
4348 frame_->EmitPush(ebx);
4349 { Reference each(this, node->each());
4350 // Loading a reference may leave the frame in an unspilled state.
4351 frame_->SpillAll();
4352 if (!each.is_illegal()) {
4353 if (each.size() > 0) {
4354 frame_->EmitPush(frame_->ElementAt(each.size()));
Leon Clarked91b9f72010-01-27 17:25:45 +00004355 each.SetValue(NOT_CONST_INIT);
4356 frame_->Drop(2);
4357 } else {
4358 // If the reference was to a slot we rely on the convenient property
4359 // that it doesn't matter whether a value (eg, ebx pushed above) is
4360 // right on top of or right underneath a zero-sized reference.
4361 each.SetValue(NOT_CONST_INIT);
Steve Blocka7e24c12009-10-30 11:49:00 +00004362 frame_->Drop();
4363 }
4364 }
4365 }
4366 // Unloading a reference may leave the frame in an unspilled state.
4367 frame_->SpillAll();
4368
Steve Blocka7e24c12009-10-30 11:49:00 +00004369 // Body.
4370 CheckStack(); // TODO(1222600): ignore if body contains calls.
4371 VisitAndSpill(node->body());
4372
4373 // Next. Reestablish a spilled frame in case we are coming here via
4374 // a continue in the body.
4375 node->continue_target()->Bind();
4376 frame_->SpillAll();
4377 frame_->EmitPop(eax);
4378 __ add(Operand(eax), Immediate(Smi::FromInt(1)));
4379 frame_->EmitPush(eax);
4380 entry.Jump();
4381
4382 // Cleanup. No need to spill because VirtualFrame::Drop is safe for
4383 // any frame.
4384 node->break_target()->Bind();
4385 frame_->Drop(5);
4386
4387 // Exit.
4388 exit.Bind();
4389
4390 node->continue_target()->Unuse();
4391 node->break_target()->Unuse();
4392}
4393
4394
Steve Block3ce2e202009-11-05 08:53:23 +00004395void CodeGenerator::VisitTryCatchStatement(TryCatchStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004396 ASSERT(!in_spilled_code());
4397 VirtualFrame::SpilledScope spilled_scope;
Steve Block3ce2e202009-11-05 08:53:23 +00004398 Comment cmnt(masm_, "[ TryCatchStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00004399 CodeForStatementPosition(node);
4400
4401 JumpTarget try_block;
4402 JumpTarget exit;
4403
4404 try_block.Call();
4405 // --- Catch block ---
4406 frame_->EmitPush(eax);
4407
4408 // Store the caught exception in the catch variable.
Leon Clarkee46be812010-01-19 14:06:41 +00004409 Variable* catch_var = node->catch_var()->var();
4410 ASSERT(catch_var != NULL && catch_var->slot() != NULL);
4411 StoreToSlot(catch_var->slot(), NOT_CONST_INIT);
Steve Blocka7e24c12009-10-30 11:49:00 +00004412
4413 // Remove the exception from the stack.
4414 frame_->Drop();
4415
4416 VisitStatementsAndSpill(node->catch_block()->statements());
4417 if (has_valid_frame()) {
4418 exit.Jump();
4419 }
4420
4421
4422 // --- Try block ---
4423 try_block.Bind();
4424
4425 frame_->PushTryHandler(TRY_CATCH_HANDLER);
4426 int handler_height = frame_->height();
4427
4428 // Shadow the jump targets for all escapes from the try block, including
4429 // returns. During shadowing, the original target is hidden as the
4430 // ShadowTarget and operations on the original actually affect the
4431 // shadowing target.
4432 //
4433 // We should probably try to unify the escaping targets and the return
4434 // target.
4435 int nof_escapes = node->escaping_targets()->length();
4436 List<ShadowTarget*> shadows(1 + nof_escapes);
4437
4438 // Add the shadow target for the function return.
4439 static const int kReturnShadowIndex = 0;
4440 shadows.Add(new ShadowTarget(&function_return_));
4441 bool function_return_was_shadowed = function_return_is_shadowed_;
4442 function_return_is_shadowed_ = true;
4443 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
4444
4445 // Add the remaining shadow targets.
4446 for (int i = 0; i < nof_escapes; i++) {
4447 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
4448 }
4449
4450 // Generate code for the statements in the try block.
4451 VisitStatementsAndSpill(node->try_block()->statements());
4452
4453 // Stop the introduced shadowing and count the number of required unlinks.
4454 // After shadowing stops, the original targets are unshadowed and the
4455 // ShadowTargets represent the formerly shadowing targets.
4456 bool has_unlinks = false;
4457 for (int i = 0; i < shadows.length(); i++) {
4458 shadows[i]->StopShadowing();
4459 has_unlinks = has_unlinks || shadows[i]->is_linked();
4460 }
4461 function_return_is_shadowed_ = function_return_was_shadowed;
4462
4463 // Get an external reference to the handler address.
4464 ExternalReference handler_address(Top::k_handler_address);
4465
4466 // Make sure that there's nothing left on the stack above the
4467 // handler structure.
4468 if (FLAG_debug_code) {
4469 __ mov(eax, Operand::StaticVariable(handler_address));
4470 __ cmp(esp, Operand(eax));
4471 __ Assert(equal, "stack pointer should point to top handler");
4472 }
4473
4474 // If we can fall off the end of the try block, unlink from try chain.
4475 if (has_valid_frame()) {
4476 // The next handler address is on top of the frame. Unlink from
4477 // the handler list and drop the rest of this handler from the
4478 // frame.
4479 ASSERT(StackHandlerConstants::kNextOffset == 0);
4480 frame_->EmitPop(Operand::StaticVariable(handler_address));
4481 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
4482 if (has_unlinks) {
4483 exit.Jump();
4484 }
4485 }
4486
4487 // Generate unlink code for the (formerly) shadowing targets that
4488 // have been jumped to. Deallocate each shadow target.
4489 Result return_value;
4490 for (int i = 0; i < shadows.length(); i++) {
4491 if (shadows[i]->is_linked()) {
4492 // Unlink from try chain; be careful not to destroy the TOS if
4493 // there is one.
4494 if (i == kReturnShadowIndex) {
4495 shadows[i]->Bind(&return_value);
4496 return_value.ToRegister(eax);
4497 } else {
4498 shadows[i]->Bind();
4499 }
4500 // Because we can be jumping here (to spilled code) from
4501 // unspilled code, we need to reestablish a spilled frame at
4502 // this block.
4503 frame_->SpillAll();
4504
4505 // Reload sp from the top handler, because some statements that we
4506 // break from (eg, for...in) may have left stuff on the stack.
4507 __ mov(esp, Operand::StaticVariable(handler_address));
4508 frame_->Forget(frame_->height() - handler_height);
4509
4510 ASSERT(StackHandlerConstants::kNextOffset == 0);
4511 frame_->EmitPop(Operand::StaticVariable(handler_address));
4512 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
4513
4514 if (i == kReturnShadowIndex) {
4515 if (!function_return_is_shadowed_) frame_->PrepareForReturn();
4516 shadows[i]->other_target()->Jump(&return_value);
4517 } else {
4518 shadows[i]->other_target()->Jump();
4519 }
4520 }
4521 }
4522
4523 exit.Bind();
4524}
4525
4526
Steve Block3ce2e202009-11-05 08:53:23 +00004527void CodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004528 ASSERT(!in_spilled_code());
4529 VirtualFrame::SpilledScope spilled_scope;
Steve Block3ce2e202009-11-05 08:53:23 +00004530 Comment cmnt(masm_, "[ TryFinallyStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00004531 CodeForStatementPosition(node);
4532
4533 // State: Used to keep track of reason for entering the finally
4534 // block. Should probably be extended to hold information for
4535 // break/continue from within the try block.
4536 enum { FALLING, THROWING, JUMPING };
4537
4538 JumpTarget try_block;
4539 JumpTarget finally_block;
4540
4541 try_block.Call();
4542
4543 frame_->EmitPush(eax);
4544 // In case of thrown exceptions, this is where we continue.
4545 __ Set(ecx, Immediate(Smi::FromInt(THROWING)));
4546 finally_block.Jump();
4547
4548 // --- Try block ---
4549 try_block.Bind();
4550
4551 frame_->PushTryHandler(TRY_FINALLY_HANDLER);
4552 int handler_height = frame_->height();
4553
4554 // Shadow the jump targets for all escapes from the try block, including
4555 // returns. During shadowing, the original target is hidden as the
4556 // ShadowTarget and operations on the original actually affect the
4557 // shadowing target.
4558 //
4559 // We should probably try to unify the escaping targets and the return
4560 // target.
4561 int nof_escapes = node->escaping_targets()->length();
4562 List<ShadowTarget*> shadows(1 + nof_escapes);
4563
4564 // Add the shadow target for the function return.
4565 static const int kReturnShadowIndex = 0;
4566 shadows.Add(new ShadowTarget(&function_return_));
4567 bool function_return_was_shadowed = function_return_is_shadowed_;
4568 function_return_is_shadowed_ = true;
4569 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
4570
4571 // Add the remaining shadow targets.
4572 for (int i = 0; i < nof_escapes; i++) {
4573 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
4574 }
4575
4576 // Generate code for the statements in the try block.
4577 VisitStatementsAndSpill(node->try_block()->statements());
4578
4579 // Stop the introduced shadowing and count the number of required unlinks.
4580 // After shadowing stops, the original targets are unshadowed and the
4581 // ShadowTargets represent the formerly shadowing targets.
4582 int nof_unlinks = 0;
4583 for (int i = 0; i < shadows.length(); i++) {
4584 shadows[i]->StopShadowing();
4585 if (shadows[i]->is_linked()) nof_unlinks++;
4586 }
4587 function_return_is_shadowed_ = function_return_was_shadowed;
4588
4589 // Get an external reference to the handler address.
4590 ExternalReference handler_address(Top::k_handler_address);
4591
4592 // If we can fall off the end of the try block, unlink from the try
4593 // chain and set the state on the frame to FALLING.
4594 if (has_valid_frame()) {
4595 // The next handler address is on top of the frame.
4596 ASSERT(StackHandlerConstants::kNextOffset == 0);
4597 frame_->EmitPop(Operand::StaticVariable(handler_address));
4598 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
4599
4600 // Fake a top of stack value (unneeded when FALLING) and set the
4601 // state in ecx, then jump around the unlink blocks if any.
4602 frame_->EmitPush(Immediate(Factory::undefined_value()));
4603 __ Set(ecx, Immediate(Smi::FromInt(FALLING)));
4604 if (nof_unlinks > 0) {
4605 finally_block.Jump();
4606 }
4607 }
4608
4609 // Generate code to unlink and set the state for the (formerly)
4610 // shadowing targets that have been jumped to.
4611 for (int i = 0; i < shadows.length(); i++) {
4612 if (shadows[i]->is_linked()) {
4613 // If we have come from the shadowed return, the return value is
4614 // on the virtual frame. We must preserve it until it is
4615 // pushed.
4616 if (i == kReturnShadowIndex) {
4617 Result return_value;
4618 shadows[i]->Bind(&return_value);
4619 return_value.ToRegister(eax);
4620 } else {
4621 shadows[i]->Bind();
4622 }
4623 // Because we can be jumping here (to spilled code) from
4624 // unspilled code, we need to reestablish a spilled frame at
4625 // this block.
4626 frame_->SpillAll();
4627
4628 // Reload sp from the top handler, because some statements that
4629 // we break from (eg, for...in) may have left stuff on the
4630 // stack.
4631 __ mov(esp, Operand::StaticVariable(handler_address));
4632 frame_->Forget(frame_->height() - handler_height);
4633
4634 // Unlink this handler and drop it from the frame.
4635 ASSERT(StackHandlerConstants::kNextOffset == 0);
4636 frame_->EmitPop(Operand::StaticVariable(handler_address));
4637 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
4638
4639 if (i == kReturnShadowIndex) {
4640 // If this target shadowed the function return, materialize
4641 // the return value on the stack.
4642 frame_->EmitPush(eax);
4643 } else {
4644 // Fake TOS for targets that shadowed breaks and continues.
4645 frame_->EmitPush(Immediate(Factory::undefined_value()));
4646 }
4647 __ Set(ecx, Immediate(Smi::FromInt(JUMPING + i)));
4648 if (--nof_unlinks > 0) {
4649 // If this is not the last unlink block, jump around the next.
4650 finally_block.Jump();
4651 }
4652 }
4653 }
4654
4655 // --- Finally block ---
4656 finally_block.Bind();
4657
4658 // Push the state on the stack.
4659 frame_->EmitPush(ecx);
4660
4661 // We keep two elements on the stack - the (possibly faked) result
4662 // and the state - while evaluating the finally block.
4663 //
4664 // Generate code for the statements in the finally block.
4665 VisitStatementsAndSpill(node->finally_block()->statements());
4666
4667 if (has_valid_frame()) {
4668 // Restore state and return value or faked TOS.
4669 frame_->EmitPop(ecx);
4670 frame_->EmitPop(eax);
4671 }
4672
4673 // Generate code to jump to the right destination for all used
4674 // formerly shadowing targets. Deallocate each shadow target.
4675 for (int i = 0; i < shadows.length(); i++) {
4676 if (has_valid_frame() && shadows[i]->is_bound()) {
4677 BreakTarget* original = shadows[i]->other_target();
4678 __ cmp(Operand(ecx), Immediate(Smi::FromInt(JUMPING + i)));
4679 if (i == kReturnShadowIndex) {
4680 // The return value is (already) in eax.
4681 Result return_value = allocator_->Allocate(eax);
4682 ASSERT(return_value.is_valid());
4683 if (function_return_is_shadowed_) {
4684 original->Branch(equal, &return_value);
4685 } else {
4686 // Branch around the preparation for return which may emit
4687 // code.
4688 JumpTarget skip;
4689 skip.Branch(not_equal);
4690 frame_->PrepareForReturn();
4691 original->Jump(&return_value);
4692 skip.Bind();
4693 }
4694 } else {
4695 original->Branch(equal);
4696 }
4697 }
4698 }
4699
4700 if (has_valid_frame()) {
4701 // Check if we need to rethrow the exception.
4702 JumpTarget exit;
4703 __ cmp(Operand(ecx), Immediate(Smi::FromInt(THROWING)));
4704 exit.Branch(not_equal);
4705
4706 // Rethrow exception.
4707 frame_->EmitPush(eax); // undo pop from above
4708 frame_->CallRuntime(Runtime::kReThrow, 1);
4709
4710 // Done.
4711 exit.Bind();
4712 }
4713}
4714
4715
4716void CodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
4717 ASSERT(!in_spilled_code());
4718 Comment cmnt(masm_, "[ DebuggerStatement");
4719 CodeForStatementPosition(node);
4720#ifdef ENABLE_DEBUGGER_SUPPORT
4721 // Spill everything, even constants, to the frame.
4722 frame_->SpillAll();
Leon Clarke4515c472010-02-03 11:58:03 +00004723
Andrei Popescu402d9372010-02-26 13:31:12 +00004724 frame_->DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00004725 // Ignore the return value.
4726#endif
4727}
4728
4729
Steve Block6ded16b2010-05-10 14:33:55 +01004730Result CodeGenerator::InstantiateFunction(
4731 Handle<SharedFunctionInfo> function_info) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004732 // The inevitable call will sync frame elements to memory anyway, so
4733 // we do it eagerly to allow us to push the arguments directly into
4734 // place.
Andrei Popescu402d9372010-02-26 13:31:12 +00004735 frame()->SyncRange(0, frame()->element_count() - 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00004736
Leon Clarkee46be812010-01-19 14:06:41 +00004737 // Use the fast case closure allocation code that allocates in new
4738 // space for nested functions that don't need literals cloning.
Steve Block6ded16b2010-05-10 14:33:55 +01004739 if (scope()->is_function_scope() && function_info->num_literals() == 0) {
Leon Clarkee46be812010-01-19 14:06:41 +00004740 FastNewClosureStub stub;
Steve Block6ded16b2010-05-10 14:33:55 +01004741 frame()->EmitPush(Immediate(function_info));
Andrei Popescu402d9372010-02-26 13:31:12 +00004742 return frame()->CallStub(&stub, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00004743 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01004744 // Call the runtime to instantiate the function based on the
4745 // shared function info.
Andrei Popescu402d9372010-02-26 13:31:12 +00004746 frame()->EmitPush(esi);
Steve Block6ded16b2010-05-10 14:33:55 +01004747 frame()->EmitPush(Immediate(function_info));
Andrei Popescu402d9372010-02-26 13:31:12 +00004748 return frame()->CallRuntime(Runtime::kNewClosure, 2);
Leon Clarkee46be812010-01-19 14:06:41 +00004749 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004750}
4751
4752
4753void CodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
4754 Comment cmnt(masm_, "[ FunctionLiteral");
Steve Block6ded16b2010-05-10 14:33:55 +01004755 ASSERT(!in_safe_int32_mode());
4756 // Build the function info and instantiate it.
4757 Handle<SharedFunctionInfo> function_info =
4758 Compiler::BuildFunctionInfo(node, script(), this);
Steve Blocka7e24c12009-10-30 11:49:00 +00004759 // Check for stack-overflow exception.
4760 if (HasStackOverflow()) return;
Steve Block6ded16b2010-05-10 14:33:55 +01004761 Result result = InstantiateFunction(function_info);
Andrei Popescu402d9372010-02-26 13:31:12 +00004762 frame()->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004763}
4764
4765
Steve Block6ded16b2010-05-10 14:33:55 +01004766void CodeGenerator::VisitSharedFunctionInfoLiteral(
4767 SharedFunctionInfoLiteral* node) {
4768 ASSERT(!in_safe_int32_mode());
4769 Comment cmnt(masm_, "[ SharedFunctionInfoLiteral");
4770 Result result = InstantiateFunction(node->shared_function_info());
Andrei Popescu402d9372010-02-26 13:31:12 +00004771 frame()->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004772}
4773
4774
4775void CodeGenerator::VisitConditional(Conditional* node) {
4776 Comment cmnt(masm_, "[ Conditional");
Steve Block6ded16b2010-05-10 14:33:55 +01004777 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004778 JumpTarget then;
4779 JumpTarget else_;
4780 JumpTarget exit;
4781 ControlDestination dest(&then, &else_, true);
Steve Blockd0582a62009-12-15 09:54:21 +00004782 LoadCondition(node->condition(), &dest, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00004783
4784 if (dest.false_was_fall_through()) {
4785 // The else target was bound, so we compile the else part first.
Steve Blockd0582a62009-12-15 09:54:21 +00004786 Load(node->else_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00004787
4788 if (then.is_linked()) {
4789 exit.Jump();
4790 then.Bind();
Steve Blockd0582a62009-12-15 09:54:21 +00004791 Load(node->then_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00004792 }
4793 } else {
4794 // The then target was bound, so we compile the then part first.
Steve Blockd0582a62009-12-15 09:54:21 +00004795 Load(node->then_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00004796
4797 if (else_.is_linked()) {
4798 exit.Jump();
4799 else_.Bind();
Steve Blockd0582a62009-12-15 09:54:21 +00004800 Load(node->else_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00004801 }
4802 }
4803
4804 exit.Bind();
4805}
4806
4807
Leon Clarkef7060e22010-06-03 12:02:55 +01004808void CodeGenerator::LoadFromSlot(Slot* slot, TypeofState typeof_state) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004809 if (slot->type() == Slot::LOOKUP) {
4810 ASSERT(slot->var()->is_dynamic());
Steve Blocka7e24c12009-10-30 11:49:00 +00004811 JumpTarget slow;
4812 JumpTarget done;
Leon Clarkef7060e22010-06-03 12:02:55 +01004813 Result value;
Steve Blocka7e24c12009-10-30 11:49:00 +00004814
Kristian Monsen25f61362010-05-21 11:50:48 +01004815 // Generate fast case for loading from slots that correspond to
4816 // local/global variables or arguments unless they are shadowed by
4817 // eval-introduced bindings.
4818 EmitDynamicLoadFromSlotFastCase(slot,
4819 typeof_state,
Leon Clarkef7060e22010-06-03 12:02:55 +01004820 &value,
Kristian Monsen25f61362010-05-21 11:50:48 +01004821 &slow,
4822 &done);
Steve Blocka7e24c12009-10-30 11:49:00 +00004823
4824 slow.Bind();
4825 // A runtime call is inevitable. We eagerly sync frame elements
4826 // to memory so that we can push the arguments directly into place
4827 // on top of the frame.
Andrei Popescu402d9372010-02-26 13:31:12 +00004828 frame()->SyncRange(0, frame()->element_count() - 1);
4829 frame()->EmitPush(esi);
4830 frame()->EmitPush(Immediate(slot->var()->name()));
Steve Blocka7e24c12009-10-30 11:49:00 +00004831 if (typeof_state == INSIDE_TYPEOF) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004832 value =
Andrei Popescu402d9372010-02-26 13:31:12 +00004833 frame()->CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00004834 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004835 value = frame()->CallRuntime(Runtime::kLoadContextSlot, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00004836 }
4837
Leon Clarkef7060e22010-06-03 12:02:55 +01004838 done.Bind(&value);
4839 frame_->Push(&value);
Steve Blocka7e24c12009-10-30 11:49:00 +00004840
4841 } else if (slot->var()->mode() == Variable::CONST) {
4842 // Const slots may contain 'the hole' value (the constant hasn't been
4843 // initialized yet) which needs to be converted into the 'undefined'
4844 // value.
4845 //
4846 // We currently spill the virtual frame because constants use the
4847 // potentially unsafe direct-frame access of SlotOperand.
4848 VirtualFrame::SpilledScope spilled_scope;
4849 Comment cmnt(masm_, "[ Load const");
Andrei Popescu402d9372010-02-26 13:31:12 +00004850 Label exit;
Steve Blocka7e24c12009-10-30 11:49:00 +00004851 __ mov(ecx, SlotOperand(slot, ecx));
4852 __ cmp(ecx, Factory::the_hole_value());
Andrei Popescu402d9372010-02-26 13:31:12 +00004853 __ j(not_equal, &exit);
Steve Blocka7e24c12009-10-30 11:49:00 +00004854 __ mov(ecx, Factory::undefined_value());
Andrei Popescu402d9372010-02-26 13:31:12 +00004855 __ bind(&exit);
Leon Clarkef7060e22010-06-03 12:02:55 +01004856 frame()->EmitPush(ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +00004857
4858 } else if (slot->type() == Slot::PARAMETER) {
Andrei Popescu402d9372010-02-26 13:31:12 +00004859 frame()->PushParameterAt(slot->index());
Steve Blocka7e24c12009-10-30 11:49:00 +00004860
4861 } else if (slot->type() == Slot::LOCAL) {
Andrei Popescu402d9372010-02-26 13:31:12 +00004862 frame()->PushLocalAt(slot->index());
Steve Blocka7e24c12009-10-30 11:49:00 +00004863
4864 } else {
4865 // The other remaining slot types (LOOKUP and GLOBAL) cannot reach
4866 // here.
4867 //
4868 // The use of SlotOperand below is safe for an unspilled frame
4869 // because it will always be a context slot.
4870 ASSERT(slot->type() == Slot::CONTEXT);
Leon Clarkef7060e22010-06-03 12:02:55 +01004871 Result temp = allocator()->Allocate();
4872 ASSERT(temp.is_valid());
4873 __ mov(temp.reg(), SlotOperand(slot, temp.reg()));
4874 frame()->Push(&temp);
Steve Blocka7e24c12009-10-30 11:49:00 +00004875 }
4876}
4877
4878
Leon Clarkef7060e22010-06-03 12:02:55 +01004879void CodeGenerator::LoadFromSlotCheckForArguments(Slot* slot,
Andrei Popescu402d9372010-02-26 13:31:12 +00004880 TypeofState state) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004881 LoadFromSlot(slot, state);
Steve Blocka7e24c12009-10-30 11:49:00 +00004882
4883 // Bail out quickly if we're not using lazy arguments allocation.
Leon Clarkef7060e22010-06-03 12:02:55 +01004884 if (ArgumentsMode() != LAZY_ARGUMENTS_ALLOCATION) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004885
4886 // ... or if the slot isn't a non-parameter arguments slot.
Leon Clarkef7060e22010-06-03 12:02:55 +01004887 if (slot->type() == Slot::PARAMETER || !slot->is_arguments()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004888
4889 // If the loaded value is a constant, we know if the arguments
4890 // object has been lazily loaded yet.
Leon Clarkef7060e22010-06-03 12:02:55 +01004891 Result result = frame()->Pop();
Andrei Popescu402d9372010-02-26 13:31:12 +00004892 if (result.is_constant()) {
4893 if (result.handle()->IsTheHole()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004894 result = StoreArgumentsObject(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00004895 }
Leon Clarkef7060e22010-06-03 12:02:55 +01004896 frame()->Push(&result);
4897 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004898 }
Leon Clarkef7060e22010-06-03 12:02:55 +01004899 ASSERT(result.is_register());
Steve Blocka7e24c12009-10-30 11:49:00 +00004900 // The loaded value is in a register. If it is the sentinel that
4901 // indicates that we haven't loaded the arguments object yet, we
4902 // need to do it now.
4903 JumpTarget exit;
Andrei Popescu402d9372010-02-26 13:31:12 +00004904 __ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
Leon Clarkef7060e22010-06-03 12:02:55 +01004905 frame()->Push(&result);
4906 exit.Branch(not_equal);
Andrei Popescu402d9372010-02-26 13:31:12 +00004907
Andrei Popescu402d9372010-02-26 13:31:12 +00004908 result = StoreArgumentsObject(false);
Leon Clarkef7060e22010-06-03 12:02:55 +01004909 frame()->SetElementAt(0, &result);
4910 result.Unuse();
4911 exit.Bind();
4912 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004913}
4914
4915
4916Result CodeGenerator::LoadFromGlobalSlotCheckExtensions(
4917 Slot* slot,
4918 TypeofState typeof_state,
4919 JumpTarget* slow) {
Steve Block6ded16b2010-05-10 14:33:55 +01004920 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004921 // Check that no extension objects have been created by calls to
4922 // eval from the current scope to the global scope.
4923 Register context = esi;
4924 Result tmp = allocator_->Allocate();
4925 ASSERT(tmp.is_valid()); // All non-reserved registers were available.
4926
4927 Scope* s = scope();
4928 while (s != NULL) {
4929 if (s->num_heap_slots() > 0) {
4930 if (s->calls_eval()) {
4931 // Check that extension is NULL.
4932 __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
4933 Immediate(0));
4934 slow->Branch(not_equal, not_taken);
4935 }
4936 // Load next context in chain.
4937 __ mov(tmp.reg(), ContextOperand(context, Context::CLOSURE_INDEX));
4938 __ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
4939 context = tmp.reg();
4940 }
4941 // If no outer scope calls eval, we do not need to check more
4942 // context extensions. If we have reached an eval scope, we check
4943 // all extensions from this point.
4944 if (!s->outer_scope_calls_eval() || s->is_eval_scope()) break;
4945 s = s->outer_scope();
4946 }
4947
4948 if (s != NULL && s->is_eval_scope()) {
4949 // Loop up the context chain. There is no frame effect so it is
4950 // safe to use raw labels here.
4951 Label next, fast;
4952 if (!context.is(tmp.reg())) {
4953 __ mov(tmp.reg(), context);
4954 }
4955 __ bind(&next);
4956 // Terminate at global context.
4957 __ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
4958 Immediate(Factory::global_context_map()));
4959 __ j(equal, &fast);
4960 // Check that extension is NULL.
4961 __ cmp(ContextOperand(tmp.reg(), Context::EXTENSION_INDEX), Immediate(0));
4962 slow->Branch(not_equal, not_taken);
4963 // Load next context in chain.
4964 __ mov(tmp.reg(), ContextOperand(tmp.reg(), Context::CLOSURE_INDEX));
4965 __ mov(tmp.reg(), FieldOperand(tmp.reg(), JSFunction::kContextOffset));
4966 __ jmp(&next);
4967 __ bind(&fast);
4968 }
4969 tmp.Unuse();
4970
4971 // All extension objects were empty and it is safe to use a global
4972 // load IC call.
Andrei Popescu402d9372010-02-26 13:31:12 +00004973 // The register allocator prefers eax if it is free, so the code generator
4974 // will load the global object directly into eax, which is where the LoadIC
4975 // expects it.
4976 frame_->Spill(eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00004977 LoadGlobal();
4978 frame_->Push(slot->var()->name());
4979 RelocInfo::Mode mode = (typeof_state == INSIDE_TYPEOF)
4980 ? RelocInfo::CODE_TARGET
4981 : RelocInfo::CODE_TARGET_CONTEXT;
4982 Result answer = frame_->CallLoadIC(mode);
4983 // A test eax instruction following the call signals that the inobject
4984 // property case was inlined. Ensure that there is not a test eax
4985 // instruction here.
4986 __ nop();
Steve Blocka7e24c12009-10-30 11:49:00 +00004987 return answer;
4988}
4989
4990
Kristian Monsen25f61362010-05-21 11:50:48 +01004991void CodeGenerator::EmitDynamicLoadFromSlotFastCase(Slot* slot,
4992 TypeofState typeof_state,
4993 Result* result,
4994 JumpTarget* slow,
4995 JumpTarget* done) {
4996 // Generate fast-case code for variables that might be shadowed by
4997 // eval-introduced variables. Eval is used a lot without
4998 // introducing variables. In those cases, we do not want to
4999 // perform a runtime call for all variables in the scope
5000 // containing the eval.
5001 if (slot->var()->mode() == Variable::DYNAMIC_GLOBAL) {
5002 *result = LoadFromGlobalSlotCheckExtensions(slot, typeof_state, slow);
5003 done->Jump(result);
5004
5005 } else if (slot->var()->mode() == Variable::DYNAMIC_LOCAL) {
5006 Slot* potential_slot = slot->var()->local_if_not_shadowed()->slot();
5007 Expression* rewrite = slot->var()->local_if_not_shadowed()->rewrite();
5008 if (potential_slot != NULL) {
5009 // Generate fast case for locals that rewrite to slots.
5010 // Allocate a fresh register to use as a temp in
5011 // ContextSlotOperandCheckExtensions and to hold the result
5012 // value.
5013 *result = allocator()->Allocate();
5014 ASSERT(result->is_valid());
5015 __ mov(result->reg(),
5016 ContextSlotOperandCheckExtensions(potential_slot, *result, slow));
5017 if (potential_slot->var()->mode() == Variable::CONST) {
5018 __ cmp(result->reg(), Factory::the_hole_value());
5019 done->Branch(not_equal, result);
5020 __ mov(result->reg(), Factory::undefined_value());
5021 }
5022 done->Jump(result);
5023 } else if (rewrite != NULL) {
5024 // Generate fast case for calls of an argument function.
5025 Property* property = rewrite->AsProperty();
5026 if (property != NULL) {
5027 VariableProxy* obj_proxy = property->obj()->AsVariableProxy();
5028 Literal* key_literal = property->key()->AsLiteral();
5029 if (obj_proxy != NULL &&
5030 key_literal != NULL &&
5031 obj_proxy->IsArguments() &&
5032 key_literal->handle()->IsSmi()) {
5033 // Load arguments object if there are no eval-introduced
5034 // variables. Then load the argument from the arguments
5035 // object using keyed load.
5036 Result arguments = allocator()->Allocate();
5037 ASSERT(arguments.is_valid());
5038 __ mov(arguments.reg(),
5039 ContextSlotOperandCheckExtensions(obj_proxy->var()->slot(),
5040 arguments,
5041 slow));
5042 frame_->Push(&arguments);
5043 frame_->Push(key_literal->handle());
5044 *result = EmitKeyedLoad();
5045 done->Jump(result);
5046 }
5047 }
5048 }
5049 }
5050}
5051
5052
Steve Blocka7e24c12009-10-30 11:49:00 +00005053void CodeGenerator::StoreToSlot(Slot* slot, InitState init_state) {
5054 if (slot->type() == Slot::LOOKUP) {
5055 ASSERT(slot->var()->is_dynamic());
5056
5057 // For now, just do a runtime call. Since the call is inevitable,
5058 // we eagerly sync the virtual frame so we can directly push the
5059 // arguments into place.
5060 frame_->SyncRange(0, frame_->element_count() - 1);
5061
5062 frame_->EmitPush(esi);
5063 frame_->EmitPush(Immediate(slot->var()->name()));
5064
5065 Result value;
5066 if (init_state == CONST_INIT) {
5067 // Same as the case for a normal store, but ignores attribute
5068 // (e.g. READ_ONLY) of context slot so that we can initialize const
5069 // properties (introduced via eval("const foo = (some expr);")). Also,
5070 // uses the current function context instead of the top context.
5071 //
5072 // Note that we must declare the foo upon entry of eval(), via a
5073 // context slot declaration, but we cannot initialize it at the same
5074 // time, because the const declaration may be at the end of the eval
5075 // code (sigh...) and the const variable may have been used before
5076 // (where its value is 'undefined'). Thus, we can only do the
5077 // initialization when we actually encounter the expression and when
5078 // the expression operands are defined and valid, and thus we need the
5079 // split into 2 operations: declaration of the context slot followed
5080 // by initialization.
5081 value = frame_->CallRuntime(Runtime::kInitializeConstContextSlot, 3);
5082 } else {
5083 value = frame_->CallRuntime(Runtime::kStoreContextSlot, 3);
5084 }
5085 // Storing a variable must keep the (new) value on the expression
5086 // stack. This is necessary for compiling chained assignment
5087 // expressions.
5088 frame_->Push(&value);
5089
5090 } else {
5091 ASSERT(!slot->var()->is_dynamic());
5092
5093 JumpTarget exit;
5094 if (init_state == CONST_INIT) {
5095 ASSERT(slot->var()->mode() == Variable::CONST);
5096 // Only the first const initialization must be executed (the slot
5097 // still contains 'the hole' value). When the assignment is executed,
5098 // the code is identical to a normal store (see below).
5099 //
5100 // We spill the frame in the code below because the direct-frame
5101 // access of SlotOperand is potentially unsafe with an unspilled
5102 // frame.
5103 VirtualFrame::SpilledScope spilled_scope;
5104 Comment cmnt(masm_, "[ Init const");
5105 __ mov(ecx, SlotOperand(slot, ecx));
5106 __ cmp(ecx, Factory::the_hole_value());
5107 exit.Branch(not_equal);
5108 }
5109
5110 // We must execute the store. Storing a variable must keep the (new)
5111 // value on the stack. This is necessary for compiling assignment
5112 // expressions.
5113 //
5114 // Note: We will reach here even with slot->var()->mode() ==
5115 // Variable::CONST because of const declarations which will initialize
5116 // consts to 'the hole' value and by doing so, end up calling this code.
5117 if (slot->type() == Slot::PARAMETER) {
5118 frame_->StoreToParameterAt(slot->index());
5119 } else if (slot->type() == Slot::LOCAL) {
5120 frame_->StoreToLocalAt(slot->index());
5121 } else {
5122 // The other slot types (LOOKUP and GLOBAL) cannot reach here.
5123 //
5124 // The use of SlotOperand below is safe for an unspilled frame
5125 // because the slot is a context slot.
5126 ASSERT(slot->type() == Slot::CONTEXT);
5127 frame_->Dup();
5128 Result value = frame_->Pop();
5129 value.ToRegister();
5130 Result start = allocator_->Allocate();
5131 ASSERT(start.is_valid());
5132 __ mov(SlotOperand(slot, start.reg()), value.reg());
5133 // RecordWrite may destroy the value registers.
5134 //
5135 // TODO(204): Avoid actually spilling when the value is not
5136 // needed (probably the common case).
5137 frame_->Spill(value.reg());
5138 int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
5139 Result temp = allocator_->Allocate();
5140 ASSERT(temp.is_valid());
5141 __ RecordWrite(start.reg(), offset, value.reg(), temp.reg());
5142 // The results start, value, and temp are unused by going out of
5143 // scope.
5144 }
5145
5146 exit.Bind();
5147 }
5148}
5149
5150
Steve Block6ded16b2010-05-10 14:33:55 +01005151void CodeGenerator::VisitSlot(Slot* slot) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005152 Comment cmnt(masm_, "[ Slot");
Steve Block6ded16b2010-05-10 14:33:55 +01005153 if (in_safe_int32_mode()) {
5154 if ((slot->type() == Slot::LOCAL && !slot->is_arguments())) {
5155 frame()->UntaggedPushLocalAt(slot->index());
5156 } else if (slot->type() == Slot::PARAMETER) {
5157 frame()->UntaggedPushParameterAt(slot->index());
5158 } else {
5159 UNREACHABLE();
5160 }
5161 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005162 LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Steve Block6ded16b2010-05-10 14:33:55 +01005163 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005164}
5165
5166
5167void CodeGenerator::VisitVariableProxy(VariableProxy* node) {
5168 Comment cmnt(masm_, "[ VariableProxy");
5169 Variable* var = node->var();
5170 Expression* expr = var->rewrite();
5171 if (expr != NULL) {
5172 Visit(expr);
5173 } else {
5174 ASSERT(var->is_global());
Steve Block6ded16b2010-05-10 14:33:55 +01005175 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005176 Reference ref(this, node);
Steve Blockd0582a62009-12-15 09:54:21 +00005177 ref.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00005178 }
5179}
5180
5181
5182void CodeGenerator::VisitLiteral(Literal* node) {
5183 Comment cmnt(masm_, "[ Literal");
Steve Block6ded16b2010-05-10 14:33:55 +01005184 if (in_safe_int32_mode()) {
5185 frame_->PushUntaggedElement(node->handle());
5186 } else {
5187 frame_->Push(node->handle());
5188 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005189}
5190
5191
Steve Blockd0582a62009-12-15 09:54:21 +00005192void CodeGenerator::PushUnsafeSmi(Handle<Object> value) {
5193 ASSERT(value->IsSmi());
5194 int bits = reinterpret_cast<int>(*value);
5195 __ push(Immediate(bits & 0x0000FFFF));
5196 __ or_(Operand(esp, 0), Immediate(bits & 0xFFFF0000));
5197}
5198
5199
5200void CodeGenerator::StoreUnsafeSmiToLocal(int offset, Handle<Object> value) {
5201 ASSERT(value->IsSmi());
5202 int bits = reinterpret_cast<int>(*value);
5203 __ mov(Operand(ebp, offset), Immediate(bits & 0x0000FFFF));
5204 __ or_(Operand(ebp, offset), Immediate(bits & 0xFFFF0000));
5205}
5206
5207
5208void CodeGenerator::MoveUnsafeSmi(Register target, Handle<Object> value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005209 ASSERT(target.is_valid());
5210 ASSERT(value->IsSmi());
5211 int bits = reinterpret_cast<int>(*value);
5212 __ Set(target, Immediate(bits & 0x0000FFFF));
Steve Blockd0582a62009-12-15 09:54:21 +00005213 __ or_(target, bits & 0xFFFF0000);
Steve Blocka7e24c12009-10-30 11:49:00 +00005214}
5215
5216
5217bool CodeGenerator::IsUnsafeSmi(Handle<Object> value) {
5218 if (!value->IsSmi()) return false;
5219 int int_value = Smi::cast(*value)->value();
5220 return !is_intn(int_value, kMaxSmiInlinedBits);
5221}
5222
5223
5224// Materialize the regexp literal 'node' in the literals array
5225// 'literals' of the function. Leave the regexp boilerplate in
5226// 'boilerplate'.
5227class DeferredRegExpLiteral: public DeferredCode {
5228 public:
5229 DeferredRegExpLiteral(Register boilerplate,
5230 Register literals,
5231 RegExpLiteral* node)
5232 : boilerplate_(boilerplate), literals_(literals), node_(node) {
5233 set_comment("[ DeferredRegExpLiteral");
5234 }
5235
5236 void Generate();
5237
5238 private:
5239 Register boilerplate_;
5240 Register literals_;
5241 RegExpLiteral* node_;
5242};
5243
5244
5245void DeferredRegExpLiteral::Generate() {
5246 // Since the entry is undefined we call the runtime system to
5247 // compute the literal.
5248 // Literal array (0).
5249 __ push(literals_);
5250 // Literal index (1).
5251 __ push(Immediate(Smi::FromInt(node_->literal_index())));
5252 // RegExp pattern (2).
5253 __ push(Immediate(node_->pattern()));
5254 // RegExp flags (3).
5255 __ push(Immediate(node_->flags()));
5256 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
5257 if (!boilerplate_.is(eax)) __ mov(boilerplate_, eax);
5258}
5259
5260
5261void CodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005262 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005263 Comment cmnt(masm_, "[ RegExp Literal");
5264
5265 // Retrieve the literals array and check the allocated entry. Begin
5266 // with a writable copy of the function of this activation in a
5267 // register.
5268 frame_->PushFunction();
5269 Result literals = frame_->Pop();
5270 literals.ToRegister();
5271 frame_->Spill(literals.reg());
5272
5273 // Load the literals array of the function.
5274 __ mov(literals.reg(),
5275 FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
5276
5277 // Load the literal at the ast saved index.
5278 Result boilerplate = allocator_->Allocate();
5279 ASSERT(boilerplate.is_valid());
5280 int literal_offset =
5281 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
5282 __ mov(boilerplate.reg(), FieldOperand(literals.reg(), literal_offset));
5283
5284 // Check whether we need to materialize the RegExp object. If so,
5285 // jump to the deferred code passing the literals array.
5286 DeferredRegExpLiteral* deferred =
5287 new DeferredRegExpLiteral(boilerplate.reg(), literals.reg(), node);
5288 __ cmp(boilerplate.reg(), Factory::undefined_value());
5289 deferred->Branch(equal);
5290 deferred->BindExit();
5291 literals.Unuse();
5292
5293 // Push the boilerplate object.
5294 frame_->Push(&boilerplate);
5295}
5296
5297
Steve Blocka7e24c12009-10-30 11:49:00 +00005298void CodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005299 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005300 Comment cmnt(masm_, "[ ObjectLiteral");
5301
Leon Clarkee46be812010-01-19 14:06:41 +00005302 // Load a writable copy of the function of this activation in a
Steve Blocka7e24c12009-10-30 11:49:00 +00005303 // register.
5304 frame_->PushFunction();
5305 Result literals = frame_->Pop();
5306 literals.ToRegister();
5307 frame_->Spill(literals.reg());
5308
5309 // Load the literals array of the function.
5310 __ mov(literals.reg(),
5311 FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
Leon Clarkee46be812010-01-19 14:06:41 +00005312 // Literal array.
5313 frame_->Push(&literals);
5314 // Literal index.
5315 frame_->Push(Smi::FromInt(node->literal_index()));
5316 // Constant properties.
5317 frame_->Push(node->constant_properties());
Steve Block6ded16b2010-05-10 14:33:55 +01005318 // Should the object literal have fast elements?
5319 frame_->Push(Smi::FromInt(node->fast_elements() ? 1 : 0));
Leon Clarkee46be812010-01-19 14:06:41 +00005320 Result clone;
5321 if (node->depth() > 1) {
Steve Block6ded16b2010-05-10 14:33:55 +01005322 clone = frame_->CallRuntime(Runtime::kCreateObjectLiteral, 4);
Leon Clarkee46be812010-01-19 14:06:41 +00005323 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005324 clone = frame_->CallRuntime(Runtime::kCreateObjectLiteralShallow, 4);
Steve Blocka7e24c12009-10-30 11:49:00 +00005325 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005326 frame_->Push(&clone);
5327
5328 for (int i = 0; i < node->properties()->length(); i++) {
5329 ObjectLiteral::Property* property = node->properties()->at(i);
5330 switch (property->kind()) {
5331 case ObjectLiteral::Property::CONSTANT:
5332 break;
5333 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
5334 if (CompileTimeValue::IsCompileTimeValue(property->value())) break;
5335 // else fall through.
5336 case ObjectLiteral::Property::COMPUTED: {
5337 Handle<Object> key(property->key()->handle());
5338 if (key->IsSymbol()) {
5339 // Duplicate the object as the IC receiver.
5340 frame_->Dup();
5341 Load(property->value());
Andrei Popescu402d9372010-02-26 13:31:12 +00005342 Result dummy = frame_->CallStoreIC(Handle<String>::cast(key), false);
5343 dummy.Unuse();
Steve Blocka7e24c12009-10-30 11:49:00 +00005344 break;
5345 }
5346 // Fall through
5347 }
5348 case ObjectLiteral::Property::PROTOTYPE: {
5349 // Duplicate the object as an argument to the runtime call.
5350 frame_->Dup();
5351 Load(property->key());
5352 Load(property->value());
5353 Result ignored = frame_->CallRuntime(Runtime::kSetProperty, 3);
5354 // Ignore the result.
5355 break;
5356 }
5357 case ObjectLiteral::Property::SETTER: {
5358 // Duplicate the object as an argument to the runtime call.
5359 frame_->Dup();
5360 Load(property->key());
5361 frame_->Push(Smi::FromInt(1));
5362 Load(property->value());
5363 Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
5364 // Ignore the result.
5365 break;
5366 }
5367 case ObjectLiteral::Property::GETTER: {
5368 // Duplicate the object as an argument to the runtime call.
5369 frame_->Dup();
5370 Load(property->key());
5371 frame_->Push(Smi::FromInt(0));
5372 Load(property->value());
5373 Result ignored = frame_->CallRuntime(Runtime::kDefineAccessor, 4);
5374 // Ignore the result.
5375 break;
5376 }
5377 default: UNREACHABLE();
5378 }
5379 }
5380}
5381
5382
Steve Blocka7e24c12009-10-30 11:49:00 +00005383void CodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005384 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005385 Comment cmnt(masm_, "[ ArrayLiteral");
5386
Leon Clarkee46be812010-01-19 14:06:41 +00005387 // Load a writable copy of the function of this activation in a
Steve Blocka7e24c12009-10-30 11:49:00 +00005388 // register.
5389 frame_->PushFunction();
5390 Result literals = frame_->Pop();
5391 literals.ToRegister();
5392 frame_->Spill(literals.reg());
5393
5394 // Load the literals array of the function.
5395 __ mov(literals.reg(),
5396 FieldOperand(literals.reg(), JSFunction::kLiteralsOffset));
5397
Leon Clarkee46be812010-01-19 14:06:41 +00005398 frame_->Push(&literals);
5399 frame_->Push(Smi::FromInt(node->literal_index()));
5400 frame_->Push(node->constant_elements());
5401 int length = node->values()->length();
5402 Result clone;
5403 if (node->depth() > 1) {
5404 clone = frame_->CallRuntime(Runtime::kCreateArrayLiteral, 3);
5405 } else if (length > FastCloneShallowArrayStub::kMaximumLength) {
5406 clone = frame_->CallRuntime(Runtime::kCreateArrayLiteralShallow, 3);
5407 } else {
5408 FastCloneShallowArrayStub stub(length);
5409 clone = frame_->CallStub(&stub, 3);
Steve Blocka7e24c12009-10-30 11:49:00 +00005410 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005411 frame_->Push(&clone);
5412
5413 // Generate code to set the elements in the array that are not
5414 // literals.
Leon Clarkee46be812010-01-19 14:06:41 +00005415 for (int i = 0; i < length; i++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005416 Expression* value = node->values()->at(i);
5417
5418 // If value is a literal the property value is already set in the
5419 // boilerplate object.
5420 if (value->AsLiteral() != NULL) continue;
5421 // If value is a materialized literal the property value is already set
5422 // in the boilerplate object if it is simple.
5423 if (CompileTimeValue::IsCompileTimeValue(value)) continue;
5424
5425 // The property must be set by generated code.
5426 Load(value);
5427
5428 // Get the property value off the stack.
5429 Result prop_value = frame_->Pop();
5430 prop_value.ToRegister();
5431
5432 // Fetch the array literal while leaving a copy on the stack and
5433 // use it to get the elements array.
5434 frame_->Dup();
5435 Result elements = frame_->Pop();
5436 elements.ToRegister();
5437 frame_->Spill(elements.reg());
5438 // Get the elements array.
5439 __ mov(elements.reg(),
5440 FieldOperand(elements.reg(), JSObject::kElementsOffset));
5441
5442 // Write to the indexed properties array.
5443 int offset = i * kPointerSize + FixedArray::kHeaderSize;
5444 __ mov(FieldOperand(elements.reg(), offset), prop_value.reg());
5445
5446 // Update the write barrier for the array address.
5447 frame_->Spill(prop_value.reg()); // Overwritten by the write barrier.
5448 Result scratch = allocator_->Allocate();
5449 ASSERT(scratch.is_valid());
5450 __ RecordWrite(elements.reg(), offset, prop_value.reg(), scratch.reg());
5451 }
5452}
5453
5454
5455void CodeGenerator::VisitCatchExtensionObject(CatchExtensionObject* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005456 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005457 ASSERT(!in_spilled_code());
5458 // Call runtime routine to allocate the catch extension object and
5459 // assign the exception value to the catch variable.
5460 Comment cmnt(masm_, "[ CatchExtensionObject");
5461 Load(node->key());
5462 Load(node->value());
5463 Result result =
5464 frame_->CallRuntime(Runtime::kCreateCatchExtensionObject, 2);
5465 frame_->Push(&result);
5466}
5467
5468
Andrei Popescu402d9372010-02-26 13:31:12 +00005469void CodeGenerator::EmitSlotAssignment(Assignment* node) {
5470#ifdef DEBUG
5471 int original_height = frame()->height();
5472#endif
5473 Comment cmnt(masm(), "[ Variable Assignment");
5474 Variable* var = node->target()->AsVariableProxy()->AsVariable();
5475 ASSERT(var != NULL);
5476 Slot* slot = var->slot();
5477 ASSERT(slot != NULL);
5478
5479 // Evaluate the right-hand side.
5480 if (node->is_compound()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005481 // For a compound assignment the right-hand side is a binary operation
5482 // between the current property value and the actual right-hand side.
Leon Clarkef7060e22010-06-03 12:02:55 +01005483 LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Andrei Popescu402d9372010-02-26 13:31:12 +00005484 Load(node->value());
5485
Steve Block6ded16b2010-05-10 14:33:55 +01005486 // Perform the binary operation.
Andrei Popescu402d9372010-02-26 13:31:12 +00005487 bool overwrite_value =
5488 (node->value()->AsBinaryOperation() != NULL &&
5489 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
Steve Block6ded16b2010-05-10 14:33:55 +01005490 // Construct the implicit binary operation.
5491 BinaryOperation expr(node, node->binary_op(), node->target(),
5492 node->value());
5493 GenericBinaryOperation(&expr,
Andrei Popescu402d9372010-02-26 13:31:12 +00005494 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
5495 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005496 // For non-compound assignment just load the right-hand side.
Andrei Popescu402d9372010-02-26 13:31:12 +00005497 Load(node->value());
5498 }
5499
5500 // Perform the assignment.
5501 if (var->mode() != Variable::CONST || node->op() == Token::INIT_CONST) {
5502 CodeForSourcePosition(node->position());
5503 StoreToSlot(slot,
5504 node->op() == Token::INIT_CONST ? CONST_INIT : NOT_CONST_INIT);
5505 }
5506 ASSERT(frame()->height() == original_height + 1);
5507}
5508
5509
5510void CodeGenerator::EmitNamedPropertyAssignment(Assignment* node) {
5511#ifdef DEBUG
5512 int original_height = frame()->height();
5513#endif
5514 Comment cmnt(masm(), "[ Named Property Assignment");
5515 Variable* var = node->target()->AsVariableProxy()->AsVariable();
5516 Property* prop = node->target()->AsProperty();
5517 ASSERT(var == NULL || (prop == NULL && var->is_global()));
5518
Steve Block6ded16b2010-05-10 14:33:55 +01005519 // Initialize name and evaluate the receiver sub-expression if necessary. If
5520 // the receiver is trivial it is not placed on the stack at this point, but
5521 // loaded whenever actually needed.
Andrei Popescu402d9372010-02-26 13:31:12 +00005522 Handle<String> name;
5523 bool is_trivial_receiver = false;
5524 if (var != NULL) {
5525 name = var->name();
5526 } else {
5527 Literal* lit = prop->key()->AsLiteral();
5528 ASSERT_NOT_NULL(lit);
5529 name = Handle<String>::cast(lit->handle());
5530 // Do not materialize the receiver on the frame if it is trivial.
5531 is_trivial_receiver = prop->obj()->IsTrivial();
5532 if (!is_trivial_receiver) Load(prop->obj());
5533 }
5534
Steve Block6ded16b2010-05-10 14:33:55 +01005535 // Change to slow case in the beginning of an initialization block to
5536 // avoid the quadratic behavior of repeatedly adding fast properties.
Andrei Popescu402d9372010-02-26 13:31:12 +00005537 if (node->starts_initialization_block()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005538 // Initialization block consists of assignments of the form expr.x = ..., so
5539 // this will never be an assignment to a variable, so there must be a
5540 // receiver object.
Andrei Popescu402d9372010-02-26 13:31:12 +00005541 ASSERT_EQ(NULL, var);
Andrei Popescu402d9372010-02-26 13:31:12 +00005542 if (is_trivial_receiver) {
5543 frame()->Push(prop->obj());
5544 } else {
5545 frame()->Dup();
5546 }
5547 Result ignored = frame()->CallRuntime(Runtime::kToSlowProperties, 1);
5548 }
5549
Steve Block6ded16b2010-05-10 14:33:55 +01005550 // Change to fast case at the end of an initialization block. To prepare for
5551 // that add an extra copy of the receiver to the frame, so that it can be
5552 // converted back to fast case after the assignment.
Andrei Popescu402d9372010-02-26 13:31:12 +00005553 if (node->ends_initialization_block() && !is_trivial_receiver) {
Andrei Popescu402d9372010-02-26 13:31:12 +00005554 frame()->Dup();
5555 }
5556
Steve Block6ded16b2010-05-10 14:33:55 +01005557 // Stack layout:
5558 // [tos] : receiver (only materialized if non-trivial)
5559 // [tos+1] : receiver if at the end of an initialization block
5560
Andrei Popescu402d9372010-02-26 13:31:12 +00005561 // Evaluate the right-hand side.
5562 if (node->is_compound()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005563 // For a compound assignment the right-hand side is a binary operation
5564 // between the current property value and the actual right-hand side.
Andrei Popescu402d9372010-02-26 13:31:12 +00005565 if (is_trivial_receiver) {
5566 frame()->Push(prop->obj());
5567 } else if (var != NULL) {
5568 // The LoadIC stub expects the object in eax.
5569 // Freeing eax causes the code generator to load the global into it.
5570 frame_->Spill(eax);
5571 LoadGlobal();
5572 } else {
5573 frame()->Dup();
5574 }
5575 Result value = EmitNamedLoad(name, var != NULL);
5576 frame()->Push(&value);
5577 Load(node->value());
5578
5579 bool overwrite_value =
5580 (node->value()->AsBinaryOperation() != NULL &&
5581 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
Steve Block6ded16b2010-05-10 14:33:55 +01005582 // Construct the implicit binary operation.
5583 BinaryOperation expr(node, node->binary_op(), node->target(),
5584 node->value());
5585 GenericBinaryOperation(&expr,
Andrei Popescu402d9372010-02-26 13:31:12 +00005586 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
5587 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005588 // For non-compound assignment just load the right-hand side.
Andrei Popescu402d9372010-02-26 13:31:12 +00005589 Load(node->value());
5590 }
5591
Steve Block6ded16b2010-05-10 14:33:55 +01005592 // Stack layout:
5593 // [tos] : value
5594 // [tos+1] : receiver (only materialized if non-trivial)
5595 // [tos+2] : receiver if at the end of an initialization block
5596
Andrei Popescu402d9372010-02-26 13:31:12 +00005597 // Perform the assignment. It is safe to ignore constants here.
5598 ASSERT(var == NULL || var->mode() != Variable::CONST);
5599 ASSERT_NE(Token::INIT_CONST, node->op());
5600 if (is_trivial_receiver) {
5601 Result value = frame()->Pop();
5602 frame()->Push(prop->obj());
5603 frame()->Push(&value);
5604 }
5605 CodeForSourcePosition(node->position());
5606 bool is_contextual = (var != NULL);
5607 Result answer = EmitNamedStore(name, is_contextual);
5608 frame()->Push(&answer);
5609
Steve Block6ded16b2010-05-10 14:33:55 +01005610 // Stack layout:
5611 // [tos] : result
5612 // [tos+1] : receiver if at the end of an initialization block
5613
Andrei Popescu402d9372010-02-26 13:31:12 +00005614 if (node->ends_initialization_block()) {
5615 ASSERT_EQ(NULL, var);
5616 // The argument to the runtime call is the receiver.
5617 if (is_trivial_receiver) {
5618 frame()->Push(prop->obj());
5619 } else {
5620 // A copy of the receiver is below the value of the assignment. Swap
5621 // the receiver and the value of the assignment expression.
5622 Result result = frame()->Pop();
5623 Result receiver = frame()->Pop();
5624 frame()->Push(&result);
5625 frame()->Push(&receiver);
5626 }
5627 Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
5628 }
5629
Steve Block6ded16b2010-05-10 14:33:55 +01005630 // Stack layout:
5631 // [tos] : result
5632
Andrei Popescu402d9372010-02-26 13:31:12 +00005633 ASSERT_EQ(frame()->height(), original_height + 1);
5634}
5635
5636
5637void CodeGenerator::EmitKeyedPropertyAssignment(Assignment* node) {
5638#ifdef DEBUG
5639 int original_height = frame()->height();
5640#endif
Steve Block6ded16b2010-05-10 14:33:55 +01005641 Comment cmnt(masm_, "[ Keyed Property Assignment");
Andrei Popescu402d9372010-02-26 13:31:12 +00005642 Property* prop = node->target()->AsProperty();
5643 ASSERT_NOT_NULL(prop);
5644
5645 // Evaluate the receiver subexpression.
5646 Load(prop->obj());
5647
Steve Block6ded16b2010-05-10 14:33:55 +01005648 // Change to slow case in the beginning of an initialization block to
5649 // avoid the quadratic behavior of repeatedly adding fast properties.
Andrei Popescu402d9372010-02-26 13:31:12 +00005650 if (node->starts_initialization_block()) {
Andrei Popescu402d9372010-02-26 13:31:12 +00005651 frame_->Dup();
5652 Result ignored = frame_->CallRuntime(Runtime::kToSlowProperties, 1);
5653 }
5654
Steve Block6ded16b2010-05-10 14:33:55 +01005655 // Change to fast case at the end of an initialization block. To prepare for
5656 // that add an extra copy of the receiver to the frame, so that it can be
5657 // converted back to fast case after the assignment.
Andrei Popescu402d9372010-02-26 13:31:12 +00005658 if (node->ends_initialization_block()) {
Andrei Popescu402d9372010-02-26 13:31:12 +00005659 frame_->Dup();
5660 }
5661
5662 // Evaluate the key subexpression.
5663 Load(prop->key());
5664
Steve Block6ded16b2010-05-10 14:33:55 +01005665 // Stack layout:
5666 // [tos] : key
5667 // [tos+1] : receiver
5668 // [tos+2] : receiver if at the end of an initialization block
5669
Andrei Popescu402d9372010-02-26 13:31:12 +00005670 // Evaluate the right-hand side.
5671 if (node->is_compound()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005672 // For a compound assignment the right-hand side is a binary operation
5673 // between the current property value and the actual right-hand side.
5674 // Duplicate receiver and key for loading the current property value.
Andrei Popescu402d9372010-02-26 13:31:12 +00005675 frame()->PushElementAt(1);
5676 frame()->PushElementAt(1);
5677 Result value = EmitKeyedLoad();
5678 frame()->Push(&value);
5679 Load(node->value());
5680
Steve Block6ded16b2010-05-10 14:33:55 +01005681 // Perform the binary operation.
Andrei Popescu402d9372010-02-26 13:31:12 +00005682 bool overwrite_value =
5683 (node->value()->AsBinaryOperation() != NULL &&
5684 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
Steve Block6ded16b2010-05-10 14:33:55 +01005685 BinaryOperation expr(node, node->binary_op(), node->target(),
5686 node->value());
5687 GenericBinaryOperation(&expr,
Andrei Popescu402d9372010-02-26 13:31:12 +00005688 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
5689 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005690 // For non-compound assignment just load the right-hand side.
Andrei Popescu402d9372010-02-26 13:31:12 +00005691 Load(node->value());
5692 }
5693
Steve Block6ded16b2010-05-10 14:33:55 +01005694 // Stack layout:
5695 // [tos] : value
5696 // [tos+1] : key
5697 // [tos+2] : receiver
5698 // [tos+3] : receiver if at the end of an initialization block
5699
Andrei Popescu402d9372010-02-26 13:31:12 +00005700 // Perform the assignment. It is safe to ignore constants here.
5701 ASSERT(node->op() != Token::INIT_CONST);
5702 CodeForSourcePosition(node->position());
5703 Result answer = EmitKeyedStore(prop->key()->type());
5704 frame()->Push(&answer);
5705
Steve Block6ded16b2010-05-10 14:33:55 +01005706 // Stack layout:
5707 // [tos] : result
5708 // [tos+1] : receiver if at the end of an initialization block
5709
5710 // Change to fast case at the end of an initialization block.
Andrei Popescu402d9372010-02-26 13:31:12 +00005711 if (node->ends_initialization_block()) {
5712 // The argument to the runtime call is the extra copy of the receiver,
5713 // which is below the value of the assignment. Swap the receiver and
5714 // the value of the assignment expression.
5715 Result result = frame()->Pop();
5716 Result receiver = frame()->Pop();
5717 frame()->Push(&result);
5718 frame()->Push(&receiver);
5719 Result ignored = frame_->CallRuntime(Runtime::kToFastProperties, 1);
5720 }
5721
Steve Block6ded16b2010-05-10 14:33:55 +01005722 // Stack layout:
5723 // [tos] : result
5724
Andrei Popescu402d9372010-02-26 13:31:12 +00005725 ASSERT(frame()->height() == original_height + 1);
5726}
5727
5728
Steve Blocka7e24c12009-10-30 11:49:00 +00005729void CodeGenerator::VisitAssignment(Assignment* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005730 ASSERT(!in_safe_int32_mode());
Leon Clarked91b9f72010-01-27 17:25:45 +00005731#ifdef DEBUG
Andrei Popescu402d9372010-02-26 13:31:12 +00005732 int original_height = frame()->height();
Leon Clarked91b9f72010-01-27 17:25:45 +00005733#endif
Andrei Popescu402d9372010-02-26 13:31:12 +00005734 Variable* var = node->target()->AsVariableProxy()->AsVariable();
5735 Property* prop = node->target()->AsProperty();
Steve Blocka7e24c12009-10-30 11:49:00 +00005736
Andrei Popescu402d9372010-02-26 13:31:12 +00005737 if (var != NULL && !var->is_global()) {
5738 EmitSlotAssignment(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00005739
Andrei Popescu402d9372010-02-26 13:31:12 +00005740 } else if ((prop != NULL && prop->key()->IsPropertyName()) ||
5741 (var != NULL && var->is_global())) {
5742 // Properties whose keys are property names and global variables are
5743 // treated as named property references. We do not need to consider
5744 // global 'this' because it is not a valid left-hand side.
5745 EmitNamedPropertyAssignment(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00005746
Andrei Popescu402d9372010-02-26 13:31:12 +00005747 } else if (prop != NULL) {
5748 // Other properties (including rewritten parameters for a function that
5749 // uses arguments) are keyed property assignments.
5750 EmitKeyedPropertyAssignment(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00005751
Andrei Popescu402d9372010-02-26 13:31:12 +00005752 } else {
5753 // Invalid left-hand side.
5754 Load(node->target());
5755 Result result = frame()->CallRuntime(Runtime::kThrowReferenceError, 1);
5756 // The runtime call doesn't actually return but the code generator will
5757 // still generate code and expects a certain frame height.
5758 frame()->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00005759 }
Andrei Popescu402d9372010-02-26 13:31:12 +00005760
5761 ASSERT(frame()->height() == original_height + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00005762}
5763
5764
5765void CodeGenerator::VisitThrow(Throw* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005766 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005767 Comment cmnt(masm_, "[ Throw");
5768 Load(node->exception());
5769 Result result = frame_->CallRuntime(Runtime::kThrow, 1);
5770 frame_->Push(&result);
5771}
5772
5773
5774void CodeGenerator::VisitProperty(Property* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005775 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005776 Comment cmnt(masm_, "[ Property");
5777 Reference property(this, node);
Steve Blockd0582a62009-12-15 09:54:21 +00005778 property.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00005779}
5780
5781
5782void CodeGenerator::VisitCall(Call* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01005783 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005784 Comment cmnt(masm_, "[ Call");
5785
5786 Expression* function = node->expression();
5787 ZoneList<Expression*>* args = node->arguments();
5788
5789 // Check if the function is a variable or a property.
5790 Variable* var = function->AsVariableProxy()->AsVariable();
5791 Property* property = function->AsProperty();
5792
5793 // ------------------------------------------------------------------------
5794 // Fast-case: Use inline caching.
5795 // ---
5796 // According to ECMA-262, section 11.2.3, page 44, the function to call
5797 // must be resolved after the arguments have been evaluated. The IC code
5798 // automatically handles this by loading the arguments before the function
5799 // is resolved in cache misses (this also holds for megamorphic calls).
5800 // ------------------------------------------------------------------------
5801
5802 if (var != NULL && var->is_possibly_eval()) {
5803 // ----------------------------------
5804 // JavaScript example: 'eval(arg)' // eval is not known to be shadowed
5805 // ----------------------------------
5806
5807 // In a call to eval, we first call %ResolvePossiblyDirectEval to
5808 // resolve the function we need to call and the receiver of the
5809 // call. Then we call the resolved function using the given
5810 // arguments.
5811
5812 // Prepare the stack for the call to the resolved function.
5813 Load(function);
5814
5815 // Allocate a frame slot for the receiver.
5816 frame_->Push(Factory::undefined_value());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005817
5818 // Load the arguments.
Steve Blocka7e24c12009-10-30 11:49:00 +00005819 int arg_count = args->length();
5820 for (int i = 0; i < arg_count; i++) {
5821 Load(args->at(i));
Leon Clarkef7060e22010-06-03 12:02:55 +01005822 frame_->SpillTop();
Steve Blocka7e24c12009-10-30 11:49:00 +00005823 }
5824
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005825 // Result to hold the result of the function resolution and the
5826 // final result of the eval call.
5827 Result result;
5828
5829 // If we know that eval can only be shadowed by eval-introduced
5830 // variables we attempt to load the global eval function directly
5831 // in generated code. If we succeed, there is no need to perform a
5832 // context lookup in the runtime system.
5833 JumpTarget done;
5834 if (var->slot() != NULL && var->mode() == Variable::DYNAMIC_GLOBAL) {
5835 ASSERT(var->slot()->type() == Slot::LOOKUP);
5836 JumpTarget slow;
5837 // Prepare the stack for the call to
5838 // ResolvePossiblyDirectEvalNoLookup by pushing the loaded
5839 // function, the first argument to the eval call and the
5840 // receiver.
5841 Result fun = LoadFromGlobalSlotCheckExtensions(var->slot(),
5842 NOT_INSIDE_TYPEOF,
5843 &slow);
5844 frame_->Push(&fun);
5845 if (arg_count > 0) {
5846 frame_->PushElementAt(arg_count);
5847 } else {
5848 frame_->Push(Factory::undefined_value());
5849 }
5850 frame_->PushParameterAt(-1);
5851
5852 // Resolve the call.
5853 result =
5854 frame_->CallRuntime(Runtime::kResolvePossiblyDirectEvalNoLookup, 3);
5855
5856 done.Jump(&result);
5857 slow.Bind();
5858 }
5859
5860 // Prepare the stack for the call to ResolvePossiblyDirectEval by
5861 // pushing the loaded function, the first argument to the eval
5862 // call and the receiver.
Steve Blocka7e24c12009-10-30 11:49:00 +00005863 frame_->PushElementAt(arg_count + 1);
5864 if (arg_count > 0) {
5865 frame_->PushElementAt(arg_count);
5866 } else {
5867 frame_->Push(Factory::undefined_value());
5868 }
Leon Clarkee46be812010-01-19 14:06:41 +00005869 frame_->PushParameterAt(-1);
5870
Steve Blocka7e24c12009-10-30 11:49:00 +00005871 // Resolve the call.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005872 result = frame_->CallRuntime(Runtime::kResolvePossiblyDirectEval, 3);
5873
5874 // If we generated fast-case code bind the jump-target where fast
5875 // and slow case merge.
5876 if (done.is_linked()) done.Bind(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00005877
Leon Clarkee46be812010-01-19 14:06:41 +00005878 // The runtime call returns a pair of values in eax (function) and
5879 // edx (receiver). Touch up the stack with the right values.
5880 Result receiver = allocator_->Allocate(edx);
5881 frame_->SetElementAt(arg_count + 1, &result);
5882 frame_->SetElementAt(arg_count, &receiver);
5883 receiver.Unuse();
Steve Blocka7e24c12009-10-30 11:49:00 +00005884
5885 // Call the function.
5886 CodeForSourcePosition(node->position());
5887 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
Leon Clarkee46be812010-01-19 14:06:41 +00005888 CallFunctionStub call_function(arg_count, in_loop, RECEIVER_MIGHT_BE_VALUE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005889 result = frame_->CallStub(&call_function, arg_count + 1);
5890
5891 // Restore the context and overwrite the function on the stack with
5892 // the result.
5893 frame_->RestoreContextRegister();
5894 frame_->SetElementAt(0, &result);
5895
5896 } else if (var != NULL && !var->is_this() && var->is_global()) {
5897 // ----------------------------------
5898 // JavaScript example: 'foo(1, 2, 3)' // foo is global
5899 // ----------------------------------
5900
Steve Blocka7e24c12009-10-30 11:49:00 +00005901 // Pass the global object as the receiver and let the IC stub
5902 // patch the stack to use the global proxy as 'this' in the
5903 // invoked function.
5904 LoadGlobal();
5905
5906 // Load the arguments.
5907 int arg_count = args->length();
5908 for (int i = 0; i < arg_count; i++) {
5909 Load(args->at(i));
Leon Clarkef7060e22010-06-03 12:02:55 +01005910 frame_->SpillTop();
Steve Blocka7e24c12009-10-30 11:49:00 +00005911 }
5912
Leon Clarkee46be812010-01-19 14:06:41 +00005913 // Push the name of the function onto the frame.
5914 frame_->Push(var->name());
5915
Steve Blocka7e24c12009-10-30 11:49:00 +00005916 // Call the IC initialization code.
5917 CodeForSourcePosition(node->position());
5918 Result result = frame_->CallCallIC(RelocInfo::CODE_TARGET_CONTEXT,
5919 arg_count,
5920 loop_nesting());
5921 frame_->RestoreContextRegister();
Leon Clarkee46be812010-01-19 14:06:41 +00005922 frame_->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00005923
5924 } else if (var != NULL && var->slot() != NULL &&
5925 var->slot()->type() == Slot::LOOKUP) {
5926 // ----------------------------------
Kristian Monsen25f61362010-05-21 11:50:48 +01005927 // JavaScript examples:
5928 //
5929 // with (obj) foo(1, 2, 3) // foo may be in obj.
5930 //
5931 // function f() {};
5932 // function g() {
5933 // eval(...);
5934 // f(); // f could be in extension object.
5935 // }
Steve Blocka7e24c12009-10-30 11:49:00 +00005936 // ----------------------------------
5937
Kristian Monsen25f61362010-05-21 11:50:48 +01005938 JumpTarget slow, done;
5939 Result function;
5940
5941 // Generate fast case for loading functions from slots that
5942 // correspond to local/global variables or arguments unless they
5943 // are shadowed by eval-introduced bindings.
5944 EmitDynamicLoadFromSlotFastCase(var->slot(),
5945 NOT_INSIDE_TYPEOF,
5946 &function,
5947 &slow,
5948 &done);
5949
5950 slow.Bind();
5951 // Enter the runtime system to load the function from the context.
5952 // Sync the frame so we can push the arguments directly into
5953 // place.
Steve Blocka7e24c12009-10-30 11:49:00 +00005954 frame_->SyncRange(0, frame_->element_count() - 1);
5955 frame_->EmitPush(esi);
5956 frame_->EmitPush(Immediate(var->name()));
5957 frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
5958 // The runtime call returns a pair of values in eax and edx. The
5959 // looked-up function is in eax and the receiver is in edx. These
5960 // register references are not ref counted here. We spill them
5961 // eagerly since they are arguments to an inevitable call (and are
5962 // not sharable by the arguments).
5963 ASSERT(!allocator()->is_used(eax));
5964 frame_->EmitPush(eax);
5965
5966 // Load the receiver.
5967 ASSERT(!allocator()->is_used(edx));
5968 frame_->EmitPush(edx);
5969
Kristian Monsen25f61362010-05-21 11:50:48 +01005970 // If fast case code has been generated, emit code to push the
5971 // function and receiver and have the slow path jump around this
5972 // code.
5973 if (done.is_linked()) {
5974 JumpTarget call;
5975 call.Jump();
5976 done.Bind(&function);
5977 frame_->Push(&function);
5978 LoadGlobalReceiver();
5979 call.Bind();
5980 }
5981
Steve Blocka7e24c12009-10-30 11:49:00 +00005982 // Call the function.
Leon Clarkee46be812010-01-19 14:06:41 +00005983 CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00005984
5985 } else if (property != NULL) {
5986 // Check if the key is a literal string.
5987 Literal* literal = property->key()->AsLiteral();
5988
5989 if (literal != NULL && literal->handle()->IsSymbol()) {
5990 // ------------------------------------------------------------------
5991 // JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
5992 // ------------------------------------------------------------------
5993
5994 Handle<String> name = Handle<String>::cast(literal->handle());
5995
5996 if (ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION &&
5997 name->IsEqualTo(CStrVector("apply")) &&
5998 args->length() == 2 &&
5999 args->at(1)->AsVariableProxy() != NULL &&
6000 args->at(1)->AsVariableProxy()->IsArguments()) {
6001 // Use the optimized Function.prototype.apply that avoids
6002 // allocating lazily allocated arguments objects.
Leon Clarked91b9f72010-01-27 17:25:45 +00006003 CallApplyLazy(property->obj(),
Steve Blocka7e24c12009-10-30 11:49:00 +00006004 args->at(0),
6005 args->at(1)->AsVariableProxy(),
6006 node->position());
6007
6008 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00006009 // Push the receiver onto the frame.
Steve Blocka7e24c12009-10-30 11:49:00 +00006010 Load(property->obj());
6011
6012 // Load the arguments.
6013 int arg_count = args->length();
6014 for (int i = 0; i < arg_count; i++) {
6015 Load(args->at(i));
Leon Clarkef7060e22010-06-03 12:02:55 +01006016 frame_->SpillTop();
Steve Blocka7e24c12009-10-30 11:49:00 +00006017 }
6018
Leon Clarkee46be812010-01-19 14:06:41 +00006019 // Push the name of the function onto the frame.
6020 frame_->Push(name);
6021
Steve Blocka7e24c12009-10-30 11:49:00 +00006022 // Call the IC initialization code.
6023 CodeForSourcePosition(node->position());
6024 Result result =
6025 frame_->CallCallIC(RelocInfo::CODE_TARGET, arg_count,
6026 loop_nesting());
6027 frame_->RestoreContextRegister();
Leon Clarkee46be812010-01-19 14:06:41 +00006028 frame_->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00006029 }
6030
6031 } else {
6032 // -------------------------------------------
6033 // JavaScript example: 'array[index](1, 2, 3)'
6034 // -------------------------------------------
6035
6036 // Load the function to call from the property through a reference.
Steve Blocka7e24c12009-10-30 11:49:00 +00006037
6038 // Pass receiver to called function.
6039 if (property->is_synthetic()) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006040 Reference ref(this, property);
6041 ref.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00006042 // Use global object as receiver.
6043 LoadGlobalReceiver();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006044 // Call the function.
6045 CallWithArguments(args, RECEIVER_MIGHT_BE_VALUE, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00006046 } else {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006047 // Push the receiver onto the frame.
Leon Clarked91b9f72010-01-27 17:25:45 +00006048 Load(property->obj());
Steve Blocka7e24c12009-10-30 11:49:00 +00006049
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006050 // Load the arguments.
6051 int arg_count = args->length();
6052 for (int i = 0; i < arg_count; i++) {
6053 Load(args->at(i));
6054 frame_->SpillTop();
6055 }
6056
6057 // Load the name of the function.
6058 Load(property->key());
6059
6060 // Call the IC initialization code.
6061 CodeForSourcePosition(node->position());
6062 Result result =
6063 frame_->CallKeyedCallIC(RelocInfo::CODE_TARGET,
6064 arg_count,
6065 loop_nesting());
6066 frame_->RestoreContextRegister();
6067 frame_->Push(&result);
6068 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006069 }
6070
6071 } else {
6072 // ----------------------------------
6073 // JavaScript example: 'foo(1, 2, 3)' // foo is not global
6074 // ----------------------------------
6075
6076 // Load the function.
6077 Load(function);
6078
6079 // Pass the global proxy as the receiver.
6080 LoadGlobalReceiver();
6081
6082 // Call the function.
Leon Clarkee46be812010-01-19 14:06:41 +00006083 CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00006084 }
6085}
6086
6087
6088void CodeGenerator::VisitCallNew(CallNew* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01006089 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00006090 Comment cmnt(masm_, "[ CallNew");
6091
6092 // According to ECMA-262, section 11.2.2, page 44, the function
6093 // expression in new calls must be evaluated before the
6094 // arguments. This is different from ordinary calls, where the
6095 // actual function to call is resolved after the arguments have been
6096 // evaluated.
6097
6098 // Compute function to call and use the global object as the
6099 // receiver. There is no need to use the global proxy here because
6100 // it will always be replaced with a newly allocated object.
6101 Load(node->expression());
6102 LoadGlobal();
6103
6104 // Push the arguments ("left-to-right") on the stack.
6105 ZoneList<Expression*>* args = node->arguments();
6106 int arg_count = args->length();
6107 for (int i = 0; i < arg_count; i++) {
6108 Load(args->at(i));
6109 }
6110
6111 // Call the construct call builtin that handles allocation and
6112 // constructor invocation.
6113 CodeForSourcePosition(node->position());
6114 Result result = frame_->CallConstructor(arg_count);
6115 // Replace the function on the stack with the result.
6116 frame_->SetElementAt(0, &result);
6117}
6118
6119
6120void CodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
6121 ASSERT(args->length() == 1);
6122 Load(args->at(0));
6123 Result value = frame_->Pop();
6124 value.ToRegister();
6125 ASSERT(value.is_valid());
6126 __ test(value.reg(), Immediate(kSmiTagMask));
6127 value.Unuse();
6128 destination()->Split(zero);
6129}
6130
6131
6132void CodeGenerator::GenerateLog(ZoneList<Expression*>* args) {
6133 // Conditionally generate a log call.
6134 // Args:
6135 // 0 (literal string): The type of logging (corresponds to the flags).
6136 // This is used to determine whether or not to generate the log call.
6137 // 1 (string): Format string. Access the string at argument index 2
6138 // with '%2s' (see Logger::LogRuntime for all the formats).
6139 // 2 (array): Arguments to the format string.
6140 ASSERT_EQ(args->length(), 3);
6141#ifdef ENABLE_LOGGING_AND_PROFILING
6142 if (ShouldGenerateLog(args->at(0))) {
6143 Load(args->at(1));
6144 Load(args->at(2));
6145 frame_->CallRuntime(Runtime::kLog, 2);
6146 }
6147#endif
6148 // Finally, we're expected to leave a value on the top of the stack.
6149 frame_->Push(Factory::undefined_value());
6150}
6151
6152
6153void CodeGenerator::GenerateIsNonNegativeSmi(ZoneList<Expression*>* args) {
6154 ASSERT(args->length() == 1);
6155 Load(args->at(0));
6156 Result value = frame_->Pop();
6157 value.ToRegister();
6158 ASSERT(value.is_valid());
Steve Block6ded16b2010-05-10 14:33:55 +01006159 __ test(value.reg(), Immediate(kSmiTagMask | kSmiSignMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00006160 value.Unuse();
6161 destination()->Split(zero);
6162}
6163
6164
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006165class DeferredStringCharCodeAt : public DeferredCode {
6166 public:
6167 DeferredStringCharCodeAt(Register object,
6168 Register index,
6169 Register scratch,
6170 Register result)
6171 : result_(result),
6172 char_code_at_generator_(object,
6173 index,
6174 scratch,
6175 result,
6176 &need_conversion_,
6177 &need_conversion_,
6178 &index_out_of_range_,
6179 STRING_INDEX_IS_NUMBER) {}
6180
6181 StringCharCodeAtGenerator* fast_case_generator() {
6182 return &char_code_at_generator_;
6183 }
6184
6185 virtual void Generate() {
6186 VirtualFrameRuntimeCallHelper call_helper(frame_state());
6187 char_code_at_generator_.GenerateSlow(masm(), call_helper);
6188
6189 __ bind(&need_conversion_);
6190 // Move the undefined value into the result register, which will
6191 // trigger conversion.
6192 __ Set(result_, Immediate(Factory::undefined_value()));
6193 __ jmp(exit_label());
6194
6195 __ bind(&index_out_of_range_);
6196 // When the index is out of range, the spec requires us to return
6197 // NaN.
6198 __ Set(result_, Immediate(Factory::nan_value()));
6199 __ jmp(exit_label());
6200 }
6201
6202 private:
6203 Register result_;
6204
6205 Label need_conversion_;
6206 Label index_out_of_range_;
6207
6208 StringCharCodeAtGenerator char_code_at_generator_;
6209};
6210
6211
6212// This generates code that performs a String.prototype.charCodeAt() call
6213// or returns a smi in order to trigger conversion.
6214void CodeGenerator::GenerateStringCharCodeAt(ZoneList<Expression*>* args) {
6215 Comment(masm_, "[ GenerateStringCharCodeAt");
Steve Blocka7e24c12009-10-30 11:49:00 +00006216 ASSERT(args->length() == 2);
6217
Steve Blocka7e24c12009-10-30 11:49:00 +00006218 Load(args->at(0));
6219 Load(args->at(1));
6220 Result index = frame_->Pop();
6221 Result object = frame_->Pop();
Steve Blocka7e24c12009-10-30 11:49:00 +00006222 object.ToRegister();
6223 index.ToRegister();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006224 // We might mutate the object register.
Steve Blocka7e24c12009-10-30 11:49:00 +00006225 frame_->Spill(object.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00006226
Steve Block6ded16b2010-05-10 14:33:55 +01006227 // We need two extra registers.
6228 Result result = allocator()->Allocate();
6229 ASSERT(result.is_valid());
6230 Result scratch = allocator()->Allocate();
6231 ASSERT(scratch.is_valid());
Steve Blocka7e24c12009-10-30 11:49:00 +00006232
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006233 DeferredStringCharCodeAt* deferred =
6234 new DeferredStringCharCodeAt(object.reg(),
6235 index.reg(),
6236 scratch.reg(),
6237 result.reg());
6238 deferred->fast_case_generator()->GenerateFast(masm_);
6239 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01006240 frame_->Push(&result);
6241}
6242
6243
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006244class DeferredStringCharFromCode : public DeferredCode {
6245 public:
6246 DeferredStringCharFromCode(Register code,
6247 Register result)
6248 : char_from_code_generator_(code, result) {}
6249
6250 StringCharFromCodeGenerator* fast_case_generator() {
6251 return &char_from_code_generator_;
6252 }
6253
6254 virtual void Generate() {
6255 VirtualFrameRuntimeCallHelper call_helper(frame_state());
6256 char_from_code_generator_.GenerateSlow(masm(), call_helper);
6257 }
6258
6259 private:
6260 StringCharFromCodeGenerator char_from_code_generator_;
6261};
6262
6263
6264// Generates code for creating a one-char string from a char code.
6265void CodeGenerator::GenerateStringCharFromCode(ZoneList<Expression*>* args) {
6266 Comment(masm_, "[ GenerateStringCharFromCode");
Steve Block6ded16b2010-05-10 14:33:55 +01006267 ASSERT(args->length() == 1);
6268
6269 Load(args->at(0));
6270
6271 Result code = frame_->Pop();
6272 code.ToRegister();
6273 ASSERT(code.is_valid());
6274
Steve Block6ded16b2010-05-10 14:33:55 +01006275 Result result = allocator()->Allocate();
6276 ASSERT(result.is_valid());
6277
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006278 DeferredStringCharFromCode* deferred = new DeferredStringCharFromCode(
6279 code.reg(), result.reg());
6280 deferred->fast_case_generator()->GenerateFast(masm_);
6281 deferred->BindExit();
6282 frame_->Push(&result);
6283}
6284
6285
6286class DeferredStringCharAt : public DeferredCode {
6287 public:
6288 DeferredStringCharAt(Register object,
6289 Register index,
6290 Register scratch1,
6291 Register scratch2,
6292 Register result)
6293 : result_(result),
6294 char_at_generator_(object,
6295 index,
6296 scratch1,
6297 scratch2,
6298 result,
6299 &need_conversion_,
6300 &need_conversion_,
6301 &index_out_of_range_,
6302 STRING_INDEX_IS_NUMBER) {}
6303
6304 StringCharAtGenerator* fast_case_generator() {
6305 return &char_at_generator_;
6306 }
6307
6308 virtual void Generate() {
6309 VirtualFrameRuntimeCallHelper call_helper(frame_state());
6310 char_at_generator_.GenerateSlow(masm(), call_helper);
6311
6312 __ bind(&need_conversion_);
6313 // Move smi zero into the result register, which will trigger
6314 // conversion.
6315 __ Set(result_, Immediate(Smi::FromInt(0)));
6316 __ jmp(exit_label());
6317
6318 __ bind(&index_out_of_range_);
6319 // When the index is out of range, the spec requires us to return
6320 // the empty string.
6321 __ Set(result_, Immediate(Factory::empty_string()));
6322 __ jmp(exit_label());
6323 }
6324
6325 private:
6326 Register result_;
6327
6328 Label need_conversion_;
6329 Label index_out_of_range_;
6330
6331 StringCharAtGenerator char_at_generator_;
6332};
6333
6334
6335// This generates code that performs a String.prototype.charAt() call
6336// or returns a smi in order to trigger conversion.
6337void CodeGenerator::GenerateStringCharAt(ZoneList<Expression*>* args) {
6338 Comment(masm_, "[ GenerateStringCharAt");
6339 ASSERT(args->length() == 2);
6340
6341 Load(args->at(0));
6342 Load(args->at(1));
6343 Result index = frame_->Pop();
6344 Result object = frame_->Pop();
6345 object.ToRegister();
6346 index.ToRegister();
6347 // We might mutate the object register.
6348 frame_->Spill(object.reg());
6349
6350 // We need three extra registers.
6351 Result result = allocator()->Allocate();
6352 ASSERT(result.is_valid());
6353 Result scratch1 = allocator()->Allocate();
6354 ASSERT(scratch1.is_valid());
6355 Result scratch2 = allocator()->Allocate();
6356 ASSERT(scratch2.is_valid());
6357
6358 DeferredStringCharAt* deferred =
6359 new DeferredStringCharAt(object.reg(),
6360 index.reg(),
6361 scratch1.reg(),
6362 scratch2.reg(),
6363 result.reg());
6364 deferred->fast_case_generator()->GenerateFast(masm_);
6365 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01006366 frame_->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00006367}
6368
6369
6370void CodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
6371 ASSERT(args->length() == 1);
6372 Load(args->at(0));
6373 Result value = frame_->Pop();
6374 value.ToRegister();
6375 ASSERT(value.is_valid());
6376 __ test(value.reg(), Immediate(kSmiTagMask));
6377 destination()->false_target()->Branch(equal);
6378 // It is a heap object - get map.
6379 Result temp = allocator()->Allocate();
6380 ASSERT(temp.is_valid());
6381 // Check if the object is a JS array or not.
6382 __ CmpObjectType(value.reg(), JS_ARRAY_TYPE, temp.reg());
6383 value.Unuse();
6384 temp.Unuse();
6385 destination()->Split(equal);
6386}
6387
6388
Andrei Popescu402d9372010-02-26 13:31:12 +00006389void CodeGenerator::GenerateIsRegExp(ZoneList<Expression*>* args) {
6390 ASSERT(args->length() == 1);
6391 Load(args->at(0));
6392 Result value = frame_->Pop();
6393 value.ToRegister();
6394 ASSERT(value.is_valid());
6395 __ test(value.reg(), Immediate(kSmiTagMask));
6396 destination()->false_target()->Branch(equal);
6397 // It is a heap object - get map.
6398 Result temp = allocator()->Allocate();
6399 ASSERT(temp.is_valid());
6400 // Check if the object is a regexp.
6401 __ CmpObjectType(value.reg(), JS_REGEXP_TYPE, temp.reg());
6402 value.Unuse();
6403 temp.Unuse();
6404 destination()->Split(equal);
6405}
6406
6407
Steve Blockd0582a62009-12-15 09:54:21 +00006408void CodeGenerator::GenerateIsObject(ZoneList<Expression*>* args) {
6409 // This generates a fast version of:
6410 // (typeof(arg) === 'object' || %_ClassOf(arg) == 'RegExp')
6411 ASSERT(args->length() == 1);
6412 Load(args->at(0));
6413 Result obj = frame_->Pop();
6414 obj.ToRegister();
6415
6416 __ test(obj.reg(), Immediate(kSmiTagMask));
6417 destination()->false_target()->Branch(zero);
6418 __ cmp(obj.reg(), Factory::null_value());
6419 destination()->true_target()->Branch(equal);
6420
6421 Result map = allocator()->Allocate();
6422 ASSERT(map.is_valid());
6423 __ mov(map.reg(), FieldOperand(obj.reg(), HeapObject::kMapOffset));
6424 // Undetectable objects behave like undefined when tested with typeof.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006425 __ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
6426 1 << Map::kIsUndetectable);
Steve Blockd0582a62009-12-15 09:54:21 +00006427 destination()->false_target()->Branch(not_zero);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006428 // Do a range test for JSObject type. We can't use
6429 // MacroAssembler::IsInstanceJSObjectType, because we are using a
6430 // ControlDestination, so we copy its implementation here.
Steve Blockd0582a62009-12-15 09:54:21 +00006431 __ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006432 __ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
6433 __ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
Steve Blockd0582a62009-12-15 09:54:21 +00006434 obj.Unuse();
6435 map.Unuse();
Leon Clarkef7060e22010-06-03 12:02:55 +01006436 destination()->Split(below_equal);
Steve Blockd0582a62009-12-15 09:54:21 +00006437}
6438
6439
Ben Murdoch3bec4d22010-07-22 14:51:16 +01006440 void CodeGenerator::GenerateIsSpecObject(ZoneList<Expression*>* args) {
6441 // This generates a fast version of:
6442 // (typeof(arg) === 'object' || %_ClassOf(arg) == 'RegExp' ||
6443 // typeof(arg) == function).
6444 // It includes undetectable objects (as opposed to IsObject).
6445 ASSERT(args->length() == 1);
6446 Load(args->at(0));
6447 Result value = frame_->Pop();
6448 value.ToRegister();
6449 ASSERT(value.is_valid());
6450 __ test(value.reg(), Immediate(kSmiTagMask));
6451 destination()->false_target()->Branch(equal);
6452
6453 // Check that this is an object.
6454 frame_->Spill(value.reg());
6455 __ CmpObjectType(value.reg(), FIRST_JS_OBJECT_TYPE, value.reg());
6456 value.Unuse();
6457 destination()->Split(above_equal);
6458}
6459
6460
Steve Blockd0582a62009-12-15 09:54:21 +00006461void CodeGenerator::GenerateIsFunction(ZoneList<Expression*>* args) {
6462 // This generates a fast version of:
6463 // (%_ClassOf(arg) === 'Function')
6464 ASSERT(args->length() == 1);
6465 Load(args->at(0));
6466 Result obj = frame_->Pop();
6467 obj.ToRegister();
6468 __ test(obj.reg(), Immediate(kSmiTagMask));
6469 destination()->false_target()->Branch(zero);
6470 Result temp = allocator()->Allocate();
6471 ASSERT(temp.is_valid());
6472 __ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, temp.reg());
6473 obj.Unuse();
6474 temp.Unuse();
6475 destination()->Split(equal);
6476}
6477
6478
Leon Clarked91b9f72010-01-27 17:25:45 +00006479void CodeGenerator::GenerateIsUndetectableObject(ZoneList<Expression*>* args) {
6480 ASSERT(args->length() == 1);
6481 Load(args->at(0));
6482 Result obj = frame_->Pop();
6483 obj.ToRegister();
6484 __ test(obj.reg(), Immediate(kSmiTagMask));
6485 destination()->false_target()->Branch(zero);
6486 Result temp = allocator()->Allocate();
6487 ASSERT(temp.is_valid());
6488 __ mov(temp.reg(),
6489 FieldOperand(obj.reg(), HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006490 __ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
6491 1 << Map::kIsUndetectable);
Leon Clarked91b9f72010-01-27 17:25:45 +00006492 obj.Unuse();
6493 temp.Unuse();
6494 destination()->Split(not_zero);
6495}
6496
6497
Steve Blocka7e24c12009-10-30 11:49:00 +00006498void CodeGenerator::GenerateIsConstructCall(ZoneList<Expression*>* args) {
6499 ASSERT(args->length() == 0);
6500
6501 // Get the frame pointer for the calling frame.
6502 Result fp = allocator()->Allocate();
6503 __ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6504
6505 // Skip the arguments adaptor frame if it exists.
6506 Label check_frame_marker;
6507 __ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
6508 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6509 __ j(not_equal, &check_frame_marker);
6510 __ mov(fp.reg(), Operand(fp.reg(), StandardFrameConstants::kCallerFPOffset));
6511
6512 // Check the marker in the calling frame.
6513 __ bind(&check_frame_marker);
6514 __ cmp(Operand(fp.reg(), StandardFrameConstants::kMarkerOffset),
6515 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6516 fp.Unuse();
6517 destination()->Split(equal);
6518}
6519
6520
6521void CodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
6522 ASSERT(args->length() == 0);
Steve Block6ded16b2010-05-10 14:33:55 +01006523
6524 Result fp = allocator_->Allocate();
6525 Result result = allocator_->Allocate();
6526 ASSERT(fp.is_valid() && result.is_valid());
6527
6528 Label exit;
6529
6530 // Get the number of formal parameters.
6531 __ Set(result.reg(), Immediate(Smi::FromInt(scope()->num_parameters())));
6532
6533 // Check if the calling frame is an arguments adaptor frame.
6534 __ mov(fp.reg(), Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6535 __ cmp(Operand(fp.reg(), StandardFrameConstants::kContextOffset),
6536 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6537 __ j(not_equal, &exit);
6538
6539 // Arguments adaptor case: Read the arguments length from the
6540 // adaptor frame.
6541 __ mov(result.reg(),
6542 Operand(fp.reg(), ArgumentsAdaptorFrameConstants::kLengthOffset));
6543
6544 __ bind(&exit);
6545 result.set_type_info(TypeInfo::Smi());
6546 if (FLAG_debug_code) __ AbortIfNotSmi(result.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00006547 frame_->Push(&result);
6548}
6549
6550
6551void CodeGenerator::GenerateClassOf(ZoneList<Expression*>* args) {
6552 ASSERT(args->length() == 1);
6553 JumpTarget leave, null, function, non_function_constructor;
6554 Load(args->at(0)); // Load the object.
6555 Result obj = frame_->Pop();
6556 obj.ToRegister();
6557 frame_->Spill(obj.reg());
6558
6559 // If the object is a smi, we return null.
6560 __ test(obj.reg(), Immediate(kSmiTagMask));
6561 null.Branch(zero);
6562
6563 // Check that the object is a JS object but take special care of JS
6564 // functions to make sure they have 'Function' as their class.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006565 __ CmpObjectType(obj.reg(), FIRST_JS_OBJECT_TYPE, obj.reg());
6566 null.Branch(below);
Steve Blocka7e24c12009-10-30 11:49:00 +00006567
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006568 // As long as JS_FUNCTION_TYPE is the last instance type and it is
6569 // right after LAST_JS_OBJECT_TYPE, we can avoid checking for
6570 // LAST_JS_OBJECT_TYPE.
6571 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
6572 ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
6573 __ CmpInstanceType(obj.reg(), JS_FUNCTION_TYPE);
6574 function.Branch(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +00006575
6576 // Check if the constructor in the map is a function.
6577 { Result tmp = allocator()->Allocate();
6578 __ mov(obj.reg(), FieldOperand(obj.reg(), Map::kConstructorOffset));
6579 __ CmpObjectType(obj.reg(), JS_FUNCTION_TYPE, tmp.reg());
6580 non_function_constructor.Branch(not_equal);
6581 }
6582
6583 // The map register now contains the constructor function. Grab the
6584 // instance class name from there.
6585 __ mov(obj.reg(),
6586 FieldOperand(obj.reg(), JSFunction::kSharedFunctionInfoOffset));
6587 __ mov(obj.reg(),
6588 FieldOperand(obj.reg(), SharedFunctionInfo::kInstanceClassNameOffset));
6589 frame_->Push(&obj);
6590 leave.Jump();
6591
6592 // Functions have class 'Function'.
6593 function.Bind();
6594 frame_->Push(Factory::function_class_symbol());
6595 leave.Jump();
6596
6597 // Objects with a non-function constructor have class 'Object'.
6598 non_function_constructor.Bind();
6599 frame_->Push(Factory::Object_symbol());
6600 leave.Jump();
6601
6602 // Non-JS objects have class null.
6603 null.Bind();
6604 frame_->Push(Factory::null_value());
6605
6606 // All done.
6607 leave.Bind();
6608}
6609
6610
6611void CodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
6612 ASSERT(args->length() == 1);
6613 JumpTarget leave;
6614 Load(args->at(0)); // Load the object.
6615 frame_->Dup();
6616 Result object = frame_->Pop();
6617 object.ToRegister();
6618 ASSERT(object.is_valid());
6619 // if (object->IsSmi()) return object.
6620 __ test(object.reg(), Immediate(kSmiTagMask));
6621 leave.Branch(zero, taken);
6622 // It is a heap object - get map.
6623 Result temp = allocator()->Allocate();
6624 ASSERT(temp.is_valid());
6625 // if (!object->IsJSValue()) return object.
6626 __ CmpObjectType(object.reg(), JS_VALUE_TYPE, temp.reg());
6627 leave.Branch(not_equal, not_taken);
6628 __ mov(temp.reg(), FieldOperand(object.reg(), JSValue::kValueOffset));
6629 object.Unuse();
6630 frame_->SetElementAt(0, &temp);
6631 leave.Bind();
6632}
6633
6634
6635void CodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
6636 ASSERT(args->length() == 2);
6637 JumpTarget leave;
6638 Load(args->at(0)); // Load the object.
6639 Load(args->at(1)); // Load the value.
6640 Result value = frame_->Pop();
6641 Result object = frame_->Pop();
6642 value.ToRegister();
6643 object.ToRegister();
6644
6645 // if (object->IsSmi()) return value.
6646 __ test(object.reg(), Immediate(kSmiTagMask));
6647 leave.Branch(zero, &value, taken);
6648
6649 // It is a heap object - get its map.
6650 Result scratch = allocator_->Allocate();
6651 ASSERT(scratch.is_valid());
6652 // if (!object->IsJSValue()) return value.
6653 __ CmpObjectType(object.reg(), JS_VALUE_TYPE, scratch.reg());
6654 leave.Branch(not_equal, &value, not_taken);
6655
6656 // Store the value.
6657 __ mov(FieldOperand(object.reg(), JSValue::kValueOffset), value.reg());
6658 // Update the write barrier. Save the value as it will be
6659 // overwritten by the write barrier code and is needed afterward.
6660 Result duplicate_value = allocator_->Allocate();
6661 ASSERT(duplicate_value.is_valid());
6662 __ mov(duplicate_value.reg(), value.reg());
6663 // The object register is also overwritten by the write barrier and
6664 // possibly aliased in the frame.
6665 frame_->Spill(object.reg());
6666 __ RecordWrite(object.reg(), JSValue::kValueOffset, duplicate_value.reg(),
6667 scratch.reg());
6668 object.Unuse();
6669 scratch.Unuse();
6670 duplicate_value.Unuse();
6671
6672 // Leave.
6673 leave.Bind(&value);
6674 frame_->Push(&value);
6675}
6676
6677
Steve Block6ded16b2010-05-10 14:33:55 +01006678void CodeGenerator::GenerateArguments(ZoneList<Expression*>* args) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006679 ASSERT(args->length() == 1);
6680
6681 // ArgumentsAccessStub expects the key in edx and the formal
6682 // parameter count in eax.
6683 Load(args->at(0));
6684 Result key = frame_->Pop();
6685 // Explicitly create a constant result.
Andrei Popescu31002712010-02-23 13:46:05 +00006686 Result count(Handle<Smi>(Smi::FromInt(scope()->num_parameters())));
Steve Blocka7e24c12009-10-30 11:49:00 +00006687 // Call the shared stub to get to arguments[key].
6688 ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT);
6689 Result result = frame_->CallStub(&stub, &key, &count);
6690 frame_->Push(&result);
6691}
6692
6693
6694void CodeGenerator::GenerateObjectEquals(ZoneList<Expression*>* args) {
6695 ASSERT(args->length() == 2);
6696
6697 // Load the two objects into registers and perform the comparison.
6698 Load(args->at(0));
6699 Load(args->at(1));
6700 Result right = frame_->Pop();
6701 Result left = frame_->Pop();
6702 right.ToRegister();
6703 left.ToRegister();
6704 __ cmp(right.reg(), Operand(left.reg()));
6705 right.Unuse();
6706 left.Unuse();
6707 destination()->Split(equal);
6708}
6709
6710
6711void CodeGenerator::GenerateGetFramePointer(ZoneList<Expression*>* args) {
6712 ASSERT(args->length() == 0);
6713 ASSERT(kSmiTag == 0); // EBP value is aligned, so it should look like Smi.
6714 Result ebp_as_smi = allocator_->Allocate();
6715 ASSERT(ebp_as_smi.is_valid());
6716 __ mov(ebp_as_smi.reg(), Operand(ebp));
6717 frame_->Push(&ebp_as_smi);
6718}
6719
6720
Steve Block6ded16b2010-05-10 14:33:55 +01006721void CodeGenerator::GenerateRandomHeapNumber(
6722 ZoneList<Expression*>* args) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006723 ASSERT(args->length() == 0);
6724 frame_->SpillAll();
6725
Steve Block6ded16b2010-05-10 14:33:55 +01006726 Label slow_allocate_heapnumber;
6727 Label heapnumber_allocated;
Steve Blocka7e24c12009-10-30 11:49:00 +00006728
Steve Block6ded16b2010-05-10 14:33:55 +01006729 __ AllocateHeapNumber(edi, ebx, ecx, &slow_allocate_heapnumber);
6730 __ jmp(&heapnumber_allocated);
Steve Blocka7e24c12009-10-30 11:49:00 +00006731
Steve Block6ded16b2010-05-10 14:33:55 +01006732 __ bind(&slow_allocate_heapnumber);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01006733 // Allocate a heap number.
6734 __ CallRuntime(Runtime::kNumberAlloc, 0);
Steve Block6ded16b2010-05-10 14:33:55 +01006735 __ mov(edi, eax);
6736
6737 __ bind(&heapnumber_allocated);
6738
6739 __ PrepareCallCFunction(0, ebx);
6740 __ CallCFunction(ExternalReference::random_uint32_function(), 0);
6741
6742 // Convert 32 random bits in eax to 0.(32 random bits) in a double
6743 // by computing:
6744 // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
6745 // This is implemented on both SSE2 and FPU.
6746 if (CpuFeatures::IsSupported(SSE2)) {
6747 CpuFeatures::Scope fscope(SSE2);
6748 __ mov(ebx, Immediate(0x49800000)); // 1.0 x 2^20 as single.
6749 __ movd(xmm1, Operand(ebx));
6750 __ movd(xmm0, Operand(eax));
6751 __ cvtss2sd(xmm1, xmm1);
6752 __ pxor(xmm0, xmm1);
6753 __ subsd(xmm0, xmm1);
6754 __ movdbl(FieldOperand(edi, HeapNumber::kValueOffset), xmm0);
6755 } else {
6756 // 0x4130000000000000 is 1.0 x 2^20 as a double.
6757 __ mov(FieldOperand(edi, HeapNumber::kExponentOffset),
6758 Immediate(0x41300000));
6759 __ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), eax);
6760 __ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
6761 __ mov(FieldOperand(edi, HeapNumber::kMantissaOffset), Immediate(0));
6762 __ fld_d(FieldOperand(edi, HeapNumber::kValueOffset));
6763 __ fsubp(1);
6764 __ fstp_d(FieldOperand(edi, HeapNumber::kValueOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00006765 }
Steve Block6ded16b2010-05-10 14:33:55 +01006766 __ mov(eax, edi);
Steve Blocka7e24c12009-10-30 11:49:00 +00006767
6768 Result result = allocator_->Allocate(eax);
6769 frame_->Push(&result);
6770}
6771
6772
Steve Blockd0582a62009-12-15 09:54:21 +00006773void CodeGenerator::GenerateStringAdd(ZoneList<Expression*>* args) {
6774 ASSERT_EQ(2, args->length());
6775
6776 Load(args->at(0));
6777 Load(args->at(1));
6778
6779 StringAddStub stub(NO_STRING_ADD_FLAGS);
6780 Result answer = frame_->CallStub(&stub, 2);
6781 frame_->Push(&answer);
6782}
6783
6784
Leon Clarkee46be812010-01-19 14:06:41 +00006785void CodeGenerator::GenerateSubString(ZoneList<Expression*>* args) {
6786 ASSERT_EQ(3, args->length());
6787
6788 Load(args->at(0));
6789 Load(args->at(1));
6790 Load(args->at(2));
6791
6792 SubStringStub stub;
6793 Result answer = frame_->CallStub(&stub, 3);
6794 frame_->Push(&answer);
6795}
6796
6797
6798void CodeGenerator::GenerateStringCompare(ZoneList<Expression*>* args) {
6799 ASSERT_EQ(2, args->length());
6800
6801 Load(args->at(0));
6802 Load(args->at(1));
6803
6804 StringCompareStub stub;
6805 Result answer = frame_->CallStub(&stub, 2);
6806 frame_->Push(&answer);
6807}
6808
6809
6810void CodeGenerator::GenerateRegExpExec(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01006811 ASSERT_EQ(4, args->length());
Leon Clarkee46be812010-01-19 14:06:41 +00006812
6813 // Load the arguments on the stack and call the stub.
6814 Load(args->at(0));
6815 Load(args->at(1));
6816 Load(args->at(2));
6817 Load(args->at(3));
6818 RegExpExecStub stub;
6819 Result result = frame_->CallStub(&stub, 4);
6820 frame_->Push(&result);
6821}
6822
6823
Steve Block6ded16b2010-05-10 14:33:55 +01006824void CodeGenerator::GenerateRegExpConstructResult(ZoneList<Expression*>* args) {
6825 // No stub. This code only occurs a few times in regexp.js.
6826 const int kMaxInlineLength = 100;
6827 ASSERT_EQ(3, args->length());
6828 Load(args->at(0)); // Size of array, smi.
6829 Load(args->at(1)); // "index" property value.
6830 Load(args->at(2)); // "input" property value.
6831 {
6832 VirtualFrame::SpilledScope spilled_scope;
6833
6834 Label slowcase;
6835 Label done;
6836 __ mov(ebx, Operand(esp, kPointerSize * 2));
6837 __ test(ebx, Immediate(kSmiTagMask));
6838 __ j(not_zero, &slowcase);
6839 __ cmp(Operand(ebx), Immediate(Smi::FromInt(kMaxInlineLength)));
6840 __ j(above, &slowcase);
6841 // Smi-tagging is equivalent to multiplying by 2.
6842 STATIC_ASSERT(kSmiTag == 0);
6843 STATIC_ASSERT(kSmiTagSize == 1);
6844 // Allocate RegExpResult followed by FixedArray with size in ebx.
6845 // JSArray: [Map][empty properties][Elements][Length-smi][index][input]
6846 // Elements: [Map][Length][..elements..]
6847 __ AllocateInNewSpace(JSRegExpResult::kSize + FixedArray::kHeaderSize,
6848 times_half_pointer_size,
6849 ebx, // In: Number of elements (times 2, being a smi)
6850 eax, // Out: Start of allocation (tagged).
6851 ecx, // Out: End of allocation.
6852 edx, // Scratch register
6853 &slowcase,
6854 TAG_OBJECT);
6855 // eax: Start of allocated area, object-tagged.
6856
6857 // Set JSArray map to global.regexp_result_map().
6858 // Set empty properties FixedArray.
6859 // Set elements to point to FixedArray allocated right after the JSArray.
6860 // Interleave operations for better latency.
6861 __ mov(edx, ContextOperand(esi, Context::GLOBAL_INDEX));
6862 __ mov(ecx, Immediate(Factory::empty_fixed_array()));
6863 __ lea(ebx, Operand(eax, JSRegExpResult::kSize));
6864 __ mov(edx, FieldOperand(edx, GlobalObject::kGlobalContextOffset));
6865 __ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
6866 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ecx);
6867 __ mov(edx, ContextOperand(edx, Context::REGEXP_RESULT_MAP_INDEX));
6868 __ mov(FieldOperand(eax, HeapObject::kMapOffset), edx);
6869
6870 // Set input, index and length fields from arguments.
6871 __ pop(FieldOperand(eax, JSRegExpResult::kInputOffset));
6872 __ pop(FieldOperand(eax, JSRegExpResult::kIndexOffset));
6873 __ pop(ecx);
6874 __ mov(FieldOperand(eax, JSArray::kLengthOffset), ecx);
6875
6876 // Fill out the elements FixedArray.
6877 // eax: JSArray.
6878 // ebx: FixedArray.
6879 // ecx: Number of elements in array, as smi.
6880
6881 // Set map.
6882 __ mov(FieldOperand(ebx, HeapObject::kMapOffset),
6883 Immediate(Factory::fixed_array_map()));
6884 // Set length.
Steve Block6ded16b2010-05-10 14:33:55 +01006885 __ mov(FieldOperand(ebx, FixedArray::kLengthOffset), ecx);
6886 // Fill contents of fixed-array with the-hole.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006887 __ SmiUntag(ecx);
Steve Block6ded16b2010-05-10 14:33:55 +01006888 __ mov(edx, Immediate(Factory::the_hole_value()));
6889 __ lea(ebx, FieldOperand(ebx, FixedArray::kHeaderSize));
6890 // Fill fixed array elements with hole.
6891 // eax: JSArray.
6892 // ecx: Number of elements to fill.
6893 // ebx: Start of elements in FixedArray.
6894 // edx: the hole.
6895 Label loop;
6896 __ test(ecx, Operand(ecx));
6897 __ bind(&loop);
6898 __ j(less_equal, &done); // Jump if ecx is negative or zero.
6899 __ sub(Operand(ecx), Immediate(1));
6900 __ mov(Operand(ebx, ecx, times_pointer_size, 0), edx);
6901 __ jmp(&loop);
6902
6903 __ bind(&slowcase);
6904 __ CallRuntime(Runtime::kRegExpConstructResult, 3);
6905
6906 __ bind(&done);
6907 }
6908 frame_->Forget(3);
6909 frame_->Push(eax);
6910}
6911
6912
6913class DeferredSearchCache: public DeferredCode {
6914 public:
6915 DeferredSearchCache(Register dst, Register cache, Register key)
6916 : dst_(dst), cache_(cache), key_(key) {
6917 set_comment("[ DeferredSearchCache");
6918 }
6919
6920 virtual void Generate();
6921
6922 private:
Kristian Monsen25f61362010-05-21 11:50:48 +01006923 Register dst_; // on invocation Smi index of finger, on exit
6924 // holds value being looked up.
6925 Register cache_; // instance of JSFunctionResultCache.
6926 Register key_; // key being looked up.
Steve Block6ded16b2010-05-10 14:33:55 +01006927};
6928
6929
6930void DeferredSearchCache::Generate() {
Kristian Monsen25f61362010-05-21 11:50:48 +01006931 Label first_loop, search_further, second_loop, cache_miss;
6932
6933 // Smi-tagging is equivalent to multiplying by 2.
6934 STATIC_ASSERT(kSmiTag == 0);
6935 STATIC_ASSERT(kSmiTagSize == 1);
6936
6937 Smi* kEntrySizeSmi = Smi::FromInt(JSFunctionResultCache::kEntrySize);
6938 Smi* kEntriesIndexSmi = Smi::FromInt(JSFunctionResultCache::kEntriesIndex);
6939
6940 // Check the cache from finger to start of the cache.
6941 __ bind(&first_loop);
6942 __ sub(Operand(dst_), Immediate(kEntrySizeSmi));
6943 __ cmp(Operand(dst_), Immediate(kEntriesIndexSmi));
6944 __ j(less, &search_further);
6945
6946 __ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
6947 __ j(not_equal, &first_loop);
6948
6949 __ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
6950 __ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
6951 __ jmp(exit_label());
6952
6953 __ bind(&search_further);
6954
6955 // Check the cache from end of cache up to finger.
6956 __ mov(dst_, FieldOperand(cache_, JSFunctionResultCache::kCacheSizeOffset));
6957
6958 __ bind(&second_loop);
6959 __ sub(Operand(dst_), Immediate(kEntrySizeSmi));
6960 // Consider prefetching into some reg.
6961 __ cmp(dst_, FieldOperand(cache_, JSFunctionResultCache::kFingerOffset));
6962 __ j(less_equal, &cache_miss);
6963
6964 __ cmp(key_, CodeGenerator::FixedArrayElementOperand(cache_, dst_));
6965 __ j(not_equal, &second_loop);
6966
6967 __ mov(FieldOperand(cache_, JSFunctionResultCache::kFingerOffset), dst_);
6968 __ mov(dst_, CodeGenerator::FixedArrayElementOperand(cache_, dst_, 1));
6969 __ jmp(exit_label());
6970
6971 __ bind(&cache_miss);
6972 __ push(cache_); // store a reference to cache
6973 __ push(key_); // store a key
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01006974 __ push(Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
Steve Block6ded16b2010-05-10 14:33:55 +01006975 __ push(key_);
Kristian Monsen25f61362010-05-21 11:50:48 +01006976 // On ia32 function must be in edi.
6977 __ mov(edi, FieldOperand(cache_, JSFunctionResultCache::kFactoryOffset));
6978 ParameterCount expected(1);
6979 __ InvokeFunction(edi, expected, CALL_FUNCTION);
6980
6981 // Find a place to put new cached value into.
6982 Label add_new_entry, update_cache;
6983 __ mov(ecx, Operand(esp, kPointerSize)); // restore the cache
6984 // Possible optimization: cache size is constant for the given cache
6985 // so technically we could use a constant here. However, if we have
6986 // cache miss this optimization would hardly matter much.
6987
6988 // Check if we could add new entry to cache.
6989 __ mov(ebx, FieldOperand(ecx, FixedArray::kLengthOffset));
Kristian Monsen25f61362010-05-21 11:50:48 +01006990 __ cmp(ebx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
6991 __ j(greater, &add_new_entry);
6992
6993 // Check if we could evict entry after finger.
6994 __ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
6995 __ add(Operand(edx), Immediate(kEntrySizeSmi));
6996 __ cmp(ebx, Operand(edx));
6997 __ j(greater, &update_cache);
6998
6999 // Need to wrap over the cache.
7000 __ mov(edx, Immediate(kEntriesIndexSmi));
7001 __ jmp(&update_cache);
7002
7003 __ bind(&add_new_entry);
7004 __ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset));
7005 __ lea(ebx, Operand(edx, JSFunctionResultCache::kEntrySize << 1));
7006 __ mov(FieldOperand(ecx, JSFunctionResultCache::kCacheSizeOffset), ebx);
7007
7008 // Update the cache itself.
7009 // edx holds the index.
7010 __ bind(&update_cache);
7011 __ pop(ebx); // restore the key
7012 __ mov(FieldOperand(ecx, JSFunctionResultCache::kFingerOffset), edx);
7013 // Store key.
7014 __ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
7015 __ RecordWrite(ecx, 0, ebx, edx);
7016
7017 // Store value.
7018 __ pop(ecx); // restore the cache.
7019 __ mov(edx, FieldOperand(ecx, JSFunctionResultCache::kFingerOffset));
7020 __ add(Operand(edx), Immediate(Smi::FromInt(1)));
7021 __ mov(ebx, eax);
7022 __ mov(CodeGenerator::FixedArrayElementOperand(ecx, edx), ebx);
7023 __ RecordWrite(ecx, 0, ebx, edx);
7024
Steve Block6ded16b2010-05-10 14:33:55 +01007025 if (!dst_.is(eax)) {
7026 __ mov(dst_, eax);
7027 }
7028}
7029
7030
7031void CodeGenerator::GenerateGetFromCache(ZoneList<Expression*>* args) {
7032 ASSERT_EQ(2, args->length());
7033
7034 ASSERT_NE(NULL, args->at(0)->AsLiteral());
7035 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->handle()))->value();
7036
7037 Handle<FixedArray> jsfunction_result_caches(
7038 Top::global_context()->jsfunction_result_caches());
7039 if (jsfunction_result_caches->length() <= cache_id) {
7040 __ Abort("Attempt to use undefined cache.");
7041 frame_->Push(Factory::undefined_value());
7042 return;
7043 }
7044
7045 Load(args->at(1));
7046 Result key = frame_->Pop();
7047 key.ToRegister();
7048
7049 Result cache = allocator()->Allocate();
7050 ASSERT(cache.is_valid());
7051 __ mov(cache.reg(), ContextOperand(esi, Context::GLOBAL_INDEX));
7052 __ mov(cache.reg(),
7053 FieldOperand(cache.reg(), GlobalObject::kGlobalContextOffset));
7054 __ mov(cache.reg(),
7055 ContextOperand(cache.reg(), Context::JSFUNCTION_RESULT_CACHES_INDEX));
7056 __ mov(cache.reg(),
7057 FieldOperand(cache.reg(), FixedArray::OffsetOfElementAt(cache_id)));
7058
7059 Result tmp = allocator()->Allocate();
7060 ASSERT(tmp.is_valid());
7061
7062 DeferredSearchCache* deferred = new DeferredSearchCache(tmp.reg(),
7063 cache.reg(),
7064 key.reg());
7065
Steve Block6ded16b2010-05-10 14:33:55 +01007066 // tmp.reg() now holds finger offset as a smi.
7067 ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
Kristian Monsen25f61362010-05-21 11:50:48 +01007068 __ mov(tmp.reg(), FieldOperand(cache.reg(),
7069 JSFunctionResultCache::kFingerOffset));
7070 __ cmp(key.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg()));
Steve Block6ded16b2010-05-10 14:33:55 +01007071 deferred->Branch(not_equal);
7072
Kristian Monsen25f61362010-05-21 11:50:48 +01007073 __ mov(tmp.reg(), FixedArrayElementOperand(cache.reg(), tmp.reg(), 1));
Steve Block6ded16b2010-05-10 14:33:55 +01007074
7075 deferred->BindExit();
7076 frame_->Push(&tmp);
7077}
7078
7079
Andrei Popescu402d9372010-02-26 13:31:12 +00007080void CodeGenerator::GenerateNumberToString(ZoneList<Expression*>* args) {
7081 ASSERT_EQ(args->length(), 1);
7082
7083 // Load the argument on the stack and call the stub.
7084 Load(args->at(0));
7085 NumberToStringStub stub;
7086 Result result = frame_->CallStub(&stub, 1);
7087 frame_->Push(&result);
7088}
7089
7090
Steve Block6ded16b2010-05-10 14:33:55 +01007091class DeferredSwapElements: public DeferredCode {
7092 public:
7093 DeferredSwapElements(Register object, Register index1, Register index2)
7094 : object_(object), index1_(index1), index2_(index2) {
7095 set_comment("[ DeferredSwapElements");
7096 }
7097
7098 virtual void Generate();
7099
7100 private:
7101 Register object_, index1_, index2_;
7102};
7103
7104
7105void DeferredSwapElements::Generate() {
7106 __ push(object_);
7107 __ push(index1_);
7108 __ push(index2_);
7109 __ CallRuntime(Runtime::kSwapElements, 3);
7110}
7111
7112
7113void CodeGenerator::GenerateSwapElements(ZoneList<Expression*>* args) {
7114 // Note: this code assumes that indices are passed are within
7115 // elements' bounds and refer to valid (not holes) values.
7116 Comment cmnt(masm_, "[ GenerateSwapElements");
7117
7118 ASSERT_EQ(3, args->length());
7119
7120 Load(args->at(0));
7121 Load(args->at(1));
7122 Load(args->at(2));
7123
7124 Result index2 = frame_->Pop();
7125 index2.ToRegister();
7126
7127 Result index1 = frame_->Pop();
7128 index1.ToRegister();
7129
7130 Result object = frame_->Pop();
7131 object.ToRegister();
7132
7133 Result tmp1 = allocator()->Allocate();
7134 tmp1.ToRegister();
7135 Result tmp2 = allocator()->Allocate();
7136 tmp2.ToRegister();
7137
7138 frame_->Spill(object.reg());
7139 frame_->Spill(index1.reg());
7140 frame_->Spill(index2.reg());
7141
7142 DeferredSwapElements* deferred = new DeferredSwapElements(object.reg(),
7143 index1.reg(),
7144 index2.reg());
7145
7146 // Fetch the map and check if array is in fast case.
7147 // Check that object doesn't require security checks and
7148 // has no indexed interceptor.
7149 __ CmpObjectType(object.reg(), FIRST_JS_OBJECT_TYPE, tmp1.reg());
Leon Clarkef7060e22010-06-03 12:02:55 +01007150 deferred->Branch(below);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007151 __ test_b(FieldOperand(tmp1.reg(), Map::kBitFieldOffset),
7152 KeyedLoadIC::kSlowCaseBitFieldMask);
Steve Block6ded16b2010-05-10 14:33:55 +01007153 deferred->Branch(not_zero);
7154
7155 // Check the object's elements are in fast case.
7156 __ mov(tmp1.reg(), FieldOperand(object.reg(), JSObject::kElementsOffset));
7157 __ cmp(FieldOperand(tmp1.reg(), HeapObject::kMapOffset),
7158 Immediate(Factory::fixed_array_map()));
7159 deferred->Branch(not_equal);
7160
7161 // Smi-tagging is equivalent to multiplying by 2.
7162 STATIC_ASSERT(kSmiTag == 0);
7163 STATIC_ASSERT(kSmiTagSize == 1);
7164
7165 // Check that both indices are smis.
7166 __ mov(tmp2.reg(), index1.reg());
7167 __ or_(tmp2.reg(), Operand(index2.reg()));
7168 __ test(tmp2.reg(), Immediate(kSmiTagMask));
7169 deferred->Branch(not_zero);
7170
7171 // Bring addresses into index1 and index2.
Kristian Monsen25f61362010-05-21 11:50:48 +01007172 __ lea(index1.reg(), FixedArrayElementOperand(tmp1.reg(), index1.reg()));
7173 __ lea(index2.reg(), FixedArrayElementOperand(tmp1.reg(), index2.reg()));
Steve Block6ded16b2010-05-10 14:33:55 +01007174
7175 // Swap elements.
7176 __ mov(object.reg(), Operand(index1.reg(), 0));
7177 __ mov(tmp2.reg(), Operand(index2.reg(), 0));
7178 __ mov(Operand(index2.reg(), 0), object.reg());
7179 __ mov(Operand(index1.reg(), 0), tmp2.reg());
7180
7181 Label done;
7182 __ InNewSpace(tmp1.reg(), tmp2.reg(), equal, &done);
7183 // Possible optimization: do a check that both values are Smis
7184 // (or them and test against Smi mask.)
7185
7186 __ mov(tmp2.reg(), tmp1.reg());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007187 __ RecordWriteHelper(tmp2.reg(), index1.reg(), object.reg());
7188 __ RecordWriteHelper(tmp1.reg(), index2.reg(), object.reg());
Steve Block6ded16b2010-05-10 14:33:55 +01007189 __ bind(&done);
7190
7191 deferred->BindExit();
7192 frame_->Push(Factory::undefined_value());
7193}
7194
7195
7196void CodeGenerator::GenerateCallFunction(ZoneList<Expression*>* args) {
7197 Comment cmnt(masm_, "[ GenerateCallFunction");
7198
7199 ASSERT(args->length() >= 2);
7200
7201 int n_args = args->length() - 2; // for receiver and function.
7202 Load(args->at(0)); // receiver
7203 for (int i = 0; i < n_args; i++) {
7204 Load(args->at(i + 1));
7205 }
7206 Load(args->at(n_args + 1)); // function
7207 Result result = frame_->CallJSFunction(n_args);
7208 frame_->Push(&result);
7209}
7210
7211
7212// Generates the Math.pow method. Only handles special cases and
7213// branches to the runtime system for everything else. Please note
7214// that this function assumes that the callsite has executed ToNumber
7215// on both arguments.
7216void CodeGenerator::GenerateMathPow(ZoneList<Expression*>* args) {
7217 ASSERT(args->length() == 2);
7218 Load(args->at(0));
7219 Load(args->at(1));
7220 if (!CpuFeatures::IsSupported(SSE2)) {
7221 Result res = frame_->CallRuntime(Runtime::kMath_pow, 2);
7222 frame_->Push(&res);
7223 } else {
7224 CpuFeatures::Scope use_sse2(SSE2);
7225 Label allocate_return;
7226 // Load the two operands while leaving the values on the frame.
7227 frame()->Dup();
7228 Result exponent = frame()->Pop();
7229 exponent.ToRegister();
7230 frame()->Spill(exponent.reg());
7231 frame()->PushElementAt(1);
7232 Result base = frame()->Pop();
7233 base.ToRegister();
7234 frame()->Spill(base.reg());
7235
7236 Result answer = allocator()->Allocate();
7237 ASSERT(answer.is_valid());
7238 ASSERT(!exponent.reg().is(base.reg()));
7239 JumpTarget call_runtime;
7240
7241 // Save 1 in xmm3 - we need this several times later on.
7242 __ mov(answer.reg(), Immediate(1));
7243 __ cvtsi2sd(xmm3, Operand(answer.reg()));
7244
7245 Label exponent_nonsmi;
7246 Label base_nonsmi;
7247 // If the exponent is a heap number go to that specific case.
7248 __ test(exponent.reg(), Immediate(kSmiTagMask));
7249 __ j(not_zero, &exponent_nonsmi);
7250 __ test(base.reg(), Immediate(kSmiTagMask));
7251 __ j(not_zero, &base_nonsmi);
7252
7253 // Optimized version when y is an integer.
7254 Label powi;
7255 __ SmiUntag(base.reg());
7256 __ cvtsi2sd(xmm0, Operand(base.reg()));
7257 __ jmp(&powi);
7258 // exponent is smi and base is a heapnumber.
7259 __ bind(&base_nonsmi);
7260 __ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
7261 Factory::heap_number_map());
7262 call_runtime.Branch(not_equal);
7263
7264 __ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
7265
7266 // Optimized version of pow if y is an integer.
7267 __ bind(&powi);
7268 __ SmiUntag(exponent.reg());
7269
7270 // Save exponent in base as we need to check if exponent is negative later.
7271 // We know that base and exponent are in different registers.
7272 __ mov(base.reg(), exponent.reg());
7273
7274 // Get absolute value of exponent.
7275 Label no_neg;
7276 __ cmp(exponent.reg(), 0);
7277 __ j(greater_equal, &no_neg);
7278 __ neg(exponent.reg());
7279 __ bind(&no_neg);
7280
7281 // Load xmm1 with 1.
7282 __ movsd(xmm1, xmm3);
7283 Label while_true;
7284 Label no_multiply;
7285
7286 __ bind(&while_true);
7287 __ shr(exponent.reg(), 1);
7288 __ j(not_carry, &no_multiply);
7289 __ mulsd(xmm1, xmm0);
7290 __ bind(&no_multiply);
7291 __ test(exponent.reg(), Operand(exponent.reg()));
7292 __ mulsd(xmm0, xmm0);
7293 __ j(not_zero, &while_true);
7294
7295 // x has the original value of y - if y is negative return 1/result.
7296 __ test(base.reg(), Operand(base.reg()));
7297 __ j(positive, &allocate_return);
7298 // Special case if xmm1 has reached infinity.
7299 __ mov(answer.reg(), Immediate(0x7FB00000));
7300 __ movd(xmm0, Operand(answer.reg()));
7301 __ cvtss2sd(xmm0, xmm0);
7302 __ ucomisd(xmm0, xmm1);
7303 call_runtime.Branch(equal);
7304 __ divsd(xmm3, xmm1);
7305 __ movsd(xmm1, xmm3);
7306 __ jmp(&allocate_return);
7307
7308 // exponent (or both) is a heapnumber - no matter what we should now work
7309 // on doubles.
7310 __ bind(&exponent_nonsmi);
7311 __ cmp(FieldOperand(exponent.reg(), HeapObject::kMapOffset),
7312 Factory::heap_number_map());
7313 call_runtime.Branch(not_equal);
7314 __ movdbl(xmm1, FieldOperand(exponent.reg(), HeapNumber::kValueOffset));
7315 // Test if exponent is nan.
7316 __ ucomisd(xmm1, xmm1);
7317 call_runtime.Branch(parity_even);
7318
7319 Label base_not_smi;
7320 Label handle_special_cases;
7321 __ test(base.reg(), Immediate(kSmiTagMask));
7322 __ j(not_zero, &base_not_smi);
7323 __ SmiUntag(base.reg());
7324 __ cvtsi2sd(xmm0, Operand(base.reg()));
7325 __ jmp(&handle_special_cases);
7326 __ bind(&base_not_smi);
7327 __ cmp(FieldOperand(base.reg(), HeapObject::kMapOffset),
7328 Factory::heap_number_map());
7329 call_runtime.Branch(not_equal);
7330 __ mov(answer.reg(), FieldOperand(base.reg(), HeapNumber::kExponentOffset));
7331 __ and_(answer.reg(), HeapNumber::kExponentMask);
7332 __ cmp(Operand(answer.reg()), Immediate(HeapNumber::kExponentMask));
7333 // base is NaN or +/-Infinity
7334 call_runtime.Branch(greater_equal);
7335 __ movdbl(xmm0, FieldOperand(base.reg(), HeapNumber::kValueOffset));
7336
7337 // base is in xmm0 and exponent is in xmm1.
7338 __ bind(&handle_special_cases);
7339 Label not_minus_half;
7340 // Test for -0.5.
7341 // Load xmm2 with -0.5.
7342 __ mov(answer.reg(), Immediate(0xBF000000));
7343 __ movd(xmm2, Operand(answer.reg()));
7344 __ cvtss2sd(xmm2, xmm2);
7345 // xmm2 now has -0.5.
7346 __ ucomisd(xmm2, xmm1);
7347 __ j(not_equal, &not_minus_half);
7348
7349 // Calculates reciprocal of square root.
7350 // Note that 1/sqrt(x) = sqrt(1/x))
7351 __ divsd(xmm3, xmm0);
7352 __ movsd(xmm1, xmm3);
7353 __ sqrtsd(xmm1, xmm1);
7354 __ jmp(&allocate_return);
7355
7356 // Test for 0.5.
7357 __ bind(&not_minus_half);
7358 // Load xmm2 with 0.5.
7359 // Since xmm3 is 1 and xmm2 is -0.5 this is simply xmm2 + xmm3.
7360 __ addsd(xmm2, xmm3);
7361 // xmm2 now has 0.5.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01007362 __ ucomisd(xmm2, xmm1);
Steve Block6ded16b2010-05-10 14:33:55 +01007363 call_runtime.Branch(not_equal);
7364 // Calculates square root.
7365 __ movsd(xmm1, xmm0);
7366 __ sqrtsd(xmm1, xmm1);
7367
7368 JumpTarget done;
7369 Label failure, success;
7370 __ bind(&allocate_return);
7371 // Make a copy of the frame to enable us to handle allocation
7372 // failure after the JumpTarget jump.
7373 VirtualFrame* clone = new VirtualFrame(frame());
7374 __ AllocateHeapNumber(answer.reg(), exponent.reg(),
7375 base.reg(), &failure);
7376 __ movdbl(FieldOperand(answer.reg(), HeapNumber::kValueOffset), xmm1);
7377 // Remove the two original values from the frame - we only need those
7378 // in the case where we branch to runtime.
7379 frame()->Drop(2);
7380 exponent.Unuse();
7381 base.Unuse();
7382 done.Jump(&answer);
7383 // Use the copy of the original frame as our current frame.
7384 RegisterFile empty_regs;
7385 SetFrame(clone, &empty_regs);
7386 // If we experience an allocation failure we branch to runtime.
7387 __ bind(&failure);
7388 call_runtime.Bind();
7389 answer = frame()->CallRuntime(Runtime::kMath_pow_cfunction, 2);
7390
7391 done.Bind(&answer);
7392 frame()->Push(&answer);
7393 }
7394}
7395
7396
Andrei Popescu402d9372010-02-26 13:31:12 +00007397void CodeGenerator::GenerateMathSin(ZoneList<Expression*>* args) {
7398 ASSERT_EQ(args->length(), 1);
7399 Load(args->at(0));
7400 TranscendentalCacheStub stub(TranscendentalCache::SIN);
7401 Result result = frame_->CallStub(&stub, 1);
7402 frame_->Push(&result);
7403}
7404
7405
7406void CodeGenerator::GenerateMathCos(ZoneList<Expression*>* args) {
7407 ASSERT_EQ(args->length(), 1);
7408 Load(args->at(0));
7409 TranscendentalCacheStub stub(TranscendentalCache::COS);
7410 Result result = frame_->CallStub(&stub, 1);
7411 frame_->Push(&result);
7412}
7413
7414
Steve Block6ded16b2010-05-10 14:33:55 +01007415// Generates the Math.sqrt method. Please note - this function assumes that
7416// the callsite has executed ToNumber on the argument.
7417void CodeGenerator::GenerateMathSqrt(ZoneList<Expression*>* args) {
7418 ASSERT_EQ(args->length(), 1);
7419 Load(args->at(0));
7420
7421 if (!CpuFeatures::IsSupported(SSE2)) {
7422 Result result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
7423 frame()->Push(&result);
7424 } else {
7425 CpuFeatures::Scope use_sse2(SSE2);
7426 // Leave original value on the frame if we need to call runtime.
7427 frame()->Dup();
7428 Result result = frame()->Pop();
7429 result.ToRegister();
7430 frame()->Spill(result.reg());
7431 Label runtime;
7432 Label non_smi;
7433 Label load_done;
7434 JumpTarget end;
7435
7436 __ test(result.reg(), Immediate(kSmiTagMask));
7437 __ j(not_zero, &non_smi);
7438 __ SmiUntag(result.reg());
7439 __ cvtsi2sd(xmm0, Operand(result.reg()));
7440 __ jmp(&load_done);
7441 __ bind(&non_smi);
7442 __ cmp(FieldOperand(result.reg(), HeapObject::kMapOffset),
7443 Factory::heap_number_map());
7444 __ j(not_equal, &runtime);
7445 __ movdbl(xmm0, FieldOperand(result.reg(), HeapNumber::kValueOffset));
7446
7447 __ bind(&load_done);
7448 __ sqrtsd(xmm0, xmm0);
7449 // A copy of the virtual frame to allow us to go to runtime after the
7450 // JumpTarget jump.
7451 Result scratch = allocator()->Allocate();
7452 VirtualFrame* clone = new VirtualFrame(frame());
7453 __ AllocateHeapNumber(result.reg(), scratch.reg(), no_reg, &runtime);
7454
7455 __ movdbl(FieldOperand(result.reg(), HeapNumber::kValueOffset), xmm0);
7456 frame()->Drop(1);
7457 scratch.Unuse();
7458 end.Jump(&result);
7459 // We only branch to runtime if we have an allocation error.
7460 // Use the copy of the original frame as our current frame.
7461 RegisterFile empty_regs;
7462 SetFrame(clone, &empty_regs);
7463 __ bind(&runtime);
7464 result = frame()->CallRuntime(Runtime::kMath_sqrt, 1);
7465
7466 end.Bind(&result);
7467 frame()->Push(&result);
7468 }
7469}
7470
7471
Steve Blocka7e24c12009-10-30 11:49:00 +00007472void CodeGenerator::VisitCallRuntime(CallRuntime* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01007473 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00007474 if (CheckForInlineRuntimeCall(node)) {
7475 return;
7476 }
7477
7478 ZoneList<Expression*>* args = node->arguments();
7479 Comment cmnt(masm_, "[ CallRuntime");
7480 Runtime::Function* function = node->function();
7481
7482 if (function == NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007483 // Push the builtins object found in the current global object.
7484 Result temp = allocator()->Allocate();
7485 ASSERT(temp.is_valid());
7486 __ mov(temp.reg(), GlobalObject());
7487 __ mov(temp.reg(), FieldOperand(temp.reg(), GlobalObject::kBuiltinsOffset));
7488 frame_->Push(&temp);
7489 }
7490
7491 // Push the arguments ("left-to-right").
7492 int arg_count = args->length();
7493 for (int i = 0; i < arg_count; i++) {
7494 Load(args->at(i));
7495 }
7496
7497 if (function == NULL) {
7498 // Call the JS runtime function.
Leon Clarkee46be812010-01-19 14:06:41 +00007499 frame_->Push(node->name());
Steve Blocka7e24c12009-10-30 11:49:00 +00007500 Result answer = frame_->CallCallIC(RelocInfo::CODE_TARGET,
7501 arg_count,
7502 loop_nesting_);
7503 frame_->RestoreContextRegister();
Leon Clarkee46be812010-01-19 14:06:41 +00007504 frame_->Push(&answer);
Steve Blocka7e24c12009-10-30 11:49:00 +00007505 } else {
7506 // Call the C runtime function.
7507 Result answer = frame_->CallRuntime(function, arg_count);
7508 frame_->Push(&answer);
7509 }
7510}
7511
7512
7513void CodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007514 Comment cmnt(masm_, "[ UnaryOperation");
7515
7516 Token::Value op = node->op();
7517
7518 if (op == Token::NOT) {
7519 // Swap the true and false targets but keep the same actual label
7520 // as the fall through.
7521 destination()->Invert();
Steve Blockd0582a62009-12-15 09:54:21 +00007522 LoadCondition(node->expression(), destination(), true);
Steve Blocka7e24c12009-10-30 11:49:00 +00007523 // Swap the labels back.
7524 destination()->Invert();
7525
7526 } else if (op == Token::DELETE) {
7527 Property* property = node->expression()->AsProperty();
7528 if (property != NULL) {
7529 Load(property->obj());
7530 Load(property->key());
7531 Result answer = frame_->InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, 2);
7532 frame_->Push(&answer);
7533 return;
7534 }
7535
7536 Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
7537 if (variable != NULL) {
7538 Slot* slot = variable->slot();
7539 if (variable->is_global()) {
7540 LoadGlobal();
7541 frame_->Push(variable->name());
7542 Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
7543 CALL_FUNCTION, 2);
7544 frame_->Push(&answer);
7545 return;
7546
7547 } else if (slot != NULL && slot->type() == Slot::LOOKUP) {
7548 // Call the runtime to look up the context holding the named
7549 // variable. Sync the virtual frame eagerly so we can push the
7550 // arguments directly into place.
7551 frame_->SyncRange(0, frame_->element_count() - 1);
7552 frame_->EmitPush(esi);
7553 frame_->EmitPush(Immediate(variable->name()));
7554 Result context = frame_->CallRuntime(Runtime::kLookupContext, 2);
7555 ASSERT(context.is_register());
7556 frame_->EmitPush(context.reg());
7557 context.Unuse();
7558 frame_->EmitPush(Immediate(variable->name()));
7559 Result answer = frame_->InvokeBuiltin(Builtins::DELETE,
7560 CALL_FUNCTION, 2);
7561 frame_->Push(&answer);
7562 return;
7563 }
7564
7565 // Default: Result of deleting non-global, not dynamically
7566 // introduced variables is false.
7567 frame_->Push(Factory::false_value());
7568
7569 } else {
7570 // Default: Result of deleting expressions is true.
7571 Load(node->expression()); // may have side-effects
7572 frame_->SetElementAt(0, Factory::true_value());
7573 }
7574
7575 } else if (op == Token::TYPEOF) {
7576 // Special case for loading the typeof expression; see comment on
7577 // LoadTypeofExpression().
7578 LoadTypeofExpression(node->expression());
7579 Result answer = frame_->CallRuntime(Runtime::kTypeof, 1);
7580 frame_->Push(&answer);
7581
7582 } else if (op == Token::VOID) {
7583 Expression* expression = node->expression();
7584 if (expression && expression->AsLiteral() && (
7585 expression->AsLiteral()->IsTrue() ||
7586 expression->AsLiteral()->IsFalse() ||
7587 expression->AsLiteral()->handle()->IsNumber() ||
7588 expression->AsLiteral()->handle()->IsString() ||
7589 expression->AsLiteral()->handle()->IsJSRegExp() ||
7590 expression->AsLiteral()->IsNull())) {
7591 // Omit evaluating the value of the primitive literal.
7592 // It will be discarded anyway, and can have no side effect.
7593 frame_->Push(Factory::undefined_value());
7594 } else {
7595 Load(node->expression());
7596 frame_->SetElementAt(0, Factory::undefined_value());
7597 }
7598
7599 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01007600 if (in_safe_int32_mode()) {
7601 Visit(node->expression());
7602 Result value = frame_->Pop();
7603 ASSERT(value.is_untagged_int32());
7604 // Registers containing an int32 value are not multiply used.
7605 ASSERT(!value.is_register() || !frame_->is_used(value.reg()));
7606 value.ToRegister();
7607 switch (op) {
7608 case Token::SUB: {
7609 __ neg(value.reg());
7610 if (node->no_negative_zero()) {
7611 // -MIN_INT is MIN_INT with the overflow flag set.
7612 unsafe_bailout_->Branch(overflow);
7613 } else {
7614 // MIN_INT and 0 both have bad negations. They both have 31 zeros.
7615 __ test(value.reg(), Immediate(0x7FFFFFFF));
7616 unsafe_bailout_->Branch(zero);
7617 }
7618 break;
7619 }
7620 case Token::BIT_NOT: {
7621 __ not_(value.reg());
7622 break;
7623 }
7624 case Token::ADD: {
7625 // Unary plus has no effect on int32 values.
7626 break;
7627 }
7628 default:
7629 UNREACHABLE();
7630 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00007631 }
Steve Block6ded16b2010-05-10 14:33:55 +01007632 frame_->Push(&value);
7633 } else {
7634 Load(node->expression());
Leon Clarkeac952652010-07-15 11:15:24 +01007635 bool can_overwrite =
Steve Block6ded16b2010-05-10 14:33:55 +01007636 (node->expression()->AsBinaryOperation() != NULL &&
7637 node->expression()->AsBinaryOperation()->ResultOverwriteAllowed());
Leon Clarkeac952652010-07-15 11:15:24 +01007638 UnaryOverwriteMode overwrite =
7639 can_overwrite ? UNARY_OVERWRITE : UNARY_NO_OVERWRITE;
7640 bool no_negative_zero = node->expression()->no_negative_zero();
Steve Block6ded16b2010-05-10 14:33:55 +01007641 switch (op) {
7642 case Token::NOT:
7643 case Token::DELETE:
7644 case Token::TYPEOF:
7645 UNREACHABLE(); // handled above
7646 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00007647
Steve Block6ded16b2010-05-10 14:33:55 +01007648 case Token::SUB: {
Leon Clarkeac952652010-07-15 11:15:24 +01007649 GenericUnaryOpStub stub(
7650 Token::SUB,
7651 overwrite,
7652 no_negative_zero ? kIgnoreNegativeZero : kStrictNegativeZero);
Steve Block6ded16b2010-05-10 14:33:55 +01007653 Result operand = frame_->Pop();
7654 Result answer = frame_->CallStub(&stub, &operand);
7655 answer.set_type_info(TypeInfo::Number());
7656 frame_->Push(&answer);
7657 break;
7658 }
7659 case Token::BIT_NOT: {
7660 // Smi check.
7661 JumpTarget smi_label;
7662 JumpTarget continue_label;
7663 Result operand = frame_->Pop();
7664 TypeInfo operand_info = operand.type_info();
7665 operand.ToRegister();
7666 if (operand_info.IsSmi()) {
7667 if (FLAG_debug_code) __ AbortIfNotSmi(operand.reg());
7668 frame_->Spill(operand.reg());
7669 // Set smi tag bit. It will be reset by the not operation.
7670 __ lea(operand.reg(), Operand(operand.reg(), kSmiTagMask));
7671 __ not_(operand.reg());
7672 Result answer = operand;
7673 answer.set_type_info(TypeInfo::Smi());
7674 frame_->Push(&answer);
7675 } else {
7676 __ test(operand.reg(), Immediate(kSmiTagMask));
7677 smi_label.Branch(zero, &operand, taken);
Steve Blocka7e24c12009-10-30 11:49:00 +00007678
Steve Block6ded16b2010-05-10 14:33:55 +01007679 GenericUnaryOpStub stub(Token::BIT_NOT, overwrite);
7680 Result answer = frame_->CallStub(&stub, &operand);
7681 continue_label.Jump(&answer);
Leon Clarkee46be812010-01-19 14:06:41 +00007682
Steve Block6ded16b2010-05-10 14:33:55 +01007683 smi_label.Bind(&answer);
7684 answer.ToRegister();
7685 frame_->Spill(answer.reg());
7686 // Set smi tag bit. It will be reset by the not operation.
7687 __ lea(answer.reg(), Operand(answer.reg(), kSmiTagMask));
7688 __ not_(answer.reg());
Leon Clarkee46be812010-01-19 14:06:41 +00007689
Steve Block6ded16b2010-05-10 14:33:55 +01007690 continue_label.Bind(&answer);
7691 answer.set_type_info(TypeInfo::Integer32());
7692 frame_->Push(&answer);
7693 }
7694 break;
7695 }
7696 case Token::ADD: {
7697 // Smi check.
7698 JumpTarget continue_label;
7699 Result operand = frame_->Pop();
7700 TypeInfo operand_info = operand.type_info();
7701 operand.ToRegister();
7702 __ test(operand.reg(), Immediate(kSmiTagMask));
7703 continue_label.Branch(zero, &operand, taken);
Steve Blocka7e24c12009-10-30 11:49:00 +00007704
Steve Block6ded16b2010-05-10 14:33:55 +01007705 frame_->Push(&operand);
7706 Result answer = frame_->InvokeBuiltin(Builtins::TO_NUMBER,
Steve Blocka7e24c12009-10-30 11:49:00 +00007707 CALL_FUNCTION, 1);
7708
Steve Block6ded16b2010-05-10 14:33:55 +01007709 continue_label.Bind(&answer);
7710 if (operand_info.IsSmi()) {
7711 answer.set_type_info(TypeInfo::Smi());
7712 } else if (operand_info.IsInteger32()) {
7713 answer.set_type_info(TypeInfo::Integer32());
7714 } else {
7715 answer.set_type_info(TypeInfo::Number());
7716 }
7717 frame_->Push(&answer);
7718 break;
7719 }
7720 default:
7721 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00007722 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007723 }
7724 }
7725}
7726
7727
7728// The value in dst was optimistically incremented or decremented. The
7729// result overflowed or was not smi tagged. Undo the operation, call
7730// into the runtime to convert the argument to a number, and call the
7731// specialized add or subtract stub. The result is left in dst.
7732class DeferredPrefixCountOperation: public DeferredCode {
7733 public:
Steve Block6ded16b2010-05-10 14:33:55 +01007734 DeferredPrefixCountOperation(Register dst,
7735 bool is_increment,
7736 TypeInfo input_type)
7737 : dst_(dst), is_increment_(is_increment), input_type_(input_type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007738 set_comment("[ DeferredCountOperation");
7739 }
7740
7741 virtual void Generate();
7742
7743 private:
7744 Register dst_;
7745 bool is_increment_;
Steve Block6ded16b2010-05-10 14:33:55 +01007746 TypeInfo input_type_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007747};
7748
7749
7750void DeferredPrefixCountOperation::Generate() {
7751 // Undo the optimistic smi operation.
7752 if (is_increment_) {
7753 __ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
7754 } else {
7755 __ add(Operand(dst_), Immediate(Smi::FromInt(1)));
7756 }
Steve Block6ded16b2010-05-10 14:33:55 +01007757 Register left;
7758 if (input_type_.IsNumber()) {
7759 left = dst_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007760 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01007761 __ push(dst_);
7762 __ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
7763 left = eax;
Steve Blocka7e24c12009-10-30 11:49:00 +00007764 }
Steve Block6ded16b2010-05-10 14:33:55 +01007765
7766 GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
7767 NO_OVERWRITE,
7768 NO_GENERIC_BINARY_FLAGS,
7769 TypeInfo::Number());
7770 stub.GenerateCall(masm_, left, Smi::FromInt(1));
7771
Steve Blocka7e24c12009-10-30 11:49:00 +00007772 if (!dst_.is(eax)) __ mov(dst_, eax);
7773}
7774
7775
7776// The value in dst was optimistically incremented or decremented. The
7777// result overflowed or was not smi tagged. Undo the operation and call
7778// into the runtime to convert the argument to a number. Update the
7779// original value in old. Call the specialized add or subtract stub.
7780// The result is left in dst.
7781class DeferredPostfixCountOperation: public DeferredCode {
7782 public:
Steve Block6ded16b2010-05-10 14:33:55 +01007783 DeferredPostfixCountOperation(Register dst,
7784 Register old,
7785 bool is_increment,
7786 TypeInfo input_type)
7787 : dst_(dst),
7788 old_(old),
7789 is_increment_(is_increment),
7790 input_type_(input_type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007791 set_comment("[ DeferredCountOperation");
7792 }
7793
7794 virtual void Generate();
7795
7796 private:
7797 Register dst_;
7798 Register old_;
7799 bool is_increment_;
Steve Block6ded16b2010-05-10 14:33:55 +01007800 TypeInfo input_type_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007801};
7802
7803
7804void DeferredPostfixCountOperation::Generate() {
7805 // Undo the optimistic smi operation.
7806 if (is_increment_) {
7807 __ sub(Operand(dst_), Immediate(Smi::FromInt(1)));
7808 } else {
7809 __ add(Operand(dst_), Immediate(Smi::FromInt(1)));
7810 }
Steve Block6ded16b2010-05-10 14:33:55 +01007811 Register left;
7812 if (input_type_.IsNumber()) {
7813 __ push(dst_); // Save the input to use as the old value.
7814 left = dst_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007815 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01007816 __ push(dst_);
7817 __ InvokeBuiltin(Builtins::TO_NUMBER, CALL_FUNCTION);
7818 __ push(eax); // Save the result of ToNumber to use as the old value.
7819 left = eax;
Steve Blocka7e24c12009-10-30 11:49:00 +00007820 }
Steve Block6ded16b2010-05-10 14:33:55 +01007821
7822 GenericBinaryOpStub stub(is_increment_ ? Token::ADD : Token::SUB,
7823 NO_OVERWRITE,
7824 NO_GENERIC_BINARY_FLAGS,
7825 TypeInfo::Number());
7826 stub.GenerateCall(masm_, left, Smi::FromInt(1));
7827
Steve Blocka7e24c12009-10-30 11:49:00 +00007828 if (!dst_.is(eax)) __ mov(dst_, eax);
7829 __ pop(old_);
7830}
7831
7832
7833void CodeGenerator::VisitCountOperation(CountOperation* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01007834 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00007835 Comment cmnt(masm_, "[ CountOperation");
7836
7837 bool is_postfix = node->is_postfix();
7838 bool is_increment = node->op() == Token::INC;
7839
7840 Variable* var = node->expression()->AsVariableProxy()->AsVariable();
7841 bool is_const = (var != NULL && var->mode() == Variable::CONST);
7842
7843 // Postfix operations need a stack slot under the reference to hold
7844 // the old value while the new value is being stored. This is so that
7845 // in the case that storing the new value requires a call, the old
7846 // value will be in the frame to be spilled.
7847 if (is_postfix) frame_->Push(Smi::FromInt(0));
7848
Leon Clarked91b9f72010-01-27 17:25:45 +00007849 // A constant reference is not saved to, so a constant reference is not a
7850 // compound assignment reference.
7851 { Reference target(this, node->expression(), !is_const);
Steve Blocka7e24c12009-10-30 11:49:00 +00007852 if (target.is_illegal()) {
7853 // Spoof the virtual frame to have the expected height (one higher
7854 // than on entry).
7855 if (!is_postfix) frame_->Push(Smi::FromInt(0));
7856 return;
7857 }
Steve Blockd0582a62009-12-15 09:54:21 +00007858 target.TakeValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00007859
7860 Result new_value = frame_->Pop();
7861 new_value.ToRegister();
7862
7863 Result old_value; // Only allocated in the postfix case.
7864 if (is_postfix) {
7865 // Allocate a temporary to preserve the old value.
7866 old_value = allocator_->Allocate();
7867 ASSERT(old_value.is_valid());
7868 __ mov(old_value.reg(), new_value.reg());
Steve Block6ded16b2010-05-10 14:33:55 +01007869
7870 // The return value for postfix operations is ToNumber(input).
7871 // Keep more precise type info if the input is some kind of
7872 // number already. If the input is not a number we have to wait
7873 // for the deferred code to convert it.
7874 if (new_value.type_info().IsNumber()) {
7875 old_value.set_type_info(new_value.type_info());
7876 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007877 }
Steve Block6ded16b2010-05-10 14:33:55 +01007878
Steve Blocka7e24c12009-10-30 11:49:00 +00007879 // Ensure the new value is writable.
7880 frame_->Spill(new_value.reg());
7881
Steve Block6ded16b2010-05-10 14:33:55 +01007882 Result tmp;
7883 if (new_value.is_smi()) {
7884 if (FLAG_debug_code) __ AbortIfNotSmi(new_value.reg());
Steve Blocka7e24c12009-10-30 11:49:00 +00007885 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01007886 // We don't know statically if the input is a smi.
7887 // In order to combine the overflow and the smi tag check, we need
7888 // to be able to allocate a byte register. We attempt to do so
7889 // without spilling. If we fail, we will generate separate overflow
7890 // and smi tag checks.
7891 // We allocate and clear a temporary byte register before performing
7892 // the count operation since clearing the register using xor will clear
7893 // the overflow flag.
7894 tmp = allocator_->AllocateByteRegisterWithoutSpilling();
7895 if (tmp.is_valid()) {
7896 __ Set(tmp.reg(), Immediate(0));
7897 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007898 }
7899
7900 if (is_increment) {
7901 __ add(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
7902 } else {
7903 __ sub(Operand(new_value.reg()), Immediate(Smi::FromInt(1)));
7904 }
7905
Steve Block6ded16b2010-05-10 14:33:55 +01007906 DeferredCode* deferred = NULL;
7907 if (is_postfix) {
7908 deferred = new DeferredPostfixCountOperation(new_value.reg(),
7909 old_value.reg(),
7910 is_increment,
7911 new_value.type_info());
7912 } else {
7913 deferred = new DeferredPrefixCountOperation(new_value.reg(),
7914 is_increment,
7915 new_value.type_info());
7916 }
7917
7918 if (new_value.is_smi()) {
7919 // In case we have a smi as input just check for overflow.
7920 deferred->Branch(overflow);
7921 } else {
7922 // If the count operation didn't overflow and the result is a valid
7923 // smi, we're done. Otherwise, we jump to the deferred slow-case
7924 // code.
Steve Blocka7e24c12009-10-30 11:49:00 +00007925 // We combine the overflow and the smi tag check if we could
7926 // successfully allocate a temporary byte register.
Steve Block6ded16b2010-05-10 14:33:55 +01007927 if (tmp.is_valid()) {
7928 __ setcc(overflow, tmp.reg());
7929 __ or_(Operand(tmp.reg()), new_value.reg());
7930 __ test(tmp.reg(), Immediate(kSmiTagMask));
7931 tmp.Unuse();
7932 deferred->Branch(not_zero);
7933 } else {
7934 // Otherwise we test separately for overflow and smi tag.
7935 deferred->Branch(overflow);
7936 __ test(new_value.reg(), Immediate(kSmiTagMask));
7937 deferred->Branch(not_zero);
7938 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007939 }
7940 deferred->BindExit();
7941
Steve Block6ded16b2010-05-10 14:33:55 +01007942 // Postfix count operations return their input converted to
7943 // number. The case when the input is already a number is covered
7944 // above in the allocation code for old_value.
7945 if (is_postfix && !new_value.type_info().IsNumber()) {
7946 old_value.set_type_info(TypeInfo::Number());
7947 }
7948
7949 // The result of ++ or -- is an Integer32 if the
7950 // input is a smi. Otherwise it is a number.
7951 if (new_value.is_smi()) {
7952 new_value.set_type_info(TypeInfo::Integer32());
7953 } else {
7954 new_value.set_type_info(TypeInfo::Number());
7955 }
7956
Steve Blocka7e24c12009-10-30 11:49:00 +00007957 // Postfix: store the old value in the allocated slot under the
7958 // reference.
7959 if (is_postfix) frame_->SetElementAt(target.size(), &old_value);
7960
7961 frame_->Push(&new_value);
7962 // Non-constant: update the reference.
7963 if (!is_const) target.SetValue(NOT_CONST_INIT);
7964 }
7965
7966 // Postfix: drop the new value and use the old.
7967 if (is_postfix) frame_->Drop();
7968}
7969
7970
Steve Block6ded16b2010-05-10 14:33:55 +01007971void CodeGenerator::Int32BinaryOperation(BinaryOperation* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007972 Token::Value op = node->op();
Steve Block6ded16b2010-05-10 14:33:55 +01007973 Comment cmnt(masm_, "[ Int32BinaryOperation");
7974 ASSERT(in_safe_int32_mode());
7975 ASSERT(safe_int32_mode_enabled());
7976 ASSERT(FLAG_safe_int32_compiler);
Steve Blocka7e24c12009-10-30 11:49:00 +00007977
Steve Block6ded16b2010-05-10 14:33:55 +01007978 if (op == Token::COMMA) {
7979 // Discard left value.
7980 frame_->Nip(1);
7981 return;
7982 }
7983
7984 Result right = frame_->Pop();
7985 Result left = frame_->Pop();
7986
7987 ASSERT(right.is_untagged_int32());
7988 ASSERT(left.is_untagged_int32());
7989 // Registers containing an int32 value are not multiply used.
7990 ASSERT(!left.is_register() || !frame_->is_used(left.reg()));
7991 ASSERT(!right.is_register() || !frame_->is_used(right.reg()));
7992
7993 switch (op) {
7994 case Token::COMMA:
7995 case Token::OR:
7996 case Token::AND:
7997 UNREACHABLE();
7998 break;
7999 case Token::BIT_OR:
8000 case Token::BIT_XOR:
8001 case Token::BIT_AND:
8002 if (left.is_constant() || right.is_constant()) {
8003 int32_t value; // Put constant in value, non-constant in left.
8004 // Constants are known to be int32 values, from static analysis,
8005 // or else will be converted to int32 by implicit ECMA [[ToInt32]].
8006 if (left.is_constant()) {
8007 ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
8008 value = NumberToInt32(*left.handle());
8009 left = right;
8010 } else {
8011 ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
8012 value = NumberToInt32(*right.handle());
8013 }
8014
8015 left.ToRegister();
8016 if (op == Token::BIT_OR) {
8017 __ or_(Operand(left.reg()), Immediate(value));
8018 } else if (op == Token::BIT_XOR) {
8019 __ xor_(Operand(left.reg()), Immediate(value));
8020 } else {
8021 ASSERT(op == Token::BIT_AND);
8022 __ and_(Operand(left.reg()), Immediate(value));
8023 }
8024 } else {
8025 ASSERT(left.is_register());
8026 ASSERT(right.is_register());
8027 if (op == Token::BIT_OR) {
8028 __ or_(left.reg(), Operand(right.reg()));
8029 } else if (op == Token::BIT_XOR) {
8030 __ xor_(left.reg(), Operand(right.reg()));
8031 } else {
8032 ASSERT(op == Token::BIT_AND);
8033 __ and_(left.reg(), Operand(right.reg()));
8034 }
8035 }
8036 frame_->Push(&left);
8037 right.Unuse();
8038 break;
8039 case Token::SAR:
8040 case Token::SHL:
8041 case Token::SHR: {
8042 bool test_shr_overflow = false;
8043 left.ToRegister();
8044 if (right.is_constant()) {
8045 ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
8046 int shift_amount = NumberToInt32(*right.handle()) & 0x1F;
8047 if (op == Token::SAR) {
8048 __ sar(left.reg(), shift_amount);
8049 } else if (op == Token::SHL) {
8050 __ shl(left.reg(), shift_amount);
8051 } else {
8052 ASSERT(op == Token::SHR);
8053 __ shr(left.reg(), shift_amount);
8054 if (shift_amount == 0) test_shr_overflow = true;
8055 }
8056 } else {
8057 // Move right to ecx
8058 if (left.is_register() && left.reg().is(ecx)) {
8059 right.ToRegister();
8060 __ xchg(left.reg(), right.reg());
8061 left = right; // Left is unused here, copy of right unused by Push.
8062 } else {
8063 right.ToRegister(ecx);
8064 left.ToRegister();
8065 }
8066 if (op == Token::SAR) {
8067 __ sar_cl(left.reg());
8068 } else if (op == Token::SHL) {
8069 __ shl_cl(left.reg());
8070 } else {
8071 ASSERT(op == Token::SHR);
8072 __ shr_cl(left.reg());
8073 test_shr_overflow = true;
8074 }
8075 }
8076 {
8077 Register left_reg = left.reg();
8078 frame_->Push(&left);
8079 right.Unuse();
8080 if (test_shr_overflow && !node->to_int32()) {
8081 // Uint32 results with top bit set are not Int32 values.
8082 // If they will be forced to Int32, skip the test.
8083 // Test is needed because shr with shift amount 0 does not set flags.
8084 __ test(left_reg, Operand(left_reg));
8085 unsafe_bailout_->Branch(sign);
8086 }
8087 }
8088 break;
8089 }
8090 case Token::ADD:
8091 case Token::SUB:
8092 case Token::MUL:
8093 if ((left.is_constant() && op != Token::SUB) || right.is_constant()) {
8094 int32_t value; // Put constant in value, non-constant in left.
8095 if (right.is_constant()) {
8096 ASSERT(right.handle()->IsSmi() || right.handle()->IsHeapNumber());
8097 value = NumberToInt32(*right.handle());
8098 } else {
8099 ASSERT(left.handle()->IsSmi() || left.handle()->IsHeapNumber());
8100 value = NumberToInt32(*left.handle());
8101 left = right;
8102 }
8103
8104 left.ToRegister();
8105 if (op == Token::ADD) {
8106 __ add(Operand(left.reg()), Immediate(value));
8107 } else if (op == Token::SUB) {
8108 __ sub(Operand(left.reg()), Immediate(value));
8109 } else {
8110 ASSERT(op == Token::MUL);
8111 __ imul(left.reg(), left.reg(), value);
8112 }
8113 } else {
8114 left.ToRegister();
8115 ASSERT(left.is_register());
8116 ASSERT(right.is_register());
8117 if (op == Token::ADD) {
8118 __ add(left.reg(), Operand(right.reg()));
8119 } else if (op == Token::SUB) {
8120 __ sub(left.reg(), Operand(right.reg()));
8121 } else {
8122 ASSERT(op == Token::MUL);
8123 // We have statically verified that a negative zero can be ignored.
8124 __ imul(left.reg(), Operand(right.reg()));
8125 }
8126 }
8127 right.Unuse();
8128 frame_->Push(&left);
8129 if (!node->to_int32()) {
8130 // If ToInt32 is called on the result of ADD, SUB, or MUL, we don't
8131 // care about overflows.
8132 unsafe_bailout_->Branch(overflow);
8133 }
8134 break;
8135 case Token::DIV:
8136 case Token::MOD: {
8137 if (right.is_register() && (right.reg().is(eax) || right.reg().is(edx))) {
8138 if (left.is_register() && left.reg().is(edi)) {
8139 right.ToRegister(ebx);
8140 } else {
8141 right.ToRegister(edi);
8142 }
8143 }
8144 left.ToRegister(eax);
8145 Result edx_reg = allocator_->Allocate(edx);
8146 right.ToRegister();
8147 // The results are unused here because BreakTarget::Branch cannot handle
8148 // live results.
8149 Register right_reg = right.reg();
8150 left.Unuse();
8151 right.Unuse();
8152 edx_reg.Unuse();
8153 __ cmp(right_reg, 0);
8154 // Ensure divisor is positive: no chance of non-int32 or -0 result.
8155 unsafe_bailout_->Branch(less_equal);
8156 __ cdq(); // Sign-extend eax into edx:eax
8157 __ idiv(right_reg);
8158 if (op == Token::MOD) {
8159 // Negative zero can arise as a negative divident with a zero result.
8160 if (!node->no_negative_zero()) {
8161 Label not_negative_zero;
8162 __ test(edx, Operand(edx));
8163 __ j(not_zero, &not_negative_zero);
8164 __ test(eax, Operand(eax));
8165 unsafe_bailout_->Branch(negative);
8166 __ bind(&not_negative_zero);
8167 }
8168 Result edx_result(edx, TypeInfo::Integer32());
8169 edx_result.set_untagged_int32(true);
8170 frame_->Push(&edx_result);
8171 } else {
8172 ASSERT(op == Token::DIV);
8173 __ test(edx, Operand(edx));
8174 unsafe_bailout_->Branch(not_equal);
8175 Result eax_result(eax, TypeInfo::Integer32());
8176 eax_result.set_untagged_int32(true);
8177 frame_->Push(&eax_result);
8178 }
8179 break;
8180 }
8181 default:
8182 UNREACHABLE();
8183 break;
8184 }
8185}
8186
8187
8188void CodeGenerator::GenerateLogicalBooleanOperation(BinaryOperation* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008189 // According to ECMA-262 section 11.11, page 58, the binary logical
8190 // operators must yield the result of one of the two expressions
8191 // before any ToBoolean() conversions. This means that the value
8192 // produced by a && or || operator is not necessarily a boolean.
8193
8194 // NOTE: If the left hand side produces a materialized value (not
8195 // control flow), we force the right hand side to do the same. This
8196 // is necessary because we assume that if we get control flow on the
8197 // last path out of an expression we got it on all paths.
Steve Block6ded16b2010-05-10 14:33:55 +01008198 if (node->op() == Token::AND) {
8199 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00008200 JumpTarget is_true;
8201 ControlDestination dest(&is_true, destination()->false_target(), true);
Steve Blockd0582a62009-12-15 09:54:21 +00008202 LoadCondition(node->left(), &dest, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008203
8204 if (dest.false_was_fall_through()) {
8205 // The current false target was used as the fall-through. If
8206 // there are no dangling jumps to is_true then the left
8207 // subexpression was unconditionally false. Otherwise we have
8208 // paths where we do have to evaluate the right subexpression.
8209 if (is_true.is_linked()) {
8210 // We need to compile the right subexpression. If the jump to
8211 // the current false target was a forward jump then we have a
8212 // valid frame, we have just bound the false target, and we
8213 // have to jump around the code for the right subexpression.
8214 if (has_valid_frame()) {
8215 destination()->false_target()->Unuse();
8216 destination()->false_target()->Jump();
8217 }
8218 is_true.Bind();
8219 // The left subexpression compiled to control flow, so the
8220 // right one is free to do so as well.
Steve Blockd0582a62009-12-15 09:54:21 +00008221 LoadCondition(node->right(), destination(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008222 } else {
8223 // We have actually just jumped to or bound the current false
8224 // target but the current control destination is not marked as
8225 // used.
8226 destination()->Use(false);
8227 }
8228
8229 } else if (dest.is_used()) {
8230 // The left subexpression compiled to control flow (and is_true
8231 // was just bound), so the right is free to do so as well.
Steve Blockd0582a62009-12-15 09:54:21 +00008232 LoadCondition(node->right(), destination(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008233
8234 } else {
8235 // We have a materialized value on the frame, so we exit with
8236 // one on all paths. There are possibly also jumps to is_true
8237 // from nested subexpressions.
8238 JumpTarget pop_and_continue;
8239 JumpTarget exit;
8240
8241 // Avoid popping the result if it converts to 'false' using the
8242 // standard ToBoolean() conversion as described in ECMA-262,
8243 // section 9.2, page 30.
8244 //
8245 // Duplicate the TOS value. The duplicate will be popped by
8246 // ToBoolean.
8247 frame_->Dup();
8248 ControlDestination dest(&pop_and_continue, &exit, true);
8249 ToBoolean(&dest);
8250
8251 // Pop the result of evaluating the first part.
8252 frame_->Drop();
8253
8254 // Compile right side expression.
8255 is_true.Bind();
8256 Load(node->right());
8257
8258 // Exit (always with a materialized value).
8259 exit.Bind();
8260 }
8261
Steve Block6ded16b2010-05-10 14:33:55 +01008262 } else {
8263 ASSERT(node->op() == Token::OR);
8264 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00008265 JumpTarget is_false;
8266 ControlDestination dest(destination()->true_target(), &is_false, false);
Steve Blockd0582a62009-12-15 09:54:21 +00008267 LoadCondition(node->left(), &dest, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008268
8269 if (dest.true_was_fall_through()) {
8270 // The current true target was used as the fall-through. If
8271 // there are no dangling jumps to is_false then the left
8272 // subexpression was unconditionally true. Otherwise we have
8273 // paths where we do have to evaluate the right subexpression.
8274 if (is_false.is_linked()) {
8275 // We need to compile the right subexpression. If the jump to
8276 // the current true target was a forward jump then we have a
8277 // valid frame, we have just bound the true target, and we
8278 // have to jump around the code for the right subexpression.
8279 if (has_valid_frame()) {
8280 destination()->true_target()->Unuse();
8281 destination()->true_target()->Jump();
8282 }
8283 is_false.Bind();
8284 // The left subexpression compiled to control flow, so the
8285 // right one is free to do so as well.
Steve Blockd0582a62009-12-15 09:54:21 +00008286 LoadCondition(node->right(), destination(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008287 } else {
8288 // We have just jumped to or bound the current true target but
8289 // the current control destination is not marked as used.
8290 destination()->Use(true);
8291 }
8292
8293 } else if (dest.is_used()) {
8294 // The left subexpression compiled to control flow (and is_false
8295 // was just bound), so the right is free to do so as well.
Steve Blockd0582a62009-12-15 09:54:21 +00008296 LoadCondition(node->right(), destination(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00008297
8298 } else {
8299 // We have a materialized value on the frame, so we exit with
8300 // one on all paths. There are possibly also jumps to is_false
8301 // from nested subexpressions.
8302 JumpTarget pop_and_continue;
8303 JumpTarget exit;
8304
8305 // Avoid popping the result if it converts to 'true' using the
8306 // standard ToBoolean() conversion as described in ECMA-262,
8307 // section 9.2, page 30.
8308 //
8309 // Duplicate the TOS value. The duplicate will be popped by
8310 // ToBoolean.
8311 frame_->Dup();
8312 ControlDestination dest(&exit, &pop_and_continue, false);
8313 ToBoolean(&dest);
8314
8315 // Pop the result of evaluating the first part.
8316 frame_->Drop();
8317
8318 // Compile right side expression.
8319 is_false.Bind();
8320 Load(node->right());
8321
8322 // Exit (always with a materialized value).
8323 exit.Bind();
8324 }
Steve Block6ded16b2010-05-10 14:33:55 +01008325 }
8326}
Steve Blocka7e24c12009-10-30 11:49:00 +00008327
Steve Block6ded16b2010-05-10 14:33:55 +01008328
8329void CodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
8330 Comment cmnt(masm_, "[ BinaryOperation");
8331
8332 if (node->op() == Token::AND || node->op() == Token::OR) {
8333 GenerateLogicalBooleanOperation(node);
8334 } else if (in_safe_int32_mode()) {
8335 Visit(node->left());
8336 Visit(node->right());
8337 Int32BinaryOperation(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00008338 } else {
8339 // NOTE: The code below assumes that the slow cases (calls to runtime)
8340 // never return a constant/immutable object.
8341 OverwriteMode overwrite_mode = NO_OVERWRITE;
8342 if (node->left()->AsBinaryOperation() != NULL &&
8343 node->left()->AsBinaryOperation()->ResultOverwriteAllowed()) {
8344 overwrite_mode = OVERWRITE_LEFT;
8345 } else if (node->right()->AsBinaryOperation() != NULL &&
8346 node->right()->AsBinaryOperation()->ResultOverwriteAllowed()) {
8347 overwrite_mode = OVERWRITE_RIGHT;
8348 }
8349
Steve Block6ded16b2010-05-10 14:33:55 +01008350 if (node->left()->IsTrivial()) {
8351 Load(node->right());
8352 Result right = frame_->Pop();
8353 frame_->Push(node->left());
8354 frame_->Push(&right);
8355 } else {
8356 Load(node->left());
8357 Load(node->right());
8358 }
8359 GenericBinaryOperation(node, overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00008360 }
8361}
8362
8363
8364void CodeGenerator::VisitThisFunction(ThisFunction* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01008365 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00008366 frame_->PushFunction();
8367}
8368
8369
8370void CodeGenerator::VisitCompareOperation(CompareOperation* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01008371 ASSERT(!in_safe_int32_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +00008372 Comment cmnt(masm_, "[ CompareOperation");
8373
Leon Clarkee46be812010-01-19 14:06:41 +00008374 bool left_already_loaded = false;
8375
Steve Blocka7e24c12009-10-30 11:49:00 +00008376 // Get the expressions from the node.
8377 Expression* left = node->left();
8378 Expression* right = node->right();
8379 Token::Value op = node->op();
8380 // To make typeof testing for natives implemented in JavaScript really
8381 // efficient, we generate special code for expressions of the form:
8382 // 'typeof <expression> == <string>'.
8383 UnaryOperation* operation = left->AsUnaryOperation();
8384 if ((op == Token::EQ || op == Token::EQ_STRICT) &&
8385 (operation != NULL && operation->op() == Token::TYPEOF) &&
8386 (right->AsLiteral() != NULL &&
8387 right->AsLiteral()->handle()->IsString())) {
8388 Handle<String> check(String::cast(*right->AsLiteral()->handle()));
8389
8390 // Load the operand and move it to a register.
8391 LoadTypeofExpression(operation->expression());
8392 Result answer = frame_->Pop();
8393 answer.ToRegister();
8394
8395 if (check->Equals(Heap::number_symbol())) {
8396 __ test(answer.reg(), Immediate(kSmiTagMask));
8397 destination()->true_target()->Branch(zero);
8398 frame_->Spill(answer.reg());
8399 __ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
8400 __ cmp(answer.reg(), Factory::heap_number_map());
8401 answer.Unuse();
8402 destination()->Split(equal);
8403
8404 } else if (check->Equals(Heap::string_symbol())) {
8405 __ test(answer.reg(), Immediate(kSmiTagMask));
8406 destination()->false_target()->Branch(zero);
8407
8408 // It can be an undetectable string object.
8409 Result temp = allocator()->Allocate();
8410 ASSERT(temp.is_valid());
8411 __ mov(temp.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008412 __ test_b(FieldOperand(temp.reg(), Map::kBitFieldOffset),
8413 1 << Map::kIsUndetectable);
Steve Blocka7e24c12009-10-30 11:49:00 +00008414 destination()->false_target()->Branch(not_zero);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008415 __ CmpInstanceType(temp.reg(), FIRST_NONSTRING_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00008416 temp.Unuse();
8417 answer.Unuse();
Andrei Popescu402d9372010-02-26 13:31:12 +00008418 destination()->Split(below);
Steve Blocka7e24c12009-10-30 11:49:00 +00008419
8420 } else if (check->Equals(Heap::boolean_symbol())) {
8421 __ cmp(answer.reg(), Factory::true_value());
8422 destination()->true_target()->Branch(equal);
8423 __ cmp(answer.reg(), Factory::false_value());
8424 answer.Unuse();
8425 destination()->Split(equal);
8426
8427 } else if (check->Equals(Heap::undefined_symbol())) {
8428 __ cmp(answer.reg(), Factory::undefined_value());
8429 destination()->true_target()->Branch(equal);
8430
8431 __ test(answer.reg(), Immediate(kSmiTagMask));
8432 destination()->false_target()->Branch(zero);
8433
8434 // It can be an undetectable object.
8435 frame_->Spill(answer.reg());
8436 __ mov(answer.reg(), FieldOperand(answer.reg(), HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008437 __ test_b(FieldOperand(answer.reg(), Map::kBitFieldOffset),
8438 1 << Map::kIsUndetectable);
Steve Blocka7e24c12009-10-30 11:49:00 +00008439 answer.Unuse();
8440 destination()->Split(not_zero);
8441
8442 } else if (check->Equals(Heap::function_symbol())) {
8443 __ test(answer.reg(), Immediate(kSmiTagMask));
8444 destination()->false_target()->Branch(zero);
8445 frame_->Spill(answer.reg());
8446 __ CmpObjectType(answer.reg(), JS_FUNCTION_TYPE, answer.reg());
Steve Blockd0582a62009-12-15 09:54:21 +00008447 destination()->true_target()->Branch(equal);
8448 // Regular expressions are callable so typeof == 'function'.
8449 __ CmpInstanceType(answer.reg(), JS_REGEXP_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00008450 answer.Unuse();
8451 destination()->Split(equal);
Steve Blocka7e24c12009-10-30 11:49:00 +00008452 } else if (check->Equals(Heap::object_symbol())) {
8453 __ test(answer.reg(), Immediate(kSmiTagMask));
8454 destination()->false_target()->Branch(zero);
8455 __ cmp(answer.reg(), Factory::null_value());
8456 destination()->true_target()->Branch(equal);
8457
Steve Blocka7e24c12009-10-30 11:49:00 +00008458 Result map = allocator()->Allocate();
8459 ASSERT(map.is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00008460 // Regular expressions are typeof == 'function', not 'object'.
8461 __ CmpObjectType(answer.reg(), JS_REGEXP_TYPE, map.reg());
8462 destination()->false_target()->Branch(equal);
8463
8464 // It can be an undetectable object.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008465 __ test_b(FieldOperand(map.reg(), Map::kBitFieldOffset),
8466 1 << Map::kIsUndetectable);
Steve Blocka7e24c12009-10-30 11:49:00 +00008467 destination()->false_target()->Branch(not_zero);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008468 // Do a range test for JSObject type. We can't use
8469 // MacroAssembler::IsInstanceJSObjectType, because we are using a
8470 // ControlDestination, so we copy its implementation here.
Steve Blocka7e24c12009-10-30 11:49:00 +00008471 __ movzx_b(map.reg(), FieldOperand(map.reg(), Map::kInstanceTypeOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008472 __ sub(Operand(map.reg()), Immediate(FIRST_JS_OBJECT_TYPE));
8473 __ cmp(map.reg(), LAST_JS_OBJECT_TYPE - FIRST_JS_OBJECT_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00008474 answer.Unuse();
8475 map.Unuse();
Leon Clarkef7060e22010-06-03 12:02:55 +01008476 destination()->Split(below_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +00008477 } else {
8478 // Uncommon case: typeof testing against a string literal that is
8479 // never returned from the typeof operator.
8480 answer.Unuse();
8481 destination()->Goto(false);
8482 }
8483 return;
Leon Clarkee46be812010-01-19 14:06:41 +00008484 } else if (op == Token::LT &&
8485 right->AsLiteral() != NULL &&
8486 right->AsLiteral()->handle()->IsHeapNumber()) {
8487 Handle<HeapNumber> check(HeapNumber::cast(*right->AsLiteral()->handle()));
8488 if (check->value() == 2147483648.0) { // 0x80000000.
8489 Load(left);
8490 left_already_loaded = true;
8491 Result lhs = frame_->Pop();
8492 lhs.ToRegister();
8493 __ test(lhs.reg(), Immediate(kSmiTagMask));
8494 destination()->true_target()->Branch(zero); // All Smis are less.
8495 Result scratch = allocator()->Allocate();
8496 ASSERT(scratch.is_valid());
8497 __ mov(scratch.reg(), FieldOperand(lhs.reg(), HeapObject::kMapOffset));
8498 __ cmp(scratch.reg(), Factory::heap_number_map());
8499 JumpTarget not_a_number;
8500 not_a_number.Branch(not_equal, &lhs);
8501 __ mov(scratch.reg(),
8502 FieldOperand(lhs.reg(), HeapNumber::kExponentOffset));
8503 __ cmp(Operand(scratch.reg()), Immediate(0xfff00000));
8504 not_a_number.Branch(above_equal, &lhs); // It's a negative NaN or -Inf.
8505 const uint32_t borderline_exponent =
8506 (HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
8507 __ cmp(Operand(scratch.reg()), Immediate(borderline_exponent));
8508 scratch.Unuse();
8509 lhs.Unuse();
8510 destination()->true_target()->Branch(less);
8511 destination()->false_target()->Jump();
8512
8513 not_a_number.Bind(&lhs);
8514 frame_->Push(&lhs);
8515 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008516 }
8517
8518 Condition cc = no_condition;
8519 bool strict = false;
8520 switch (op) {
8521 case Token::EQ_STRICT:
8522 strict = true;
8523 // Fall through
8524 case Token::EQ:
8525 cc = equal;
8526 break;
8527 case Token::LT:
8528 cc = less;
8529 break;
8530 case Token::GT:
8531 cc = greater;
8532 break;
8533 case Token::LTE:
8534 cc = less_equal;
8535 break;
8536 case Token::GTE:
8537 cc = greater_equal;
8538 break;
8539 case Token::IN: {
Leon Clarkee46be812010-01-19 14:06:41 +00008540 if (!left_already_loaded) Load(left);
Steve Blocka7e24c12009-10-30 11:49:00 +00008541 Load(right);
8542 Result answer = frame_->InvokeBuiltin(Builtins::IN, CALL_FUNCTION, 2);
8543 frame_->Push(&answer); // push the result
8544 return;
8545 }
8546 case Token::INSTANCEOF: {
Leon Clarkee46be812010-01-19 14:06:41 +00008547 if (!left_already_loaded) Load(left);
Steve Blocka7e24c12009-10-30 11:49:00 +00008548 Load(right);
8549 InstanceofStub stub;
8550 Result answer = frame_->CallStub(&stub, 2);
8551 answer.ToRegister();
8552 __ test(answer.reg(), Operand(answer.reg()));
8553 answer.Unuse();
8554 destination()->Split(zero);
8555 return;
8556 }
8557 default:
8558 UNREACHABLE();
8559 }
Steve Block6ded16b2010-05-10 14:33:55 +01008560
8561 if (left->IsTrivial()) {
8562 if (!left_already_loaded) {
8563 Load(right);
8564 Result right_result = frame_->Pop();
8565 frame_->Push(left);
8566 frame_->Push(&right_result);
8567 } else {
8568 Load(right);
8569 }
8570 } else {
8571 if (!left_already_loaded) Load(left);
8572 Load(right);
8573 }
Leon Clarkee46be812010-01-19 14:06:41 +00008574 Comparison(node, cc, strict, destination());
Steve Blocka7e24c12009-10-30 11:49:00 +00008575}
8576
8577
8578#ifdef DEBUG
8579bool CodeGenerator::HasValidEntryRegisters() {
8580 return (allocator()->count(eax) == (frame()->is_used(eax) ? 1 : 0))
8581 && (allocator()->count(ebx) == (frame()->is_used(ebx) ? 1 : 0))
8582 && (allocator()->count(ecx) == (frame()->is_used(ecx) ? 1 : 0))
8583 && (allocator()->count(edx) == (frame()->is_used(edx) ? 1 : 0))
8584 && (allocator()->count(edi) == (frame()->is_used(edi) ? 1 : 0));
8585}
8586#endif
8587
8588
8589// Emit a LoadIC call to get the value from receiver and leave it in
Andrei Popescu402d9372010-02-26 13:31:12 +00008590// dst.
Steve Blocka7e24c12009-10-30 11:49:00 +00008591class DeferredReferenceGetNamedValue: public DeferredCode {
8592 public:
8593 DeferredReferenceGetNamedValue(Register dst,
8594 Register receiver,
8595 Handle<String> name)
8596 : dst_(dst), receiver_(receiver), name_(name) {
8597 set_comment("[ DeferredReferenceGetNamedValue");
8598 }
8599
8600 virtual void Generate();
8601
8602 Label* patch_site() { return &patch_site_; }
8603
8604 private:
8605 Label patch_site_;
8606 Register dst_;
8607 Register receiver_;
8608 Handle<String> name_;
8609};
8610
8611
8612void DeferredReferenceGetNamedValue::Generate() {
Andrei Popescu402d9372010-02-26 13:31:12 +00008613 if (!receiver_.is(eax)) {
8614 __ mov(eax, receiver_);
8615 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008616 __ Set(ecx, Immediate(name_));
8617 Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
8618 __ call(ic, RelocInfo::CODE_TARGET);
8619 // The call must be followed by a test eax instruction to indicate
8620 // that the inobject property case was inlined.
8621 //
8622 // Store the delta to the map check instruction here in the test
8623 // instruction. Use masm_-> instead of the __ macro since the
8624 // latter can't return a value.
8625 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
8626 // Here we use masm_-> instead of the __ macro because this is the
8627 // instruction that gets patched and coverage code gets in the way.
8628 masm_->test(eax, Immediate(-delta_to_patch_site));
8629 __ IncrementCounter(&Counters::named_load_inline_miss, 1);
8630
8631 if (!dst_.is(eax)) __ mov(dst_, eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00008632}
8633
8634
8635class DeferredReferenceGetKeyedValue: public DeferredCode {
8636 public:
8637 explicit DeferredReferenceGetKeyedValue(Register dst,
8638 Register receiver,
Andrei Popescu402d9372010-02-26 13:31:12 +00008639 Register key)
8640 : dst_(dst), receiver_(receiver), key_(key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008641 set_comment("[ DeferredReferenceGetKeyedValue");
8642 }
8643
8644 virtual void Generate();
8645
8646 Label* patch_site() { return &patch_site_; }
8647
8648 private:
8649 Label patch_site_;
8650 Register dst_;
8651 Register receiver_;
8652 Register key_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008653};
8654
8655
8656void DeferredReferenceGetKeyedValue::Generate() {
Andrei Popescu402d9372010-02-26 13:31:12 +00008657 if (!receiver_.is(eax)) {
8658 // Register eax is available for key.
8659 if (!key_.is(eax)) {
8660 __ mov(eax, key_);
8661 }
8662 if (!receiver_.is(edx)) {
8663 __ mov(edx, receiver_);
8664 }
8665 } else if (!key_.is(edx)) {
8666 // Register edx is available for receiver.
8667 if (!receiver_.is(edx)) {
8668 __ mov(edx, receiver_);
8669 }
8670 if (!key_.is(eax)) {
8671 __ mov(eax, key_);
8672 }
8673 } else {
8674 __ xchg(edx, eax);
8675 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008676 // Calculate the delta from the IC call instruction to the map check
8677 // cmp instruction in the inlined version. This delta is stored in
8678 // a test(eax, delta) instruction after the call so that we can find
8679 // it in the IC initialization code and patch the cmp instruction.
8680 // This means that we cannot allow test instructions after calls to
8681 // KeyedLoadIC stubs in other places.
8682 Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize));
Andrei Popescu402d9372010-02-26 13:31:12 +00008683 __ call(ic, RelocInfo::CODE_TARGET);
Steve Blocka7e24c12009-10-30 11:49:00 +00008684 // The delta from the start of the map-compare instruction to the
8685 // test instruction. We use masm_-> directly here instead of the __
8686 // macro because the macro sometimes uses macro expansion to turn
8687 // into something that can't return a value. This is encountered
8688 // when doing generated code coverage tests.
8689 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
8690 // Here we use masm_-> instead of the __ macro because this is the
8691 // instruction that gets patched and coverage code gets in the way.
8692 masm_->test(eax, Immediate(-delta_to_patch_site));
8693 __ IncrementCounter(&Counters::keyed_load_inline_miss, 1);
8694
8695 if (!dst_.is(eax)) __ mov(dst_, eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00008696}
8697
8698
8699class DeferredReferenceSetKeyedValue: public DeferredCode {
8700 public:
8701 DeferredReferenceSetKeyedValue(Register value,
8702 Register key,
Steve Block6ded16b2010-05-10 14:33:55 +01008703 Register receiver,
8704 Register scratch)
8705 : value_(value),
8706 key_(key),
8707 receiver_(receiver),
8708 scratch_(scratch) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008709 set_comment("[ DeferredReferenceSetKeyedValue");
8710 }
8711
8712 virtual void Generate();
8713
8714 Label* patch_site() { return &patch_site_; }
8715
8716 private:
8717 Register value_;
8718 Register key_;
8719 Register receiver_;
Steve Block6ded16b2010-05-10 14:33:55 +01008720 Register scratch_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008721 Label patch_site_;
8722};
8723
8724
8725void DeferredReferenceSetKeyedValue::Generate() {
8726 __ IncrementCounter(&Counters::keyed_store_inline_miss, 1);
Steve Block6ded16b2010-05-10 14:33:55 +01008727 // Move value_ to eax, key_ to ecx, and receiver_ to edx.
8728 Register old_value = value_;
8729
8730 // First, move value to eax.
8731 if (!value_.is(eax)) {
8732 if (key_.is(eax)) {
8733 // Move key_ out of eax, preferably to ecx.
8734 if (!value_.is(ecx) && !receiver_.is(ecx)) {
8735 __ mov(ecx, key_);
8736 key_ = ecx;
8737 } else {
8738 __ mov(scratch_, key_);
8739 key_ = scratch_;
8740 }
8741 }
8742 if (receiver_.is(eax)) {
8743 // Move receiver_ out of eax, preferably to edx.
8744 if (!value_.is(edx) && !key_.is(edx)) {
8745 __ mov(edx, receiver_);
8746 receiver_ = edx;
8747 } else {
8748 // Both moves to scratch are from eax, also, no valid path hits both.
8749 __ mov(scratch_, receiver_);
8750 receiver_ = scratch_;
8751 }
8752 }
8753 __ mov(eax, value_);
8754 value_ = eax;
8755 }
8756
8757 // Now value_ is in eax. Move the other two to the right positions.
8758 // We do not update the variables key_ and receiver_ to ecx and edx.
8759 if (key_.is(ecx)) {
8760 if (!receiver_.is(edx)) {
8761 __ mov(edx, receiver_);
8762 }
8763 } else if (key_.is(edx)) {
8764 if (receiver_.is(ecx)) {
8765 __ xchg(edx, ecx);
8766 } else {
8767 __ mov(ecx, key_);
8768 if (!receiver_.is(edx)) {
8769 __ mov(edx, receiver_);
8770 }
8771 }
8772 } else { // Key is not in edx or ecx.
8773 if (!receiver_.is(edx)) {
8774 __ mov(edx, receiver_);
8775 }
8776 __ mov(ecx, key_);
8777 }
8778
Steve Blocka7e24c12009-10-30 11:49:00 +00008779 // Call the IC stub.
8780 Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Initialize));
8781 __ call(ic, RelocInfo::CODE_TARGET);
8782 // The delta from the start of the map-compare instruction to the
8783 // test instruction. We use masm_-> directly here instead of the
8784 // __ macro because the macro sometimes uses macro expansion to turn
8785 // into something that can't return a value. This is encountered
8786 // when doing generated code coverage tests.
8787 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(patch_site());
8788 // Here we use masm_-> instead of the __ macro because this is the
8789 // instruction that gets patched and coverage code gets in the way.
8790 masm_->test(eax, Immediate(-delta_to_patch_site));
Steve Block6ded16b2010-05-10 14:33:55 +01008791 // Restore value (returned from store IC) register.
8792 if (!old_value.is(eax)) __ mov(old_value, eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00008793}
8794
8795
Andrei Popescu402d9372010-02-26 13:31:12 +00008796Result CodeGenerator::EmitNamedLoad(Handle<String> name, bool is_contextual) {
8797#ifdef DEBUG
8798 int original_height = frame()->height();
8799#endif
8800 Result result;
8801 // Do not inline the inobject property case for loads from the global
8802 // object. Also do not inline for unoptimized code. This saves time in
8803 // the code generator. Unoptimized code is toplevel code or code that is
8804 // not in a loop.
8805 if (is_contextual || scope()->is_global_scope() || loop_nesting() == 0) {
8806 Comment cmnt(masm(), "[ Load from named Property");
8807 frame()->Push(name);
8808
8809 RelocInfo::Mode mode = is_contextual
8810 ? RelocInfo::CODE_TARGET_CONTEXT
8811 : RelocInfo::CODE_TARGET;
8812 result = frame()->CallLoadIC(mode);
8813 // A test eax instruction following the call signals that the inobject
8814 // property case was inlined. Ensure that there is not a test eax
8815 // instruction here.
8816 __ nop();
8817 } else {
8818 // Inline the inobject property case.
8819 Comment cmnt(masm(), "[ Inlined named property load");
8820 Result receiver = frame()->Pop();
8821 receiver.ToRegister();
8822
8823 result = allocator()->Allocate();
8824 ASSERT(result.is_valid());
8825 DeferredReferenceGetNamedValue* deferred =
8826 new DeferredReferenceGetNamedValue(result.reg(), receiver.reg(), name);
8827
8828 // Check that the receiver is a heap object.
8829 __ test(receiver.reg(), Immediate(kSmiTagMask));
8830 deferred->Branch(zero);
8831
8832 __ bind(deferred->patch_site());
8833 // This is the map check instruction that will be patched (so we can't
8834 // use the double underscore macro that may insert instructions).
8835 // Initially use an invalid map to force a failure.
8836 masm()->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
8837 Immediate(Factory::null_value()));
8838 // This branch is always a forwards branch so it's always a fixed size
8839 // which allows the assert below to succeed and patching to work.
8840 deferred->Branch(not_equal);
8841
8842 // The delta from the patch label to the load offset must be statically
8843 // known.
8844 ASSERT(masm()->SizeOfCodeGeneratedSince(deferred->patch_site()) ==
8845 LoadIC::kOffsetToLoadInstruction);
8846 // The initial (invalid) offset has to be large enough to force a 32-bit
8847 // instruction encoding to allow patching with an arbitrary offset. Use
8848 // kMaxInt (minus kHeapObjectTag).
8849 int offset = kMaxInt;
8850 masm()->mov(result.reg(), FieldOperand(receiver.reg(), offset));
8851
8852 __ IncrementCounter(&Counters::named_load_inline, 1);
8853 deferred->BindExit();
8854 }
8855 ASSERT(frame()->height() == original_height - 1);
8856 return result;
8857}
8858
8859
8860Result CodeGenerator::EmitNamedStore(Handle<String> name, bool is_contextual) {
8861#ifdef DEBUG
8862 int expected_height = frame()->height() - (is_contextual ? 1 : 2);
8863#endif
8864 Result result = frame()->CallStoreIC(name, is_contextual);
8865
8866 ASSERT_EQ(expected_height, frame()->height());
8867 return result;
8868}
8869
8870
8871Result CodeGenerator::EmitKeyedLoad() {
8872#ifdef DEBUG
8873 int original_height = frame()->height();
8874#endif
8875 Result result;
8876 // Inline array load code if inside of a loop. We do not know the
8877 // receiver map yet, so we initially generate the code with a check
8878 // against an invalid map. In the inline cache code, we patch the map
8879 // check if appropriate.
Leon Clarked91b9f72010-01-27 17:25:45 +00008880 if (loop_nesting() > 0) {
8881 Comment cmnt(masm_, "[ Inlined load from keyed Property");
8882
Leon Clarked91b9f72010-01-27 17:25:45 +00008883 // Use a fresh temporary to load the elements without destroying
8884 // the receiver which is needed for the deferred slow case.
8885 Result elements = allocator()->Allocate();
8886 ASSERT(elements.is_valid());
8887
Leon Clarkef7060e22010-06-03 12:02:55 +01008888 Result key = frame_->Pop();
8889 Result receiver = frame_->Pop();
8890 key.ToRegister();
8891 receiver.ToRegister();
8892
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008893 // If key and receiver are shared registers on the frame, their values will
8894 // be automatically saved and restored when going to deferred code.
8895 // The result is in elements, which is guaranteed non-shared.
Leon Clarked91b9f72010-01-27 17:25:45 +00008896 DeferredReferenceGetKeyedValue* deferred =
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008897 new DeferredReferenceGetKeyedValue(elements.reg(),
Leon Clarked91b9f72010-01-27 17:25:45 +00008898 receiver.reg(),
Andrei Popescu402d9372010-02-26 13:31:12 +00008899 key.reg());
Leon Clarked91b9f72010-01-27 17:25:45 +00008900
Andrei Popescu402d9372010-02-26 13:31:12 +00008901 __ test(receiver.reg(), Immediate(kSmiTagMask));
8902 deferred->Branch(zero);
Leon Clarked91b9f72010-01-27 17:25:45 +00008903
Leon Clarkef7060e22010-06-03 12:02:55 +01008904 // Check that the receiver has the expected map.
Leon Clarked91b9f72010-01-27 17:25:45 +00008905 // Initially, use an invalid map. The map is patched in the IC
8906 // initialization code.
8907 __ bind(deferred->patch_site());
8908 // Use masm-> here instead of the double underscore macro since extra
8909 // coverage code can interfere with the patching.
8910 masm_->cmp(FieldOperand(receiver.reg(), HeapObject::kMapOffset),
Steve Block8defd9f2010-07-08 12:39:36 +01008911 Immediate(Factory::null_value()));
Leon Clarked91b9f72010-01-27 17:25:45 +00008912 deferred->Branch(not_equal);
8913
8914 // Check that the key is a smi.
Steve Block6ded16b2010-05-10 14:33:55 +01008915 if (!key.is_smi()) {
8916 __ test(key.reg(), Immediate(kSmiTagMask));
8917 deferred->Branch(not_zero);
8918 } else {
8919 if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
8920 }
Leon Clarked91b9f72010-01-27 17:25:45 +00008921
8922 // Get the elements array from the receiver and check that it
8923 // is not a dictionary.
8924 __ mov(elements.reg(),
8925 FieldOperand(receiver.reg(), JSObject::kElementsOffset));
Steve Block8defd9f2010-07-08 12:39:36 +01008926 if (FLAG_debug_code) {
8927 __ cmp(FieldOperand(elements.reg(), HeapObject::kMapOffset),
8928 Immediate(Factory::fixed_array_map()));
8929 __ Assert(equal, "JSObject with fast elements map has slow elements");
8930 }
Leon Clarked91b9f72010-01-27 17:25:45 +00008931
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008932 // Check that the key is within bounds.
8933 __ cmp(key.reg(),
Leon Clarked91b9f72010-01-27 17:25:45 +00008934 FieldOperand(elements.reg(), FixedArray::kLengthOffset));
8935 deferred->Branch(above_equal);
8936
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01008937 // Load and check that the result is not the hole.
8938 // Key holds a smi.
8939 ASSERT((kSmiTag == 0) && (kSmiTagSize == 1));
8940 __ mov(elements.reg(),
8941 FieldOperand(elements.reg(),
8942 key.reg(),
8943 times_2,
8944 FixedArray::kHeaderSize));
8945 result = elements;
Andrei Popescu402d9372010-02-26 13:31:12 +00008946 __ cmp(Operand(result.reg()), Immediate(Factory::the_hole_value()));
Leon Clarked91b9f72010-01-27 17:25:45 +00008947 deferred->Branch(equal);
8948 __ IncrementCounter(&Counters::keyed_load_inline, 1);
8949
8950 deferred->BindExit();
Leon Clarked91b9f72010-01-27 17:25:45 +00008951 } else {
8952 Comment cmnt(masm_, "[ Load from keyed Property");
Andrei Popescu402d9372010-02-26 13:31:12 +00008953 result = frame_->CallKeyedLoadIC(RelocInfo::CODE_TARGET);
Leon Clarked91b9f72010-01-27 17:25:45 +00008954 // Make sure that we do not have a test instruction after the
8955 // call. A test instruction after the call is used to
8956 // indicate that we have generated an inline version of the
8957 // keyed load. The explicit nop instruction is here because
8958 // the push that follows might be peep-hole optimized away.
8959 __ nop();
Leon Clarked91b9f72010-01-27 17:25:45 +00008960 }
Andrei Popescu402d9372010-02-26 13:31:12 +00008961 ASSERT(frame()->height() == original_height - 2);
8962 return result;
8963}
8964
8965
8966Result CodeGenerator::EmitKeyedStore(StaticType* key_type) {
8967#ifdef DEBUG
8968 int original_height = frame()->height();
8969#endif
8970 Result result;
8971 // Generate inlined version of the keyed store if the code is in a loop
8972 // and the key is likely to be a smi.
8973 if (loop_nesting() > 0 && key_type->IsLikelySmi()) {
8974 Comment cmnt(masm(), "[ Inlined store to keyed Property");
8975
8976 // Get the receiver, key and value into registers.
8977 result = frame()->Pop();
8978 Result key = frame()->Pop();
8979 Result receiver = frame()->Pop();
8980
8981 Result tmp = allocator_->Allocate();
8982 ASSERT(tmp.is_valid());
Steve Block6ded16b2010-05-10 14:33:55 +01008983 Result tmp2 = allocator_->Allocate();
8984 ASSERT(tmp2.is_valid());
Andrei Popescu402d9372010-02-26 13:31:12 +00008985
8986 // Determine whether the value is a constant before putting it in a
8987 // register.
8988 bool value_is_constant = result.is_constant();
8989
8990 // Make sure that value, key and receiver are in registers.
8991 result.ToRegister();
8992 key.ToRegister();
8993 receiver.ToRegister();
8994
8995 DeferredReferenceSetKeyedValue* deferred =
8996 new DeferredReferenceSetKeyedValue(result.reg(),
8997 key.reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01008998 receiver.reg(),
8999 tmp.reg());
Andrei Popescu402d9372010-02-26 13:31:12 +00009000
9001 // Check that the receiver is not a smi.
9002 __ test(receiver.reg(), Immediate(kSmiTagMask));
9003 deferred->Branch(zero);
9004
Steve Block6ded16b2010-05-10 14:33:55 +01009005 // Check that the key is a smi.
9006 if (!key.is_smi()) {
9007 __ test(key.reg(), Immediate(kSmiTagMask));
9008 deferred->Branch(not_zero);
9009 } else {
9010 if (FLAG_debug_code) __ AbortIfNotSmi(key.reg());
9011 }
9012
Andrei Popescu402d9372010-02-26 13:31:12 +00009013 // Check that the receiver is a JSArray.
Steve Block6ded16b2010-05-10 14:33:55 +01009014 __ CmpObjectType(receiver.reg(), JS_ARRAY_TYPE, tmp.reg());
Andrei Popescu402d9372010-02-26 13:31:12 +00009015 deferred->Branch(not_equal);
9016
9017 // Check that the key is within bounds. Both the key and the length of
Steve Block6ded16b2010-05-10 14:33:55 +01009018 // the JSArray are smis. Use unsigned comparison to handle negative keys.
Andrei Popescu402d9372010-02-26 13:31:12 +00009019 __ cmp(key.reg(),
9020 FieldOperand(receiver.reg(), JSArray::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01009021 deferred->Branch(above_equal);
Andrei Popescu402d9372010-02-26 13:31:12 +00009022
9023 // Get the elements array from the receiver and check that it is not a
9024 // dictionary.
9025 __ mov(tmp.reg(),
Steve Block6ded16b2010-05-10 14:33:55 +01009026 FieldOperand(receiver.reg(), JSArray::kElementsOffset));
9027
9028 // Check whether it is possible to omit the write barrier. If the elements
9029 // array is in new space or the value written is a smi we can safely update
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009030 // the elements array without write barrier.
Steve Block6ded16b2010-05-10 14:33:55 +01009031 Label in_new_space;
9032 __ InNewSpace(tmp.reg(), tmp2.reg(), equal, &in_new_space);
9033 if (!value_is_constant) {
9034 __ test(result.reg(), Immediate(kSmiTagMask));
9035 deferred->Branch(not_zero);
9036 }
9037
9038 __ bind(&in_new_space);
Andrei Popescu402d9372010-02-26 13:31:12 +00009039 // Bind the deferred code patch site to be able to locate the fixed
9040 // array map comparison. When debugging, we patch this comparison to
9041 // always fail so that we will hit the IC call in the deferred code
9042 // which will allow the debugger to break for fast case stores.
9043 __ bind(deferred->patch_site());
9044 __ cmp(FieldOperand(tmp.reg(), HeapObject::kMapOffset),
9045 Immediate(Factory::fixed_array_map()));
9046 deferred->Branch(not_equal);
9047
9048 // Store the value.
Kristian Monsen25f61362010-05-21 11:50:48 +01009049 __ mov(FixedArrayElementOperand(tmp.reg(), key.reg()), result.reg());
Andrei Popescu402d9372010-02-26 13:31:12 +00009050 __ IncrementCounter(&Counters::keyed_store_inline, 1);
9051
9052 deferred->BindExit();
9053 } else {
9054 result = frame()->CallKeyedStoreIC();
9055 // Make sure that we do not have a test instruction after the
9056 // call. A test instruction after the call is used to
9057 // indicate that we have generated an inline version of the
9058 // keyed store.
9059 __ nop();
Andrei Popescu402d9372010-02-26 13:31:12 +00009060 }
9061 ASSERT(frame()->height() == original_height - 3);
9062 return result;
Leon Clarked91b9f72010-01-27 17:25:45 +00009063}
9064
9065
Steve Blocka7e24c12009-10-30 11:49:00 +00009066#undef __
9067#define __ ACCESS_MASM(masm)
9068
9069
9070Handle<String> Reference::GetName() {
9071 ASSERT(type_ == NAMED);
9072 Property* property = expression_->AsProperty();
9073 if (property == NULL) {
9074 // Global variable reference treated as a named property reference.
9075 VariableProxy* proxy = expression_->AsVariableProxy();
9076 ASSERT(proxy->AsVariable() != NULL);
9077 ASSERT(proxy->AsVariable()->is_global());
9078 return proxy->name();
9079 } else {
9080 Literal* raw_name = property->key()->AsLiteral();
9081 ASSERT(raw_name != NULL);
Andrei Popescu402d9372010-02-26 13:31:12 +00009082 return Handle<String>::cast(raw_name->handle());
Steve Blocka7e24c12009-10-30 11:49:00 +00009083 }
9084}
9085
9086
Steve Blockd0582a62009-12-15 09:54:21 +00009087void Reference::GetValue() {
Steve Blocka7e24c12009-10-30 11:49:00 +00009088 ASSERT(!cgen_->in_spilled_code());
9089 ASSERT(cgen_->HasValidEntryRegisters());
9090 ASSERT(!is_illegal());
9091 MacroAssembler* masm = cgen_->masm();
9092
9093 // Record the source position for the property load.
9094 Property* property = expression_->AsProperty();
9095 if (property != NULL) {
9096 cgen_->CodeForSourcePosition(property->position());
9097 }
9098
9099 switch (type_) {
9100 case SLOT: {
9101 Comment cmnt(masm, "[ Load from Slot");
9102 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
9103 ASSERT(slot != NULL);
Leon Clarkef7060e22010-06-03 12:02:55 +01009104 cgen_->LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Andrei Popescu402d9372010-02-26 13:31:12 +00009105 if (!persist_after_get_) set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00009106 break;
9107 }
9108
9109 case NAMED: {
Steve Blocka7e24c12009-10-30 11:49:00 +00009110 Variable* var = expression_->AsVariableProxy()->AsVariable();
9111 bool is_global = var != NULL;
9112 ASSERT(!is_global || var->is_global());
Andrei Popescu402d9372010-02-26 13:31:12 +00009113 if (persist_after_get_) cgen_->frame()->Dup();
9114 Result result = cgen_->EmitNamedLoad(GetName(), is_global);
9115 if (!persist_after_get_) set_unloaded();
9116 cgen_->frame()->Push(&result);
Steve Blocka7e24c12009-10-30 11:49:00 +00009117 break;
9118 }
9119
9120 case KEYED: {
Andrei Popescu402d9372010-02-26 13:31:12 +00009121 if (persist_after_get_) {
9122 cgen_->frame()->PushElementAt(1);
9123 cgen_->frame()->PushElementAt(1);
9124 }
9125 Result value = cgen_->EmitKeyedLoad();
Leon Clarked91b9f72010-01-27 17:25:45 +00009126 cgen_->frame()->Push(&value);
Andrei Popescu402d9372010-02-26 13:31:12 +00009127 if (!persist_after_get_) set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00009128 break;
9129 }
9130
9131 default:
9132 UNREACHABLE();
9133 }
9134}
9135
9136
Steve Blockd0582a62009-12-15 09:54:21 +00009137void Reference::TakeValue() {
Steve Blocka7e24c12009-10-30 11:49:00 +00009138 // For non-constant frame-allocated slots, we invalidate the value in the
9139 // slot. For all others, we fall back on GetValue.
9140 ASSERT(!cgen_->in_spilled_code());
9141 ASSERT(!is_illegal());
9142 if (type_ != SLOT) {
Steve Blockd0582a62009-12-15 09:54:21 +00009143 GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00009144 return;
9145 }
9146
9147 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
9148 ASSERT(slot != NULL);
9149 if (slot->type() == Slot::LOOKUP ||
9150 slot->type() == Slot::CONTEXT ||
9151 slot->var()->mode() == Variable::CONST ||
9152 slot->is_arguments()) {
Steve Blockd0582a62009-12-15 09:54:21 +00009153 GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00009154 return;
9155 }
9156
9157 // Only non-constant, frame-allocated parameters and locals can
9158 // reach here. Be careful not to use the optimizations for arguments
9159 // object access since it may not have been initialized yet.
9160 ASSERT(!slot->is_arguments());
9161 if (slot->type() == Slot::PARAMETER) {
9162 cgen_->frame()->TakeParameterAt(slot->index());
9163 } else {
9164 ASSERT(slot->type() == Slot::LOCAL);
9165 cgen_->frame()->TakeLocalAt(slot->index());
9166 }
Leon Clarked91b9f72010-01-27 17:25:45 +00009167
9168 ASSERT(persist_after_get_);
9169 // Do not unload the reference, because it is used in SetValue.
Steve Blocka7e24c12009-10-30 11:49:00 +00009170}
9171
9172
9173void Reference::SetValue(InitState init_state) {
9174 ASSERT(cgen_->HasValidEntryRegisters());
9175 ASSERT(!is_illegal());
9176 MacroAssembler* masm = cgen_->masm();
9177 switch (type_) {
9178 case SLOT: {
9179 Comment cmnt(masm, "[ Store to Slot");
9180 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
9181 ASSERT(slot != NULL);
9182 cgen_->StoreToSlot(slot, init_state);
Andrei Popescu402d9372010-02-26 13:31:12 +00009183 set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00009184 break;
9185 }
9186
9187 case NAMED: {
9188 Comment cmnt(masm, "[ Store to named Property");
Andrei Popescu402d9372010-02-26 13:31:12 +00009189 Result answer = cgen_->EmitNamedStore(GetName(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00009190 cgen_->frame()->Push(&answer);
Leon Clarke4515c472010-02-03 11:58:03 +00009191 set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00009192 break;
9193 }
9194
9195 case KEYED: {
9196 Comment cmnt(masm, "[ Store to keyed Property");
Steve Blocka7e24c12009-10-30 11:49:00 +00009197 Property* property = expression()->AsProperty();
9198 ASSERT(property != NULL);
Steve Block6ded16b2010-05-10 14:33:55 +01009199
Andrei Popescu402d9372010-02-26 13:31:12 +00009200 Result answer = cgen_->EmitKeyedStore(property->key()->type());
9201 cgen_->frame()->Push(&answer);
9202 set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00009203 break;
9204 }
9205
Andrei Popescu402d9372010-02-26 13:31:12 +00009206 case UNLOADED:
9207 case ILLEGAL:
Steve Blocka7e24c12009-10-30 11:49:00 +00009208 UNREACHABLE();
9209 }
9210}
9211
9212
Leon Clarkee46be812010-01-19 14:06:41 +00009213void FastNewClosureStub::Generate(MacroAssembler* masm) {
Steve Block6ded16b2010-05-10 14:33:55 +01009214 // Create a new closure from the given function info in new
9215 // space. Set the context to the current context in esi.
Leon Clarkee46be812010-01-19 14:06:41 +00009216 Label gc;
9217 __ AllocateInNewSpace(JSFunction::kSize, eax, ebx, ecx, &gc, TAG_OBJECT);
9218
Steve Block6ded16b2010-05-10 14:33:55 +01009219 // Get the function info from the stack.
Leon Clarkee46be812010-01-19 14:06:41 +00009220 __ mov(edx, Operand(esp, 1 * kPointerSize));
9221
9222 // Compute the function map in the current global context and set that
9223 // as the map of the allocated object.
9224 __ mov(ecx, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
9225 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalContextOffset));
9226 __ mov(ecx, Operand(ecx, Context::SlotOffset(Context::FUNCTION_MAP_INDEX)));
9227 __ mov(FieldOperand(eax, JSObject::kMapOffset), ecx);
9228
Steve Block6ded16b2010-05-10 14:33:55 +01009229 // Initialize the rest of the function. We don't have to update the
9230 // write barrier because the allocated object is in new space.
9231 __ mov(ebx, Immediate(Factory::empty_fixed_array()));
9232 __ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ebx);
9233 __ mov(FieldOperand(eax, JSObject::kElementsOffset), ebx);
9234 __ mov(FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset),
9235 Immediate(Factory::the_hole_value()));
9236 __ mov(FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset), edx);
9237 __ mov(FieldOperand(eax, JSFunction::kContextOffset), esi);
9238 __ mov(FieldOperand(eax, JSFunction::kLiteralsOffset), ebx);
Leon Clarkee46be812010-01-19 14:06:41 +00009239
9240 // Return and remove the on-stack parameter.
9241 __ ret(1 * kPointerSize);
9242
9243 // Create a new closure through the slower runtime call.
9244 __ bind(&gc);
9245 __ pop(ecx); // Temporarily remove return address.
9246 __ pop(edx);
9247 __ push(esi);
9248 __ push(edx);
9249 __ push(ecx); // Restore return address.
Steve Block6ded16b2010-05-10 14:33:55 +01009250 __ TailCallRuntime(Runtime::kNewClosure, 2, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00009251}
9252
9253
9254void FastNewContextStub::Generate(MacroAssembler* masm) {
9255 // Try to allocate the context in new space.
9256 Label gc;
9257 int length = slots_ + Context::MIN_CONTEXT_SLOTS;
9258 __ AllocateInNewSpace((length * kPointerSize) + FixedArray::kHeaderSize,
9259 eax, ebx, ecx, &gc, TAG_OBJECT);
9260
9261 // Get the function from the stack.
9262 __ mov(ecx, Operand(esp, 1 * kPointerSize));
9263
9264 // Setup the object header.
9265 __ mov(FieldOperand(eax, HeapObject::kMapOffset), Factory::context_map());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009266 __ mov(FieldOperand(eax, Context::kLengthOffset),
9267 Immediate(Smi::FromInt(length)));
Leon Clarkee46be812010-01-19 14:06:41 +00009268
9269 // Setup the fixed slots.
9270 __ xor_(ebx, Operand(ebx)); // Set to NULL.
9271 __ mov(Operand(eax, Context::SlotOffset(Context::CLOSURE_INDEX)), ecx);
9272 __ mov(Operand(eax, Context::SlotOffset(Context::FCONTEXT_INDEX)), eax);
9273 __ mov(Operand(eax, Context::SlotOffset(Context::PREVIOUS_INDEX)), ebx);
9274 __ mov(Operand(eax, Context::SlotOffset(Context::EXTENSION_INDEX)), ebx);
9275
9276 // Copy the global object from the surrounding context. We go through the
9277 // context in the function (ecx) to match the allocation behavior we have
9278 // in the runtime system (see Heap::AllocateFunctionContext).
9279 __ mov(ebx, FieldOperand(ecx, JSFunction::kContextOffset));
9280 __ mov(ebx, Operand(ebx, Context::SlotOffset(Context::GLOBAL_INDEX)));
9281 __ mov(Operand(eax, Context::SlotOffset(Context::GLOBAL_INDEX)), ebx);
9282
9283 // Initialize the rest of the slots to undefined.
9284 __ mov(ebx, Factory::undefined_value());
9285 for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
9286 __ mov(Operand(eax, Context::SlotOffset(i)), ebx);
9287 }
9288
9289 // Return and remove the on-stack parameter.
9290 __ mov(esi, Operand(eax));
9291 __ ret(1 * kPointerSize);
9292
9293 // Need to collect. Call into runtime system.
9294 __ bind(&gc);
Steve Block6ded16b2010-05-10 14:33:55 +01009295 __ TailCallRuntime(Runtime::kNewContext, 1, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00009296}
9297
9298
9299void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) {
Andrei Popescu402d9372010-02-26 13:31:12 +00009300 // Stack layout on entry:
9301 //
9302 // [esp + kPointerSize]: constant elements.
9303 // [esp + (2 * kPointerSize)]: literal index.
9304 // [esp + (3 * kPointerSize)]: literals array.
9305
9306 // All sizes here are multiples of kPointerSize.
Leon Clarkee46be812010-01-19 14:06:41 +00009307 int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0;
9308 int size = JSArray::kSize + elements_size;
9309
9310 // Load boilerplate object into ecx and check if we need to create a
9311 // boilerplate.
9312 Label slow_case;
9313 __ mov(ecx, Operand(esp, 3 * kPointerSize));
9314 __ mov(eax, Operand(esp, 2 * kPointerSize));
9315 ASSERT((kPointerSize == 4) && (kSmiTagSize == 1) && (kSmiTag == 0));
Kristian Monsen25f61362010-05-21 11:50:48 +01009316 __ mov(ecx, CodeGenerator::FixedArrayElementOperand(ecx, eax));
Leon Clarkee46be812010-01-19 14:06:41 +00009317 __ cmp(ecx, Factory::undefined_value());
9318 __ j(equal, &slow_case);
9319
9320 // Allocate both the JS array and the elements array in one big
9321 // allocation. This avoids multiple limit checks.
9322 __ AllocateInNewSpace(size, eax, ebx, edx, &slow_case, TAG_OBJECT);
9323
9324 // Copy the JS array part.
9325 for (int i = 0; i < JSArray::kSize; i += kPointerSize) {
9326 if ((i != JSArray::kElementsOffset) || (length_ == 0)) {
9327 __ mov(ebx, FieldOperand(ecx, i));
9328 __ mov(FieldOperand(eax, i), ebx);
9329 }
9330 }
9331
9332 if (length_ > 0) {
9333 // Get hold of the elements array of the boilerplate and setup the
9334 // elements pointer in the resulting object.
9335 __ mov(ecx, FieldOperand(ecx, JSArray::kElementsOffset));
9336 __ lea(edx, Operand(eax, JSArray::kSize));
9337 __ mov(FieldOperand(eax, JSArray::kElementsOffset), edx);
9338
9339 // Copy the elements array.
9340 for (int i = 0; i < elements_size; i += kPointerSize) {
9341 __ mov(ebx, FieldOperand(ecx, i));
9342 __ mov(FieldOperand(edx, i), ebx);
9343 }
9344 }
9345
9346 // Return and remove the on-stack parameters.
9347 __ ret(3 * kPointerSize);
9348
9349 __ bind(&slow_case);
Steve Block6ded16b2010-05-10 14:33:55 +01009350 __ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00009351}
9352
9353
Steve Blocka7e24c12009-10-30 11:49:00 +00009354// NOTE: The stub does not handle the inlined cases (Smis, Booleans, undefined).
9355void ToBooleanStub::Generate(MacroAssembler* masm) {
9356 Label false_result, true_result, not_string;
9357 __ mov(eax, Operand(esp, 1 * kPointerSize));
9358
9359 // 'null' => false.
9360 __ cmp(eax, Factory::null_value());
9361 __ j(equal, &false_result);
9362
9363 // Get the map and type of the heap object.
9364 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
9365 __ movzx_b(ecx, FieldOperand(edx, Map::kInstanceTypeOffset));
9366
9367 // Undetectable => false.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009368 __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
9369 1 << Map::kIsUndetectable);
Steve Blocka7e24c12009-10-30 11:49:00 +00009370 __ j(not_zero, &false_result);
9371
9372 // JavaScript object => true.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009373 __ CmpInstanceType(edx, FIRST_JS_OBJECT_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00009374 __ j(above_equal, &true_result);
9375
9376 // String value => false iff empty.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009377 __ CmpInstanceType(edx, FIRST_NONSTRING_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00009378 __ j(above_equal, &not_string);
Steve Block6ded16b2010-05-10 14:33:55 +01009379 ASSERT(kSmiTag == 0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01009380 __ cmp(FieldOperand(eax, String::kLengthOffset), Immediate(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00009381 __ j(zero, &false_result);
9382 __ jmp(&true_result);
9383
9384 __ bind(&not_string);
9385 // HeapNumber => false iff +0, -0, or NaN.
9386 __ cmp(edx, Factory::heap_number_map());
9387 __ j(not_equal, &true_result);
9388 __ fldz();
9389 __ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
Steve Block3ce2e202009-11-05 08:53:23 +00009390 __ FCmp();
Steve Blocka7e24c12009-10-30 11:49:00 +00009391 __ j(zero, &false_result);
9392 // Fall through to |true_result|.
9393
9394 // Return 1/0 for true/false in eax.
9395 __ bind(&true_result);
9396 __ mov(eax, 1);
9397 __ ret(1 * kPointerSize);
9398 __ bind(&false_result);
9399 __ mov(eax, 0);
9400 __ ret(1 * kPointerSize);
9401}
9402
9403
Steve Block3ce2e202009-11-05 08:53:23 +00009404void GenericBinaryOpStub::GenerateCall(
9405 MacroAssembler* masm,
9406 Register left,
9407 Register right) {
9408 if (!ArgsInRegistersSupported()) {
9409 // Pass arguments on the stack.
9410 __ push(left);
9411 __ push(right);
9412 } else {
9413 // The calling convention with registers is left in edx and right in eax.
Steve Blockd0582a62009-12-15 09:54:21 +00009414 Register left_arg = edx;
9415 Register right_arg = eax;
9416 if (!(left.is(left_arg) && right.is(right_arg))) {
9417 if (left.is(right_arg) && right.is(left_arg)) {
Steve Block3ce2e202009-11-05 08:53:23 +00009418 if (IsOperationCommutative()) {
9419 SetArgsReversed();
9420 } else {
9421 __ xchg(left, right);
9422 }
Steve Blockd0582a62009-12-15 09:54:21 +00009423 } else if (left.is(left_arg)) {
9424 __ mov(right_arg, right);
Andrei Popescu402d9372010-02-26 13:31:12 +00009425 } else if (right.is(right_arg)) {
9426 __ mov(left_arg, left);
Steve Blockd0582a62009-12-15 09:54:21 +00009427 } else if (left.is(right_arg)) {
Steve Block3ce2e202009-11-05 08:53:23 +00009428 if (IsOperationCommutative()) {
Steve Blockd0582a62009-12-15 09:54:21 +00009429 __ mov(left_arg, right);
Steve Block3ce2e202009-11-05 08:53:23 +00009430 SetArgsReversed();
9431 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00009432 // Order of moves important to avoid destroying left argument.
9433 __ mov(left_arg, left);
9434 __ mov(right_arg, right);
Steve Block3ce2e202009-11-05 08:53:23 +00009435 }
Steve Blockd0582a62009-12-15 09:54:21 +00009436 } else if (right.is(left_arg)) {
Steve Block3ce2e202009-11-05 08:53:23 +00009437 if (IsOperationCommutative()) {
Steve Blockd0582a62009-12-15 09:54:21 +00009438 __ mov(right_arg, left);
Steve Block3ce2e202009-11-05 08:53:23 +00009439 SetArgsReversed();
9440 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00009441 // Order of moves important to avoid destroying right argument.
9442 __ mov(right_arg, right);
9443 __ mov(left_arg, left);
Steve Block3ce2e202009-11-05 08:53:23 +00009444 }
Steve Block3ce2e202009-11-05 08:53:23 +00009445 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00009446 // Order of moves is not important.
9447 __ mov(left_arg, left);
9448 __ mov(right_arg, right);
Steve Block3ce2e202009-11-05 08:53:23 +00009449 }
9450 }
9451
9452 // Update flags to indicate that arguments are in registers.
9453 SetArgsInRegisters();
Steve Blockd0582a62009-12-15 09:54:21 +00009454 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
Steve Block3ce2e202009-11-05 08:53:23 +00009455 }
9456
9457 // Call the stub.
9458 __ CallStub(this);
9459}
9460
9461
9462void GenericBinaryOpStub::GenerateCall(
9463 MacroAssembler* masm,
9464 Register left,
9465 Smi* right) {
9466 if (!ArgsInRegistersSupported()) {
9467 // Pass arguments on the stack.
9468 __ push(left);
9469 __ push(Immediate(right));
9470 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00009471 // The calling convention with registers is left in edx and right in eax.
9472 Register left_arg = edx;
9473 Register right_arg = eax;
9474 if (left.is(left_arg)) {
9475 __ mov(right_arg, Immediate(right));
9476 } else if (left.is(right_arg) && IsOperationCommutative()) {
9477 __ mov(left_arg, Immediate(right));
Steve Block3ce2e202009-11-05 08:53:23 +00009478 SetArgsReversed();
9479 } else {
Andrei Popescu402d9372010-02-26 13:31:12 +00009480 // For non-commutative operations, left and right_arg might be
9481 // the same register. Therefore, the order of the moves is
9482 // important here in order to not overwrite left before moving
9483 // it to left_arg.
Steve Blockd0582a62009-12-15 09:54:21 +00009484 __ mov(left_arg, left);
9485 __ mov(right_arg, Immediate(right));
Steve Block3ce2e202009-11-05 08:53:23 +00009486 }
9487
9488 // Update flags to indicate that arguments are in registers.
9489 SetArgsInRegisters();
Steve Blockd0582a62009-12-15 09:54:21 +00009490 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
Steve Block3ce2e202009-11-05 08:53:23 +00009491 }
9492
9493 // Call the stub.
9494 __ CallStub(this);
9495}
9496
9497
9498void GenericBinaryOpStub::GenerateCall(
9499 MacroAssembler* masm,
9500 Smi* left,
9501 Register right) {
9502 if (!ArgsInRegistersSupported()) {
9503 // Pass arguments on the stack.
9504 __ push(Immediate(left));
9505 __ push(right);
9506 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00009507 // The calling convention with registers is left in edx and right in eax.
9508 Register left_arg = edx;
9509 Register right_arg = eax;
9510 if (right.is(right_arg)) {
9511 __ mov(left_arg, Immediate(left));
9512 } else if (right.is(left_arg) && IsOperationCommutative()) {
9513 __ mov(right_arg, Immediate(left));
9514 SetArgsReversed();
Steve Block3ce2e202009-11-05 08:53:23 +00009515 } else {
Andrei Popescu402d9372010-02-26 13:31:12 +00009516 // For non-commutative operations, right and left_arg might be
9517 // the same register. Therefore, the order of the moves is
9518 // important here in order to not overwrite right before moving
9519 // it to right_arg.
Steve Blockd0582a62009-12-15 09:54:21 +00009520 __ mov(right_arg, right);
Andrei Popescu402d9372010-02-26 13:31:12 +00009521 __ mov(left_arg, Immediate(left));
Steve Block3ce2e202009-11-05 08:53:23 +00009522 }
9523 // Update flags to indicate that arguments are in registers.
9524 SetArgsInRegisters();
Steve Blockd0582a62009-12-15 09:54:21 +00009525 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
Steve Block3ce2e202009-11-05 08:53:23 +00009526 }
9527
9528 // Call the stub.
9529 __ CallStub(this);
9530}
9531
9532
Leon Clarked91b9f72010-01-27 17:25:45 +00009533Result GenericBinaryOpStub::GenerateCall(MacroAssembler* masm,
9534 VirtualFrame* frame,
9535 Result* left,
9536 Result* right) {
9537 if (ArgsInRegistersSupported()) {
9538 SetArgsInRegisters();
9539 return frame->CallStub(this, left, right);
9540 } else {
9541 frame->Push(left);
9542 frame->Push(right);
9543 return frame->CallStub(this, 2);
9544 }
9545}
9546
9547
Steve Blocka7e24c12009-10-30 11:49:00 +00009548void GenericBinaryOpStub::GenerateSmiCode(MacroAssembler* masm, Label* slow) {
Leon Clarked91b9f72010-01-27 17:25:45 +00009549 // 1. Move arguments into edx, eax except for DIV and MOD, which need the
9550 // dividend in eax and edx free for the division. Use eax, ebx for those.
9551 Comment load_comment(masm, "-- Load arguments");
9552 Register left = edx;
9553 Register right = eax;
9554 if (op_ == Token::DIV || op_ == Token::MOD) {
9555 left = eax;
9556 right = ebx;
9557 if (HasArgsInRegisters()) {
9558 __ mov(ebx, eax);
9559 __ mov(eax, edx);
9560 }
9561 }
9562 if (!HasArgsInRegisters()) {
9563 __ mov(right, Operand(esp, 1 * kPointerSize));
9564 __ mov(left, Operand(esp, 2 * kPointerSize));
9565 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009566
Steve Block6ded16b2010-05-10 14:33:55 +01009567 if (static_operands_type_.IsSmi()) {
9568 if (FLAG_debug_code) {
9569 __ AbortIfNotSmi(left);
9570 __ AbortIfNotSmi(right);
9571 }
9572 if (op_ == Token::BIT_OR) {
9573 __ or_(right, Operand(left));
9574 GenerateReturn(masm);
9575 return;
9576 } else if (op_ == Token::BIT_AND) {
9577 __ and_(right, Operand(left));
9578 GenerateReturn(masm);
9579 return;
9580 } else if (op_ == Token::BIT_XOR) {
9581 __ xor_(right, Operand(left));
9582 GenerateReturn(masm);
9583 return;
9584 }
9585 }
9586
Leon Clarked91b9f72010-01-27 17:25:45 +00009587 // 2. Prepare the smi check of both operands by oring them together.
9588 Comment smi_check_comment(masm, "-- Smi check arguments");
9589 Label not_smis;
9590 Register combined = ecx;
9591 ASSERT(!left.is(combined) && !right.is(combined));
Steve Blocka7e24c12009-10-30 11:49:00 +00009592 switch (op_) {
Leon Clarked91b9f72010-01-27 17:25:45 +00009593 case Token::BIT_OR:
9594 // Perform the operation into eax and smi check the result. Preserve
9595 // eax in case the result is not a smi.
9596 ASSERT(!left.is(ecx) && !right.is(ecx));
9597 __ mov(ecx, right);
9598 __ or_(right, Operand(left)); // Bitwise or is commutative.
9599 combined = right;
9600 break;
9601
9602 case Token::BIT_XOR:
9603 case Token::BIT_AND:
Leon Clarkeeab96aa2010-01-27 16:31:12 +00009604 case Token::ADD:
Steve Blocka7e24c12009-10-30 11:49:00 +00009605 case Token::SUB:
Leon Clarked91b9f72010-01-27 17:25:45 +00009606 case Token::MUL:
Steve Blocka7e24c12009-10-30 11:49:00 +00009607 case Token::DIV:
9608 case Token::MOD:
Leon Clarked91b9f72010-01-27 17:25:45 +00009609 __ mov(combined, right);
9610 __ or_(combined, Operand(left));
9611 break;
9612
9613 case Token::SHL:
9614 case Token::SAR:
9615 case Token::SHR:
9616 // Move the right operand into ecx for the shift operation, use eax
9617 // for the smi check register.
9618 ASSERT(!left.is(ecx) && !right.is(ecx));
9619 __ mov(ecx, right);
9620 __ or_(right, Operand(left));
9621 combined = right;
Steve Blocka7e24c12009-10-30 11:49:00 +00009622 break;
9623
9624 default:
Steve Blocka7e24c12009-10-30 11:49:00 +00009625 break;
9626 }
9627
Leon Clarked91b9f72010-01-27 17:25:45 +00009628 // 3. Perform the smi check of the operands.
9629 ASSERT(kSmiTag == 0); // Adjust zero check if not the case.
9630 __ test(combined, Immediate(kSmiTagMask));
9631 __ j(not_zero, &not_smis, not_taken);
Steve Blocka7e24c12009-10-30 11:49:00 +00009632
Leon Clarked91b9f72010-01-27 17:25:45 +00009633 // 4. Operands are both smis, perform the operation leaving the result in
9634 // eax and check the result if necessary.
9635 Comment perform_smi(masm, "-- Perform smi operation");
9636 Label use_fp_on_smis;
Steve Blocka7e24c12009-10-30 11:49:00 +00009637 switch (op_) {
Leon Clarked91b9f72010-01-27 17:25:45 +00009638 case Token::BIT_OR:
9639 // Nothing to do.
9640 break;
9641
9642 case Token::BIT_XOR:
9643 ASSERT(right.is(eax));
9644 __ xor_(right, Operand(left)); // Bitwise xor is commutative.
9645 break;
9646
9647 case Token::BIT_AND:
9648 ASSERT(right.is(eax));
9649 __ and_(right, Operand(left)); // Bitwise and is commutative.
9650 break;
9651
9652 case Token::SHL:
9653 // Remove tags from operands (but keep sign).
9654 __ SmiUntag(left);
9655 __ SmiUntag(ecx);
9656 // Perform the operation.
9657 __ shl_cl(left);
9658 // Check that the *signed* result fits in a smi.
9659 __ cmp(left, 0xc0000000);
9660 __ j(sign, &use_fp_on_smis, not_taken);
9661 // Tag the result and store it in register eax.
9662 __ SmiTag(left);
9663 __ mov(eax, left);
9664 break;
9665
9666 case Token::SAR:
9667 // Remove tags from operands (but keep sign).
9668 __ SmiUntag(left);
9669 __ SmiUntag(ecx);
9670 // Perform the operation.
9671 __ sar_cl(left);
9672 // Tag the result and store it in register eax.
9673 __ SmiTag(left);
9674 __ mov(eax, left);
9675 break;
9676
9677 case Token::SHR:
9678 // Remove tags from operands (but keep sign).
9679 __ SmiUntag(left);
9680 __ SmiUntag(ecx);
9681 // Perform the operation.
9682 __ shr_cl(left);
9683 // Check that the *unsigned* result fits in a smi.
9684 // Neither of the two high-order bits can be set:
9685 // - 0x80000000: high bit would be lost when smi tagging.
9686 // - 0x40000000: this number would convert to negative when
9687 // Smi tagging these two cases can only happen with shifts
9688 // by 0 or 1 when handed a valid smi.
9689 __ test(left, Immediate(0xc0000000));
9690 __ j(not_zero, slow, not_taken);
9691 // Tag the result and store it in register eax.
9692 __ SmiTag(left);
9693 __ mov(eax, left);
9694 break;
9695
Steve Blocka7e24c12009-10-30 11:49:00 +00009696 case Token::ADD:
Leon Clarked91b9f72010-01-27 17:25:45 +00009697 ASSERT(right.is(eax));
9698 __ add(right, Operand(left)); // Addition is commutative.
9699 __ j(overflow, &use_fp_on_smis, not_taken);
9700 break;
9701
Steve Blocka7e24c12009-10-30 11:49:00 +00009702 case Token::SUB:
Leon Clarked91b9f72010-01-27 17:25:45 +00009703 __ sub(left, Operand(right));
9704 __ j(overflow, &use_fp_on_smis, not_taken);
9705 __ mov(eax, left);
Steve Blocka7e24c12009-10-30 11:49:00 +00009706 break;
9707
9708 case Token::MUL:
9709 // If the smi tag is 0 we can just leave the tag on one operand.
Leon Clarked91b9f72010-01-27 17:25:45 +00009710 ASSERT(kSmiTag == 0); // Adjust code below if not the case.
9711 // We can't revert the multiplication if the result is not a smi
9712 // so save the right operand.
9713 __ mov(ebx, right);
Steve Blocka7e24c12009-10-30 11:49:00 +00009714 // Remove tag from one of the operands (but keep sign).
Leon Clarked91b9f72010-01-27 17:25:45 +00009715 __ SmiUntag(right);
Steve Blocka7e24c12009-10-30 11:49:00 +00009716 // Do multiplication.
Leon Clarked91b9f72010-01-27 17:25:45 +00009717 __ imul(right, Operand(left)); // Multiplication is commutative.
9718 __ j(overflow, &use_fp_on_smis, not_taken);
9719 // Check for negative zero result. Use combined = left | right.
9720 __ NegativeZeroTest(right, combined, &use_fp_on_smis);
Steve Blocka7e24c12009-10-30 11:49:00 +00009721 break;
9722
9723 case Token::DIV:
Leon Clarked91b9f72010-01-27 17:25:45 +00009724 // We can't revert the division if the result is not a smi so
9725 // save the left operand.
9726 __ mov(edi, left);
9727 // Check for 0 divisor.
9728 __ test(right, Operand(right));
9729 __ j(zero, &use_fp_on_smis, not_taken);
9730 // Sign extend left into edx:eax.
9731 ASSERT(left.is(eax));
9732 __ cdq();
9733 // Divide edx:eax by right.
9734 __ idiv(right);
9735 // Check for the corner case of dividing the most negative smi by
9736 // -1. We cannot use the overflow flag, since it is not set by idiv
9737 // instruction.
Steve Blocka7e24c12009-10-30 11:49:00 +00009738 ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
9739 __ cmp(eax, 0x40000000);
Leon Clarked91b9f72010-01-27 17:25:45 +00009740 __ j(equal, &use_fp_on_smis);
9741 // Check for negative zero result. Use combined = left | right.
9742 __ NegativeZeroTest(eax, combined, &use_fp_on_smis);
Steve Blocka7e24c12009-10-30 11:49:00 +00009743 // Check that the remainder is zero.
9744 __ test(edx, Operand(edx));
Leon Clarked91b9f72010-01-27 17:25:45 +00009745 __ j(not_zero, &use_fp_on_smis);
Steve Blocka7e24c12009-10-30 11:49:00 +00009746 // Tag the result and store it in register eax.
Leon Clarkee46be812010-01-19 14:06:41 +00009747 __ SmiTag(eax);
Steve Blocka7e24c12009-10-30 11:49:00 +00009748 break;
9749
9750 case Token::MOD:
Leon Clarked91b9f72010-01-27 17:25:45 +00009751 // Check for 0 divisor.
9752 __ test(right, Operand(right));
9753 __ j(zero, &not_smis, not_taken);
9754
9755 // Sign extend left into edx:eax.
9756 ASSERT(left.is(eax));
9757 __ cdq();
9758 // Divide edx:eax by right.
9759 __ idiv(right);
9760 // Check for negative zero result. Use combined = left | right.
9761 __ NegativeZeroTest(edx, combined, slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00009762 // Move remainder to register eax.
Leon Clarked91b9f72010-01-27 17:25:45 +00009763 __ mov(eax, edx);
Steve Blocka7e24c12009-10-30 11:49:00 +00009764 break;
9765
9766 default:
9767 UNREACHABLE();
Leon Clarked91b9f72010-01-27 17:25:45 +00009768 }
9769
9770 // 5. Emit return of result in eax.
9771 GenerateReturn(masm);
9772
9773 // 6. For some operations emit inline code to perform floating point
9774 // operations on known smis (e.g., if the result of the operation
9775 // overflowed the smi range).
9776 switch (op_) {
9777 case Token::SHL: {
9778 Comment perform_float(masm, "-- Perform float operation on smis");
9779 __ bind(&use_fp_on_smis);
9780 // Result we want is in left == edx, so we can put the allocated heap
9781 // number in eax.
9782 __ AllocateHeapNumber(eax, ecx, ebx, slow);
9783 // Store the result in the HeapNumber and return.
9784 if (CpuFeatures::IsSupported(SSE2)) {
9785 CpuFeatures::Scope use_sse2(SSE2);
9786 __ cvtsi2sd(xmm0, Operand(left));
9787 __ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
9788 } else {
9789 // It's OK to overwrite the right argument on the stack because we
9790 // are about to return.
9791 __ mov(Operand(esp, 1 * kPointerSize), left);
9792 __ fild_s(Operand(esp, 1 * kPointerSize));
9793 __ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
9794 }
9795 GenerateReturn(masm);
9796 break;
9797 }
9798
9799 case Token::ADD:
9800 case Token::SUB:
9801 case Token::MUL:
9802 case Token::DIV: {
9803 Comment perform_float(masm, "-- Perform float operation on smis");
9804 __ bind(&use_fp_on_smis);
9805 // Restore arguments to edx, eax.
9806 switch (op_) {
9807 case Token::ADD:
9808 // Revert right = right + left.
9809 __ sub(right, Operand(left));
9810 break;
9811 case Token::SUB:
9812 // Revert left = left - right.
9813 __ add(left, Operand(right));
9814 break;
9815 case Token::MUL:
9816 // Right was clobbered but a copy is in ebx.
9817 __ mov(right, ebx);
9818 break;
9819 case Token::DIV:
9820 // Left was clobbered but a copy is in edi. Right is in ebx for
9821 // division.
9822 __ mov(edx, edi);
9823 __ mov(eax, right);
9824 break;
9825 default: UNREACHABLE();
9826 break;
9827 }
9828 __ AllocateHeapNumber(ecx, ebx, no_reg, slow);
9829 if (CpuFeatures::IsSupported(SSE2)) {
9830 CpuFeatures::Scope use_sse2(SSE2);
9831 FloatingPointHelper::LoadSSE2Smis(masm, ebx);
9832 switch (op_) {
9833 case Token::ADD: __ addsd(xmm0, xmm1); break;
9834 case Token::SUB: __ subsd(xmm0, xmm1); break;
9835 case Token::MUL: __ mulsd(xmm0, xmm1); break;
9836 case Token::DIV: __ divsd(xmm0, xmm1); break;
9837 default: UNREACHABLE();
9838 }
9839 __ movdbl(FieldOperand(ecx, HeapNumber::kValueOffset), xmm0);
9840 } else { // SSE2 not available, use FPU.
9841 FloatingPointHelper::LoadFloatSmis(masm, ebx);
9842 switch (op_) {
9843 case Token::ADD: __ faddp(1); break;
9844 case Token::SUB: __ fsubp(1); break;
9845 case Token::MUL: __ fmulp(1); break;
9846 case Token::DIV: __ fdivp(1); break;
9847 default: UNREACHABLE();
9848 }
9849 __ fstp_d(FieldOperand(ecx, HeapNumber::kValueOffset));
9850 }
9851 __ mov(eax, ecx);
9852 GenerateReturn(masm);
9853 break;
9854 }
9855
9856 default:
9857 break;
9858 }
9859
9860 // 7. Non-smi operands, fall out to the non-smi code with the operands in
9861 // edx and eax.
9862 Comment done_comment(masm, "-- Enter non-smi code");
9863 __ bind(&not_smis);
9864 switch (op_) {
9865 case Token::BIT_OR:
9866 case Token::SHL:
9867 case Token::SAR:
9868 case Token::SHR:
9869 // Right operand is saved in ecx and eax was destroyed by the smi
9870 // check.
9871 __ mov(eax, ecx);
9872 break;
9873
9874 case Token::DIV:
9875 case Token::MOD:
9876 // Operands are in eax, ebx at this point.
9877 __ mov(edx, eax);
9878 __ mov(eax, ebx);
9879 break;
9880
9881 default:
Steve Blocka7e24c12009-10-30 11:49:00 +00009882 break;
9883 }
9884}
9885
9886
9887void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
9888 Label call_runtime;
9889
Steve Block3ce2e202009-11-05 08:53:23 +00009890 __ IncrementCounter(&Counters::generic_binary_stub_calls, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00009891
Steve Block3ce2e202009-11-05 08:53:23 +00009892 // Generate fast case smi code if requested. This flag is set when the fast
9893 // case smi code is not generated by the caller. Generating it here will speed
9894 // up common operations.
Steve Block6ded16b2010-05-10 14:33:55 +01009895 if (ShouldGenerateSmiCode()) {
Leon Clarked91b9f72010-01-27 17:25:45 +00009896 GenerateSmiCode(masm, &call_runtime);
9897 } else if (op_ != Token::MOD) { // MOD goes straight to runtime.
Steve Block6ded16b2010-05-10 14:33:55 +01009898 if (!HasArgsInRegisters()) {
9899 GenerateLoadArguments(masm);
9900 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009901 }
9902
Steve Blocka7e24c12009-10-30 11:49:00 +00009903 // Floating point case.
Steve Block6ded16b2010-05-10 14:33:55 +01009904 if (ShouldGenerateFPCode()) {
9905 switch (op_) {
9906 case Token::ADD:
9907 case Token::SUB:
9908 case Token::MUL:
9909 case Token::DIV: {
9910 if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
9911 HasSmiCodeInStub()) {
9912 // Execution reaches this point when the first non-smi argument occurs
9913 // (and only if smi code is generated). This is the right moment to
9914 // patch to HEAP_NUMBERS state. The transition is attempted only for
9915 // the four basic operations. The stub stays in the DEFAULT state
9916 // forever for all other operations (also if smi code is skipped).
9917 GenerateTypeTransition(masm);
Leon Clarkeac952652010-07-15 11:15:24 +01009918 break;
Andrei Popescu402d9372010-02-26 13:31:12 +00009919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009920
Steve Block6ded16b2010-05-10 14:33:55 +01009921 Label not_floats;
Leon Clarkee46be812010-01-19 14:06:41 +00009922 if (CpuFeatures::IsSupported(SSE2)) {
9923 CpuFeatures::Scope use_sse2(SSE2);
Steve Block6ded16b2010-05-10 14:33:55 +01009924 if (static_operands_type_.IsNumber()) {
9925 if (FLAG_debug_code) {
9926 // Assert at runtime that inputs are only numbers.
9927 __ AbortIfNotNumber(edx);
9928 __ AbortIfNotNumber(eax);
9929 }
9930 if (static_operands_type_.IsSmi()) {
9931 if (FLAG_debug_code) {
9932 __ AbortIfNotSmi(edx);
9933 __ AbortIfNotSmi(eax);
9934 }
9935 FloatingPointHelper::LoadSSE2Smis(masm, ecx);
9936 } else {
9937 FloatingPointHelper::LoadSSE2Operands(masm);
9938 }
9939 } else {
9940 FloatingPointHelper::LoadSSE2Operands(masm, &call_runtime);
9941 }
9942
9943 switch (op_) {
9944 case Token::ADD: __ addsd(xmm0, xmm1); break;
9945 case Token::SUB: __ subsd(xmm0, xmm1); break;
9946 case Token::MUL: __ mulsd(xmm0, xmm1); break;
9947 case Token::DIV: __ divsd(xmm0, xmm1); break;
9948 default: UNREACHABLE();
9949 }
9950 GenerateHeapResultAllocation(masm, &call_runtime);
Leon Clarkee46be812010-01-19 14:06:41 +00009951 __ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
Steve Block6ded16b2010-05-10 14:33:55 +01009952 GenerateReturn(masm);
9953 } else { // SSE2 not available, use FPU.
9954 if (static_operands_type_.IsNumber()) {
9955 if (FLAG_debug_code) {
9956 // Assert at runtime that inputs are only numbers.
9957 __ AbortIfNotNumber(edx);
9958 __ AbortIfNotNumber(eax);
9959 }
9960 } else {
9961 FloatingPointHelper::CheckFloatOperands(masm, &call_runtime, ebx);
9962 }
9963 FloatingPointHelper::LoadFloatOperands(
9964 masm,
9965 ecx,
9966 FloatingPointHelper::ARGS_IN_REGISTERS);
9967 switch (op_) {
9968 case Token::ADD: __ faddp(1); break;
9969 case Token::SUB: __ fsubp(1); break;
9970 case Token::MUL: __ fmulp(1); break;
9971 case Token::DIV: __ fdivp(1); break;
9972 default: UNREACHABLE();
9973 }
9974 Label after_alloc_failure;
9975 GenerateHeapResultAllocation(masm, &after_alloc_failure);
Leon Clarkee46be812010-01-19 14:06:41 +00009976 __ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01009977 GenerateReturn(masm);
9978 __ bind(&after_alloc_failure);
9979 __ ffree();
9980 __ jmp(&call_runtime);
Leon Clarkee46be812010-01-19 14:06:41 +00009981 }
Steve Block6ded16b2010-05-10 14:33:55 +01009982 __ bind(&not_floats);
9983 if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
9984 !HasSmiCodeInStub()) {
9985 // Execution reaches this point when the first non-number argument
9986 // occurs (and only if smi code is skipped from the stub, otherwise
9987 // the patching has already been done earlier in this case branch).
9988 // Try patching to STRINGS for ADD operation.
9989 if (op_ == Token::ADD) {
9990 GenerateTypeTransition(masm);
9991 }
9992 }
9993 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00009994 }
Steve Block6ded16b2010-05-10 14:33:55 +01009995 case Token::MOD: {
9996 // For MOD we go directly to runtime in the non-smi case.
9997 break;
9998 }
9999 case Token::BIT_OR:
10000 case Token::BIT_AND:
10001 case Token::BIT_XOR:
10002 case Token::SAR:
10003 case Token::SHL:
10004 case Token::SHR: {
10005 Label non_smi_result;
10006 FloatingPointHelper::LoadAsIntegers(masm,
10007 static_operands_type_,
10008 use_sse3_,
10009 &call_runtime);
10010 switch (op_) {
10011 case Token::BIT_OR: __ or_(eax, Operand(ecx)); break;
10012 case Token::BIT_AND: __ and_(eax, Operand(ecx)); break;
10013 case Token::BIT_XOR: __ xor_(eax, Operand(ecx)); break;
10014 case Token::SAR: __ sar_cl(eax); break;
10015 case Token::SHL: __ shl_cl(eax); break;
10016 case Token::SHR: __ shr_cl(eax); break;
10017 default: UNREACHABLE();
10018 }
10019 if (op_ == Token::SHR) {
10020 // Check if result is non-negative and fits in a smi.
10021 __ test(eax, Immediate(0xc0000000));
10022 __ j(not_zero, &call_runtime);
10023 } else {
10024 // Check if result fits in a smi.
10025 __ cmp(eax, 0xc0000000);
10026 __ j(negative, &non_smi_result);
10027 }
10028 // Tag smi result and return.
10029 __ SmiTag(eax);
10030 GenerateReturn(masm);
10031
10032 // All ops except SHR return a signed int32 that we load in
10033 // a HeapNumber.
10034 if (op_ != Token::SHR) {
10035 __ bind(&non_smi_result);
10036 // Allocate a heap number if needed.
10037 __ mov(ebx, Operand(eax)); // ebx: result
10038 Label skip_allocation;
10039 switch (mode_) {
10040 case OVERWRITE_LEFT:
10041 case OVERWRITE_RIGHT:
10042 // If the operand was an object, we skip the
10043 // allocation of a heap number.
10044 __ mov(eax, Operand(esp, mode_ == OVERWRITE_RIGHT ?
10045 1 * kPointerSize : 2 * kPointerSize));
10046 __ test(eax, Immediate(kSmiTagMask));
10047 __ j(not_zero, &skip_allocation, not_taken);
10048 // Fall through!
10049 case NO_OVERWRITE:
10050 __ AllocateHeapNumber(eax, ecx, edx, &call_runtime);
10051 __ bind(&skip_allocation);
10052 break;
10053 default: UNREACHABLE();
10054 }
10055 // Store the result in the HeapNumber and return.
10056 if (CpuFeatures::IsSupported(SSE2)) {
10057 CpuFeatures::Scope use_sse2(SSE2);
10058 __ cvtsi2sd(xmm0, Operand(ebx));
10059 __ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
10060 } else {
10061 __ mov(Operand(esp, 1 * kPointerSize), ebx);
10062 __ fild_s(Operand(esp, 1 * kPointerSize));
10063 __ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
10064 }
10065 GenerateReturn(masm);
10066 }
10067 break;
10068 }
10069 default: UNREACHABLE(); break;
Steve Blocka7e24c12009-10-30 11:49:00 +000010070 }
Steve Blocka7e24c12009-10-30 11:49:00 +000010071 }
10072
10073 // If all else fails, use the runtime system to get the correct
Steve Block3ce2e202009-11-05 08:53:23 +000010074 // result. If arguments was passed in registers now place them on the
Steve Blockd0582a62009-12-15 09:54:21 +000010075 // stack in the correct order below the return address.
Steve Blocka7e24c12009-10-30 11:49:00 +000010076 __ bind(&call_runtime);
Leon Clarked91b9f72010-01-27 17:25:45 +000010077 if (HasArgsInRegisters()) {
Steve Block6ded16b2010-05-10 14:33:55 +010010078 GenerateRegisterArgsPush(masm);
Steve Block3ce2e202009-11-05 08:53:23 +000010079 }
Steve Block6ded16b2010-05-10 14:33:55 +010010080
Steve Blocka7e24c12009-10-30 11:49:00 +000010081 switch (op_) {
10082 case Token::ADD: {
10083 // Test for string arguments before calling runtime.
Andrei Popescu402d9372010-02-26 13:31:12 +000010084 Label not_strings, not_string1, string1, string1_smi2;
Steve Block6ded16b2010-05-10 14:33:55 +010010085
10086 // If this stub has already generated FP-specific code then the arguments
10087 // are already in edx, eax
10088 if (!ShouldGenerateFPCode() && !HasArgsInRegisters()) {
10089 GenerateLoadArguments(masm);
10090 }
10091
10092 // Registers containing left and right operands respectively.
10093 Register lhs, rhs;
10094 if (HasArgsReversed()) {
10095 lhs = eax;
10096 rhs = edx;
10097 } else {
10098 lhs = edx;
10099 rhs = eax;
10100 }
10101
10102 // Test if first argument is a string.
10103 __ test(lhs, Immediate(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +000010104 __ j(zero, &not_string1);
Steve Block6ded16b2010-05-10 14:33:55 +010010105 __ CmpObjectType(lhs, FIRST_NONSTRING_TYPE, ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +000010106 __ j(above_equal, &not_string1);
10107
Leon Clarked91b9f72010-01-27 17:25:45 +000010108 // First argument is a string, test second.
Steve Block6ded16b2010-05-10 14:33:55 +010010109 __ test(rhs, Immediate(kSmiTagMask));
Andrei Popescu402d9372010-02-26 13:31:12 +000010110 __ j(zero, &string1_smi2);
Steve Block6ded16b2010-05-10 14:33:55 +010010111 __ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +000010112 __ j(above_equal, &string1);
10113
Steve Blockd0582a62009-12-15 09:54:21 +000010114 // First and second argument are strings. Jump to the string add stub.
Andrei Popescu402d9372010-02-26 13:31:12 +000010115 StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB);
10116 __ TailCallStub(&string_add_stub);
Steve Blocka7e24c12009-10-30 11:49:00 +000010117
Andrei Popescu402d9372010-02-26 13:31:12 +000010118 __ bind(&string1_smi2);
10119 // First argument is a string, second is a smi. Try to lookup the number
10120 // string for the smi in the number string cache.
10121 NumberToStringStub::GenerateLookupNumberStringCache(
Steve Block6ded16b2010-05-10 14:33:55 +010010122 masm, rhs, edi, ebx, ecx, true, &string1);
Andrei Popescu402d9372010-02-26 13:31:12 +000010123
Steve Block6ded16b2010-05-10 14:33:55 +010010124 // Replace second argument on stack and tailcall string add stub to make
10125 // the result.
10126 __ mov(Operand(esp, 1 * kPointerSize), edi);
10127 __ TailCallStub(&string_add_stub);
Andrei Popescu402d9372010-02-26 13:31:12 +000010128
Steve Block6ded16b2010-05-10 14:33:55 +010010129 // Only first argument is a string.
Steve Blocka7e24c12009-10-30 11:49:00 +000010130 __ bind(&string1);
Steve Block6ded16b2010-05-10 14:33:55 +010010131 __ InvokeBuiltin(Builtins::STRING_ADD_LEFT, JUMP_FUNCTION);
Steve Blocka7e24c12009-10-30 11:49:00 +000010132
10133 // First argument was not a string, test second.
10134 __ bind(&not_string1);
Steve Block6ded16b2010-05-10 14:33:55 +010010135 __ test(rhs, Immediate(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +000010136 __ j(zero, &not_strings);
Steve Block6ded16b2010-05-10 14:33:55 +010010137 __ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +000010138 __ j(above_equal, &not_strings);
10139
10140 // Only second argument is a string.
Steve Block6ded16b2010-05-10 14:33:55 +010010141 __ InvokeBuiltin(Builtins::STRING_ADD_RIGHT, JUMP_FUNCTION);
Steve Blocka7e24c12009-10-30 11:49:00 +000010142
10143 __ bind(&not_strings);
10144 // Neither argument is a string.
10145 __ InvokeBuiltin(Builtins::ADD, JUMP_FUNCTION);
10146 break;
10147 }
10148 case Token::SUB:
10149 __ InvokeBuiltin(Builtins::SUB, JUMP_FUNCTION);
10150 break;
10151 case Token::MUL:
10152 __ InvokeBuiltin(Builtins::MUL, JUMP_FUNCTION);
Leon Clarked91b9f72010-01-27 17:25:45 +000010153 break;
Steve Blocka7e24c12009-10-30 11:49:00 +000010154 case Token::DIV:
10155 __ InvokeBuiltin(Builtins::DIV, JUMP_FUNCTION);
10156 break;
10157 case Token::MOD:
10158 __ InvokeBuiltin(Builtins::MOD, JUMP_FUNCTION);
10159 break;
10160 case Token::BIT_OR:
10161 __ InvokeBuiltin(Builtins::BIT_OR, JUMP_FUNCTION);
10162 break;
10163 case Token::BIT_AND:
10164 __ InvokeBuiltin(Builtins::BIT_AND, JUMP_FUNCTION);
10165 break;
10166 case Token::BIT_XOR:
10167 __ InvokeBuiltin(Builtins::BIT_XOR, JUMP_FUNCTION);
10168 break;
10169 case Token::SAR:
10170 __ InvokeBuiltin(Builtins::SAR, JUMP_FUNCTION);
10171 break;
10172 case Token::SHL:
10173 __ InvokeBuiltin(Builtins::SHL, JUMP_FUNCTION);
10174 break;
10175 case Token::SHR:
10176 __ InvokeBuiltin(Builtins::SHR, JUMP_FUNCTION);
10177 break;
10178 default:
10179 UNREACHABLE();
10180 }
10181}
10182
10183
Leon Clarked91b9f72010-01-27 17:25:45 +000010184void GenericBinaryOpStub::GenerateHeapResultAllocation(MacroAssembler* masm,
10185 Label* alloc_failure) {
10186 Label skip_allocation;
10187 OverwriteMode mode = mode_;
10188 if (HasArgsReversed()) {
10189 if (mode == OVERWRITE_RIGHT) {
10190 mode = OVERWRITE_LEFT;
10191 } else if (mode == OVERWRITE_LEFT) {
10192 mode = OVERWRITE_RIGHT;
10193 }
10194 }
10195 switch (mode) {
10196 case OVERWRITE_LEFT: {
10197 // If the argument in edx is already an object, we skip the
10198 // allocation of a heap number.
10199 __ test(edx, Immediate(kSmiTagMask));
10200 __ j(not_zero, &skip_allocation, not_taken);
10201 // Allocate a heap number for the result. Keep eax and edx intact
10202 // for the possible runtime call.
10203 __ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
10204 // Now edx can be overwritten losing one of the arguments as we are
10205 // now done and will not need it any more.
10206 __ mov(edx, Operand(ebx));
10207 __ bind(&skip_allocation);
10208 // Use object in edx as a result holder
10209 __ mov(eax, Operand(edx));
10210 break;
10211 }
10212 case OVERWRITE_RIGHT:
10213 // If the argument in eax is already an object, we skip the
10214 // allocation of a heap number.
10215 __ test(eax, Immediate(kSmiTagMask));
10216 __ j(not_zero, &skip_allocation, not_taken);
10217 // Fall through!
10218 case NO_OVERWRITE:
10219 // Allocate a heap number for the result. Keep eax and edx intact
10220 // for the possible runtime call.
10221 __ AllocateHeapNumber(ebx, ecx, no_reg, alloc_failure);
10222 // Now eax can be overwritten losing one of the arguments as we are
10223 // now done and will not need it any more.
10224 __ mov(eax, ebx);
10225 __ bind(&skip_allocation);
10226 break;
10227 default: UNREACHABLE();
10228 }
10229}
10230
10231
Steve Block3ce2e202009-11-05 08:53:23 +000010232void GenericBinaryOpStub::GenerateLoadArguments(MacroAssembler* masm) {
10233 // If arguments are not passed in registers read them from the stack.
Steve Block6ded16b2010-05-10 14:33:55 +010010234 ASSERT(!HasArgsInRegisters());
10235 __ mov(eax, Operand(esp, 1 * kPointerSize));
10236 __ mov(edx, Operand(esp, 2 * kPointerSize));
Steve Block3ce2e202009-11-05 08:53:23 +000010237}
Steve Blocka7e24c12009-10-30 11:49:00 +000010238
Steve Block3ce2e202009-11-05 08:53:23 +000010239
10240void GenericBinaryOpStub::GenerateReturn(MacroAssembler* masm) {
10241 // If arguments are not passed in registers remove them from the stack before
10242 // returning.
Leon Clarked91b9f72010-01-27 17:25:45 +000010243 if (!HasArgsInRegisters()) {
Steve Block3ce2e202009-11-05 08:53:23 +000010244 __ ret(2 * kPointerSize); // Remove both operands
10245 } else {
10246 __ ret(0);
10247 }
Steve Blocka7e24c12009-10-30 11:49:00 +000010248}
10249
10250
Steve Block6ded16b2010-05-10 14:33:55 +010010251void GenericBinaryOpStub::GenerateRegisterArgsPush(MacroAssembler* masm) {
10252 ASSERT(HasArgsInRegisters());
10253 __ pop(ecx);
10254 if (HasArgsReversed()) {
10255 __ push(eax);
10256 __ push(edx);
10257 } else {
10258 __ push(edx);
10259 __ push(eax);
10260 }
10261 __ push(ecx);
10262}
10263
10264
10265void GenericBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) {
Leon Clarkeac952652010-07-15 11:15:24 +010010266 // Ensure the operands are on the stack.
Steve Block6ded16b2010-05-10 14:33:55 +010010267 if (HasArgsInRegisters()) {
10268 GenerateRegisterArgsPush(masm);
Steve Block6ded16b2010-05-10 14:33:55 +010010269 }
10270
Leon Clarkeac952652010-07-15 11:15:24 +010010271 __ pop(ecx); // Save return address.
Steve Block6ded16b2010-05-10 14:33:55 +010010272
Steve Block6ded16b2010-05-10 14:33:55 +010010273 // Left and right arguments are now on top.
Steve Block6ded16b2010-05-10 14:33:55 +010010274 // Push this stub's key. Although the operation and the type info are
10275 // encoded into the key, the encoding is opaque, so push them too.
10276 __ push(Immediate(Smi::FromInt(MinorKey())));
10277 __ push(Immediate(Smi::FromInt(op_)));
10278 __ push(Immediate(Smi::FromInt(runtime_operands_type_)));
10279
Leon Clarkeac952652010-07-15 11:15:24 +010010280 __ push(ecx); // Push return address.
Steve Block6ded16b2010-05-10 14:33:55 +010010281
Leon Clarkeac952652010-07-15 11:15:24 +010010282 // Patch the caller to an appropriate specialized stub and return the
10283 // operation result to the caller of the stub.
Steve Block6ded16b2010-05-10 14:33:55 +010010284 __ TailCallExternalReference(
10285 ExternalReference(IC_Utility(IC::kBinaryOp_Patch)),
Leon Clarkeac952652010-07-15 11:15:24 +010010286 5,
Steve Block6ded16b2010-05-10 14:33:55 +010010287 1);
Steve Block6ded16b2010-05-10 14:33:55 +010010288}
10289
10290
10291Handle<Code> GetBinaryOpStub(int key, BinaryOpIC::TypeInfo type_info) {
10292 GenericBinaryOpStub stub(key, type_info);
10293 return stub.GetCode();
10294}
10295
10296
Andrei Popescu402d9372010-02-26 13:31:12 +000010297void TranscendentalCacheStub::Generate(MacroAssembler* masm) {
10298 // Input on stack:
10299 // esp[4]: argument (should be number).
10300 // esp[0]: return address.
10301 // Test that eax is a number.
10302 Label runtime_call;
10303 Label runtime_call_clear_stack;
10304 Label input_not_smi;
10305 Label loaded;
10306 __ mov(eax, Operand(esp, kPointerSize));
10307 __ test(eax, Immediate(kSmiTagMask));
10308 __ j(not_zero, &input_not_smi);
10309 // Input is a smi. Untag and load it onto the FPU stack.
10310 // Then load the low and high words of the double into ebx, edx.
10311 ASSERT_EQ(1, kSmiTagSize);
10312 __ sar(eax, 1);
10313 __ sub(Operand(esp), Immediate(2 * kPointerSize));
10314 __ mov(Operand(esp, 0), eax);
10315 __ fild_s(Operand(esp, 0));
10316 __ fst_d(Operand(esp, 0));
10317 __ pop(edx);
10318 __ pop(ebx);
10319 __ jmp(&loaded);
10320 __ bind(&input_not_smi);
10321 // Check if input is a HeapNumber.
10322 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
10323 __ cmp(Operand(ebx), Immediate(Factory::heap_number_map()));
10324 __ j(not_equal, &runtime_call);
10325 // Input is a HeapNumber. Push it on the FPU stack and load its
10326 // low and high words into ebx, edx.
10327 __ fld_d(FieldOperand(eax, HeapNumber::kValueOffset));
10328 __ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
10329 __ mov(ebx, FieldOperand(eax, HeapNumber::kMantissaOffset));
10330
10331 __ bind(&loaded);
10332 // ST[0] == double value
10333 // ebx = low 32 bits of double value
10334 // edx = high 32 bits of double value
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010010335 // Compute hash (the shifts are arithmetic):
Andrei Popescu402d9372010-02-26 13:31:12 +000010336 // h = (low ^ high); h ^= h >> 16; h ^= h >> 8; h = h & (cacheSize - 1);
10337 __ mov(ecx, ebx);
10338 __ xor_(ecx, Operand(edx));
10339 __ mov(eax, ecx);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010010340 __ sar(eax, 16);
Andrei Popescu402d9372010-02-26 13:31:12 +000010341 __ xor_(ecx, Operand(eax));
10342 __ mov(eax, ecx);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010010343 __ sar(eax, 8);
Andrei Popescu402d9372010-02-26 13:31:12 +000010344 __ xor_(ecx, Operand(eax));
10345 ASSERT(IsPowerOf2(TranscendentalCache::kCacheSize));
10346 __ and_(Operand(ecx), Immediate(TranscendentalCache::kCacheSize - 1));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010010347
Andrei Popescu402d9372010-02-26 13:31:12 +000010348 // ST[0] == double value.
10349 // ebx = low 32 bits of double value.
10350 // edx = high 32 bits of double value.
10351 // ecx = TranscendentalCache::hash(double value).
10352 __ mov(eax,
10353 Immediate(ExternalReference::transcendental_cache_array_address()));
10354 // Eax points to cache array.
10355 __ mov(eax, Operand(eax, type_ * sizeof(TranscendentalCache::caches_[0])));
10356 // Eax points to the cache for the type type_.
10357 // If NULL, the cache hasn't been initialized yet, so go through runtime.
10358 __ test(eax, Operand(eax));
10359 __ j(zero, &runtime_call_clear_stack);
10360#ifdef DEBUG
10361 // Check that the layout of cache elements match expectations.
Steve Block6ded16b2010-05-10 14:33:55 +010010362 { TranscendentalCache::Element test_elem[2];
Andrei Popescu402d9372010-02-26 13:31:12 +000010363 char* elem_start = reinterpret_cast<char*>(&test_elem[0]);
10364 char* elem2_start = reinterpret_cast<char*>(&test_elem[1]);
10365 char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0]));
10366 char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1]));
10367 char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output));
10368 CHECK_EQ(12, elem2_start - elem_start); // Two uint_32's and a pointer.
10369 CHECK_EQ(0, elem_in0 - elem_start);
10370 CHECK_EQ(kIntSize, elem_in1 - elem_start);
10371 CHECK_EQ(2 * kIntSize, elem_out - elem_start);
10372 }
10373#endif
10374 // Find the address of the ecx'th entry in the cache, i.e., &eax[ecx*12].
10375 __ lea(ecx, Operand(ecx, ecx, times_2, 0));
10376 __ lea(ecx, Operand(eax, ecx, times_4, 0));
10377 // Check if cache matches: Double value is stored in uint32_t[2] array.
10378 Label cache_miss;
10379 __ cmp(ebx, Operand(ecx, 0));
10380 __ j(not_equal, &cache_miss);
10381 __ cmp(edx, Operand(ecx, kIntSize));
10382 __ j(not_equal, &cache_miss);
10383 // Cache hit!
10384 __ mov(eax, Operand(ecx, 2 * kIntSize));
10385 __ fstp(0);
10386 __ ret(kPointerSize);
10387
10388 __ bind(&cache_miss);
10389 // Update cache with new value.
10390 // We are short on registers, so use no_reg as scratch.
10391 // This gives slightly larger code.
10392 __ AllocateHeapNumber(eax, edi, no_reg, &runtime_call_clear_stack);
10393 GenerateOperation(masm);
10394 __ mov(Operand(ecx, 0), ebx);
10395 __ mov(Operand(ecx, kIntSize), edx);
10396 __ mov(Operand(ecx, 2 * kIntSize), eax);
10397 __ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
10398 __ ret(kPointerSize);
10399
10400 __ bind(&runtime_call_clear_stack);
10401 __ fstp(0);
10402 __ bind(&runtime_call);
Steve Block6ded16b2010-05-10 14:33:55 +010010403 __ TailCallExternalReference(ExternalReference(RuntimeFunction()), 1, 1);
Andrei Popescu402d9372010-02-26 13:31:12 +000010404}
10405
10406
10407Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() {
10408 switch (type_) {
10409 // Add more cases when necessary.
10410 case TranscendentalCache::SIN: return Runtime::kMath_sin;
10411 case TranscendentalCache::COS: return Runtime::kMath_cos;
10412 default:
10413 UNIMPLEMENTED();
10414 return Runtime::kAbort;
10415 }
10416}
10417
10418
10419void TranscendentalCacheStub::GenerateOperation(MacroAssembler* masm) {
10420 // Only free register is edi.
10421 Label done;
10422 ASSERT(type_ == TranscendentalCache::SIN ||
10423 type_ == TranscendentalCache::COS);
10424 // More transcendental types can be added later.
10425
10426 // Both fsin and fcos require arguments in the range +/-2^63 and
10427 // return NaN for infinities and NaN. They can share all code except
10428 // the actual fsin/fcos operation.
10429 Label in_range;
10430 // If argument is outside the range -2^63..2^63, fsin/cos doesn't
10431 // work. We must reduce it to the appropriate range.
10432 __ mov(edi, edx);
10433 __ and_(Operand(edi), Immediate(0x7ff00000)); // Exponent only.
10434 int supported_exponent_limit =
10435 (63 + HeapNumber::kExponentBias) << HeapNumber::kExponentShift;
10436 __ cmp(Operand(edi), Immediate(supported_exponent_limit));
10437 __ j(below, &in_range, taken);
10438 // Check for infinity and NaN. Both return NaN for sin.
10439 __ cmp(Operand(edi), Immediate(0x7ff00000));
10440 Label non_nan_result;
10441 __ j(not_equal, &non_nan_result, taken);
10442 // Input is +/-Infinity or NaN. Result is NaN.
10443 __ fstp(0);
10444 // NaN is represented by 0x7ff8000000000000.
10445 __ push(Immediate(0x7ff80000));
10446 __ push(Immediate(0));
10447 __ fld_d(Operand(esp, 0));
10448 __ add(Operand(esp), Immediate(2 * kPointerSize));
10449 __ jmp(&done);
10450
10451 __ bind(&non_nan_result);
10452
10453 // Use fpmod to restrict argument to the range +/-2*PI.
10454 __ mov(edi, eax); // Save eax before using fnstsw_ax.
10455 __ fldpi();
10456 __ fadd(0);
10457 __ fld(1);
10458 // FPU Stack: input, 2*pi, input.
10459 {
10460 Label no_exceptions;
10461 __ fwait();
10462 __ fnstsw_ax();
10463 // Clear if Illegal Operand or Zero Division exceptions are set.
10464 __ test(Operand(eax), Immediate(5));
10465 __ j(zero, &no_exceptions);
10466 __ fnclex();
10467 __ bind(&no_exceptions);
10468 }
10469
10470 // Compute st(0) % st(1)
10471 {
10472 Label partial_remainder_loop;
10473 __ bind(&partial_remainder_loop);
10474 __ fprem1();
10475 __ fwait();
10476 __ fnstsw_ax();
10477 __ test(Operand(eax), Immediate(0x400 /* C2 */));
10478 // If C2 is set, computation only has partial result. Loop to
10479 // continue computation.
10480 __ j(not_zero, &partial_remainder_loop);
10481 }
10482 // FPU Stack: input, 2*pi, input % 2*pi
10483 __ fstp(2);
10484 __ fstp(0);
10485 __ mov(eax, edi); // Restore eax (allocated HeapNumber pointer).
10486
10487 // FPU Stack: input % 2*pi
10488 __ bind(&in_range);
10489 switch (type_) {
10490 case TranscendentalCache::SIN:
10491 __ fsin();
10492 break;
10493 case TranscendentalCache::COS:
10494 __ fcos();
10495 break;
10496 default:
10497 UNREACHABLE();
10498 }
10499 __ bind(&done);
10500}
10501
10502
Leon Clarkee46be812010-01-19 14:06:41 +000010503// Get the integer part of a heap number. Surprisingly, all this bit twiddling
10504// is faster than using the built-in instructions on floating point registers.
10505// Trashes edi and ebx. Dest is ecx. Source cannot be ecx or one of the
10506// trashed registers.
10507void IntegerConvert(MacroAssembler* masm,
10508 Register source,
Steve Block6ded16b2010-05-10 14:33:55 +010010509 TypeInfo type_info,
Leon Clarkee46be812010-01-19 14:06:41 +000010510 bool use_sse3,
10511 Label* conversion_failure) {
Leon Clarked91b9f72010-01-27 17:25:45 +000010512 ASSERT(!source.is(ecx) && !source.is(edi) && !source.is(ebx));
Leon Clarkee46be812010-01-19 14:06:41 +000010513 Label done, right_exponent, normal_exponent;
10514 Register scratch = ebx;
10515 Register scratch2 = edi;
Kristian Monsen25f61362010-05-21 11:50:48 +010010516 if (type_info.IsInteger32() && CpuFeatures::IsEnabled(SSE2)) {
10517 CpuFeatures::Scope scope(SSE2);
10518 __ cvttsd2si(ecx, FieldOperand(source, HeapNumber::kValueOffset));
10519 return;
10520 }
Steve Block6ded16b2010-05-10 14:33:55 +010010521 if (!type_info.IsInteger32() || !use_sse3) {
10522 // Get exponent word.
10523 __ mov(scratch, FieldOperand(source, HeapNumber::kExponentOffset));
10524 // Get exponent alone in scratch2.
10525 __ mov(scratch2, scratch);
10526 __ and_(scratch2, HeapNumber::kExponentMask);
10527 }
Leon Clarkee46be812010-01-19 14:06:41 +000010528 if (use_sse3) {
10529 CpuFeatures::Scope scope(SSE3);
Steve Block6ded16b2010-05-10 14:33:55 +010010530 if (!type_info.IsInteger32()) {
10531 // Check whether the exponent is too big for a 64 bit signed integer.
10532 static const uint32_t kTooBigExponent =
10533 (HeapNumber::kExponentBias + 63) << HeapNumber::kExponentShift;
10534 __ cmp(Operand(scratch2), Immediate(kTooBigExponent));
10535 __ j(greater_equal, conversion_failure);
10536 }
Leon Clarkee46be812010-01-19 14:06:41 +000010537 // Load x87 register with heap number.
10538 __ fld_d(FieldOperand(source, HeapNumber::kValueOffset));
10539 // Reserve space for 64 bit answer.
10540 __ sub(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
10541 // Do conversion, which cannot fail because we checked the exponent.
10542 __ fisttp_d(Operand(esp, 0));
10543 __ mov(ecx, Operand(esp, 0)); // Load low word of answer into ecx.
10544 __ add(Operand(esp), Immediate(sizeof(uint64_t))); // Nolint.
10545 } else {
10546 // Load ecx with zero. We use this either for the final shift or
10547 // for the answer.
10548 __ xor_(ecx, Operand(ecx));
10549 // Check whether the exponent matches a 32 bit signed int that cannot be
10550 // represented by a Smi. A non-smi 32 bit integer is 1.xxx * 2^30 so the
10551 // exponent is 30 (biased). This is the exponent that we are fastest at and
10552 // also the highest exponent we can handle here.
10553 const uint32_t non_smi_exponent =
10554 (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
10555 __ cmp(Operand(scratch2), Immediate(non_smi_exponent));
10556 // If we have a match of the int32-but-not-Smi exponent then skip some
10557 // logic.
10558 __ j(equal, &right_exponent);
10559 // If the exponent is higher than that then go to slow case. This catches
10560 // numbers that don't fit in a signed int32, infinities and NaNs.
10561 __ j(less, &normal_exponent);
10562
10563 {
10564 // Handle a big exponent. The only reason we have this code is that the
10565 // >>> operator has a tendency to generate numbers with an exponent of 31.
10566 const uint32_t big_non_smi_exponent =
10567 (HeapNumber::kExponentBias + 31) << HeapNumber::kExponentShift;
10568 __ cmp(Operand(scratch2), Immediate(big_non_smi_exponent));
10569 __ j(not_equal, conversion_failure);
10570 // We have the big exponent, typically from >>>. This means the number is
10571 // in the range 2^31 to 2^32 - 1. Get the top bits of the mantissa.
10572 __ mov(scratch2, scratch);
10573 __ and_(scratch2, HeapNumber::kMantissaMask);
10574 // Put back the implicit 1.
10575 __ or_(scratch2, 1 << HeapNumber::kExponentShift);
10576 // Shift up the mantissa bits to take up the space the exponent used to
10577 // take. We just orred in the implicit bit so that took care of one and
10578 // we want to use the full unsigned range so we subtract 1 bit from the
10579 // shift distance.
10580 const int big_shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 1;
10581 __ shl(scratch2, big_shift_distance);
10582 // Get the second half of the double.
10583 __ mov(ecx, FieldOperand(source, HeapNumber::kMantissaOffset));
10584 // Shift down 21 bits to get the most significant 11 bits or the low
10585 // mantissa word.
10586 __ shr(ecx, 32 - big_shift_distance);
10587 __ or_(ecx, Operand(scratch2));
10588 // We have the answer in ecx, but we may need to negate it.
10589 __ test(scratch, Operand(scratch));
10590 __ j(positive, &done);
10591 __ neg(ecx);
10592 __ jmp(&done);
10593 }
10594
10595 __ bind(&normal_exponent);
10596 // Exponent word in scratch, exponent part of exponent word in scratch2.
10597 // Zero in ecx.
10598 // We know the exponent is smaller than 30 (biased). If it is less than
10599 // 0 (biased) then the number is smaller in magnitude than 1.0 * 2^0, ie
10600 // it rounds to zero.
10601 const uint32_t zero_exponent =
10602 (HeapNumber::kExponentBias + 0) << HeapNumber::kExponentShift;
10603 __ sub(Operand(scratch2), Immediate(zero_exponent));
10604 // ecx already has a Smi zero.
10605 __ j(less, &done);
10606
10607 // We have a shifted exponent between 0 and 30 in scratch2.
10608 __ shr(scratch2, HeapNumber::kExponentShift);
10609 __ mov(ecx, Immediate(30));
10610 __ sub(ecx, Operand(scratch2));
10611
10612 __ bind(&right_exponent);
10613 // Here ecx is the shift, scratch is the exponent word.
10614 // Get the top bits of the mantissa.
10615 __ and_(scratch, HeapNumber::kMantissaMask);
10616 // Put back the implicit 1.
10617 __ or_(scratch, 1 << HeapNumber::kExponentShift);
10618 // Shift up the mantissa bits to take up the space the exponent used to
10619 // take. We have kExponentShift + 1 significant bits int he low end of the
10620 // word. Shift them to the top bits.
10621 const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
10622 __ shl(scratch, shift_distance);
10623 // Get the second half of the double. For some exponents we don't
10624 // actually need this because the bits get shifted out again, but
10625 // it's probably slower to test than just to do it.
10626 __ mov(scratch2, FieldOperand(source, HeapNumber::kMantissaOffset));
10627 // Shift down 22 bits to get the most significant 10 bits or the low
10628 // mantissa word.
10629 __ shr(scratch2, 32 - shift_distance);
10630 __ or_(scratch2, Operand(scratch));
10631 // Move down according to the exponent.
10632 __ shr_cl(scratch2);
10633 // Now the unsigned answer is in scratch2. We need to move it to ecx and
10634 // we may need to fix the sign.
10635 Label negative;
10636 __ xor_(ecx, Operand(ecx));
10637 __ cmp(ecx, FieldOperand(source, HeapNumber::kExponentOffset));
10638 __ j(greater, &negative);
10639 __ mov(ecx, scratch2);
10640 __ jmp(&done);
10641 __ bind(&negative);
10642 __ sub(ecx, Operand(scratch2));
10643 __ bind(&done);
10644 }
10645}
10646
10647
10648// Input: edx, eax are the left and right objects of a bit op.
10649// Output: eax, ecx are left and right integers for a bit op.
Steve Block6ded16b2010-05-10 14:33:55 +010010650void FloatingPointHelper::LoadNumbersAsIntegers(MacroAssembler* masm,
10651 TypeInfo type_info,
10652 bool use_sse3,
10653 Label* conversion_failure) {
Leon Clarkee46be812010-01-19 14:06:41 +000010654 // Check float operands.
10655 Label arg1_is_object, check_undefined_arg1;
10656 Label arg2_is_object, check_undefined_arg2;
10657 Label load_arg2, done;
10658
Steve Block6ded16b2010-05-10 14:33:55 +010010659 if (!type_info.IsDouble()) {
10660 if (!type_info.IsSmi()) {
10661 __ test(edx, Immediate(kSmiTagMask));
10662 __ j(not_zero, &arg1_is_object);
10663 } else {
10664 if (FLAG_debug_code) __ AbortIfNotSmi(edx);
10665 }
10666 __ SmiUntag(edx);
10667 __ jmp(&load_arg2);
10668 }
10669
10670 __ bind(&arg1_is_object);
10671
10672 // Get the untagged integer version of the edx heap number in ecx.
10673 IntegerConvert(masm, edx, type_info, use_sse3, conversion_failure);
10674 __ mov(edx, ecx);
10675
10676 // Here edx has the untagged integer, eax has a Smi or a heap number.
10677 __ bind(&load_arg2);
10678 if (!type_info.IsDouble()) {
10679 // Test if arg2 is a Smi.
10680 if (!type_info.IsSmi()) {
10681 __ test(eax, Immediate(kSmiTagMask));
10682 __ j(not_zero, &arg2_is_object);
10683 } else {
10684 if (FLAG_debug_code) __ AbortIfNotSmi(eax);
10685 }
10686 __ SmiUntag(eax);
10687 __ mov(ecx, eax);
10688 __ jmp(&done);
10689 }
10690
10691 __ bind(&arg2_is_object);
10692
10693 // Get the untagged integer version of the eax heap number in ecx.
10694 IntegerConvert(masm, eax, type_info, use_sse3, conversion_failure);
10695 __ bind(&done);
10696 __ mov(eax, edx);
10697}
10698
10699
10700// Input: edx, eax are the left and right objects of a bit op.
10701// Output: eax, ecx are left and right integers for a bit op.
10702void FloatingPointHelper::LoadUnknownsAsIntegers(MacroAssembler* masm,
10703 bool use_sse3,
10704 Label* conversion_failure) {
10705 // Check float operands.
10706 Label arg1_is_object, check_undefined_arg1;
10707 Label arg2_is_object, check_undefined_arg2;
10708 Label load_arg2, done;
10709
10710 // Test if arg1 is a Smi.
Leon Clarkee46be812010-01-19 14:06:41 +000010711 __ test(edx, Immediate(kSmiTagMask));
10712 __ j(not_zero, &arg1_is_object);
Steve Block6ded16b2010-05-10 14:33:55 +010010713
Leon Clarkee46be812010-01-19 14:06:41 +000010714 __ SmiUntag(edx);
10715 __ jmp(&load_arg2);
10716
10717 // If the argument is undefined it converts to zero (ECMA-262, section 9.5).
10718 __ bind(&check_undefined_arg1);
10719 __ cmp(edx, Factory::undefined_value());
10720 __ j(not_equal, conversion_failure);
10721 __ mov(edx, Immediate(0));
10722 __ jmp(&load_arg2);
10723
10724 __ bind(&arg1_is_object);
10725 __ mov(ebx, FieldOperand(edx, HeapObject::kMapOffset));
10726 __ cmp(ebx, Factory::heap_number_map());
10727 __ j(not_equal, &check_undefined_arg1);
Steve Block6ded16b2010-05-10 14:33:55 +010010728
Leon Clarkee46be812010-01-19 14:06:41 +000010729 // Get the untagged integer version of the edx heap number in ecx.
Steve Block6ded16b2010-05-10 14:33:55 +010010730 IntegerConvert(masm,
10731 edx,
10732 TypeInfo::Unknown(),
10733 use_sse3,
10734 conversion_failure);
Leon Clarkee46be812010-01-19 14:06:41 +000010735 __ mov(edx, ecx);
10736
10737 // Here edx has the untagged integer, eax has a Smi or a heap number.
10738 __ bind(&load_arg2);
Steve Block6ded16b2010-05-10 14:33:55 +010010739
Leon Clarkee46be812010-01-19 14:06:41 +000010740 // Test if arg2 is a Smi.
10741 __ test(eax, Immediate(kSmiTagMask));
10742 __ j(not_zero, &arg2_is_object);
Steve Block6ded16b2010-05-10 14:33:55 +010010743
Leon Clarkee46be812010-01-19 14:06:41 +000010744 __ SmiUntag(eax);
10745 __ mov(ecx, eax);
10746 __ jmp(&done);
10747
10748 // If the argument is undefined it converts to zero (ECMA-262, section 9.5).
10749 __ bind(&check_undefined_arg2);
10750 __ cmp(eax, Factory::undefined_value());
10751 __ j(not_equal, conversion_failure);
10752 __ mov(ecx, Immediate(0));
10753 __ jmp(&done);
10754
10755 __ bind(&arg2_is_object);
10756 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
10757 __ cmp(ebx, Factory::heap_number_map());
10758 __ j(not_equal, &check_undefined_arg2);
Steve Block6ded16b2010-05-10 14:33:55 +010010759
Leon Clarkee46be812010-01-19 14:06:41 +000010760 // Get the untagged integer version of the eax heap number in ecx.
Steve Block6ded16b2010-05-10 14:33:55 +010010761 IntegerConvert(masm,
10762 eax,
10763 TypeInfo::Unknown(),
10764 use_sse3,
10765 conversion_failure);
Leon Clarkee46be812010-01-19 14:06:41 +000010766 __ bind(&done);
10767 __ mov(eax, edx);
10768}
10769
10770
Steve Block6ded16b2010-05-10 14:33:55 +010010771void FloatingPointHelper::LoadAsIntegers(MacroAssembler* masm,
10772 TypeInfo type_info,
10773 bool use_sse3,
10774 Label* conversion_failure) {
10775 if (type_info.IsNumber()) {
10776 LoadNumbersAsIntegers(masm, type_info, use_sse3, conversion_failure);
10777 } else {
10778 LoadUnknownsAsIntegers(masm, use_sse3, conversion_failure);
10779 }
10780}
10781
10782
Steve Blocka7e24c12009-10-30 11:49:00 +000010783void FloatingPointHelper::LoadFloatOperand(MacroAssembler* masm,
10784 Register number) {
10785 Label load_smi, done;
10786
10787 __ test(number, Immediate(kSmiTagMask));
10788 __ j(zero, &load_smi, not_taken);
10789 __ fld_d(FieldOperand(number, HeapNumber::kValueOffset));
10790 __ jmp(&done);
10791
10792 __ bind(&load_smi);
Leon Clarkee46be812010-01-19 14:06:41 +000010793 __ SmiUntag(number);
Steve Blocka7e24c12009-10-30 11:49:00 +000010794 __ push(number);
10795 __ fild_s(Operand(esp, 0));
10796 __ pop(number);
10797
10798 __ bind(&done);
10799}
10800
10801
Andrei Popescu402d9372010-02-26 13:31:12 +000010802void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm) {
10803 Label load_smi_edx, load_eax, load_smi_eax, done;
10804 // Load operand in edx into xmm0.
10805 __ test(edx, Immediate(kSmiTagMask));
10806 __ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
10807 __ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
10808
10809 __ bind(&load_eax);
10810 // Load operand in eax into xmm1.
10811 __ test(eax, Immediate(kSmiTagMask));
10812 __ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
10813 __ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
10814 __ jmp(&done);
10815
10816 __ bind(&load_smi_edx);
10817 __ SmiUntag(edx); // Untag smi before converting to float.
10818 __ cvtsi2sd(xmm0, Operand(edx));
10819 __ SmiTag(edx); // Retag smi for heap number overwriting test.
10820 __ jmp(&load_eax);
10821
10822 __ bind(&load_smi_eax);
10823 __ SmiUntag(eax); // Untag smi before converting to float.
10824 __ cvtsi2sd(xmm1, Operand(eax));
10825 __ SmiTag(eax); // Retag smi for heap number overwriting test.
10826
10827 __ bind(&done);
10828}
10829
10830
Leon Clarked91b9f72010-01-27 17:25:45 +000010831void FloatingPointHelper::LoadSSE2Operands(MacroAssembler* masm,
Steve Blocka7e24c12009-10-30 11:49:00 +000010832 Label* not_numbers) {
10833 Label load_smi_edx, load_eax, load_smi_eax, load_float_eax, done;
10834 // Load operand in edx into xmm0, or branch to not_numbers.
10835 __ test(edx, Immediate(kSmiTagMask));
10836 __ j(zero, &load_smi_edx, not_taken); // Argument in edx is a smi.
10837 __ cmp(FieldOperand(edx, HeapObject::kMapOffset), Factory::heap_number_map());
10838 __ j(not_equal, not_numbers); // Argument in edx is not a number.
10839 __ movdbl(xmm0, FieldOperand(edx, HeapNumber::kValueOffset));
10840 __ bind(&load_eax);
10841 // Load operand in eax into xmm1, or branch to not_numbers.
10842 __ test(eax, Immediate(kSmiTagMask));
10843 __ j(zero, &load_smi_eax, not_taken); // Argument in eax is a smi.
10844 __ cmp(FieldOperand(eax, HeapObject::kMapOffset), Factory::heap_number_map());
10845 __ j(equal, &load_float_eax);
10846 __ jmp(not_numbers); // Argument in eax is not a number.
10847 __ bind(&load_smi_edx);
Leon Clarkee46be812010-01-19 14:06:41 +000010848 __ SmiUntag(edx); // Untag smi before converting to float.
Steve Blocka7e24c12009-10-30 11:49:00 +000010849 __ cvtsi2sd(xmm0, Operand(edx));
Leon Clarkee46be812010-01-19 14:06:41 +000010850 __ SmiTag(edx); // Retag smi for heap number overwriting test.
Steve Blocka7e24c12009-10-30 11:49:00 +000010851 __ jmp(&load_eax);
10852 __ bind(&load_smi_eax);
Leon Clarkee46be812010-01-19 14:06:41 +000010853 __ SmiUntag(eax); // Untag smi before converting to float.
Steve Blocka7e24c12009-10-30 11:49:00 +000010854 __ cvtsi2sd(xmm1, Operand(eax));
Leon Clarkee46be812010-01-19 14:06:41 +000010855 __ SmiTag(eax); // Retag smi for heap number overwriting test.
Steve Blocka7e24c12009-10-30 11:49:00 +000010856 __ jmp(&done);
10857 __ bind(&load_float_eax);
10858 __ movdbl(xmm1, FieldOperand(eax, HeapNumber::kValueOffset));
10859 __ bind(&done);
10860}
10861
10862
Leon Clarked91b9f72010-01-27 17:25:45 +000010863void FloatingPointHelper::LoadSSE2Smis(MacroAssembler* masm,
10864 Register scratch) {
10865 const Register left = edx;
10866 const Register right = eax;
10867 __ mov(scratch, left);
10868 ASSERT(!scratch.is(right)); // We're about to clobber scratch.
10869 __ SmiUntag(scratch);
10870 __ cvtsi2sd(xmm0, Operand(scratch));
10871
10872 __ mov(scratch, right);
10873 __ SmiUntag(scratch);
10874 __ cvtsi2sd(xmm1, Operand(scratch));
10875}
10876
10877
Steve Blocka7e24c12009-10-30 11:49:00 +000010878void FloatingPointHelper::LoadFloatOperands(MacroAssembler* masm,
Leon Clarked91b9f72010-01-27 17:25:45 +000010879 Register scratch,
10880 ArgLocation arg_location) {
Steve Blocka7e24c12009-10-30 11:49:00 +000010881 Label load_smi_1, load_smi_2, done_load_1, done;
Leon Clarked91b9f72010-01-27 17:25:45 +000010882 if (arg_location == ARGS_IN_REGISTERS) {
10883 __ mov(scratch, edx);
10884 } else {
10885 __ mov(scratch, Operand(esp, 2 * kPointerSize));
10886 }
Steve Blocka7e24c12009-10-30 11:49:00 +000010887 __ test(scratch, Immediate(kSmiTagMask));
10888 __ j(zero, &load_smi_1, not_taken);
10889 __ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
10890 __ bind(&done_load_1);
10891
Leon Clarked91b9f72010-01-27 17:25:45 +000010892 if (arg_location == ARGS_IN_REGISTERS) {
10893 __ mov(scratch, eax);
10894 } else {
10895 __ mov(scratch, Operand(esp, 1 * kPointerSize));
10896 }
Steve Blocka7e24c12009-10-30 11:49:00 +000010897 __ test(scratch, Immediate(kSmiTagMask));
10898 __ j(zero, &load_smi_2, not_taken);
10899 __ fld_d(FieldOperand(scratch, HeapNumber::kValueOffset));
10900 __ jmp(&done);
10901
10902 __ bind(&load_smi_1);
Leon Clarkee46be812010-01-19 14:06:41 +000010903 __ SmiUntag(scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +000010904 __ push(scratch);
10905 __ fild_s(Operand(esp, 0));
10906 __ pop(scratch);
10907 __ jmp(&done_load_1);
10908
10909 __ bind(&load_smi_2);
Leon Clarkee46be812010-01-19 14:06:41 +000010910 __ SmiUntag(scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +000010911 __ push(scratch);
10912 __ fild_s(Operand(esp, 0));
10913 __ pop(scratch);
10914
10915 __ bind(&done);
10916}
10917
10918
Leon Clarked91b9f72010-01-27 17:25:45 +000010919void FloatingPointHelper::LoadFloatSmis(MacroAssembler* masm,
10920 Register scratch) {
10921 const Register left = edx;
10922 const Register right = eax;
10923 __ mov(scratch, left);
10924 ASSERT(!scratch.is(right)); // We're about to clobber scratch.
10925 __ SmiUntag(scratch);
10926 __ push(scratch);
10927 __ fild_s(Operand(esp, 0));
10928
10929 __ mov(scratch, right);
10930 __ SmiUntag(scratch);
10931 __ mov(Operand(esp, 0), scratch);
10932 __ fild_s(Operand(esp, 0));
10933 __ pop(scratch);
10934}
10935
10936
Steve Blocka7e24c12009-10-30 11:49:00 +000010937void FloatingPointHelper::CheckFloatOperands(MacroAssembler* masm,
10938 Label* non_float,
10939 Register scratch) {
10940 Label test_other, done;
10941 // Test if both operands are floats or smi -> scratch=k_is_float;
10942 // Otherwise scratch = k_not_float.
10943 __ test(edx, Immediate(kSmiTagMask));
10944 __ j(zero, &test_other, not_taken); // argument in edx is OK
10945 __ mov(scratch, FieldOperand(edx, HeapObject::kMapOffset));
10946 __ cmp(scratch, Factory::heap_number_map());
10947 __ j(not_equal, non_float); // argument in edx is not a number -> NaN
10948
10949 __ bind(&test_other);
10950 __ test(eax, Immediate(kSmiTagMask));
10951 __ j(zero, &done); // argument in eax is OK
10952 __ mov(scratch, FieldOperand(eax, HeapObject::kMapOffset));
10953 __ cmp(scratch, Factory::heap_number_map());
10954 __ j(not_equal, non_float); // argument in eax is not a number -> NaN
10955
10956 // Fall-through: Both operands are numbers.
10957 __ bind(&done);
10958}
10959
10960
Leon Clarkee46be812010-01-19 14:06:41 +000010961void GenericUnaryOpStub::Generate(MacroAssembler* masm) {
10962 Label slow, done;
Steve Blocka7e24c12009-10-30 11:49:00 +000010963
Leon Clarkee46be812010-01-19 14:06:41 +000010964 if (op_ == Token::SUB) {
10965 // Check whether the value is a smi.
10966 Label try_float;
10967 __ test(eax, Immediate(kSmiTagMask));
10968 __ j(not_zero, &try_float, not_taken);
Steve Blocka7e24c12009-10-30 11:49:00 +000010969
Leon Clarkeac952652010-07-15 11:15:24 +010010970 if (negative_zero_ == kStrictNegativeZero) {
10971 // Go slow case if the value of the expression is zero
10972 // to make sure that we switch between 0 and -0.
10973 __ test(eax, Operand(eax));
10974 __ j(zero, &slow, not_taken);
10975 }
Steve Blocka7e24c12009-10-30 11:49:00 +000010976
Leon Clarkee46be812010-01-19 14:06:41 +000010977 // The value of the expression is a smi that is not zero. Try
10978 // optimistic subtraction '0 - value'.
10979 Label undo;
Steve Blocka7e24c12009-10-30 11:49:00 +000010980 __ mov(edx, Operand(eax));
Leon Clarkee46be812010-01-19 14:06:41 +000010981 __ Set(eax, Immediate(0));
10982 __ sub(eax, Operand(edx));
Leon Clarkeac952652010-07-15 11:15:24 +010010983 __ j(no_overflow, &done, taken);
Leon Clarkee46be812010-01-19 14:06:41 +000010984
10985 // Restore eax and go slow case.
10986 __ bind(&undo);
10987 __ mov(eax, Operand(edx));
10988 __ jmp(&slow);
10989
10990 // Try floating point case.
10991 __ bind(&try_float);
10992 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
10993 __ cmp(edx, Factory::heap_number_map());
10994 __ j(not_equal, &slow);
Leon Clarkeac952652010-07-15 11:15:24 +010010995 if (overwrite_ == UNARY_OVERWRITE) {
Leon Clarkee46be812010-01-19 14:06:41 +000010996 __ mov(edx, FieldOperand(eax, HeapNumber::kExponentOffset));
10997 __ xor_(edx, HeapNumber::kSignMask); // Flip sign.
10998 __ mov(FieldOperand(eax, HeapNumber::kExponentOffset), edx);
10999 } else {
11000 __ mov(edx, Operand(eax));
11001 // edx: operand
11002 __ AllocateHeapNumber(eax, ebx, ecx, &undo);
11003 // eax: allocated 'empty' number
11004 __ mov(ecx, FieldOperand(edx, HeapNumber::kExponentOffset));
11005 __ xor_(ecx, HeapNumber::kSignMask); // Flip sign.
11006 __ mov(FieldOperand(eax, HeapNumber::kExponentOffset), ecx);
11007 __ mov(ecx, FieldOperand(edx, HeapNumber::kMantissaOffset));
11008 __ mov(FieldOperand(eax, HeapNumber::kMantissaOffset), ecx);
11009 }
11010 } else if (op_ == Token::BIT_NOT) {
11011 // Check if the operand is a heap number.
11012 __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
11013 __ cmp(edx, Factory::heap_number_map());
11014 __ j(not_equal, &slow, not_taken);
11015
11016 // Convert the heap number in eax to an untagged integer in ecx.
Steve Block6ded16b2010-05-10 14:33:55 +010011017 IntegerConvert(masm,
11018 eax,
11019 TypeInfo::Unknown(),
11020 CpuFeatures::IsSupported(SSE3),
11021 &slow);
Leon Clarkee46be812010-01-19 14:06:41 +000011022
11023 // Do the bitwise operation and check if the result fits in a smi.
11024 Label try_float;
11025 __ not_(ecx);
11026 __ cmp(ecx, 0xc0000000);
11027 __ j(sign, &try_float, not_taken);
11028
11029 // Tag the result as a smi and we're done.
11030 ASSERT(kSmiTagSize == 1);
11031 __ lea(eax, Operand(ecx, times_2, kSmiTag));
11032 __ jmp(&done);
11033
11034 // Try to store the result in a heap number.
11035 __ bind(&try_float);
Leon Clarkeac952652010-07-15 11:15:24 +010011036 if (overwrite_ == UNARY_NO_OVERWRITE) {
Leon Clarkee46be812010-01-19 14:06:41 +000011037 // Allocate a fresh heap number, but don't overwrite eax until
11038 // we're sure we can do it without going through the slow case
11039 // that needs the value in eax.
11040 __ AllocateHeapNumber(ebx, edx, edi, &slow);
11041 __ mov(eax, Operand(ebx));
11042 }
11043 if (CpuFeatures::IsSupported(SSE2)) {
11044 CpuFeatures::Scope use_sse2(SSE2);
11045 __ cvtsi2sd(xmm0, Operand(ecx));
11046 __ movdbl(FieldOperand(eax, HeapNumber::kValueOffset), xmm0);
11047 } else {
11048 __ push(ecx);
11049 __ fild_s(Operand(esp, 0));
11050 __ pop(ecx);
11051 __ fstp_d(FieldOperand(eax, HeapNumber::kValueOffset));
11052 }
11053 } else {
11054 UNIMPLEMENTED();
Steve Blocka7e24c12009-10-30 11:49:00 +000011055 }
11056
Leon Clarkee46be812010-01-19 14:06:41 +000011057 // Return from the stub.
Steve Blocka7e24c12009-10-30 11:49:00 +000011058 __ bind(&done);
Steve Blocka7e24c12009-10-30 11:49:00 +000011059 __ StubReturn(1);
Leon Clarkee46be812010-01-19 14:06:41 +000011060
11061 // Handle the slow case by jumping to the JavaScript builtin.
11062 __ bind(&slow);
11063 __ pop(ecx); // pop return address.
11064 __ push(eax);
11065 __ push(ecx); // push return address
11066 switch (op_) {
11067 case Token::SUB:
11068 __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION);
11069 break;
11070 case Token::BIT_NOT:
11071 __ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION);
11072 break;
11073 default:
11074 UNREACHABLE();
11075 }
Steve Blocka7e24c12009-10-30 11:49:00 +000011076}
11077
11078
Steve Blocka7e24c12009-10-30 11:49:00 +000011079void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
11080 // The key is in edx and the parameter count is in eax.
11081
11082 // The displacement is used for skipping the frame pointer on the
11083 // stack. It is the offset of the last parameter (if any) relative
11084 // to the frame pointer.
11085 static const int kDisplacement = 1 * kPointerSize;
11086
11087 // Check that the key is a smi.
11088 Label slow;
11089 __ test(edx, Immediate(kSmiTagMask));
11090 __ j(not_zero, &slow, not_taken);
11091
11092 // Check if the calling frame is an arguments adaptor frame.
11093 Label adaptor;
11094 __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
11095 __ mov(ecx, Operand(ebx, StandardFrameConstants::kContextOffset));
11096 __ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
11097 __ j(equal, &adaptor);
11098
11099 // Check index against formal parameters count limit passed in
11100 // through register eax. Use unsigned comparison to get negative
11101 // check for free.
11102 __ cmp(edx, Operand(eax));
11103 __ j(above_equal, &slow, not_taken);
11104
11105 // Read the argument from the stack and return it.
11106 ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
11107 __ lea(ebx, Operand(ebp, eax, times_2, 0));
11108 __ neg(edx);
11109 __ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
11110 __ ret(0);
11111
11112 // Arguments adaptor case: Check index against actual arguments
11113 // limit found in the arguments adaptor frame. Use unsigned
11114 // comparison to get negative check for free.
11115 __ bind(&adaptor);
11116 __ mov(ecx, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));
11117 __ cmp(edx, Operand(ecx));
11118 __ j(above_equal, &slow, not_taken);
11119
11120 // Read the argument from the stack and return it.
11121 ASSERT(kSmiTagSize == 1 && kSmiTag == 0); // shifting code depends on this
11122 __ lea(ebx, Operand(ebx, ecx, times_2, 0));
11123 __ neg(edx);
11124 __ mov(eax, Operand(ebx, edx, times_2, kDisplacement));
11125 __ ret(0);
11126
11127 // Slow-case: Handle non-smi or out-of-bounds access to arguments
11128 // by calling the runtime system.
11129 __ bind(&slow);
11130 __ pop(ebx); // Return address.
11131 __ push(edx);
11132 __ push(ebx);
Steve Block6ded16b2010-05-10 14:33:55 +010011133 __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +000011134}
11135
11136
11137void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
Andrei Popescu402d9372010-02-26 13:31:12 +000011138 // esp[0] : return address
11139 // esp[4] : number of parameters
11140 // esp[8] : receiver displacement
11141 // esp[16] : function
11142
Steve Blocka7e24c12009-10-30 11:49:00 +000011143 // The displacement is used for skipping the return address and the
11144 // frame pointer on the stack. It is the offset of the last
11145 // parameter (if any) relative to the frame pointer.
11146 static const int kDisplacement = 2 * kPointerSize;
11147
11148 // Check if the calling frame is an arguments adaptor frame.
Leon Clarkee46be812010-01-19 14:06:41 +000011149 Label adaptor_frame, try_allocate, runtime;
Steve Blocka7e24c12009-10-30 11:49:00 +000011150 __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
11151 __ mov(ecx, Operand(edx, StandardFrameConstants::kContextOffset));
11152 __ cmp(Operand(ecx), Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
Leon Clarkee46be812010-01-19 14:06:41 +000011153 __ j(equal, &adaptor_frame);
11154
11155 // Get the length from the frame.
11156 __ mov(ecx, Operand(esp, 1 * kPointerSize));
11157 __ jmp(&try_allocate);
Steve Blocka7e24c12009-10-30 11:49:00 +000011158
11159 // Patch the arguments.length and the parameters pointer.
Leon Clarkee46be812010-01-19 14:06:41 +000011160 __ bind(&adaptor_frame);
Steve Blocka7e24c12009-10-30 11:49:00 +000011161 __ mov(ecx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
11162 __ mov(Operand(esp, 1 * kPointerSize), ecx);
11163 __ lea(edx, Operand(edx, ecx, times_2, kDisplacement));
11164 __ mov(Operand(esp, 2 * kPointerSize), edx);
11165
Leon Clarkee46be812010-01-19 14:06:41 +000011166 // Try the new space allocation. Start out with computing the size of
11167 // the arguments object and the elements array.
11168 Label add_arguments_object;
11169 __ bind(&try_allocate);
11170 __ test(ecx, Operand(ecx));
11171 __ j(zero, &add_arguments_object);
11172 __ lea(ecx, Operand(ecx, times_2, FixedArray::kHeaderSize));
11173 __ bind(&add_arguments_object);
11174 __ add(Operand(ecx), Immediate(Heap::kArgumentsObjectSize));
11175
11176 // Do the allocation of both objects in one go.
11177 __ AllocateInNewSpace(ecx, eax, edx, ebx, &runtime, TAG_OBJECT);
11178
11179 // Get the arguments boilerplate from the current (global) context.
11180 int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
11181 __ mov(edi, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
11182 __ mov(edi, FieldOperand(edi, GlobalObject::kGlobalContextOffset));
11183 __ mov(edi, Operand(edi, offset));
11184
11185 // Copy the JS object part.
11186 for (int i = 0; i < JSObject::kHeaderSize; i += kPointerSize) {
11187 __ mov(ebx, FieldOperand(edi, i));
11188 __ mov(FieldOperand(eax, i), ebx);
11189 }
11190
11191 // Setup the callee in-object property.
11192 ASSERT(Heap::arguments_callee_index == 0);
11193 __ mov(ebx, Operand(esp, 3 * kPointerSize));
11194 __ mov(FieldOperand(eax, JSObject::kHeaderSize), ebx);
11195
11196 // Get the length (smi tagged) and set that as an in-object property too.
11197 ASSERT(Heap::arguments_length_index == 1);
11198 __ mov(ecx, Operand(esp, 1 * kPointerSize));
11199 __ mov(FieldOperand(eax, JSObject::kHeaderSize + kPointerSize), ecx);
11200
11201 // If there are no actual arguments, we're done.
11202 Label done;
11203 __ test(ecx, Operand(ecx));
11204 __ j(zero, &done);
11205
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010011206 // Get the parameters pointer from the stack.
Leon Clarkee46be812010-01-19 14:06:41 +000011207 __ mov(edx, Operand(esp, 2 * kPointerSize));
Leon Clarkee46be812010-01-19 14:06:41 +000011208
11209 // Setup the elements pointer in the allocated arguments object and
11210 // initialize the header in the elements fixed array.
11211 __ lea(edi, Operand(eax, Heap::kArgumentsObjectSize));
11212 __ mov(FieldOperand(eax, JSObject::kElementsOffset), edi);
11213 __ mov(FieldOperand(edi, FixedArray::kMapOffset),
11214 Immediate(Factory::fixed_array_map()));
11215 __ mov(FieldOperand(edi, FixedArray::kLengthOffset), ecx);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010011216 // Untag the length for the loop below.
11217 __ SmiUntag(ecx);
Leon Clarkee46be812010-01-19 14:06:41 +000011218
11219 // Copy the fixed array slots.
11220 Label loop;
11221 __ bind(&loop);
11222 __ mov(ebx, Operand(edx, -1 * kPointerSize)); // Skip receiver.
11223 __ mov(FieldOperand(edi, FixedArray::kHeaderSize), ebx);
11224 __ add(Operand(edi), Immediate(kPointerSize));
11225 __ sub(Operand(edx), Immediate(kPointerSize));
11226 __ dec(ecx);
Leon Clarkee46be812010-01-19 14:06:41 +000011227 __ j(not_zero, &loop);
11228
11229 // Return and remove the on-stack parameters.
11230 __ bind(&done);
11231 __ ret(3 * kPointerSize);
11232
Steve Blocka7e24c12009-10-30 11:49:00 +000011233 // Do the runtime call to allocate the arguments object.
11234 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +010011235 __ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +000011236}
11237
11238
Leon Clarkee46be812010-01-19 14:06:41 +000011239void RegExpExecStub::Generate(MacroAssembler* masm) {
Leon Clarke4515c472010-02-03 11:58:03 +000011240 // Just jump directly to runtime if native RegExp is not selected at compile
11241 // time or if regexp entry in generated code is turned off runtime switch or
11242 // at compilation.
Steve Block6ded16b2010-05-10 14:33:55 +010011243#ifdef V8_INTERPRETED_REGEXP
11244 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
11245#else // V8_INTERPRETED_REGEXP
Leon Clarkee46be812010-01-19 14:06:41 +000011246 if (!FLAG_regexp_entry_native) {
Steve Block6ded16b2010-05-10 14:33:55 +010011247 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
Leon Clarkee46be812010-01-19 14:06:41 +000011248 return;
11249 }
11250
11251 // Stack frame on entry.
11252 // esp[0]: return address
11253 // esp[4]: last_match_info (expected JSArray)
11254 // esp[8]: previous index
11255 // esp[12]: subject string
11256 // esp[16]: JSRegExp object
11257
Leon Clarked91b9f72010-01-27 17:25:45 +000011258 static const int kLastMatchInfoOffset = 1 * kPointerSize;
11259 static const int kPreviousIndexOffset = 2 * kPointerSize;
11260 static const int kSubjectOffset = 3 * kPointerSize;
11261 static const int kJSRegExpOffset = 4 * kPointerSize;
11262
11263 Label runtime, invoke_regexp;
11264
11265 // Ensure that a RegExp stack is allocated.
11266 ExternalReference address_of_regexp_stack_memory_address =
11267 ExternalReference::address_of_regexp_stack_memory_address();
11268 ExternalReference address_of_regexp_stack_memory_size =
11269 ExternalReference::address_of_regexp_stack_memory_size();
11270 __ mov(ebx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
11271 __ test(ebx, Operand(ebx));
11272 __ j(zero, &runtime, not_taken);
Leon Clarkee46be812010-01-19 14:06:41 +000011273
11274 // Check that the first argument is a JSRegExp object.
Leon Clarked91b9f72010-01-27 17:25:45 +000011275 __ mov(eax, Operand(esp, kJSRegExpOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011276 ASSERT_EQ(0, kSmiTag);
11277 __ test(eax, Immediate(kSmiTagMask));
11278 __ j(zero, &runtime);
11279 __ CmpObjectType(eax, JS_REGEXP_TYPE, ecx);
11280 __ j(not_equal, &runtime);
11281 // Check that the RegExp has been compiled (data contains a fixed array).
11282 __ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
Leon Clarke4515c472010-02-03 11:58:03 +000011283 if (FLAG_debug_code) {
11284 __ test(ecx, Immediate(kSmiTagMask));
11285 __ Check(not_zero, "Unexpected type for RegExp data, FixedArray expected");
11286 __ CmpObjectType(ecx, FIXED_ARRAY_TYPE, ebx);
11287 __ Check(equal, "Unexpected type for RegExp data, FixedArray expected");
11288 }
Leon Clarkee46be812010-01-19 14:06:41 +000011289
11290 // ecx: RegExp data (FixedArray)
11291 // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
11292 __ mov(ebx, FieldOperand(ecx, JSRegExp::kDataTagOffset));
11293 __ cmp(Operand(ebx), Immediate(Smi::FromInt(JSRegExp::IRREGEXP)));
11294 __ j(not_equal, &runtime);
11295
11296 // ecx: RegExp data (FixedArray)
11297 // Check that the number of captures fit in the static offsets vector buffer.
11298 __ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
11299 // Calculate number of capture registers (number_of_captures + 1) * 2. This
11300 // uses the asumption that smis are 2 * their untagged value.
11301 ASSERT_EQ(0, kSmiTag);
11302 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
11303 __ add(Operand(edx), Immediate(2)); // edx was a smi.
11304 // Check that the static offsets vector buffer is large enough.
11305 __ cmp(edx, OffsetsVector::kStaticOffsetsVectorSize);
11306 __ j(above, &runtime);
11307
11308 // ecx: RegExp data (FixedArray)
11309 // edx: Number of capture registers
11310 // Check that the second argument is a string.
Leon Clarked91b9f72010-01-27 17:25:45 +000011311 __ mov(eax, Operand(esp, kSubjectOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011312 __ test(eax, Immediate(kSmiTagMask));
11313 __ j(zero, &runtime);
11314 Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
11315 __ j(NegateCondition(is_string), &runtime);
11316 // Get the length of the string to ebx.
11317 __ mov(ebx, FieldOperand(eax, String::kLengthOffset));
11318
Steve Block6ded16b2010-05-10 14:33:55 +010011319 // ebx: Length of subject string as a smi
Leon Clarkee46be812010-01-19 14:06:41 +000011320 // ecx: RegExp data (FixedArray)
11321 // edx: Number of capture registers
Leon Clarke4515c472010-02-03 11:58:03 +000011322 // Check that the third argument is a positive smi less than the subject
Steve Block6ded16b2010-05-10 14:33:55 +010011323 // string length. A negative value will be greater (unsigned comparison).
Leon Clarked91b9f72010-01-27 17:25:45 +000011324 __ mov(eax, Operand(esp, kPreviousIndexOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010011325 __ test(eax, Immediate(kSmiTagMask));
Kristian Monsen25f61362010-05-21 11:50:48 +010011326 __ j(not_zero, &runtime);
Leon Clarkee46be812010-01-19 14:06:41 +000011327 __ cmp(eax, Operand(ebx));
Steve Block6ded16b2010-05-10 14:33:55 +010011328 __ j(above_equal, &runtime);
Leon Clarkee46be812010-01-19 14:06:41 +000011329
11330 // ecx: RegExp data (FixedArray)
11331 // edx: Number of capture registers
11332 // Check that the fourth object is a JSArray object.
Leon Clarked91b9f72010-01-27 17:25:45 +000011333 __ mov(eax, Operand(esp, kLastMatchInfoOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011334 __ test(eax, Immediate(kSmiTagMask));
11335 __ j(zero, &runtime);
11336 __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
11337 __ j(not_equal, &runtime);
11338 // Check that the JSArray is in fast case.
11339 __ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
11340 __ mov(eax, FieldOperand(ebx, HeapObject::kMapOffset));
11341 __ cmp(eax, Factory::fixed_array_map());
11342 __ j(not_equal, &runtime);
11343 // Check that the last match info has space for the capture registers and the
11344 // additional information.
11345 __ mov(eax, FieldOperand(ebx, FixedArray::kLengthOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010011346 __ SmiUntag(eax);
Leon Clarkee46be812010-01-19 14:06:41 +000011347 __ add(Operand(edx), Immediate(RegExpImpl::kLastMatchOverhead));
11348 __ cmp(edx, Operand(eax));
11349 __ j(greater, &runtime);
11350
11351 // ecx: RegExp data (FixedArray)
Leon Clarked91b9f72010-01-27 17:25:45 +000011352 // Check the representation and encoding of the subject string.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011353 Label seq_ascii_string, seq_two_byte_string, check_code;
Leon Clarked91b9f72010-01-27 17:25:45 +000011354 __ mov(eax, Operand(esp, kSubjectOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011355 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
11356 __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011357 // First check for flat two byte string.
11358 __ and_(ebx,
11359 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask);
11360 ASSERT_EQ(0, kStringTag | kSeqStringTag | kTwoByteStringTag);
11361 __ j(zero, &seq_two_byte_string);
11362 // Any other flat string must be a flat ascii string.
Leon Clarked91b9f72010-01-27 17:25:45 +000011363 __ test(Operand(ebx),
11364 Immediate(kIsNotStringMask | kStringRepresentationMask));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011365 __ j(zero, &seq_ascii_string);
Leon Clarked91b9f72010-01-27 17:25:45 +000011366
11367 // Check for flat cons string.
11368 // A flat cons string is a cons string where the second part is the empty
11369 // string. In that case the subject string is just the first part of the cons
11370 // string. Also in this case the first part of the cons string is known to be
Leon Clarke4515c472010-02-03 11:58:03 +000011371 // a sequential string or an external string.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011372 ASSERT(kExternalStringTag !=0);
11373 ASSERT_EQ(0, kConsStringTag & kExternalStringTag);
11374 __ test(Operand(ebx),
11375 Immediate(kIsNotStringMask | kExternalStringTag));
11376 __ j(not_zero, &runtime);
11377 // String is a cons string.
Leon Clarked91b9f72010-01-27 17:25:45 +000011378 __ mov(edx, FieldOperand(eax, ConsString::kSecondOffset));
Leon Clarke4515c472010-02-03 11:58:03 +000011379 __ cmp(Operand(edx), Factory::empty_string());
Leon Clarked91b9f72010-01-27 17:25:45 +000011380 __ j(not_equal, &runtime);
11381 __ mov(eax, FieldOperand(eax, ConsString::kFirstOffset));
11382 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011383 // String is a cons string with empty second part.
11384 // eax: first part of cons string.
11385 // ebx: map of first part of cons string.
11386 // Is first part a flat two byte string?
11387 __ test_b(FieldOperand(ebx, Map::kInstanceTypeOffset),
11388 kStringRepresentationMask | kStringEncodingMask);
11389 ASSERT_EQ(0, kSeqStringTag | kTwoByteStringTag);
11390 __ j(zero, &seq_two_byte_string);
11391 // Any other flat string must be ascii.
11392 __ test_b(FieldOperand(ebx, Map::kInstanceTypeOffset),
11393 kStringRepresentationMask);
Leon Clarke4515c472010-02-03 11:58:03 +000011394 __ j(not_zero, &runtime);
Leon Clarkee46be812010-01-19 14:06:41 +000011395
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011396 __ bind(&seq_ascii_string);
11397 // eax: subject string (flat ascii)
Leon Clarkee46be812010-01-19 14:06:41 +000011398 // ecx: RegExp data (FixedArray)
Leon Clarkee46be812010-01-19 14:06:41 +000011399 __ mov(edx, FieldOperand(ecx, JSRegExp::kDataAsciiCodeOffset));
Leon Clarked91b9f72010-01-27 17:25:45 +000011400 __ Set(edi, Immediate(1)); // Type is ascii.
11401 __ jmp(&check_code);
11402
11403 __ bind(&seq_two_byte_string);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011404 // eax: subject string (flat two byte)
Leon Clarked91b9f72010-01-27 17:25:45 +000011405 // ecx: RegExp data (FixedArray)
11406 __ mov(edx, FieldOperand(ecx, JSRegExp::kDataUC16CodeOffset));
11407 __ Set(edi, Immediate(0)); // Type is two byte.
11408
11409 __ bind(&check_code);
Leon Clarke4515c472010-02-03 11:58:03 +000011410 // Check that the irregexp code has been generated for the actual string
11411 // encoding. If it has, the field contains a code object otherwise it contains
11412 // the hole.
Leon Clarkee46be812010-01-19 14:06:41 +000011413 __ CmpObjectType(edx, CODE_TYPE, ebx);
11414 __ j(not_equal, &runtime);
11415
Leon Clarked91b9f72010-01-27 17:25:45 +000011416 // eax: subject string
11417 // edx: code
Leon Clarke4515c472010-02-03 11:58:03 +000011418 // edi: encoding of subject string (1 if ascii, 0 if two_byte);
Leon Clarkee46be812010-01-19 14:06:41 +000011419 // Load used arguments before starting to push arguments for call to native
11420 // RegExp code to avoid handling changing stack height.
Leon Clarked91b9f72010-01-27 17:25:45 +000011421 __ mov(ebx, Operand(esp, kPreviousIndexOffset));
Leon Clarked91b9f72010-01-27 17:25:45 +000011422 __ SmiUntag(ebx); // Previous index from smi.
Leon Clarkee46be812010-01-19 14:06:41 +000011423
11424 // eax: subject string
11425 // ebx: previous index
11426 // edx: code
Leon Clarke4515c472010-02-03 11:58:03 +000011427 // edi: encoding of subject string (1 if ascii 0 if two_byte);
Leon Clarkee46be812010-01-19 14:06:41 +000011428 // All checks done. Now push arguments for native regexp code.
11429 __ IncrementCounter(&Counters::regexp_entry_native, 1);
11430
Steve Block6ded16b2010-05-10 14:33:55 +010011431 static const int kRegExpExecuteArguments = 7;
11432 __ PrepareCallCFunction(kRegExpExecuteArguments, ecx);
11433
Leon Clarked91b9f72010-01-27 17:25:45 +000011434 // Argument 7: Indicate that this is a direct call from JavaScript.
Steve Block6ded16b2010-05-10 14:33:55 +010011435 __ mov(Operand(esp, 6 * kPointerSize), Immediate(1));
Leon Clarkee46be812010-01-19 14:06:41 +000011436
Leon Clarked91b9f72010-01-27 17:25:45 +000011437 // Argument 6: Start (high end) of backtracking stack memory area.
Leon Clarkee46be812010-01-19 14:06:41 +000011438 __ mov(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_address));
11439 __ add(ecx, Operand::StaticVariable(address_of_regexp_stack_memory_size));
Steve Block6ded16b2010-05-10 14:33:55 +010011440 __ mov(Operand(esp, 5 * kPointerSize), ecx);
Leon Clarkee46be812010-01-19 14:06:41 +000011441
Leon Clarkee46be812010-01-19 14:06:41 +000011442 // Argument 5: static offsets vector buffer.
Steve Block6ded16b2010-05-10 14:33:55 +010011443 __ mov(Operand(esp, 4 * kPointerSize),
11444 Immediate(ExternalReference::address_of_static_offsets_vector()));
Leon Clarkee46be812010-01-19 14:06:41 +000011445
Leon Clarked91b9f72010-01-27 17:25:45 +000011446 // Argument 4: End of string data
11447 // Argument 3: Start of string data
Steve Block6ded16b2010-05-10 14:33:55 +010011448 Label setup_two_byte, setup_rest;
Leon Clarked91b9f72010-01-27 17:25:45 +000011449 __ test(edi, Operand(edi));
11450 __ mov(edi, FieldOperand(eax, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010011451 __ j(zero, &setup_two_byte);
11452 __ SmiUntag(edi);
Leon Clarked91b9f72010-01-27 17:25:45 +000011453 __ lea(ecx, FieldOperand(eax, edi, times_1, SeqAsciiString::kHeaderSize));
Steve Block6ded16b2010-05-10 14:33:55 +010011454 __ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
Leon Clarked91b9f72010-01-27 17:25:45 +000011455 __ lea(ecx, FieldOperand(eax, ebx, times_1, SeqAsciiString::kHeaderSize));
Steve Block6ded16b2010-05-10 14:33:55 +010011456 __ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
11457 __ jmp(&setup_rest);
Leon Clarkee46be812010-01-19 14:06:41 +000011458
Steve Block6ded16b2010-05-10 14:33:55 +010011459 __ bind(&setup_two_byte);
11460 ASSERT(kSmiTag == 0 && kSmiTagSize == 1); // edi is smi (powered by 2).
11461 __ lea(ecx, FieldOperand(eax, edi, times_1, SeqTwoByteString::kHeaderSize));
11462 __ mov(Operand(esp, 3 * kPointerSize), ecx); // Argument 4.
Leon Clarked91b9f72010-01-27 17:25:45 +000011463 __ lea(ecx, FieldOperand(eax, ebx, times_2, SeqTwoByteString::kHeaderSize));
Steve Block6ded16b2010-05-10 14:33:55 +010011464 __ mov(Operand(esp, 2 * kPointerSize), ecx); // Argument 3.
Leon Clarked91b9f72010-01-27 17:25:45 +000011465
Steve Block6ded16b2010-05-10 14:33:55 +010011466 __ bind(&setup_rest);
Leon Clarkee46be812010-01-19 14:06:41 +000011467
11468 // Argument 2: Previous index.
Steve Block6ded16b2010-05-10 14:33:55 +010011469 __ mov(Operand(esp, 1 * kPointerSize), ebx);
Leon Clarkee46be812010-01-19 14:06:41 +000011470
11471 // Argument 1: Subject string.
Steve Block6ded16b2010-05-10 14:33:55 +010011472 __ mov(Operand(esp, 0 * kPointerSize), eax);
Leon Clarkee46be812010-01-19 14:06:41 +000011473
11474 // Locate the code entry and call it.
11475 __ add(Operand(edx), Immediate(Code::kHeaderSize - kHeapObjectTag));
Steve Block6ded16b2010-05-10 14:33:55 +010011476 __ CallCFunction(edx, kRegExpExecuteArguments);
Leon Clarkee46be812010-01-19 14:06:41 +000011477
11478 // Check the result.
11479 Label success;
11480 __ cmp(eax, NativeRegExpMacroAssembler::SUCCESS);
11481 __ j(equal, &success, taken);
11482 Label failure;
11483 __ cmp(eax, NativeRegExpMacroAssembler::FAILURE);
11484 __ j(equal, &failure, taken);
11485 __ cmp(eax, NativeRegExpMacroAssembler::EXCEPTION);
11486 // If not exception it can only be retry. Handle that in the runtime system.
11487 __ j(not_equal, &runtime);
11488 // Result must now be exception. If there is no pending exception already a
11489 // stack overflow (on the backtrack stack) was detected in RegExp code but
11490 // haven't created the exception yet. Handle that in the runtime system.
Steve Block6ded16b2010-05-10 14:33:55 +010011491 // TODO(592): Rerunning the RegExp to get the stack overflow exception.
Leon Clarkee46be812010-01-19 14:06:41 +000011492 ExternalReference pending_exception(Top::k_pending_exception_address);
11493 __ mov(eax,
11494 Operand::StaticVariable(ExternalReference::the_hole_value_location()));
11495 __ cmp(eax, Operand::StaticVariable(pending_exception));
11496 __ j(equal, &runtime);
11497 __ bind(&failure);
11498 // For failure and exception return null.
11499 __ mov(Operand(eax), Factory::null_value());
11500 __ ret(4 * kPointerSize);
11501
11502 // Load RegExp data.
11503 __ bind(&success);
Leon Clarked91b9f72010-01-27 17:25:45 +000011504 __ mov(eax, Operand(esp, kJSRegExpOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011505 __ mov(ecx, FieldOperand(eax, JSRegExp::kDataOffset));
11506 __ mov(edx, FieldOperand(ecx, JSRegExp::kIrregexpCaptureCountOffset));
11507 // Calculate number of capture registers (number_of_captures + 1) * 2.
Leon Clarke4515c472010-02-03 11:58:03 +000011508 ASSERT_EQ(0, kSmiTag);
11509 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
Leon Clarkee46be812010-01-19 14:06:41 +000011510 __ add(Operand(edx), Immediate(2)); // edx was a smi.
11511
11512 // edx: Number of capture registers
11513 // Load last_match_info which is still known to be a fast case JSArray.
Leon Clarked91b9f72010-01-27 17:25:45 +000011514 __ mov(eax, Operand(esp, kLastMatchInfoOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011515 __ mov(ebx, FieldOperand(eax, JSArray::kElementsOffset));
11516
11517 // ebx: last_match_info backing store (FixedArray)
11518 // edx: number of capture registers
11519 // Store the capture count.
11520 __ SmiTag(edx); // Number of capture registers to smi.
11521 __ mov(FieldOperand(ebx, RegExpImpl::kLastCaptureCountOffset), edx);
11522 __ SmiUntag(edx); // Number of capture registers back from smi.
11523 // Store last subject and last input.
Leon Clarked91b9f72010-01-27 17:25:45 +000011524 __ mov(eax, Operand(esp, kSubjectOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011525 __ mov(FieldOperand(ebx, RegExpImpl::kLastSubjectOffset), eax);
11526 __ mov(ecx, ebx);
11527 __ RecordWrite(ecx, RegExpImpl::kLastSubjectOffset, eax, edi);
Leon Clarked91b9f72010-01-27 17:25:45 +000011528 __ mov(eax, Operand(esp, kSubjectOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011529 __ mov(FieldOperand(ebx, RegExpImpl::kLastInputOffset), eax);
11530 __ mov(ecx, ebx);
11531 __ RecordWrite(ecx, RegExpImpl::kLastInputOffset, eax, edi);
11532
11533 // Get the static offsets vector filled by the native regexp code.
11534 ExternalReference address_of_static_offsets_vector =
11535 ExternalReference::address_of_static_offsets_vector();
11536 __ mov(ecx, Immediate(address_of_static_offsets_vector));
11537
11538 // ebx: last_match_info backing store (FixedArray)
11539 // ecx: offsets vector
11540 // edx: number of capture registers
11541 Label next_capture, done;
Leon Clarkee46be812010-01-19 14:06:41 +000011542 // Capture register counter starts from number of capture registers and
11543 // counts down until wraping after zero.
11544 __ bind(&next_capture);
11545 __ sub(Operand(edx), Immediate(1));
11546 __ j(negative, &done);
11547 // Read the value from the static offsets vector buffer.
Leon Clarke4515c472010-02-03 11:58:03 +000011548 __ mov(edi, Operand(ecx, edx, times_int_size, 0));
Steve Block6ded16b2010-05-10 14:33:55 +010011549 __ SmiTag(edi);
Leon Clarkee46be812010-01-19 14:06:41 +000011550 // Store the smi value in the last match info.
11551 __ mov(FieldOperand(ebx,
11552 edx,
11553 times_pointer_size,
11554 RegExpImpl::kFirstCaptureOffset),
11555 edi);
11556 __ jmp(&next_capture);
11557 __ bind(&done);
11558
11559 // Return last match info.
Leon Clarked91b9f72010-01-27 17:25:45 +000011560 __ mov(eax, Operand(esp, kLastMatchInfoOffset));
Leon Clarkee46be812010-01-19 14:06:41 +000011561 __ ret(4 * kPointerSize);
11562
11563 // Do the runtime call to execute the regexp.
11564 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +010011565 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
11566#endif // V8_INTERPRETED_REGEXP
Leon Clarkee46be812010-01-19 14:06:41 +000011567}
11568
11569
Andrei Popescu402d9372010-02-26 13:31:12 +000011570void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
11571 Register object,
11572 Register result,
11573 Register scratch1,
11574 Register scratch2,
11575 bool object_is_smi,
11576 Label* not_found) {
Andrei Popescu402d9372010-02-26 13:31:12 +000011577 // Use of registers. Register result is used as a temporary.
11578 Register number_string_cache = result;
11579 Register mask = scratch1;
11580 Register scratch = scratch2;
11581
11582 // Load the number string cache.
11583 ExternalReference roots_address = ExternalReference::roots_address();
11584 __ mov(scratch, Immediate(Heap::kNumberStringCacheRootIndex));
11585 __ mov(number_string_cache,
11586 Operand::StaticArray(scratch, times_pointer_size, roots_address));
11587 // Make the hash mask from the length of the number string cache. It
11588 // contains two elements (number and string) for each cache entry.
11589 __ mov(mask, FieldOperand(number_string_cache, FixedArray::kLengthOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010011590 __ shr(mask, kSmiTagSize + 1); // Untag length and divide it by two.
Andrei Popescu402d9372010-02-26 13:31:12 +000011591 __ sub(Operand(mask), Immediate(1)); // Make mask.
Steve Block6ded16b2010-05-10 14:33:55 +010011592
Andrei Popescu402d9372010-02-26 13:31:12 +000011593 // Calculate the entry in the number string cache. The hash value in the
Steve Block6ded16b2010-05-10 14:33:55 +010011594 // number string cache for smis is just the smi value, and the hash for
11595 // doubles is the xor of the upper and lower words. See
11596 // Heap::GetNumberStringCache.
11597 Label smi_hash_calculated;
11598 Label load_result_from_cache;
11599 if (object_is_smi) {
11600 __ mov(scratch, object);
11601 __ SmiUntag(scratch);
11602 } else {
11603 Label not_smi, hash_calculated;
11604 ASSERT(kSmiTag == 0);
11605 __ test(object, Immediate(kSmiTagMask));
11606 __ j(not_zero, &not_smi);
11607 __ mov(scratch, object);
11608 __ SmiUntag(scratch);
11609 __ jmp(&smi_hash_calculated);
11610 __ bind(&not_smi);
11611 __ cmp(FieldOperand(object, HeapObject::kMapOffset),
11612 Factory::heap_number_map());
11613 __ j(not_equal, not_found);
11614 ASSERT_EQ(8, kDoubleSize);
11615 __ mov(scratch, FieldOperand(object, HeapNumber::kValueOffset));
11616 __ xor_(scratch, FieldOperand(object, HeapNumber::kValueOffset + 4));
11617 // Object is heap number and hash is now in scratch. Calculate cache index.
11618 __ and_(scratch, Operand(mask));
11619 Register index = scratch;
11620 Register probe = mask;
11621 __ mov(probe,
11622 FieldOperand(number_string_cache,
11623 index,
11624 times_twice_pointer_size,
11625 FixedArray::kHeaderSize));
11626 __ test(probe, Immediate(kSmiTagMask));
11627 __ j(zero, not_found);
11628 if (CpuFeatures::IsSupported(SSE2)) {
11629 CpuFeatures::Scope fscope(SSE2);
11630 __ movdbl(xmm0, FieldOperand(object, HeapNumber::kValueOffset));
11631 __ movdbl(xmm1, FieldOperand(probe, HeapNumber::kValueOffset));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011632 __ ucomisd(xmm0, xmm1);
Steve Block6ded16b2010-05-10 14:33:55 +010011633 } else {
11634 __ fld_d(FieldOperand(object, HeapNumber::kValueOffset));
11635 __ fld_d(FieldOperand(probe, HeapNumber::kValueOffset));
11636 __ FCmp();
11637 }
11638 __ j(parity_even, not_found); // Bail out if NaN is involved.
11639 __ j(not_equal, not_found); // The cache did not contain this value.
11640 __ jmp(&load_result_from_cache);
11641 }
11642
11643 __ bind(&smi_hash_calculated);
11644 // Object is smi and hash is now in scratch. Calculate cache index.
Andrei Popescu402d9372010-02-26 13:31:12 +000011645 __ and_(scratch, Operand(mask));
Steve Block6ded16b2010-05-10 14:33:55 +010011646 Register index = scratch;
Andrei Popescu402d9372010-02-26 13:31:12 +000011647 // Check if the entry is the smi we are looking for.
11648 __ cmp(object,
11649 FieldOperand(number_string_cache,
Steve Block6ded16b2010-05-10 14:33:55 +010011650 index,
Andrei Popescu402d9372010-02-26 13:31:12 +000011651 times_twice_pointer_size,
11652 FixedArray::kHeaderSize));
11653 __ j(not_equal, not_found);
11654
11655 // Get the result from the cache.
Steve Block6ded16b2010-05-10 14:33:55 +010011656 __ bind(&load_result_from_cache);
Andrei Popescu402d9372010-02-26 13:31:12 +000011657 __ mov(result,
11658 FieldOperand(number_string_cache,
Steve Block6ded16b2010-05-10 14:33:55 +010011659 index,
Andrei Popescu402d9372010-02-26 13:31:12 +000011660 times_twice_pointer_size,
11661 FixedArray::kHeaderSize + kPointerSize));
11662 __ IncrementCounter(&Counters::number_to_string_native, 1);
11663}
11664
11665
11666void NumberToStringStub::Generate(MacroAssembler* masm) {
11667 Label runtime;
11668
11669 __ mov(ebx, Operand(esp, kPointerSize));
11670
11671 // Generate code to lookup number in the number string cache.
11672 GenerateLookupNumberStringCache(masm, ebx, eax, ecx, edx, false, &runtime);
11673 __ ret(1 * kPointerSize);
11674
11675 __ bind(&runtime);
11676 // Handle number to string in the runtime system if not found in the cache.
Steve Block6ded16b2010-05-10 14:33:55 +010011677 __ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
11678}
11679
11680
Steve Block6ded16b2010-05-10 14:33:55 +010011681static int NegativeComparisonResult(Condition cc) {
11682 ASSERT(cc != equal);
11683 ASSERT((cc == less) || (cc == less_equal)
11684 || (cc == greater) || (cc == greater_equal));
11685 return (cc == greater || cc == greater_equal) ? LESS : GREATER;
Andrei Popescu402d9372010-02-26 13:31:12 +000011686}
11687
11688
Steve Blocka7e24c12009-10-30 11:49:00 +000011689void CompareStub::Generate(MacroAssembler* masm) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +010011690 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
11691
Steve Block8defd9f2010-07-08 12:39:36 +010011692 Label check_unequal_objects, done;
Steve Blocka7e24c12009-10-30 11:49:00 +000011693
11694 // NOTICE! This code is only reached after a smi-fast-case check, so
11695 // it is certain that at least one operand isn't a smi.
11696
Steve Block6ded16b2010-05-10 14:33:55 +010011697 // Identical objects can be compared fast, but there are some tricky cases
11698 // for NaN and undefined.
11699 {
11700 Label not_identical;
11701 __ cmp(eax, Operand(edx));
11702 __ j(not_equal, &not_identical);
Steve Blocka7e24c12009-10-30 11:49:00 +000011703
Steve Block6ded16b2010-05-10 14:33:55 +010011704 if (cc_ != equal) {
11705 // Check for undefined. undefined OP undefined is false even though
11706 // undefined == undefined.
11707 Label check_for_nan;
11708 __ cmp(edx, Factory::undefined_value());
11709 __ j(not_equal, &check_for_nan);
11710 __ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
11711 __ ret(0);
11712 __ bind(&check_for_nan);
11713 }
Steve Blocka7e24c12009-10-30 11:49:00 +000011714
Steve Block6ded16b2010-05-10 14:33:55 +010011715 // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
11716 // so we do the second best thing - test it ourselves.
11717 // Note: if cc_ != equal, never_nan_nan_ is not used.
11718 if (never_nan_nan_ && (cc_ == equal)) {
11719 __ Set(eax, Immediate(Smi::FromInt(EQUAL)));
11720 __ ret(0);
11721 } else {
Steve Block6ded16b2010-05-10 14:33:55 +010011722 Label heap_number;
Steve Block6ded16b2010-05-10 14:33:55 +010011723 __ cmp(FieldOperand(edx, HeapObject::kMapOffset),
11724 Immediate(Factory::heap_number_map()));
11725 __ j(equal, &heap_number);
Steve Block8defd9f2010-07-08 12:39:36 +010011726 if (cc_ != equal) {
11727 // Call runtime on identical JSObjects. Otherwise return equal.
11728 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
11729 __ j(above_equal, &not_identical);
11730 }
Steve Block6ded16b2010-05-10 14:33:55 +010011731 __ Set(eax, Immediate(Smi::FromInt(EQUAL)));
11732 __ ret(0);
Steve Blocka7e24c12009-10-30 11:49:00 +000011733
Steve Block6ded16b2010-05-10 14:33:55 +010011734 __ bind(&heap_number);
11735 // It is a heap number, so return non-equal if it's NaN and equal if
11736 // it's not NaN.
11737 // The representation of NaN values has all exponent bits (52..62) set,
11738 // and not all mantissa bits (0..51) clear.
11739 // We only accept QNaNs, which have bit 51 set.
11740 // Read top bits of double representation (second word of value).
11741
11742 // Value is a QNaN if value & kQuietNaNMask == kQuietNaNMask, i.e.,
11743 // all bits in the mask are set. We only need to check the word
11744 // that contains the exponent and high bit of the mantissa.
11745 ASSERT_NE(0, (kQuietNaNHighBitsMask << 1) & 0x80000000u);
11746 __ mov(edx, FieldOperand(edx, HeapNumber::kExponentOffset));
11747 __ xor_(eax, Operand(eax));
11748 // Shift value and mask so kQuietNaNHighBitsMask applies to topmost
11749 // bits.
11750 __ add(edx, Operand(edx));
11751 __ cmp(edx, kQuietNaNHighBitsMask << 1);
11752 if (cc_ == equal) {
11753 ASSERT_NE(1, EQUAL);
Leon Clarkee46be812010-01-19 14:06:41 +000011754 __ setcc(above_equal, eax);
11755 __ ret(0);
Steve Block6ded16b2010-05-10 14:33:55 +010011756 } else {
11757 Label nan;
11758 __ j(above_equal, &nan);
11759 __ Set(eax, Immediate(Smi::FromInt(EQUAL)));
11760 __ ret(0);
11761 __ bind(&nan);
11762 __ Set(eax, Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
11763 __ ret(0);
Leon Clarkee46be812010-01-19 14:06:41 +000011764 }
Steve Blocka7e24c12009-10-30 11:49:00 +000011765 }
11766
Steve Block6ded16b2010-05-10 14:33:55 +010011767 __ bind(&not_identical);
11768 }
11769
Steve Block8defd9f2010-07-08 12:39:36 +010011770 // Strict equality can quickly decide whether objects are equal.
11771 // Non-strict object equality is slower, so it is handled later in the stub.
11772 if (cc_ == equal && strict_) {
Steve Block6ded16b2010-05-10 14:33:55 +010011773 Label slow; // Fallthrough label.
Steve Block8defd9f2010-07-08 12:39:36 +010011774 Label not_smis;
Steve Blocka7e24c12009-10-30 11:49:00 +000011775 // If we're doing a strict equality comparison, we don't have to do
11776 // type conversion, so we generate code to do fast comparison for objects
11777 // and oddballs. Non-smi numbers and strings still go through the usual
11778 // slow-case code.
Steve Block8defd9f2010-07-08 12:39:36 +010011779 // If either is a Smi (we know that not both are), then they can only
11780 // be equal if the other is a HeapNumber. If so, use the slow case.
11781 ASSERT_EQ(0, kSmiTag);
11782 ASSERT_EQ(0, Smi::FromInt(0));
11783 __ mov(ecx, Immediate(kSmiTagMask));
11784 __ and_(ecx, Operand(eax));
11785 __ test(ecx, Operand(edx));
11786 __ j(not_zero, &not_smis);
11787 // One operand is a smi.
Steve Blocka7e24c12009-10-30 11:49:00 +000011788
Steve Block8defd9f2010-07-08 12:39:36 +010011789 // Check whether the non-smi is a heap number.
11790 ASSERT_EQ(1, kSmiTagMask);
11791 // ecx still holds eax & kSmiTag, which is either zero or one.
11792 __ sub(Operand(ecx), Immediate(0x01));
11793 __ mov(ebx, edx);
11794 __ xor_(ebx, Operand(eax));
11795 __ and_(ebx, Operand(ecx)); // ebx holds either 0 or eax ^ edx.
11796 __ xor_(ebx, Operand(eax));
11797 // if eax was smi, ebx is now edx, else eax.
Steve Blocka7e24c12009-10-30 11:49:00 +000011798
Steve Block8defd9f2010-07-08 12:39:36 +010011799 // Check if the non-smi operand is a heap number.
11800 __ cmp(FieldOperand(ebx, HeapObject::kMapOffset),
11801 Immediate(Factory::heap_number_map()));
11802 // If heap number, handle it in the slow case.
11803 __ j(equal, &slow);
11804 // Return non-equal (ebx is not zero)
11805 __ mov(eax, ebx);
11806 __ ret(0);
Steve Blocka7e24c12009-10-30 11:49:00 +000011807
Steve Block8defd9f2010-07-08 12:39:36 +010011808 __ bind(&not_smis);
11809 // If either operand is a JSObject or an oddball value, then they are not
11810 // equal since their pointers are different
11811 // There is no test for undetectability in strict equality.
Steve Blocka7e24c12009-10-30 11:49:00 +000011812
Steve Block8defd9f2010-07-08 12:39:36 +010011813 // Get the type of the first operand.
11814 // If the first object is a JS object, we have done pointer comparison.
11815 Label first_non_object;
11816 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
11817 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
11818 __ j(below, &first_non_object);
Steve Blocka7e24c12009-10-30 11:49:00 +000011819
Steve Block8defd9f2010-07-08 12:39:36 +010011820 // Return non-zero (eax is not zero)
11821 Label return_not_equal;
11822 ASSERT(kHeapObjectTag != 0);
11823 __ bind(&return_not_equal);
11824 __ ret(0);
Steve Blocka7e24c12009-10-30 11:49:00 +000011825
Steve Block8defd9f2010-07-08 12:39:36 +010011826 __ bind(&first_non_object);
11827 // Check for oddballs: true, false, null, undefined.
11828 __ CmpInstanceType(ecx, ODDBALL_TYPE);
11829 __ j(equal, &return_not_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +000011830
Steve Block8defd9f2010-07-08 12:39:36 +010011831 __ CmpObjectType(edx, FIRST_JS_OBJECT_TYPE, ecx);
11832 __ j(above_equal, &return_not_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +000011833
Steve Block8defd9f2010-07-08 12:39:36 +010011834 // Check for oddballs: true, false, null, undefined.
11835 __ CmpInstanceType(ecx, ODDBALL_TYPE);
11836 __ j(equal, &return_not_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +000011837
Steve Block8defd9f2010-07-08 12:39:36 +010011838 // Fall through to the general case.
Steve Blocka7e24c12009-10-30 11:49:00 +000011839 __ bind(&slow);
11840 }
11841
11842 // Push arguments below the return address.
11843 __ pop(ecx);
11844 __ push(eax);
11845 __ push(edx);
11846 __ push(ecx);
11847
Steve Block6ded16b2010-05-10 14:33:55 +010011848 // Generate the number comparison code.
11849 if (include_number_compare_) {
11850 Label non_number_comparison;
11851 Label unordered;
11852 if (CpuFeatures::IsSupported(SSE2)) {
11853 CpuFeatures::Scope use_sse2(SSE2);
11854 CpuFeatures::Scope use_cmov(CMOV);
Steve Blocka7e24c12009-10-30 11:49:00 +000011855
Steve Block6ded16b2010-05-10 14:33:55 +010011856 FloatingPointHelper::LoadSSE2Operands(masm, &non_number_comparison);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010011857 __ ucomisd(xmm0, xmm1);
Steve Blocka7e24c12009-10-30 11:49:00 +000011858
Steve Block6ded16b2010-05-10 14:33:55 +010011859 // Don't base result on EFLAGS when a NaN is involved.
11860 __ j(parity_even, &unordered, not_taken);
11861 // Return a result of -1, 0, or 1, based on EFLAGS.
11862 __ mov(eax, 0); // equal
11863 __ mov(ecx, Immediate(Smi::FromInt(1)));
11864 __ cmov(above, eax, Operand(ecx));
11865 __ mov(ecx, Immediate(Smi::FromInt(-1)));
11866 __ cmov(below, eax, Operand(ecx));
11867 __ ret(2 * kPointerSize);
11868 } else {
11869 FloatingPointHelper::CheckFloatOperands(
11870 masm, &non_number_comparison, ebx);
11871 FloatingPointHelper::LoadFloatOperands(masm, ecx);
11872 __ FCmp();
Steve Blocka7e24c12009-10-30 11:49:00 +000011873
Steve Block6ded16b2010-05-10 14:33:55 +010011874 // Don't base result on EFLAGS when a NaN is involved.
11875 __ j(parity_even, &unordered, not_taken);
Steve Blocka7e24c12009-10-30 11:49:00 +000011876
Steve Block6ded16b2010-05-10 14:33:55 +010011877 Label below_label, above_label;
11878 // Return a result of -1, 0, or 1, based on EFLAGS. In all cases remove
11879 // two arguments from the stack as they have been pushed in preparation
11880 // of a possible runtime call.
11881 __ j(below, &below_label, not_taken);
11882 __ j(above, &above_label, not_taken);
Steve Blocka7e24c12009-10-30 11:49:00 +000011883
Steve Block6ded16b2010-05-10 14:33:55 +010011884 __ xor_(eax, Operand(eax));
11885 __ ret(2 * kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +000011886
Steve Block6ded16b2010-05-10 14:33:55 +010011887 __ bind(&below_label);
11888 __ mov(eax, Immediate(Smi::FromInt(-1)));
11889 __ ret(2 * kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +000011890
Steve Block6ded16b2010-05-10 14:33:55 +010011891 __ bind(&above_label);
11892 __ mov(eax, Immediate(Smi::FromInt(1)));
11893 __ ret(2 * kPointerSize);
11894 }
11895
11896 // If one of the numbers was NaN, then the result is always false.
11897 // The cc is never not-equal.
11898 __ bind(&unordered);
11899 ASSERT(cc_ != not_equal);
11900 if (cc_ == less || cc_ == less_equal) {
11901 __ mov(eax, Immediate(Smi::FromInt(1)));
11902 } else {
11903 __ mov(eax, Immediate(Smi::FromInt(-1)));
11904 }
Steve Blocka7e24c12009-10-30 11:49:00 +000011905 __ ret(2 * kPointerSize); // eax, edx were pushed
Steve Block6ded16b2010-05-10 14:33:55 +010011906
11907 // The number comparison code did not provide a valid result.
11908 __ bind(&non_number_comparison);
Steve Blocka7e24c12009-10-30 11:49:00 +000011909 }
Steve Blocka7e24c12009-10-30 11:49:00 +000011910
11911 // Fast negative check for symbol-to-symbol equality.
Leon Clarkee46be812010-01-19 14:06:41 +000011912 Label check_for_strings;
Steve Blocka7e24c12009-10-30 11:49:00 +000011913 if (cc_ == equal) {
Leon Clarkee46be812010-01-19 14:06:41 +000011914 BranchIfNonSymbol(masm, &check_for_strings, eax, ecx);
11915 BranchIfNonSymbol(masm, &check_for_strings, edx, ecx);
Steve Blocka7e24c12009-10-30 11:49:00 +000011916
11917 // We've already checked for object identity, so if both operands
11918 // are symbols they aren't equal. Register eax already holds a
11919 // non-zero value, which indicates not equal, so just return.
11920 __ ret(2 * kPointerSize);
11921 }
11922
Leon Clarkee46be812010-01-19 14:06:41 +000011923 __ bind(&check_for_strings);
11924
Steve Block8defd9f2010-07-08 12:39:36 +010011925 __ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx,
11926 &check_unequal_objects);
Leon Clarkee46be812010-01-19 14:06:41 +000011927
11928 // Inline comparison of ascii strings.
11929 StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
11930 edx,
11931 eax,
11932 ecx,
11933 ebx,
11934 edi);
11935#ifdef DEBUG
11936 __ Abort("Unexpected fall-through from string comparison");
11937#endif
11938
Steve Block8defd9f2010-07-08 12:39:36 +010011939 __ bind(&check_unequal_objects);
11940 if (cc_ == equal && !strict_) {
11941 // Non-strict equality. Objects are unequal if
11942 // they are both JSObjects and not undetectable,
11943 // and their pointers are different.
11944 Label not_both_objects;
11945 Label return_unequal;
11946 // At most one is a smi, so we can test for smi by adding the two.
11947 // A smi plus a heap object has the low bit set, a heap object plus
11948 // a heap object has the low bit clear.
11949 ASSERT_EQ(0, kSmiTag);
11950 ASSERT_EQ(1, kSmiTagMask);
11951 __ lea(ecx, Operand(eax, edx, times_1, 0));
11952 __ test(ecx, Immediate(kSmiTagMask));
11953 __ j(not_zero, &not_both_objects);
11954 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, ecx);
11955 __ j(below, &not_both_objects);
11956 __ CmpObjectType(edx, FIRST_JS_OBJECT_TYPE, ebx);
11957 __ j(below, &not_both_objects);
11958 // We do not bail out after this point. Both are JSObjects, and
11959 // they are equal if and only if both are undetectable.
11960 // The and of the undetectable flags is 1 if and only if they are equal.
11961 __ test_b(FieldOperand(ecx, Map::kBitFieldOffset),
11962 1 << Map::kIsUndetectable);
11963 __ j(zero, &return_unequal);
11964 __ test_b(FieldOperand(ebx, Map::kBitFieldOffset),
11965 1 << Map::kIsUndetectable);
11966 __ j(zero, &return_unequal);
11967 // The objects are both undetectable, so they both compare as the value
11968 // undefined, and are equal.
11969 __ Set(eax, Immediate(EQUAL));
11970 __ bind(&return_unequal);
11971 // Return non-equal by returning the non-zero object pointer in eax,
11972 // or return equal if we fell through to here.
11973 __ ret(2 * kPointerSize); // rax, rdx were pushed
11974 __ bind(&not_both_objects);
11975 }
11976
Steve Blocka7e24c12009-10-30 11:49:00 +000011977 // must swap argument order
11978 __ pop(ecx);
11979 __ pop(edx);
11980 __ pop(eax);
11981 __ push(edx);
11982 __ push(eax);
11983
11984 // Figure out which native to call and setup the arguments.
11985 Builtins::JavaScript builtin;
11986 if (cc_ == equal) {
11987 builtin = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
11988 } else {
11989 builtin = Builtins::COMPARE;
Steve Block6ded16b2010-05-10 14:33:55 +010011990 __ push(Immediate(Smi::FromInt(NegativeComparisonResult(cc_))));
Steve Blocka7e24c12009-10-30 11:49:00 +000011991 }
11992
11993 // Restore return address on the stack.
11994 __ push(ecx);
11995
11996 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
11997 // tagged as a small integer.
11998 __ InvokeBuiltin(builtin, JUMP_FUNCTION);
11999}
12000
12001
12002void CompareStub::BranchIfNonSymbol(MacroAssembler* masm,
12003 Label* label,
12004 Register object,
12005 Register scratch) {
12006 __ test(object, Immediate(kSmiTagMask));
12007 __ j(zero, label);
12008 __ mov(scratch, FieldOperand(object, HeapObject::kMapOffset));
12009 __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
12010 __ and_(scratch, kIsSymbolMask | kIsNotStringMask);
12011 __ cmp(scratch, kSymbolTag | kStringTag);
12012 __ j(not_equal, label);
12013}
12014
12015
12016void StackCheckStub::Generate(MacroAssembler* masm) {
12017 // Because builtins always remove the receiver from the stack, we
12018 // have to fake one to avoid underflowing the stack. The receiver
12019 // must be inserted below the return address on the stack so we
12020 // temporarily store that in a register.
12021 __ pop(eax);
12022 __ push(Immediate(Smi::FromInt(0)));
12023 __ push(eax);
12024
12025 // Do tail-call to runtime routine.
Steve Block6ded16b2010-05-10 14:33:55 +010012026 __ TailCallRuntime(Runtime::kStackGuard, 1, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +000012027}
12028
12029
12030void CallFunctionStub::Generate(MacroAssembler* masm) {
12031 Label slow;
12032
Leon Clarkee46be812010-01-19 14:06:41 +000012033 // If the receiver might be a value (string, number or boolean) check for this
12034 // and box it if it is.
12035 if (ReceiverMightBeValue()) {
12036 // Get the receiver from the stack.
12037 // +1 ~ return address
12038 Label receiver_is_value, receiver_is_js_object;
12039 __ mov(eax, Operand(esp, (argc_ + 1) * kPointerSize));
12040
12041 // Check if receiver is a smi (which is a number value).
12042 __ test(eax, Immediate(kSmiTagMask));
12043 __ j(zero, &receiver_is_value, not_taken);
12044
12045 // Check if the receiver is a valid JS object.
12046 __ CmpObjectType(eax, FIRST_JS_OBJECT_TYPE, edi);
12047 __ j(above_equal, &receiver_is_js_object);
12048
12049 // Call the runtime to box the value.
12050 __ bind(&receiver_is_value);
12051 __ EnterInternalFrame();
12052 __ push(eax);
12053 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
12054 __ LeaveInternalFrame();
12055 __ mov(Operand(esp, (argc_ + 1) * kPointerSize), eax);
12056
12057 __ bind(&receiver_is_js_object);
12058 }
12059
Steve Blocka7e24c12009-10-30 11:49:00 +000012060 // Get the function to call from the stack.
12061 // +2 ~ receiver, return address
12062 __ mov(edi, Operand(esp, (argc_ + 2) * kPointerSize));
12063
12064 // Check that the function really is a JavaScript function.
12065 __ test(edi, Immediate(kSmiTagMask));
12066 __ j(zero, &slow, not_taken);
12067 // Goto slow case if we do not have a function.
12068 __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
12069 __ j(not_equal, &slow, not_taken);
12070
12071 // Fast-case: Just invoke the function.
12072 ParameterCount actual(argc_);
12073 __ InvokeFunction(edi, actual, JUMP_FUNCTION);
12074
12075 // Slow-case: Non-function called.
12076 __ bind(&slow);
Andrei Popescu402d9372010-02-26 13:31:12 +000012077 // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
12078 // of the original receiver from the call site).
12079 __ mov(Operand(esp, (argc_ + 1) * kPointerSize), edi);
Steve Blocka7e24c12009-10-30 11:49:00 +000012080 __ Set(eax, Immediate(argc_));
12081 __ Set(ebx, Immediate(0));
12082 __ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION);
12083 Handle<Code> adaptor(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
12084 __ jmp(adaptor, RelocInfo::CODE_TARGET);
12085}
12086
12087
Steve Blocka7e24c12009-10-30 11:49:00 +000012088void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
12089 // eax holds the exception.
12090
12091 // Adjust this code if not the case.
12092 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
12093
12094 // Drop the sp to the top of the handler.
12095 ExternalReference handler_address(Top::k_handler_address);
12096 __ mov(esp, Operand::StaticVariable(handler_address));
12097
12098 // Restore next handler and frame pointer, discard handler state.
12099 ASSERT(StackHandlerConstants::kNextOffset == 0);
12100 __ pop(Operand::StaticVariable(handler_address));
12101 ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
12102 __ pop(ebp);
12103 __ pop(edx); // Remove state.
12104
12105 // Before returning we restore the context from the frame pointer if
12106 // not NULL. The frame pointer is NULL in the exception handler of
12107 // a JS entry frame.
12108 __ xor_(esi, Operand(esi)); // Tentatively set context pointer to NULL.
12109 Label skip;
12110 __ cmp(ebp, 0);
12111 __ j(equal, &skip, not_taken);
12112 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
12113 __ bind(&skip);
12114
12115 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
12116 __ ret(0);
12117}
12118
12119
Steve Blockd0582a62009-12-15 09:54:21 +000012120// If true, a Handle<T> passed by value is passed and returned by
12121// using the location_ field directly. If false, it is passed and
12122// returned as a pointer to a handle.
Steve Block6ded16b2010-05-10 14:33:55 +010012123#ifdef USING_BSD_ABI
Steve Blockd0582a62009-12-15 09:54:21 +000012124static const bool kPassHandlesDirectly = true;
12125#else
12126static const bool kPassHandlesDirectly = false;
12127#endif
12128
12129
12130void ApiGetterEntryStub::Generate(MacroAssembler* masm) {
12131 Label get_result;
12132 Label prologue;
12133 Label promote_scheduled_exception;
12134 __ EnterApiExitFrame(ExitFrame::MODE_NORMAL, kStackSpace, kArgc);
12135 ASSERT_EQ(kArgc, 4);
12136 if (kPassHandlesDirectly) {
12137 // When handles as passed directly we don't have to allocate extra
12138 // space for and pass an out parameter.
12139 __ mov(Operand(esp, 0 * kPointerSize), ebx); // name.
12140 __ mov(Operand(esp, 1 * kPointerSize), eax); // arguments pointer.
12141 } else {
12142 // The function expects three arguments to be passed but we allocate
12143 // four to get space for the output cell. The argument slots are filled
12144 // as follows:
12145 //
12146 // 3: output cell
12147 // 2: arguments pointer
12148 // 1: name
12149 // 0: pointer to the output cell
12150 //
12151 // Note that this is one more "argument" than the function expects
12152 // so the out cell will have to be popped explicitly after returning
12153 // from the function.
12154 __ mov(Operand(esp, 1 * kPointerSize), ebx); // name.
12155 __ mov(Operand(esp, 2 * kPointerSize), eax); // arguments pointer.
12156 __ mov(ebx, esp);
12157 __ add(Operand(ebx), Immediate(3 * kPointerSize));
12158 __ mov(Operand(esp, 0 * kPointerSize), ebx); // output
12159 __ mov(Operand(esp, 3 * kPointerSize), Immediate(0)); // out cell.
12160 }
12161 // Call the api function!
12162 __ call(fun()->address(), RelocInfo::RUNTIME_ENTRY);
12163 // Check if the function scheduled an exception.
12164 ExternalReference scheduled_exception_address =
12165 ExternalReference::scheduled_exception_address();
12166 __ cmp(Operand::StaticVariable(scheduled_exception_address),
12167 Immediate(Factory::the_hole_value()));
12168 __ j(not_equal, &promote_scheduled_exception, not_taken);
12169 if (!kPassHandlesDirectly) {
12170 // The returned value is a pointer to the handle holding the result.
12171 // Dereference this to get to the location.
12172 __ mov(eax, Operand(eax, 0));
12173 }
12174 // Check if the result handle holds 0
12175 __ test(eax, Operand(eax));
12176 __ j(not_zero, &get_result, taken);
12177 // It was zero; the result is undefined.
12178 __ mov(eax, Factory::undefined_value());
12179 __ jmp(&prologue);
12180 // It was non-zero. Dereference to get the result value.
12181 __ bind(&get_result);
12182 __ mov(eax, Operand(eax, 0));
12183 __ bind(&prologue);
12184 __ LeaveExitFrame(ExitFrame::MODE_NORMAL);
12185 __ ret(0);
12186 __ bind(&promote_scheduled_exception);
Steve Block6ded16b2010-05-10 14:33:55 +010012187 __ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
Steve Blockd0582a62009-12-15 09:54:21 +000012188}
12189
12190
Steve Blocka7e24c12009-10-30 11:49:00 +000012191void CEntryStub::GenerateCore(MacroAssembler* masm,
12192 Label* throw_normal_exception,
12193 Label* throw_termination_exception,
12194 Label* throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +000012195 bool do_gc,
Steve Block6ded16b2010-05-10 14:33:55 +010012196 bool always_allocate_scope,
12197 int /* alignment_skew */) {
Steve Blocka7e24c12009-10-30 11:49:00 +000012198 // eax: result parameter for PerformGC, if any
12199 // ebx: pointer to C function (C callee-saved)
12200 // ebp: frame pointer (restored after C call)
12201 // esp: stack pointer (restored after C call)
12202 // edi: number of arguments including receiver (C callee-saved)
12203 // esi: pointer to the first argument (C callee-saved)
12204
Leon Clarke4515c472010-02-03 11:58:03 +000012205 // Result returned in eax, or eax+edx if result_size_ is 2.
12206
Steve Block6ded16b2010-05-10 14:33:55 +010012207 // Check stack alignment.
12208 if (FLAG_debug_code) {
12209 __ CheckStackAlignment();
12210 }
12211
Steve Blocka7e24c12009-10-30 11:49:00 +000012212 if (do_gc) {
Steve Block6ded16b2010-05-10 14:33:55 +010012213 // Pass failure code returned from last attempt as first argument to
12214 // PerformGC. No need to use PrepareCallCFunction/CallCFunction here as the
12215 // stack alignment is known to be correct. This function takes one argument
12216 // which is passed on the stack, and we know that the stack has been
12217 // prepared to pass at least one argument.
Steve Blocka7e24c12009-10-30 11:49:00 +000012218 __ mov(Operand(esp, 0 * kPointerSize), eax); // Result.
12219 __ call(FUNCTION_ADDR(Runtime::PerformGC), RelocInfo::RUNTIME_ENTRY);
12220 }
12221
12222 ExternalReference scope_depth =
12223 ExternalReference::heap_always_allocate_scope_depth();
12224 if (always_allocate_scope) {
12225 __ inc(Operand::StaticVariable(scope_depth));
12226 }
12227
12228 // Call C function.
12229 __ mov(Operand(esp, 0 * kPointerSize), edi); // argc.
12230 __ mov(Operand(esp, 1 * kPointerSize), esi); // argv.
12231 __ call(Operand(ebx));
12232 // Result is in eax or edx:eax - do not destroy these registers!
12233
12234 if (always_allocate_scope) {
12235 __ dec(Operand::StaticVariable(scope_depth));
12236 }
12237
12238 // Make sure we're not trying to return 'the hole' from the runtime
12239 // call as this may lead to crashes in the IC code later.
12240 if (FLAG_debug_code) {
12241 Label okay;
12242 __ cmp(eax, Factory::the_hole_value());
12243 __ j(not_equal, &okay);
12244 __ int3();
12245 __ bind(&okay);
12246 }
12247
12248 // Check for failure result.
12249 Label failure_returned;
12250 ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
12251 __ lea(ecx, Operand(eax, 1));
12252 // Lower 2 bits of ecx are 0 iff eax has failure tag.
12253 __ test(ecx, Immediate(kFailureTagMask));
12254 __ j(zero, &failure_returned, not_taken);
12255
12256 // Exit the JavaScript to C++ exit frame.
Leon Clarke4515c472010-02-03 11:58:03 +000012257 __ LeaveExitFrame(mode_);
Steve Blocka7e24c12009-10-30 11:49:00 +000012258 __ ret(0);
12259
12260 // Handling of failure.
12261 __ bind(&failure_returned);
12262
12263 Label retry;
12264 // If the returned exception is RETRY_AFTER_GC continue at retry label
12265 ASSERT(Failure::RETRY_AFTER_GC == 0);
12266 __ test(eax, Immediate(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
12267 __ j(zero, &retry, taken);
12268
12269 // Special handling of out of memory exceptions.
12270 __ cmp(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
12271 __ j(equal, throw_out_of_memory_exception);
12272
12273 // Retrieve the pending exception and clear the variable.
12274 ExternalReference pending_exception_address(Top::k_pending_exception_address);
12275 __ mov(eax, Operand::StaticVariable(pending_exception_address));
12276 __ mov(edx,
12277 Operand::StaticVariable(ExternalReference::the_hole_value_location()));
12278 __ mov(Operand::StaticVariable(pending_exception_address), edx);
12279
12280 // Special handling of termination exceptions which are uncatchable
12281 // by javascript code.
12282 __ cmp(eax, Factory::termination_exception());
12283 __ j(equal, throw_termination_exception);
12284
12285 // Handle normal exception.
12286 __ jmp(throw_normal_exception);
12287
12288 // Retry.
12289 __ bind(&retry);
12290}
12291
12292
12293void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
12294 UncatchableExceptionType type) {
12295 // Adjust this code if not the case.
12296 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
12297
12298 // Drop sp to the top stack handler.
12299 ExternalReference handler_address(Top::k_handler_address);
12300 __ mov(esp, Operand::StaticVariable(handler_address));
12301
12302 // Unwind the handlers until the ENTRY handler is found.
12303 Label loop, done;
12304 __ bind(&loop);
12305 // Load the type of the current stack handler.
12306 const int kStateOffset = StackHandlerConstants::kStateOffset;
12307 __ cmp(Operand(esp, kStateOffset), Immediate(StackHandler::ENTRY));
12308 __ j(equal, &done);
12309 // Fetch the next handler in the list.
12310 const int kNextOffset = StackHandlerConstants::kNextOffset;
12311 __ mov(esp, Operand(esp, kNextOffset));
12312 __ jmp(&loop);
12313 __ bind(&done);
12314
12315 // Set the top handler address to next handler past the current ENTRY handler.
12316 ASSERT(StackHandlerConstants::kNextOffset == 0);
12317 __ pop(Operand::StaticVariable(handler_address));
12318
12319 if (type == OUT_OF_MEMORY) {
12320 // Set external caught exception to false.
12321 ExternalReference external_caught(Top::k_external_caught_exception_address);
12322 __ mov(eax, false);
12323 __ mov(Operand::StaticVariable(external_caught), eax);
12324
12325 // Set pending exception and eax to out of memory exception.
12326 ExternalReference pending_exception(Top::k_pending_exception_address);
12327 __ mov(eax, reinterpret_cast<int32_t>(Failure::OutOfMemoryException()));
12328 __ mov(Operand::StaticVariable(pending_exception), eax);
12329 }
12330
12331 // Clear the context pointer.
12332 __ xor_(esi, Operand(esi));
12333
12334 // Restore fp from handler and discard handler state.
12335 ASSERT(StackHandlerConstants::kFPOffset == 1 * kPointerSize);
12336 __ pop(ebp);
12337 __ pop(edx); // State.
12338
12339 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
12340 __ ret(0);
12341}
12342
12343
Leon Clarke4515c472010-02-03 11:58:03 +000012344void CEntryStub::Generate(MacroAssembler* masm) {
Steve Blocka7e24c12009-10-30 11:49:00 +000012345 // eax: number of arguments including receiver
12346 // ebx: pointer to C function (C callee-saved)
12347 // ebp: frame pointer (restored after C call)
12348 // esp: stack pointer (restored after C call)
12349 // esi: current context (C callee-saved)
12350 // edi: JS function of the caller (C callee-saved)
12351
12352 // NOTE: Invocations of builtins may return failure objects instead
12353 // of a proper result. The builtin entry handles this by performing
12354 // a garbage collection and retrying the builtin (twice).
12355
Steve Blocka7e24c12009-10-30 11:49:00 +000012356 // Enter the exit frame that transitions from JavaScript to C++.
Leon Clarke4515c472010-02-03 11:58:03 +000012357 __ EnterExitFrame(mode_);
Steve Blocka7e24c12009-10-30 11:49:00 +000012358
12359 // eax: result parameter for PerformGC, if any (setup below)
12360 // ebx: pointer to builtin function (C callee-saved)
12361 // ebp: frame pointer (restored after C call)
12362 // esp: stack pointer (restored after C call)
12363 // edi: number of arguments including receiver (C callee-saved)
12364 // esi: argv pointer (C callee-saved)
12365
12366 Label throw_normal_exception;
12367 Label throw_termination_exception;
12368 Label throw_out_of_memory_exception;
12369
12370 // Call into the runtime system.
12371 GenerateCore(masm,
12372 &throw_normal_exception,
12373 &throw_termination_exception,
12374 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +000012375 false,
12376 false);
12377
12378 // Do space-specific GC and retry runtime call.
12379 GenerateCore(masm,
12380 &throw_normal_exception,
12381 &throw_termination_exception,
12382 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +000012383 true,
12384 false);
12385
12386 // Do full GC and retry runtime call one final time.
12387 Failure* failure = Failure::InternalError();
12388 __ mov(eax, Immediate(reinterpret_cast<int32_t>(failure)));
12389 GenerateCore(masm,
12390 &throw_normal_exception,
12391 &throw_termination_exception,
12392 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +000012393 true,
12394 true);
12395
12396 __ bind(&throw_out_of_memory_exception);
12397 GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
12398
12399 __ bind(&throw_termination_exception);
12400 GenerateThrowUncatchable(masm, TERMINATION);
12401
12402 __ bind(&throw_normal_exception);
12403 GenerateThrowTOS(masm);
12404}
12405
12406
12407void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
12408 Label invoke, exit;
12409#ifdef ENABLE_LOGGING_AND_PROFILING
12410 Label not_outermost_js, not_outermost_js_2;
12411#endif
12412
12413 // Setup frame.
12414 __ push(ebp);
12415 __ mov(ebp, Operand(esp));
12416
12417 // Push marker in two places.
12418 int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
12419 __ push(Immediate(Smi::FromInt(marker))); // context slot
12420 __ push(Immediate(Smi::FromInt(marker))); // function slot
12421 // Save callee-saved registers (C calling conventions).
12422 __ push(edi);
12423 __ push(esi);
12424 __ push(ebx);
12425
12426 // Save copies of the top frame descriptor on the stack.
12427 ExternalReference c_entry_fp(Top::k_c_entry_fp_address);
12428 __ push(Operand::StaticVariable(c_entry_fp));
12429
12430#ifdef ENABLE_LOGGING_AND_PROFILING
12431 // If this is the outermost JS call, set js_entry_sp value.
12432 ExternalReference js_entry_sp(Top::k_js_entry_sp_address);
12433 __ cmp(Operand::StaticVariable(js_entry_sp), Immediate(0));
12434 __ j(not_equal, &not_outermost_js);
12435 __ mov(Operand::StaticVariable(js_entry_sp), ebp);
12436 __ bind(&not_outermost_js);
12437#endif
12438
12439 // Call a faked try-block that does the invoke.
12440 __ call(&invoke);
12441
12442 // Caught exception: Store result (exception) in the pending
12443 // exception field in the JSEnv and return a failure sentinel.
12444 ExternalReference pending_exception(Top::k_pending_exception_address);
12445 __ mov(Operand::StaticVariable(pending_exception), eax);
12446 __ mov(eax, reinterpret_cast<int32_t>(Failure::Exception()));
12447 __ jmp(&exit);
12448
12449 // Invoke: Link this frame into the handler chain.
12450 __ bind(&invoke);
12451 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
12452
12453 // Clear any pending exceptions.
12454 __ mov(edx,
12455 Operand::StaticVariable(ExternalReference::the_hole_value_location()));
12456 __ mov(Operand::StaticVariable(pending_exception), edx);
12457
12458 // Fake a receiver (NULL).
12459 __ push(Immediate(0)); // receiver
12460
12461 // Invoke the function by calling through JS entry trampoline
12462 // builtin and pop the faked function when we return. Notice that we
12463 // cannot store a reference to the trampoline code directly in this
12464 // stub, because the builtin stubs may not have been generated yet.
12465 if (is_construct) {
12466 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
12467 __ mov(edx, Immediate(construct_entry));
12468 } else {
12469 ExternalReference entry(Builtins::JSEntryTrampoline);
12470 __ mov(edx, Immediate(entry));
12471 }
12472 __ mov(edx, Operand(edx, 0)); // deref address
12473 __ lea(edx, FieldOperand(edx, Code::kHeaderSize));
12474 __ call(Operand(edx));
12475
12476 // Unlink this frame from the handler chain.
12477 __ pop(Operand::StaticVariable(ExternalReference(Top::k_handler_address)));
12478 // Pop next_sp.
12479 __ add(Operand(esp), Immediate(StackHandlerConstants::kSize - kPointerSize));
12480
12481#ifdef ENABLE_LOGGING_AND_PROFILING
12482 // If current EBP value is the same as js_entry_sp value, it means that
12483 // the current function is the outermost.
12484 __ cmp(ebp, Operand::StaticVariable(js_entry_sp));
12485 __ j(not_equal, &not_outermost_js_2);
12486 __ mov(Operand::StaticVariable(js_entry_sp), Immediate(0));
12487 __ bind(&not_outermost_js_2);
12488#endif
12489
12490 // Restore the top frame descriptor from the stack.
12491 __ bind(&exit);
12492 __ pop(Operand::StaticVariable(ExternalReference(Top::k_c_entry_fp_address)));
12493
12494 // Restore callee-saved registers (C calling conventions).
12495 __ pop(ebx);
12496 __ pop(esi);
12497 __ pop(edi);
12498 __ add(Operand(esp), Immediate(2 * kPointerSize)); // remove markers
12499
12500 // Restore frame pointer and return.
12501 __ pop(ebp);
12502 __ ret(0);
12503}
12504
12505
12506void InstanceofStub::Generate(MacroAssembler* masm) {
12507 // Get the object - go slow case if it's a smi.
12508 Label slow;
12509 __ mov(eax, Operand(esp, 2 * kPointerSize)); // 2 ~ return address, function
12510 __ test(eax, Immediate(kSmiTagMask));
12511 __ j(zero, &slow, not_taken);
12512
12513 // Check that the left hand is a JS object.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012514 __ IsObjectJSObjectType(eax, eax, edx, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +000012515
12516 // Get the prototype of the function.
12517 __ mov(edx, Operand(esp, 1 * kPointerSize)); // 1 ~ return address
Kristian Monsen25f61362010-05-21 11:50:48 +010012518 // edx is function, eax is map.
12519
12520 // Look up the function and the map in the instanceof cache.
12521 Label miss;
12522 ExternalReference roots_address = ExternalReference::roots_address();
12523 __ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
12524 __ cmp(edx, Operand::StaticArray(ecx, times_pointer_size, roots_address));
12525 __ j(not_equal, &miss);
12526 __ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
12527 __ cmp(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
12528 __ j(not_equal, &miss);
12529 __ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
12530 __ mov(eax, Operand::StaticArray(ecx, times_pointer_size, roots_address));
12531 __ ret(2 * kPointerSize);
12532
12533 __ bind(&miss);
Steve Blocka7e24c12009-10-30 11:49:00 +000012534 __ TryGetFunctionPrototype(edx, ebx, ecx, &slow);
12535
12536 // Check that the function prototype is a JS object.
12537 __ test(ebx, Immediate(kSmiTagMask));
12538 __ j(zero, &slow, not_taken);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012539 __ IsObjectJSObjectType(ebx, ecx, ecx, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +000012540
Kristian Monsen25f61362010-05-21 11:50:48 +010012541 // Register mapping:
12542 // eax is object map.
12543 // edx is function.
12544 // ebx is function prototype.
12545 __ mov(ecx, Immediate(Heap::kInstanceofCacheMapRootIndex));
12546 __ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
12547 __ mov(ecx, Immediate(Heap::kInstanceofCacheFunctionRootIndex));
12548 __ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), edx);
12549
Steve Blocka7e24c12009-10-30 11:49:00 +000012550 __ mov(ecx, FieldOperand(eax, Map::kPrototypeOffset));
12551
12552 // Loop through the prototype chain looking for the function prototype.
12553 Label loop, is_instance, is_not_instance;
12554 __ bind(&loop);
12555 __ cmp(ecx, Operand(ebx));
12556 __ j(equal, &is_instance);
12557 __ cmp(Operand(ecx), Immediate(Factory::null_value()));
12558 __ j(equal, &is_not_instance);
12559 __ mov(ecx, FieldOperand(ecx, HeapObject::kMapOffset));
12560 __ mov(ecx, FieldOperand(ecx, Map::kPrototypeOffset));
12561 __ jmp(&loop);
12562
12563 __ bind(&is_instance);
12564 __ Set(eax, Immediate(0));
Kristian Monsen25f61362010-05-21 11:50:48 +010012565 __ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
12566 __ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
Steve Blocka7e24c12009-10-30 11:49:00 +000012567 __ ret(2 * kPointerSize);
12568
12569 __ bind(&is_not_instance);
12570 __ Set(eax, Immediate(Smi::FromInt(1)));
Kristian Monsen25f61362010-05-21 11:50:48 +010012571 __ mov(ecx, Immediate(Heap::kInstanceofCacheAnswerRootIndex));
12572 __ mov(Operand::StaticArray(ecx, times_pointer_size, roots_address), eax);
Steve Blocka7e24c12009-10-30 11:49:00 +000012573 __ ret(2 * kPointerSize);
12574
12575 // Slow-case: Go through the JavaScript implementation.
12576 __ bind(&slow);
12577 __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
12578}
12579
12580
Steve Block6ded16b2010-05-10 14:33:55 +010012581int CompareStub::MinorKey() {
12582 // Encode the three parameters in a unique 16 bit value. To avoid duplicate
12583 // stubs the never NaN NaN condition is only taken into account if the
12584 // condition is equals.
Ben Murdoch3bec4d22010-07-22 14:51:16 +010012585 ASSERT(static_cast<unsigned>(cc_) < (1 << 12));
12586 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
Steve Block6ded16b2010-05-10 14:33:55 +010012587 return ConditionField::encode(static_cast<unsigned>(cc_))
Ben Murdoch3bec4d22010-07-22 14:51:16 +010012588 | RegisterField::encode(false) // lhs_ and rhs_ are not used
Steve Block6ded16b2010-05-10 14:33:55 +010012589 | StrictField::encode(strict_)
12590 | NeverNanNanField::encode(cc_ == equal ? never_nan_nan_ : false)
12591 | IncludeNumberCompareField::encode(include_number_compare_);
Leon Clarkee46be812010-01-19 14:06:41 +000012592}
12593
12594
Steve Block6ded16b2010-05-10 14:33:55 +010012595// Unfortunately you have to run without snapshots to see most of these
12596// names in the profile since most compare stubs end up in the snapshot.
12597const char* CompareStub::GetName() {
Ben Murdoch3bec4d22010-07-22 14:51:16 +010012598 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
12599
Steve Block6ded16b2010-05-10 14:33:55 +010012600 if (name_ != NULL) return name_;
12601 const int kMaxNameLength = 100;
12602 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
12603 if (name_ == NULL) return "OOM";
12604
12605 const char* cc_name;
12606 switch (cc_) {
12607 case less: cc_name = "LT"; break;
12608 case greater: cc_name = "GT"; break;
12609 case less_equal: cc_name = "LE"; break;
12610 case greater_equal: cc_name = "GE"; break;
12611 case equal: cc_name = "EQ"; break;
12612 case not_equal: cc_name = "NE"; break;
12613 default: cc_name = "UnknownCondition"; break;
12614 }
12615
12616 const char* strict_name = "";
12617 if (strict_ && (cc_ == equal || cc_ == not_equal)) {
12618 strict_name = "_STRICT";
12619 }
12620
12621 const char* never_nan_nan_name = "";
12622 if (never_nan_nan_ && (cc_ == equal || cc_ == not_equal)) {
12623 never_nan_nan_name = "_NO_NAN";
12624 }
12625
12626 const char* include_number_compare_name = "";
12627 if (!include_number_compare_) {
12628 include_number_compare_name = "_NO_NUMBER";
12629 }
12630
12631 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
12632 "CompareStub_%s%s%s%s",
12633 cc_name,
12634 strict_name,
12635 never_nan_nan_name,
12636 include_number_compare_name);
12637 return name_;
12638}
12639
12640
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012641// -------------------------------------------------------------------------
12642// StringCharCodeAtGenerator
12643
12644void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
12645 Label flat_string;
Steve Block6ded16b2010-05-10 14:33:55 +010012646 Label ascii_string;
12647 Label got_char_code;
12648
12649 // If the receiver is a smi trigger the non-string case.
12650 ASSERT(kSmiTag == 0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012651 __ test(object_, Immediate(kSmiTagMask));
12652 __ j(zero, receiver_not_string_);
Steve Block6ded16b2010-05-10 14:33:55 +010012653
12654 // Fetch the instance type of the receiver into result register.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012655 __ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
12656 __ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010012657 // If the receiver is not a string trigger the non-string case.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012658 __ test(result_, Immediate(kIsNotStringMask));
12659 __ j(not_zero, receiver_not_string_);
Steve Block6ded16b2010-05-10 14:33:55 +010012660
12661 // If the index is non-smi trigger the non-smi case.
12662 ASSERT(kSmiTag == 0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012663 __ test(index_, Immediate(kSmiTagMask));
12664 __ j(not_zero, &index_not_smi_);
12665
12666 // Put smi-tagged index into scratch register.
12667 __ mov(scratch_, index_);
12668 __ bind(&got_smi_index_);
Steve Block6ded16b2010-05-10 14:33:55 +010012669
12670 // Check for index out of range.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012671 __ cmp(scratch_, FieldOperand(object_, String::kLengthOffset));
12672 __ j(above_equal, index_out_of_range_);
Steve Block6ded16b2010-05-10 14:33:55 +010012673
12674 // We need special handling for non-flat strings.
12675 ASSERT(kSeqStringTag == 0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012676 __ test(result_, Immediate(kStringRepresentationMask));
12677 __ j(zero, &flat_string);
Steve Block6ded16b2010-05-10 14:33:55 +010012678
12679 // Handle non-flat strings.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012680 __ test(result_, Immediate(kIsConsStringMask));
12681 __ j(zero, &call_runtime_);
Steve Block6ded16b2010-05-10 14:33:55 +010012682
12683 // ConsString.
12684 // Check whether the right hand side is the empty string (i.e. if
12685 // this is really a flat string in a cons string). If that is not
12686 // the case we would rather go to the runtime system now to flatten
12687 // the string.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012688 __ cmp(FieldOperand(object_, ConsString::kSecondOffset),
12689 Immediate(Factory::empty_string()));
12690 __ j(not_equal, &call_runtime_);
Steve Block6ded16b2010-05-10 14:33:55 +010012691 // Get the first of the two strings and load its instance type.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012692 __ mov(object_, FieldOperand(object_, ConsString::kFirstOffset));
12693 __ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
12694 __ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
12695 // If the first cons component is also non-flat, then go to runtime.
12696 ASSERT(kSeqStringTag == 0);
12697 __ test(result_, Immediate(kStringRepresentationMask));
12698 __ j(not_zero, &call_runtime_);
12699
12700 // Check for 1-byte or 2-byte string.
12701 __ bind(&flat_string);
12702 ASSERT(kAsciiStringTag != 0);
12703 __ test(result_, Immediate(kStringEncodingMask));
12704 __ j(not_zero, &ascii_string);
12705
12706 // 2-byte string.
12707 // Load the 2-byte character code into the result register.
12708 ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
12709 __ movzx_w(result_, FieldOperand(object_,
12710 scratch_, times_1, // Scratch is smi-tagged.
12711 SeqTwoByteString::kHeaderSize));
12712 __ jmp(&got_char_code);
Steve Block6ded16b2010-05-10 14:33:55 +010012713
12714 // ASCII string.
Steve Block6ded16b2010-05-10 14:33:55 +010012715 // Load the byte into the result register.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012716 __ bind(&ascii_string);
12717 __ SmiUntag(scratch_);
12718 __ movzx_b(result_, FieldOperand(object_,
12719 scratch_, times_1,
12720 SeqAsciiString::kHeaderSize));
Steve Block6ded16b2010-05-10 14:33:55 +010012721 __ bind(&got_char_code);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012722 __ SmiTag(result_);
12723 __ bind(&exit_);
Steve Block6ded16b2010-05-10 14:33:55 +010012724}
12725
12726
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012727void StringCharCodeAtGenerator::GenerateSlow(
12728 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
12729 __ Abort("Unexpected fallthrough to CharCodeAt slow case");
Steve Block6ded16b2010-05-10 14:33:55 +010012730
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012731 // Index is not a smi.
12732 __ bind(&index_not_smi_);
12733 // If index is a heap number, try converting it to an integer.
12734 __ CheckMap(index_, Factory::heap_number_map(), index_not_number_, true);
12735 call_helper.BeforeCall(masm);
12736 __ push(object_);
12737 __ push(index_);
12738 __ push(index_); // Consumed by runtime conversion function.
12739 if (index_flags_ == STRING_INDEX_IS_NUMBER) {
12740 __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
12741 } else {
12742 ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
12743 // NumberToSmi discards numbers that are not exact integers.
12744 __ CallRuntime(Runtime::kNumberToSmi, 1);
12745 }
12746 if (!scratch_.is(eax)) {
12747 // Save the conversion result before the pop instructions below
12748 // have a chance to overwrite it.
12749 __ mov(scratch_, eax);
12750 }
12751 __ pop(index_);
12752 __ pop(object_);
12753 // Reload the instance type.
12754 __ mov(result_, FieldOperand(object_, HeapObject::kMapOffset));
12755 __ movzx_b(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
12756 call_helper.AfterCall(masm);
12757 // If index is still not a smi, it must be out of range.
12758 ASSERT(kSmiTag == 0);
12759 __ test(scratch_, Immediate(kSmiTagMask));
12760 __ j(not_zero, index_out_of_range_);
12761 // Otherwise, return to the fast path.
12762 __ jmp(&got_smi_index_);
Steve Block6ded16b2010-05-10 14:33:55 +010012763
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012764 // Call runtime. We get here when the receiver is a string and the
12765 // index is a number, but the code of getting the actual character
12766 // is too complex (e.g., when the string needs to be flattened).
12767 __ bind(&call_runtime_);
12768 call_helper.BeforeCall(masm);
12769 __ push(object_);
12770 __ push(index_);
12771 __ CallRuntime(Runtime::kStringCharCodeAt, 2);
12772 if (!result_.is(eax)) {
12773 __ mov(result_, eax);
12774 }
12775 call_helper.AfterCall(masm);
12776 __ jmp(&exit_);
12777
12778 __ Abort("Unexpected fallthrough from CharCodeAt slow case");
12779}
12780
12781
12782// -------------------------------------------------------------------------
12783// StringCharFromCodeGenerator
12784
12785void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
Steve Block6ded16b2010-05-10 14:33:55 +010012786 // Fast case of Heap::LookupSingleCharacterStringFromCode.
12787 ASSERT(kSmiTag == 0);
12788 ASSERT(kSmiShiftSize == 0);
12789 ASSERT(IsPowerOf2(String::kMaxAsciiCharCode + 1));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012790 __ test(code_,
Steve Block6ded16b2010-05-10 14:33:55 +010012791 Immediate(kSmiTagMask |
12792 ((~String::kMaxAsciiCharCode) << kSmiTagSize)));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012793 __ j(not_zero, &slow_case_, not_taken);
Steve Block6ded16b2010-05-10 14:33:55 +010012794
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012795 __ Set(result_, Immediate(Factory::single_character_string_cache()));
Steve Block6ded16b2010-05-10 14:33:55 +010012796 ASSERT(kSmiTag == 0);
12797 ASSERT(kSmiTagSize == 1);
12798 ASSERT(kSmiShiftSize == 0);
12799 // At this point code register contains smi tagged ascii char code.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012800 __ mov(result_, FieldOperand(result_,
12801 code_, times_half_pointer_size,
12802 FixedArray::kHeaderSize));
12803 __ cmp(result_, Factory::undefined_value());
12804 __ j(equal, &slow_case_, not_taken);
12805 __ bind(&exit_);
12806}
Steve Block6ded16b2010-05-10 14:33:55 +010012807
Steve Block6ded16b2010-05-10 14:33:55 +010012808
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012809void StringCharFromCodeGenerator::GenerateSlow(
12810 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
12811 __ Abort("Unexpected fallthrough to CharFromCode slow case");
12812
12813 __ bind(&slow_case_);
12814 call_helper.BeforeCall(masm);
12815 __ push(code_);
12816 __ CallRuntime(Runtime::kCharFromCode, 1);
12817 if (!result_.is(eax)) {
12818 __ mov(result_, eax);
Steve Block6ded16b2010-05-10 14:33:55 +010012819 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012820 call_helper.AfterCall(masm);
12821 __ jmp(&exit_);
12822
12823 __ Abort("Unexpected fallthrough from CharFromCode slow case");
12824}
12825
12826
12827// -------------------------------------------------------------------------
12828// StringCharAtGenerator
12829
12830void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) {
12831 char_code_at_generator_.GenerateFast(masm);
12832 char_from_code_generator_.GenerateFast(masm);
12833}
12834
12835
12836void StringCharAtGenerator::GenerateSlow(
12837 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
12838 char_code_at_generator_.GenerateSlow(masm, call_helper);
12839 char_from_code_generator_.GenerateSlow(masm, call_helper);
Steve Blocka7e24c12009-10-30 11:49:00 +000012840}
12841
Steve Blockd0582a62009-12-15 09:54:21 +000012842
12843void StringAddStub::Generate(MacroAssembler* masm) {
12844 Label string_add_runtime;
12845
12846 // Load the two arguments.
12847 __ mov(eax, Operand(esp, 2 * kPointerSize)); // First argument.
12848 __ mov(edx, Operand(esp, 1 * kPointerSize)); // Second argument.
12849
12850 // Make sure that both arguments are strings if not known in advance.
12851 if (string_check_) {
12852 __ test(eax, Immediate(kSmiTagMask));
12853 __ j(zero, &string_add_runtime);
12854 __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, ebx);
12855 __ j(above_equal, &string_add_runtime);
12856
12857 // First argument is a a string, test second.
12858 __ test(edx, Immediate(kSmiTagMask));
12859 __ j(zero, &string_add_runtime);
12860 __ CmpObjectType(edx, FIRST_NONSTRING_TYPE, ebx);
12861 __ j(above_equal, &string_add_runtime);
12862 }
12863
12864 // Both arguments are strings.
12865 // eax: first string
12866 // edx: second string
12867 // Check if either of the strings are empty. In that case return the other.
12868 Label second_not_zero_length, both_not_zero_length;
12869 __ mov(ecx, FieldOperand(edx, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010012870 ASSERT(kSmiTag == 0);
Steve Blockd0582a62009-12-15 09:54:21 +000012871 __ test(ecx, Operand(ecx));
12872 __ j(not_zero, &second_not_zero_length);
12873 // Second string is empty, result is first string which is already in eax.
12874 __ IncrementCounter(&Counters::string_add_native, 1);
12875 __ ret(2 * kPointerSize);
12876 __ bind(&second_not_zero_length);
12877 __ mov(ebx, FieldOperand(eax, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010012878 ASSERT(kSmiTag == 0);
Steve Blockd0582a62009-12-15 09:54:21 +000012879 __ test(ebx, Operand(ebx));
12880 __ j(not_zero, &both_not_zero_length);
12881 // First string is empty, result is second string which is in edx.
12882 __ mov(eax, edx);
12883 __ IncrementCounter(&Counters::string_add_native, 1);
12884 __ ret(2 * kPointerSize);
12885
12886 // Both strings are non-empty.
12887 // eax: first string
Steve Block6ded16b2010-05-10 14:33:55 +010012888 // ebx: length of first string as a smi
12889 // ecx: length of second string as a smi
Steve Blockd0582a62009-12-15 09:54:21 +000012890 // edx: second string
12891 // Look at the length of the result of adding the two strings.
Andrei Popescu402d9372010-02-26 13:31:12 +000012892 Label string_add_flat_result, longer_than_two;
Steve Blockd0582a62009-12-15 09:54:21 +000012893 __ bind(&both_not_zero_length);
12894 __ add(ebx, Operand(ecx));
Steve Block6ded16b2010-05-10 14:33:55 +010012895 ASSERT(Smi::kMaxValue == String::kMaxLength);
12896 // Handle exceptionally long strings in the runtime system.
12897 __ j(overflow, &string_add_runtime);
Steve Blockd0582a62009-12-15 09:54:21 +000012898 // Use the runtime system when adding two one character strings, as it
12899 // contains optimizations for this specific case using the symbol table.
Steve Block6ded16b2010-05-10 14:33:55 +010012900 __ cmp(Operand(ebx), Immediate(Smi::FromInt(2)));
Andrei Popescu402d9372010-02-26 13:31:12 +000012901 __ j(not_equal, &longer_than_two);
12902
12903 // Check that both strings are non-external ascii strings.
12904 __ JumpIfNotBothSequentialAsciiStrings(eax, edx, ebx, ecx,
12905 &string_add_runtime);
12906
12907 // Get the two characters forming the sub string.
12908 __ movzx_b(ebx, FieldOperand(eax, SeqAsciiString::kHeaderSize));
12909 __ movzx_b(ecx, FieldOperand(edx, SeqAsciiString::kHeaderSize));
12910
12911 // Try to lookup two character string in symbol table. If it is not found
12912 // just allocate a new one.
12913 Label make_two_character_string, make_flat_ascii_string;
Steve Block6ded16b2010-05-10 14:33:55 +010012914 StringHelper::GenerateTwoCharacterSymbolTableProbe(
12915 masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
12916 __ IncrementCounter(&Counters::string_add_native, 1);
Andrei Popescu402d9372010-02-26 13:31:12 +000012917 __ ret(2 * kPointerSize);
12918
12919 __ bind(&make_two_character_string);
Steve Block6ded16b2010-05-10 14:33:55 +010012920 __ Set(ebx, Immediate(Smi::FromInt(2)));
Andrei Popescu402d9372010-02-26 13:31:12 +000012921 __ jmp(&make_flat_ascii_string);
12922
12923 __ bind(&longer_than_two);
Steve Blockd0582a62009-12-15 09:54:21 +000012924 // Check if resulting string will be flat.
Steve Block6ded16b2010-05-10 14:33:55 +010012925 __ cmp(Operand(ebx), Immediate(Smi::FromInt(String::kMinNonFlatLength)));
Steve Blockd0582a62009-12-15 09:54:21 +000012926 __ j(below, &string_add_flat_result);
Steve Blockd0582a62009-12-15 09:54:21 +000012927
12928 // If result is not supposed to be flat allocate a cons string object. If both
12929 // strings are ascii the result is an ascii cons string.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010012930 Label non_ascii, allocated, ascii_data;
Steve Blockd0582a62009-12-15 09:54:21 +000012931 __ mov(edi, FieldOperand(eax, HeapObject::kMapOffset));
12932 __ movzx_b(ecx, FieldOperand(edi, Map::kInstanceTypeOffset));
12933 __ mov(edi, FieldOperand(edx, HeapObject::kMapOffset));
12934 __ movzx_b(edi, FieldOperand(edi, Map::kInstanceTypeOffset));
12935 __ and_(ecx, Operand(edi));
Leon Clarkee46be812010-01-19 14:06:41 +000012936 ASSERT(kStringEncodingMask == kAsciiStringTag);
Steve Blockd0582a62009-12-15 09:54:21 +000012937 __ test(ecx, Immediate(kAsciiStringTag));
12938 __ j(zero, &non_ascii);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010012939 __ bind(&ascii_data);
Steve Blockd0582a62009-12-15 09:54:21 +000012940 // Allocate an acsii cons string.
12941 __ AllocateAsciiConsString(ecx, edi, no_reg, &string_add_runtime);
12942 __ bind(&allocated);
12943 // Fill the fields of the cons string.
Steve Block6ded16b2010-05-10 14:33:55 +010012944 if (FLAG_debug_code) __ AbortIfNotSmi(ebx);
Steve Blockd0582a62009-12-15 09:54:21 +000012945 __ mov(FieldOperand(ecx, ConsString::kLengthOffset), ebx);
12946 __ mov(FieldOperand(ecx, ConsString::kHashFieldOffset),
12947 Immediate(String::kEmptyHashField));
12948 __ mov(FieldOperand(ecx, ConsString::kFirstOffset), eax);
12949 __ mov(FieldOperand(ecx, ConsString::kSecondOffset), edx);
12950 __ mov(eax, ecx);
12951 __ IncrementCounter(&Counters::string_add_native, 1);
12952 __ ret(2 * kPointerSize);
12953 __ bind(&non_ascii);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010012954 // At least one of the strings is two-byte. Check whether it happens
12955 // to contain only ascii characters.
12956 // ecx: first instance type AND second instance type.
12957 // edi: second instance type.
12958 __ test(ecx, Immediate(kAsciiDataHintMask));
12959 __ j(not_zero, &ascii_data);
12960 __ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
12961 __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
12962 __ xor_(edi, Operand(ecx));
12963 ASSERT(kAsciiStringTag != 0 && kAsciiDataHintTag != 0);
12964 __ and_(edi, kAsciiStringTag | kAsciiDataHintTag);
12965 __ cmp(edi, kAsciiStringTag | kAsciiDataHintTag);
12966 __ j(equal, &ascii_data);
Steve Blockd0582a62009-12-15 09:54:21 +000012967 // Allocate a two byte cons string.
12968 __ AllocateConsString(ecx, edi, no_reg, &string_add_runtime);
12969 __ jmp(&allocated);
12970
12971 // Handle creating a flat result. First check that both strings are not
12972 // external strings.
12973 // eax: first string
Steve Block6ded16b2010-05-10 14:33:55 +010012974 // ebx: length of resulting flat string as a smi
Steve Blockd0582a62009-12-15 09:54:21 +000012975 // edx: second string
12976 __ bind(&string_add_flat_result);
12977 __ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
12978 __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
12979 __ and_(ecx, kStringRepresentationMask);
12980 __ cmp(ecx, kExternalStringTag);
12981 __ j(equal, &string_add_runtime);
12982 __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
12983 __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset));
12984 __ and_(ecx, kStringRepresentationMask);
12985 __ cmp(ecx, kExternalStringTag);
12986 __ j(equal, &string_add_runtime);
12987 // Now check if both strings are ascii strings.
12988 // eax: first string
Steve Block6ded16b2010-05-10 14:33:55 +010012989 // ebx: length of resulting flat string as a smi
Steve Blockd0582a62009-12-15 09:54:21 +000012990 // edx: second string
12991 Label non_ascii_string_add_flat_result;
Leon Clarkee46be812010-01-19 14:06:41 +000012992 ASSERT(kStringEncodingMask == kAsciiStringTag);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012993 __ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset));
12994 __ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
Steve Blockd0582a62009-12-15 09:54:21 +000012995 __ j(zero, &non_ascii_string_add_flat_result);
12996 __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010012997 __ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
Steve Blockd0582a62009-12-15 09:54:21 +000012998 __ j(zero, &string_add_runtime);
Andrei Popescu402d9372010-02-26 13:31:12 +000012999
13000 __ bind(&make_flat_ascii_string);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010013001 // Both strings are ascii strings. As they are short they are both flat.
Steve Block6ded16b2010-05-10 14:33:55 +010013002 // ebx: length of resulting flat string as a smi
13003 __ SmiUntag(ebx);
Steve Blockd0582a62009-12-15 09:54:21 +000013004 __ AllocateAsciiString(eax, ebx, ecx, edx, edi, &string_add_runtime);
13005 // eax: result string
13006 __ mov(ecx, eax);
13007 // Locate first character of result.
13008 __ add(Operand(ecx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13009 // Load first argument and locate first character.
13010 __ mov(edx, Operand(esp, 2 * kPointerSize));
13011 __ mov(edi, FieldOperand(edx, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010013012 __ SmiUntag(edi);
Steve Blockd0582a62009-12-15 09:54:21 +000013013 __ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13014 // eax: result string
13015 // ecx: first character of result
13016 // edx: first char of first argument
13017 // edi: length of first argument
Steve Block6ded16b2010-05-10 14:33:55 +010013018 StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
Steve Blockd0582a62009-12-15 09:54:21 +000013019 // Load second argument and locate first character.
13020 __ mov(edx, Operand(esp, 1 * kPointerSize));
13021 __ mov(edi, FieldOperand(edx, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010013022 __ SmiUntag(edi);
Steve Blockd0582a62009-12-15 09:54:21 +000013023 __ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13024 // eax: result string
13025 // ecx: next character of result
13026 // edx: first char of second argument
13027 // edi: length of second argument
Steve Block6ded16b2010-05-10 14:33:55 +010013028 StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, true);
Steve Blockd0582a62009-12-15 09:54:21 +000013029 __ IncrementCounter(&Counters::string_add_native, 1);
13030 __ ret(2 * kPointerSize);
13031
13032 // Handle creating a flat two byte result.
13033 // eax: first string - known to be two byte
Steve Block6ded16b2010-05-10 14:33:55 +010013034 // ebx: length of resulting flat string as a smi
Steve Blockd0582a62009-12-15 09:54:21 +000013035 // edx: second string
13036 __ bind(&non_ascii_string_add_flat_result);
13037 __ mov(ecx, FieldOperand(edx, HeapObject::kMapOffset));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010013038 __ test_b(FieldOperand(ecx, Map::kInstanceTypeOffset), kAsciiStringTag);
Steve Blockd0582a62009-12-15 09:54:21 +000013039 __ j(not_zero, &string_add_runtime);
13040 // Both strings are two byte strings. As they are short they are both
13041 // flat.
Steve Block6ded16b2010-05-10 14:33:55 +010013042 __ SmiUntag(ebx);
Steve Blockd0582a62009-12-15 09:54:21 +000013043 __ AllocateTwoByteString(eax, ebx, ecx, edx, edi, &string_add_runtime);
13044 // eax: result string
13045 __ mov(ecx, eax);
13046 // Locate first character of result.
13047 __ add(Operand(ecx),
13048 Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
13049 // Load first argument and locate first character.
13050 __ mov(edx, Operand(esp, 2 * kPointerSize));
13051 __ mov(edi, FieldOperand(edx, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010013052 __ SmiUntag(edi);
Steve Blockd0582a62009-12-15 09:54:21 +000013053 __ add(Operand(edx),
13054 Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
13055 // eax: result string
13056 // ecx: first character of result
13057 // edx: first char of first argument
13058 // edi: length of first argument
Steve Block6ded16b2010-05-10 14:33:55 +010013059 StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
Steve Blockd0582a62009-12-15 09:54:21 +000013060 // Load second argument and locate first character.
13061 __ mov(edx, Operand(esp, 1 * kPointerSize));
13062 __ mov(edi, FieldOperand(edx, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +010013063 __ SmiUntag(edi);
Steve Blockd0582a62009-12-15 09:54:21 +000013064 __ add(Operand(edx), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13065 // eax: result string
13066 // ecx: next character of result
13067 // edx: first char of second argument
13068 // edi: length of second argument
Steve Block6ded16b2010-05-10 14:33:55 +010013069 StringHelper::GenerateCopyCharacters(masm, ecx, edx, edi, ebx, false);
Steve Blockd0582a62009-12-15 09:54:21 +000013070 __ IncrementCounter(&Counters::string_add_native, 1);
13071 __ ret(2 * kPointerSize);
13072
13073 // Just jump to runtime to add the two strings.
13074 __ bind(&string_add_runtime);
Steve Block6ded16b2010-05-10 14:33:55 +010013075 __ TailCallRuntime(Runtime::kStringAdd, 2, 1);
Steve Blockd0582a62009-12-15 09:54:21 +000013076}
13077
13078
Steve Block6ded16b2010-05-10 14:33:55 +010013079void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
13080 Register dest,
13081 Register src,
13082 Register count,
13083 Register scratch,
13084 bool ascii) {
Steve Blockd0582a62009-12-15 09:54:21 +000013085 Label loop;
13086 __ bind(&loop);
13087 // This loop just copies one character at a time, as it is only used for very
13088 // short strings.
13089 if (ascii) {
13090 __ mov_b(scratch, Operand(src, 0));
13091 __ mov_b(Operand(dest, 0), scratch);
13092 __ add(Operand(src), Immediate(1));
13093 __ add(Operand(dest), Immediate(1));
13094 } else {
13095 __ mov_w(scratch, Operand(src, 0));
13096 __ mov_w(Operand(dest, 0), scratch);
13097 __ add(Operand(src), Immediate(2));
13098 __ add(Operand(dest), Immediate(2));
13099 }
13100 __ sub(Operand(count), Immediate(1));
13101 __ j(not_zero, &loop);
13102}
13103
13104
Steve Block6ded16b2010-05-10 14:33:55 +010013105void StringHelper::GenerateCopyCharactersREP(MacroAssembler* masm,
13106 Register dest,
13107 Register src,
13108 Register count,
13109 Register scratch,
13110 bool ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +000013111 // Copy characters using rep movs of doublewords. Align destination on 4 byte
13112 // boundary before starting rep movs. Copy remaining characters after running
13113 // rep movs.
13114 ASSERT(dest.is(edi)); // rep movs destination
13115 ASSERT(src.is(esi)); // rep movs source
13116 ASSERT(count.is(ecx)); // rep movs count
13117 ASSERT(!scratch.is(dest));
13118 ASSERT(!scratch.is(src));
13119 ASSERT(!scratch.is(count));
13120
13121 // Nothing to do for zero characters.
13122 Label done;
13123 __ test(count, Operand(count));
13124 __ j(zero, &done);
13125
13126 // Make count the number of bytes to copy.
13127 if (!ascii) {
13128 __ shl(count, 1);
13129 }
13130
13131 // Don't enter the rep movs if there are less than 4 bytes to copy.
13132 Label last_bytes;
13133 __ test(count, Immediate(~3));
13134 __ j(zero, &last_bytes);
13135
13136 // Copy from edi to esi using rep movs instruction.
13137 __ mov(scratch, count);
13138 __ sar(count, 2); // Number of doublewords to copy.
Steve Block6ded16b2010-05-10 14:33:55 +010013139 __ cld();
Leon Clarkee46be812010-01-19 14:06:41 +000013140 __ rep_movs();
13141
13142 // Find number of bytes left.
13143 __ mov(count, scratch);
13144 __ and_(count, 3);
13145
13146 // Check if there are more bytes to copy.
13147 __ bind(&last_bytes);
13148 __ test(count, Operand(count));
13149 __ j(zero, &done);
13150
13151 // Copy remaining characters.
13152 Label loop;
13153 __ bind(&loop);
13154 __ mov_b(scratch, Operand(src, 0));
13155 __ mov_b(Operand(dest, 0), scratch);
13156 __ add(Operand(src), Immediate(1));
13157 __ add(Operand(dest), Immediate(1));
13158 __ sub(Operand(count), Immediate(1));
13159 __ j(not_zero, &loop);
13160
13161 __ bind(&done);
13162}
13163
13164
Steve Block6ded16b2010-05-10 14:33:55 +010013165void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
13166 Register c1,
13167 Register c2,
13168 Register scratch1,
13169 Register scratch2,
13170 Register scratch3,
13171 Label* not_found) {
Andrei Popescu402d9372010-02-26 13:31:12 +000013172 // Register scratch3 is the general scratch register in this function.
13173 Register scratch = scratch3;
13174
13175 // Make sure that both characters are not digits as such strings has a
13176 // different hash algorithm. Don't try to look for these in the symbol table.
13177 Label not_array_index;
13178 __ mov(scratch, c1);
13179 __ sub(Operand(scratch), Immediate(static_cast<int>('0')));
13180 __ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
13181 __ j(above, &not_array_index);
13182 __ mov(scratch, c2);
13183 __ sub(Operand(scratch), Immediate(static_cast<int>('0')));
13184 __ cmp(Operand(scratch), Immediate(static_cast<int>('9' - '0')));
13185 __ j(below_equal, not_found);
13186
13187 __ bind(&not_array_index);
13188 // Calculate the two character string hash.
13189 Register hash = scratch1;
13190 GenerateHashInit(masm, hash, c1, scratch);
13191 GenerateHashAddCharacter(masm, hash, c2, scratch);
13192 GenerateHashGetHash(masm, hash, scratch);
13193
13194 // Collect the two characters in a register.
13195 Register chars = c1;
13196 __ shl(c2, kBitsPerByte);
13197 __ or_(chars, Operand(c2));
13198
13199 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
13200 // hash: hash of two character string.
13201
13202 // Load the symbol table.
13203 Register symbol_table = c2;
13204 ExternalReference roots_address = ExternalReference::roots_address();
13205 __ mov(scratch, Immediate(Heap::kSymbolTableRootIndex));
13206 __ mov(symbol_table,
13207 Operand::StaticArray(scratch, times_pointer_size, roots_address));
13208
13209 // Calculate capacity mask from the symbol table capacity.
13210 Register mask = scratch2;
Steve Block6ded16b2010-05-10 14:33:55 +010013211 __ mov(mask, FieldOperand(symbol_table, SymbolTable::kCapacityOffset));
Andrei Popescu402d9372010-02-26 13:31:12 +000013212 __ SmiUntag(mask);
13213 __ sub(Operand(mask), Immediate(1));
13214
13215 // Registers
13216 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
13217 // hash: hash of two character string
13218 // symbol_table: symbol table
13219 // mask: capacity mask
13220 // scratch: -
13221
13222 // Perform a number of probes in the symbol table.
13223 static const int kProbes = 4;
13224 Label found_in_symbol_table;
13225 Label next_probe[kProbes], next_probe_pop_mask[kProbes];
13226 for (int i = 0; i < kProbes; i++) {
13227 // Calculate entry in symbol table.
13228 __ mov(scratch, hash);
13229 if (i > 0) {
13230 __ add(Operand(scratch), Immediate(SymbolTable::GetProbeOffset(i)));
13231 }
13232 __ and_(scratch, Operand(mask));
13233
13234 // Load the entry from the symble table.
13235 Register candidate = scratch; // Scratch register contains candidate.
Steve Block6ded16b2010-05-10 14:33:55 +010013236 ASSERT_EQ(1, SymbolTable::kEntrySize);
Andrei Popescu402d9372010-02-26 13:31:12 +000013237 __ mov(candidate,
13238 FieldOperand(symbol_table,
13239 scratch,
13240 times_pointer_size,
Steve Block6ded16b2010-05-10 14:33:55 +010013241 SymbolTable::kElementsStartOffset));
Andrei Popescu402d9372010-02-26 13:31:12 +000013242
13243 // If entry is undefined no string with this hash can be found.
13244 __ cmp(candidate, Factory::undefined_value());
13245 __ j(equal, not_found);
13246
13247 // If length is not 2 the string is not a candidate.
Steve Block6ded16b2010-05-10 14:33:55 +010013248 __ cmp(FieldOperand(candidate, String::kLengthOffset),
13249 Immediate(Smi::FromInt(2)));
Andrei Popescu402d9372010-02-26 13:31:12 +000013250 __ j(not_equal, &next_probe[i]);
13251
13252 // As we are out of registers save the mask on the stack and use that
13253 // register as a temporary.
13254 __ push(mask);
13255 Register temp = mask;
13256
13257 // Check that the candidate is a non-external ascii string.
13258 __ mov(temp, FieldOperand(candidate, HeapObject::kMapOffset));
13259 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
13260 __ JumpIfInstanceTypeIsNotSequentialAscii(
13261 temp, temp, &next_probe_pop_mask[i]);
13262
13263 // Check if the two characters match.
13264 __ mov(temp, FieldOperand(candidate, SeqAsciiString::kHeaderSize));
13265 __ and_(temp, 0x0000ffff);
13266 __ cmp(chars, Operand(temp));
13267 __ j(equal, &found_in_symbol_table);
13268 __ bind(&next_probe_pop_mask[i]);
13269 __ pop(mask);
13270 __ bind(&next_probe[i]);
13271 }
13272
13273 // No matching 2 character string found by probing.
13274 __ jmp(not_found);
13275
13276 // Scratch register contains result when we fall through to here.
13277 Register result = scratch;
13278 __ bind(&found_in_symbol_table);
13279 __ pop(mask); // Pop temporally saved mask from the stack.
13280 if (!result.is(eax)) {
13281 __ mov(eax, result);
13282 }
13283}
13284
13285
Steve Block6ded16b2010-05-10 14:33:55 +010013286void StringHelper::GenerateHashInit(MacroAssembler* masm,
13287 Register hash,
13288 Register character,
13289 Register scratch) {
Andrei Popescu402d9372010-02-26 13:31:12 +000013290 // hash = character + (character << 10);
13291 __ mov(hash, character);
13292 __ shl(hash, 10);
13293 __ add(hash, Operand(character));
13294 // hash ^= hash >> 6;
13295 __ mov(scratch, hash);
13296 __ sar(scratch, 6);
13297 __ xor_(hash, Operand(scratch));
13298}
13299
13300
Steve Block6ded16b2010-05-10 14:33:55 +010013301void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
13302 Register hash,
13303 Register character,
13304 Register scratch) {
Andrei Popescu402d9372010-02-26 13:31:12 +000013305 // hash += character;
13306 __ add(hash, Operand(character));
13307 // hash += hash << 10;
13308 __ mov(scratch, hash);
13309 __ shl(scratch, 10);
13310 __ add(hash, Operand(scratch));
13311 // hash ^= hash >> 6;
13312 __ mov(scratch, hash);
13313 __ sar(scratch, 6);
13314 __ xor_(hash, Operand(scratch));
13315}
13316
13317
Steve Block6ded16b2010-05-10 14:33:55 +010013318void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
13319 Register hash,
13320 Register scratch) {
Andrei Popescu402d9372010-02-26 13:31:12 +000013321 // hash += hash << 3;
13322 __ mov(scratch, hash);
13323 __ shl(scratch, 3);
13324 __ add(hash, Operand(scratch));
13325 // hash ^= hash >> 11;
13326 __ mov(scratch, hash);
13327 __ sar(scratch, 11);
13328 __ xor_(hash, Operand(scratch));
13329 // hash += hash << 15;
13330 __ mov(scratch, hash);
13331 __ shl(scratch, 15);
13332 __ add(hash, Operand(scratch));
13333
13334 // if (hash == 0) hash = 27;
13335 Label hash_not_zero;
13336 __ test(hash, Operand(hash));
13337 __ j(not_zero, &hash_not_zero);
13338 __ mov(hash, Immediate(27));
13339 __ bind(&hash_not_zero);
13340}
13341
13342
Leon Clarkee46be812010-01-19 14:06:41 +000013343void SubStringStub::Generate(MacroAssembler* masm) {
13344 Label runtime;
13345
13346 // Stack frame on entry.
13347 // esp[0]: return address
13348 // esp[4]: to
13349 // esp[8]: from
13350 // esp[12]: string
13351
13352 // Make sure first argument is a string.
13353 __ mov(eax, Operand(esp, 3 * kPointerSize));
13354 ASSERT_EQ(0, kSmiTag);
13355 __ test(eax, Immediate(kSmiTagMask));
13356 __ j(zero, &runtime);
13357 Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
13358 __ j(NegateCondition(is_string), &runtime);
13359
13360 // eax: string
13361 // ebx: instance type
13362 // Calculate length of sub string using the smi values.
Andrei Popescu402d9372010-02-26 13:31:12 +000013363 Label result_longer_than_two;
13364 __ mov(ecx, Operand(esp, 1 * kPointerSize)); // To index.
Leon Clarkee46be812010-01-19 14:06:41 +000013365 __ test(ecx, Immediate(kSmiTagMask));
13366 __ j(not_zero, &runtime);
Andrei Popescu402d9372010-02-26 13:31:12 +000013367 __ mov(edx, Operand(esp, 2 * kPointerSize)); // From index.
Leon Clarkee46be812010-01-19 14:06:41 +000013368 __ test(edx, Immediate(kSmiTagMask));
13369 __ j(not_zero, &runtime);
13370 __ sub(ecx, Operand(edx));
Steve Block8defd9f2010-07-08 12:39:36 +010013371 __ cmp(ecx, FieldOperand(eax, String::kLengthOffset));
13372 Label return_eax;
13373 __ j(equal, &return_eax);
Andrei Popescu402d9372010-02-26 13:31:12 +000013374 // Special handling of sub-strings of length 1 and 2. One character strings
13375 // are handled in the runtime system (looked up in the single character
13376 // cache). Two character strings are looked for in the symbol cache.
Leon Clarkee46be812010-01-19 14:06:41 +000013377 __ SmiUntag(ecx); // Result length is no longer smi.
13378 __ cmp(ecx, 2);
Andrei Popescu402d9372010-02-26 13:31:12 +000013379 __ j(greater, &result_longer_than_two);
13380 __ j(less, &runtime);
Leon Clarkee46be812010-01-19 14:06:41 +000013381
Andrei Popescu402d9372010-02-26 13:31:12 +000013382 // Sub string of length 2 requested.
13383 // eax: string
13384 // ebx: instance type
13385 // ecx: sub string length (value is 2)
13386 // edx: from index (smi)
13387 __ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &runtime);
13388
13389 // Get the two characters forming the sub string.
13390 __ SmiUntag(edx); // From index is no longer smi.
13391 __ movzx_b(ebx, FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize));
13392 __ movzx_b(ecx,
13393 FieldOperand(eax, edx, times_1, SeqAsciiString::kHeaderSize + 1));
13394
13395 // Try to lookup two character string in symbol table.
13396 Label make_two_character_string;
Steve Block6ded16b2010-05-10 14:33:55 +010013397 StringHelper::GenerateTwoCharacterSymbolTableProbe(
13398 masm, ebx, ecx, eax, edx, edi, &make_two_character_string);
13399 __ ret(3 * kPointerSize);
Andrei Popescu402d9372010-02-26 13:31:12 +000013400
13401 __ bind(&make_two_character_string);
13402 // Setup registers for allocating the two character string.
13403 __ mov(eax, Operand(esp, 3 * kPointerSize));
13404 __ mov(ebx, FieldOperand(eax, HeapObject::kMapOffset));
13405 __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
13406 __ Set(ecx, Immediate(2));
13407
13408 __ bind(&result_longer_than_two);
Leon Clarkee46be812010-01-19 14:06:41 +000013409 // eax: string
13410 // ebx: instance type
13411 // ecx: result string length
13412 // Check for flat ascii string
13413 Label non_ascii_flat;
Andrei Popescu402d9372010-02-26 13:31:12 +000013414 __ JumpIfInstanceTypeIsNotSequentialAscii(ebx, ebx, &non_ascii_flat);
Leon Clarkee46be812010-01-19 14:06:41 +000013415
13416 // Allocate the result.
13417 __ AllocateAsciiString(eax, ecx, ebx, edx, edi, &runtime);
13418
13419 // eax: result string
13420 // ecx: result string length
13421 __ mov(edx, esi); // esi used by following code.
13422 // Locate first character of result.
13423 __ mov(edi, eax);
13424 __ add(Operand(edi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13425 // Load string argument and locate character of sub string start.
13426 __ mov(esi, Operand(esp, 3 * kPointerSize));
13427 __ add(Operand(esi), Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
13428 __ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
13429 __ SmiUntag(ebx);
13430 __ add(esi, Operand(ebx));
13431
13432 // eax: result string
13433 // ecx: result length
13434 // edx: original value of esi
13435 // edi: first character of result
13436 // esi: character of sub string start
Steve Block6ded16b2010-05-10 14:33:55 +010013437 StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, true);
Leon Clarkee46be812010-01-19 14:06:41 +000013438 __ mov(esi, edx); // Restore esi.
13439 __ IncrementCounter(&Counters::sub_string_native, 1);
13440 __ ret(3 * kPointerSize);
13441
13442 __ bind(&non_ascii_flat);
13443 // eax: string
13444 // ebx: instance type & kStringRepresentationMask | kStringEncodingMask
13445 // ecx: result string length
13446 // Check for flat two byte string
13447 __ cmp(ebx, kSeqStringTag | kTwoByteStringTag);
13448 __ j(not_equal, &runtime);
13449
13450 // Allocate the result.
13451 __ AllocateTwoByteString(eax, ecx, ebx, edx, edi, &runtime);
13452
13453 // eax: result string
13454 // ecx: result string length
13455 __ mov(edx, esi); // esi used by following code.
13456 // Locate first character of result.
13457 __ mov(edi, eax);
13458 __ add(Operand(edi),
13459 Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
13460 // Load string argument and locate character of sub string start.
13461 __ mov(esi, Operand(esp, 3 * kPointerSize));
Andrei Popescu31002712010-02-23 13:46:05 +000013462 __ add(Operand(esi),
13463 Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
Leon Clarkee46be812010-01-19 14:06:41 +000013464 __ mov(ebx, Operand(esp, 2 * kPointerSize)); // from
13465 // As from is a smi it is 2 times the value which matches the size of a two
13466 // byte character.
13467 ASSERT_EQ(0, kSmiTag);
13468 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
13469 __ add(esi, Operand(ebx));
13470
13471 // eax: result string
13472 // ecx: result length
13473 // edx: original value of esi
13474 // edi: first character of result
13475 // esi: character of sub string start
Steve Block6ded16b2010-05-10 14:33:55 +010013476 StringHelper::GenerateCopyCharactersREP(masm, edi, esi, ecx, ebx, false);
Leon Clarkee46be812010-01-19 14:06:41 +000013477 __ mov(esi, edx); // Restore esi.
Steve Block8defd9f2010-07-08 12:39:36 +010013478
13479 __ bind(&return_eax);
Leon Clarkee46be812010-01-19 14:06:41 +000013480 __ IncrementCounter(&Counters::sub_string_native, 1);
13481 __ ret(3 * kPointerSize);
13482
13483 // Just jump to runtime to create the sub string.
13484 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +010013485 __ TailCallRuntime(Runtime::kSubString, 3, 1);
Leon Clarkee46be812010-01-19 14:06:41 +000013486}
13487
13488
13489void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
13490 Register left,
13491 Register right,
13492 Register scratch1,
13493 Register scratch2,
13494 Register scratch3) {
Leon Clarked91b9f72010-01-27 17:25:45 +000013495 Label result_not_equal;
13496 Label result_greater;
13497 Label compare_lengths;
Steve Block6ded16b2010-05-10 14:33:55 +010013498
13499 __ IncrementCounter(&Counters::string_compare_native, 1);
13500
Leon Clarked91b9f72010-01-27 17:25:45 +000013501 // Find minimum length.
13502 Label left_shorter;
Leon Clarkee46be812010-01-19 14:06:41 +000013503 __ mov(scratch1, FieldOperand(left, String::kLengthOffset));
Leon Clarked91b9f72010-01-27 17:25:45 +000013504 __ mov(scratch3, scratch1);
13505 __ sub(scratch3, FieldOperand(right, String::kLengthOffset));
13506
13507 Register length_delta = scratch3;
13508
13509 __ j(less_equal, &left_shorter);
13510 // Right string is shorter. Change scratch1 to be length of right string.
13511 __ sub(scratch1, Operand(length_delta));
13512 __ bind(&left_shorter);
13513
13514 Register min_length = scratch1;
13515
13516 // If either length is zero, just compare lengths.
13517 __ test(min_length, Operand(min_length));
13518 __ j(zero, &compare_lengths);
13519
13520 // Change index to run from -min_length to -1 by adding min_length
13521 // to string start. This means that loop ends when index reaches zero,
13522 // which doesn't need an additional compare.
Steve Block6ded16b2010-05-10 14:33:55 +010013523 __ SmiUntag(min_length);
Leon Clarked91b9f72010-01-27 17:25:45 +000013524 __ lea(left,
13525 FieldOperand(left,
13526 min_length, times_1,
13527 SeqAsciiString::kHeaderSize));
13528 __ lea(right,
13529 FieldOperand(right,
13530 min_length, times_1,
13531 SeqAsciiString::kHeaderSize));
13532 __ neg(min_length);
13533
13534 Register index = min_length; // index = -min_length;
13535
13536 {
13537 // Compare loop.
13538 Label loop;
13539 __ bind(&loop);
13540 // Compare characters.
13541 __ mov_b(scratch2, Operand(left, index, times_1, 0));
13542 __ cmpb(scratch2, Operand(right, index, times_1, 0));
13543 __ j(not_equal, &result_not_equal);
13544 __ add(Operand(index), Immediate(1));
13545 __ j(not_zero, &loop);
Leon Clarkee46be812010-01-19 14:06:41 +000013546 }
13547
Leon Clarked91b9f72010-01-27 17:25:45 +000013548 // Compare lengths - strings up to min-length are equal.
Leon Clarkee46be812010-01-19 14:06:41 +000013549 __ bind(&compare_lengths);
Leon Clarked91b9f72010-01-27 17:25:45 +000013550 __ test(length_delta, Operand(length_delta));
Leon Clarkee46be812010-01-19 14:06:41 +000013551 __ j(not_zero, &result_not_equal);
13552
13553 // Result is EQUAL.
13554 ASSERT_EQ(0, EQUAL);
13555 ASSERT_EQ(0, kSmiTag);
Leon Clarked91b9f72010-01-27 17:25:45 +000013556 __ Set(eax, Immediate(Smi::FromInt(EQUAL)));
Leon Clarkee46be812010-01-19 14:06:41 +000013557 __ ret(2 * kPointerSize);
Leon Clarked91b9f72010-01-27 17:25:45 +000013558
Leon Clarkee46be812010-01-19 14:06:41 +000013559 __ bind(&result_not_equal);
13560 __ j(greater, &result_greater);
13561
13562 // Result is LESS.
Leon Clarked91b9f72010-01-27 17:25:45 +000013563 __ Set(eax, Immediate(Smi::FromInt(LESS)));
Leon Clarkee46be812010-01-19 14:06:41 +000013564 __ ret(2 * kPointerSize);
13565
13566 // Result is GREATER.
13567 __ bind(&result_greater);
Leon Clarked91b9f72010-01-27 17:25:45 +000013568 __ Set(eax, Immediate(Smi::FromInt(GREATER)));
Leon Clarkee46be812010-01-19 14:06:41 +000013569 __ ret(2 * kPointerSize);
13570}
13571
13572
13573void StringCompareStub::Generate(MacroAssembler* masm) {
13574 Label runtime;
13575
13576 // Stack frame on entry.
13577 // esp[0]: return address
13578 // esp[4]: right string
13579 // esp[8]: left string
13580
13581 __ mov(edx, Operand(esp, 2 * kPointerSize)); // left
13582 __ mov(eax, Operand(esp, 1 * kPointerSize)); // right
13583
13584 Label not_same;
13585 __ cmp(edx, Operand(eax));
13586 __ j(not_equal, &not_same);
13587 ASSERT_EQ(0, EQUAL);
13588 ASSERT_EQ(0, kSmiTag);
Leon Clarked91b9f72010-01-27 17:25:45 +000013589 __ Set(eax, Immediate(Smi::FromInt(EQUAL)));
Leon Clarkee46be812010-01-19 14:06:41 +000013590 __ IncrementCounter(&Counters::string_compare_native, 1);
13591 __ ret(2 * kPointerSize);
13592
13593 __ bind(&not_same);
13594
Leon Clarked91b9f72010-01-27 17:25:45 +000013595 // Check that both objects are sequential ascii strings.
13596 __ JumpIfNotBothSequentialAsciiStrings(edx, eax, ecx, ebx, &runtime);
Leon Clarkee46be812010-01-19 14:06:41 +000013597
13598 // Compare flat ascii strings.
13599 GenerateCompareFlatAsciiStrings(masm, edx, eax, ecx, ebx, edi);
13600
Leon Clarkee46be812010-01-19 14:06:41 +000013601 // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
13602 // tagged as a small integer.
13603 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +010013604 __ TailCallRuntime(Runtime::kStringCompare, 2, 1);
Leon Clarkee46be812010-01-19 14:06:41 +000013605}
13606
Steve Blocka7e24c12009-10-30 11:49:00 +000013607#undef __
13608
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010013609#define __ masm.
13610
13611MemCopyFunction CreateMemCopyFunction() {
13612 size_t actual_size;
13613 byte* buffer = static_cast<byte*>(OS::Allocate(Assembler::kMinimalBufferSize,
13614 &actual_size,
13615 true));
13616 CHECK(buffer);
13617 HandleScope handles;
13618 MacroAssembler masm(buffer, static_cast<int>(actual_size));
13619
13620 // Generated code is put into a fixed, unmovable, buffer, and not into
13621 // the V8 heap. We can't, and don't, refer to any relocatable addresses
13622 // (e.g. the JavaScript nan-object).
13623
13624 // 32-bit C declaration function calls pass arguments on stack.
13625
13626 // Stack layout:
13627 // esp[12]: Third argument, size.
13628 // esp[8]: Second argument, source pointer.
13629 // esp[4]: First argument, destination pointer.
13630 // esp[0]: return address
13631
13632 const int kDestinationOffset = 1 * kPointerSize;
13633 const int kSourceOffset = 2 * kPointerSize;
13634 const int kSizeOffset = 3 * kPointerSize;
13635
13636 int stack_offset = 0; // Update if we change the stack height.
13637
13638 if (FLAG_debug_code) {
13639 __ cmp(Operand(esp, kSizeOffset + stack_offset),
13640 Immediate(kMinComplexMemCopy));
13641 Label ok;
13642 __ j(greater_equal, &ok);
13643 __ int3();
13644 __ bind(&ok);
13645 }
13646 if (CpuFeatures::IsSupported(SSE2)) {
13647 CpuFeatures::Scope enable(SSE2);
13648 __ push(edi);
13649 __ push(esi);
13650 stack_offset += 2 * kPointerSize;
13651 Register dst = edi;
13652 Register src = esi;
13653 Register count = ecx;
13654 __ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
13655 __ mov(src, Operand(esp, stack_offset + kSourceOffset));
13656 __ mov(count, Operand(esp, stack_offset + kSizeOffset));
13657
13658
13659 __ movdqu(xmm0, Operand(src, 0));
13660 __ movdqu(Operand(dst, 0), xmm0);
13661 __ mov(edx, dst);
13662 __ and_(edx, 0xF);
13663 __ neg(edx);
13664 __ add(Operand(edx), Immediate(16));
13665 __ add(dst, Operand(edx));
13666 __ add(src, Operand(edx));
13667 __ sub(Operand(count), edx);
13668
13669 // edi is now aligned. Check if esi is also aligned.
13670 Label unaligned_source;
13671 __ test(Operand(src), Immediate(0x0F));
13672 __ j(not_zero, &unaligned_source);
13673 {
13674 __ IncrementCounter(&Counters::memcopy_aligned, 1);
13675 // Copy loop for aligned source and destination.
13676 __ mov(edx, count);
13677 Register loop_count = ecx;
13678 Register count = edx;
13679 __ shr(loop_count, 5);
13680 {
13681 // Main copy loop.
13682 Label loop;
13683 __ bind(&loop);
13684 __ prefetch(Operand(src, 0x20), 1);
13685 __ movdqa(xmm0, Operand(src, 0x00));
13686 __ movdqa(xmm1, Operand(src, 0x10));
13687 __ add(Operand(src), Immediate(0x20));
13688
13689 __ movdqa(Operand(dst, 0x00), xmm0);
13690 __ movdqa(Operand(dst, 0x10), xmm1);
13691 __ add(Operand(dst), Immediate(0x20));
13692
13693 __ dec(loop_count);
13694 __ j(not_zero, &loop);
13695 }
13696
13697 // At most 31 bytes to copy.
13698 Label move_less_16;
13699 __ test(Operand(count), Immediate(0x10));
13700 __ j(zero, &move_less_16);
13701 __ movdqa(xmm0, Operand(src, 0));
13702 __ add(Operand(src), Immediate(0x10));
13703 __ movdqa(Operand(dst, 0), xmm0);
13704 __ add(Operand(dst), Immediate(0x10));
13705 __ bind(&move_less_16);
13706
13707 // At most 15 bytes to copy. Copy 16 bytes at end of string.
13708 __ and_(count, 0xF);
13709 __ movdqu(xmm0, Operand(src, count, times_1, -0x10));
13710 __ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
13711
13712 __ pop(esi);
13713 __ pop(edi);
13714 __ ret(0);
13715 }
13716 __ Align(16);
13717 {
13718 // Copy loop for unaligned source and aligned destination.
13719 // If source is not aligned, we can't read it as efficiently.
13720 __ bind(&unaligned_source);
13721 __ IncrementCounter(&Counters::memcopy_unaligned, 1);
13722 __ mov(edx, ecx);
13723 Register loop_count = ecx;
13724 Register count = edx;
13725 __ shr(loop_count, 5);
13726 {
13727 // Main copy loop
13728 Label loop;
13729 __ bind(&loop);
13730 __ prefetch(Operand(src, 0x20), 1);
13731 __ movdqu(xmm0, Operand(src, 0x00));
13732 __ movdqu(xmm1, Operand(src, 0x10));
13733 __ add(Operand(src), Immediate(0x20));
13734
13735 __ movdqa(Operand(dst, 0x00), xmm0);
13736 __ movdqa(Operand(dst, 0x10), xmm1);
13737 __ add(Operand(dst), Immediate(0x20));
13738
13739 __ dec(loop_count);
13740 __ j(not_zero, &loop);
13741 }
13742
13743 // At most 31 bytes to copy.
13744 Label move_less_16;
13745 __ test(Operand(count), Immediate(0x10));
13746 __ j(zero, &move_less_16);
13747 __ movdqu(xmm0, Operand(src, 0));
13748 __ add(Operand(src), Immediate(0x10));
13749 __ movdqa(Operand(dst, 0), xmm0);
13750 __ add(Operand(dst), Immediate(0x10));
13751 __ bind(&move_less_16);
13752
13753 // At most 15 bytes to copy. Copy 16 bytes at end of string.
13754 __ and_(count, 0x0F);
13755 __ movdqu(xmm0, Operand(src, count, times_1, -0x10));
13756 __ movdqu(Operand(dst, count, times_1, -0x10), xmm0);
13757
13758 __ pop(esi);
13759 __ pop(edi);
13760 __ ret(0);
13761 }
13762
13763 } else {
13764 __ IncrementCounter(&Counters::memcopy_noxmm, 1);
13765 // SSE2 not supported. Unlikely to happen in practice.
13766 __ push(edi);
13767 __ push(esi);
13768 stack_offset += 2 * kPointerSize;
13769 __ cld();
13770 Register dst = edi;
13771 Register src = esi;
13772 Register count = ecx;
13773 __ mov(dst, Operand(esp, stack_offset + kDestinationOffset));
13774 __ mov(src, Operand(esp, stack_offset + kSourceOffset));
13775 __ mov(count, Operand(esp, stack_offset + kSizeOffset));
13776
13777 // Copy the first word.
13778 __ mov(eax, Operand(src, 0));
13779 __ mov(Operand(dst, 0), eax);
13780
13781 // Increment src,dstso that dst is aligned.
13782 __ mov(edx, dst);
13783 __ and_(edx, 0x03);
13784 __ neg(edx);
13785 __ add(Operand(edx), Immediate(4)); // edx = 4 - (dst & 3)
13786 __ add(dst, Operand(edx));
13787 __ add(src, Operand(edx));
13788 __ sub(Operand(count), edx);
13789 // edi is now aligned, ecx holds number of remaning bytes to copy.
13790
13791 __ mov(edx, count);
13792 count = edx;
13793 __ shr(ecx, 2); // Make word count instead of byte count.
13794 __ rep_movs();
13795
13796 // At most 3 bytes left to copy. Copy 4 bytes at end of string.
13797 __ and_(count, 3);
13798 __ mov(eax, Operand(src, count, times_1, -4));
13799 __ mov(Operand(dst, count, times_1, -4), eax);
13800
13801 __ pop(esi);
13802 __ pop(edi);
13803 __ ret(0);
13804 }
13805
13806 CodeDesc desc;
13807 masm.GetCode(&desc);
13808 // Call the function from C++.
13809 return FUNCTION_CAST<MemCopyFunction>(buffer);
13810}
13811
13812#undef __
13813
Steve Blocka7e24c12009-10-30 11:49:00 +000013814} } // namespace v8::internal
Leon Clarkef7060e22010-06-03 12:02:55 +010013815
13816#endif // V8_TARGET_ARCH_IA32