blob: 6399a8bb09abb724afb1529165cbd88d955e8657 [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2013 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/crankshaft/arm64/lithium-codegen-arm64.h"
6
7#include "src/arm64/frames-arm64.h"
8#include "src/base/bits.h"
9#include "src/code-factory.h"
10#include "src/code-stubs.h"
11#include "src/crankshaft/arm64/lithium-gap-resolver-arm64.h"
12#include "src/crankshaft/hydrogen-osr.h"
13#include "src/ic/ic.h"
14#include "src/ic/stub-cache.h"
15#include "src/profiler/cpu-profiler.h"
16
17namespace v8 {
18namespace internal {
19
20
21class SafepointGenerator final : public CallWrapper {
22 public:
23 SafepointGenerator(LCodeGen* codegen,
24 LPointerMap* pointers,
25 Safepoint::DeoptMode mode)
26 : codegen_(codegen),
27 pointers_(pointers),
28 deopt_mode_(mode) { }
29 virtual ~SafepointGenerator() { }
30
31 virtual void BeforeCall(int call_size) const { }
32
33 virtual void AfterCall() const {
34 codegen_->RecordSafepoint(pointers_, deopt_mode_);
35 }
36
37 private:
38 LCodeGen* codegen_;
39 LPointerMap* pointers_;
40 Safepoint::DeoptMode deopt_mode_;
41};
42
43
44#define __ masm()->
45
46// Emit code to branch if the given condition holds.
47// The code generated here doesn't modify the flags and they must have
48// been set by some prior instructions.
49//
50// The EmitInverted function simply inverts the condition.
51class BranchOnCondition : public BranchGenerator {
52 public:
53 BranchOnCondition(LCodeGen* codegen, Condition cond)
54 : BranchGenerator(codegen),
55 cond_(cond) { }
56
57 virtual void Emit(Label* label) const {
58 __ B(cond_, label);
59 }
60
61 virtual void EmitInverted(Label* label) const {
62 if (cond_ != al) {
63 __ B(NegateCondition(cond_), label);
64 }
65 }
66
67 private:
68 Condition cond_;
69};
70
71
72// Emit code to compare lhs and rhs and branch if the condition holds.
73// This uses MacroAssembler's CompareAndBranch function so it will handle
74// converting the comparison to Cbz/Cbnz if the right-hand side is 0.
75//
76// EmitInverted still compares the two operands but inverts the condition.
77class CompareAndBranch : public BranchGenerator {
78 public:
79 CompareAndBranch(LCodeGen* codegen,
80 Condition cond,
81 const Register& lhs,
82 const Operand& rhs)
83 : BranchGenerator(codegen),
84 cond_(cond),
85 lhs_(lhs),
86 rhs_(rhs) { }
87
88 virtual void Emit(Label* label) const {
89 __ CompareAndBranch(lhs_, rhs_, cond_, label);
90 }
91
92 virtual void EmitInverted(Label* label) const {
93 __ CompareAndBranch(lhs_, rhs_, NegateCondition(cond_), label);
94 }
95
96 private:
97 Condition cond_;
98 const Register& lhs_;
99 const Operand& rhs_;
100};
101
102
103// Test the input with the given mask and branch if the condition holds.
104// If the condition is 'eq' or 'ne' this will use MacroAssembler's
105// TestAndBranchIfAllClear and TestAndBranchIfAnySet so it will handle the
106// conversion to Tbz/Tbnz when possible.
107class TestAndBranch : public BranchGenerator {
108 public:
109 TestAndBranch(LCodeGen* codegen,
110 Condition cond,
111 const Register& value,
112 uint64_t mask)
113 : BranchGenerator(codegen),
114 cond_(cond),
115 value_(value),
116 mask_(mask) { }
117
118 virtual void Emit(Label* label) const {
119 switch (cond_) {
120 case eq:
121 __ TestAndBranchIfAllClear(value_, mask_, label);
122 break;
123 case ne:
124 __ TestAndBranchIfAnySet(value_, mask_, label);
125 break;
126 default:
127 __ Tst(value_, mask_);
128 __ B(cond_, label);
129 }
130 }
131
132 virtual void EmitInverted(Label* label) const {
133 // The inverse of "all clear" is "any set" and vice versa.
134 switch (cond_) {
135 case eq:
136 __ TestAndBranchIfAnySet(value_, mask_, label);
137 break;
138 case ne:
139 __ TestAndBranchIfAllClear(value_, mask_, label);
140 break;
141 default:
142 __ Tst(value_, mask_);
143 __ B(NegateCondition(cond_), label);
144 }
145 }
146
147 private:
148 Condition cond_;
149 const Register& value_;
150 uint64_t mask_;
151};
152
153
154// Test the input and branch if it is non-zero and not a NaN.
155class BranchIfNonZeroNumber : public BranchGenerator {
156 public:
157 BranchIfNonZeroNumber(LCodeGen* codegen, const FPRegister& value,
158 const FPRegister& scratch)
159 : BranchGenerator(codegen), value_(value), scratch_(scratch) { }
160
161 virtual void Emit(Label* label) const {
162 __ Fabs(scratch_, value_);
163 // Compare with 0.0. Because scratch_ is positive, the result can be one of
164 // nZCv (equal), nzCv (greater) or nzCV (unordered).
165 __ Fcmp(scratch_, 0.0);
166 __ B(gt, label);
167 }
168
169 virtual void EmitInverted(Label* label) const {
170 __ Fabs(scratch_, value_);
171 __ Fcmp(scratch_, 0.0);
172 __ B(le, label);
173 }
174
175 private:
176 const FPRegister& value_;
177 const FPRegister& scratch_;
178};
179
180
181// Test the input and branch if it is a heap number.
182class BranchIfHeapNumber : public BranchGenerator {
183 public:
184 BranchIfHeapNumber(LCodeGen* codegen, const Register& value)
185 : BranchGenerator(codegen), value_(value) { }
186
187 virtual void Emit(Label* label) const {
188 __ JumpIfHeapNumber(value_, label);
189 }
190
191 virtual void EmitInverted(Label* label) const {
192 __ JumpIfNotHeapNumber(value_, label);
193 }
194
195 private:
196 const Register& value_;
197};
198
199
200// Test the input and branch if it is the specified root value.
201class BranchIfRoot : public BranchGenerator {
202 public:
203 BranchIfRoot(LCodeGen* codegen, const Register& value,
204 Heap::RootListIndex index)
205 : BranchGenerator(codegen), value_(value), index_(index) { }
206
207 virtual void Emit(Label* label) const {
208 __ JumpIfRoot(value_, index_, label);
209 }
210
211 virtual void EmitInverted(Label* label) const {
212 __ JumpIfNotRoot(value_, index_, label);
213 }
214
215 private:
216 const Register& value_;
217 const Heap::RootListIndex index_;
218};
219
220
221void LCodeGen::WriteTranslation(LEnvironment* environment,
222 Translation* translation) {
223 if (environment == NULL) return;
224
225 // The translation includes one command per value in the environment.
226 int translation_size = environment->translation_size();
227
228 WriteTranslation(environment->outer(), translation);
229 WriteTranslationFrame(environment, translation);
230
231 int object_index = 0;
232 int dematerialized_index = 0;
233 for (int i = 0; i < translation_size; ++i) {
234 LOperand* value = environment->values()->at(i);
235 AddToTranslation(
236 environment, translation, value, environment->HasTaggedValueAt(i),
237 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
238 }
239}
240
241
242void LCodeGen::AddToTranslation(LEnvironment* environment,
243 Translation* translation,
244 LOperand* op,
245 bool is_tagged,
246 bool is_uint32,
247 int* object_index_pointer,
248 int* dematerialized_index_pointer) {
249 if (op == LEnvironment::materialization_marker()) {
250 int object_index = (*object_index_pointer)++;
251 if (environment->ObjectIsDuplicateAt(object_index)) {
252 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
253 translation->DuplicateObject(dupe_of);
254 return;
255 }
256 int object_length = environment->ObjectLengthAt(object_index);
257 if (environment->ObjectIsArgumentsAt(object_index)) {
258 translation->BeginArgumentsObject(object_length);
259 } else {
260 translation->BeginCapturedObject(object_length);
261 }
262 int dematerialized_index = *dematerialized_index_pointer;
263 int env_offset = environment->translation_size() + dematerialized_index;
264 *dematerialized_index_pointer += object_length;
265 for (int i = 0; i < object_length; ++i) {
266 LOperand* value = environment->values()->at(env_offset + i);
267 AddToTranslation(environment,
268 translation,
269 value,
270 environment->HasTaggedValueAt(env_offset + i),
271 environment->HasUint32ValueAt(env_offset + i),
272 object_index_pointer,
273 dematerialized_index_pointer);
274 }
275 return;
276 }
277
278 if (op->IsStackSlot()) {
279 int index = op->index();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000280 if (is_tagged) {
281 translation->StoreStackSlot(index);
282 } else if (is_uint32) {
283 translation->StoreUint32StackSlot(index);
284 } else {
285 translation->StoreInt32StackSlot(index);
286 }
287 } else if (op->IsDoubleStackSlot()) {
288 int index = op->index();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000289 translation->StoreDoubleStackSlot(index);
290 } else if (op->IsRegister()) {
291 Register reg = ToRegister(op);
292 if (is_tagged) {
293 translation->StoreRegister(reg);
294 } else if (is_uint32) {
295 translation->StoreUint32Register(reg);
296 } else {
297 translation->StoreInt32Register(reg);
298 }
299 } else if (op->IsDoubleRegister()) {
300 DoubleRegister reg = ToDoubleRegister(op);
301 translation->StoreDoubleRegister(reg);
302 } else if (op->IsConstantOperand()) {
303 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
304 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
305 translation->StoreLiteral(src_index);
306 } else {
307 UNREACHABLE();
308 }
309}
310
311
312void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
313 Safepoint::DeoptMode mode) {
314 environment->set_has_been_used();
315 if (!environment->HasBeenRegistered()) {
316 int frame_count = 0;
317 int jsframe_count = 0;
318 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
319 ++frame_count;
320 if (e->frame_type() == JS_FUNCTION) {
321 ++jsframe_count;
322 }
323 }
324 Translation translation(&translations_, frame_count, jsframe_count, zone());
325 WriteTranslation(environment, &translation);
326 int deoptimization_index = deoptimizations_.length();
327 int pc_offset = masm()->pc_offset();
328 environment->Register(deoptimization_index,
329 translation.index(),
330 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
331 deoptimizations_.Add(environment, zone());
332 }
333}
334
335
336void LCodeGen::CallCode(Handle<Code> code,
337 RelocInfo::Mode mode,
338 LInstruction* instr) {
339 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
340}
341
342
343void LCodeGen::CallCodeGeneric(Handle<Code> code,
344 RelocInfo::Mode mode,
345 LInstruction* instr,
346 SafepointMode safepoint_mode) {
347 DCHECK(instr != NULL);
348
349 Assembler::BlockPoolsScope scope(masm_);
350 __ Call(code, mode);
351 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
352
353 if ((code->kind() == Code::BINARY_OP_IC) ||
354 (code->kind() == Code::COMPARE_IC)) {
355 // Signal that we don't inline smi code before these stubs in the
356 // optimizing code generator.
357 InlineSmiCheckInfo::EmitNotInlined(masm());
358 }
359}
360
361
362void LCodeGen::DoCallFunction(LCallFunction* instr) {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100363 HCallFunction* hinstr = instr->hydrogen();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000364 DCHECK(ToRegister(instr->context()).is(cp));
365 DCHECK(ToRegister(instr->function()).Is(x1));
366 DCHECK(ToRegister(instr->result()).Is(x0));
367
368 int arity = instr->arity();
Ben Murdoch097c5b22016-05-18 11:27:45 +0100369 ConvertReceiverMode mode = hinstr->convert_mode();
370 if (hinstr->HasVectorAndSlot()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000371 Register slot_register = ToRegister(instr->temp_slot());
372 Register vector_register = ToRegister(instr->temp_vector());
373 DCHECK(slot_register.is(x3));
374 DCHECK(vector_register.is(x2));
375
376 AllowDeferredHandleDereference vector_structure_check;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100377 Handle<TypeFeedbackVector> vector = hinstr->feedback_vector();
378 int index = vector->GetIndex(hinstr->slot());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000379
380 __ Mov(vector_register, vector);
381 __ Mov(slot_register, Operand(Smi::FromInt(index)));
382
383 Handle<Code> ic =
384 CodeFactory::CallICInOptimizedCode(isolate(), arity, mode).code();
385 CallCode(ic, RelocInfo::CODE_TARGET, instr);
386 } else {
387 __ Mov(x0, arity);
388 CallCode(isolate()->builtins()->Call(mode), RelocInfo::CODE_TARGET, instr);
389 }
Ben Murdoch097c5b22016-05-18 11:27:45 +0100390 RecordPushedArgumentsDelta(hinstr->argument_delta());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000391}
392
393
394void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
395 DCHECK(instr->IsMarkedAsCall());
396 DCHECK(ToRegister(instr->context()).is(cp));
397 DCHECK(ToRegister(instr->constructor()).is(x1));
398
399 __ Mov(x0, Operand(instr->arity()));
400 if (instr->arity() == 1) {
401 // We only need the allocation site for the case we have a length argument.
402 // The case may bail out to the runtime, which will determine the correct
403 // elements kind with the site.
404 __ Mov(x2, instr->hydrogen()->site());
405 } else {
406 __ LoadRoot(x2, Heap::kUndefinedValueRootIndex);
407 }
408
409
410 ElementsKind kind = instr->hydrogen()->elements_kind();
411 AllocationSiteOverrideMode override_mode =
412 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
413 ? DISABLE_ALLOCATION_SITES
414 : DONT_OVERRIDE;
415
416 if (instr->arity() == 0) {
417 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
418 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
419 } else if (instr->arity() == 1) {
420 Label done;
421 if (IsFastPackedElementsKind(kind)) {
422 Label packed_case;
423
424 // We might need to create a holey array; look at the first argument.
425 __ Peek(x10, 0);
426 __ Cbz(x10, &packed_case);
427
428 ElementsKind holey_kind = GetHoleyElementsKind(kind);
429 ArraySingleArgumentConstructorStub stub(isolate(),
430 holey_kind,
431 override_mode);
432 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
433 __ B(&done);
434 __ Bind(&packed_case);
435 }
436
437 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
438 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
439 __ Bind(&done);
440 } else {
441 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
442 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
443 }
444 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
445
446 DCHECK(ToRegister(instr->result()).is(x0));
447}
448
449
450void LCodeGen::CallRuntime(const Runtime::Function* function,
451 int num_arguments,
452 LInstruction* instr,
453 SaveFPRegsMode save_doubles) {
454 DCHECK(instr != NULL);
455
456 __ CallRuntime(function, num_arguments, save_doubles);
457
458 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
459}
460
461
462void LCodeGen::LoadContextFromDeferred(LOperand* context) {
463 if (context->IsRegister()) {
464 __ Mov(cp, ToRegister(context));
465 } else if (context->IsStackSlot()) {
466 __ Ldr(cp, ToMemOperand(context, kMustUseFramePointer));
467 } else if (context->IsConstantOperand()) {
468 HConstant* constant =
469 chunk_->LookupConstant(LConstantOperand::cast(context));
470 __ LoadHeapObject(cp,
471 Handle<HeapObject>::cast(constant->handle(isolate())));
472 } else {
473 UNREACHABLE();
474 }
475}
476
477
478void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
479 int argc,
480 LInstruction* instr,
481 LOperand* context) {
482 LoadContextFromDeferred(context);
483 __ CallRuntimeSaveDoubles(id);
484 RecordSafepointWithRegisters(
485 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
486}
487
488
489void LCodeGen::RecordAndWritePosition(int position) {
490 if (position == RelocInfo::kNoPosition) return;
491 masm()->positions_recorder()->RecordPosition(position);
492 masm()->positions_recorder()->WriteRecordedPositions();
493}
494
495
496void LCodeGen::RecordSafepointWithLazyDeopt(LInstruction* instr,
497 SafepointMode safepoint_mode) {
498 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
499 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
500 } else {
501 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
502 RecordSafepointWithRegisters(
503 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
504 }
505}
506
507
508void LCodeGen::RecordSafepoint(LPointerMap* pointers,
509 Safepoint::Kind kind,
510 int arguments,
511 Safepoint::DeoptMode deopt_mode) {
512 DCHECK(expected_safepoint_kind_ == kind);
513
514 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
515 Safepoint safepoint = safepoints_.DefineSafepoint(
516 masm(), kind, arguments, deopt_mode);
517
518 for (int i = 0; i < operands->length(); i++) {
519 LOperand* pointer = operands->at(i);
520 if (pointer->IsStackSlot()) {
521 safepoint.DefinePointerSlot(pointer->index(), zone());
522 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
523 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
524 }
525 }
526}
527
528void LCodeGen::RecordSafepoint(LPointerMap* pointers,
529 Safepoint::DeoptMode deopt_mode) {
530 RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
531}
532
533
534void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
535 LPointerMap empty_pointers(zone());
536 RecordSafepoint(&empty_pointers, deopt_mode);
537}
538
539
540void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
541 int arguments,
542 Safepoint::DeoptMode deopt_mode) {
543 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
544}
545
546
547bool LCodeGen::GenerateCode() {
548 LPhase phase("Z_Code generation", chunk());
549 DCHECK(is_unused());
550 status_ = GENERATING;
551
552 // Open a frame scope to indicate that there is a frame on the stack. The
553 // NONE indicates that the scope shouldn't actually generate code to set up
554 // the frame (that is done in GeneratePrologue).
555 FrameScope frame_scope(masm_, StackFrame::NONE);
556
557 return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() &&
558 GenerateJumpTable() && GenerateSafepointTable();
559}
560
561
562void LCodeGen::SaveCallerDoubles() {
563 DCHECK(info()->saves_caller_doubles());
564 DCHECK(NeedsEagerFrame());
565 Comment(";;; Save clobbered callee double registers");
566 BitVector* doubles = chunk()->allocated_double_registers();
567 BitVector::Iterator iterator(doubles);
568 int count = 0;
569 while (!iterator.Done()) {
570 // TODO(all): Is this supposed to save just the callee-saved doubles? It
571 // looks like it's saving all of them.
572 FPRegister value = FPRegister::from_code(iterator.Current());
573 __ Poke(value, count * kDoubleSize);
574 iterator.Advance();
575 count++;
576 }
577}
578
579
580void LCodeGen::RestoreCallerDoubles() {
581 DCHECK(info()->saves_caller_doubles());
582 DCHECK(NeedsEagerFrame());
583 Comment(";;; Restore clobbered callee double registers");
584 BitVector* doubles = chunk()->allocated_double_registers();
585 BitVector::Iterator iterator(doubles);
586 int count = 0;
587 while (!iterator.Done()) {
588 // TODO(all): Is this supposed to restore just the callee-saved doubles? It
589 // looks like it's restoring all of them.
590 FPRegister value = FPRegister::from_code(iterator.Current());
591 __ Peek(value, count * kDoubleSize);
592 iterator.Advance();
593 count++;
594 }
595}
596
597
598bool LCodeGen::GeneratePrologue() {
599 DCHECK(is_generating());
600
601 if (info()->IsOptimizing()) {
602 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000603 }
604
605 DCHECK(__ StackPointer().Is(jssp));
606 info()->set_prologue_offset(masm_->pc_offset());
607 if (NeedsEagerFrame()) {
608 if (info()->IsStub()) {
609 __ StubPrologue();
610 } else {
611 __ Prologue(info()->GeneratePreagedPrologue());
612 }
613 frame_is_built_ = true;
614 }
615
616 // Reserve space for the stack slots needed by the code.
617 int slots = GetStackSlotCount();
618 if (slots > 0) {
619 __ Claim(slots, kPointerSize);
620 }
621
622 if (info()->saves_caller_doubles()) {
623 SaveCallerDoubles();
624 }
625 return !is_aborted();
626}
627
628
629void LCodeGen::DoPrologue(LPrologue* instr) {
630 Comment(";;; Prologue begin");
631
632 // Allocate a local context if needed.
633 if (info()->num_heap_slots() > 0) {
634 Comment(";;; Allocate local context");
635 bool need_write_barrier = true;
636 // Argument to NewContext is the function, which is in x1.
637 int slots = info()->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
638 Safepoint::DeoptMode deopt_mode = Safepoint::kNoLazyDeopt;
639 if (info()->scope()->is_script_scope()) {
640 __ Mov(x10, Operand(info()->scope()->GetScopeInfo(info()->isolate())));
641 __ Push(x1, x10);
642 __ CallRuntime(Runtime::kNewScriptContext);
643 deopt_mode = Safepoint::kLazyDeopt;
644 } else if (slots <= FastNewContextStub::kMaximumSlots) {
645 FastNewContextStub stub(isolate(), slots);
646 __ CallStub(&stub);
647 // Result of FastNewContextStub is always in new space.
648 need_write_barrier = false;
649 } else {
650 __ Push(x1);
651 __ CallRuntime(Runtime::kNewFunctionContext);
652 }
653 RecordSafepoint(deopt_mode);
654 // Context is returned in x0. It replaces the context passed to us. It's
655 // saved in the stack and kept live in cp.
656 __ Mov(cp, x0);
657 __ Str(x0, MemOperand(fp, StandardFrameConstants::kContextOffset));
658 // Copy any necessary parameters into the context.
659 int num_parameters = scope()->num_parameters();
660 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
661 for (int i = first_parameter; i < num_parameters; i++) {
662 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
663 if (var->IsContextSlot()) {
664 Register value = x0;
665 Register scratch = x3;
666
667 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
668 (num_parameters - 1 - i) * kPointerSize;
669 // Load parameter from stack.
670 __ Ldr(value, MemOperand(fp, parameter_offset));
671 // Store it in the context.
672 MemOperand target = ContextMemOperand(cp, var->index());
673 __ Str(value, target);
674 // Update the write barrier. This clobbers value and scratch.
675 if (need_write_barrier) {
676 __ RecordWriteContextSlot(cp, static_cast<int>(target.offset()),
677 value, scratch, GetLinkRegisterState(),
678 kSaveFPRegs);
679 } else if (FLAG_debug_code) {
680 Label done;
681 __ JumpIfInNewSpace(cp, &done);
682 __ Abort(kExpectedNewSpaceObject);
683 __ bind(&done);
684 }
685 }
686 }
687 Comment(";;; End allocate local context");
688 }
689
690 Comment(";;; Prologue end");
691}
692
693
694void LCodeGen::GenerateOsrPrologue() {
695 // Generate the OSR entry prologue at the first unknown OSR value, or if there
696 // are none, at the OSR entrypoint instruction.
697 if (osr_pc_offset_ >= 0) return;
698
699 osr_pc_offset_ = masm()->pc_offset();
700
701 // Adjust the frame size, subsuming the unoptimized frame into the
702 // optimized frame.
703 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
704 DCHECK(slots >= 0);
705 __ Claim(slots);
706}
707
708
709void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
710 if (instr->IsCall()) {
711 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
712 }
713 if (!instr->IsLazyBailout() && !instr->IsGap()) {
714 safepoints_.BumpLastLazySafepointIndex();
715 }
716}
717
718
719bool LCodeGen::GenerateDeferredCode() {
720 DCHECK(is_generating());
721 if (deferred_.length() > 0) {
722 for (int i = 0; !is_aborted() && (i < deferred_.length()); i++) {
723 LDeferredCode* code = deferred_[i];
724
725 HValue* value =
726 instructions_->at(code->instruction_index())->hydrogen_value();
727 RecordAndWritePosition(
728 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
729
730 Comment(";;; <@%d,#%d> "
731 "-------------------- Deferred %s --------------------",
732 code->instruction_index(),
733 code->instr()->hydrogen_value()->id(),
734 code->instr()->Mnemonic());
735
736 __ Bind(code->entry());
737
738 if (NeedsDeferredFrame()) {
739 Comment(";;; Build frame");
740 DCHECK(!frame_is_built_);
741 DCHECK(info()->IsStub());
742 frame_is_built_ = true;
743 __ Push(lr, fp, cp);
744 __ Mov(fp, Smi::FromInt(StackFrame::STUB));
745 __ Push(fp);
746 __ Add(fp, __ StackPointer(),
747 StandardFrameConstants::kFixedFrameSizeFromFp);
748 Comment(";;; Deferred code");
749 }
750
751 code->Generate();
752
753 if (NeedsDeferredFrame()) {
754 Comment(";;; Destroy frame");
755 DCHECK(frame_is_built_);
756 __ Pop(xzr, cp, fp, lr);
757 frame_is_built_ = false;
758 }
759
760 __ B(code->exit());
761 }
762 }
763
764 // Force constant pool emission at the end of the deferred code to make
765 // sure that no constant pools are emitted after deferred code because
766 // deferred code generation is the last step which generates code. The two
767 // following steps will only output data used by crakshaft.
768 masm()->CheckConstPool(true, false);
769
770 return !is_aborted();
771}
772
773
774bool LCodeGen::GenerateJumpTable() {
775 Label needs_frame, call_deopt_entry;
776
777 if (jump_table_.length() > 0) {
778 Comment(";;; -------------------- Jump table --------------------");
779 Address base = jump_table_[0]->address;
780
781 UseScratchRegisterScope temps(masm());
782 Register entry_offset = temps.AcquireX();
783
784 int length = jump_table_.length();
785 for (int i = 0; i < length; i++) {
786 Deoptimizer::JumpTableEntry* table_entry = jump_table_[i];
787 __ Bind(&table_entry->label);
788
789 Address entry = table_entry->address;
790 DeoptComment(table_entry->deopt_info);
791
792 // Second-level deopt table entries are contiguous and small, so instead
793 // of loading the full, absolute address of each one, load the base
794 // address and add an immediate offset.
795 __ Mov(entry_offset, entry - base);
796
797 if (table_entry->needs_frame) {
798 DCHECK(!info()->saves_caller_doubles());
799 Comment(";;; call deopt with frame");
800 // Save lr before Bl, fp will be adjusted in the needs_frame code.
801 __ Push(lr, fp);
802 // Reuse the existing needs_frame code.
803 __ Bl(&needs_frame);
804 } else {
805 // There is nothing special to do, so just continue to the second-level
806 // table.
807 __ Bl(&call_deopt_entry);
808 }
809 info()->LogDeoptCallPosition(masm()->pc_offset(),
810 table_entry->deopt_info.inlining_id);
811
812 masm()->CheckConstPool(false, false);
813 }
814
815 if (needs_frame.is_linked()) {
816 // This variant of deopt can only be used with stubs. Since we don't
817 // have a function pointer to install in the stack frame that we're
818 // building, install a special marker there instead.
819 DCHECK(info()->IsStub());
820
821 Comment(";;; needs_frame common code");
822 UseScratchRegisterScope temps(masm());
823 Register stub_marker = temps.AcquireX();
824 __ Bind(&needs_frame);
825 __ Mov(stub_marker, Smi::FromInt(StackFrame::STUB));
826 __ Push(cp, stub_marker);
827 __ Add(fp, __ StackPointer(), 2 * kPointerSize);
828 }
829
830 // Generate common code for calling the second-level deopt table.
831 __ Bind(&call_deopt_entry);
832
833 if (info()->saves_caller_doubles()) {
834 DCHECK(info()->IsStub());
835 RestoreCallerDoubles();
836 }
837
838 Register deopt_entry = temps.AcquireX();
839 __ Mov(deopt_entry, Operand(reinterpret_cast<uint64_t>(base),
840 RelocInfo::RUNTIME_ENTRY));
841 __ Add(deopt_entry, deopt_entry, entry_offset);
842 __ Br(deopt_entry);
843 }
844
845 // Force constant pool emission at the end of the deopt jump table to make
846 // sure that no constant pools are emitted after.
847 masm()->CheckConstPool(true, false);
848
849 // The deoptimization jump table is the last part of the instruction
850 // sequence. Mark the generated code as done unless we bailed out.
851 if (!is_aborted()) status_ = DONE;
852 return !is_aborted();
853}
854
855
856bool LCodeGen::GenerateSafepointTable() {
857 DCHECK(is_done());
858 // We do not know how much data will be emitted for the safepoint table, so
859 // force emission of the veneer pool.
860 masm()->CheckVeneerPool(true, true);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100861 safepoints_.Emit(masm(), GetTotalFrameSlotCount());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000862 return !is_aborted();
863}
864
865
866void LCodeGen::FinishCode(Handle<Code> code) {
867 DCHECK(is_done());
Ben Murdoch097c5b22016-05-18 11:27:45 +0100868 code->set_stack_slots(GetTotalFrameSlotCount());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000869 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
870 PopulateDeoptimizationData(code);
871}
872
873
874void LCodeGen::DeoptimizeBranch(
875 LInstruction* instr, Deoptimizer::DeoptReason deopt_reason,
876 BranchType branch_type, Register reg, int bit,
877 Deoptimizer::BailoutType* override_bailout_type) {
878 LEnvironment* environment = instr->environment();
879 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
880 Deoptimizer::BailoutType bailout_type =
881 info()->IsStub() ? Deoptimizer::LAZY : Deoptimizer::EAGER;
882
883 if (override_bailout_type != NULL) {
884 bailout_type = *override_bailout_type;
885 }
886
887 DCHECK(environment->HasBeenRegistered());
888 int id = environment->deoptimization_index();
889 Address entry =
890 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
891
892 if (entry == NULL) {
893 Abort(kBailoutWasNotPrepared);
894 }
895
896 if (FLAG_deopt_every_n_times != 0 && !info()->IsStub()) {
897 Label not_zero;
898 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
899
900 __ Push(x0, x1, x2);
901 __ Mrs(x2, NZCV);
902 __ Mov(x0, count);
903 __ Ldr(w1, MemOperand(x0));
904 __ Subs(x1, x1, 1);
905 __ B(gt, &not_zero);
906 __ Mov(w1, FLAG_deopt_every_n_times);
907 __ Str(w1, MemOperand(x0));
908 __ Pop(x2, x1, x0);
909 DCHECK(frame_is_built_);
910 __ Call(entry, RelocInfo::RUNTIME_ENTRY);
911 __ Unreachable();
912
913 __ Bind(&not_zero);
914 __ Str(w1, MemOperand(x0));
915 __ Msr(NZCV, x2);
916 __ Pop(x2, x1, x0);
917 }
918
919 if (info()->ShouldTrapOnDeopt()) {
920 Label dont_trap;
921 __ B(&dont_trap, InvertBranchType(branch_type), reg, bit);
922 __ Debug("trap_on_deopt", __LINE__, BREAK);
923 __ Bind(&dont_trap);
924 }
925
926 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
927
928 DCHECK(info()->IsStub() || frame_is_built_);
929 // Go through jump table if we need to build frame, or restore caller doubles.
930 if (branch_type == always &&
931 frame_is_built_ && !info()->saves_caller_doubles()) {
932 DeoptComment(deopt_info);
933 __ Call(entry, RelocInfo::RUNTIME_ENTRY);
934 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
935 } else {
936 Deoptimizer::JumpTableEntry* table_entry =
937 new (zone()) Deoptimizer::JumpTableEntry(
938 entry, deopt_info, bailout_type, !frame_is_built_);
939 // We often have several deopts to the same entry, reuse the last
940 // jump entry if this is the case.
941 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
942 jump_table_.is_empty() ||
943 !table_entry->IsEquivalentTo(*jump_table_.last())) {
944 jump_table_.Add(table_entry, zone());
945 }
946 __ B(&jump_table_.last()->label, branch_type, reg, bit);
947 }
948}
949
950
951void LCodeGen::Deoptimize(LInstruction* instr,
952 Deoptimizer::DeoptReason deopt_reason,
953 Deoptimizer::BailoutType* override_bailout_type) {
954 DeoptimizeBranch(instr, deopt_reason, always, NoReg, -1,
955 override_bailout_type);
956}
957
958
959void LCodeGen::DeoptimizeIf(Condition cond, LInstruction* instr,
960 Deoptimizer::DeoptReason deopt_reason) {
961 DeoptimizeBranch(instr, deopt_reason, static_cast<BranchType>(cond));
962}
963
964
965void LCodeGen::DeoptimizeIfZero(Register rt, LInstruction* instr,
966 Deoptimizer::DeoptReason deopt_reason) {
967 DeoptimizeBranch(instr, deopt_reason, reg_zero, rt);
968}
969
970
971void LCodeGen::DeoptimizeIfNotZero(Register rt, LInstruction* instr,
972 Deoptimizer::DeoptReason deopt_reason) {
973 DeoptimizeBranch(instr, deopt_reason, reg_not_zero, rt);
974}
975
976
977void LCodeGen::DeoptimizeIfNegative(Register rt, LInstruction* instr,
978 Deoptimizer::DeoptReason deopt_reason) {
979 int sign_bit = rt.Is64Bits() ? kXSignBit : kWSignBit;
980 DeoptimizeIfBitSet(rt, sign_bit, instr, deopt_reason);
981}
982
983
984void LCodeGen::DeoptimizeIfSmi(Register rt, LInstruction* instr,
985 Deoptimizer::DeoptReason deopt_reason) {
986 DeoptimizeIfBitClear(rt, MaskToBit(kSmiTagMask), instr, deopt_reason);
987}
988
989
990void LCodeGen::DeoptimizeIfNotSmi(Register rt, LInstruction* instr,
991 Deoptimizer::DeoptReason deopt_reason) {
992 DeoptimizeIfBitSet(rt, MaskToBit(kSmiTagMask), instr, deopt_reason);
993}
994
995
996void LCodeGen::DeoptimizeIfRoot(Register rt, Heap::RootListIndex index,
997 LInstruction* instr,
998 Deoptimizer::DeoptReason deopt_reason) {
999 __ CompareRoot(rt, index);
1000 DeoptimizeIf(eq, instr, deopt_reason);
1001}
1002
1003
1004void LCodeGen::DeoptimizeIfNotRoot(Register rt, Heap::RootListIndex index,
1005 LInstruction* instr,
1006 Deoptimizer::DeoptReason deopt_reason) {
1007 __ CompareRoot(rt, index);
1008 DeoptimizeIf(ne, instr, deopt_reason);
1009}
1010
1011
1012void LCodeGen::DeoptimizeIfMinusZero(DoubleRegister input, LInstruction* instr,
1013 Deoptimizer::DeoptReason deopt_reason) {
1014 __ TestForMinusZero(input);
1015 DeoptimizeIf(vs, instr, deopt_reason);
1016}
1017
1018
1019void LCodeGen::DeoptimizeIfNotHeapNumber(Register object, LInstruction* instr) {
1020 __ CompareObjectMap(object, Heap::kHeapNumberMapRootIndex);
1021 DeoptimizeIf(ne, instr, Deoptimizer::kNotAHeapNumber);
1022}
1023
1024
1025void LCodeGen::DeoptimizeIfBitSet(Register rt, int bit, LInstruction* instr,
1026 Deoptimizer::DeoptReason deopt_reason) {
1027 DeoptimizeBranch(instr, deopt_reason, reg_bit_set, rt, bit);
1028}
1029
1030
1031void LCodeGen::DeoptimizeIfBitClear(Register rt, int bit, LInstruction* instr,
1032 Deoptimizer::DeoptReason deopt_reason) {
1033 DeoptimizeBranch(instr, deopt_reason, reg_bit_clear, rt, bit);
1034}
1035
1036
1037void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
1038 if (info()->ShouldEnsureSpaceForLazyDeopt()) {
1039 // Ensure that we have enough space after the previous lazy-bailout
1040 // instruction for patching the code here.
1041 intptr_t current_pc = masm()->pc_offset();
1042
1043 if (current_pc < (last_lazy_deopt_pc_ + space_needed)) {
1044 ptrdiff_t padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
1045 DCHECK((padding_size % kInstructionSize) == 0);
1046 InstructionAccurateScope instruction_accurate(
1047 masm(), padding_size / kInstructionSize);
1048
1049 while (padding_size > 0) {
1050 __ nop();
1051 padding_size -= kInstructionSize;
1052 }
1053 }
1054 }
1055 last_lazy_deopt_pc_ = masm()->pc_offset();
1056}
1057
1058
1059Register LCodeGen::ToRegister(LOperand* op) const {
1060 // TODO(all): support zero register results, as ToRegister32.
1061 DCHECK((op != NULL) && op->IsRegister());
1062 return Register::from_code(op->index());
1063}
1064
1065
1066Register LCodeGen::ToRegister32(LOperand* op) const {
1067 DCHECK(op != NULL);
1068 if (op->IsConstantOperand()) {
1069 // If this is a constant operand, the result must be the zero register.
1070 DCHECK(ToInteger32(LConstantOperand::cast(op)) == 0);
1071 return wzr;
1072 } else {
1073 return ToRegister(op).W();
1074 }
1075}
1076
1077
1078Smi* LCodeGen::ToSmi(LConstantOperand* op) const {
1079 HConstant* constant = chunk_->LookupConstant(op);
1080 return Smi::FromInt(constant->Integer32Value());
1081}
1082
1083
1084DoubleRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
1085 DCHECK((op != NULL) && op->IsDoubleRegister());
1086 return DoubleRegister::from_code(op->index());
1087}
1088
1089
1090Operand LCodeGen::ToOperand(LOperand* op) {
1091 DCHECK(op != NULL);
1092 if (op->IsConstantOperand()) {
1093 LConstantOperand* const_op = LConstantOperand::cast(op);
1094 HConstant* constant = chunk()->LookupConstant(const_op);
1095 Representation r = chunk_->LookupLiteralRepresentation(const_op);
1096 if (r.IsSmi()) {
1097 DCHECK(constant->HasSmiValue());
1098 return Operand(Smi::FromInt(constant->Integer32Value()));
1099 } else if (r.IsInteger32()) {
1100 DCHECK(constant->HasInteger32Value());
1101 return Operand(constant->Integer32Value());
1102 } else if (r.IsDouble()) {
1103 Abort(kToOperandUnsupportedDoubleImmediate);
1104 }
1105 DCHECK(r.IsTagged());
1106 return Operand(constant->handle(isolate()));
1107 } else if (op->IsRegister()) {
1108 return Operand(ToRegister(op));
1109 } else if (op->IsDoubleRegister()) {
1110 Abort(kToOperandIsDoubleRegisterUnimplemented);
1111 return Operand(0);
1112 }
1113 // Stack slots not implemented, use ToMemOperand instead.
1114 UNREACHABLE();
1115 return Operand(0);
1116}
1117
1118
1119Operand LCodeGen::ToOperand32(LOperand* op) {
1120 DCHECK(op != NULL);
1121 if (op->IsRegister()) {
1122 return Operand(ToRegister32(op));
1123 } else if (op->IsConstantOperand()) {
1124 LConstantOperand* const_op = LConstantOperand::cast(op);
1125 HConstant* constant = chunk()->LookupConstant(const_op);
1126 Representation r = chunk_->LookupLiteralRepresentation(const_op);
1127 if (r.IsInteger32()) {
1128 return Operand(constant->Integer32Value());
1129 } else {
1130 // Other constants not implemented.
1131 Abort(kToOperand32UnsupportedImmediate);
1132 }
1133 }
1134 // Other cases are not implemented.
1135 UNREACHABLE();
1136 return Operand(0);
1137}
1138
1139
1140static int64_t ArgumentsOffsetWithoutFrame(int index) {
1141 DCHECK(index < 0);
1142 return -(index + 1) * kPointerSize;
1143}
1144
1145
1146MemOperand LCodeGen::ToMemOperand(LOperand* op, StackMode stack_mode) const {
1147 DCHECK(op != NULL);
1148 DCHECK(!op->IsRegister());
1149 DCHECK(!op->IsDoubleRegister());
1150 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
1151 if (NeedsEagerFrame()) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01001152 int fp_offset = FrameSlotToFPOffset(op->index());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001153 // Loads and stores have a bigger reach in positive offset than negative.
1154 // We try to access using jssp (positive offset) first, then fall back to
1155 // fp (negative offset) if that fails.
1156 //
1157 // We can reference a stack slot from jssp only if we know how much we've
1158 // put on the stack. We don't know this in the following cases:
1159 // - stack_mode != kCanUseStackPointer: this is the case when deferred
1160 // code has saved the registers.
1161 // - saves_caller_doubles(): some double registers have been pushed, jssp
1162 // references the end of the double registers and not the end of the stack
1163 // slots.
1164 // In both of the cases above, we _could_ add the tracking information
1165 // required so that we can use jssp here, but in practice it isn't worth it.
1166 if ((stack_mode == kCanUseStackPointer) &&
1167 !info()->saves_caller_doubles()) {
1168 int jssp_offset_to_fp =
Ben Murdoch097c5b22016-05-18 11:27:45 +01001169 (pushed_arguments_ + GetTotalFrameSlotCount()) * kPointerSize -
1170 StandardFrameConstants::kFixedFrameSizeAboveFp;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001171 int jssp_offset = fp_offset + jssp_offset_to_fp;
1172 if (masm()->IsImmLSScaled(jssp_offset, LSDoubleWord)) {
1173 return MemOperand(masm()->StackPointer(), jssp_offset);
1174 }
1175 }
1176 return MemOperand(fp, fp_offset);
1177 } else {
1178 // Retrieve parameter without eager stack-frame relative to the
1179 // stack-pointer.
1180 return MemOperand(masm()->StackPointer(),
1181 ArgumentsOffsetWithoutFrame(op->index()));
1182 }
1183}
1184
1185
1186Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
1187 HConstant* constant = chunk_->LookupConstant(op);
1188 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
1189 return constant->handle(isolate());
1190}
1191
1192
1193template <class LI>
1194Operand LCodeGen::ToShiftedRightOperand32(LOperand* right, LI* shift_info) {
1195 if (shift_info->shift() == NO_SHIFT) {
1196 return ToOperand32(right);
1197 } else {
1198 return Operand(
1199 ToRegister32(right),
1200 shift_info->shift(),
1201 JSShiftAmountFromLConstant(shift_info->shift_amount()));
1202 }
1203}
1204
1205
1206bool LCodeGen::IsSmi(LConstantOperand* op) const {
1207 return chunk_->LookupLiteralRepresentation(op).IsSmi();
1208}
1209
1210
1211bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const {
1212 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
1213}
1214
1215
1216int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
1217 HConstant* constant = chunk_->LookupConstant(op);
1218 return constant->Integer32Value();
1219}
1220
1221
1222double LCodeGen::ToDouble(LConstantOperand* op) const {
1223 HConstant* constant = chunk_->LookupConstant(op);
1224 DCHECK(constant->HasDoubleValue());
1225 return constant->DoubleValue();
1226}
1227
1228
1229Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
1230 Condition cond = nv;
1231 switch (op) {
1232 case Token::EQ:
1233 case Token::EQ_STRICT:
1234 cond = eq;
1235 break;
1236 case Token::NE:
1237 case Token::NE_STRICT:
1238 cond = ne;
1239 break;
1240 case Token::LT:
1241 cond = is_unsigned ? lo : lt;
1242 break;
1243 case Token::GT:
1244 cond = is_unsigned ? hi : gt;
1245 break;
1246 case Token::LTE:
1247 cond = is_unsigned ? ls : le;
1248 break;
1249 case Token::GTE:
1250 cond = is_unsigned ? hs : ge;
1251 break;
1252 case Token::IN:
1253 case Token::INSTANCEOF:
1254 default:
1255 UNREACHABLE();
1256 }
1257 return cond;
1258}
1259
1260
1261template<class InstrType>
1262void LCodeGen::EmitBranchGeneric(InstrType instr,
1263 const BranchGenerator& branch) {
1264 int left_block = instr->TrueDestination(chunk_);
1265 int right_block = instr->FalseDestination(chunk_);
1266
1267 int next_block = GetNextEmittedBlock();
1268
1269 if (right_block == left_block) {
1270 EmitGoto(left_block);
1271 } else if (left_block == next_block) {
1272 branch.EmitInverted(chunk_->GetAssemblyLabel(right_block));
1273 } else {
1274 branch.Emit(chunk_->GetAssemblyLabel(left_block));
1275 if (right_block != next_block) {
1276 __ B(chunk_->GetAssemblyLabel(right_block));
1277 }
1278 }
1279}
1280
1281
1282template<class InstrType>
1283void LCodeGen::EmitBranch(InstrType instr, Condition condition) {
1284 DCHECK((condition != al) && (condition != nv));
1285 BranchOnCondition branch(this, condition);
1286 EmitBranchGeneric(instr, branch);
1287}
1288
1289
1290template<class InstrType>
1291void LCodeGen::EmitCompareAndBranch(InstrType instr,
1292 Condition condition,
1293 const Register& lhs,
1294 const Operand& rhs) {
1295 DCHECK((condition != al) && (condition != nv));
1296 CompareAndBranch branch(this, condition, lhs, rhs);
1297 EmitBranchGeneric(instr, branch);
1298}
1299
1300
1301template<class InstrType>
1302void LCodeGen::EmitTestAndBranch(InstrType instr,
1303 Condition condition,
1304 const Register& value,
1305 uint64_t mask) {
1306 DCHECK((condition != al) && (condition != nv));
1307 TestAndBranch branch(this, condition, value, mask);
1308 EmitBranchGeneric(instr, branch);
1309}
1310
1311
1312template<class InstrType>
1313void LCodeGen::EmitBranchIfNonZeroNumber(InstrType instr,
1314 const FPRegister& value,
1315 const FPRegister& scratch) {
1316 BranchIfNonZeroNumber branch(this, value, scratch);
1317 EmitBranchGeneric(instr, branch);
1318}
1319
1320
1321template<class InstrType>
1322void LCodeGen::EmitBranchIfHeapNumber(InstrType instr,
1323 const Register& value) {
1324 BranchIfHeapNumber branch(this, value);
1325 EmitBranchGeneric(instr, branch);
1326}
1327
1328
1329template<class InstrType>
1330void LCodeGen::EmitBranchIfRoot(InstrType instr,
1331 const Register& value,
1332 Heap::RootListIndex index) {
1333 BranchIfRoot branch(this, value, index);
1334 EmitBranchGeneric(instr, branch);
1335}
1336
1337
1338void LCodeGen::DoGap(LGap* gap) {
1339 for (int i = LGap::FIRST_INNER_POSITION;
1340 i <= LGap::LAST_INNER_POSITION;
1341 i++) {
1342 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1343 LParallelMove* move = gap->GetParallelMove(inner_pos);
1344 if (move != NULL) {
1345 resolver_.Resolve(move);
1346 }
1347 }
1348}
1349
1350
1351void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
1352 Register arguments = ToRegister(instr->arguments());
1353 Register result = ToRegister(instr->result());
1354
1355 // The pointer to the arguments array come from DoArgumentsElements.
1356 // It does not point directly to the arguments and there is an offest of
1357 // two words that we must take into account when accessing an argument.
1358 // Subtracting the index from length accounts for one, so we add one more.
1359
1360 if (instr->length()->IsConstantOperand() &&
1361 instr->index()->IsConstantOperand()) {
1362 int index = ToInteger32(LConstantOperand::cast(instr->index()));
1363 int length = ToInteger32(LConstantOperand::cast(instr->length()));
1364 int offset = ((length - index) + 1) * kPointerSize;
1365 __ Ldr(result, MemOperand(arguments, offset));
1366 } else if (instr->index()->IsConstantOperand()) {
1367 Register length = ToRegister32(instr->length());
1368 int index = ToInteger32(LConstantOperand::cast(instr->index()));
1369 int loc = index - 1;
1370 if (loc != 0) {
1371 __ Sub(result.W(), length, loc);
1372 __ Ldr(result, MemOperand(arguments, result, UXTW, kPointerSizeLog2));
1373 } else {
1374 __ Ldr(result, MemOperand(arguments, length, UXTW, kPointerSizeLog2));
1375 }
1376 } else {
1377 Register length = ToRegister32(instr->length());
1378 Operand index = ToOperand32(instr->index());
1379 __ Sub(result.W(), length, index);
1380 __ Add(result.W(), result.W(), 1);
1381 __ Ldr(result, MemOperand(arguments, result, UXTW, kPointerSizeLog2));
1382 }
1383}
1384
1385
1386void LCodeGen::DoAddE(LAddE* instr) {
1387 Register result = ToRegister(instr->result());
1388 Register left = ToRegister(instr->left());
1389 Operand right = Operand(x0); // Dummy initialization.
1390 if (instr->hydrogen()->external_add_type() == AddOfExternalAndTagged) {
1391 right = Operand(ToRegister(instr->right()));
1392 } else if (instr->right()->IsConstantOperand()) {
1393 right = ToInteger32(LConstantOperand::cast(instr->right()));
1394 } else {
1395 right = Operand(ToRegister32(instr->right()), SXTW);
1396 }
1397
1398 DCHECK(!instr->hydrogen()->CheckFlag(HValue::kCanOverflow));
1399 __ Add(result, left, right);
1400}
1401
1402
1403void LCodeGen::DoAddI(LAddI* instr) {
1404 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1405 Register result = ToRegister32(instr->result());
1406 Register left = ToRegister32(instr->left());
1407 Operand right = ToShiftedRightOperand32(instr->right(), instr);
1408
1409 if (can_overflow) {
1410 __ Adds(result, left, right);
1411 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
1412 } else {
1413 __ Add(result, left, right);
1414 }
1415}
1416
1417
1418void LCodeGen::DoAddS(LAddS* instr) {
1419 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1420 Register result = ToRegister(instr->result());
1421 Register left = ToRegister(instr->left());
1422 Operand right = ToOperand(instr->right());
1423 if (can_overflow) {
1424 __ Adds(result, left, right);
1425 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
1426 } else {
1427 __ Add(result, left, right);
1428 }
1429}
1430
1431
1432void LCodeGen::DoAllocate(LAllocate* instr) {
1433 class DeferredAllocate: public LDeferredCode {
1434 public:
1435 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
1436 : LDeferredCode(codegen), instr_(instr) { }
1437 virtual void Generate() { codegen()->DoDeferredAllocate(instr_); }
1438 virtual LInstruction* instr() { return instr_; }
1439 private:
1440 LAllocate* instr_;
1441 };
1442
1443 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
1444
1445 Register result = ToRegister(instr->result());
1446 Register temp1 = ToRegister(instr->temp1());
1447 Register temp2 = ToRegister(instr->temp2());
1448
1449 // Allocate memory for the object.
1450 AllocationFlags flags = TAG_OBJECT;
1451 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
1452 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
1453 }
1454
1455 if (instr->hydrogen()->IsOldSpaceAllocation()) {
1456 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
1457 flags = static_cast<AllocationFlags>(flags | PRETENURE);
1458 }
1459
1460 if (instr->size()->IsConstantOperand()) {
1461 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
1462 CHECK(size <= Page::kMaxRegularHeapObjectSize);
1463 __ Allocate(size, result, temp1, temp2, deferred->entry(), flags);
1464 } else {
1465 Register size = ToRegister32(instr->size());
1466 __ Sxtw(size.X(), size);
1467 __ Allocate(size.X(), result, temp1, temp2, deferred->entry(), flags);
1468 }
1469
1470 __ Bind(deferred->exit());
1471
1472 if (instr->hydrogen()->MustPrefillWithFiller()) {
1473 Register start = temp1;
1474 Register end = temp2;
1475 Register filler = ToRegister(instr->temp3());
1476
1477 __ Sub(start, result, kHeapObjectTag);
1478
1479 if (instr->size()->IsConstantOperand()) {
1480 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
1481 __ Add(end, start, size);
1482 } else {
1483 __ Add(end, start, ToRegister(instr->size()));
1484 }
1485 __ LoadRoot(filler, Heap::kOnePointerFillerMapRootIndex);
1486 __ InitializeFieldsWithFiller(start, end, filler);
1487 } else {
1488 DCHECK(instr->temp3() == NULL);
1489 }
1490}
1491
1492
1493void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
1494 // TODO(3095996): Get rid of this. For now, we need to make the
1495 // result register contain a valid pointer because it is already
1496 // contained in the register pointer map.
1497 __ Mov(ToRegister(instr->result()), Smi::FromInt(0));
1498
1499 PushSafepointRegistersScope scope(this);
1500 // We're in a SafepointRegistersScope so we can use any scratch registers.
1501 Register size = x0;
1502 if (instr->size()->IsConstantOperand()) {
1503 __ Mov(size, ToSmi(LConstantOperand::cast(instr->size())));
1504 } else {
1505 __ SmiTag(size, ToRegister32(instr->size()).X());
1506 }
1507 int flags = AllocateDoubleAlignFlag::encode(
1508 instr->hydrogen()->MustAllocateDoubleAligned());
1509 if (instr->hydrogen()->IsOldSpaceAllocation()) {
1510 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
1511 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
1512 } else {
1513 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
1514 }
1515 __ Mov(x10, Smi::FromInt(flags));
1516 __ Push(size, x10);
1517
1518 CallRuntimeFromDeferred(
1519 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
1520 __ StoreToSafepointRegisterSlot(x0, ToRegister(instr->result()));
1521}
1522
1523
1524void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
1525 Register receiver = ToRegister(instr->receiver());
1526 Register function = ToRegister(instr->function());
1527 Register length = ToRegister32(instr->length());
1528
1529 Register elements = ToRegister(instr->elements());
1530 Register scratch = x5;
1531 DCHECK(receiver.Is(x0)); // Used for parameter count.
1532 DCHECK(function.Is(x1)); // Required by InvokeFunction.
1533 DCHECK(ToRegister(instr->result()).Is(x0));
1534 DCHECK(instr->IsMarkedAsCall());
1535
1536 // Copy the arguments to this function possibly from the
1537 // adaptor frame below it.
1538 const uint32_t kArgumentsLimit = 1 * KB;
1539 __ Cmp(length, kArgumentsLimit);
1540 DeoptimizeIf(hi, instr, Deoptimizer::kTooManyArguments);
1541
1542 // Push the receiver and use the register to keep the original
1543 // number of arguments.
1544 __ Push(receiver);
1545 Register argc = receiver;
1546 receiver = NoReg;
1547 __ Sxtw(argc, length);
1548 // The arguments are at a one pointer size offset from elements.
1549 __ Add(elements, elements, 1 * kPointerSize);
1550
1551 // Loop through the arguments pushing them onto the execution
1552 // stack.
1553 Label invoke, loop;
1554 // length is a small non-negative integer, due to the test above.
1555 __ Cbz(length, &invoke);
1556 __ Bind(&loop);
1557 __ Ldr(scratch, MemOperand(elements, length, SXTW, kPointerSizeLog2));
1558 __ Push(scratch);
1559 __ Subs(length, length, 1);
1560 __ B(ne, &loop);
1561
1562 __ Bind(&invoke);
1563 DCHECK(instr->HasPointerMap());
1564 LPointerMap* pointers = instr->pointer_map();
1565 SafepointGenerator safepoint_generator(this, pointers, Safepoint::kLazyDeopt);
1566 // The number of arguments is stored in argc (receiver) which is x0, as
1567 // expected by InvokeFunction.
1568 ParameterCount actual(argc);
1569 __ InvokeFunction(function, no_reg, actual, CALL_FUNCTION,
1570 safepoint_generator);
1571}
1572
1573
1574void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
1575 Register result = ToRegister(instr->result());
1576
1577 if (instr->hydrogen()->from_inlined()) {
1578 // When we are inside an inlined function, the arguments are the last things
1579 // that have been pushed on the stack. Therefore the arguments array can be
1580 // accessed directly from jssp.
1581 // However in the normal case, it is accessed via fp but there are two words
1582 // on the stack between fp and the arguments (the saved lr and fp) and the
1583 // LAccessArgumentsAt implementation take that into account.
1584 // In the inlined case we need to subtract the size of 2 words to jssp to
1585 // get a pointer which will work well with LAccessArgumentsAt.
1586 DCHECK(masm()->StackPointer().Is(jssp));
1587 __ Sub(result, jssp, 2 * kPointerSize);
1588 } else {
1589 DCHECK(instr->temp() != NULL);
1590 Register previous_fp = ToRegister(instr->temp());
1591
1592 __ Ldr(previous_fp,
1593 MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1594 __ Ldr(result,
1595 MemOperand(previous_fp, StandardFrameConstants::kContextOffset));
1596 __ Cmp(result, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1597 __ Csel(result, fp, previous_fp, ne);
1598 }
1599}
1600
1601
1602void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
1603 Register elements = ToRegister(instr->elements());
1604 Register result = ToRegister32(instr->result());
1605 Label done;
1606
1607 // If no arguments adaptor frame the number of arguments is fixed.
1608 __ Cmp(fp, elements);
1609 __ Mov(result, scope()->num_parameters());
1610 __ B(eq, &done);
1611
1612 // Arguments adaptor frame present. Get argument length from there.
1613 __ Ldr(result.X(), MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1614 __ Ldr(result,
1615 UntagSmiMemOperand(result.X(),
1616 ArgumentsAdaptorFrameConstants::kLengthOffset));
1617
1618 // Argument length is in result register.
1619 __ Bind(&done);
1620}
1621
1622
1623void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1624 DoubleRegister left = ToDoubleRegister(instr->left());
1625 DoubleRegister right = ToDoubleRegister(instr->right());
1626 DoubleRegister result = ToDoubleRegister(instr->result());
1627
1628 switch (instr->op()) {
1629 case Token::ADD: __ Fadd(result, left, right); break;
1630 case Token::SUB: __ Fsub(result, left, right); break;
1631 case Token::MUL: __ Fmul(result, left, right); break;
1632 case Token::DIV: __ Fdiv(result, left, right); break;
1633 case Token::MOD: {
1634 // The ECMA-262 remainder operator is the remainder from a truncating
1635 // (round-towards-zero) division. Note that this differs from IEEE-754.
1636 //
1637 // TODO(jbramley): See if it's possible to do this inline, rather than by
1638 // calling a helper function. With frintz (to produce the intermediate
1639 // quotient) and fmsub (to calculate the remainder without loss of
1640 // precision), it should be possible. However, we would need support for
1641 // fdiv in round-towards-zero mode, and the ARM64 simulator doesn't
1642 // support that yet.
1643 DCHECK(left.Is(d0));
1644 DCHECK(right.Is(d1));
1645 __ CallCFunction(
1646 ExternalReference::mod_two_doubles_operation(isolate()),
1647 0, 2);
1648 DCHECK(result.Is(d0));
1649 break;
1650 }
1651 default:
1652 UNREACHABLE();
1653 break;
1654 }
1655}
1656
1657
1658void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
1659 DCHECK(ToRegister(instr->context()).is(cp));
1660 DCHECK(ToRegister(instr->left()).is(x1));
1661 DCHECK(ToRegister(instr->right()).is(x0));
1662 DCHECK(ToRegister(instr->result()).is(x0));
1663
Ben Murdoch097c5b22016-05-18 11:27:45 +01001664 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001665 CallCode(code, RelocInfo::CODE_TARGET, instr);
1666}
1667
1668
1669void LCodeGen::DoBitI(LBitI* instr) {
1670 Register result = ToRegister32(instr->result());
1671 Register left = ToRegister32(instr->left());
1672 Operand right = ToShiftedRightOperand32(instr->right(), instr);
1673
1674 switch (instr->op()) {
1675 case Token::BIT_AND: __ And(result, left, right); break;
1676 case Token::BIT_OR: __ Orr(result, left, right); break;
1677 case Token::BIT_XOR: __ Eor(result, left, right); break;
1678 default:
1679 UNREACHABLE();
1680 break;
1681 }
1682}
1683
1684
1685void LCodeGen::DoBitS(LBitS* instr) {
1686 Register result = ToRegister(instr->result());
1687 Register left = ToRegister(instr->left());
1688 Operand right = ToOperand(instr->right());
1689
1690 switch (instr->op()) {
1691 case Token::BIT_AND: __ And(result, left, right); break;
1692 case Token::BIT_OR: __ Orr(result, left, right); break;
1693 case Token::BIT_XOR: __ Eor(result, left, right); break;
1694 default:
1695 UNREACHABLE();
1696 break;
1697 }
1698}
1699
1700
1701void LCodeGen::DoBoundsCheck(LBoundsCheck *instr) {
1702 Condition cond = instr->hydrogen()->allow_equality() ? hi : hs;
1703 DCHECK(instr->hydrogen()->index()->representation().IsInteger32());
1704 DCHECK(instr->hydrogen()->length()->representation().IsInteger32());
1705 if (instr->index()->IsConstantOperand()) {
1706 Operand index = ToOperand32(instr->index());
1707 Register length = ToRegister32(instr->length());
1708 __ Cmp(length, index);
1709 cond = CommuteCondition(cond);
1710 } else {
1711 Register index = ToRegister32(instr->index());
1712 Operand length = ToOperand32(instr->length());
1713 __ Cmp(index, length);
1714 }
1715 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
1716 __ Assert(NegateCondition(cond), kEliminatedBoundsCheckFailed);
1717 } else {
1718 DeoptimizeIf(cond, instr, Deoptimizer::kOutOfBounds);
1719 }
1720}
1721
1722
1723void LCodeGen::DoBranch(LBranch* instr) {
1724 Representation r = instr->hydrogen()->value()->representation();
1725 Label* true_label = instr->TrueLabel(chunk_);
1726 Label* false_label = instr->FalseLabel(chunk_);
1727
1728 if (r.IsInteger32()) {
1729 DCHECK(!info()->IsStub());
1730 EmitCompareAndBranch(instr, ne, ToRegister32(instr->value()), 0);
1731 } else if (r.IsSmi()) {
1732 DCHECK(!info()->IsStub());
1733 STATIC_ASSERT(kSmiTag == 0);
1734 EmitCompareAndBranch(instr, ne, ToRegister(instr->value()), 0);
1735 } else if (r.IsDouble()) {
1736 DoubleRegister value = ToDoubleRegister(instr->value());
1737 // Test the double value. Zero and NaN are false.
1738 EmitBranchIfNonZeroNumber(instr, value, double_scratch());
1739 } else {
1740 DCHECK(r.IsTagged());
1741 Register value = ToRegister(instr->value());
1742 HType type = instr->hydrogen()->value()->type();
1743
1744 if (type.IsBoolean()) {
1745 DCHECK(!info()->IsStub());
1746 __ CompareRoot(value, Heap::kTrueValueRootIndex);
1747 EmitBranch(instr, eq);
1748 } else if (type.IsSmi()) {
1749 DCHECK(!info()->IsStub());
1750 EmitCompareAndBranch(instr, ne, value, Smi::FromInt(0));
1751 } else if (type.IsJSArray()) {
1752 DCHECK(!info()->IsStub());
1753 EmitGoto(instr->TrueDestination(chunk()));
1754 } else if (type.IsHeapNumber()) {
1755 DCHECK(!info()->IsStub());
1756 __ Ldr(double_scratch(), FieldMemOperand(value,
1757 HeapNumber::kValueOffset));
1758 // Test the double value. Zero and NaN are false.
1759 EmitBranchIfNonZeroNumber(instr, double_scratch(), double_scratch());
1760 } else if (type.IsString()) {
1761 DCHECK(!info()->IsStub());
1762 Register temp = ToRegister(instr->temp1());
1763 __ Ldr(temp, FieldMemOperand(value, String::kLengthOffset));
1764 EmitCompareAndBranch(instr, ne, temp, 0);
1765 } else {
1766 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
1767 // Avoid deopts in the case where we've never executed this path before.
1768 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
1769
1770 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
1771 // undefined -> false.
1772 __ JumpIfRoot(
1773 value, Heap::kUndefinedValueRootIndex, false_label);
1774 }
1775
1776 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
1777 // Boolean -> its value.
1778 __ JumpIfRoot(
1779 value, Heap::kTrueValueRootIndex, true_label);
1780 __ JumpIfRoot(
1781 value, Heap::kFalseValueRootIndex, false_label);
1782 }
1783
1784 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
1785 // 'null' -> false.
1786 __ JumpIfRoot(
1787 value, Heap::kNullValueRootIndex, false_label);
1788 }
1789
1790 if (expected.Contains(ToBooleanStub::SMI)) {
1791 // Smis: 0 -> false, all other -> true.
1792 DCHECK(Smi::FromInt(0) == 0);
1793 __ Cbz(value, false_label);
1794 __ JumpIfSmi(value, true_label);
1795 } else if (expected.NeedsMap()) {
1796 // If we need a map later and have a smi, deopt.
1797 DeoptimizeIfSmi(value, instr, Deoptimizer::kSmi);
1798 }
1799
1800 Register map = NoReg;
1801 Register scratch = NoReg;
1802
1803 if (expected.NeedsMap()) {
1804 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
1805 map = ToRegister(instr->temp1());
1806 scratch = ToRegister(instr->temp2());
1807
1808 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
1809
1810 if (expected.CanBeUndetectable()) {
1811 // Undetectable -> false.
1812 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
1813 __ TestAndBranchIfAnySet(
1814 scratch, 1 << Map::kIsUndetectable, false_label);
1815 }
1816 }
1817
1818 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
1819 // spec object -> true.
1820 __ CompareInstanceType(map, scratch, FIRST_JS_RECEIVER_TYPE);
1821 __ B(ge, true_label);
1822 }
1823
1824 if (expected.Contains(ToBooleanStub::STRING)) {
1825 // String value -> false iff empty.
1826 Label not_string;
1827 __ CompareInstanceType(map, scratch, FIRST_NONSTRING_TYPE);
1828 __ B(ge, &not_string);
1829 __ Ldr(scratch, FieldMemOperand(value, String::kLengthOffset));
1830 __ Cbz(scratch, false_label);
1831 __ B(true_label);
1832 __ Bind(&not_string);
1833 }
1834
1835 if (expected.Contains(ToBooleanStub::SYMBOL)) {
1836 // Symbol value -> true.
1837 __ CompareInstanceType(map, scratch, SYMBOL_TYPE);
1838 __ B(eq, true_label);
1839 }
1840
1841 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
1842 // SIMD value -> true.
1843 __ CompareInstanceType(map, scratch, SIMD128_VALUE_TYPE);
1844 __ B(eq, true_label);
1845 }
1846
1847 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
1848 Label not_heap_number;
1849 __ JumpIfNotRoot(map, Heap::kHeapNumberMapRootIndex, &not_heap_number);
1850
1851 __ Ldr(double_scratch(),
1852 FieldMemOperand(value, HeapNumber::kValueOffset));
1853 __ Fcmp(double_scratch(), 0.0);
1854 // If we got a NaN (overflow bit is set), jump to the false branch.
1855 __ B(vs, false_label);
1856 __ B(eq, false_label);
1857 __ B(true_label);
1858 __ Bind(&not_heap_number);
1859 }
1860
1861 if (!expected.IsGeneric()) {
1862 // We've seen something for the first time -> deopt.
1863 // This can only happen if we are not generic already.
1864 Deoptimize(instr, Deoptimizer::kUnexpectedObject);
1865 }
1866 }
1867 }
1868}
1869
1870
1871void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
1872 int formal_parameter_count, int arity,
1873 LInstruction* instr) {
1874 bool dont_adapt_arguments =
1875 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
1876 bool can_invoke_directly =
1877 dont_adapt_arguments || formal_parameter_count == arity;
1878
1879 // The function interface relies on the following register assignments.
1880 Register function_reg = x1;
1881 Register arity_reg = x0;
1882
1883 LPointerMap* pointers = instr->pointer_map();
1884
1885 if (FLAG_debug_code) {
1886 Label is_not_smi;
1887 // Try to confirm that function_reg (x1) is a tagged pointer.
1888 __ JumpIfNotSmi(function_reg, &is_not_smi);
1889 __ Abort(kExpectedFunctionObject);
1890 __ Bind(&is_not_smi);
1891 }
1892
1893 if (can_invoke_directly) {
1894 // Change context.
1895 __ Ldr(cp, FieldMemOperand(function_reg, JSFunction::kContextOffset));
1896
1897 // Always initialize new target and number of actual arguments.
1898 __ LoadRoot(x3, Heap::kUndefinedValueRootIndex);
1899 __ Mov(arity_reg, arity);
1900
1901 // Invoke function.
1902 __ Ldr(x10, FieldMemOperand(function_reg, JSFunction::kCodeEntryOffset));
1903 __ Call(x10);
1904
1905 // Set up deoptimization.
1906 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1907 } else {
1908 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
1909 ParameterCount count(arity);
1910 ParameterCount expected(formal_parameter_count);
1911 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
1912 }
1913}
1914
1915
1916void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
1917 DCHECK(instr->IsMarkedAsCall());
1918 DCHECK(ToRegister(instr->result()).Is(x0));
1919
1920 if (instr->hydrogen()->IsTailCall()) {
1921 if (NeedsEagerFrame()) __ LeaveFrame(StackFrame::INTERNAL);
1922
1923 if (instr->target()->IsConstantOperand()) {
1924 LConstantOperand* target = LConstantOperand::cast(instr->target());
1925 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
1926 // TODO(all): on ARM we use a call descriptor to specify a storage mode
1927 // but on ARM64 we only have one storage mode so it isn't necessary. Check
1928 // this understanding is correct.
1929 __ Jump(code, RelocInfo::CODE_TARGET);
1930 } else {
1931 DCHECK(instr->target()->IsRegister());
1932 Register target = ToRegister(instr->target());
1933 __ Add(target, target, Code::kHeaderSize - kHeapObjectTag);
1934 __ Br(target);
1935 }
1936 } else {
1937 LPointerMap* pointers = instr->pointer_map();
1938 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
1939
1940 if (instr->target()->IsConstantOperand()) {
1941 LConstantOperand* target = LConstantOperand::cast(instr->target());
1942 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
1943 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
1944 // TODO(all): on ARM we use a call descriptor to specify a storage mode
1945 // but on ARM64 we only have one storage mode so it isn't necessary. Check
1946 // this understanding is correct.
1947 __ Call(code, RelocInfo::CODE_TARGET, TypeFeedbackId::None());
1948 } else {
1949 DCHECK(instr->target()->IsRegister());
1950 Register target = ToRegister(instr->target());
1951 generator.BeforeCall(__ CallSize(target));
1952 __ Add(target, target, Code::kHeaderSize - kHeapObjectTag);
1953 __ Call(target);
1954 }
1955 generator.AfterCall();
1956 }
1957
1958 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
1959}
1960
1961
1962void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
1963 DCHECK(instr->IsMarkedAsCall());
1964 DCHECK(ToRegister(instr->function()).is(x1));
1965
1966 // Change context.
1967 __ Ldr(cp, FieldMemOperand(x1, JSFunction::kContextOffset));
1968
1969 // Always initialize new target and number of actual arguments.
1970 __ LoadRoot(x3, Heap::kUndefinedValueRootIndex);
1971 __ Mov(x0, instr->arity());
1972
1973 // Load the code entry address
1974 __ Ldr(x10, FieldMemOperand(x1, JSFunction::kCodeEntryOffset));
1975 __ Call(x10);
1976
1977 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1978 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
1979}
1980
1981
1982void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
1983 CallRuntime(instr->function(), instr->arity(), instr);
1984 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
1985}
1986
1987
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001988void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1989 GenerateOsrPrologue();
1990}
1991
1992
1993void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
1994 Register temp = ToRegister(instr->temp());
1995 {
1996 PushSafepointRegistersScope scope(this);
1997 __ Push(object);
1998 __ Mov(cp, 0);
1999 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
2000 RecordSafepointWithRegisters(
2001 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
2002 __ StoreToSafepointRegisterSlot(x0, temp);
2003 }
2004 DeoptimizeIfSmi(temp, instr, Deoptimizer::kInstanceMigrationFailed);
2005}
2006
2007
2008void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
2009 class DeferredCheckMaps: public LDeferredCode {
2010 public:
2011 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
2012 : LDeferredCode(codegen), instr_(instr), object_(object) {
2013 SetExit(check_maps());
2014 }
2015 virtual void Generate() {
2016 codegen()->DoDeferredInstanceMigration(instr_, object_);
2017 }
2018 Label* check_maps() { return &check_maps_; }
2019 virtual LInstruction* instr() { return instr_; }
2020 private:
2021 LCheckMaps* instr_;
2022 Label check_maps_;
2023 Register object_;
2024 };
2025
2026 if (instr->hydrogen()->IsStabilityCheck()) {
2027 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
2028 for (int i = 0; i < maps->size(); ++i) {
2029 AddStabilityDependency(maps->at(i).handle());
2030 }
2031 return;
2032 }
2033
2034 Register object = ToRegister(instr->value());
2035 Register map_reg = ToRegister(instr->temp());
2036
2037 __ Ldr(map_reg, FieldMemOperand(object, HeapObject::kMapOffset));
2038
2039 DeferredCheckMaps* deferred = NULL;
2040 if (instr->hydrogen()->HasMigrationTarget()) {
2041 deferred = new(zone()) DeferredCheckMaps(this, instr, object);
2042 __ Bind(deferred->check_maps());
2043 }
2044
2045 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
2046 Label success;
2047 for (int i = 0; i < maps->size() - 1; i++) {
2048 Handle<Map> map = maps->at(i).handle();
2049 __ CompareMap(map_reg, map);
2050 __ B(eq, &success);
2051 }
2052 Handle<Map> map = maps->at(maps->size() - 1).handle();
2053 __ CompareMap(map_reg, map);
2054
2055 // We didn't match a map.
2056 if (instr->hydrogen()->HasMigrationTarget()) {
2057 __ B(ne, deferred->entry());
2058 } else {
2059 DeoptimizeIf(ne, instr, Deoptimizer::kWrongMap);
2060 }
2061
2062 __ Bind(&success);
2063}
2064
2065
2066void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
2067 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2068 DeoptimizeIfSmi(ToRegister(instr->value()), instr, Deoptimizer::kSmi);
2069 }
2070}
2071
2072
2073void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
2074 Register value = ToRegister(instr->value());
2075 DCHECK(!instr->result() || ToRegister(instr->result()).Is(value));
2076 DeoptimizeIfNotSmi(value, instr, Deoptimizer::kNotASmi);
2077}
2078
2079
2080void LCodeGen::DoCheckArrayBufferNotNeutered(
2081 LCheckArrayBufferNotNeutered* instr) {
2082 UseScratchRegisterScope temps(masm());
2083 Register view = ToRegister(instr->view());
2084 Register scratch = temps.AcquireX();
2085
2086 __ Ldr(scratch, FieldMemOperand(view, JSArrayBufferView::kBufferOffset));
2087 __ Ldr(scratch, FieldMemOperand(scratch, JSArrayBuffer::kBitFieldOffset));
2088 __ Tst(scratch, Operand(1 << JSArrayBuffer::WasNeutered::kShift));
2089 DeoptimizeIf(ne, instr, Deoptimizer::kOutOfBounds);
2090}
2091
2092
2093void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
2094 Register input = ToRegister(instr->value());
2095 Register scratch = ToRegister(instr->temp());
2096
2097 __ Ldr(scratch, FieldMemOperand(input, HeapObject::kMapOffset));
2098 __ Ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
2099
2100 if (instr->hydrogen()->is_interval_check()) {
2101 InstanceType first, last;
2102 instr->hydrogen()->GetCheckInterval(&first, &last);
2103
2104 __ Cmp(scratch, first);
2105 if (first == last) {
2106 // If there is only one type in the interval check for equality.
2107 DeoptimizeIf(ne, instr, Deoptimizer::kWrongInstanceType);
2108 } else if (last == LAST_TYPE) {
2109 // We don't need to compare with the higher bound of the interval.
2110 DeoptimizeIf(lo, instr, Deoptimizer::kWrongInstanceType);
2111 } else {
2112 // If we are below the lower bound, set the C flag and clear the Z flag
2113 // to force a deopt.
2114 __ Ccmp(scratch, last, CFlag, hs);
2115 DeoptimizeIf(hi, instr, Deoptimizer::kWrongInstanceType);
2116 }
2117 } else {
2118 uint8_t mask;
2119 uint8_t tag;
2120 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
2121
2122 if (base::bits::IsPowerOfTwo32(mask)) {
2123 DCHECK((tag == 0) || (tag == mask));
2124 if (tag == 0) {
2125 DeoptimizeIfBitSet(scratch, MaskToBit(mask), instr,
2126 Deoptimizer::kWrongInstanceType);
2127 } else {
2128 DeoptimizeIfBitClear(scratch, MaskToBit(mask), instr,
2129 Deoptimizer::kWrongInstanceType);
2130 }
2131 } else {
2132 if (tag == 0) {
2133 __ Tst(scratch, mask);
2134 } else {
2135 __ And(scratch, scratch, mask);
2136 __ Cmp(scratch, tag);
2137 }
2138 DeoptimizeIf(ne, instr, Deoptimizer::kWrongInstanceType);
2139 }
2140 }
2141}
2142
2143
2144void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
2145 DoubleRegister input = ToDoubleRegister(instr->unclamped());
2146 Register result = ToRegister32(instr->result());
2147 __ ClampDoubleToUint8(result, input, double_scratch());
2148}
2149
2150
2151void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
2152 Register input = ToRegister32(instr->unclamped());
2153 Register result = ToRegister32(instr->result());
2154 __ ClampInt32ToUint8(result, input);
2155}
2156
2157
2158void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
2159 Register input = ToRegister(instr->unclamped());
2160 Register result = ToRegister32(instr->result());
2161 Label done;
2162
2163 // Both smi and heap number cases are handled.
2164 Label is_not_smi;
2165 __ JumpIfNotSmi(input, &is_not_smi);
2166 __ SmiUntag(result.X(), input);
2167 __ ClampInt32ToUint8(result);
2168 __ B(&done);
2169
2170 __ Bind(&is_not_smi);
2171
2172 // Check for heap number.
2173 Label is_heap_number;
2174 __ JumpIfHeapNumber(input, &is_heap_number);
2175
2176 // Check for undefined. Undefined is coverted to zero for clamping conversion.
2177 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
2178 Deoptimizer::kNotAHeapNumberUndefined);
2179 __ Mov(result, 0);
2180 __ B(&done);
2181
2182 // Heap number case.
2183 __ Bind(&is_heap_number);
2184 DoubleRegister dbl_scratch = double_scratch();
2185 DoubleRegister dbl_scratch2 = ToDoubleRegister(instr->temp1());
2186 __ Ldr(dbl_scratch, FieldMemOperand(input, HeapNumber::kValueOffset));
2187 __ ClampDoubleToUint8(result, dbl_scratch, dbl_scratch2);
2188
2189 __ Bind(&done);
2190}
2191
2192
2193void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
2194 DoubleRegister value_reg = ToDoubleRegister(instr->value());
2195 Register result_reg = ToRegister(instr->result());
2196 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
2197 __ Fmov(result_reg, value_reg);
2198 __ Lsr(result_reg, result_reg, 32);
2199 } else {
2200 __ Fmov(result_reg.W(), value_reg.S());
2201 }
2202}
2203
2204
2205void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
2206 Register hi_reg = ToRegister(instr->hi());
2207 Register lo_reg = ToRegister(instr->lo());
2208 DoubleRegister result_reg = ToDoubleRegister(instr->result());
2209
2210 // Insert the least significant 32 bits of hi_reg into the most significant
2211 // 32 bits of lo_reg, and move to a floating point register.
2212 __ Bfi(lo_reg, hi_reg, 32, 32);
2213 __ Fmov(result_reg, lo_reg);
2214}
2215
2216
2217void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2218 Handle<String> class_name = instr->hydrogen()->class_name();
2219 Label* true_label = instr->TrueLabel(chunk_);
2220 Label* false_label = instr->FalseLabel(chunk_);
2221 Register input = ToRegister(instr->value());
2222 Register scratch1 = ToRegister(instr->temp1());
2223 Register scratch2 = ToRegister(instr->temp2());
2224
2225 __ JumpIfSmi(input, false_label);
2226
2227 Register map = scratch2;
2228 __ CompareObjectType(input, map, scratch1, JS_FUNCTION_TYPE);
2229 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2230 __ B(eq, true_label);
2231 } else {
2232 __ B(eq, false_label);
2233 }
2234
2235 // Check if the constructor in the map is a function.
2236 {
2237 UseScratchRegisterScope temps(masm());
2238 Register instance_type = temps.AcquireX();
2239 __ GetMapConstructor(scratch1, map, scratch2, instance_type);
2240 __ Cmp(instance_type, JS_FUNCTION_TYPE);
2241 }
2242 // Objects with a non-function constructor have class 'Object'.
2243 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2244 __ B(ne, true_label);
2245 } else {
2246 __ B(ne, false_label);
2247 }
2248
2249 // The constructor function is in scratch1. Get its instance class name.
2250 __ Ldr(scratch1,
2251 FieldMemOperand(scratch1, JSFunction::kSharedFunctionInfoOffset));
2252 __ Ldr(scratch1,
2253 FieldMemOperand(scratch1,
2254 SharedFunctionInfo::kInstanceClassNameOffset));
2255
2256 // The class name we are testing against is internalized since it's a literal.
2257 // The name in the constructor is internalized because of the way the context
2258 // is booted. This routine isn't expected to work for random API-created
2259 // classes and it doesn't have to because you can't access it with natives
2260 // syntax. Since both sides are internalized it is sufficient to use an
2261 // identity comparison.
2262 EmitCompareAndBranch(instr, eq, scratch1, Operand(class_name));
2263}
2264
2265
2266void LCodeGen::DoCmpHoleAndBranchD(LCmpHoleAndBranchD* instr) {
2267 DCHECK(instr->hydrogen()->representation().IsDouble());
2268 FPRegister object = ToDoubleRegister(instr->object());
2269 Register temp = ToRegister(instr->temp());
2270
2271 // If we don't have a NaN, we don't have the hole, so branch now to avoid the
2272 // (relatively expensive) hole-NaN check.
2273 __ Fcmp(object, object);
2274 __ B(vc, instr->FalseLabel(chunk_));
2275
2276 // We have a NaN, but is it the hole?
2277 __ Fmov(temp, object);
2278 EmitCompareAndBranch(instr, eq, temp, kHoleNanInt64);
2279}
2280
2281
2282void LCodeGen::DoCmpHoleAndBranchT(LCmpHoleAndBranchT* instr) {
2283 DCHECK(instr->hydrogen()->representation().IsTagged());
2284 Register object = ToRegister(instr->object());
2285
2286 EmitBranchIfRoot(instr, object, Heap::kTheHoleValueRootIndex);
2287}
2288
2289
2290void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2291 Register value = ToRegister(instr->value());
2292 Register map = ToRegister(instr->temp());
2293
2294 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset));
2295 EmitCompareAndBranch(instr, eq, map, Operand(instr->map()));
2296}
2297
2298
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002299void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2300 LOperand* left = instr->left();
2301 LOperand* right = instr->right();
2302 bool is_unsigned =
2303 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2304 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2305 Condition cond = TokenToCondition(instr->op(), is_unsigned);
2306
2307 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2308 // We can statically evaluate the comparison.
2309 double left_val = ToDouble(LConstantOperand::cast(left));
2310 double right_val = ToDouble(LConstantOperand::cast(right));
Ben Murdoch097c5b22016-05-18 11:27:45 +01002311 int next_block = Token::EvalComparison(instr->op(), left_val, right_val)
2312 ? instr->TrueDestination(chunk_)
2313 : instr->FalseDestination(chunk_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002314 EmitGoto(next_block);
2315 } else {
2316 if (instr->is_double()) {
2317 __ Fcmp(ToDoubleRegister(left), ToDoubleRegister(right));
2318
2319 // If a NaN is involved, i.e. the result is unordered (V set),
2320 // jump to false block label.
2321 __ B(vs, instr->FalseLabel(chunk_));
2322 EmitBranch(instr, cond);
2323 } else {
2324 if (instr->hydrogen_value()->representation().IsInteger32()) {
2325 if (right->IsConstantOperand()) {
2326 EmitCompareAndBranch(instr, cond, ToRegister32(left),
2327 ToOperand32(right));
2328 } else {
2329 // Commute the operands and the condition.
2330 EmitCompareAndBranch(instr, CommuteCondition(cond),
2331 ToRegister32(right), ToOperand32(left));
2332 }
2333 } else {
2334 DCHECK(instr->hydrogen_value()->representation().IsSmi());
2335 if (right->IsConstantOperand()) {
2336 int32_t value = ToInteger32(LConstantOperand::cast(right));
2337 EmitCompareAndBranch(instr,
2338 cond,
2339 ToRegister(left),
2340 Operand(Smi::FromInt(value)));
2341 } else if (left->IsConstantOperand()) {
2342 // Commute the operands and the condition.
2343 int32_t value = ToInteger32(LConstantOperand::cast(left));
2344 EmitCompareAndBranch(instr,
2345 CommuteCondition(cond),
2346 ToRegister(right),
2347 Operand(Smi::FromInt(value)));
2348 } else {
2349 EmitCompareAndBranch(instr,
2350 cond,
2351 ToRegister(left),
2352 ToRegister(right));
2353 }
2354 }
2355 }
2356 }
2357}
2358
2359
2360void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2361 Register left = ToRegister(instr->left());
2362 Register right = ToRegister(instr->right());
2363 EmitCompareAndBranch(instr, eq, left, right);
2364}
2365
2366
2367void LCodeGen::DoCmpT(LCmpT* instr) {
2368 DCHECK(ToRegister(instr->context()).is(cp));
2369 Token::Value op = instr->op();
2370 Condition cond = TokenToCondition(op, false);
2371
2372 DCHECK(ToRegister(instr->left()).Is(x1));
2373 DCHECK(ToRegister(instr->right()).Is(x0));
Ben Murdoch097c5b22016-05-18 11:27:45 +01002374 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002375 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2376 // Signal that we don't inline smi code before this stub.
2377 InlineSmiCheckInfo::EmitNotInlined(masm());
2378
2379 // Return true or false depending on CompareIC result.
2380 // This instruction is marked as call. We can clobber any register.
2381 DCHECK(instr->IsMarkedAsCall());
2382 __ LoadTrueFalseRoots(x1, x2);
2383 __ Cmp(x0, 0);
2384 __ Csel(ToRegister(instr->result()), x1, x2, cond);
2385}
2386
2387
2388void LCodeGen::DoConstantD(LConstantD* instr) {
2389 DCHECK(instr->result()->IsDoubleRegister());
2390 DoubleRegister result = ToDoubleRegister(instr->result());
2391 if (instr->value() == 0) {
2392 if (copysign(1.0, instr->value()) == 1.0) {
2393 __ Fmov(result, fp_zero);
2394 } else {
2395 __ Fneg(result, fp_zero);
2396 }
2397 } else {
2398 __ Fmov(result, instr->value());
2399 }
2400}
2401
2402
2403void LCodeGen::DoConstantE(LConstantE* instr) {
2404 __ Mov(ToRegister(instr->result()), Operand(instr->value()));
2405}
2406
2407
2408void LCodeGen::DoConstantI(LConstantI* instr) {
2409 DCHECK(is_int32(instr->value()));
2410 // Cast the value here to ensure that the value isn't sign extended by the
2411 // implicit Operand constructor.
2412 __ Mov(ToRegister32(instr->result()), static_cast<uint32_t>(instr->value()));
2413}
2414
2415
2416void LCodeGen::DoConstantS(LConstantS* instr) {
2417 __ Mov(ToRegister(instr->result()), Operand(instr->value()));
2418}
2419
2420
2421void LCodeGen::DoConstantT(LConstantT* instr) {
2422 Handle<Object> object = instr->value(isolate());
2423 AllowDeferredHandleDereference smi_check;
2424 __ LoadObject(ToRegister(instr->result()), object);
2425}
2426
2427
2428void LCodeGen::DoContext(LContext* instr) {
2429 // If there is a non-return use, the context must be moved to a register.
2430 Register result = ToRegister(instr->result());
2431 if (info()->IsOptimizing()) {
2432 __ Ldr(result, MemOperand(fp, StandardFrameConstants::kContextOffset));
2433 } else {
2434 // If there is no frame, the context must be in cp.
2435 DCHECK(result.is(cp));
2436 }
2437}
2438
2439
2440void LCodeGen::DoCheckValue(LCheckValue* instr) {
2441 Register reg = ToRegister(instr->value());
2442 Handle<HeapObject> object = instr->hydrogen()->object().handle();
2443 AllowDeferredHandleDereference smi_check;
2444 if (isolate()->heap()->InNewSpace(*object)) {
2445 UseScratchRegisterScope temps(masm());
2446 Register temp = temps.AcquireX();
2447 Handle<Cell> cell = isolate()->factory()->NewCell(object);
2448 __ Mov(temp, Operand(cell));
2449 __ Ldr(temp, FieldMemOperand(temp, Cell::kValueOffset));
2450 __ Cmp(reg, temp);
2451 } else {
2452 __ Cmp(reg, Operand(object));
2453 }
2454 DeoptimizeIf(ne, instr, Deoptimizer::kValueMismatch);
2455}
2456
2457
2458void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
2459 last_lazy_deopt_pc_ = masm()->pc_offset();
2460 DCHECK(instr->HasEnvironment());
2461 LEnvironment* env = instr->environment();
2462 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
2463 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2464}
2465
2466
2467void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
2468 Deoptimizer::BailoutType type = instr->hydrogen()->type();
2469 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
2470 // needed return address), even though the implementation of LAZY and EAGER is
2471 // now identical. When LAZY is eventually completely folded into EAGER, remove
2472 // the special case below.
2473 if (info()->IsStub() && (type == Deoptimizer::EAGER)) {
2474 type = Deoptimizer::LAZY;
2475 }
2476
2477 Deoptimize(instr, instr->hydrogen()->reason(), &type);
2478}
2479
2480
2481void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
2482 Register dividend = ToRegister32(instr->dividend());
2483 int32_t divisor = instr->divisor();
2484 Register result = ToRegister32(instr->result());
2485 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
2486 DCHECK(!result.is(dividend));
2487
2488 // Check for (0 / -x) that will produce negative zero.
2489 HDiv* hdiv = instr->hydrogen();
2490 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
2491 DeoptimizeIfZero(dividend, instr, Deoptimizer::kDivisionByZero);
2492 }
2493 // Check for (kMinInt / -1).
2494 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
2495 // Test dividend for kMinInt by subtracting one (cmp) and checking for
2496 // overflow.
2497 __ Cmp(dividend, 1);
2498 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
2499 }
2500 // Deoptimize if remainder will not be 0.
2501 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
2502 divisor != 1 && divisor != -1) {
2503 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
2504 __ Tst(dividend, mask);
2505 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecision);
2506 }
2507
2508 if (divisor == -1) { // Nice shortcut, not needed for correctness.
2509 __ Neg(result, dividend);
2510 return;
2511 }
2512 int32_t shift = WhichPowerOf2Abs(divisor);
2513 if (shift == 0) {
2514 __ Mov(result, dividend);
2515 } else if (shift == 1) {
2516 __ Add(result, dividend, Operand(dividend, LSR, 31));
2517 } else {
2518 __ Mov(result, Operand(dividend, ASR, 31));
2519 __ Add(result, dividend, Operand(result, LSR, 32 - shift));
2520 }
2521 if (shift > 0) __ Mov(result, Operand(result, ASR, shift));
2522 if (divisor < 0) __ Neg(result, result);
2523}
2524
2525
2526void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
2527 Register dividend = ToRegister32(instr->dividend());
2528 int32_t divisor = instr->divisor();
2529 Register result = ToRegister32(instr->result());
2530 DCHECK(!AreAliased(dividend, result));
2531
2532 if (divisor == 0) {
2533 Deoptimize(instr, Deoptimizer::kDivisionByZero);
2534 return;
2535 }
2536
2537 // Check for (0 / -x) that will produce negative zero.
2538 HDiv* hdiv = instr->hydrogen();
2539 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
2540 DeoptimizeIfZero(dividend, instr, Deoptimizer::kMinusZero);
2541 }
2542
2543 __ TruncatingDiv(result, dividend, Abs(divisor));
2544 if (divisor < 0) __ Neg(result, result);
2545
2546 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
2547 Register temp = ToRegister32(instr->temp());
2548 DCHECK(!AreAliased(dividend, result, temp));
2549 __ Sxtw(dividend.X(), dividend);
2550 __ Mov(temp, divisor);
2551 __ Smsubl(temp.X(), result, temp, dividend.X());
2552 DeoptimizeIfNotZero(temp, instr, Deoptimizer::kLostPrecision);
2553 }
2554}
2555
2556
2557// TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
2558void LCodeGen::DoDivI(LDivI* instr) {
2559 HBinaryOperation* hdiv = instr->hydrogen();
2560 Register dividend = ToRegister32(instr->dividend());
2561 Register divisor = ToRegister32(instr->divisor());
2562 Register result = ToRegister32(instr->result());
2563
2564 // Issue the division first, and then check for any deopt cases whilst the
2565 // result is computed.
2566 __ Sdiv(result, dividend, divisor);
2567
2568 if (hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
2569 DCHECK(!instr->temp());
2570 return;
2571 }
2572
2573 // Check for x / 0.
2574 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
2575 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
2576 }
2577
2578 // Check for (0 / -x) as that will produce negative zero.
2579 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
2580 __ Cmp(divisor, 0);
2581
2582 // If the divisor < 0 (mi), compare the dividend, and deopt if it is
2583 // zero, ie. zero dividend with negative divisor deopts.
2584 // If the divisor >= 0 (pl, the opposite of mi) set the flags to
2585 // condition ne, so we don't deopt, ie. positive divisor doesn't deopt.
2586 __ Ccmp(dividend, 0, NoFlag, mi);
2587 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
2588 }
2589
2590 // Check for (kMinInt / -1).
2591 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
2592 // Test dividend for kMinInt by subtracting one (cmp) and checking for
2593 // overflow.
2594 __ Cmp(dividend, 1);
2595 // If overflow is set, ie. dividend = kMinInt, compare the divisor with
2596 // -1. If overflow is clear, set the flags for condition ne, as the
2597 // dividend isn't -1, and thus we shouldn't deopt.
2598 __ Ccmp(divisor, -1, NoFlag, vs);
2599 DeoptimizeIf(eq, instr, Deoptimizer::kOverflow);
2600 }
2601
2602 // Compute remainder and deopt if it's not zero.
2603 Register remainder = ToRegister32(instr->temp());
2604 __ Msub(remainder, result, divisor, dividend);
2605 DeoptimizeIfNotZero(remainder, instr, Deoptimizer::kLostPrecision);
2606}
2607
2608
2609void LCodeGen::DoDoubleToIntOrSmi(LDoubleToIntOrSmi* instr) {
2610 DoubleRegister input = ToDoubleRegister(instr->value());
2611 Register result = ToRegister32(instr->result());
2612
2613 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
2614 DeoptimizeIfMinusZero(input, instr, Deoptimizer::kMinusZero);
2615 }
2616
2617 __ TryRepresentDoubleAsInt32(result, input, double_scratch());
2618 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
2619
2620 if (instr->tag_result()) {
2621 __ SmiTag(result.X());
2622 }
2623}
2624
2625
2626void LCodeGen::DoDrop(LDrop* instr) {
2627 __ Drop(instr->count());
2628
2629 RecordPushedArgumentsDelta(instr->hydrogen_value()->argument_delta());
2630}
2631
2632
2633void LCodeGen::DoDummy(LDummy* instr) {
2634 // Nothing to see here, move on!
2635}
2636
2637
2638void LCodeGen::DoDummyUse(LDummyUse* instr) {
2639 // Nothing to see here, move on!
2640}
2641
2642
2643void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
2644 Register map = ToRegister(instr->map());
2645 Register result = ToRegister(instr->result());
2646 Label load_cache, done;
2647
2648 __ EnumLengthUntagged(result, map);
2649 __ Cbnz(result, &load_cache);
2650
2651 __ Mov(result, Operand(isolate()->factory()->empty_fixed_array()));
2652 __ B(&done);
2653
2654 __ Bind(&load_cache);
2655 __ LoadInstanceDescriptors(map, result);
2656 __ Ldr(result, FieldMemOperand(result, DescriptorArray::kEnumCacheOffset));
2657 __ Ldr(result, FieldMemOperand(result, FixedArray::SizeFor(instr->idx())));
2658 DeoptimizeIfZero(result, instr, Deoptimizer::kNoCache);
2659
2660 __ Bind(&done);
2661}
2662
2663
2664void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
2665 Register object = ToRegister(instr->object());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002666
2667 DCHECK(instr->IsMarkedAsCall());
2668 DCHECK(object.Is(x0));
2669
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002670 Label use_cache, call_runtime;
Ben Murdoch097c5b22016-05-18 11:27:45 +01002671 __ CheckEnumCache(object, x5, x1, x2, x3, x4, &call_runtime);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002672
2673 __ Ldr(object, FieldMemOperand(object, HeapObject::kMapOffset));
2674 __ B(&use_cache);
2675
2676 // Get the set of properties to enumerate.
2677 __ Bind(&call_runtime);
2678 __ Push(object);
Ben Murdoch097c5b22016-05-18 11:27:45 +01002679 CallRuntime(Runtime::kForInEnumerate, instr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002680 __ Bind(&use_cache);
2681}
2682
2683
2684void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2685 Register input = ToRegister(instr->value());
2686 Register result = ToRegister(instr->result());
2687
2688 __ AssertString(input);
2689
2690 // Assert that we can use a W register load to get the hash.
2691 DCHECK((String::kHashShift + String::kArrayIndexValueBits) < kWRegSizeInBits);
2692 __ Ldr(result.W(), FieldMemOperand(input, String::kHashFieldOffset));
2693 __ IndexFromHash(result, result);
2694}
2695
2696
2697void LCodeGen::EmitGoto(int block) {
2698 // Do not emit jump if we are emitting a goto to the next block.
2699 if (!IsNextEmittedBlock(block)) {
2700 __ B(chunk_->GetAssemblyLabel(LookupDestination(block)));
2701 }
2702}
2703
2704
2705void LCodeGen::DoGoto(LGoto* instr) {
2706 EmitGoto(instr->block_id());
2707}
2708
2709
2710void LCodeGen::DoHasCachedArrayIndexAndBranch(
2711 LHasCachedArrayIndexAndBranch* instr) {
2712 Register input = ToRegister(instr->value());
2713 Register temp = ToRegister32(instr->temp());
2714
2715 // Assert that the cache status bits fit in a W register.
2716 DCHECK(is_uint32(String::kContainsCachedArrayIndexMask));
2717 __ Ldr(temp, FieldMemOperand(input, String::kHashFieldOffset));
2718 __ Tst(temp, String::kContainsCachedArrayIndexMask);
2719 EmitBranch(instr, eq);
2720}
2721
2722
2723// HHasInstanceTypeAndBranch instruction is built with an interval of type
2724// to test but is only used in very restricted ways. The only possible kinds
2725// of intervals are:
2726// - [ FIRST_TYPE, instr->to() ]
2727// - [ instr->form(), LAST_TYPE ]
2728// - instr->from() == instr->to()
2729//
2730// These kinds of intervals can be check with only one compare instruction
2731// providing the correct value and test condition are used.
2732//
2733// TestType() will return the value to use in the compare instruction and
2734// BranchCondition() will return the condition to use depending on the kind
2735// of interval actually specified in the instruction.
2736static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2737 InstanceType from = instr->from();
2738 InstanceType to = instr->to();
2739 if (from == FIRST_TYPE) return to;
2740 DCHECK((from == to) || (to == LAST_TYPE));
2741 return from;
2742}
2743
2744
2745// See comment above TestType function for what this function does.
2746static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2747 InstanceType from = instr->from();
2748 InstanceType to = instr->to();
2749 if (from == to) return eq;
2750 if (to == LAST_TYPE) return hs;
2751 if (from == FIRST_TYPE) return ls;
2752 UNREACHABLE();
2753 return eq;
2754}
2755
2756
2757void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2758 Register input = ToRegister(instr->value());
2759 Register scratch = ToRegister(instr->temp());
2760
2761 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2762 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2763 }
2764 __ CompareObjectType(input, scratch, scratch, TestType(instr->hydrogen()));
2765 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2766}
2767
2768
2769void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
2770 Register result = ToRegister(instr->result());
2771 Register base = ToRegister(instr->base_object());
2772 if (instr->offset()->IsConstantOperand()) {
2773 __ Add(result, base, ToOperand32(instr->offset()));
2774 } else {
2775 __ Add(result, base, Operand(ToRegister32(instr->offset()), SXTW));
2776 }
2777}
2778
2779
2780void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2781 DCHECK(ToRegister(instr->context()).is(cp));
2782 DCHECK(ToRegister(instr->left()).is(InstanceOfDescriptor::LeftRegister()));
2783 DCHECK(ToRegister(instr->right()).is(InstanceOfDescriptor::RightRegister()));
2784 DCHECK(ToRegister(instr->result()).is(x0));
2785 InstanceOfStub stub(isolate());
2786 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2787}
2788
2789
2790void LCodeGen::DoHasInPrototypeChainAndBranch(
2791 LHasInPrototypeChainAndBranch* instr) {
2792 Register const object = ToRegister(instr->object());
2793 Register const object_map = ToRegister(instr->scratch1());
2794 Register const object_instance_type = ToRegister(instr->scratch2());
2795 Register const object_prototype = object_map;
2796 Register const prototype = ToRegister(instr->prototype());
2797
2798 // The {object} must be a spec object. It's sufficient to know that {object}
2799 // is not a smi, since all other non-spec objects have {null} prototypes and
2800 // will be ruled out below.
2801 if (instr->hydrogen()->ObjectNeedsSmiCheck()) {
2802 __ JumpIfSmi(object, instr->FalseLabel(chunk_));
2803 }
2804
2805 // Loop through the {object}s prototype chain looking for the {prototype}.
2806 __ Ldr(object_map, FieldMemOperand(object, HeapObject::kMapOffset));
2807 Label loop;
2808 __ Bind(&loop);
2809
2810 // Deoptimize if the object needs to be access checked.
2811 __ Ldrb(object_instance_type,
2812 FieldMemOperand(object_map, Map::kBitFieldOffset));
2813 __ Tst(object_instance_type, Operand(1 << Map::kIsAccessCheckNeeded));
2814 DeoptimizeIf(ne, instr, Deoptimizer::kAccessCheck);
2815 // Deoptimize for proxies.
2816 __ CompareInstanceType(object_map, object_instance_type, JS_PROXY_TYPE);
2817 DeoptimizeIf(eq, instr, Deoptimizer::kProxy);
2818
2819 __ Ldr(object_prototype, FieldMemOperand(object_map, Map::kPrototypeOffset));
2820 __ Cmp(object_prototype, prototype);
2821 __ B(eq, instr->TrueLabel(chunk_));
2822 __ CompareRoot(object_prototype, Heap::kNullValueRootIndex);
2823 __ B(eq, instr->FalseLabel(chunk_));
2824 __ Ldr(object_map, FieldMemOperand(object_prototype, HeapObject::kMapOffset));
2825 __ B(&loop);
2826}
2827
2828
2829void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
2830 DoGap(instr);
2831}
2832
2833
2834void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
2835 Register value = ToRegister32(instr->value());
2836 DoubleRegister result = ToDoubleRegister(instr->result());
2837 __ Scvtf(result, value);
2838}
2839
2840
2841void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
2842 DCHECK(ToRegister(instr->context()).is(cp));
2843 // The function is required to be in x1.
2844 DCHECK(ToRegister(instr->function()).is(x1));
2845 DCHECK(instr->HasPointerMap());
2846
2847 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
2848 if (known_function.is_null()) {
2849 LPointerMap* pointers = instr->pointer_map();
2850 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
2851 ParameterCount count(instr->arity());
2852 __ InvokeFunction(x1, no_reg, count, CALL_FUNCTION, generator);
2853 } else {
2854 CallKnownFunction(known_function,
2855 instr->hydrogen()->formal_parameter_count(),
2856 instr->arity(), instr);
2857 }
2858 RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
2859}
2860
2861
2862Condition LCodeGen::EmitIsString(Register input,
2863 Register temp1,
2864 Label* is_not_string,
2865 SmiCheck check_needed = INLINE_SMI_CHECK) {
2866 if (check_needed == INLINE_SMI_CHECK) {
2867 __ JumpIfSmi(input, is_not_string);
2868 }
2869 __ CompareObjectType(input, temp1, temp1, FIRST_NONSTRING_TYPE);
2870
2871 return lt;
2872}
2873
2874
2875void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2876 Register val = ToRegister(instr->value());
2877 Register scratch = ToRegister(instr->temp());
2878
2879 SmiCheck check_needed =
2880 instr->hydrogen()->value()->type().IsHeapObject()
2881 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2882 Condition true_cond =
2883 EmitIsString(val, scratch, instr->FalseLabel(chunk_), check_needed);
2884
2885 EmitBranch(instr, true_cond);
2886}
2887
2888
2889void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2890 Register value = ToRegister(instr->value());
2891 STATIC_ASSERT(kSmiTag == 0);
2892 EmitTestAndBranch(instr, eq, value, kSmiTagMask);
2893}
2894
2895
2896void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2897 Register input = ToRegister(instr->value());
2898 Register temp = ToRegister(instr->temp());
2899
2900 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2901 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2902 }
2903 __ Ldr(temp, FieldMemOperand(input, HeapObject::kMapOffset));
2904 __ Ldrb(temp, FieldMemOperand(temp, Map::kBitFieldOffset));
2905
2906 EmitTestAndBranch(instr, ne, temp, 1 << Map::kIsUndetectable);
2907}
2908
2909
2910static const char* LabelType(LLabel* label) {
2911 if (label->is_loop_header()) return " (loop header)";
2912 if (label->is_osr_entry()) return " (OSR entry)";
2913 return "";
2914}
2915
2916
2917void LCodeGen::DoLabel(LLabel* label) {
2918 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
2919 current_instruction_,
2920 label->hydrogen_value()->id(),
2921 label->block_id(),
2922 LabelType(label));
2923
2924 // Inherit pushed_arguments_ from the predecessor's argument count.
2925 if (label->block()->HasPredecessor()) {
2926 pushed_arguments_ = label->block()->predecessors()->at(0)->argument_count();
2927#ifdef DEBUG
2928 for (auto p : *label->block()->predecessors()) {
2929 DCHECK_EQ(p->argument_count(), pushed_arguments_);
2930 }
2931#endif
2932 }
2933
2934 __ Bind(label->label());
2935 current_block_ = label->block_id();
2936 DoGap(label);
2937}
2938
2939
2940void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2941 Register context = ToRegister(instr->context());
2942 Register result = ToRegister(instr->result());
2943 __ Ldr(result, ContextMemOperand(context, instr->slot_index()));
2944 if (instr->hydrogen()->RequiresHoleCheck()) {
2945 if (instr->hydrogen()->DeoptimizesOnHole()) {
2946 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
2947 Deoptimizer::kHole);
2948 } else {
2949 Label not_the_hole;
2950 __ JumpIfNotRoot(result, Heap::kTheHoleValueRootIndex, &not_the_hole);
2951 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2952 __ Bind(&not_the_hole);
2953 }
2954 }
2955}
2956
2957
2958void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2959 Register function = ToRegister(instr->function());
2960 Register result = ToRegister(instr->result());
2961 Register temp = ToRegister(instr->temp());
2962
2963 // Get the prototype or initial map from the function.
2964 __ Ldr(result, FieldMemOperand(function,
2965 JSFunction::kPrototypeOrInitialMapOffset));
2966
2967 // Check that the function has a prototype or an initial map.
2968 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
2969 Deoptimizer::kHole);
2970
2971 // If the function does not have an initial map, we're done.
2972 Label done;
2973 __ CompareObjectType(result, temp, temp, MAP_TYPE);
2974 __ B(ne, &done);
2975
2976 // Get the prototype from the initial map.
2977 __ Ldr(result, FieldMemOperand(result, Map::kPrototypeOffset));
2978
2979 // All done.
2980 __ Bind(&done);
2981}
2982
2983
2984template <class T>
2985void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2986 Register vector_register = ToRegister(instr->temp_vector());
2987 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2988 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2989 DCHECK(slot_register.is(x0));
2990
2991 AllowDeferredHandleDereference vector_structure_check;
2992 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2993 __ Mov(vector_register, vector);
2994 // No need to allocate this register.
2995 FeedbackVectorSlot slot = instr->hydrogen()->slot();
2996 int index = vector->GetIndex(slot);
2997 __ Mov(slot_register, Smi::FromInt(index));
2998}
2999
3000
3001template <class T>
3002void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
3003 Register vector_register = ToRegister(instr->temp_vector());
3004 Register slot_register = ToRegister(instr->temp_slot());
3005
3006 AllowDeferredHandleDereference vector_structure_check;
3007 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3008 __ Mov(vector_register, vector);
3009 FeedbackVectorSlot slot = instr->hydrogen()->slot();
3010 int index = vector->GetIndex(slot);
3011 __ Mov(slot_register, Smi::FromInt(index));
3012}
3013
3014
3015void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3016 DCHECK(ToRegister(instr->context()).is(cp));
3017 DCHECK(ToRegister(instr->global_object())
3018 .is(LoadDescriptor::ReceiverRegister()));
3019 DCHECK(ToRegister(instr->result()).Is(x0));
3020 __ Mov(LoadDescriptor::NameRegister(), Operand(instr->name()));
3021 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
Ben Murdoch097c5b22016-05-18 11:27:45 +01003022 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3023 isolate(), instr->typeof_mode(), PREMONOMORPHIC)
3024 .code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003025 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3026}
3027
3028
3029MemOperand LCodeGen::PrepareKeyedExternalArrayOperand(
3030 Register key,
3031 Register base,
3032 Register scratch,
3033 bool key_is_smi,
3034 bool key_is_constant,
3035 int constant_key,
3036 ElementsKind elements_kind,
3037 int base_offset) {
3038 int element_size_shift = ElementsKindToShiftSize(elements_kind);
3039
3040 if (key_is_constant) {
3041 int key_offset = constant_key << element_size_shift;
3042 return MemOperand(base, key_offset + base_offset);
3043 }
3044
3045 if (key_is_smi) {
3046 __ Add(scratch, base, Operand::UntagSmiAndScale(key, element_size_shift));
3047 return MemOperand(scratch, base_offset);
3048 }
3049
3050 if (base_offset == 0) {
3051 return MemOperand(base, key, SXTW, element_size_shift);
3052 }
3053
3054 DCHECK(!AreAliased(scratch, key));
3055 __ Add(scratch, base, base_offset);
3056 return MemOperand(scratch, key, SXTW, element_size_shift);
3057}
3058
3059
3060void LCodeGen::DoLoadKeyedExternal(LLoadKeyedExternal* instr) {
3061 Register ext_ptr = ToRegister(instr->elements());
3062 Register scratch;
3063 ElementsKind elements_kind = instr->elements_kind();
3064
3065 bool key_is_smi = instr->hydrogen()->key()->representation().IsSmi();
3066 bool key_is_constant = instr->key()->IsConstantOperand();
3067 Register key = no_reg;
3068 int constant_key = 0;
3069 if (key_is_constant) {
3070 DCHECK(instr->temp() == NULL);
3071 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3072 if (constant_key & 0xf0000000) {
3073 Abort(kArrayIndexConstantValueTooBig);
3074 }
3075 } else {
3076 scratch = ToRegister(instr->temp());
3077 key = ToRegister(instr->key());
3078 }
3079
3080 MemOperand mem_op =
3081 PrepareKeyedExternalArrayOperand(key, ext_ptr, scratch, key_is_smi,
3082 key_is_constant, constant_key,
3083 elements_kind,
3084 instr->base_offset());
3085
3086 if (elements_kind == FLOAT32_ELEMENTS) {
3087 DoubleRegister result = ToDoubleRegister(instr->result());
3088 __ Ldr(result.S(), mem_op);
3089 __ Fcvt(result, result.S());
3090 } else if (elements_kind == FLOAT64_ELEMENTS) {
3091 DoubleRegister result = ToDoubleRegister(instr->result());
3092 __ Ldr(result, mem_op);
3093 } else {
3094 Register result = ToRegister(instr->result());
3095
3096 switch (elements_kind) {
3097 case INT8_ELEMENTS:
3098 __ Ldrsb(result, mem_op);
3099 break;
3100 case UINT8_ELEMENTS:
3101 case UINT8_CLAMPED_ELEMENTS:
3102 __ Ldrb(result, mem_op);
3103 break;
3104 case INT16_ELEMENTS:
3105 __ Ldrsh(result, mem_op);
3106 break;
3107 case UINT16_ELEMENTS:
3108 __ Ldrh(result, mem_op);
3109 break;
3110 case INT32_ELEMENTS:
3111 __ Ldrsw(result, mem_op);
3112 break;
3113 case UINT32_ELEMENTS:
3114 __ Ldr(result.W(), mem_op);
3115 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3116 // Deopt if value > 0x80000000.
3117 __ Tst(result, 0xFFFFFFFF80000000);
3118 DeoptimizeIf(ne, instr, Deoptimizer::kNegativeValue);
3119 }
3120 break;
3121 case FLOAT32_ELEMENTS:
3122 case FLOAT64_ELEMENTS:
3123 case FAST_HOLEY_DOUBLE_ELEMENTS:
3124 case FAST_HOLEY_ELEMENTS:
3125 case FAST_HOLEY_SMI_ELEMENTS:
3126 case FAST_DOUBLE_ELEMENTS:
3127 case FAST_ELEMENTS:
3128 case FAST_SMI_ELEMENTS:
3129 case DICTIONARY_ELEMENTS:
3130 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3131 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
Ben Murdoch097c5b22016-05-18 11:27:45 +01003132 case FAST_STRING_WRAPPER_ELEMENTS:
3133 case SLOW_STRING_WRAPPER_ELEMENTS:
3134 case NO_ELEMENTS:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003135 UNREACHABLE();
3136 break;
3137 }
3138 }
3139}
3140
3141
3142MemOperand LCodeGen::PrepareKeyedArrayOperand(Register base,
3143 Register elements,
3144 Register key,
3145 bool key_is_tagged,
3146 ElementsKind elements_kind,
3147 Representation representation,
3148 int base_offset) {
3149 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3150 STATIC_ASSERT(kSmiTag == 0);
3151 int element_size_shift = ElementsKindToShiftSize(elements_kind);
3152
3153 // Even though the HLoad/StoreKeyed instructions force the input
3154 // representation for the key to be an integer, the input gets replaced during
3155 // bounds check elimination with the index argument to the bounds check, which
3156 // can be tagged, so that case must be handled here, too.
3157 if (key_is_tagged) {
3158 __ Add(base, elements, Operand::UntagSmiAndScale(key, element_size_shift));
3159 if (representation.IsInteger32()) {
3160 DCHECK(elements_kind == FAST_SMI_ELEMENTS);
3161 // Read or write only the smi payload in the case of fast smi arrays.
3162 return UntagSmiMemOperand(base, base_offset);
3163 } else {
3164 return MemOperand(base, base_offset);
3165 }
3166 } else {
3167 // Sign extend key because it could be a 32-bit negative value or contain
3168 // garbage in the top 32-bits. The address computation happens in 64-bit.
3169 DCHECK((element_size_shift >= 0) && (element_size_shift <= 4));
3170 if (representation.IsInteger32()) {
3171 DCHECK(elements_kind == FAST_SMI_ELEMENTS);
3172 // Read or write only the smi payload in the case of fast smi arrays.
3173 __ Add(base, elements, Operand(key, SXTW, element_size_shift));
3174 return UntagSmiMemOperand(base, base_offset);
3175 } else {
3176 __ Add(base, elements, base_offset);
3177 return MemOperand(base, key, SXTW, element_size_shift);
3178 }
3179 }
3180}
3181
3182
3183void LCodeGen::DoLoadKeyedFixedDouble(LLoadKeyedFixedDouble* instr) {
3184 Register elements = ToRegister(instr->elements());
3185 DoubleRegister result = ToDoubleRegister(instr->result());
3186 MemOperand mem_op;
3187
3188 if (instr->key()->IsConstantOperand()) {
3189 DCHECK(instr->hydrogen()->RequiresHoleCheck() ||
3190 (instr->temp() == NULL));
3191
3192 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3193 if (constant_key & 0xf0000000) {
3194 Abort(kArrayIndexConstantValueTooBig);
3195 }
3196 int offset = instr->base_offset() + constant_key * kDoubleSize;
3197 mem_op = MemOperand(elements, offset);
3198 } else {
3199 Register load_base = ToRegister(instr->temp());
3200 Register key = ToRegister(instr->key());
3201 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3202 mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3203 instr->hydrogen()->elements_kind(),
3204 instr->hydrogen()->representation(),
3205 instr->base_offset());
3206 }
3207
3208 __ Ldr(result, mem_op);
3209
3210 if (instr->hydrogen()->RequiresHoleCheck()) {
3211 Register scratch = ToRegister(instr->temp());
3212 __ Fmov(scratch, result);
3213 __ Eor(scratch, scratch, kHoleNanInt64);
3214 DeoptimizeIfZero(scratch, instr, Deoptimizer::kHole);
3215 }
3216}
3217
3218
3219void LCodeGen::DoLoadKeyedFixed(LLoadKeyedFixed* instr) {
3220 Register elements = ToRegister(instr->elements());
3221 Register result = ToRegister(instr->result());
3222 MemOperand mem_op;
3223
3224 Representation representation = instr->hydrogen()->representation();
3225 if (instr->key()->IsConstantOperand()) {
3226 DCHECK(instr->temp() == NULL);
3227 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
3228 int offset = instr->base_offset() +
3229 ToInteger32(const_operand) * kPointerSize;
3230 if (representation.IsInteger32()) {
3231 DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
3232 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3233 STATIC_ASSERT(kSmiTag == 0);
3234 mem_op = UntagSmiMemOperand(elements, offset);
3235 } else {
3236 mem_op = MemOperand(elements, offset);
3237 }
3238 } else {
3239 Register load_base = ToRegister(instr->temp());
3240 Register key = ToRegister(instr->key());
3241 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
3242
3243 mem_op = PrepareKeyedArrayOperand(load_base, elements, key, key_is_tagged,
3244 instr->hydrogen()->elements_kind(),
3245 representation, instr->base_offset());
3246 }
3247
3248 __ Load(result, mem_op, representation);
3249
3250 if (instr->hydrogen()->RequiresHoleCheck()) {
3251 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3252 DeoptimizeIfNotSmi(result, instr, Deoptimizer::kNotASmi);
3253 } else {
3254 DeoptimizeIfRoot(result, Heap::kTheHoleValueRootIndex, instr,
3255 Deoptimizer::kHole);
3256 }
3257 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3258 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3259 Label done;
3260 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
3261 __ B(ne, &done);
3262 if (info()->IsStub()) {
3263 // A stub can safely convert the hole to undefined only if the array
3264 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3265 // it needs to bail out.
3266 __ LoadRoot(result, Heap::kArrayProtectorRootIndex);
3267 __ Ldr(result, FieldMemOperand(result, Cell::kValueOffset));
3268 __ Cmp(result, Operand(Smi::FromInt(Isolate::kArrayProtectorValid)));
3269 DeoptimizeIf(ne, instr, Deoptimizer::kHole);
3270 }
3271 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
3272 __ Bind(&done);
3273 }
3274}
3275
3276
3277void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3278 DCHECK(ToRegister(instr->context()).is(cp));
3279 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3280 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3281
3282 if (instr->hydrogen()->HasVectorAndSlot()) {
3283 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3284 }
3285
3286 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
Ben Murdoch097c5b22016-05-18 11:27:45 +01003287 isolate(), instr->hydrogen()->initialization_state())
3288 .code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003289 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3290
3291 DCHECK(ToRegister(instr->result()).Is(x0));
3292}
3293
3294
3295void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3296 HObjectAccess access = instr->hydrogen()->access();
3297 int offset = access.offset();
3298 Register object = ToRegister(instr->object());
3299
3300 if (access.IsExternalMemory()) {
3301 Register result = ToRegister(instr->result());
3302 __ Load(result, MemOperand(object, offset), access.representation());
3303 return;
3304 }
3305
3306 if (instr->hydrogen()->representation().IsDouble()) {
3307 DCHECK(access.IsInobject());
3308 FPRegister result = ToDoubleRegister(instr->result());
3309 __ Ldr(result, FieldMemOperand(object, offset));
3310 return;
3311 }
3312
3313 Register result = ToRegister(instr->result());
3314 Register source;
3315 if (access.IsInobject()) {
3316 source = object;
3317 } else {
3318 // Load the properties array, using result as a scratch register.
3319 __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
3320 source = result;
3321 }
3322
3323 if (access.representation().IsSmi() &&
3324 instr->hydrogen()->representation().IsInteger32()) {
3325 // Read int value directly from upper half of the smi.
3326 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
3327 STATIC_ASSERT(kSmiTag == 0);
3328 __ Load(result, UntagSmiFieldMemOperand(source, offset),
3329 Representation::Integer32());
3330 } else {
3331 __ Load(result, FieldMemOperand(source, offset), access.representation());
3332 }
3333}
3334
3335
3336void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3337 DCHECK(ToRegister(instr->context()).is(cp));
3338 // LoadIC expects name and receiver in registers.
3339 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3340 __ Mov(LoadDescriptor::NameRegister(), Operand(instr->name()));
3341 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
Ben Murdoch097c5b22016-05-18 11:27:45 +01003342 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3343 isolate(), NOT_INSIDE_TYPEOF,
3344 instr->hydrogen()->initialization_state())
3345 .code();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003346 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3347
3348 DCHECK(ToRegister(instr->result()).is(x0));
3349}
3350
3351
3352void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3353 Register result = ToRegister(instr->result());
3354 __ LoadRoot(result, instr->index());
3355}
3356
3357
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003358void LCodeGen::DoMathAbs(LMathAbs* instr) {
3359 Representation r = instr->hydrogen()->value()->representation();
3360 if (r.IsDouble()) {
3361 DoubleRegister input = ToDoubleRegister(instr->value());
3362 DoubleRegister result = ToDoubleRegister(instr->result());
3363 __ Fabs(result, input);
3364 } else if (r.IsSmi() || r.IsInteger32()) {
3365 Register input = r.IsSmi() ? ToRegister(instr->value())
3366 : ToRegister32(instr->value());
3367 Register result = r.IsSmi() ? ToRegister(instr->result())
3368 : ToRegister32(instr->result());
3369 __ Abs(result, input);
3370 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3371 }
3372}
3373
3374
3375void LCodeGen::DoDeferredMathAbsTagged(LMathAbsTagged* instr,
3376 Label* exit,
3377 Label* allocation_entry) {
3378 // Handle the tricky cases of MathAbsTagged:
3379 // - HeapNumber inputs.
3380 // - Negative inputs produce a positive result, so a new HeapNumber is
3381 // allocated to hold it.
3382 // - Positive inputs are returned as-is, since there is no need to allocate
3383 // a new HeapNumber for the result.
3384 // - The (smi) input -0x80000000, produces +0x80000000, which does not fit
3385 // a smi. In this case, the inline code sets the result and jumps directly
3386 // to the allocation_entry label.
3387 DCHECK(instr->context() != NULL);
3388 DCHECK(ToRegister(instr->context()).is(cp));
3389 Register input = ToRegister(instr->value());
3390 Register temp1 = ToRegister(instr->temp1());
3391 Register temp2 = ToRegister(instr->temp2());
3392 Register result_bits = ToRegister(instr->temp3());
3393 Register result = ToRegister(instr->result());
3394
3395 Label runtime_allocation;
3396
3397 // Deoptimize if the input is not a HeapNumber.
3398 DeoptimizeIfNotHeapNumber(input, instr);
3399
3400 // If the argument is positive, we can return it as-is, without any need to
3401 // allocate a new HeapNumber for the result. We have to do this in integer
3402 // registers (rather than with fabs) because we need to be able to distinguish
3403 // the two zeroes.
3404 __ Ldr(result_bits, FieldMemOperand(input, HeapNumber::kValueOffset));
3405 __ Mov(result, input);
3406 __ Tbz(result_bits, kXSignBit, exit);
3407
3408 // Calculate abs(input) by clearing the sign bit.
3409 __ Bic(result_bits, result_bits, kXSignMask);
3410
3411 // Allocate a new HeapNumber to hold the result.
3412 // result_bits The bit representation of the (double) result.
3413 __ Bind(allocation_entry);
3414 __ AllocateHeapNumber(result, &runtime_allocation, temp1, temp2);
3415 // The inline (non-deferred) code will store result_bits into result.
3416 __ B(exit);
3417
3418 __ Bind(&runtime_allocation);
3419 if (FLAG_debug_code) {
3420 // Because result is in the pointer map, we need to make sure it has a valid
3421 // tagged value before we call the runtime. We speculatively set it to the
3422 // input (for abs(+x)) or to a smi (for abs(-SMI_MIN)), so it should already
3423 // be valid.
3424 Label result_ok;
3425 Register input = ToRegister(instr->value());
3426 __ JumpIfSmi(result, &result_ok);
3427 __ Cmp(input, result);
3428 __ Assert(eq, kUnexpectedValue);
3429 __ Bind(&result_ok);
3430 }
3431
3432 { PushSafepointRegistersScope scope(this);
3433 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr,
3434 instr->context());
3435 __ StoreToSafepointRegisterSlot(x0, result);
3436 }
3437 // The inline (non-deferred) code will store result_bits into result.
3438}
3439
3440
3441void LCodeGen::DoMathAbsTagged(LMathAbsTagged* instr) {
3442 // Class for deferred case.
3443 class DeferredMathAbsTagged: public LDeferredCode {
3444 public:
3445 DeferredMathAbsTagged(LCodeGen* codegen, LMathAbsTagged* instr)
3446 : LDeferredCode(codegen), instr_(instr) { }
3447 virtual void Generate() {
3448 codegen()->DoDeferredMathAbsTagged(instr_, exit(),
3449 allocation_entry());
3450 }
3451 virtual LInstruction* instr() { return instr_; }
3452 Label* allocation_entry() { return &allocation; }
3453 private:
3454 LMathAbsTagged* instr_;
3455 Label allocation;
3456 };
3457
3458 // TODO(jbramley): The early-exit mechanism would skip the new frame handling
3459 // in GenerateDeferredCode. Tidy this up.
3460 DCHECK(!NeedsDeferredFrame());
3461
3462 DeferredMathAbsTagged* deferred =
3463 new(zone()) DeferredMathAbsTagged(this, instr);
3464
3465 DCHECK(instr->hydrogen()->value()->representation().IsTagged() ||
3466 instr->hydrogen()->value()->representation().IsSmi());
3467 Register input = ToRegister(instr->value());
3468 Register result_bits = ToRegister(instr->temp3());
3469 Register result = ToRegister(instr->result());
3470 Label done;
3471
3472 // Handle smis inline.
3473 // We can treat smis as 64-bit integers, since the (low-order) tag bits will
3474 // never get set by the negation. This is therefore the same as the Integer32
3475 // case in DoMathAbs, except that it operates on 64-bit values.
3476 STATIC_ASSERT((kSmiValueSize == 32) && (kSmiShift == 32) && (kSmiTag == 0));
3477
3478 __ JumpIfNotSmi(input, deferred->entry());
3479
3480 __ Abs(result, input, NULL, &done);
3481
3482 // The result is the magnitude (abs) of the smallest value a smi can
3483 // represent, encoded as a double.
3484 __ Mov(result_bits, double_to_rawbits(0x80000000));
3485 __ B(deferred->allocation_entry());
3486
3487 __ Bind(deferred->exit());
3488 __ Str(result_bits, FieldMemOperand(result, HeapNumber::kValueOffset));
3489
3490 __ Bind(&done);
3491}
3492
3493
3494void LCodeGen::DoMathExp(LMathExp* instr) {
3495 DoubleRegister input = ToDoubleRegister(instr->value());
3496 DoubleRegister result = ToDoubleRegister(instr->result());
3497 DoubleRegister double_temp1 = ToDoubleRegister(instr->double_temp1());
3498 DoubleRegister double_temp2 = double_scratch();
3499 Register temp1 = ToRegister(instr->temp1());
3500 Register temp2 = ToRegister(instr->temp2());
3501 Register temp3 = ToRegister(instr->temp3());
3502
3503 MathExpGenerator::EmitMathExp(masm(), input, result,
3504 double_temp1, double_temp2,
3505 temp1, temp2, temp3);
3506}
3507
3508
3509void LCodeGen::DoMathFloorD(LMathFloorD* instr) {
3510 DoubleRegister input = ToDoubleRegister(instr->value());
3511 DoubleRegister result = ToDoubleRegister(instr->result());
3512
3513 __ Frintm(result, input);
3514}
3515
3516
3517void LCodeGen::DoMathFloorI(LMathFloorI* instr) {
3518 DoubleRegister input = ToDoubleRegister(instr->value());
3519 Register result = ToRegister(instr->result());
3520
3521 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3522 DeoptimizeIfMinusZero(input, instr, Deoptimizer::kMinusZero);
3523 }
3524
3525 __ Fcvtms(result, input);
3526
3527 // Check that the result fits into a 32-bit integer.
3528 // - The result did not overflow.
3529 __ Cmp(result, Operand(result, SXTW));
3530 // - The input was not NaN.
3531 __ Fccmp(input, input, NoFlag, eq);
3532 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
3533}
3534
3535
3536void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
3537 Register dividend = ToRegister32(instr->dividend());
3538 Register result = ToRegister32(instr->result());
3539 int32_t divisor = instr->divisor();
3540
3541 // If the divisor is 1, return the dividend.
3542 if (divisor == 1) {
3543 __ Mov(result, dividend, kDiscardForSameWReg);
3544 return;
3545 }
3546
3547 // If the divisor is positive, things are easy: There can be no deopts and we
3548 // can simply do an arithmetic right shift.
3549 int32_t shift = WhichPowerOf2Abs(divisor);
3550 if (divisor > 1) {
3551 __ Mov(result, Operand(dividend, ASR, shift));
3552 return;
3553 }
3554
3555 // If the divisor is negative, we have to negate and handle edge cases.
3556 __ Negs(result, dividend);
3557 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3558 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
3559 }
3560
3561 // Dividing by -1 is basically negation, unless we overflow.
3562 if (divisor == -1) {
3563 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3564 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3565 }
3566 return;
3567 }
3568
3569 // If the negation could not overflow, simply shifting is OK.
3570 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
3571 __ Mov(result, Operand(dividend, ASR, shift));
3572 return;
3573 }
3574
3575 __ Asr(result, result, shift);
3576 __ Csel(result, result, kMinInt / divisor, vc);
3577}
3578
3579
3580void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
3581 Register dividend = ToRegister32(instr->dividend());
3582 int32_t divisor = instr->divisor();
3583 Register result = ToRegister32(instr->result());
3584 DCHECK(!AreAliased(dividend, result));
3585
3586 if (divisor == 0) {
3587 Deoptimize(instr, Deoptimizer::kDivisionByZero);
3588 return;
3589 }
3590
3591 // Check for (0 / -x) that will produce negative zero.
3592 HMathFloorOfDiv* hdiv = instr->hydrogen();
3593 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
3594 DeoptimizeIfZero(dividend, instr, Deoptimizer::kMinusZero);
3595 }
3596
3597 // Easy case: We need no dynamic check for the dividend and the flooring
3598 // division is the same as the truncating division.
3599 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
3600 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
3601 __ TruncatingDiv(result, dividend, Abs(divisor));
3602 if (divisor < 0) __ Neg(result, result);
3603 return;
3604 }
3605
3606 // In the general case we may need to adjust before and after the truncating
3607 // division to get a flooring division.
3608 Register temp = ToRegister32(instr->temp());
3609 DCHECK(!AreAliased(temp, dividend, result));
3610 Label needs_adjustment, done;
3611 __ Cmp(dividend, 0);
3612 __ B(divisor > 0 ? lt : gt, &needs_adjustment);
3613 __ TruncatingDiv(result, dividend, Abs(divisor));
3614 if (divisor < 0) __ Neg(result, result);
3615 __ B(&done);
3616 __ Bind(&needs_adjustment);
3617 __ Add(temp, dividend, Operand(divisor > 0 ? 1 : -1));
3618 __ TruncatingDiv(result, temp, Abs(divisor));
3619 if (divisor < 0) __ Neg(result, result);
3620 __ Sub(result, result, Operand(1));
3621 __ Bind(&done);
3622}
3623
3624
3625// TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
3626void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
3627 Register dividend = ToRegister32(instr->dividend());
3628 Register divisor = ToRegister32(instr->divisor());
3629 Register remainder = ToRegister32(instr->temp());
3630 Register result = ToRegister32(instr->result());
3631
3632 // This can't cause an exception on ARM, so we can speculatively
3633 // execute it already now.
3634 __ Sdiv(result, dividend, divisor);
3635
3636 // Check for x / 0.
3637 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
3638
3639 // Check for (kMinInt / -1).
3640 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
3641 // The V flag will be set iff dividend == kMinInt.
3642 __ Cmp(dividend, 1);
3643 __ Ccmp(divisor, -1, NoFlag, vs);
3644 DeoptimizeIf(eq, instr, Deoptimizer::kOverflow);
3645 }
3646
3647 // Check for (0 / -x) that will produce negative zero.
3648 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3649 __ Cmp(divisor, 0);
3650 __ Ccmp(dividend, 0, ZFlag, mi);
3651 // "divisor" can't be null because the code would have already been
3652 // deoptimized. The Z flag is set only if (divisor < 0) and (dividend == 0).
3653 // In this case we need to deoptimize to produce a -0.
3654 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
3655 }
3656
3657 Label done;
3658 // If both operands have the same sign then we are done.
3659 __ Eor(remainder, dividend, divisor);
3660 __ Tbz(remainder, kWSignBit, &done);
3661
3662 // Check if the result needs to be corrected.
3663 __ Msub(remainder, result, divisor, dividend);
3664 __ Cbz(remainder, &done);
3665 __ Sub(result, result, 1);
3666
3667 __ Bind(&done);
3668}
3669
3670
3671void LCodeGen::DoMathLog(LMathLog* instr) {
3672 DCHECK(instr->IsMarkedAsCall());
3673 DCHECK(ToDoubleRegister(instr->value()).is(d0));
3674 __ CallCFunction(ExternalReference::math_log_double_function(isolate()),
3675 0, 1);
3676 DCHECK(ToDoubleRegister(instr->result()).Is(d0));
3677}
3678
3679
3680void LCodeGen::DoMathClz32(LMathClz32* instr) {
3681 Register input = ToRegister32(instr->value());
3682 Register result = ToRegister32(instr->result());
3683 __ Clz(result, input);
3684}
3685
3686
3687void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3688 DoubleRegister input = ToDoubleRegister(instr->value());
3689 DoubleRegister result = ToDoubleRegister(instr->result());
3690 Label done;
3691
3692 // Math.pow(x, 0.5) differs from fsqrt(x) in the following cases:
3693 // Math.pow(-Infinity, 0.5) == +Infinity
3694 // Math.pow(-0.0, 0.5) == +0.0
3695
3696 // Catch -infinity inputs first.
3697 // TODO(jbramley): A constant infinity register would be helpful here.
3698 __ Fmov(double_scratch(), kFP64NegativeInfinity);
3699 __ Fcmp(double_scratch(), input);
3700 __ Fabs(result, input);
3701 __ B(&done, eq);
3702
3703 // Add +0.0 to convert -0.0 to +0.0.
3704 __ Fadd(double_scratch(), input, fp_zero);
3705 __ Fsqrt(result, double_scratch());
3706
3707 __ Bind(&done);
3708}
3709
3710
3711void LCodeGen::DoPower(LPower* instr) {
3712 Representation exponent_type = instr->hydrogen()->right()->representation();
3713 // Having marked this as a call, we can use any registers.
3714 // Just make sure that the input/output registers are the expected ones.
3715 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3716 Register integer_exponent = MathPowIntegerDescriptor::exponent();
3717 DCHECK(!instr->right()->IsDoubleRegister() ||
3718 ToDoubleRegister(instr->right()).is(d1));
3719 DCHECK(exponent_type.IsInteger32() || !instr->right()->IsRegister() ||
3720 ToRegister(instr->right()).is(tagged_exponent));
3721 DCHECK(!exponent_type.IsInteger32() ||
3722 ToRegister(instr->right()).is(integer_exponent));
3723 DCHECK(ToDoubleRegister(instr->left()).is(d0));
3724 DCHECK(ToDoubleRegister(instr->result()).is(d0));
3725
3726 if (exponent_type.IsSmi()) {
3727 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3728 __ CallStub(&stub);
3729 } else if (exponent_type.IsTagged()) {
3730 Label no_deopt;
3731 __ JumpIfSmi(tagged_exponent, &no_deopt);
3732 DeoptimizeIfNotHeapNumber(tagged_exponent, instr);
3733 __ Bind(&no_deopt);
3734 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3735 __ CallStub(&stub);
3736 } else if (exponent_type.IsInteger32()) {
3737 // Ensure integer exponent has no garbage in top 32-bits, as MathPowStub
3738 // supports large integer exponents.
3739 __ Sxtw(integer_exponent, integer_exponent);
3740 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3741 __ CallStub(&stub);
3742 } else {
3743 DCHECK(exponent_type.IsDouble());
3744 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3745 __ CallStub(&stub);
3746 }
3747}
3748
3749
3750void LCodeGen::DoMathRoundD(LMathRoundD* instr) {
3751 DoubleRegister input = ToDoubleRegister(instr->value());
3752 DoubleRegister result = ToDoubleRegister(instr->result());
3753 DoubleRegister scratch_d = double_scratch();
3754
3755 DCHECK(!AreAliased(input, result, scratch_d));
3756
3757 Label done;
3758
3759 __ Frinta(result, input);
3760 __ Fcmp(input, 0.0);
3761 __ Fccmp(result, input, ZFlag, lt);
3762 // The result is correct if the input was in [-0, +infinity], or was a
3763 // negative integral value.
3764 __ B(eq, &done);
3765
3766 // Here the input is negative, non integral, with an exponent lower than 52.
3767 // We do not have to worry about the 0.49999999999999994 (0x3fdfffffffffffff)
3768 // case. So we can safely add 0.5.
3769 __ Fmov(scratch_d, 0.5);
3770 __ Fadd(result, input, scratch_d);
3771 __ Frintm(result, result);
3772 // The range [-0.5, -0.0[ yielded +0.0. Force the sign to negative.
3773 __ Fabs(result, result);
3774 __ Fneg(result, result);
3775
3776 __ Bind(&done);
3777}
3778
3779
3780void LCodeGen::DoMathRoundI(LMathRoundI* instr) {
3781 DoubleRegister input = ToDoubleRegister(instr->value());
3782 DoubleRegister temp = ToDoubleRegister(instr->temp1());
3783 DoubleRegister dot_five = double_scratch();
3784 Register result = ToRegister(instr->result());
3785 Label done;
3786
3787 // Math.round() rounds to the nearest integer, with ties going towards
3788 // +infinity. This does not match any IEEE-754 rounding mode.
3789 // - Infinities and NaNs are propagated unchanged, but cause deopts because
3790 // they can't be represented as integers.
3791 // - The sign of the result is the same as the sign of the input. This means
3792 // that -0.0 rounds to itself, and values -0.5 <= input < 0 also produce a
3793 // result of -0.0.
3794
3795 // Add 0.5 and round towards -infinity.
3796 __ Fmov(dot_five, 0.5);
3797 __ Fadd(temp, input, dot_five);
3798 __ Fcvtms(result, temp);
3799
3800 // The result is correct if:
3801 // result is not 0, as the input could be NaN or [-0.5, -0.0].
3802 // result is not 1, as 0.499...94 will wrongly map to 1.
3803 // result fits in 32 bits.
3804 __ Cmp(result, Operand(result.W(), SXTW));
3805 __ Ccmp(result, 1, ZFlag, eq);
3806 __ B(hi, &done);
3807
3808 // At this point, we have to handle possible inputs of NaN or numbers in the
3809 // range [-0.5, 1.5[, or numbers larger than 32 bits.
3810
3811 // Deoptimize if the result > 1, as it must be larger than 32 bits.
3812 __ Cmp(result, 1);
3813 DeoptimizeIf(hi, instr, Deoptimizer::kOverflow);
3814
3815 // Deoptimize for negative inputs, which at this point are only numbers in
3816 // the range [-0.5, -0.0]
3817 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3818 __ Fmov(result, input);
3819 DeoptimizeIfNegative(result, instr, Deoptimizer::kMinusZero);
3820 }
3821
3822 // Deoptimize if the input was NaN.
3823 __ Fcmp(input, dot_five);
3824 DeoptimizeIf(vs, instr, Deoptimizer::kNaN);
3825
3826 // Now, the only unhandled inputs are in the range [0.0, 1.5[ (or [-0.5, 1.5[
3827 // if we didn't generate a -0.0 bailout). If input >= 0.5 then return 1,
3828 // else 0; we avoid dealing with 0.499...94 directly.
3829 __ Cset(result, ge);
3830 __ Bind(&done);
3831}
3832
3833
3834void LCodeGen::DoMathFround(LMathFround* instr) {
3835 DoubleRegister input = ToDoubleRegister(instr->value());
3836 DoubleRegister result = ToDoubleRegister(instr->result());
3837 __ Fcvt(result.S(), input);
3838 __ Fcvt(result, result.S());
3839}
3840
3841
3842void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3843 DoubleRegister input = ToDoubleRegister(instr->value());
3844 DoubleRegister result = ToDoubleRegister(instr->result());
3845 __ Fsqrt(result, input);
3846}
3847
3848
3849void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
3850 HMathMinMax::Operation op = instr->hydrogen()->operation();
3851 if (instr->hydrogen()->representation().IsInteger32()) {
3852 Register result = ToRegister32(instr->result());
3853 Register left = ToRegister32(instr->left());
3854 Operand right = ToOperand32(instr->right());
3855
3856 __ Cmp(left, right);
3857 __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
3858 } else if (instr->hydrogen()->representation().IsSmi()) {
3859 Register result = ToRegister(instr->result());
3860 Register left = ToRegister(instr->left());
3861 Operand right = ToOperand(instr->right());
3862
3863 __ Cmp(left, right);
3864 __ Csel(result, left, right, (op == HMathMinMax::kMathMax) ? ge : le);
3865 } else {
3866 DCHECK(instr->hydrogen()->representation().IsDouble());
3867 DoubleRegister result = ToDoubleRegister(instr->result());
3868 DoubleRegister left = ToDoubleRegister(instr->left());
3869 DoubleRegister right = ToDoubleRegister(instr->right());
3870
3871 if (op == HMathMinMax::kMathMax) {
3872 __ Fmax(result, left, right);
3873 } else {
3874 DCHECK(op == HMathMinMax::kMathMin);
3875 __ Fmin(result, left, right);
3876 }
3877 }
3878}
3879
3880
3881void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
3882 Register dividend = ToRegister32(instr->dividend());
3883 int32_t divisor = instr->divisor();
3884 DCHECK(dividend.is(ToRegister32(instr->result())));
3885
3886 // Theoretically, a variation of the branch-free code for integer division by
3887 // a power of 2 (calculating the remainder via an additional multiplication
3888 // (which gets simplified to an 'and') and subtraction) should be faster, and
3889 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
3890 // indicate that positive dividends are heavily favored, so the branching
3891 // version performs better.
3892 HMod* hmod = instr->hydrogen();
3893 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
3894 Label dividend_is_not_negative, done;
3895 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
3896 __ Tbz(dividend, kWSignBit, &dividend_is_not_negative);
3897 // Note that this is correct even for kMinInt operands.
3898 __ Neg(dividend, dividend);
3899 __ And(dividend, dividend, mask);
3900 __ Negs(dividend, dividend);
3901 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
3902 DeoptimizeIf(eq, instr, Deoptimizer::kMinusZero);
3903 }
3904 __ B(&done);
3905 }
3906
3907 __ bind(&dividend_is_not_negative);
3908 __ And(dividend, dividend, mask);
3909 __ bind(&done);
3910}
3911
3912
3913void LCodeGen::DoModByConstI(LModByConstI* instr) {
3914 Register dividend = ToRegister32(instr->dividend());
3915 int32_t divisor = instr->divisor();
3916 Register result = ToRegister32(instr->result());
3917 Register temp = ToRegister32(instr->temp());
3918 DCHECK(!AreAliased(dividend, result, temp));
3919
3920 if (divisor == 0) {
3921 Deoptimize(instr, Deoptimizer::kDivisionByZero);
3922 return;
3923 }
3924
3925 __ TruncatingDiv(result, dividend, Abs(divisor));
3926 __ Sxtw(dividend.X(), dividend);
3927 __ Mov(temp, Abs(divisor));
3928 __ Smsubl(result.X(), result, temp, dividend.X());
3929
3930 // Check for negative zero.
3931 HMod* hmod = instr->hydrogen();
3932 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
3933 Label remainder_not_zero;
3934 __ Cbnz(result, &remainder_not_zero);
3935 DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
3936 __ bind(&remainder_not_zero);
3937 }
3938}
3939
3940
3941void LCodeGen::DoModI(LModI* instr) {
3942 Register dividend = ToRegister32(instr->left());
3943 Register divisor = ToRegister32(instr->right());
3944 Register result = ToRegister32(instr->result());
3945
3946 Label done;
3947 // modulo = dividend - quotient * divisor
3948 __ Sdiv(result, dividend, divisor);
3949 if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
3950 DeoptimizeIfZero(divisor, instr, Deoptimizer::kDivisionByZero);
3951 }
3952 __ Msub(result, result, divisor, dividend);
3953 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3954 __ Cbnz(result, &done);
3955 DeoptimizeIfNegative(dividend, instr, Deoptimizer::kMinusZero);
3956 }
3957 __ Bind(&done);
3958}
3959
3960
3961void LCodeGen::DoMulConstIS(LMulConstIS* instr) {
3962 DCHECK(instr->hydrogen()->representation().IsSmiOrInteger32());
3963 bool is_smi = instr->hydrogen()->representation().IsSmi();
3964 Register result =
3965 is_smi ? ToRegister(instr->result()) : ToRegister32(instr->result());
3966 Register left =
3967 is_smi ? ToRegister(instr->left()) : ToRegister32(instr->left());
3968 int32_t right = ToInteger32(instr->right());
3969 DCHECK((right > -kMaxInt) && (right < kMaxInt));
3970
3971 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
3972 bool bailout_on_minus_zero =
3973 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
3974
3975 if (bailout_on_minus_zero) {
3976 if (right < 0) {
3977 // The result is -0 if right is negative and left is zero.
3978 DeoptimizeIfZero(left, instr, Deoptimizer::kMinusZero);
3979 } else if (right == 0) {
3980 // The result is -0 if the right is zero and the left is negative.
3981 DeoptimizeIfNegative(left, instr, Deoptimizer::kMinusZero);
3982 }
3983 }
3984
3985 switch (right) {
3986 // Cases which can detect overflow.
3987 case -1:
3988 if (can_overflow) {
3989 // Only 0x80000000 can overflow here.
3990 __ Negs(result, left);
3991 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
3992 } else {
3993 __ Neg(result, left);
3994 }
3995 break;
3996 case 0:
3997 // This case can never overflow.
3998 __ Mov(result, 0);
3999 break;
4000 case 1:
4001 // This case can never overflow.
4002 __ Mov(result, left, kDiscardForSameWReg);
4003 break;
4004 case 2:
4005 if (can_overflow) {
4006 __ Adds(result, left, left);
4007 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4008 } else {
4009 __ Add(result, left, left);
4010 }
4011 break;
4012
4013 default:
4014 // Multiplication by constant powers of two (and some related values)
4015 // can be done efficiently with shifted operands.
4016 int32_t right_abs = Abs(right);
4017
4018 if (base::bits::IsPowerOfTwo32(right_abs)) {
4019 int right_log2 = WhichPowerOf2(right_abs);
4020
4021 if (can_overflow) {
4022 Register scratch = result;
4023 DCHECK(!AreAliased(scratch, left));
4024 __ Cls(scratch, left);
4025 __ Cmp(scratch, right_log2);
4026 DeoptimizeIf(lt, instr, Deoptimizer::kOverflow);
4027 }
4028
4029 if (right >= 0) {
4030 // result = left << log2(right)
4031 __ Lsl(result, left, right_log2);
4032 } else {
4033 // result = -left << log2(-right)
4034 if (can_overflow) {
4035 __ Negs(result, Operand(left, LSL, right_log2));
4036 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
4037 } else {
4038 __ Neg(result, Operand(left, LSL, right_log2));
4039 }
4040 }
4041 return;
4042 }
4043
4044
4045 // For the following cases, we could perform a conservative overflow check
4046 // with CLS as above. However the few cycles saved are likely not worth
4047 // the risk of deoptimizing more often than required.
4048 DCHECK(!can_overflow);
4049
4050 if (right >= 0) {
4051 if (base::bits::IsPowerOfTwo32(right - 1)) {
4052 // result = left + left << log2(right - 1)
4053 __ Add(result, left, Operand(left, LSL, WhichPowerOf2(right - 1)));
4054 } else if (base::bits::IsPowerOfTwo32(right + 1)) {
4055 // result = -left + left << log2(right + 1)
4056 __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(right + 1)));
4057 __ Neg(result, result);
4058 } else {
4059 UNREACHABLE();
4060 }
4061 } else {
4062 if (base::bits::IsPowerOfTwo32(-right + 1)) {
4063 // result = left - left << log2(-right + 1)
4064 __ Sub(result, left, Operand(left, LSL, WhichPowerOf2(-right + 1)));
4065 } else if (base::bits::IsPowerOfTwo32(-right - 1)) {
4066 // result = -left - left << log2(-right - 1)
4067 __ Add(result, left, Operand(left, LSL, WhichPowerOf2(-right - 1)));
4068 __ Neg(result, result);
4069 } else {
4070 UNREACHABLE();
4071 }
4072 }
4073 }
4074}
4075
4076
4077void LCodeGen::DoMulI(LMulI* instr) {
4078 Register result = ToRegister32(instr->result());
4079 Register left = ToRegister32(instr->left());
4080 Register right = ToRegister32(instr->right());
4081
4082 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4083 bool bailout_on_minus_zero =
4084 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4085
4086 if (bailout_on_minus_zero && !left.Is(right)) {
4087 // If one operand is zero and the other is negative, the result is -0.
4088 // - Set Z (eq) if either left or right, or both, are 0.
4089 __ Cmp(left, 0);
4090 __ Ccmp(right, 0, ZFlag, ne);
4091 // - If so (eq), set N (mi) if left + right is negative.
4092 // - Otherwise, clear N.
4093 __ Ccmn(left, right, NoFlag, eq);
4094 DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4095 }
4096
4097 if (can_overflow) {
4098 __ Smull(result.X(), left, right);
4099 __ Cmp(result.X(), Operand(result, SXTW));
4100 DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4101 } else {
4102 __ Mul(result, left, right);
4103 }
4104}
4105
4106
4107void LCodeGen::DoMulS(LMulS* instr) {
4108 Register result = ToRegister(instr->result());
4109 Register left = ToRegister(instr->left());
4110 Register right = ToRegister(instr->right());
4111
4112 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
4113 bool bailout_on_minus_zero =
4114 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
4115
4116 if (bailout_on_minus_zero && !left.Is(right)) {
4117 // If one operand is zero and the other is negative, the result is -0.
4118 // - Set Z (eq) if either left or right, or both, are 0.
4119 __ Cmp(left, 0);
4120 __ Ccmp(right, 0, ZFlag, ne);
4121 // - If so (eq), set N (mi) if left + right is negative.
4122 // - Otherwise, clear N.
4123 __ Ccmn(left, right, NoFlag, eq);
4124 DeoptimizeIf(mi, instr, Deoptimizer::kMinusZero);
4125 }
4126
4127 STATIC_ASSERT((kSmiShift == 32) && (kSmiTag == 0));
4128 if (can_overflow) {
4129 __ Smulh(result, left, right);
4130 __ Cmp(result, Operand(result.W(), SXTW));
4131 __ SmiTag(result);
4132 DeoptimizeIf(ne, instr, Deoptimizer::kOverflow);
4133 } else {
4134 if (AreAliased(result, left, right)) {
4135 // All three registers are the same: half untag the input and then
4136 // multiply, giving a tagged result.
4137 STATIC_ASSERT((kSmiShift % 2) == 0);
4138 __ Asr(result, left, kSmiShift / 2);
4139 __ Mul(result, result, result);
4140 } else if (result.Is(left) && !left.Is(right)) {
4141 // Registers result and left alias, right is distinct: untag left into
4142 // result, and then multiply by right, giving a tagged result.
4143 __ SmiUntag(result, left);
4144 __ Mul(result, result, right);
4145 } else {
4146 DCHECK(!left.Is(result));
4147 // Registers result and right alias, left is distinct, or all registers
4148 // are distinct: untag right into result, and then multiply by left,
4149 // giving a tagged result.
4150 __ SmiUntag(result, right);
4151 __ Mul(result, left, result);
4152 }
4153 }
4154}
4155
4156
4157void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4158 // TODO(3095996): Get rid of this. For now, we need to make the
4159 // result register contain a valid pointer because it is already
4160 // contained in the register pointer map.
4161 Register result = ToRegister(instr->result());
4162 __ Mov(result, 0);
4163
4164 PushSafepointRegistersScope scope(this);
4165 // NumberTagU and NumberTagD use the context from the frame, rather than
4166 // the environment's HContext or HInlinedContext value.
4167 // They only call Runtime::kAllocateHeapNumber.
4168 // The corresponding HChange instructions are added in a phase that does
4169 // not have easy access to the local context.
4170 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4171 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4172 RecordSafepointWithRegisters(
4173 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4174 __ StoreToSafepointRegisterSlot(x0, result);
4175}
4176
4177
4178void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4179 class DeferredNumberTagD: public LDeferredCode {
4180 public:
4181 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4182 : LDeferredCode(codegen), instr_(instr) { }
4183 virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); }
4184 virtual LInstruction* instr() { return instr_; }
4185 private:
4186 LNumberTagD* instr_;
4187 };
4188
4189 DoubleRegister input = ToDoubleRegister(instr->value());
4190 Register result = ToRegister(instr->result());
4191 Register temp1 = ToRegister(instr->temp1());
4192 Register temp2 = ToRegister(instr->temp2());
4193
4194 DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4195 if (FLAG_inline_new) {
4196 __ AllocateHeapNumber(result, deferred->entry(), temp1, temp2);
4197 } else {
4198 __ B(deferred->entry());
4199 }
4200
4201 __ Bind(deferred->exit());
4202 __ Str(input, FieldMemOperand(result, HeapNumber::kValueOffset));
4203}
4204
4205
4206void LCodeGen::DoDeferredNumberTagU(LInstruction* instr,
4207 LOperand* value,
4208 LOperand* temp1,
4209 LOperand* temp2) {
4210 Label slow, convert_and_store;
4211 Register src = ToRegister32(value);
4212 Register dst = ToRegister(instr->result());
4213 Register scratch1 = ToRegister(temp1);
4214
4215 if (FLAG_inline_new) {
4216 Register scratch2 = ToRegister(temp2);
4217 __ AllocateHeapNumber(dst, &slow, scratch1, scratch2);
4218 __ B(&convert_and_store);
4219 }
4220
4221 // Slow case: call the runtime system to do the number allocation.
4222 __ Bind(&slow);
4223 // TODO(3095996): Put a valid pointer value in the stack slot where the result
4224 // register is stored, as this register is in the pointer map, but contains an
4225 // integer value.
4226 __ Mov(dst, 0);
4227 {
4228 // Preserve the value of all registers.
4229 PushSafepointRegistersScope scope(this);
4230
4231 // NumberTagU and NumberTagD use the context from the frame, rather than
4232 // the environment's HContext or HInlinedContext value.
4233 // They only call Runtime::kAllocateHeapNumber.
4234 // The corresponding HChange instructions are added in a phase that does
4235 // not have easy access to the local context.
4236 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4237 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4238 RecordSafepointWithRegisters(
4239 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4240 __ StoreToSafepointRegisterSlot(x0, dst);
4241 }
4242
4243 // Convert number to floating point and store in the newly allocated heap
4244 // number.
4245 __ Bind(&convert_and_store);
4246 DoubleRegister dbl_scratch = double_scratch();
4247 __ Ucvtf(dbl_scratch, src);
4248 __ Str(dbl_scratch, FieldMemOperand(dst, HeapNumber::kValueOffset));
4249}
4250
4251
4252void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4253 class DeferredNumberTagU: public LDeferredCode {
4254 public:
4255 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4256 : LDeferredCode(codegen), instr_(instr) { }
4257 virtual void Generate() {
4258 codegen()->DoDeferredNumberTagU(instr_,
4259 instr_->value(),
4260 instr_->temp1(),
4261 instr_->temp2());
4262 }
4263 virtual LInstruction* instr() { return instr_; }
4264 private:
4265 LNumberTagU* instr_;
4266 };
4267
4268 Register value = ToRegister32(instr->value());
4269 Register result = ToRegister(instr->result());
4270
4271 DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
4272 __ Cmp(value, Smi::kMaxValue);
4273 __ B(hi, deferred->entry());
4274 __ SmiTag(result, value.X());
4275 __ Bind(deferred->exit());
4276}
4277
4278
4279void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4280 Register input = ToRegister(instr->value());
4281 Register scratch = ToRegister(instr->temp());
4282 DoubleRegister result = ToDoubleRegister(instr->result());
4283 bool can_convert_undefined_to_nan =
4284 instr->hydrogen()->can_convert_undefined_to_nan();
4285
4286 Label done, load_smi;
4287
4288 // Work out what untag mode we're working with.
4289 HValue* value = instr->hydrogen()->value();
4290 NumberUntagDMode mode = value->representation().IsSmi()
4291 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4292
4293 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4294 __ JumpIfSmi(input, &load_smi);
4295
4296 Label convert_undefined;
4297
4298 // Heap number map check.
4299 if (can_convert_undefined_to_nan) {
4300 __ JumpIfNotHeapNumber(input, &convert_undefined);
4301 } else {
4302 DeoptimizeIfNotHeapNumber(input, instr);
4303 }
4304
4305 // Load heap number.
4306 __ Ldr(result, FieldMemOperand(input, HeapNumber::kValueOffset));
4307 if (instr->hydrogen()->deoptimize_on_minus_zero()) {
4308 DeoptimizeIfMinusZero(result, instr, Deoptimizer::kMinusZero);
4309 }
4310 __ B(&done);
4311
4312 if (can_convert_undefined_to_nan) {
4313 __ Bind(&convert_undefined);
4314 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
4315 Deoptimizer::kNotAHeapNumberUndefined);
4316
4317 __ LoadRoot(scratch, Heap::kNanValueRootIndex);
4318 __ Ldr(result, FieldMemOperand(scratch, HeapNumber::kValueOffset));
4319 __ B(&done);
4320 }
4321
4322 } else {
4323 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4324 // Fall through to load_smi.
4325 }
4326
4327 // Smi to double register conversion.
4328 __ Bind(&load_smi);
4329 __ SmiUntagToDouble(result, input);
4330
4331 __ Bind(&done);
4332}
4333
4334
4335void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
4336 // This is a pseudo-instruction that ensures that the environment here is
4337 // properly registered for deoptimization and records the assembler's PC
4338 // offset.
4339 LEnvironment* environment = instr->environment();
4340
4341 // If the environment were already registered, we would have no way of
4342 // backpatching it with the spill slot operands.
4343 DCHECK(!environment->HasBeenRegistered());
4344 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
4345
4346 GenerateOsrPrologue();
4347}
4348
4349
4350void LCodeGen::DoParameter(LParameter* instr) {
4351 // Nothing to do.
4352}
4353
4354
4355void LCodeGen::DoPreparePushArguments(LPreparePushArguments* instr) {
4356 __ PushPreamble(instr->argc(), kPointerSize);
4357}
4358
4359
4360void LCodeGen::DoPushArguments(LPushArguments* instr) {
4361 MacroAssembler::PushPopQueue args(masm());
4362
4363 for (int i = 0; i < instr->ArgumentCount(); ++i) {
4364 LOperand* arg = instr->argument(i);
4365 if (arg->IsDoubleRegister() || arg->IsDoubleStackSlot()) {
4366 Abort(kDoPushArgumentNotImplementedForDoubleType);
4367 return;
4368 }
4369 args.Queue(ToRegister(arg));
4370 }
4371
4372 // The preamble was done by LPreparePushArguments.
4373 args.PushQueued(MacroAssembler::PushPopQueue::SKIP_PREAMBLE);
4374
4375 RecordPushedArgumentsDelta(instr->ArgumentCount());
4376}
4377
4378
4379void LCodeGen::DoReturn(LReturn* instr) {
4380 if (FLAG_trace && info()->IsOptimizing()) {
4381 // Push the return value on the stack as the parameter.
4382 // Runtime::TraceExit returns its parameter in x0. We're leaving the code
4383 // managed by the register allocator and tearing down the frame, it's
4384 // safe to write to the context register.
4385 __ Push(x0);
4386 __ Ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
4387 __ CallRuntime(Runtime::kTraceExit);
4388 }
4389
4390 if (info()->saves_caller_doubles()) {
4391 RestoreCallerDoubles();
4392 }
4393
4394 if (NeedsEagerFrame()) {
4395 Register stack_pointer = masm()->StackPointer();
4396 __ Mov(stack_pointer, fp);
4397 __ Pop(fp, lr);
4398 }
4399
4400 if (instr->has_constant_parameter_count()) {
4401 int parameter_count = ToInteger32(instr->constant_parameter_count());
4402 __ Drop(parameter_count + 1);
4403 } else {
4404 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
4405 Register parameter_count = ToRegister(instr->parameter_count());
4406 __ DropBySMI(parameter_count);
4407 }
4408 __ Ret();
4409}
4410
4411
4412MemOperand LCodeGen::BuildSeqStringOperand(Register string,
4413 Register temp,
4414 LOperand* index,
4415 String::Encoding encoding) {
4416 if (index->IsConstantOperand()) {
4417 int offset = ToInteger32(LConstantOperand::cast(index));
4418 if (encoding == String::TWO_BYTE_ENCODING) {
4419 offset *= kUC16Size;
4420 }
4421 STATIC_ASSERT(kCharSize == 1);
4422 return FieldMemOperand(string, SeqString::kHeaderSize + offset);
4423 }
4424
4425 __ Add(temp, string, SeqString::kHeaderSize - kHeapObjectTag);
4426 if (encoding == String::ONE_BYTE_ENCODING) {
4427 return MemOperand(temp, ToRegister32(index), SXTW);
4428 } else {
4429 STATIC_ASSERT(kUC16Size == 2);
4430 return MemOperand(temp, ToRegister32(index), SXTW, 1);
4431 }
4432}
4433
4434
4435void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
4436 String::Encoding encoding = instr->hydrogen()->encoding();
4437 Register string = ToRegister(instr->string());
4438 Register result = ToRegister(instr->result());
4439 Register temp = ToRegister(instr->temp());
4440
4441 if (FLAG_debug_code) {
4442 // Even though this lithium instruction comes with a temp register, we
4443 // can't use it here because we want to use "AtStart" constraints on the
4444 // inputs and the debug code here needs a scratch register.
4445 UseScratchRegisterScope temps(masm());
4446 Register dbg_temp = temps.AcquireX();
4447
4448 __ Ldr(dbg_temp, FieldMemOperand(string, HeapObject::kMapOffset));
4449 __ Ldrb(dbg_temp, FieldMemOperand(dbg_temp, Map::kInstanceTypeOffset));
4450
4451 __ And(dbg_temp, dbg_temp,
4452 Operand(kStringRepresentationMask | kStringEncodingMask));
4453 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4454 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4455 __ Cmp(dbg_temp, Operand(encoding == String::ONE_BYTE_ENCODING
4456 ? one_byte_seq_type : two_byte_seq_type));
4457 __ Check(eq, kUnexpectedStringType);
4458 }
4459
4460 MemOperand operand =
4461 BuildSeqStringOperand(string, temp, instr->index(), encoding);
4462 if (encoding == String::ONE_BYTE_ENCODING) {
4463 __ Ldrb(result, operand);
4464 } else {
4465 __ Ldrh(result, operand);
4466 }
4467}
4468
4469
4470void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
4471 String::Encoding encoding = instr->hydrogen()->encoding();
4472 Register string = ToRegister(instr->string());
4473 Register value = ToRegister(instr->value());
4474 Register temp = ToRegister(instr->temp());
4475
4476 if (FLAG_debug_code) {
4477 DCHECK(ToRegister(instr->context()).is(cp));
4478 Register index = ToRegister(instr->index());
4479 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
4480 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
4481 int encoding_mask =
4482 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
4483 ? one_byte_seq_type : two_byte_seq_type;
4484 __ EmitSeqStringSetCharCheck(string, index, kIndexIsInteger32, temp,
4485 encoding_mask);
4486 }
4487 MemOperand operand =
4488 BuildSeqStringOperand(string, temp, instr->index(), encoding);
4489 if (encoding == String::ONE_BYTE_ENCODING) {
4490 __ Strb(value, operand);
4491 } else {
4492 __ Strh(value, operand);
4493 }
4494}
4495
4496
4497void LCodeGen::DoSmiTag(LSmiTag* instr) {
4498 HChange* hchange = instr->hydrogen();
4499 Register input = ToRegister(instr->value());
4500 Register output = ToRegister(instr->result());
4501 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4502 hchange->value()->CheckFlag(HValue::kUint32)) {
4503 DeoptimizeIfNegative(input.W(), instr, Deoptimizer::kOverflow);
4504 }
4505 __ SmiTag(output, input);
4506}
4507
4508
4509void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4510 Register input = ToRegister(instr->value());
4511 Register result = ToRegister(instr->result());
4512 Label done, untag;
4513
4514 if (instr->needs_check()) {
4515 DeoptimizeIfNotSmi(input, instr, Deoptimizer::kNotASmi);
4516 }
4517
4518 __ Bind(&untag);
4519 __ SmiUntag(result, input);
4520 __ Bind(&done);
4521}
4522
4523
4524void LCodeGen::DoShiftI(LShiftI* instr) {
4525 LOperand* right_op = instr->right();
4526 Register left = ToRegister32(instr->left());
4527 Register result = ToRegister32(instr->result());
4528
4529 if (right_op->IsRegister()) {
4530 Register right = ToRegister32(instr->right());
4531 switch (instr->op()) {
4532 case Token::ROR: __ Ror(result, left, right); break;
4533 case Token::SAR: __ Asr(result, left, right); break;
4534 case Token::SHL: __ Lsl(result, left, right); break;
4535 case Token::SHR:
4536 __ Lsr(result, left, right);
4537 if (instr->can_deopt()) {
4538 // If `left >>> right` >= 0x80000000, the result is not representable
4539 // in a signed 32-bit smi.
4540 DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4541 }
4542 break;
4543 default: UNREACHABLE();
4544 }
4545 } else {
4546 DCHECK(right_op->IsConstantOperand());
4547 int shift_count = JSShiftAmountFromLConstant(right_op);
4548 if (shift_count == 0) {
4549 if ((instr->op() == Token::SHR) && instr->can_deopt()) {
4550 DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
4551 }
4552 __ Mov(result, left, kDiscardForSameWReg);
4553 } else {
4554 switch (instr->op()) {
4555 case Token::ROR: __ Ror(result, left, shift_count); break;
4556 case Token::SAR: __ Asr(result, left, shift_count); break;
4557 case Token::SHL: __ Lsl(result, left, shift_count); break;
4558 case Token::SHR: __ Lsr(result, left, shift_count); break;
4559 default: UNREACHABLE();
4560 }
4561 }
4562 }
4563}
4564
4565
4566void LCodeGen::DoShiftS(LShiftS* instr) {
4567 LOperand* right_op = instr->right();
4568 Register left = ToRegister(instr->left());
4569 Register result = ToRegister(instr->result());
4570
4571 if (right_op->IsRegister()) {
4572 Register right = ToRegister(instr->right());
4573
4574 // JavaScript shifts only look at the bottom 5 bits of the 'right' operand.
4575 // Since we're handling smis in X registers, we have to extract these bits
4576 // explicitly.
4577 __ Ubfx(result, right, kSmiShift, 5);
4578
4579 switch (instr->op()) {
4580 case Token::ROR: {
4581 // This is the only case that needs a scratch register. To keep things
4582 // simple for the other cases, borrow a MacroAssembler scratch register.
4583 UseScratchRegisterScope temps(masm());
4584 Register temp = temps.AcquireW();
4585 __ SmiUntag(temp, left);
4586 __ Ror(result.W(), temp.W(), result.W());
4587 __ SmiTag(result);
4588 break;
4589 }
4590 case Token::SAR:
4591 __ Asr(result, left, result);
4592 __ Bic(result, result, kSmiShiftMask);
4593 break;
4594 case Token::SHL:
4595 __ Lsl(result, left, result);
4596 break;
4597 case Token::SHR:
4598 __ Lsr(result, left, result);
4599 __ Bic(result, result, kSmiShiftMask);
4600 if (instr->can_deopt()) {
4601 // If `left >>> right` >= 0x80000000, the result is not representable
4602 // in a signed 32-bit smi.
4603 DeoptimizeIfNegative(result, instr, Deoptimizer::kNegativeValue);
4604 }
4605 break;
4606 default: UNREACHABLE();
4607 }
4608 } else {
4609 DCHECK(right_op->IsConstantOperand());
4610 int shift_count = JSShiftAmountFromLConstant(right_op);
4611 if (shift_count == 0) {
4612 if ((instr->op() == Token::SHR) && instr->can_deopt()) {
4613 DeoptimizeIfNegative(left, instr, Deoptimizer::kNegativeValue);
4614 }
4615 __ Mov(result, left);
4616 } else {
4617 switch (instr->op()) {
4618 case Token::ROR:
4619 __ SmiUntag(result, left);
4620 __ Ror(result.W(), result.W(), shift_count);
4621 __ SmiTag(result);
4622 break;
4623 case Token::SAR:
4624 __ Asr(result, left, shift_count);
4625 __ Bic(result, result, kSmiShiftMask);
4626 break;
4627 case Token::SHL:
4628 __ Lsl(result, left, shift_count);
4629 break;
4630 case Token::SHR:
4631 __ Lsr(result, left, shift_count);
4632 __ Bic(result, result, kSmiShiftMask);
4633 break;
4634 default: UNREACHABLE();
4635 }
4636 }
4637 }
4638}
4639
4640
4641void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
4642 __ Debug("LDebugBreak", 0, BREAK);
4643}
4644
4645
4646void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
4647 DCHECK(ToRegister(instr->context()).is(cp));
4648 Register scratch1 = x5;
4649 Register scratch2 = x6;
4650 DCHECK(instr->IsMarkedAsCall());
4651
4652 // TODO(all): if Mov could handle object in new space then it could be used
4653 // here.
4654 __ LoadHeapObject(scratch1, instr->hydrogen()->pairs());
4655 __ Mov(scratch2, Smi::FromInt(instr->hydrogen()->flags()));
4656 __ Push(scratch1, scratch2);
4657 CallRuntime(Runtime::kDeclareGlobals, instr);
4658}
4659
4660
4661void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
4662 PushSafepointRegistersScope scope(this);
4663 LoadContextFromDeferred(instr->context());
4664 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
4665 RecordSafepointWithLazyDeopt(
4666 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4667 DCHECK(instr->HasEnvironment());
4668 LEnvironment* env = instr->environment();
4669 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
4670}
4671
4672
4673void LCodeGen::DoStackCheck(LStackCheck* instr) {
4674 class DeferredStackCheck: public LDeferredCode {
4675 public:
4676 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
4677 : LDeferredCode(codegen), instr_(instr) { }
4678 virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); }
4679 virtual LInstruction* instr() { return instr_; }
4680 private:
4681 LStackCheck* instr_;
4682 };
4683
4684 DCHECK(instr->HasEnvironment());
4685 LEnvironment* env = instr->environment();
4686 // There is no LLazyBailout instruction for stack-checks. We have to
4687 // prepare for lazy deoptimization explicitly here.
4688 if (instr->hydrogen()->is_function_entry()) {
4689 // Perform stack overflow check.
4690 Label done;
4691 __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
4692 __ B(hs, &done);
4693
4694 PredictableCodeSizeScope predictable(masm_,
4695 Assembler::kCallSizeWithRelocation);
4696 DCHECK(instr->context()->IsRegister());
4697 DCHECK(ToRegister(instr->context()).is(cp));
4698 CallCode(isolate()->builtins()->StackCheck(),
4699 RelocInfo::CODE_TARGET,
4700 instr);
4701 __ Bind(&done);
4702 } else {
4703 DCHECK(instr->hydrogen()->is_backwards_branch());
4704 // Perform stack overflow check if this goto needs it before jumping.
4705 DeferredStackCheck* deferred_stack_check =
4706 new(zone()) DeferredStackCheck(this, instr);
4707 __ CompareRoot(masm()->StackPointer(), Heap::kStackLimitRootIndex);
4708 __ B(lo, deferred_stack_check->entry());
4709
4710 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
4711 __ Bind(instr->done_label());
4712 deferred_stack_check->SetExit(instr->done_label());
4713 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
4714 // Don't record a deoptimization index for the safepoint here.
4715 // This will be done explicitly when emitting call and the safepoint in
4716 // the deferred code.
4717 }
4718}
4719
4720
4721void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4722 Register function = ToRegister(instr->function());
4723 Register code_object = ToRegister(instr->code_object());
4724 Register temp = ToRegister(instr->temp());
4725 __ Add(temp, code_object, Code::kHeaderSize - kHeapObjectTag);
4726 __ Str(temp, FieldMemOperand(function, JSFunction::kCodeEntryOffset));
4727}
4728
4729
4730void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
4731 Register context = ToRegister(instr->context());
4732 Register value = ToRegister(instr->value());
4733 Register scratch = ToRegister(instr->temp());
4734 MemOperand target = ContextMemOperand(context, instr->slot_index());
4735
4736 Label skip_assignment;
4737
4738 if (instr->hydrogen()->RequiresHoleCheck()) {
4739 __ Ldr(scratch, target);
4740 if (instr->hydrogen()->DeoptimizesOnHole()) {
4741 DeoptimizeIfRoot(scratch, Heap::kTheHoleValueRootIndex, instr,
4742 Deoptimizer::kHole);
4743 } else {
4744 __ JumpIfNotRoot(scratch, Heap::kTheHoleValueRootIndex, &skip_assignment);
4745 }
4746 }
4747
4748 __ Str(value, target);
4749 if (instr->hydrogen()->NeedsWriteBarrier()) {
4750 SmiCheck check_needed =
4751 instr->hydrogen()->value()->type().IsHeapObject()
4752 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4753 __ RecordWriteContextSlot(context, static_cast<int>(target.offset()), value,
4754 scratch, GetLinkRegisterState(), kSaveFPRegs,
4755 EMIT_REMEMBERED_SET, check_needed);
4756 }
4757 __ Bind(&skip_assignment);
4758}
4759
4760
4761void LCodeGen::DoStoreKeyedExternal(LStoreKeyedExternal* instr) {
4762 Register ext_ptr = ToRegister(instr->elements());
4763 Register key = no_reg;
4764 Register scratch;
4765 ElementsKind elements_kind = instr->elements_kind();
4766
4767 bool key_is_smi = instr->hydrogen()->key()->representation().IsSmi();
4768 bool key_is_constant = instr->key()->IsConstantOperand();
4769 int constant_key = 0;
4770 if (key_is_constant) {
4771 DCHECK(instr->temp() == NULL);
4772 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
4773 if (constant_key & 0xf0000000) {
4774 Abort(kArrayIndexConstantValueTooBig);
4775 }
4776 } else {
4777 key = ToRegister(instr->key());
4778 scratch = ToRegister(instr->temp());
4779 }
4780
4781 MemOperand dst =
4782 PrepareKeyedExternalArrayOperand(key, ext_ptr, scratch, key_is_smi,
4783 key_is_constant, constant_key,
4784 elements_kind,
4785 instr->base_offset());
4786
4787 if (elements_kind == FLOAT32_ELEMENTS) {
4788 DoubleRegister value = ToDoubleRegister(instr->value());
4789 DoubleRegister dbl_scratch = double_scratch();
4790 __ Fcvt(dbl_scratch.S(), value);
4791 __ Str(dbl_scratch.S(), dst);
4792 } else if (elements_kind == FLOAT64_ELEMENTS) {
4793 DoubleRegister value = ToDoubleRegister(instr->value());
4794 __ Str(value, dst);
4795 } else {
4796 Register value = ToRegister(instr->value());
4797
4798 switch (elements_kind) {
4799 case UINT8_ELEMENTS:
4800 case UINT8_CLAMPED_ELEMENTS:
4801 case INT8_ELEMENTS:
4802 __ Strb(value, dst);
4803 break;
4804 case INT16_ELEMENTS:
4805 case UINT16_ELEMENTS:
4806 __ Strh(value, dst);
4807 break;
4808 case INT32_ELEMENTS:
4809 case UINT32_ELEMENTS:
4810 __ Str(value.W(), dst);
4811 break;
4812 case FLOAT32_ELEMENTS:
4813 case FLOAT64_ELEMENTS:
4814 case FAST_DOUBLE_ELEMENTS:
4815 case FAST_ELEMENTS:
4816 case FAST_SMI_ELEMENTS:
4817 case FAST_HOLEY_DOUBLE_ELEMENTS:
4818 case FAST_HOLEY_ELEMENTS:
4819 case FAST_HOLEY_SMI_ELEMENTS:
4820 case DICTIONARY_ELEMENTS:
4821 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4822 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
Ben Murdoch097c5b22016-05-18 11:27:45 +01004823 case FAST_STRING_WRAPPER_ELEMENTS:
4824 case SLOW_STRING_WRAPPER_ELEMENTS:
4825 case NO_ELEMENTS:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004826 UNREACHABLE();
4827 break;
4828 }
4829 }
4830}
4831
4832
4833void LCodeGen::DoStoreKeyedFixedDouble(LStoreKeyedFixedDouble* instr) {
4834 Register elements = ToRegister(instr->elements());
4835 DoubleRegister value = ToDoubleRegister(instr->value());
4836 MemOperand mem_op;
4837
4838 if (instr->key()->IsConstantOperand()) {
4839 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
4840 if (constant_key & 0xf0000000) {
4841 Abort(kArrayIndexConstantValueTooBig);
4842 }
4843 int offset = instr->base_offset() + constant_key * kDoubleSize;
4844 mem_op = MemOperand(elements, offset);
4845 } else {
4846 Register store_base = ToRegister(instr->temp());
4847 Register key = ToRegister(instr->key());
4848 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
4849 mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
4850 instr->hydrogen()->elements_kind(),
4851 instr->hydrogen()->representation(),
4852 instr->base_offset());
4853 }
4854
4855 if (instr->NeedsCanonicalization()) {
4856 __ CanonicalizeNaN(double_scratch(), value);
4857 __ Str(double_scratch(), mem_op);
4858 } else {
4859 __ Str(value, mem_op);
4860 }
4861}
4862
4863
4864void LCodeGen::DoStoreKeyedFixed(LStoreKeyedFixed* instr) {
4865 Register value = ToRegister(instr->value());
4866 Register elements = ToRegister(instr->elements());
4867 Register scratch = no_reg;
4868 Register store_base = no_reg;
4869 Register key = no_reg;
4870 MemOperand mem_op;
4871
4872 if (!instr->key()->IsConstantOperand() ||
4873 instr->hydrogen()->NeedsWriteBarrier()) {
4874 scratch = ToRegister(instr->temp());
4875 }
4876
4877 Representation representation = instr->hydrogen()->value()->representation();
4878 if (instr->key()->IsConstantOperand()) {
4879 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
4880 int offset = instr->base_offset() +
4881 ToInteger32(const_operand) * kPointerSize;
4882 store_base = elements;
4883 if (representation.IsInteger32()) {
4884 DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
4885 DCHECK(instr->hydrogen()->elements_kind() == FAST_SMI_ELEMENTS);
4886 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
4887 STATIC_ASSERT(kSmiTag == 0);
4888 mem_op = UntagSmiMemOperand(store_base, offset);
4889 } else {
4890 mem_op = MemOperand(store_base, offset);
4891 }
4892 } else {
4893 store_base = scratch;
4894 key = ToRegister(instr->key());
4895 bool key_is_tagged = instr->hydrogen()->key()->representation().IsSmi();
4896
4897 mem_op = PrepareKeyedArrayOperand(store_base, elements, key, key_is_tagged,
4898 instr->hydrogen()->elements_kind(),
4899 representation, instr->base_offset());
4900 }
4901
4902 __ Store(value, mem_op, representation);
4903
4904 if (instr->hydrogen()->NeedsWriteBarrier()) {
4905 DCHECK(representation.IsTagged());
4906 // This assignment may cause element_addr to alias store_base.
4907 Register element_addr = scratch;
4908 SmiCheck check_needed =
4909 instr->hydrogen()->value()->type().IsHeapObject()
4910 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4911 // Compute address of modified element and store it into key register.
4912 __ Add(element_addr, mem_op.base(), mem_op.OffsetAsOperand());
4913 __ RecordWrite(elements, element_addr, value, GetLinkRegisterState(),
4914 kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed,
4915 instr->hydrogen()->PointersToHereCheckForValue());
4916 }
4917}
4918
4919
4920void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4921 DCHECK(ToRegister(instr->context()).is(cp));
4922 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4923 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4924 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4925
4926 if (instr->hydrogen()->HasVectorAndSlot()) {
4927 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4928 }
4929
4930 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4931 isolate(), instr->language_mode(),
4932 instr->hydrogen()->initialization_state()).code();
4933 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4934}
4935
4936
4937void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4938 class DeferredMaybeGrowElements final : public LDeferredCode {
4939 public:
4940 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4941 : LDeferredCode(codegen), instr_(instr) {}
4942 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4943 LInstruction* instr() override { return instr_; }
4944
4945 private:
4946 LMaybeGrowElements* instr_;
4947 };
4948
4949 Register result = x0;
4950 DeferredMaybeGrowElements* deferred =
4951 new (zone()) DeferredMaybeGrowElements(this, instr);
4952 LOperand* key = instr->key();
4953 LOperand* current_capacity = instr->current_capacity();
4954
4955 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4956 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4957 DCHECK(key->IsConstantOperand() || key->IsRegister());
4958 DCHECK(current_capacity->IsConstantOperand() ||
4959 current_capacity->IsRegister());
4960
4961 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4962 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4963 int32_t constant_capacity =
4964 ToInteger32(LConstantOperand::cast(current_capacity));
4965 if (constant_key >= constant_capacity) {
4966 // Deferred case.
4967 __ B(deferred->entry());
4968 }
4969 } else if (key->IsConstantOperand()) {
4970 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4971 __ Cmp(ToRegister(current_capacity), Operand(constant_key));
4972 __ B(le, deferred->entry());
4973 } else if (current_capacity->IsConstantOperand()) {
4974 int32_t constant_capacity =
4975 ToInteger32(LConstantOperand::cast(current_capacity));
4976 __ Cmp(ToRegister(key), Operand(constant_capacity));
4977 __ B(ge, deferred->entry());
4978 } else {
4979 __ Cmp(ToRegister(key), ToRegister(current_capacity));
4980 __ B(ge, deferred->entry());
4981 }
4982
4983 __ Mov(result, ToRegister(instr->elements()));
4984
4985 __ Bind(deferred->exit());
4986}
4987
4988
4989void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4990 // TODO(3095996): Get rid of this. For now, we need to make the
4991 // result register contain a valid pointer because it is already
4992 // contained in the register pointer map.
4993 Register result = x0;
4994 __ Mov(result, 0);
4995
4996 // We have to call a stub.
4997 {
4998 PushSafepointRegistersScope scope(this);
4999 __ Move(result, ToRegister(instr->object()));
5000
5001 LOperand* key = instr->key();
5002 if (key->IsConstantOperand()) {
5003 __ Mov(x3, Operand(ToSmi(LConstantOperand::cast(key))));
5004 } else {
5005 __ Mov(x3, ToRegister(key));
5006 __ SmiTag(x3);
5007 }
5008
5009 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
5010 instr->hydrogen()->kind());
5011 __ CallStub(&stub);
5012 RecordSafepointWithLazyDeopt(
5013 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5014 __ StoreToSafepointRegisterSlot(result, result);
5015 }
5016
5017 // Deopt on smi, which means the elements array changed to dictionary mode.
5018 DeoptimizeIfSmi(result, instr, Deoptimizer::kSmi);
5019}
5020
5021
5022void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
5023 Representation representation = instr->representation();
5024
5025 Register object = ToRegister(instr->object());
5026 HObjectAccess access = instr->hydrogen()->access();
5027 int offset = access.offset();
5028
5029 if (access.IsExternalMemory()) {
5030 DCHECK(!instr->hydrogen()->has_transition());
5031 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5032 Register value = ToRegister(instr->value());
5033 __ Store(value, MemOperand(object, offset), representation);
5034 return;
5035 }
5036
5037 __ AssertNotSmi(object);
5038
5039 if (!FLAG_unbox_double_fields && representation.IsDouble()) {
5040 DCHECK(access.IsInobject());
5041 DCHECK(!instr->hydrogen()->has_transition());
5042 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
5043 FPRegister value = ToDoubleRegister(instr->value());
5044 __ Str(value, FieldMemOperand(object, offset));
5045 return;
5046 }
5047
5048 DCHECK(!representation.IsSmi() ||
5049 !instr->value()->IsConstantOperand() ||
5050 IsInteger32Constant(LConstantOperand::cast(instr->value())));
5051
5052 if (instr->hydrogen()->has_transition()) {
5053 Handle<Map> transition = instr->hydrogen()->transition_map();
5054 AddDeprecationDependency(transition);
5055 // Store the new map value.
5056 Register new_map_value = ToRegister(instr->temp0());
5057 __ Mov(new_map_value, Operand(transition));
5058 __ Str(new_map_value, FieldMemOperand(object, HeapObject::kMapOffset));
5059 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
5060 // Update the write barrier for the map field.
5061 __ RecordWriteForMap(object,
5062 new_map_value,
5063 ToRegister(instr->temp1()),
5064 GetLinkRegisterState(),
5065 kSaveFPRegs);
5066 }
5067 }
5068
5069 // Do the store.
5070 Register destination;
5071 if (access.IsInobject()) {
5072 destination = object;
5073 } else {
5074 Register temp0 = ToRegister(instr->temp0());
5075 __ Ldr(temp0, FieldMemOperand(object, JSObject::kPropertiesOffset));
5076 destination = temp0;
5077 }
5078
5079 if (FLAG_unbox_double_fields && representation.IsDouble()) {
5080 DCHECK(access.IsInobject());
5081 FPRegister value = ToDoubleRegister(instr->value());
5082 __ Str(value, FieldMemOperand(object, offset));
5083 } else if (representation.IsSmi() &&
5084 instr->hydrogen()->value()->representation().IsInteger32()) {
5085 DCHECK(instr->hydrogen()->store_mode() == STORE_TO_INITIALIZED_ENTRY);
5086#ifdef DEBUG
5087 Register temp0 = ToRegister(instr->temp0());
5088 __ Ldr(temp0, FieldMemOperand(destination, offset));
5089 __ AssertSmi(temp0);
5090 // If destination aliased temp0, restore it to the address calculated
5091 // earlier.
5092 if (destination.Is(temp0)) {
5093 DCHECK(!access.IsInobject());
5094 __ Ldr(destination, FieldMemOperand(object, JSObject::kPropertiesOffset));
5095 }
5096#endif
5097 STATIC_ASSERT(static_cast<unsigned>(kSmiValueSize) == kWRegSizeInBits);
5098 STATIC_ASSERT(kSmiTag == 0);
5099 Register value = ToRegister(instr->value());
5100 __ Store(value, UntagSmiFieldMemOperand(destination, offset),
5101 Representation::Integer32());
5102 } else {
5103 Register value = ToRegister(instr->value());
5104 __ Store(value, FieldMemOperand(destination, offset), representation);
5105 }
5106 if (instr->hydrogen()->NeedsWriteBarrier()) {
5107 Register value = ToRegister(instr->value());
5108 __ RecordWriteField(destination,
5109 offset,
5110 value, // Clobbered.
5111 ToRegister(instr->temp1()), // Clobbered.
5112 GetLinkRegisterState(),
5113 kSaveFPRegs,
5114 EMIT_REMEMBERED_SET,
5115 instr->hydrogen()->SmiCheckForWriteBarrier(),
5116 instr->hydrogen()->PointersToHereCheckForValue());
5117 }
5118}
5119
5120
5121void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
5122 DCHECK(ToRegister(instr->context()).is(cp));
5123 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
5124 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
5125
5126 if (instr->hydrogen()->HasVectorAndSlot()) {
5127 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
5128 }
5129
5130 __ Mov(StoreDescriptor::NameRegister(), Operand(instr->name()));
5131 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
5132 isolate(), instr->language_mode(),
5133 instr->hydrogen()->initialization_state()).code();
5134 CallCode(ic, RelocInfo::CODE_TARGET, instr);
5135}
5136
5137
5138void LCodeGen::DoStringAdd(LStringAdd* instr) {
5139 DCHECK(ToRegister(instr->context()).is(cp));
5140 DCHECK(ToRegister(instr->left()).Is(x1));
5141 DCHECK(ToRegister(instr->right()).Is(x0));
5142 StringAddStub stub(isolate(),
5143 instr->hydrogen()->flags(),
5144 instr->hydrogen()->pretenure_flag());
5145 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5146}
5147
5148
5149void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
5150 class DeferredStringCharCodeAt: public LDeferredCode {
5151 public:
5152 DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
5153 : LDeferredCode(codegen), instr_(instr) { }
5154 virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); }
5155 virtual LInstruction* instr() { return instr_; }
5156 private:
5157 LStringCharCodeAt* instr_;
5158 };
5159
5160 DeferredStringCharCodeAt* deferred =
5161 new(zone()) DeferredStringCharCodeAt(this, instr);
5162
5163 StringCharLoadGenerator::Generate(masm(),
5164 ToRegister(instr->string()),
5165 ToRegister32(instr->index()),
5166 ToRegister(instr->result()),
5167 deferred->entry());
5168 __ Bind(deferred->exit());
5169}
5170
5171
5172void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
5173 Register string = ToRegister(instr->string());
5174 Register result = ToRegister(instr->result());
5175
5176 // TODO(3095996): Get rid of this. For now, we need to make the
5177 // result register contain a valid pointer because it is already
5178 // contained in the register pointer map.
5179 __ Mov(result, 0);
5180
5181 PushSafepointRegistersScope scope(this);
5182 __ Push(string);
5183 // Push the index as a smi. This is safe because of the checks in
5184 // DoStringCharCodeAt above.
5185 Register index = ToRegister(instr->index());
5186 __ SmiTagAndPush(index);
5187
5188 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2, instr,
5189 instr->context());
5190 __ AssertSmi(x0);
5191 __ SmiUntag(x0);
5192 __ StoreToSafepointRegisterSlot(x0, result);
5193}
5194
5195
5196void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
5197 class DeferredStringCharFromCode: public LDeferredCode {
5198 public:
5199 DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
5200 : LDeferredCode(codegen), instr_(instr) { }
5201 virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); }
5202 virtual LInstruction* instr() { return instr_; }
5203 private:
5204 LStringCharFromCode* instr_;
5205 };
5206
5207 DeferredStringCharFromCode* deferred =
5208 new(zone()) DeferredStringCharFromCode(this, instr);
5209
5210 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
5211 Register char_code = ToRegister32(instr->char_code());
5212 Register result = ToRegister(instr->result());
5213
5214 __ Cmp(char_code, String::kMaxOneByteCharCode);
5215 __ B(hi, deferred->entry());
5216 __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
5217 __ Add(result, result, FixedArray::kHeaderSize - kHeapObjectTag);
5218 __ Ldr(result, MemOperand(result, char_code, SXTW, kPointerSizeLog2));
5219 __ CompareRoot(result, Heap::kUndefinedValueRootIndex);
5220 __ B(eq, deferred->entry());
5221 __ Bind(deferred->exit());
5222}
5223
5224
5225void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
5226 Register char_code = ToRegister(instr->char_code());
5227 Register result = ToRegister(instr->result());
5228
5229 // TODO(3095996): Get rid of this. For now, we need to make the
5230 // result register contain a valid pointer because it is already
5231 // contained in the register pointer map.
5232 __ Mov(result, 0);
5233
5234 PushSafepointRegistersScope scope(this);
5235 __ SmiTagAndPush(char_code);
5236 CallRuntimeFromDeferred(Runtime::kStringCharFromCode, 1, instr,
5237 instr->context());
5238 __ StoreToSafepointRegisterSlot(x0, result);
5239}
5240
5241
5242void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
5243 DCHECK(ToRegister(instr->context()).is(cp));
5244 DCHECK(ToRegister(instr->left()).is(x1));
5245 DCHECK(ToRegister(instr->right()).is(x0));
5246
5247 Handle<Code> code = CodeFactory::StringCompare(isolate()).code();
5248 CallCode(code, RelocInfo::CODE_TARGET, instr);
5249
5250 EmitCompareAndBranch(instr, TokenToCondition(instr->op(), false), x0, 0);
5251}
5252
5253
5254void LCodeGen::DoSubI(LSubI* instr) {
5255 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5256 Register result = ToRegister32(instr->result());
5257 Register left = ToRegister32(instr->left());
5258 Operand right = ToShiftedRightOperand32(instr->right(), instr);
5259
5260 if (can_overflow) {
5261 __ Subs(result, left, right);
5262 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5263 } else {
5264 __ Sub(result, left, right);
5265 }
5266}
5267
5268
5269void LCodeGen::DoSubS(LSubS* instr) {
5270 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
5271 Register result = ToRegister(instr->result());
5272 Register left = ToRegister(instr->left());
5273 Operand right = ToOperand(instr->right());
5274 if (can_overflow) {
5275 __ Subs(result, left, right);
5276 DeoptimizeIf(vs, instr, Deoptimizer::kOverflow);
5277 } else {
5278 __ Sub(result, left, right);
5279 }
5280}
5281
5282
5283void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr,
5284 LOperand* value,
5285 LOperand* temp1,
5286 LOperand* temp2) {
5287 Register input = ToRegister(value);
5288 Register scratch1 = ToRegister(temp1);
5289 DoubleRegister dbl_scratch1 = double_scratch();
5290
5291 Label done;
5292
5293 if (instr->truncating()) {
5294 Register output = ToRegister(instr->result());
5295 Label check_bools;
5296
5297 // If it's not a heap number, jump to undefined check.
5298 __ JumpIfNotHeapNumber(input, &check_bools);
5299
5300 // A heap number: load value and convert to int32 using truncating function.
5301 __ TruncateHeapNumberToI(output, input);
5302 __ B(&done);
5303
5304 __ Bind(&check_bools);
5305
5306 Register true_root = output;
5307 Register false_root = scratch1;
5308 __ LoadTrueFalseRoots(true_root, false_root);
5309 __ Cmp(input, true_root);
5310 __ Cset(output, eq);
5311 __ Ccmp(input, false_root, ZFlag, ne);
5312 __ B(eq, &done);
5313
5314 // Output contains zero, undefined is converted to zero for truncating
5315 // conversions.
5316 DeoptimizeIfNotRoot(input, Heap::kUndefinedValueRootIndex, instr,
5317 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5318 } else {
5319 Register output = ToRegister32(instr->result());
5320 DoubleRegister dbl_scratch2 = ToDoubleRegister(temp2);
5321
5322 DeoptimizeIfNotHeapNumber(input, instr);
5323
5324 // A heap number: load value and convert to int32 using non-truncating
5325 // function. If the result is out of range, branch to deoptimize.
5326 __ Ldr(dbl_scratch1, FieldMemOperand(input, HeapNumber::kValueOffset));
5327 __ TryRepresentDoubleAsInt32(output, dbl_scratch1, dbl_scratch2);
5328 DeoptimizeIf(ne, instr, Deoptimizer::kLostPrecisionOrNaN);
5329
5330 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
5331 __ Cmp(output, 0);
5332 __ B(ne, &done);
5333 __ Fmov(scratch1, dbl_scratch1);
5334 DeoptimizeIfNegative(scratch1, instr, Deoptimizer::kMinusZero);
5335 }
5336 }
5337 __ Bind(&done);
5338}
5339
5340
5341void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5342 class DeferredTaggedToI: public LDeferredCode {
5343 public:
5344 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
5345 : LDeferredCode(codegen), instr_(instr) { }
5346 virtual void Generate() {
5347 codegen()->DoDeferredTaggedToI(instr_, instr_->value(), instr_->temp1(),
5348 instr_->temp2());
5349 }
5350
5351 virtual LInstruction* instr() { return instr_; }
5352 private:
5353 LTaggedToI* instr_;
5354 };
5355
5356 Register input = ToRegister(instr->value());
5357 Register output = ToRegister(instr->result());
5358
5359 if (instr->hydrogen()->value()->representation().IsSmi()) {
5360 __ SmiUntag(output, input);
5361 } else {
5362 DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
5363
5364 __ JumpIfNotSmi(input, deferred->entry());
5365 __ SmiUntag(output, input);
5366 __ Bind(deferred->exit());
5367 }
5368}
5369
5370
5371void LCodeGen::DoThisFunction(LThisFunction* instr) {
5372 Register result = ToRegister(instr->result());
5373 __ Ldr(result, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
5374}
5375
5376
5377void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5378 DCHECK(ToRegister(instr->value()).Is(x0));
5379 DCHECK(ToRegister(instr->result()).Is(x0));
5380 __ Push(x0);
5381 CallRuntime(Runtime::kToFastProperties, 1, instr);
5382}
5383
5384
5385void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
5386 Register object = ToRegister(instr->object());
5387
5388 Handle<Map> from_map = instr->original_map();
5389 Handle<Map> to_map = instr->transitioned_map();
5390 ElementsKind from_kind = instr->from_kind();
5391 ElementsKind to_kind = instr->to_kind();
5392
5393 Label not_applicable;
5394
5395 if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
5396 Register temp1 = ToRegister(instr->temp1());
5397 Register new_map = ToRegister(instr->temp2());
5398 __ CheckMap(object, temp1, from_map, &not_applicable, DONT_DO_SMI_CHECK);
5399 __ Mov(new_map, Operand(to_map));
5400 __ Str(new_map, FieldMemOperand(object, HeapObject::kMapOffset));
5401 // Write barrier.
5402 __ RecordWriteForMap(object, new_map, temp1, GetLinkRegisterState(),
5403 kDontSaveFPRegs);
5404 } else {
5405 {
5406 UseScratchRegisterScope temps(masm());
5407 // Use the temp register only in a restricted scope - the codegen checks
5408 // that we do not use any register across a call.
5409 __ CheckMap(object, temps.AcquireX(), from_map, &not_applicable,
5410 DONT_DO_SMI_CHECK);
5411 }
5412 DCHECK(object.is(x0));
5413 DCHECK(ToRegister(instr->context()).is(cp));
5414 PushSafepointRegistersScope scope(this);
5415 __ Mov(x1, Operand(to_map));
5416 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
5417 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
5418 __ CallStub(&stub);
5419 RecordSafepointWithRegisters(
5420 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
5421 }
5422 __ Bind(&not_applicable);
5423}
5424
5425
5426void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
5427 Register object = ToRegister(instr->object());
5428 Register temp1 = ToRegister(instr->temp1());
5429 Register temp2 = ToRegister(instr->temp2());
5430
5431 Label no_memento_found;
5432 __ TestJSArrayForAllocationMemento(object, temp1, temp2, &no_memento_found);
5433 DeoptimizeIf(eq, instr, Deoptimizer::kMementoFound);
5434 __ Bind(&no_memento_found);
5435}
5436
5437
5438void LCodeGen::DoTruncateDoubleToIntOrSmi(LTruncateDoubleToIntOrSmi* instr) {
5439 DoubleRegister input = ToDoubleRegister(instr->value());
5440 Register result = ToRegister(instr->result());
5441 __ TruncateDoubleToI(result, input);
5442 if (instr->tag_result()) {
5443 __ SmiTag(result, result);
5444 }
5445}
5446
5447
5448void LCodeGen::DoTypeof(LTypeof* instr) {
5449 DCHECK(ToRegister(instr->value()).is(x3));
5450 DCHECK(ToRegister(instr->result()).is(x0));
5451 Label end, do_call;
5452 Register value_register = ToRegister(instr->value());
5453 __ JumpIfNotSmi(value_register, &do_call);
5454 __ Mov(x0, Immediate(isolate()->factory()->number_string()));
5455 __ B(&end);
5456 __ Bind(&do_call);
5457 TypeofStub stub(isolate());
5458 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5459 __ Bind(&end);
5460}
5461
5462
5463void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5464 Handle<String> type_name = instr->type_literal();
5465 Label* true_label = instr->TrueLabel(chunk_);
5466 Label* false_label = instr->FalseLabel(chunk_);
5467 Register value = ToRegister(instr->value());
5468
5469 Factory* factory = isolate()->factory();
5470 if (String::Equals(type_name, factory->number_string())) {
5471 __ JumpIfSmi(value, true_label);
5472
5473 int true_block = instr->TrueDestination(chunk_);
5474 int false_block = instr->FalseDestination(chunk_);
5475 int next_block = GetNextEmittedBlock();
5476
5477 if (true_block == false_block) {
5478 EmitGoto(true_block);
5479 } else if (true_block == next_block) {
5480 __ JumpIfNotHeapNumber(value, chunk_->GetAssemblyLabel(false_block));
5481 } else {
5482 __ JumpIfHeapNumber(value, chunk_->GetAssemblyLabel(true_block));
5483 if (false_block != next_block) {
5484 __ B(chunk_->GetAssemblyLabel(false_block));
5485 }
5486 }
5487
5488 } else if (String::Equals(type_name, factory->string_string())) {
5489 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5490 Register map = ToRegister(instr->temp1());
5491 Register scratch = ToRegister(instr->temp2());
5492
5493 __ JumpIfSmi(value, false_label);
5494 __ CompareObjectType(value, map, scratch, FIRST_NONSTRING_TYPE);
5495 EmitBranch(instr, lt);
5496
5497 } else if (String::Equals(type_name, factory->symbol_string())) {
5498 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5499 Register map = ToRegister(instr->temp1());
5500 Register scratch = ToRegister(instr->temp2());
5501
5502 __ JumpIfSmi(value, false_label);
5503 __ CompareObjectType(value, map, scratch, SYMBOL_TYPE);
5504 EmitBranch(instr, eq);
5505
5506 } else if (String::Equals(type_name, factory->boolean_string())) {
5507 __ JumpIfRoot(value, Heap::kTrueValueRootIndex, true_label);
5508 __ CompareRoot(value, Heap::kFalseValueRootIndex);
5509 EmitBranch(instr, eq);
5510
5511 } else if (String::Equals(type_name, factory->undefined_string())) {
5512 DCHECK(instr->temp1() != NULL);
5513 Register scratch = ToRegister(instr->temp1());
5514
Ben Murdoch097c5b22016-05-18 11:27:45 +01005515 __ JumpIfRoot(value, Heap::kNullValueRootIndex, false_label);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00005516 __ JumpIfSmi(value, false_label);
5517 // Check for undetectable objects and jump to the true branch in this case.
5518 __ Ldr(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
5519 __ Ldrb(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5520 EmitTestAndBranch(instr, ne, scratch, 1 << Map::kIsUndetectable);
5521
5522 } else if (String::Equals(type_name, factory->function_string())) {
5523 DCHECK(instr->temp1() != NULL);
5524 Register scratch = ToRegister(instr->temp1());
5525
5526 __ JumpIfSmi(value, false_label);
5527 __ Ldr(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
5528 __ Ldrb(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5529 __ And(scratch, scratch,
5530 (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
5531 EmitCompareAndBranch(instr, eq, scratch, 1 << Map::kIsCallable);
5532
5533 } else if (String::Equals(type_name, factory->object_string())) {
5534 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL));
5535 Register map = ToRegister(instr->temp1());
5536 Register scratch = ToRegister(instr->temp2());
5537
5538 __ JumpIfSmi(value, false_label);
5539 __ JumpIfRoot(value, Heap::kNullValueRootIndex, true_label);
5540 STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
5541 __ JumpIfObjectType(value, map, scratch, FIRST_JS_RECEIVER_TYPE,
5542 false_label, lt);
5543 // Check for callable or undetectable objects => false.
5544 __ Ldrb(scratch, FieldMemOperand(map, Map::kBitFieldOffset));
5545 EmitTestAndBranch(instr, eq, scratch,
5546 (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
5547
5548// clang-format off
5549#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
5550 } else if (String::Equals(type_name, factory->type##_string())) { \
5551 DCHECK((instr->temp1() != NULL) && (instr->temp2() != NULL)); \
5552 Register map = ToRegister(instr->temp1()); \
5553 \
5554 __ JumpIfSmi(value, false_label); \
5555 __ Ldr(map, FieldMemOperand(value, HeapObject::kMapOffset)); \
5556 __ CompareRoot(map, Heap::k##Type##MapRootIndex); \
5557 EmitBranch(instr, eq);
5558 SIMD128_TYPES(SIMD128_TYPE)
5559#undef SIMD128_TYPE
5560 // clang-format on
5561
5562 } else {
5563 __ B(false_label);
5564 }
5565}
5566
5567
5568void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
5569 __ Ucvtf(ToDoubleRegister(instr->result()), ToRegister32(instr->value()));
5570}
5571
5572
5573void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5574 Register object = ToRegister(instr->value());
5575 Register map = ToRegister(instr->map());
5576 Register temp = ToRegister(instr->temp());
5577 __ Ldr(temp, FieldMemOperand(object, HeapObject::kMapOffset));
5578 __ Cmp(map, temp);
5579 DeoptimizeIf(ne, instr, Deoptimizer::kWrongMap);
5580}
5581
5582
5583void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
5584 Register receiver = ToRegister(instr->receiver());
5585 Register function = ToRegister(instr->function());
5586 Register result = ToRegister(instr->result());
5587
5588 // If the receiver is null or undefined, we have to pass the global object as
5589 // a receiver to normal functions. Values have to be passed unchanged to
5590 // builtins and strict-mode functions.
5591 Label global_object, done, copy_receiver;
5592
5593 if (!instr->hydrogen()->known_function()) {
5594 __ Ldr(result, FieldMemOperand(function,
5595 JSFunction::kSharedFunctionInfoOffset));
5596
5597 // CompilerHints is an int32 field. See objects.h.
5598 __ Ldr(result.W(),
5599 FieldMemOperand(result, SharedFunctionInfo::kCompilerHintsOffset));
5600
5601 // Do not transform the receiver to object for strict mode functions.
5602 __ Tbnz(result, SharedFunctionInfo::kStrictModeFunction, &copy_receiver);
5603
5604 // Do not transform the receiver to object for builtins.
5605 __ Tbnz(result, SharedFunctionInfo::kNative, &copy_receiver);
5606 }
5607
5608 // Normal function. Replace undefined or null with global receiver.
5609 __ JumpIfRoot(receiver, Heap::kNullValueRootIndex, &global_object);
5610 __ JumpIfRoot(receiver, Heap::kUndefinedValueRootIndex, &global_object);
5611
5612 // Deoptimize if the receiver is not a JS object.
5613 DeoptimizeIfSmi(receiver, instr, Deoptimizer::kSmi);
5614 __ CompareObjectType(receiver, result, result, FIRST_JS_RECEIVER_TYPE);
5615 __ B(ge, &copy_receiver);
5616 Deoptimize(instr, Deoptimizer::kNotAJavaScriptObject);
5617
5618 __ Bind(&global_object);
5619 __ Ldr(result, FieldMemOperand(function, JSFunction::kContextOffset));
5620 __ Ldr(result, ContextMemOperand(result, Context::NATIVE_CONTEXT_INDEX));
5621 __ Ldr(result, ContextMemOperand(result, Context::GLOBAL_PROXY_INDEX));
5622 __ B(&done);
5623
5624 __ Bind(&copy_receiver);
5625 __ Mov(result, receiver);
5626 __ Bind(&done);
5627}
5628
5629
5630void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5631 Register result,
5632 Register object,
5633 Register index) {
5634 PushSafepointRegistersScope scope(this);
5635 __ Push(object);
5636 __ Push(index);
5637 __ Mov(cp, 0);
5638 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5639 RecordSafepointWithRegisters(
5640 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5641 __ StoreToSafepointRegisterSlot(x0, result);
5642}
5643
5644
5645void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5646 class DeferredLoadMutableDouble final : public LDeferredCode {
5647 public:
5648 DeferredLoadMutableDouble(LCodeGen* codegen,
5649 LLoadFieldByIndex* instr,
5650 Register result,
5651 Register object,
5652 Register index)
5653 : LDeferredCode(codegen),
5654 instr_(instr),
5655 result_(result),
5656 object_(object),
5657 index_(index) {
5658 }
5659 void Generate() override {
5660 codegen()->DoDeferredLoadMutableDouble(instr_, result_, object_, index_);
5661 }
5662 LInstruction* instr() override { return instr_; }
5663
5664 private:
5665 LLoadFieldByIndex* instr_;
5666 Register result_;
5667 Register object_;
5668 Register index_;
5669 };
5670 Register object = ToRegister(instr->object());
5671 Register index = ToRegister(instr->index());
5672 Register result = ToRegister(instr->result());
5673
5674 __ AssertSmi(index);
5675
5676 DeferredLoadMutableDouble* deferred;
5677 deferred = new(zone()) DeferredLoadMutableDouble(
5678 this, instr, result, object, index);
5679
5680 Label out_of_object, done;
5681
5682 __ TestAndBranchIfAnySet(
5683 index, reinterpret_cast<uint64_t>(Smi::FromInt(1)), deferred->entry());
5684 __ Mov(index, Operand(index, ASR, 1));
5685
5686 __ Cmp(index, Smi::FromInt(0));
5687 __ B(lt, &out_of_object);
5688
5689 STATIC_ASSERT(kPointerSizeLog2 > kSmiTagSize);
5690 __ Add(result, object, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
5691 __ Ldr(result, FieldMemOperand(result, JSObject::kHeaderSize));
5692
5693 __ B(&done);
5694
5695 __ Bind(&out_of_object);
5696 __ Ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
5697 // Index is equal to negated out of object property index plus 1.
5698 __ Sub(result, result, Operand::UntagSmiAndScale(index, kPointerSizeLog2));
5699 __ Ldr(result, FieldMemOperand(result,
5700 FixedArray::kHeaderSize - kPointerSize));
5701 __ Bind(deferred->exit());
5702 __ Bind(&done);
5703}
5704
5705
5706void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5707 Register context = ToRegister(instr->context());
5708 __ Str(context, MemOperand(fp, StandardFrameConstants::kContextOffset));
5709}
5710
5711
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00005712} // namespace internal
5713} // namespace v8