deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / x64 / macro-assembler-x64.h
1 // Copyright 2012 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 #ifndef V8_X64_MACRO_ASSEMBLER_X64_H_
6 #define V8_X64_MACRO_ASSEMBLER_X64_H_
7
8 #include "src/assembler.h"
9 #include "src/bailout-reason.h"
10 #include "src/frames.h"
11 #include "src/globals.h"
12
13 namespace v8 {
14 namespace internal {
15
16 // Default scratch register used by MacroAssembler (and other code that needs
17 // a spare register). The register isn't callee save, and not used by the
18 // function calling convention.
19 const Register kScratchRegister = { 10 };      // r10.
20 const Register kRootRegister = { 13 };         // r13 (callee save).
21 // Actual value of root register is offset from the root array's start
22 // to take advantage of negitive 8-bit displacement values.
23 const int kRootRegisterBias = 128;
24
25 // Convenience for platform-independent signatures.
26 typedef Operand MemOperand;
27
28 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
29 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
30 enum PointersToHereCheck {
31   kPointersToHereMaybeInteresting,
32   kPointersToHereAreAlwaysInteresting
33 };
34
35 enum SmiOperationConstraint {
36   PRESERVE_SOURCE_REGISTER,
37   BAILOUT_ON_NO_OVERFLOW,
38   BAILOUT_ON_OVERFLOW,
39   NUMBER_OF_CONSTRAINTS
40 };
41
42 STATIC_ASSERT(NUMBER_OF_CONSTRAINTS <= 8);
43
44 class SmiOperationExecutionMode : public EnumSet<SmiOperationConstraint, byte> {
45  public:
46   SmiOperationExecutionMode() : EnumSet<SmiOperationConstraint, byte>(0) { }
47   explicit SmiOperationExecutionMode(byte bits)
48       : EnumSet<SmiOperationConstraint, byte>(bits) { }
49 };
50
51 #ifdef DEBUG
52 bool AreAliased(Register reg1,
53                 Register reg2,
54                 Register reg3 = no_reg,
55                 Register reg4 = no_reg,
56                 Register reg5 = no_reg,
57                 Register reg6 = no_reg,
58                 Register reg7 = no_reg,
59                 Register reg8 = no_reg);
60 #endif
61
62 // Forward declaration.
63 class JumpTarget;
64
65 struct SmiIndex {
66   SmiIndex(Register index_register, ScaleFactor scale)
67       : reg(index_register),
68         scale(scale) {}
69   Register reg;
70   ScaleFactor scale;
71 };
72
73
74 // MacroAssembler implements a collection of frequently used macros.
75 class MacroAssembler: public Assembler {
76  public:
77   // The isolate parameter can be NULL if the macro assembler should
78   // not use isolate-dependent functionality. In this case, it's the
79   // responsibility of the caller to never invoke such function on the
80   // macro assembler.
81   MacroAssembler(Isolate* isolate, void* buffer, int size);
82
83   // Prevent the use of the RootArray during the lifetime of this
84   // scope object.
85   class NoRootArrayScope BASE_EMBEDDED {
86    public:
87     explicit NoRootArrayScope(MacroAssembler* assembler)
88         : variable_(&assembler->root_array_available_),
89           old_value_(assembler->root_array_available_) {
90       assembler->root_array_available_ = false;
91     }
92     ~NoRootArrayScope() {
93       *variable_ = old_value_;
94     }
95    private:
96     bool* variable_;
97     bool old_value_;
98   };
99
100   // Operand pointing to an external reference.
101   // May emit code to set up the scratch register. The operand is
102   // only guaranteed to be correct as long as the scratch register
103   // isn't changed.
104   // If the operand is used more than once, use a scratch register
105   // that is guaranteed not to be clobbered.
106   Operand ExternalOperand(ExternalReference reference,
107                           Register scratch = kScratchRegister);
108   // Loads and stores the value of an external reference.
109   // Special case code for load and store to take advantage of
110   // load_rax/store_rax if possible/necessary.
111   // For other operations, just use:
112   //   Operand operand = ExternalOperand(extref);
113   //   operation(operand, ..);
114   void Load(Register destination, ExternalReference source);
115   void Store(ExternalReference destination, Register source);
116   // Loads the address of the external reference into the destination
117   // register.
118   void LoadAddress(Register destination, ExternalReference source);
119   // Returns the size of the code generated by LoadAddress.
120   // Used by CallSize(ExternalReference) to find the size of a call.
121   int LoadAddressSize(ExternalReference source);
122   // Pushes the address of the external reference onto the stack.
123   void PushAddress(ExternalReference source);
124
125   // Operations on roots in the root-array.
126   void LoadRoot(Register destination, Heap::RootListIndex index);
127   void StoreRoot(Register source, Heap::RootListIndex index);
128   // Load a root value where the index (or part of it) is variable.
129   // The variable_offset register is added to the fixed_offset value
130   // to get the index into the root-array.
131   void LoadRootIndexed(Register destination,
132                        Register variable_offset,
133                        int fixed_offset);
134   void CompareRoot(Register with, Heap::RootListIndex index);
135   void CompareRoot(const Operand& with, Heap::RootListIndex index);
136   void PushRoot(Heap::RootListIndex index);
137
138   // These functions do not arrange the registers in any particular order so
139   // they are not useful for calls that can cause a GC.  The caller can
140   // exclude up to 3 registers that do not need to be saved and restored.
141   void PushCallerSaved(SaveFPRegsMode fp_mode,
142                        Register exclusion1 = no_reg,
143                        Register exclusion2 = no_reg,
144                        Register exclusion3 = no_reg);
145   void PopCallerSaved(SaveFPRegsMode fp_mode,
146                       Register exclusion1 = no_reg,
147                       Register exclusion2 = no_reg,
148                       Register exclusion3 = no_reg);
149
150 // ---------------------------------------------------------------------------
151 // GC Support
152
153
154   enum RememberedSetFinalAction {
155     kReturnAtEnd,
156     kFallThroughAtEnd
157   };
158
159   // Record in the remembered set the fact that we have a pointer to new space
160   // at the address pointed to by the addr register.  Only works if addr is not
161   // in new space.
162   void RememberedSetHelper(Register object,  // Used for debug code.
163                            Register addr,
164                            Register scratch,
165                            SaveFPRegsMode save_fp,
166                            RememberedSetFinalAction and_then);
167
168   void CheckPageFlag(Register object,
169                      Register scratch,
170                      int mask,
171                      Condition cc,
172                      Label* condition_met,
173                      Label::Distance condition_met_distance = Label::kFar);
174
175   // Check if object is in new space.  Jumps if the object is not in new space.
176   // The register scratch can be object itself, but scratch will be clobbered.
177   void JumpIfNotInNewSpace(Register object,
178                            Register scratch,
179                            Label* branch,
180                            Label::Distance distance = Label::kFar) {
181     InNewSpace(object, scratch, not_equal, branch, distance);
182   }
183
184   // Check if object is in new space.  Jumps if the object is in new space.
185   // The register scratch can be object itself, but it will be clobbered.
186   void JumpIfInNewSpace(Register object,
187                         Register scratch,
188                         Label* branch,
189                         Label::Distance distance = Label::kFar) {
190     InNewSpace(object, scratch, equal, branch, distance);
191   }
192
193   // Check if an object has the black incremental marking color.  Also uses rcx!
194   void JumpIfBlack(Register object,
195                    Register scratch0,
196                    Register scratch1,
197                    Label* on_black,
198                    Label::Distance on_black_distance = Label::kFar);
199
200   // Detects conservatively whether an object is data-only, i.e. it does need to
201   // be scanned by the garbage collector.
202   void JumpIfDataObject(Register value,
203                         Register scratch,
204                         Label* not_data_object,
205                         Label::Distance not_data_object_distance);
206
207   // Checks the color of an object.  If the object is already grey or black
208   // then we just fall through, since it is already live.  If it is white and
209   // we can determine that it doesn't need to be scanned, then we just mark it
210   // black and fall through.  For the rest we jump to the label so the
211   // incremental marker can fix its assumptions.
212   void EnsureNotWhite(Register object,
213                       Register scratch1,
214                       Register scratch2,
215                       Label* object_is_white_and_not_data,
216                       Label::Distance distance);
217
218   // Notify the garbage collector that we wrote a pointer into an object.
219   // |object| is the object being stored into, |value| is the object being
220   // stored.  value and scratch registers are clobbered by the operation.
221   // The offset is the offset from the start of the object, not the offset from
222   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
223   void RecordWriteField(
224       Register object,
225       int offset,
226       Register value,
227       Register scratch,
228       SaveFPRegsMode save_fp,
229       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
230       SmiCheck smi_check = INLINE_SMI_CHECK,
231       PointersToHereCheck pointers_to_here_check_for_value =
232           kPointersToHereMaybeInteresting);
233
234   // As above, but the offset has the tag presubtracted.  For use with
235   // Operand(reg, off).
236   void RecordWriteContextSlot(
237       Register context,
238       int offset,
239       Register value,
240       Register scratch,
241       SaveFPRegsMode save_fp,
242       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
243       SmiCheck smi_check = INLINE_SMI_CHECK,
244       PointersToHereCheck pointers_to_here_check_for_value =
245           kPointersToHereMaybeInteresting) {
246     RecordWriteField(context,
247                      offset + kHeapObjectTag,
248                      value,
249                      scratch,
250                      save_fp,
251                      remembered_set_action,
252                      smi_check,
253                      pointers_to_here_check_for_value);
254   }
255
256   // Notify the garbage collector that we wrote a pointer into a fixed array.
257   // |array| is the array being stored into, |value| is the
258   // object being stored.  |index| is the array index represented as a non-smi.
259   // All registers are clobbered by the operation RecordWriteArray
260   // filters out smis so it does not update the write barrier if the
261   // value is a smi.
262   void RecordWriteArray(
263       Register array,
264       Register value,
265       Register index,
266       SaveFPRegsMode save_fp,
267       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
268       SmiCheck smi_check = INLINE_SMI_CHECK,
269       PointersToHereCheck pointers_to_here_check_for_value =
270           kPointersToHereMaybeInteresting);
271
272   void RecordWriteForMap(
273       Register object,
274       Register map,
275       Register dst,
276       SaveFPRegsMode save_fp);
277
278   // For page containing |object| mark region covering |address|
279   // dirty. |object| is the object being stored into, |value| is the
280   // object being stored. The address and value registers are clobbered by the
281   // operation.  RecordWrite filters out smis so it does not update
282   // the write barrier if the value is a smi.
283   void RecordWrite(
284       Register object,
285       Register address,
286       Register value,
287       SaveFPRegsMode save_fp,
288       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
289       SmiCheck smi_check = INLINE_SMI_CHECK,
290       PointersToHereCheck pointers_to_here_check_for_value =
291           kPointersToHereMaybeInteresting);
292
293   // ---------------------------------------------------------------------------
294   // Debugger Support
295
296   void DebugBreak();
297
298   // Generates function and stub prologue code.
299   void StubPrologue();
300   void Prologue(bool code_pre_aging);
301
302   // Enter specific kind of exit frame; either in normal or
303   // debug mode. Expects the number of arguments in register rax and
304   // sets up the number of arguments in register rdi and the pointer
305   // to the first argument in register rsi.
306   //
307   // Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
308   // accessible via StackSpaceOperand.
309   void EnterExitFrame(int arg_stack_space = 0, bool save_doubles = false);
310
311   // Enter specific kind of exit frame. Allocates arg_stack_space * kPointerSize
312   // memory (not GCed) on the stack accessible via StackSpaceOperand.
313   void EnterApiExitFrame(int arg_stack_space);
314
315   // Leave the current exit frame. Expects/provides the return value in
316   // register rax:rdx (untouched) and the pointer to the first
317   // argument in register rsi.
318   void LeaveExitFrame(bool save_doubles = false);
319
320   // Leave the current exit frame. Expects/provides the return value in
321   // register rax (untouched).
322   void LeaveApiExitFrame(bool restore_context);
323
324   // Push and pop the registers that can hold pointers.
325   void PushSafepointRegisters() { Pushad(); }
326   void PopSafepointRegisters() { Popad(); }
327   // Store the value in register src in the safepoint register stack
328   // slot for register dst.
329   void StoreToSafepointRegisterSlot(Register dst, const Immediate& imm);
330   void StoreToSafepointRegisterSlot(Register dst, Register src);
331   void LoadFromSafepointRegisterSlot(Register dst, Register src);
332
333   void InitializeRootRegister() {
334     ExternalReference roots_array_start =
335         ExternalReference::roots_array_start(isolate());
336     Move(kRootRegister, roots_array_start);
337     addp(kRootRegister, Immediate(kRootRegisterBias));
338   }
339
340   // ---------------------------------------------------------------------------
341   // JavaScript invokes
342
343   // Invoke the JavaScript function code by either calling or jumping.
344   void InvokeCode(Register code,
345                   const ParameterCount& expected,
346                   const ParameterCount& actual,
347                   InvokeFlag flag,
348                   const CallWrapper& call_wrapper);
349
350   // Invoke the JavaScript function in the given register. Changes the
351   // current context to the context in the function before invoking.
352   void InvokeFunction(Register function,
353                       const ParameterCount& actual,
354                       InvokeFlag flag,
355                       const CallWrapper& call_wrapper);
356
357   void InvokeFunction(Register function,
358                       const ParameterCount& expected,
359                       const ParameterCount& actual,
360                       InvokeFlag flag,
361                       const CallWrapper& call_wrapper);
362
363   void InvokeFunction(Handle<JSFunction> function,
364                       const ParameterCount& expected,
365                       const ParameterCount& actual,
366                       InvokeFlag flag,
367                       const CallWrapper& call_wrapper);
368
369   // Invoke specified builtin JavaScript function. Adds an entry to
370   // the unresolved list if the name does not resolve.
371   void InvokeBuiltin(Builtins::JavaScript id,
372                      InvokeFlag flag,
373                      const CallWrapper& call_wrapper = NullCallWrapper());
374
375   // Store the function for the given builtin in the target register.
376   void GetBuiltinFunction(Register target, Builtins::JavaScript id);
377
378   // Store the code object for the given builtin in the target register.
379   void GetBuiltinEntry(Register target, Builtins::JavaScript id);
380
381
382   // ---------------------------------------------------------------------------
383   // Smi tagging, untagging and operations on tagged smis.
384
385   // Support for constant splitting.
386   bool IsUnsafeInt(const int32_t x);
387   void SafeMove(Register dst, Smi* src);
388   void SafePush(Smi* src);
389
390   // Conversions between tagged smi values and non-tagged integer values.
391
392   // Tag an integer value. The result must be known to be a valid smi value.
393   // Only uses the low 32 bits of the src register. Sets the N and Z flags
394   // based on the value of the resulting smi.
395   void Integer32ToSmi(Register dst, Register src);
396
397   // Stores an integer32 value into a memory field that already holds a smi.
398   void Integer32ToSmiField(const Operand& dst, Register src);
399
400   // Adds constant to src and tags the result as a smi.
401   // Result must be a valid smi.
402   void Integer64PlusConstantToSmi(Register dst, Register src, int constant);
403
404   // Convert smi to 32-bit integer. I.e., not sign extended into
405   // high 32 bits of destination.
406   void SmiToInteger32(Register dst, Register src);
407   void SmiToInteger32(Register dst, const Operand& src);
408
409   // Convert smi to 64-bit integer (sign extended if necessary).
410   void SmiToInteger64(Register dst, Register src);
411   void SmiToInteger64(Register dst, const Operand& src);
412
413   // Multiply a positive smi's integer value by a power of two.
414   // Provides result as 64-bit integer value.
415   void PositiveSmiTimesPowerOfTwoToInteger64(Register dst,
416                                              Register src,
417                                              int power);
418
419   // Divide a positive smi's integer value by a power of two.
420   // Provides result as 32-bit integer value.
421   void PositiveSmiDivPowerOfTwoToInteger32(Register dst,
422                                            Register src,
423                                            int power);
424
425   // Perform the logical or of two smi values and return a smi value.
426   // If either argument is not a smi, jump to on_not_smis and retain
427   // the original values of source registers. The destination register
428   // may be changed if it's not one of the source registers.
429   void SmiOrIfSmis(Register dst,
430                    Register src1,
431                    Register src2,
432                    Label* on_not_smis,
433                    Label::Distance near_jump = Label::kFar);
434
435
436   // Simple comparison of smis.  Both sides must be known smis to use these,
437   // otherwise use Cmp.
438   void SmiCompare(Register smi1, Register smi2);
439   void SmiCompare(Register dst, Smi* src);
440   void SmiCompare(Register dst, const Operand& src);
441   void SmiCompare(const Operand& dst, Register src);
442   void SmiCompare(const Operand& dst, Smi* src);
443   // Compare the int32 in src register to the value of the smi stored at dst.
444   void SmiCompareInteger32(const Operand& dst, Register src);
445   // Sets sign and zero flags depending on value of smi in register.
446   void SmiTest(Register src);
447
448   // Functions performing a check on a known or potential smi. Returns
449   // a condition that is satisfied if the check is successful.
450
451   // Is the value a tagged smi.
452   Condition CheckSmi(Register src);
453   Condition CheckSmi(const Operand& src);
454
455   // Is the value a non-negative tagged smi.
456   Condition CheckNonNegativeSmi(Register src);
457
458   // Are both values tagged smis.
459   Condition CheckBothSmi(Register first, Register second);
460
461   // Are both values non-negative tagged smis.
462   Condition CheckBothNonNegativeSmi(Register first, Register second);
463
464   // Are either value a tagged smi.
465   Condition CheckEitherSmi(Register first,
466                            Register second,
467                            Register scratch = kScratchRegister);
468
469   // Checks whether an 32-bit integer value is a valid for conversion
470   // to a smi.
471   Condition CheckInteger32ValidSmiValue(Register src);
472
473   // Checks whether an 32-bit unsigned integer value is a valid for
474   // conversion to a smi.
475   Condition CheckUInteger32ValidSmiValue(Register src);
476
477   // Check whether src is a Smi, and set dst to zero if it is a smi,
478   // and to one if it isn't.
479   void CheckSmiToIndicator(Register dst, Register src);
480   void CheckSmiToIndicator(Register dst, const Operand& src);
481
482   // Test-and-jump functions. Typically combines a check function
483   // above with a conditional jump.
484
485   // Jump if the value can be represented by a smi.
486   void JumpIfValidSmiValue(Register src, Label* on_valid,
487                            Label::Distance near_jump = Label::kFar);
488
489   // Jump if the value cannot be represented by a smi.
490   void JumpIfNotValidSmiValue(Register src, Label* on_invalid,
491                               Label::Distance near_jump = Label::kFar);
492
493   // Jump if the unsigned integer value can be represented by a smi.
494   void JumpIfUIntValidSmiValue(Register src, Label* on_valid,
495                                Label::Distance near_jump = Label::kFar);
496
497   // Jump if the unsigned integer value cannot be represented by a smi.
498   void JumpIfUIntNotValidSmiValue(Register src, Label* on_invalid,
499                                   Label::Distance near_jump = Label::kFar);
500
501   // Jump to label if the value is a tagged smi.
502   void JumpIfSmi(Register src,
503                  Label* on_smi,
504                  Label::Distance near_jump = Label::kFar);
505
506   // Jump to label if the value is not a tagged smi.
507   void JumpIfNotSmi(Register src,
508                     Label* on_not_smi,
509                     Label::Distance near_jump = Label::kFar);
510
511   // Jump to label if the value is not a non-negative tagged smi.
512   void JumpUnlessNonNegativeSmi(Register src,
513                                 Label* on_not_smi,
514                                 Label::Distance near_jump = Label::kFar);
515
516   // Jump to label if the value, which must be a tagged smi, has value equal
517   // to the constant.
518   void JumpIfSmiEqualsConstant(Register src,
519                                Smi* constant,
520                                Label* on_equals,
521                                Label::Distance near_jump = Label::kFar);
522
523   // Jump if either or both register are not smi values.
524   void JumpIfNotBothSmi(Register src1,
525                         Register src2,
526                         Label* on_not_both_smi,
527                         Label::Distance near_jump = Label::kFar);
528
529   // Jump if either or both register are not non-negative smi values.
530   void JumpUnlessBothNonNegativeSmi(Register src1, Register src2,
531                                     Label* on_not_both_smi,
532                                     Label::Distance near_jump = Label::kFar);
533
534   // Operations on tagged smi values.
535
536   // Smis represent a subset of integers. The subset is always equivalent to
537   // a two's complement interpretation of a fixed number of bits.
538
539   // Add an integer constant to a tagged smi, giving a tagged smi as result.
540   // No overflow testing on the result is done.
541   void SmiAddConstant(Register dst, Register src, Smi* constant);
542
543   // Add an integer constant to a tagged smi, giving a tagged smi as result.
544   // No overflow testing on the result is done.
545   void SmiAddConstant(const Operand& dst, Smi* constant);
546
547   // Add an integer constant to a tagged smi, giving a tagged smi as result,
548   // or jumping to a label if the result cannot be represented by a smi.
549   void SmiAddConstant(Register dst,
550                       Register src,
551                       Smi* constant,
552                       SmiOperationExecutionMode mode,
553                       Label* bailout_label,
554                       Label::Distance near_jump = Label::kFar);
555
556   // Subtract an integer constant from a tagged smi, giving a tagged smi as
557   // result. No testing on the result is done. Sets the N and Z flags
558   // based on the value of the resulting integer.
559   void SmiSubConstant(Register dst, Register src, Smi* constant);
560
561   // Subtract an integer constant from a tagged smi, giving a tagged smi as
562   // result, or jumping to a label if the result cannot be represented by a smi.
563   void SmiSubConstant(Register dst,
564                       Register src,
565                       Smi* constant,
566                       SmiOperationExecutionMode mode,
567                       Label* bailout_label,
568                       Label::Distance near_jump = Label::kFar);
569
570   // Negating a smi can give a negative zero or too large positive value.
571   // NOTICE: This operation jumps on success, not failure!
572   void SmiNeg(Register dst,
573               Register src,
574               Label* on_smi_result,
575               Label::Distance near_jump = Label::kFar);
576
577   // Adds smi values and return the result as a smi.
578   // If dst is src1, then src1 will be destroyed if the operation is
579   // successful, otherwise kept intact.
580   void SmiAdd(Register dst,
581               Register src1,
582               Register src2,
583               Label* on_not_smi_result,
584               Label::Distance near_jump = Label::kFar);
585   void SmiAdd(Register dst,
586               Register src1,
587               const Operand& src2,
588               Label* on_not_smi_result,
589               Label::Distance near_jump = Label::kFar);
590
591   void SmiAdd(Register dst,
592               Register src1,
593               Register src2);
594
595   // Subtracts smi values and return the result as a smi.
596   // If dst is src1, then src1 will be destroyed if the operation is
597   // successful, otherwise kept intact.
598   void SmiSub(Register dst,
599               Register src1,
600               Register src2,
601               Label* on_not_smi_result,
602               Label::Distance near_jump = Label::kFar);
603   void SmiSub(Register dst,
604               Register src1,
605               const Operand& src2,
606               Label* on_not_smi_result,
607               Label::Distance near_jump = Label::kFar);
608
609   void SmiSub(Register dst,
610               Register src1,
611               Register src2);
612
613   void SmiSub(Register dst,
614               Register src1,
615               const Operand& src2);
616
617   // Multiplies smi values and return the result as a smi,
618   // if possible.
619   // If dst is src1, then src1 will be destroyed, even if
620   // the operation is unsuccessful.
621   void SmiMul(Register dst,
622               Register src1,
623               Register src2,
624               Label* on_not_smi_result,
625               Label::Distance near_jump = Label::kFar);
626
627   // Divides one smi by another and returns the quotient.
628   // Clobbers rax and rdx registers.
629   void SmiDiv(Register dst,
630               Register src1,
631               Register src2,
632               Label* on_not_smi_result,
633               Label::Distance near_jump = Label::kFar);
634
635   // Divides one smi by another and returns the remainder.
636   // Clobbers rax and rdx registers.
637   void SmiMod(Register dst,
638               Register src1,
639               Register src2,
640               Label* on_not_smi_result,
641               Label::Distance near_jump = Label::kFar);
642
643   // Bitwise operations.
644   void SmiNot(Register dst, Register src);
645   void SmiAnd(Register dst, Register src1, Register src2);
646   void SmiOr(Register dst, Register src1, Register src2);
647   void SmiXor(Register dst, Register src1, Register src2);
648   void SmiAndConstant(Register dst, Register src1, Smi* constant);
649   void SmiOrConstant(Register dst, Register src1, Smi* constant);
650   void SmiXorConstant(Register dst, Register src1, Smi* constant);
651
652   void SmiShiftLeftConstant(Register dst,
653                             Register src,
654                             int shift_value,
655                             Label* on_not_smi_result = NULL,
656                             Label::Distance near_jump = Label::kFar);
657   void SmiShiftLogicalRightConstant(Register dst,
658                                     Register src,
659                                     int shift_value,
660                                     Label* on_not_smi_result,
661                                     Label::Distance near_jump = Label::kFar);
662   void SmiShiftArithmeticRightConstant(Register dst,
663                                        Register src,
664                                        int shift_value);
665
666   // Shifts a smi value to the left, and returns the result if that is a smi.
667   // Uses and clobbers rcx, so dst may not be rcx.
668   void SmiShiftLeft(Register dst,
669                     Register src1,
670                     Register src2,
671                     Label* on_not_smi_result = NULL,
672                     Label::Distance near_jump = Label::kFar);
673   // Shifts a smi value to the right, shifting in zero bits at the top, and
674   // returns the unsigned intepretation of the result if that is a smi.
675   // Uses and clobbers rcx, so dst may not be rcx.
676   void SmiShiftLogicalRight(Register dst,
677                             Register src1,
678                             Register src2,
679                             Label* on_not_smi_result,
680                             Label::Distance near_jump = Label::kFar);
681   // Shifts a smi value to the right, sign extending the top, and
682   // returns the signed intepretation of the result. That will always
683   // be a valid smi value, since it's numerically smaller than the
684   // original.
685   // Uses and clobbers rcx, so dst may not be rcx.
686   void SmiShiftArithmeticRight(Register dst,
687                                Register src1,
688                                Register src2);
689
690   // Specialized operations
691
692   // Select the non-smi register of two registers where exactly one is a
693   // smi. If neither are smis, jump to the failure label.
694   void SelectNonSmi(Register dst,
695                     Register src1,
696                     Register src2,
697                     Label* on_not_smis,
698                     Label::Distance near_jump = Label::kFar);
699
700   // Converts, if necessary, a smi to a combination of number and
701   // multiplier to be used as a scaled index.
702   // The src register contains a *positive* smi value. The shift is the
703   // power of two to multiply the index value by (e.g.
704   // to index by smi-value * kPointerSize, pass the smi and kPointerSizeLog2).
705   // The returned index register may be either src or dst, depending
706   // on what is most efficient. If src and dst are different registers,
707   // src is always unchanged.
708   SmiIndex SmiToIndex(Register dst, Register src, int shift);
709
710   // Converts a positive smi to a negative index.
711   SmiIndex SmiToNegativeIndex(Register dst, Register src, int shift);
712
713   // Add the value of a smi in memory to an int32 register.
714   // Sets flags as a normal add.
715   void AddSmiField(Register dst, const Operand& src);
716
717   // Basic Smi operations.
718   void Move(Register dst, Smi* source) {
719     LoadSmiConstant(dst, source);
720   }
721
722   void Move(const Operand& dst, Smi* source) {
723     Register constant = GetSmiConstant(source);
724     movp(dst, constant);
725   }
726
727   void Push(Smi* smi);
728
729   // Save away a raw integer with pointer size on the stack as two integers
730   // masquerading as smis so that the garbage collector skips visiting them.
731   void PushRegisterAsTwoSmis(Register src, Register scratch = kScratchRegister);
732   // Reconstruct a raw integer with pointer size from two integers masquerading
733   // as smis on the top of stack.
734   void PopRegisterAsTwoSmis(Register dst, Register scratch = kScratchRegister);
735
736   void Test(const Operand& dst, Smi* source);
737
738
739   // ---------------------------------------------------------------------------
740   // String macros.
741
742   // Generate code to do a lookup in the number string cache. If the number in
743   // the register object is found in the cache the generated code falls through
744   // with the result in the result register. The object and the result register
745   // can be the same. If the number is not found in the cache the code jumps to
746   // the label not_found with only the content of register object unchanged.
747   void LookupNumberStringCache(Register object,
748                                Register result,
749                                Register scratch1,
750                                Register scratch2,
751                                Label* not_found);
752
753   // If object is a string, its map is loaded into object_map.
754   void JumpIfNotString(Register object,
755                        Register object_map,
756                        Label* not_string,
757                        Label::Distance near_jump = Label::kFar);
758
759
760   void JumpIfNotBothSequentialOneByteStrings(
761       Register first_object, Register second_object, Register scratch1,
762       Register scratch2, Label* on_not_both_flat_one_byte,
763       Label::Distance near_jump = Label::kFar);
764
765   // Check whether the instance type represents a flat one-byte string. Jump
766   // to the label if not. If the instance type can be scratched specify same
767   // register for both instance type and scratch.
768   void JumpIfInstanceTypeIsNotSequentialOneByte(
769       Register instance_type, Register scratch,
770       Label* on_not_flat_one_byte_string,
771       Label::Distance near_jump = Label::kFar);
772
773   void JumpIfBothInstanceTypesAreNotSequentialOneByte(
774       Register first_object_instance_type, Register second_object_instance_type,
775       Register scratch1, Register scratch2, Label* on_fail,
776       Label::Distance near_jump = Label::kFar);
777
778   void EmitSeqStringSetCharCheck(Register string,
779                                  Register index,
780                                  Register value,
781                                  uint32_t encoding_mask);
782
783   // Checks if the given register or operand is a unique name
784   void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name,
785                                        Label::Distance distance = Label::kFar);
786   void JumpIfNotUniqueNameInstanceType(Operand operand, Label* not_unique_name,
787                                        Label::Distance distance = Label::kFar);
788
789   // ---------------------------------------------------------------------------
790   // Macro instructions.
791
792   // Load/store with specific representation.
793   void Load(Register dst, const Operand& src, Representation r);
794   void Store(const Operand& dst, Register src, Representation r);
795
796   // Load a register with a long value as efficiently as possible.
797   void Set(Register dst, int64_t x);
798   void Set(const Operand& dst, intptr_t x);
799
800   // cvtsi2sd instruction only writes to the low 64-bit of dst register, which
801   // hinders register renaming and makes dependence chains longer. So we use
802   // xorps to clear the dst register before cvtsi2sd to solve this issue.
803   void Cvtlsi2sd(XMMRegister dst, Register src);
804   void Cvtlsi2sd(XMMRegister dst, const Operand& src);
805
806   // Move if the registers are not identical.
807   void Move(Register target, Register source);
808
809   // TestBit and Load SharedFunctionInfo special field.
810   void TestBitSharedFunctionInfoSpecialField(Register base,
811                                              int offset,
812                                              int bit_index);
813   void LoadSharedFunctionInfoSpecialField(Register dst,
814                                           Register base,
815                                           int offset);
816
817   // Handle support
818   void Move(Register dst, Handle<Object> source);
819   void Move(const Operand& dst, Handle<Object> source);
820   void Cmp(Register dst, Handle<Object> source);
821   void Cmp(const Operand& dst, Handle<Object> source);
822   void Cmp(Register dst, Smi* src);
823   void Cmp(const Operand& dst, Smi* src);
824   void Push(Handle<Object> source);
825
826   // Load a heap object and handle the case of new-space objects by
827   // indirecting via a global cell.
828   void MoveHeapObject(Register result, Handle<Object> object);
829
830   // Load a global cell into a register.
831   void LoadGlobalCell(Register dst, Handle<Cell> cell);
832
833   // Compare the given value and the value of weak cell.
834   void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
835
836   void GetWeakValue(Register value, Handle<WeakCell> cell);
837
838   // Load the value of the weak cell in the value register. Branch to the given
839   // miss label if the weak cell was cleared.
840   void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
841
842   // Emit code to discard a non-negative number of pointer-sized elements
843   // from the stack, clobbering only the rsp register.
844   void Drop(int stack_elements);
845   // Emit code to discard a positive number of pointer-sized elements
846   // from the stack under the return address which remains on the top,
847   // clobbering the rsp register.
848   void DropUnderReturnAddress(int stack_elements,
849                               Register scratch = kScratchRegister);
850
851   void Call(Label* target) { call(target); }
852   void Push(Register src);
853   void Push(const Operand& src);
854   void PushQuad(const Operand& src);
855   void Push(Immediate value);
856   void PushImm32(int32_t imm32);
857   void Pop(Register dst);
858   void Pop(const Operand& dst);
859   void PopQuad(const Operand& dst);
860   void PushReturnAddressFrom(Register src) { pushq(src); }
861   void PopReturnAddressTo(Register dst) { popq(dst); }
862   void Move(Register dst, ExternalReference ext) {
863     movp(dst, reinterpret_cast<void*>(ext.address()),
864          RelocInfo::EXTERNAL_REFERENCE);
865   }
866
867   // Loads a pointer into a register with a relocation mode.
868   void Move(Register dst, void* ptr, RelocInfo::Mode rmode) {
869     // This method must not be used with heap object references. The stored
870     // address is not GC safe. Use the handle version instead.
871     DCHECK(rmode > RelocInfo::LAST_GCED_ENUM);
872     movp(dst, ptr, rmode);
873   }
874
875   void Move(Register dst, Handle<Object> value, RelocInfo::Mode rmode) {
876     AllowDeferredHandleDereference using_raw_address;
877     DCHECK(!RelocInfo::IsNone(rmode));
878     DCHECK(value->IsHeapObject());
879     DCHECK(!isolate()->heap()->InNewSpace(*value));
880     movp(dst, reinterpret_cast<void*>(value.location()), rmode);
881   }
882
883   void Move(XMMRegister dst, uint32_t src);
884   void Move(XMMRegister dst, uint64_t src);
885   void Move(XMMRegister dst, float src) { Move(dst, bit_cast<uint32_t>(src)); }
886   void Move(XMMRegister dst, double src) { Move(dst, bit_cast<uint64_t>(src)); }
887
888   // Control Flow
889   void Jump(Address destination, RelocInfo::Mode rmode);
890   void Jump(ExternalReference ext);
891   void Jump(const Operand& op);
892   void Jump(Handle<Code> code_object, RelocInfo::Mode rmode);
893
894   void Call(Address destination, RelocInfo::Mode rmode);
895   void Call(ExternalReference ext);
896   void Call(const Operand& op);
897   void Call(Handle<Code> code_object,
898             RelocInfo::Mode rmode,
899             TypeFeedbackId ast_id = TypeFeedbackId::None());
900
901   // The size of the code generated for different call instructions.
902   int CallSize(Address destination) {
903     return kCallSequenceLength;
904   }
905   int CallSize(ExternalReference ext);
906   int CallSize(Handle<Code> code_object) {
907     // Code calls use 32-bit relative addressing.
908     return kShortCallInstructionLength;
909   }
910   int CallSize(Register target) {
911     // Opcode: REX_opt FF /2 m64
912     return (target.high_bit() != 0) ? 3 : 2;
913   }
914   int CallSize(const Operand& target) {
915     // Opcode: REX_opt FF /2 m64
916     return (target.requires_rex() ? 2 : 1) + target.operand_size();
917   }
918
919   // Emit call to the code we are currently generating.
920   void CallSelf() {
921     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
922     Call(self, RelocInfo::CODE_TARGET);
923   }
924
925   // Non-SSE2 instructions.
926   void Pextrd(Register dst, XMMRegister src, int8_t imm8);
927   void Pinsrd(XMMRegister dst, Register src, int8_t imm8);
928   void Pinsrd(XMMRegister dst, const Operand& src, int8_t imm8);
929
930   void Lzcntl(Register dst, Register src);
931   void Lzcntl(Register dst, const Operand& src);
932
933   // Non-x64 instructions.
934   // Push/pop all general purpose registers.
935   // Does not push rsp/rbp nor any of the assembler's special purpose registers
936   // (kScratchRegister, kRootRegister).
937   void Pushad();
938   void Popad();
939   // Sets the stack as after performing Popad, without actually loading the
940   // registers.
941   void Dropad();
942
943   // Compare object type for heap object.
944   // Always use unsigned comparisons: above and below, not less and greater.
945   // Incoming register is heap_object and outgoing register is map.
946   // They may be the same register, and may be kScratchRegister.
947   void CmpObjectType(Register heap_object, InstanceType type, Register map);
948
949   // Compare instance type for map.
950   // Always use unsigned comparisons: above and below, not less and greater.
951   void CmpInstanceType(Register map, InstanceType type);
952
953   // Check if a map for a JSObject indicates that the object has fast elements.
954   // Jump to the specified label if it does not.
955   void CheckFastElements(Register map,
956                          Label* fail,
957                          Label::Distance distance = Label::kFar);
958
959   // Check if a map for a JSObject indicates that the object can have both smi
960   // and HeapObject elements.  Jump to the specified label if it does not.
961   void CheckFastObjectElements(Register map,
962                                Label* fail,
963                                Label::Distance distance = Label::kFar);
964
965   // Check if a map for a JSObject indicates that the object has fast smi only
966   // elements.  Jump to the specified label if it does not.
967   void CheckFastSmiElements(Register map,
968                             Label* fail,
969                             Label::Distance distance = Label::kFar);
970
971   // Check to see if maybe_number can be stored as a double in
972   // FastDoubleElements. If it can, store it at the index specified by index in
973   // the FastDoubleElements array elements, otherwise jump to fail.  Note that
974   // index must not be smi-tagged.
975   void StoreNumberToDoubleElements(Register maybe_number,
976                                    Register elements,
977                                    Register index,
978                                    XMMRegister xmm_scratch,
979                                    Label* fail,
980                                    int elements_offset = 0);
981
982   // Compare an object's map with the specified map.
983   void CompareMap(Register obj, Handle<Map> map);
984
985   // Check if the map of an object is equal to a specified map and branch to
986   // label if not. Skip the smi check if not required (object is known to be a
987   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
988   // against maps that are ElementsKind transition maps of the specified map.
989   void CheckMap(Register obj,
990                 Handle<Map> map,
991                 Label* fail,
992                 SmiCheckType smi_check_type);
993
994   // Check if the map of an object is equal to a specified weak map and branch
995   // to a specified target if equal. Skip the smi check if not required
996   // (object is known to be a heap object)
997   void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
998                        Handle<WeakCell> cell, Handle<Code> success,
999                        SmiCheckType smi_check_type);
1000
1001   // Check if the object in register heap_object is a string. Afterwards the
1002   // register map contains the object map and the register instance_type
1003   // contains the instance_type. The registers map and instance_type can be the
1004   // same in which case it contains the instance type afterwards. Either of the
1005   // registers map and instance_type can be the same as heap_object.
1006   Condition IsObjectStringType(Register heap_object,
1007                                Register map,
1008                                Register instance_type);
1009
1010   // Check if the object in register heap_object is a name. Afterwards the
1011   // register map contains the object map and the register instance_type
1012   // contains the instance_type. The registers map and instance_type can be the
1013   // same in which case it contains the instance type afterwards. Either of the
1014   // registers map and instance_type can be the same as heap_object.
1015   Condition IsObjectNameType(Register heap_object,
1016                              Register map,
1017                              Register instance_type);
1018
1019   // FCmp compares and pops the two values on top of the FPU stack.
1020   // The flag results are similar to integer cmp, but requires unsigned
1021   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
1022   void FCmp();
1023
1024   void ClampUint8(Register reg);
1025
1026   void ClampDoubleToUint8(XMMRegister input_reg,
1027                           XMMRegister temp_xmm_reg,
1028                           Register result_reg);
1029
1030   void SlowTruncateToI(Register result_reg, Register input_reg,
1031       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
1032
1033   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
1034   void TruncateDoubleToI(Register result_reg, XMMRegister input_reg);
1035
1036   void DoubleToI(Register result_reg, XMMRegister input_reg,
1037                  XMMRegister scratch, MinusZeroMode minus_zero_mode,
1038                  Label* lost_precision, Label* is_nan, Label* minus_zero,
1039                  Label::Distance dst = Label::kFar);
1040
1041   void LoadUint32(XMMRegister dst, Register src);
1042
1043   void LoadInstanceDescriptors(Register map, Register descriptors);
1044   void EnumLength(Register dst, Register map);
1045   void NumberOfOwnDescriptors(Register dst, Register map);
1046   void LoadAccessor(Register dst, Register holder, int accessor_index,
1047                     AccessorComponent accessor);
1048
1049   template<typename Field>
1050   void DecodeField(Register reg) {
1051     static const int shift = Field::kShift;
1052     static const int mask = Field::kMask >> Field::kShift;
1053     if (shift != 0) {
1054       shrp(reg, Immediate(shift));
1055     }
1056     andp(reg, Immediate(mask));
1057   }
1058
1059   template<typename Field>
1060   void DecodeFieldToSmi(Register reg) {
1061     if (SmiValuesAre32Bits()) {
1062       andp(reg, Immediate(Field::kMask));
1063       shlp(reg, Immediate(kSmiShift - Field::kShift));
1064     } else {
1065       static const int shift = Field::kShift;
1066       static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
1067       DCHECK(SmiValuesAre31Bits());
1068       DCHECK(kSmiShift == kSmiTagSize);
1069       DCHECK((mask & 0x80000000u) == 0);
1070       if (shift < kSmiShift) {
1071         shlp(reg, Immediate(kSmiShift - shift));
1072       } else if (shift > kSmiShift) {
1073         sarp(reg, Immediate(shift - kSmiShift));
1074       }
1075       andp(reg, Immediate(mask));
1076     }
1077   }
1078
1079   // Abort execution if argument is not a number, enabled via --debug-code.
1080   void AssertNumber(Register object);
1081
1082   // Abort execution if argument is a smi, enabled via --debug-code.
1083   void AssertNotSmi(Register object);
1084
1085   // Abort execution if argument is not a smi, enabled via --debug-code.
1086   void AssertSmi(Register object);
1087   void AssertSmi(const Operand& object);
1088
1089   // Abort execution if a 64 bit register containing a 32 bit payload does not
1090   // have zeros in the top 32 bits, enabled via --debug-code.
1091   void AssertZeroExtended(Register reg);
1092
1093   // Abort execution if argument is not a string, enabled via --debug-code.
1094   void AssertString(Register object);
1095
1096   // Abort execution if argument is not a name, enabled via --debug-code.
1097   void AssertName(Register object);
1098
1099   // Abort execution if argument is not undefined or an AllocationSite, enabled
1100   // via --debug-code.
1101   void AssertUndefinedOrAllocationSite(Register object);
1102
1103   // Abort execution if argument is not the root value with the given index,
1104   // enabled via --debug-code.
1105   void AssertRootValue(Register src,
1106                        Heap::RootListIndex root_value_index,
1107                        BailoutReason reason);
1108
1109   // ---------------------------------------------------------------------------
1110   // Exception handling
1111
1112   // Push a new stack handler and link it into stack handler chain.
1113   void PushStackHandler();
1114
1115   // Unlink the stack handler on top of the stack from the stack handler chain.
1116   void PopStackHandler();
1117
1118   // ---------------------------------------------------------------------------
1119   // Inline caching support
1120
1121   // Generate code for checking access rights - used for security checks
1122   // on access to global objects across environments. The holder register
1123   // is left untouched, but the scratch register and kScratchRegister,
1124   // which must be different, are clobbered.
1125   void CheckAccessGlobalProxy(Register holder_reg,
1126                               Register scratch,
1127                               Label* miss);
1128
1129   void GetNumberHash(Register r0, Register scratch);
1130
1131   void LoadFromNumberDictionary(Label* miss,
1132                                 Register elements,
1133                                 Register key,
1134                                 Register r0,
1135                                 Register r1,
1136                                 Register r2,
1137                                 Register result);
1138
1139
1140   // ---------------------------------------------------------------------------
1141   // Allocation support
1142
1143   // Allocate an object in new space or old pointer space. If the given space
1144   // is exhausted control continues at the gc_required label. The allocated
1145   // object is returned in result and end of the new object is returned in
1146   // result_end. The register scratch can be passed as no_reg in which case
1147   // an additional object reference will be added to the reloc info. The
1148   // returned pointers in result and result_end have not yet been tagged as
1149   // heap objects. If result_contains_top_on_entry is true the content of
1150   // result is known to be the allocation top on entry (could be result_end
1151   // from a previous call). If result_contains_top_on_entry is true scratch
1152   // should be no_reg as it is never used.
1153   void Allocate(int object_size,
1154                 Register result,
1155                 Register result_end,
1156                 Register scratch,
1157                 Label* gc_required,
1158                 AllocationFlags flags);
1159
1160   void Allocate(int header_size,
1161                 ScaleFactor element_size,
1162                 Register element_count,
1163                 Register result,
1164                 Register result_end,
1165                 Register scratch,
1166                 Label* gc_required,
1167                 AllocationFlags flags);
1168
1169   void Allocate(Register object_size,
1170                 Register result,
1171                 Register result_end,
1172                 Register scratch,
1173                 Label* gc_required,
1174                 AllocationFlags flags);
1175
1176   // Undo allocation in new space. The object passed and objects allocated after
1177   // it will no longer be allocated. Make sure that no pointers are left to the
1178   // object(s) no longer allocated as they would be invalid when allocation is
1179   // un-done.
1180   void UndoAllocationInNewSpace(Register object);
1181
1182   // Allocate a heap number in new space with undefined value. Returns
1183   // tagged pointer in result register, or jumps to gc_required if new
1184   // space is full.
1185   void AllocateHeapNumber(Register result,
1186                           Register scratch,
1187                           Label* gc_required,
1188                           MutableMode mode = IMMUTABLE);
1189
1190   // Allocate a sequential string. All the header fields of the string object
1191   // are initialized.
1192   void AllocateTwoByteString(Register result,
1193                              Register length,
1194                              Register scratch1,
1195                              Register scratch2,
1196                              Register scratch3,
1197                              Label* gc_required);
1198   void AllocateOneByteString(Register result, Register length,
1199                              Register scratch1, Register scratch2,
1200                              Register scratch3, Label* gc_required);
1201
1202   // Allocate a raw cons string object. Only the map field of the result is
1203   // initialized.
1204   void AllocateTwoByteConsString(Register result,
1205                           Register scratch1,
1206                           Register scratch2,
1207                           Label* gc_required);
1208   void AllocateOneByteConsString(Register result, Register scratch1,
1209                                  Register scratch2, Label* gc_required);
1210
1211   // Allocate a raw sliced string object. Only the map field of the result is
1212   // initialized.
1213   void AllocateTwoByteSlicedString(Register result,
1214                             Register scratch1,
1215                             Register scratch2,
1216                             Label* gc_required);
1217   void AllocateOneByteSlicedString(Register result, Register scratch1,
1218                                    Register scratch2, Label* gc_required);
1219
1220   // ---------------------------------------------------------------------------
1221   // Support functions.
1222
1223   // Check if result is zero and op is negative.
1224   void NegativeZeroTest(Register result, Register op, Label* then_label);
1225
1226   // Check if result is zero and op is negative in code using jump targets.
1227   void NegativeZeroTest(CodeGenerator* cgen,
1228                         Register result,
1229                         Register op,
1230                         JumpTarget* then_target);
1231
1232   // Check if result is zero and any of op1 and op2 are negative.
1233   // Register scratch is destroyed, and it must be different from op2.
1234   void NegativeZeroTest(Register result, Register op1, Register op2,
1235                         Register scratch, Label* then_label);
1236
1237   // Machine code version of Map::GetConstructor().
1238   // |temp| holds |result|'s map when done.
1239   void GetMapConstructor(Register result, Register map, Register temp);
1240
1241   // Try to get function prototype of a function and puts the value in
1242   // the result register. Checks that the function really is a
1243   // function and jumps to the miss label if the fast checks fail. The
1244   // function register will be untouched; the other register may be
1245   // clobbered.
1246   void TryGetFunctionPrototype(Register function,
1247                                Register result,
1248                                Label* miss,
1249                                bool miss_on_bound_function = false);
1250
1251   // Picks out an array index from the hash field.
1252   // Register use:
1253   //   hash - holds the index's hash. Clobbered.
1254   //   index - holds the overwritten index on exit.
1255   void IndexFromHash(Register hash, Register index);
1256
1257   // Find the function context up the context chain.
1258   void LoadContext(Register dst, int context_chain_length);
1259
1260   // Conditionally load the cached Array transitioned map of type
1261   // transitioned_kind from the native context if the map in register
1262   // map_in_out is the cached Array map in the native context of
1263   // expected_kind.
1264   void LoadTransitionedArrayMapConditional(
1265       ElementsKind expected_kind,
1266       ElementsKind transitioned_kind,
1267       Register map_in_out,
1268       Register scratch,
1269       Label* no_map_match);
1270
1271   // Load the global function with the given index.
1272   void LoadGlobalFunction(int index, Register function);
1273
1274   // Load the initial map from the global function. The registers
1275   // function and map can be the same.
1276   void LoadGlobalFunctionInitialMap(Register function, Register map);
1277
1278   // ---------------------------------------------------------------------------
1279   // Runtime calls
1280
1281   // Call a code stub.
1282   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
1283
1284   // Tail call a code stub (jump).
1285   void TailCallStub(CodeStub* stub);
1286
1287   // Return from a code stub after popping its arguments.
1288   void StubReturn(int argc);
1289
1290   // Call a runtime routine.
1291   void CallRuntime(const Runtime::Function* f,
1292                    int num_arguments,
1293                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
1294
1295   // Call a runtime function and save the value of XMM registers.
1296   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1297     const Runtime::Function* function = Runtime::FunctionForId(id);
1298     CallRuntime(function, function->nargs, kSaveFPRegs);
1299   }
1300
1301   // Convenience function: Same as above, but takes the fid instead.
1302   void CallRuntime(Runtime::FunctionId id,
1303                    int num_arguments,
1304                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
1305     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
1306   }
1307
1308   // Convenience function: call an external reference.
1309   void CallExternalReference(const ExternalReference& ext,
1310                              int num_arguments);
1311
1312   // Tail call of a runtime routine (jump).
1313   // Like JumpToExternalReference, but also takes care of passing the number
1314   // of parameters.
1315   void TailCallExternalReference(const ExternalReference& ext,
1316                                  int num_arguments,
1317                                  int result_size);
1318
1319   // Convenience function: tail call a runtime routine (jump).
1320   void TailCallRuntime(Runtime::FunctionId fid,
1321                        int num_arguments,
1322                        int result_size);
1323
1324   // Jump to a runtime routine.
1325   void JumpToExternalReference(const ExternalReference& ext, int result_size);
1326
1327   // Before calling a C-function from generated code, align arguments on stack.
1328   // After aligning the frame, arguments must be stored in rsp[0], rsp[8],
1329   // etc., not pushed. The argument count assumes all arguments are word sized.
1330   // The number of slots reserved for arguments depends on platform. On Windows
1331   // stack slots are reserved for the arguments passed in registers. On other
1332   // platforms stack slots are only reserved for the arguments actually passed
1333   // on the stack.
1334   void PrepareCallCFunction(int num_arguments);
1335
1336   // Calls a C function and cleans up the space for arguments allocated
1337   // by PrepareCallCFunction. The called function is not allowed to trigger a
1338   // garbage collection, since that might move the code and invalidate the
1339   // return address (unless this is somehow accounted for by the called
1340   // function).
1341   void CallCFunction(ExternalReference function, int num_arguments);
1342   void CallCFunction(Register function, int num_arguments);
1343
1344   // Calculate the number of stack slots to reserve for arguments when calling a
1345   // C function.
1346   int ArgumentStackSlotsForCFunctionCall(int num_arguments);
1347
1348   // ---------------------------------------------------------------------------
1349   // Utilities
1350
1351   void Ret();
1352
1353   // Return and drop arguments from stack, where the number of arguments
1354   // may be bigger than 2^16 - 1.  Requires a scratch register.
1355   void Ret(int bytes_dropped, Register scratch);
1356
1357   Handle<Object> CodeObject() {
1358     DCHECK(!code_object_.is_null());
1359     return code_object_;
1360   }
1361
1362   // Copy length bytes from source to destination.
1363   // Uses scratch register internally (if you have a low-eight register
1364   // free, do use it, otherwise kScratchRegister will be used).
1365   // The min_length is a minimum limit on the value that length will have.
1366   // The algorithm has some special cases that might be omitted if the string
1367   // is known to always be long.
1368   void CopyBytes(Register destination,
1369                  Register source,
1370                  Register length,
1371                  int min_length = 0,
1372                  Register scratch = kScratchRegister);
1373
1374   // Initialize fields with filler values.  Fields starting at |start_offset|
1375   // not including end_offset are overwritten with the value in |filler|.  At
1376   // the end the loop, |start_offset| takes the value of |end_offset|.
1377   void InitializeFieldsWithFiller(Register start_offset,
1378                                   Register end_offset,
1379                                   Register filler);
1380
1381
1382   // Emit code for a truncating division by a constant. The dividend register is
1383   // unchanged, the result is in rdx, and rax gets clobbered.
1384   void TruncatingDiv(Register dividend, int32_t divisor);
1385
1386   // ---------------------------------------------------------------------------
1387   // StatsCounter support
1388
1389   void SetCounter(StatsCounter* counter, int value);
1390   void IncrementCounter(StatsCounter* counter, int value);
1391   void DecrementCounter(StatsCounter* counter, int value);
1392
1393
1394   // ---------------------------------------------------------------------------
1395   // Debugging
1396
1397   // Calls Abort(msg) if the condition cc is not satisfied.
1398   // Use --debug_code to enable.
1399   void Assert(Condition cc, BailoutReason reason);
1400
1401   void AssertFastElements(Register elements);
1402
1403   // Like Assert(), but always enabled.
1404   void Check(Condition cc, BailoutReason reason);
1405
1406   // Print a message to stdout and abort execution.
1407   void Abort(BailoutReason msg);
1408
1409   // Check that the stack is aligned.
1410   void CheckStackAlignment();
1411
1412   // Verify restrictions about code generated in stubs.
1413   void set_generating_stub(bool value) { generating_stub_ = value; }
1414   bool generating_stub() { return generating_stub_; }
1415   void set_has_frame(bool value) { has_frame_ = value; }
1416   bool has_frame() { return has_frame_; }
1417   inline bool AllowThisStubCall(CodeStub* stub);
1418
1419   static int SafepointRegisterStackIndex(Register reg) {
1420     return SafepointRegisterStackIndex(reg.code());
1421   }
1422
1423   // Activation support.
1424   void EnterFrame(StackFrame::Type type);
1425   void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg);
1426   void LeaveFrame(StackFrame::Type type);
1427
1428   // Expects object in rax and returns map with validated enum cache
1429   // in rax.  Assumes that any other register can be used as a scratch.
1430   void CheckEnumCache(Register null_value,
1431                       Label* call_runtime);
1432
1433   // AllocationMemento support. Arrays may have an associated
1434   // AllocationMemento object that can be checked for in order to pretransition
1435   // to another type.
1436   // On entry, receiver_reg should point to the array object.
1437   // scratch_reg gets clobbered.
1438   // If allocation info is present, condition flags are set to equal.
1439   void TestJSArrayForAllocationMemento(Register receiver_reg,
1440                                        Register scratch_reg,
1441                                        Label* no_memento_found);
1442
1443   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
1444                                          Register scratch_reg,
1445                                          Label* memento_found) {
1446     Label no_memento_found;
1447     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
1448                                     &no_memento_found);
1449     j(equal, memento_found);
1450     bind(&no_memento_found);
1451   }
1452
1453   // Jumps to found label if a prototype map has dictionary elements.
1454   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
1455                                         Register scratch1, Label* found);
1456
1457  private:
1458   // Order general registers are pushed by Pushad.
1459   // rax, rcx, rdx, rbx, rsi, rdi, r8, r9, r11, r12, r14, r15.
1460   static const int kSafepointPushRegisterIndices[Register::kNumRegisters];
1461   static const int kNumSafepointSavedRegisters = 12;
1462   static const int kSmiShift = kSmiTagSize + kSmiShiftSize;
1463
1464   bool generating_stub_;
1465   bool has_frame_;
1466   bool root_array_available_;
1467
1468   // Returns a register holding the smi value. The register MUST NOT be
1469   // modified. It may be the "smi 1 constant" register.
1470   Register GetSmiConstant(Smi* value);
1471
1472   int64_t RootRegisterDelta(ExternalReference other);
1473
1474   // Moves the smi value to the destination register.
1475   void LoadSmiConstant(Register dst, Smi* value);
1476
1477   // This handle will be patched with the code object on installation.
1478   Handle<Object> code_object_;
1479
1480   // Helper functions for generating invokes.
1481   void InvokePrologue(const ParameterCount& expected,
1482                       const ParameterCount& actual,
1483                       Handle<Code> code_constant,
1484                       Register code_register,
1485                       Label* done,
1486                       bool* definitely_mismatches,
1487                       InvokeFlag flag,
1488                       Label::Distance near_jump = Label::kFar,
1489                       const CallWrapper& call_wrapper = NullCallWrapper());
1490
1491   void EnterExitFramePrologue(bool save_rax);
1492
1493   // Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
1494   // accessible via StackSpaceOperand.
1495   void EnterExitFrameEpilogue(int arg_stack_space, bool save_doubles);
1496
1497   void LeaveExitFrameEpilogue(bool restore_context);
1498
1499   // Allocation support helpers.
1500   // Loads the top of new-space into the result register.
1501   // Otherwise the address of the new-space top is loaded into scratch (if
1502   // scratch is valid), and the new-space top is loaded into result.
1503   void LoadAllocationTopHelper(Register result,
1504                                Register scratch,
1505                                AllocationFlags flags);
1506
1507   void MakeSureDoubleAlignedHelper(Register result,
1508                                    Register scratch,
1509                                    Label* gc_required,
1510                                    AllocationFlags flags);
1511
1512   // Update allocation top with value in result_end register.
1513   // If scratch is valid, it contains the address of the allocation top.
1514   void UpdateAllocationTopHelper(Register result_end,
1515                                  Register scratch,
1516                                  AllocationFlags flags);
1517
1518   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1519   void InNewSpace(Register object,
1520                   Register scratch,
1521                   Condition cc,
1522                   Label* branch,
1523                   Label::Distance distance = Label::kFar);
1524
1525   // Helper for finding the mark bits for an address.  Afterwards, the
1526   // bitmap register points at the word with the mark bits and the mask
1527   // the position of the first bit.  Uses rcx as scratch and leaves addr_reg
1528   // unchanged.
1529   inline void GetMarkBits(Register addr_reg,
1530                           Register bitmap_reg,
1531                           Register mask_reg);
1532
1533   // Compute memory operands for safepoint stack slots.
1534   Operand SafepointRegisterSlot(Register reg);
1535   static int SafepointRegisterStackIndex(int reg_code) {
1536     return kNumSafepointRegisters - kSafepointPushRegisterIndices[reg_code] - 1;
1537   }
1538
1539   // Needs access to SafepointRegisterStackIndex for compiled frame
1540   // traversal.
1541   friend class StandardFrame;
1542 };
1543
1544
1545 // The code patcher is used to patch (typically) small parts of code e.g. for
1546 // debugging and other types of instrumentation. When using the code patcher
1547 // the exact number of bytes specified must be emitted. Is not legal to emit
1548 // relocation information. If any of these constraints are violated it causes
1549 // an assertion.
1550 class CodePatcher {
1551  public:
1552   CodePatcher(byte* address, int size);
1553   virtual ~CodePatcher();
1554
1555   // Macro assembler to emit code.
1556   MacroAssembler* masm() { return &masm_; }
1557
1558  private:
1559   byte* address_;  // The address of the code being patched.
1560   int size_;  // Number of bytes of the expected patch size.
1561   MacroAssembler masm_;  // Macro assembler used to generate the code.
1562 };
1563
1564
1565 // -----------------------------------------------------------------------------
1566 // Static helper functions.
1567
1568 // Generate an Operand for loading a field from an object.
1569 inline Operand FieldOperand(Register object, int offset) {
1570   return Operand(object, offset - kHeapObjectTag);
1571 }
1572
1573
1574 // Generate an Operand for loading an indexed field from an object.
1575 inline Operand FieldOperand(Register object,
1576                             Register index,
1577                             ScaleFactor scale,
1578                             int offset) {
1579   return Operand(object, index, scale, offset - kHeapObjectTag);
1580 }
1581
1582
1583 inline Operand ContextOperand(Register context, int index) {
1584   return Operand(context, Context::SlotOffset(index));
1585 }
1586
1587
1588 inline Operand GlobalObjectOperand() {
1589   return ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX);
1590 }
1591
1592
1593 // Provides access to exit frame stack space (not GCed).
1594 inline Operand StackSpaceOperand(int index) {
1595 #ifdef _WIN64
1596   const int kShaddowSpace = 4;
1597   return Operand(rsp, (index + kShaddowSpace) * kPointerSize);
1598 #else
1599   return Operand(rsp, index * kPointerSize);
1600 #endif
1601 }
1602
1603
1604 inline Operand StackOperandForReturnAddress(int32_t disp) {
1605   return Operand(rsp, disp);
1606 }
1607
1608
1609 #ifdef GENERATED_CODE_COVERAGE
1610 extern void LogGeneratedCodeCoverage(const char* file_line);
1611 #define CODE_COVERAGE_STRINGIFY(x) #x
1612 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1613 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1614 #define ACCESS_MASM(masm) {                                                  \
1615     Address x64_coverage_function = FUNCTION_ADDR(LogGeneratedCodeCoverage); \
1616     masm->pushfq();                                                          \
1617     masm->Pushad();                                                          \
1618     masm->Push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));            \
1619     masm->Call(x64_coverage_function, RelocInfo::EXTERNAL_REFERENCE);        \
1620     masm->Pop(rax);                                                          \
1621     masm->Popad();                                                           \
1622     masm->popfq();                                                           \
1623   }                                                                          \
1624   masm->
1625 #else
1626 #define ACCESS_MASM(masm) masm->
1627 #endif
1628
1629 } }  // namespace v8::internal
1630
1631 #endif  // V8_X64_MACRO_ASSEMBLER_X64_H_