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