target_x86.cc revision 58994cdb00b323339bd83828eddc53976048006f
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <string>
18#include <inttypes.h>
19
20#include "codegen_x86.h"
21#include "dex/compiler_internals.h"
22#include "dex/quick/mir_to_lir-inl.h"
23#include "mirror/array.h"
24#include "mirror/string.h"
25#include "x86_lir.h"
26
27namespace art {
28
29static constexpr RegStorage core_regs_arr_32[] = {
30    rs_rAX, rs_rCX, rs_rDX, rs_rBX, rs_rX86_SP_32, rs_rBP, rs_rSI, rs_rDI,
31};
32static constexpr RegStorage core_regs_arr_64[] = {
33    rs_rAX, rs_rCX, rs_rDX, rs_rBX, rs_rX86_SP_32, rs_rBP, rs_rSI, rs_rDI,
34#ifdef TARGET_REX_SUPPORT
35    rs_r8, rs_r9, rs_r10, rs_r11, rs_r12, rs_r13, rs_r14, rs_r15
36#endif
37};
38static constexpr RegStorage core_regs_arr_64q[] = {
39    rs_r0q, rs_r1q, rs_r2q, rs_r3q, rs_rX86_SP_64, rs_r5q, rs_r6q, rs_r7q,
40#ifdef TARGET_REX_SUPPORT
41    rs_r8q, rs_r9q, rs_r10q, rs_r11q, rs_r12q, rs_r13q, rs_r14q, rs_r15q
42#endif
43};
44static constexpr RegStorage sp_regs_arr_32[] = {
45    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
46};
47static constexpr RegStorage sp_regs_arr_64[] = {
48    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
49#ifdef TARGET_REX_SUPPORT
50    rs_fr8, rs_fr9, rs_fr10, rs_fr11, rs_fr12, rs_fr13, rs_fr14, rs_fr15
51#endif
52};
53static constexpr RegStorage dp_regs_arr_32[] = {
54    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
55};
56static constexpr RegStorage dp_regs_arr_64[] = {
57    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
58#ifdef TARGET_REX_SUPPORT
59    rs_dr8, rs_dr9, rs_dr10, rs_dr11, rs_dr12, rs_dr13, rs_dr14, rs_dr15
60#endif
61};
62static constexpr RegStorage reserved_regs_arr_32[] = {rs_rX86_SP_32};
63static constexpr RegStorage reserved_regs_arr_64[] = {rs_rX86_SP_32};
64static constexpr RegStorage reserved_regs_arr_64q[] = {rs_rX86_SP_64};
65static constexpr RegStorage core_temps_arr_32[] = {rs_rAX, rs_rCX, rs_rDX, rs_rBX};
66static constexpr RegStorage core_temps_arr_64[] = {
67    rs_rAX, rs_rCX, rs_rDX, rs_rSI, rs_rDI,
68#ifdef TARGET_REX_SUPPORT
69    rs_r8, rs_r9, rs_r10, rs_r11
70#endif
71};
72static constexpr RegStorage core_temps_arr_64q[] = {
73    rs_r0q, rs_r1q, rs_r2q, rs_r6q, rs_r7q,
74#ifdef TARGET_REX_SUPPORT
75    rs_r8q, rs_r9q, rs_r10q, rs_r11q
76#endif
77};
78static constexpr RegStorage sp_temps_arr_32[] = {
79    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
80};
81static constexpr RegStorage sp_temps_arr_64[] = {
82    rs_fr0, rs_fr1, rs_fr2, rs_fr3, rs_fr4, rs_fr5, rs_fr6, rs_fr7,
83#ifdef TARGET_REX_SUPPORT
84    rs_fr8, rs_fr9, rs_fr10, rs_fr11, rs_fr12, rs_fr13, rs_fr14, rs_fr15
85#endif
86};
87static constexpr RegStorage dp_temps_arr_32[] = {
88    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
89};
90static constexpr RegStorage dp_temps_arr_64[] = {
91    rs_dr0, rs_dr1, rs_dr2, rs_dr3, rs_dr4, rs_dr5, rs_dr6, rs_dr7,
92#ifdef TARGET_REX_SUPPORT
93    rs_dr8, rs_dr9, rs_dr10, rs_dr11, rs_dr12, rs_dr13, rs_dr14, rs_dr15
94#endif
95};
96
97static constexpr RegStorage xp_temps_arr_32[] = {
98    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
99};
100static constexpr RegStorage xp_temps_arr_64[] = {
101    rs_xr0, rs_xr1, rs_xr2, rs_xr3, rs_xr4, rs_xr5, rs_xr6, rs_xr7,
102#ifdef TARGET_REX_SUPPORT
103    rs_xr8, rs_xr9, rs_xr10, rs_xr11, rs_xr12, rs_xr13, rs_xr14, rs_xr15
104#endif
105};
106
107static constexpr ArrayRef<const RegStorage> empty_pool;
108static constexpr ArrayRef<const RegStorage> core_regs_32(core_regs_arr_32);
109static constexpr ArrayRef<const RegStorage> core_regs_64(core_regs_arr_64);
110static constexpr ArrayRef<const RegStorage> core_regs_64q(core_regs_arr_64q);
111static constexpr ArrayRef<const RegStorage> sp_regs_32(sp_regs_arr_32);
112static constexpr ArrayRef<const RegStorage> sp_regs_64(sp_regs_arr_64);
113static constexpr ArrayRef<const RegStorage> dp_regs_32(dp_regs_arr_32);
114static constexpr ArrayRef<const RegStorage> dp_regs_64(dp_regs_arr_64);
115static constexpr ArrayRef<const RegStorage> reserved_regs_32(reserved_regs_arr_32);
116static constexpr ArrayRef<const RegStorage> reserved_regs_64(reserved_regs_arr_64);
117static constexpr ArrayRef<const RegStorage> reserved_regs_64q(reserved_regs_arr_64q);
118static constexpr ArrayRef<const RegStorage> core_temps_32(core_temps_arr_32);
119static constexpr ArrayRef<const RegStorage> core_temps_64(core_temps_arr_64);
120static constexpr ArrayRef<const RegStorage> core_temps_64q(core_temps_arr_64q);
121static constexpr ArrayRef<const RegStorage> sp_temps_32(sp_temps_arr_32);
122static constexpr ArrayRef<const RegStorage> sp_temps_64(sp_temps_arr_64);
123static constexpr ArrayRef<const RegStorage> dp_temps_32(dp_temps_arr_32);
124static constexpr ArrayRef<const RegStorage> dp_temps_64(dp_temps_arr_64);
125
126static constexpr ArrayRef<const RegStorage> xp_temps_32(xp_temps_arr_32);
127static constexpr ArrayRef<const RegStorage> xp_temps_64(xp_temps_arr_64);
128
129RegStorage rs_rX86_SP;
130
131X86NativeRegisterPool rX86_ARG0;
132X86NativeRegisterPool rX86_ARG1;
133X86NativeRegisterPool rX86_ARG2;
134X86NativeRegisterPool rX86_ARG3;
135#ifdef TARGET_REX_SUPPORT
136X86NativeRegisterPool rX86_ARG4;
137X86NativeRegisterPool rX86_ARG5;
138#endif
139X86NativeRegisterPool rX86_FARG0;
140X86NativeRegisterPool rX86_FARG1;
141X86NativeRegisterPool rX86_FARG2;
142X86NativeRegisterPool rX86_FARG3;
143X86NativeRegisterPool rX86_FARG4;
144X86NativeRegisterPool rX86_FARG5;
145X86NativeRegisterPool rX86_FARG6;
146X86NativeRegisterPool rX86_FARG7;
147X86NativeRegisterPool rX86_RET0;
148X86NativeRegisterPool rX86_RET1;
149X86NativeRegisterPool rX86_INVOKE_TGT;
150X86NativeRegisterPool rX86_COUNT;
151
152RegStorage rs_rX86_ARG0;
153RegStorage rs_rX86_ARG1;
154RegStorage rs_rX86_ARG2;
155RegStorage rs_rX86_ARG3;
156RegStorage rs_rX86_ARG4;
157RegStorage rs_rX86_ARG5;
158RegStorage rs_rX86_FARG0;
159RegStorage rs_rX86_FARG1;
160RegStorage rs_rX86_FARG2;
161RegStorage rs_rX86_FARG3;
162RegStorage rs_rX86_FARG4;
163RegStorage rs_rX86_FARG5;
164RegStorage rs_rX86_FARG6;
165RegStorage rs_rX86_FARG7;
166RegStorage rs_rX86_RET0;
167RegStorage rs_rX86_RET1;
168RegStorage rs_rX86_INVOKE_TGT;
169RegStorage rs_rX86_COUNT;
170
171RegLocation X86Mir2Lir::LocCReturn() {
172  return x86_loc_c_return;
173}
174
175RegLocation X86Mir2Lir::LocCReturnRef() {
176  // FIXME: return x86_loc_c_return_wide for x86_64 when wide refs supported.
177  return x86_loc_c_return;
178}
179
180RegLocation X86Mir2Lir::LocCReturnWide() {
181  return x86_loc_c_return_wide;
182}
183
184RegLocation X86Mir2Lir::LocCReturnFloat() {
185  return x86_loc_c_return_float;
186}
187
188RegLocation X86Mir2Lir::LocCReturnDouble() {
189  return x86_loc_c_return_double;
190}
191
192// Return a target-dependent special register.
193RegStorage X86Mir2Lir::TargetReg(SpecialTargetRegister reg) {
194  RegStorage res_reg = RegStorage::InvalidReg();
195  switch (reg) {
196    case kSelf: res_reg = RegStorage::InvalidReg(); break;
197    case kSuspend: res_reg =  RegStorage::InvalidReg(); break;
198    case kLr: res_reg =  RegStorage::InvalidReg(); break;
199    case kPc: res_reg =  RegStorage::InvalidReg(); break;
200    case kSp: res_reg =  rs_rX86_SP; break;
201    case kArg0: res_reg = rs_rX86_ARG0; break;
202    case kArg1: res_reg = rs_rX86_ARG1; break;
203    case kArg2: res_reg = rs_rX86_ARG2; break;
204    case kArg3: res_reg = rs_rX86_ARG3; break;
205    case kArg4: res_reg = rs_rX86_ARG4; break;
206    case kArg5: res_reg = rs_rX86_ARG5; break;
207    case kFArg0: res_reg = rs_rX86_FARG0; break;
208    case kFArg1: res_reg = rs_rX86_FARG1; break;
209    case kFArg2: res_reg = rs_rX86_FARG2; break;
210    case kFArg3: res_reg = rs_rX86_FARG3; break;
211    case kFArg4: res_reg = rs_rX86_FARG4; break;
212    case kFArg5: res_reg = rs_rX86_FARG5; break;
213    case kFArg6: res_reg = rs_rX86_FARG6; break;
214    case kFArg7: res_reg = rs_rX86_FARG7; break;
215    case kRet0: res_reg = rs_rX86_RET0; break;
216    case kRet1: res_reg = rs_rX86_RET1; break;
217    case kInvokeTgt: res_reg = rs_rX86_INVOKE_TGT; break;
218    case kHiddenArg: res_reg = rs_rAX; break;
219    case kHiddenFpArg: res_reg = rs_fr0; break;
220    case kCount: res_reg = rs_rX86_COUNT; break;
221    default: res_reg = RegStorage::InvalidReg();
222  }
223  return res_reg;
224}
225
226/*
227 * Decode the register id.
228 */
229uint64_t X86Mir2Lir::GetRegMaskCommon(RegStorage reg) {
230  uint64_t seed;
231  int shift;
232  int reg_id;
233
234  reg_id = reg.GetRegNum();
235  /* Double registers in x86 are just a single FP register */
236  seed = 1;
237  /* FP register starts at bit position 16 */
238  shift = (reg.IsFloat() || reg.StorageSize() > 8) ? kX86FPReg0 : 0;
239  /* Expand the double register id into single offset */
240  shift += reg_id;
241  return (seed << shift);
242}
243
244uint64_t X86Mir2Lir::GetPCUseDefEncoding() {
245  /*
246   * FIXME: might make sense to use a virtual resource encoding bit for pc.  Might be
247   * able to clean up some of the x86/Arm_Mips differences
248   */
249  LOG(FATAL) << "Unexpected call to GetPCUseDefEncoding for x86";
250  return 0ULL;
251}
252
253void X86Mir2Lir::SetupTargetResourceMasks(LIR* lir, uint64_t flags) {
254  DCHECK(cu_->instruction_set == kX86 || cu_->instruction_set == kX86_64);
255  DCHECK(!lir->flags.use_def_invalid);
256
257  // X86-specific resource map setup here.
258  if (flags & REG_USE_SP) {
259    lir->u.m.use_mask |= ENCODE_X86_REG_SP;
260  }
261
262  if (flags & REG_DEF_SP) {
263    lir->u.m.def_mask |= ENCODE_X86_REG_SP;
264  }
265
266  if (flags & REG_DEFA) {
267    SetupRegMask(&lir->u.m.def_mask, rs_rAX.GetReg());
268  }
269
270  if (flags & REG_DEFD) {
271    SetupRegMask(&lir->u.m.def_mask, rs_rDX.GetReg());
272  }
273  if (flags & REG_USEA) {
274    SetupRegMask(&lir->u.m.use_mask, rs_rAX.GetReg());
275  }
276
277  if (flags & REG_USEC) {
278    SetupRegMask(&lir->u.m.use_mask, rs_rCX.GetReg());
279  }
280
281  if (flags & REG_USED) {
282    SetupRegMask(&lir->u.m.use_mask, rs_rDX.GetReg());
283  }
284
285  if (flags & REG_USEB) {
286    SetupRegMask(&lir->u.m.use_mask, rs_rBX.GetReg());
287  }
288
289  // Fixup hard to describe instruction: Uses rAX, rCX, rDI; sets rDI.
290  if (lir->opcode == kX86RepneScasw) {
291    SetupRegMask(&lir->u.m.use_mask, rs_rAX.GetReg());
292    SetupRegMask(&lir->u.m.use_mask, rs_rCX.GetReg());
293    SetupRegMask(&lir->u.m.use_mask, rs_rDI.GetReg());
294    SetupRegMask(&lir->u.m.def_mask, rs_rDI.GetReg());
295  }
296
297  if (flags & USE_FP_STACK) {
298    lir->u.m.use_mask |= ENCODE_X86_FP_STACK;
299    lir->u.m.def_mask |= ENCODE_X86_FP_STACK;
300  }
301}
302
303/* For dumping instructions */
304static const char* x86RegName[] = {
305  "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
306  "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
307};
308
309static const char* x86CondName[] = {
310  "O",
311  "NO",
312  "B/NAE/C",
313  "NB/AE/NC",
314  "Z/EQ",
315  "NZ/NE",
316  "BE/NA",
317  "NBE/A",
318  "S",
319  "NS",
320  "P/PE",
321  "NP/PO",
322  "L/NGE",
323  "NL/GE",
324  "LE/NG",
325  "NLE/G"
326};
327
328/*
329 * Interpret a format string and build a string no longer than size
330 * See format key in Assemble.cc.
331 */
332std::string X86Mir2Lir::BuildInsnString(const char *fmt, LIR *lir, unsigned char* base_addr) {
333  std::string buf;
334  size_t i = 0;
335  size_t fmt_len = strlen(fmt);
336  while (i < fmt_len) {
337    if (fmt[i] != '!') {
338      buf += fmt[i];
339      i++;
340    } else {
341      i++;
342      DCHECK_LT(i, fmt_len);
343      char operand_number_ch = fmt[i];
344      i++;
345      if (operand_number_ch == '!') {
346        buf += "!";
347      } else {
348        int operand_number = operand_number_ch - '0';
349        DCHECK_LT(operand_number, 6);  // Expect upto 6 LIR operands.
350        DCHECK_LT(i, fmt_len);
351        int operand = lir->operands[operand_number];
352        switch (fmt[i]) {
353          case 'c':
354            DCHECK_LT(static_cast<size_t>(operand), sizeof(x86CondName));
355            buf += x86CondName[operand];
356            break;
357          case 'd':
358            buf += StringPrintf("%d", operand);
359            break;
360          case 'p': {
361            EmbeddedData *tab_rec = reinterpret_cast<EmbeddedData*>(UnwrapPointer(operand));
362            buf += StringPrintf("0x%08x", tab_rec->offset);
363            break;
364          }
365          case 'r':
366            if (RegStorage::IsFloat(operand)) {
367              int fp_reg = RegStorage::RegNum(operand);
368              buf += StringPrintf("xmm%d", fp_reg);
369            } else {
370              int reg_num = RegStorage::RegNum(operand);
371              DCHECK_LT(static_cast<size_t>(reg_num), sizeof(x86RegName));
372              buf += x86RegName[reg_num];
373            }
374            break;
375          case 't':
376            buf += StringPrintf("0x%08" PRIxPTR " (L%p)",
377                                reinterpret_cast<uintptr_t>(base_addr) + lir->offset + operand,
378                                lir->target);
379            break;
380          default:
381            buf += StringPrintf("DecodeError '%c'", fmt[i]);
382            break;
383        }
384        i++;
385      }
386    }
387  }
388  return buf;
389}
390
391void X86Mir2Lir::DumpResourceMask(LIR *x86LIR, uint64_t mask, const char *prefix) {
392  char buf[256];
393  buf[0] = 0;
394
395  if (mask == ENCODE_ALL) {
396    strcpy(buf, "all");
397  } else {
398    char num[8];
399    int i;
400
401    for (i = 0; i < kX86RegEnd; i++) {
402      if (mask & (1ULL << i)) {
403        snprintf(num, arraysize(num), "%d ", i);
404        strcat(buf, num);
405      }
406    }
407
408    if (mask & ENCODE_CCODE) {
409      strcat(buf, "cc ");
410    }
411    /* Memory bits */
412    if (x86LIR && (mask & ENCODE_DALVIK_REG)) {
413      snprintf(buf + strlen(buf), arraysize(buf) - strlen(buf), "dr%d%s",
414               DECODE_ALIAS_INFO_REG(x86LIR->flags.alias_info),
415               (DECODE_ALIAS_INFO_WIDE(x86LIR->flags.alias_info)) ? "(+1)" : "");
416    }
417    if (mask & ENCODE_LITERAL) {
418      strcat(buf, "lit ");
419    }
420
421    if (mask & ENCODE_HEAP_REF) {
422      strcat(buf, "heap ");
423    }
424    if (mask & ENCODE_MUST_NOT_ALIAS) {
425      strcat(buf, "noalias ");
426    }
427  }
428  if (buf[0]) {
429    LOG(INFO) << prefix << ": " <<  buf;
430  }
431}
432
433void X86Mir2Lir::AdjustSpillMask() {
434  // Adjustment for LR spilling, x86 has no LR so nothing to do here
435  core_spill_mask_ |= (1 << rs_rRET.GetRegNum());
436  num_core_spills_++;
437}
438
439/*
440 * Mark a callee-save fp register as promoted.  Note that
441 * vpush/vpop uses contiguous register lists so we must
442 * include any holes in the mask.  Associate holes with
443 * Dalvik register INVALID_VREG (0xFFFFU).
444 */
445void X86Mir2Lir::MarkPreservedSingle(int v_reg, RegStorage reg) {
446  UNIMPLEMENTED(FATAL) << "MarkPreservedSingle";
447}
448
449void X86Mir2Lir::MarkPreservedDouble(int v_reg, RegStorage reg) {
450  UNIMPLEMENTED(FATAL) << "MarkPreservedDouble";
451}
452
453RegStorage X86Mir2Lir::AllocateByteRegister() {
454  return AllocTypedTemp(false, kCoreReg);
455}
456
457/* Clobber all regs that might be used by an external C call */
458void X86Mir2Lir::ClobberCallerSave() {
459  Clobber(rs_rAX);
460  Clobber(rs_rCX);
461  Clobber(rs_rDX);
462  Clobber(rs_rBX);
463}
464
465RegLocation X86Mir2Lir::GetReturnWideAlt() {
466  RegLocation res = LocCReturnWide();
467  DCHECK(res.reg.GetLowReg() == rs_rAX.GetReg());
468  DCHECK(res.reg.GetHighReg() == rs_rDX.GetReg());
469  Clobber(rs_rAX);
470  Clobber(rs_rDX);
471  MarkInUse(rs_rAX);
472  MarkInUse(rs_rDX);
473  MarkWide(res.reg);
474  return res;
475}
476
477RegLocation X86Mir2Lir::GetReturnAlt() {
478  RegLocation res = LocCReturn();
479  res.reg.SetReg(rs_rDX.GetReg());
480  Clobber(rs_rDX);
481  MarkInUse(rs_rDX);
482  return res;
483}
484
485/* To be used when explicitly managing register use */
486void X86Mir2Lir::LockCallTemps() {
487  LockTemp(rs_rX86_ARG0);
488  LockTemp(rs_rX86_ARG1);
489  LockTemp(rs_rX86_ARG2);
490  LockTemp(rs_rX86_ARG3);
491#ifdef TARGET_REX_SUPPORT
492  if (Gen64Bit()) {
493    LockTemp(rs_rX86_ARG4);
494    LockTemp(rs_rX86_ARG5);
495    LockTemp(rs_rX86_FARG0);
496    LockTemp(rs_rX86_FARG1);
497    LockTemp(rs_rX86_FARG2);
498    LockTemp(rs_rX86_FARG3);
499    LockTemp(rs_rX86_FARG4);
500    LockTemp(rs_rX86_FARG5);
501    LockTemp(rs_rX86_FARG6);
502    LockTemp(rs_rX86_FARG7);
503  }
504#endif
505}
506
507/* To be used when explicitly managing register use */
508void X86Mir2Lir::FreeCallTemps() {
509  FreeTemp(rs_rX86_ARG0);
510  FreeTemp(rs_rX86_ARG1);
511  FreeTemp(rs_rX86_ARG2);
512  FreeTemp(rs_rX86_ARG3);
513#ifdef TARGET_REX_SUPPORT
514  if (Gen64Bit()) {
515    FreeTemp(rs_rX86_ARG4);
516    FreeTemp(rs_rX86_ARG5);
517    FreeTemp(rs_rX86_FARG0);
518    FreeTemp(rs_rX86_FARG1);
519    FreeTemp(rs_rX86_FARG2);
520    FreeTemp(rs_rX86_FARG3);
521    FreeTemp(rs_rX86_FARG4);
522    FreeTemp(rs_rX86_FARG5);
523    FreeTemp(rs_rX86_FARG6);
524    FreeTemp(rs_rX86_FARG7);
525  }
526#endif
527}
528
529bool X86Mir2Lir::ProvidesFullMemoryBarrier(X86OpCode opcode) {
530    switch (opcode) {
531      case kX86LockCmpxchgMR:
532      case kX86LockCmpxchgAR:
533      case kX86LockCmpxchg8bM:
534      case kX86LockCmpxchg8bA:
535      case kX86XchgMR:
536      case kX86Mfence:
537        // Atomic memory instructions provide full barrier.
538        return true;
539      default:
540        break;
541    }
542
543    // Conservative if cannot prove it provides full barrier.
544    return false;
545}
546
547bool X86Mir2Lir::GenMemBarrier(MemBarrierKind barrier_kind) {
548#if ANDROID_SMP != 0
549  // Start off with using the last LIR as the barrier. If it is not enough, then we will update it.
550  LIR* mem_barrier = last_lir_insn_;
551
552  bool ret = false;
553  /*
554   * According to the JSR-133 Cookbook, for x86 only StoreLoad barriers need memory fence. All other barriers
555   * (LoadLoad, LoadStore, StoreStore) are nops due to the x86 memory model. For those cases, all we need
556   * to ensure is that there is a scheduling barrier in place.
557   */
558  if (barrier_kind == kStoreLoad) {
559    // If no LIR exists already that can be used a barrier, then generate an mfence.
560    if (mem_barrier == nullptr) {
561      mem_barrier = NewLIR0(kX86Mfence);
562      ret = true;
563    }
564
565    // If last instruction does not provide full barrier, then insert an mfence.
566    if (ProvidesFullMemoryBarrier(static_cast<X86OpCode>(mem_barrier->opcode)) == false) {
567      mem_barrier = NewLIR0(kX86Mfence);
568      ret = true;
569    }
570  }
571
572  // Now ensure that a scheduling barrier is in place.
573  if (mem_barrier == nullptr) {
574    GenBarrier();
575  } else {
576    // Mark as a scheduling barrier.
577    DCHECK(!mem_barrier->flags.use_def_invalid);
578    mem_barrier->u.m.def_mask = ENCODE_ALL;
579  }
580  return ret;
581#else
582  return false;
583#endif
584}
585
586void X86Mir2Lir::CompilerInitializeRegAlloc() {
587  if (Gen64Bit()) {
588    reg_pool_ = new (arena_) RegisterPool(this, arena_, core_regs_64, core_regs_64q, sp_regs_64,
589                                          dp_regs_64, reserved_regs_64, reserved_regs_64q,
590                                          core_temps_64, core_temps_64q, sp_temps_64, dp_temps_64);
591  } else {
592    reg_pool_ = new (arena_) RegisterPool(this, arena_, core_regs_32, empty_pool, sp_regs_32,
593                                          dp_regs_32, reserved_regs_32, empty_pool,
594                                          core_temps_32, empty_pool, sp_temps_32, dp_temps_32);
595  }
596
597  // Target-specific adjustments.
598
599  // Add in XMM registers.
600  const ArrayRef<const RegStorage> *xp_temps = Gen64Bit() ? &xp_temps_64 : &xp_temps_32;
601  for (RegStorage reg : *xp_temps) {
602    RegisterInfo* info = new (arena_) RegisterInfo(reg, GetRegMaskCommon(reg));
603    reginfo_map_.Put(reg.GetReg(), info);
604    info->SetIsTemp(true);
605  }
606
607  // Alias single precision xmm to double xmms.
608  // TODO: as needed, add larger vector sizes - alias all to the largest.
609  GrowableArray<RegisterInfo*>::Iterator it(&reg_pool_->sp_regs_);
610  for (RegisterInfo* info = it.Next(); info != nullptr; info = it.Next()) {
611    int sp_reg_num = info->GetReg().GetRegNum();
612    RegStorage xp_reg = RegStorage::Solo128(sp_reg_num);
613    RegisterInfo* xp_reg_info = GetRegInfo(xp_reg);
614    // 128-bit xmm vector register's master storage should refer to itself.
615    DCHECK_EQ(xp_reg_info, xp_reg_info->Master());
616
617    // Redirect 32-bit vector's master storage to 128-bit vector.
618    info->SetMaster(xp_reg_info);
619
620    RegStorage dp_reg = RegStorage::FloatSolo64(sp_reg_num);
621    RegisterInfo* dp_reg_info = GetRegInfo(dp_reg);
622    // Redirect 64-bit vector's master storage to 128-bit vector.
623    dp_reg_info->SetMaster(xp_reg_info);
624    // Singles should show a single 32-bit mask bit, at first referring to the low half.
625    DCHECK_EQ(info->StorageMask(), 0x1U);
626  }
627
628  if (Gen64Bit()) {
629    // Alias 32bit W registers to corresponding 64bit X registers.
630    GrowableArray<RegisterInfo*>::Iterator w_it(&reg_pool_->core_regs_);
631    for (RegisterInfo* info = w_it.Next(); info != nullptr; info = w_it.Next()) {
632      int x_reg_num = info->GetReg().GetRegNum();
633      RegStorage x_reg = RegStorage::Solo64(x_reg_num);
634      RegisterInfo* x_reg_info = GetRegInfo(x_reg);
635      // 64bit X register's master storage should refer to itself.
636      DCHECK_EQ(x_reg_info, x_reg_info->Master());
637      // Redirect 32bit W master storage to 64bit X.
638      info->SetMaster(x_reg_info);
639      // 32bit W should show a single 32-bit mask bit, at first referring to the low half.
640      DCHECK_EQ(info->StorageMask(), 0x1U);
641    }
642  }
643
644  // Don't start allocating temps at r0/s0/d0 or you may clobber return regs in early-exit methods.
645  // TODO: adjust for x86/hard float calling convention.
646  reg_pool_->next_core_reg_ = 2;
647  reg_pool_->next_sp_reg_ = 2;
648  reg_pool_->next_dp_reg_ = 1;
649}
650
651void X86Mir2Lir::SpillCoreRegs() {
652  if (num_core_spills_ == 0) {
653    return;
654  }
655  // Spill mask not including fake return address register
656  uint32_t mask = core_spill_mask_ & ~(1 << rs_rRET.GetRegNum());
657  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * num_core_spills_);
658  for (int reg = 0; mask; mask >>= 1, reg++) {
659    if (mask & 0x1) {
660      StoreWordDisp(rs_rX86_SP, offset, RegStorage::Solo32(reg));
661      offset += GetInstructionSetPointerSize(cu_->instruction_set);
662    }
663  }
664}
665
666void X86Mir2Lir::UnSpillCoreRegs() {
667  if (num_core_spills_ == 0) {
668    return;
669  }
670  // Spill mask not including fake return address register
671  uint32_t mask = core_spill_mask_ & ~(1 << rs_rRET.GetRegNum());
672  int offset = frame_size_ - (GetInstructionSetPointerSize(cu_->instruction_set) * num_core_spills_);
673  for (int reg = 0; mask; mask >>= 1, reg++) {
674    if (mask & 0x1) {
675      LoadWordDisp(rs_rX86_SP, offset, RegStorage::Solo32(reg));
676      offset += GetInstructionSetPointerSize(cu_->instruction_set);
677    }
678  }
679}
680
681bool X86Mir2Lir::IsUnconditionalBranch(LIR* lir) {
682  return (lir->opcode == kX86Jmp8 || lir->opcode == kX86Jmp32);
683}
684
685bool X86Mir2Lir::SupportsVolatileLoadStore(OpSize size) {
686  return true;
687}
688
689RegisterClass X86Mir2Lir::RegClassForFieldLoadStore(OpSize size, bool is_volatile) {
690  if (UNLIKELY(is_volatile)) {
691    // On x86, atomic 64-bit load/store requires an fp register.
692    // Smaller aligned load/store is atomic for both core and fp registers.
693    if (size == k64 || size == kDouble) {
694      return kFPReg;
695    }
696  }
697  return RegClassBySize(size);
698}
699
700X86Mir2Lir::X86Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena, bool gen64bit)
701    : Mir2Lir(cu, mir_graph, arena),
702      base_of_code_(nullptr), store_method_addr_(false), store_method_addr_used_(false),
703      method_address_insns_(arena, 100, kGrowableArrayMisc),
704      class_type_address_insns_(arena, 100, kGrowableArrayMisc),
705      call_method_insns_(arena, 100, kGrowableArrayMisc),
706      stack_decrement_(nullptr), stack_increment_(nullptr), gen64bit_(gen64bit),
707      const_vectors_(nullptr) {
708  store_method_addr_used_ = false;
709  if (kIsDebugBuild) {
710    for (int i = 0; i < kX86Last; i++) {
711      if (X86Mir2Lir::EncodingMap[i].opcode != i) {
712        LOG(FATAL) << "Encoding order for " << X86Mir2Lir::EncodingMap[i].name
713                   << " is wrong: expecting " << i << ", seeing "
714                   << static_cast<int>(X86Mir2Lir::EncodingMap[i].opcode);
715      }
716    }
717  }
718  if (Gen64Bit()) {
719    rs_rX86_SP = rs_rX86_SP_64;
720
721    rs_rX86_ARG0 = rs_rDI;
722    rs_rX86_ARG1 = rs_rSI;
723    rs_rX86_ARG2 = rs_rDX;
724    rs_rX86_ARG3 = rs_rCX;
725#ifdef TARGET_REX_SUPPORT
726    rs_rX86_ARG4 = rs_r8;
727    rs_rX86_ARG5 = rs_r9;
728#else
729    rs_rX86_ARG4 = RegStorage::InvalidReg();
730    rs_rX86_ARG5 = RegStorage::InvalidReg();
731#endif
732    rs_rX86_FARG0 = rs_fr0;
733    rs_rX86_FARG1 = rs_fr1;
734    rs_rX86_FARG2 = rs_fr2;
735    rs_rX86_FARG3 = rs_fr3;
736    rs_rX86_FARG4 = rs_fr4;
737    rs_rX86_FARG5 = rs_fr5;
738    rs_rX86_FARG6 = rs_fr6;
739    rs_rX86_FARG7 = rs_fr7;
740    rX86_ARG0 = rDI;
741    rX86_ARG1 = rSI;
742    rX86_ARG2 = rDX;
743    rX86_ARG3 = rCX;
744#ifdef TARGET_REX_SUPPORT
745    rX86_ARG4 = r8;
746    rX86_ARG5 = r9;
747#endif
748    rX86_FARG0 = fr0;
749    rX86_FARG1 = fr1;
750    rX86_FARG2 = fr2;
751    rX86_FARG3 = fr3;
752    rX86_FARG4 = fr4;
753    rX86_FARG5 = fr5;
754    rX86_FARG6 = fr6;
755    rX86_FARG7 = fr7;
756  } else {
757    rs_rX86_SP = rs_rX86_SP_32;
758
759    rs_rX86_ARG0 = rs_rAX;
760    rs_rX86_ARG1 = rs_rCX;
761    rs_rX86_ARG2 = rs_rDX;
762    rs_rX86_ARG3 = rs_rBX;
763    rs_rX86_ARG4 = RegStorage::InvalidReg();
764    rs_rX86_ARG5 = RegStorage::InvalidReg();
765    rs_rX86_FARG0 = rs_rAX;
766    rs_rX86_FARG1 = rs_rCX;
767    rs_rX86_FARG2 = rs_rDX;
768    rs_rX86_FARG3 = rs_rBX;
769    rs_rX86_FARG4 = RegStorage::InvalidReg();
770    rs_rX86_FARG5 = RegStorage::InvalidReg();
771    rs_rX86_FARG6 = RegStorage::InvalidReg();
772    rs_rX86_FARG7 = RegStorage::InvalidReg();
773    rX86_ARG0 = rAX;
774    rX86_ARG1 = rCX;
775    rX86_ARG2 = rDX;
776    rX86_ARG3 = rBX;
777    rX86_FARG0 = rAX;
778    rX86_FARG1 = rCX;
779    rX86_FARG2 = rDX;
780    rX86_FARG3 = rBX;
781    // TODO(64): Initialize with invalid reg
782//    rX86_ARG4 = RegStorage::InvalidReg();
783//    rX86_ARG5 = RegStorage::InvalidReg();
784  }
785  rs_rX86_RET0 = rs_rAX;
786  rs_rX86_RET1 = rs_rDX;
787  rs_rX86_INVOKE_TGT = rs_rAX;
788  rs_rX86_COUNT = rs_rCX;
789  rX86_RET0 = rAX;
790  rX86_RET1 = rDX;
791  rX86_INVOKE_TGT = rAX;
792  rX86_COUNT = rCX;
793}
794
795Mir2Lir* X86CodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
796                          ArenaAllocator* const arena) {
797  return new X86Mir2Lir(cu, mir_graph, arena, false);
798}
799
800Mir2Lir* X86_64CodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
801                          ArenaAllocator* const arena) {
802  return new X86Mir2Lir(cu, mir_graph, arena, true);
803}
804
805// Not used in x86
806RegStorage X86Mir2Lir::LoadHelper(ThreadOffset<4> offset) {
807  LOG(FATAL) << "Unexpected use of LoadHelper in x86";
808  return RegStorage::InvalidReg();
809}
810
811// Not used in x86
812RegStorage X86Mir2Lir::LoadHelper(ThreadOffset<8> offset) {
813  LOG(FATAL) << "Unexpected use of LoadHelper in x86";
814  return RegStorage::InvalidReg();
815}
816
817LIR* X86Mir2Lir::CheckSuspendUsingLoad() {
818  LOG(FATAL) << "Unexpected use of CheckSuspendUsingLoad in x86";
819  return nullptr;
820}
821
822uint64_t X86Mir2Lir::GetTargetInstFlags(int opcode) {
823  DCHECK(!IsPseudoLirOp(opcode));
824  return X86Mir2Lir::EncodingMap[opcode].flags;
825}
826
827const char* X86Mir2Lir::GetTargetInstName(int opcode) {
828  DCHECK(!IsPseudoLirOp(opcode));
829  return X86Mir2Lir::EncodingMap[opcode].name;
830}
831
832const char* X86Mir2Lir::GetTargetInstFmt(int opcode) {
833  DCHECK(!IsPseudoLirOp(opcode));
834  return X86Mir2Lir::EncodingMap[opcode].fmt;
835}
836
837void X86Mir2Lir::GenConstWide(RegLocation rl_dest, int64_t value) {
838  // Can we do this directly to memory?
839  rl_dest = UpdateLocWide(rl_dest);
840  if ((rl_dest.location == kLocDalvikFrame) ||
841      (rl_dest.location == kLocCompilerTemp)) {
842    int32_t val_lo = Low32Bits(value);
843    int32_t val_hi = High32Bits(value);
844    int r_base = TargetReg(kSp).GetReg();
845    int displacement = SRegOffset(rl_dest.s_reg_low);
846
847    LIR * store = NewLIR3(kX86Mov32MI, r_base, displacement + LOWORD_OFFSET, val_lo);
848    AnnotateDalvikRegAccess(store, (displacement + LOWORD_OFFSET) >> 2,
849                              false /* is_load */, true /* is64bit */);
850    store = NewLIR3(kX86Mov32MI, r_base, displacement + HIWORD_OFFSET, val_hi);
851    AnnotateDalvikRegAccess(store, (displacement + HIWORD_OFFSET) >> 2,
852                              false /* is_load */, true /* is64bit */);
853    return;
854  }
855
856  // Just use the standard code to do the generation.
857  Mir2Lir::GenConstWide(rl_dest, value);
858}
859
860// TODO: Merge with existing RegLocation dumper in vreg_analysis.cc
861void X86Mir2Lir::DumpRegLocation(RegLocation loc) {
862  LOG(INFO)  << "location: " << loc.location << ','
863             << (loc.wide ? " w" : "  ")
864             << (loc.defined ? " D" : "  ")
865             << (loc.is_const ? " c" : "  ")
866             << (loc.fp ? " F" : "  ")
867             << (loc.core ? " C" : "  ")
868             << (loc.ref ? " r" : "  ")
869             << (loc.high_word ? " h" : "  ")
870             << (loc.home ? " H" : "  ")
871             << ", low: " << static_cast<int>(loc.reg.GetLowReg())
872             << ", high: " << static_cast<int>(loc.reg.GetHighReg())
873             << ", s_reg: " << loc.s_reg_low
874             << ", orig: " << loc.orig_sreg;
875}
876
877void X86Mir2Lir::Materialize() {
878  // A good place to put the analysis before starting.
879  AnalyzeMIR();
880
881  // Now continue with regular code generation.
882  Mir2Lir::Materialize();
883}
884
885void X86Mir2Lir::LoadMethodAddress(const MethodReference& target_method, InvokeType type,
886                                   SpecialTargetRegister symbolic_reg) {
887  /*
888   * For x86, just generate a 32 bit move immediate instruction, that will be filled
889   * in at 'link time'.  For now, put a unique value based on target to ensure that
890   * code deduplication works.
891   */
892  int target_method_idx = target_method.dex_method_index;
893  const DexFile* target_dex_file = target_method.dex_file;
894  const DexFile::MethodId& target_method_id = target_dex_file->GetMethodId(target_method_idx);
895  uintptr_t target_method_id_ptr = reinterpret_cast<uintptr_t>(&target_method_id);
896
897  // Generate the move instruction with the unique pointer and save index, dex_file, and type.
898  LIR *move = RawLIR(current_dalvik_offset_, kX86Mov32RI, TargetReg(symbolic_reg).GetReg(),
899                     static_cast<int>(target_method_id_ptr), target_method_idx,
900                     WrapPointer(const_cast<DexFile*>(target_dex_file)), type);
901  AppendLIR(move);
902  method_address_insns_.Insert(move);
903}
904
905void X86Mir2Lir::LoadClassType(uint32_t type_idx, SpecialTargetRegister symbolic_reg) {
906  /*
907   * For x86, just generate a 32 bit move immediate instruction, that will be filled
908   * in at 'link time'.  For now, put a unique value based on target to ensure that
909   * code deduplication works.
910   */
911  const DexFile::TypeId& id = cu_->dex_file->GetTypeId(type_idx);
912  uintptr_t ptr = reinterpret_cast<uintptr_t>(&id);
913
914  // Generate the move instruction with the unique pointer and save index and type.
915  LIR *move = RawLIR(current_dalvik_offset_, kX86Mov32RI, TargetReg(symbolic_reg).GetReg(),
916                     static_cast<int>(ptr), type_idx);
917  AppendLIR(move);
918  class_type_address_insns_.Insert(move);
919}
920
921LIR *X86Mir2Lir::CallWithLinkerFixup(const MethodReference& target_method, InvokeType type) {
922  /*
923   * For x86, just generate a 32 bit call relative instruction, that will be filled
924   * in at 'link time'.  For now, put a unique value based on target to ensure that
925   * code deduplication works.
926   */
927  int target_method_idx = target_method.dex_method_index;
928  const DexFile* target_dex_file = target_method.dex_file;
929  const DexFile::MethodId& target_method_id = target_dex_file->GetMethodId(target_method_idx);
930  uintptr_t target_method_id_ptr = reinterpret_cast<uintptr_t>(&target_method_id);
931
932  // Generate the call instruction with the unique pointer and save index, dex_file, and type.
933  LIR *call = RawLIR(current_dalvik_offset_, kX86CallI, static_cast<int>(target_method_id_ptr),
934                     target_method_idx, WrapPointer(const_cast<DexFile*>(target_dex_file)), type);
935  AppendLIR(call);
936  call_method_insns_.Insert(call);
937  return call;
938}
939
940/*
941 * @brief Enter a 32 bit quantity into a buffer
942 * @param buf buffer.
943 * @param data Data value.
944 */
945
946static void PushWord(std::vector<uint8_t>&buf, int32_t data) {
947  buf.push_back(data & 0xff);
948  buf.push_back((data >> 8) & 0xff);
949  buf.push_back((data >> 16) & 0xff);
950  buf.push_back((data >> 24) & 0xff);
951}
952
953void X86Mir2Lir::InstallLiteralPools() {
954  // These are handled differently for x86.
955  DCHECK(code_literal_list_ == nullptr);
956  DCHECK(method_literal_list_ == nullptr);
957  DCHECK(class_literal_list_ == nullptr);
958
959  // Align to 16 byte boundary.  We have implicit knowledge that the start of the method is
960  // on a 4 byte boundary.   How can I check this if it changes (other than aligned loads
961  // will fail at runtime)?
962  if (const_vectors_ != nullptr) {
963    int align_size = (16-4) - (code_buffer_.size() & 0xF);
964    if (align_size < 0) {
965      align_size += 16;
966    }
967
968    while (align_size > 0) {
969      code_buffer_.push_back(0);
970      align_size--;
971    }
972    for (LIR *p = const_vectors_; p != nullptr; p = p->next) {
973      PushWord(code_buffer_, p->operands[0]);
974      PushWord(code_buffer_, p->operands[1]);
975      PushWord(code_buffer_, p->operands[2]);
976      PushWord(code_buffer_, p->operands[3]);
977    }
978  }
979
980  // Handle the fixups for methods.
981  for (uint32_t i = 0; i < method_address_insns_.Size(); i++) {
982      LIR* p = method_address_insns_.Get(i);
983      DCHECK_EQ(p->opcode, kX86Mov32RI);
984      uint32_t target_method_idx = p->operands[2];
985      const DexFile* target_dex_file =
986          reinterpret_cast<const DexFile*>(UnwrapPointer(p->operands[3]));
987
988      // The offset to patch is the last 4 bytes of the instruction.
989      int patch_offset = p->offset + p->flags.size - 4;
990      cu_->compiler_driver->AddMethodPatch(cu_->dex_file, cu_->class_def_idx,
991                                           cu_->method_idx, cu_->invoke_type,
992                                           target_method_idx, target_dex_file,
993                                           static_cast<InvokeType>(p->operands[4]),
994                                           patch_offset);
995  }
996
997  // Handle the fixups for class types.
998  for (uint32_t i = 0; i < class_type_address_insns_.Size(); i++) {
999      LIR* p = class_type_address_insns_.Get(i);
1000      DCHECK_EQ(p->opcode, kX86Mov32RI);
1001      uint32_t target_method_idx = p->operands[2];
1002
1003      // The offset to patch is the last 4 bytes of the instruction.
1004      int patch_offset = p->offset + p->flags.size - 4;
1005      cu_->compiler_driver->AddClassPatch(cu_->dex_file, cu_->class_def_idx,
1006                                          cu_->method_idx, target_method_idx, patch_offset);
1007  }
1008
1009  // And now the PC-relative calls to methods.
1010  for (uint32_t i = 0; i < call_method_insns_.Size(); i++) {
1011      LIR* p = call_method_insns_.Get(i);
1012      DCHECK_EQ(p->opcode, kX86CallI);
1013      uint32_t target_method_idx = p->operands[1];
1014      const DexFile* target_dex_file =
1015          reinterpret_cast<const DexFile*>(UnwrapPointer(p->operands[2]));
1016
1017      // The offset to patch is the last 4 bytes of the instruction.
1018      int patch_offset = p->offset + p->flags.size - 4;
1019      cu_->compiler_driver->AddRelativeCodePatch(cu_->dex_file, cu_->class_def_idx,
1020                                                 cu_->method_idx, cu_->invoke_type,
1021                                                 target_method_idx, target_dex_file,
1022                                                 static_cast<InvokeType>(p->operands[3]),
1023                                                 patch_offset, -4 /* offset */);
1024  }
1025
1026  // And do the normal processing.
1027  Mir2Lir::InstallLiteralPools();
1028}
1029
1030/*
1031 * Fast string.index_of(I) & (II).  Inline check for simple case of char <= 0xffff,
1032 * otherwise bails to standard library code.
1033 */
1034bool X86Mir2Lir::GenInlinedIndexOf(CallInfo* info, bool zero_based) {
1035  ClobberCallerSave();
1036  LockCallTemps();  // Using fixed registers
1037
1038  // EAX: 16 bit character being searched.
1039  // ECX: count: number of words to be searched.
1040  // EDI: String being searched.
1041  // EDX: temporary during execution.
1042  // EBX: temporary during execution.
1043
1044  RegLocation rl_obj = info->args[0];
1045  RegLocation rl_char = info->args[1];
1046  RegLocation rl_start;  // Note: only present in III flavor or IndexOf.
1047
1048  uint32_t char_value =
1049    rl_char.is_const ? mir_graph_->ConstantValue(rl_char.orig_sreg) : 0;
1050
1051  if (char_value > 0xFFFF) {
1052    // We have to punt to the real String.indexOf.
1053    return false;
1054  }
1055
1056  // Okay, we are commited to inlining this.
1057  RegLocation rl_return = GetReturn(kCoreReg);
1058  RegLocation rl_dest = InlineTarget(info);
1059
1060  // Is the string non-NULL?
1061  LoadValueDirectFixed(rl_obj, rs_rDX);
1062  GenNullCheck(rs_rDX, info->opt_flags);
1063  info->opt_flags |= MIR_IGNORE_NULL_CHECK;  // Record that we've null checked.
1064
1065  // Does the character fit in 16 bits?
1066  LIR* slowpath_branch = nullptr;
1067  if (rl_char.is_const) {
1068    // We need the value in EAX.
1069    LoadConstantNoClobber(rs_rAX, char_value);
1070  } else {
1071    // Character is not a constant; compare at runtime.
1072    LoadValueDirectFixed(rl_char, rs_rAX);
1073    slowpath_branch = OpCmpImmBranch(kCondGt, rs_rAX, 0xFFFF, nullptr);
1074  }
1075
1076  // From here down, we know that we are looking for a char that fits in 16 bits.
1077  // Location of reference to data array within the String object.
1078  int value_offset = mirror::String::ValueOffset().Int32Value();
1079  // Location of count within the String object.
1080  int count_offset = mirror::String::CountOffset().Int32Value();
1081  // Starting offset within data array.
1082  int offset_offset = mirror::String::OffsetOffset().Int32Value();
1083  // Start of char data with array_.
1084  int data_offset = mirror::Array::DataOffset(sizeof(uint16_t)).Int32Value();
1085
1086  // Character is in EAX.
1087  // Object pointer is in EDX.
1088
1089  // We need to preserve EDI, but have no spare registers, so push it on the stack.
1090  // We have to remember that all stack addresses after this are offset by sizeof(EDI).
1091  NewLIR1(kX86Push32R, rs_rDI.GetReg());
1092
1093  // Compute the number of words to search in to rCX.
1094  Load32Disp(rs_rDX, count_offset, rs_rCX);
1095  LIR *length_compare = nullptr;
1096  int start_value = 0;
1097  bool is_index_on_stack = false;
1098  if (zero_based) {
1099    // We have to handle an empty string.  Use special instruction JECXZ.
1100    length_compare = NewLIR0(kX86Jecxz8);
1101  } else {
1102    rl_start = info->args[2];
1103    // We have to offset by the start index.
1104    if (rl_start.is_const) {
1105      start_value = mir_graph_->ConstantValue(rl_start.orig_sreg);
1106      start_value = std::max(start_value, 0);
1107
1108      // Is the start > count?
1109      length_compare = OpCmpImmBranch(kCondLe, rs_rCX, start_value, nullptr);
1110
1111      if (start_value != 0) {
1112        OpRegImm(kOpSub, rs_rCX, start_value);
1113      }
1114    } else {
1115      // Runtime start index.
1116      rl_start = UpdateLocTyped(rl_start, kCoreReg);
1117      if (rl_start.location == kLocPhysReg) {
1118        // Handle "start index < 0" case.
1119        OpRegReg(kOpXor, rs_rBX, rs_rBX);
1120        OpRegReg(kOpCmp, rl_start.reg, rs_rBX);
1121        OpCondRegReg(kOpCmov, kCondLt, rl_start.reg, rs_rBX);
1122
1123        // The length of the string should be greater than the start index.
1124        length_compare = OpCmpBranch(kCondLe, rs_rCX, rl_start.reg, nullptr);
1125        OpRegReg(kOpSub, rs_rCX, rl_start.reg);
1126        if (rl_start.reg == rs_rDI) {
1127          // The special case. We will use EDI further, so lets put start index to stack.
1128          NewLIR1(kX86Push32R, rs_rDI.GetReg());
1129          is_index_on_stack = true;
1130        }
1131      } else {
1132        // Load the start index from stack, remembering that we pushed EDI.
1133        int displacement = SRegOffset(rl_start.s_reg_low) + sizeof(uint32_t);
1134        Load32Disp(rs_rX86_SP, displacement, rs_rBX);
1135        OpRegReg(kOpXor, rs_rDI, rs_rDI);
1136        OpRegReg(kOpCmp, rs_rBX, rs_rDI);
1137        OpCondRegReg(kOpCmov, kCondLt, rs_rBX, rs_rDI);
1138
1139        length_compare = OpCmpBranch(kCondLe, rs_rCX, rs_rBX, nullptr);
1140        OpRegReg(kOpSub, rs_rCX, rs_rBX);
1141        // Put the start index to stack.
1142        NewLIR1(kX86Push32R, rs_rBX.GetReg());
1143        is_index_on_stack = true;
1144      }
1145    }
1146  }
1147  DCHECK(length_compare != nullptr);
1148
1149  // ECX now contains the count in words to be searched.
1150
1151  // Load the address of the string into EBX.
1152  // The string starts at VALUE(String) + 2 * OFFSET(String) + DATA_OFFSET.
1153  Load32Disp(rs_rDX, value_offset, rs_rDI);
1154  Load32Disp(rs_rDX, offset_offset, rs_rBX);
1155  OpLea(rs_rBX, rs_rDI, rs_rBX, 1, data_offset);
1156
1157  // Now compute into EDI where the search will start.
1158  if (zero_based || rl_start.is_const) {
1159    if (start_value == 0) {
1160      OpRegCopy(rs_rDI, rs_rBX);
1161    } else {
1162      NewLIR3(kX86Lea32RM, rs_rDI.GetReg(), rs_rBX.GetReg(), 2 * start_value);
1163    }
1164  } else {
1165    if (is_index_on_stack == true) {
1166      // Load the start index from stack.
1167      NewLIR1(kX86Pop32R, rs_rDX.GetReg());
1168      OpLea(rs_rDI, rs_rBX, rs_rDX, 1, 0);
1169    } else {
1170      OpLea(rs_rDI, rs_rBX, rl_start.reg, 1, 0);
1171    }
1172  }
1173
1174  // EDI now contains the start of the string to be searched.
1175  // We are all prepared to do the search for the character.
1176  NewLIR0(kX86RepneScasw);
1177
1178  // Did we find a match?
1179  LIR* failed_branch = OpCondBranch(kCondNe, nullptr);
1180
1181  // yes, we matched.  Compute the index of the result.
1182  // index = ((curr_ptr - orig_ptr) / 2) - 1.
1183  OpRegReg(kOpSub, rs_rDI, rs_rBX);
1184  OpRegImm(kOpAsr, rs_rDI, 1);
1185  NewLIR3(kX86Lea32RM, rl_return.reg.GetReg(), rs_rDI.GetReg(), -1);
1186  LIR *all_done = NewLIR1(kX86Jmp8, 0);
1187
1188  // Failed to match; return -1.
1189  LIR *not_found = NewLIR0(kPseudoTargetLabel);
1190  length_compare->target = not_found;
1191  failed_branch->target = not_found;
1192  LoadConstantNoClobber(rl_return.reg, -1);
1193
1194  // And join up at the end.
1195  all_done->target = NewLIR0(kPseudoTargetLabel);
1196  // Restore EDI from the stack.
1197  NewLIR1(kX86Pop32R, rs_rDI.GetReg());
1198
1199  // Out of line code returns here.
1200  if (slowpath_branch != nullptr) {
1201    LIR *return_point = NewLIR0(kPseudoTargetLabel);
1202    AddIntrinsicSlowPath(info, slowpath_branch, return_point);
1203  }
1204
1205  StoreValue(rl_dest, rl_return);
1206  return true;
1207}
1208
1209/*
1210 * @brief Enter an 'advance LOC' into the FDE buffer
1211 * @param buf FDE buffer.
1212 * @param increment Amount by which to increase the current location.
1213 */
1214static void AdvanceLoc(std::vector<uint8_t>&buf, uint32_t increment) {
1215  if (increment < 64) {
1216    // Encoding in opcode.
1217    buf.push_back(0x1 << 6 | increment);
1218  } else if (increment < 256) {
1219    // Single byte delta.
1220    buf.push_back(0x02);
1221    buf.push_back(increment);
1222  } else if (increment < 256 * 256) {
1223    // Two byte delta.
1224    buf.push_back(0x03);
1225    buf.push_back(increment & 0xff);
1226    buf.push_back((increment >> 8) & 0xff);
1227  } else {
1228    // Four byte delta.
1229    buf.push_back(0x04);
1230    PushWord(buf, increment);
1231  }
1232}
1233
1234
1235std::vector<uint8_t>* X86CFIInitialization() {
1236  return X86Mir2Lir::ReturnCommonCallFrameInformation();
1237}
1238
1239std::vector<uint8_t>* X86Mir2Lir::ReturnCommonCallFrameInformation() {
1240  std::vector<uint8_t>*cfi_info = new std::vector<uint8_t>;
1241
1242  // Length of the CIE (except for this field).
1243  PushWord(*cfi_info, 16);
1244
1245  // CIE id.
1246  PushWord(*cfi_info, 0xFFFFFFFFU);
1247
1248  // Version: 3.
1249  cfi_info->push_back(0x03);
1250
1251  // Augmentation: empty string.
1252  cfi_info->push_back(0x0);
1253
1254  // Code alignment: 1.
1255  cfi_info->push_back(0x01);
1256
1257  // Data alignment: -4.
1258  cfi_info->push_back(0x7C);
1259
1260  // Return address register (R8).
1261  cfi_info->push_back(0x08);
1262
1263  // Initial return PC is 4(ESP): DW_CFA_def_cfa R4 4.
1264  cfi_info->push_back(0x0C);
1265  cfi_info->push_back(0x04);
1266  cfi_info->push_back(0x04);
1267
1268  // Return address location: 0(SP): DW_CFA_offset R8 1 (* -4);.
1269  cfi_info->push_back(0x2 << 6 | 0x08);
1270  cfi_info->push_back(0x01);
1271
1272  // And 2 Noops to align to 4 byte boundary.
1273  cfi_info->push_back(0x0);
1274  cfi_info->push_back(0x0);
1275
1276  DCHECK_EQ(cfi_info->size() & 3, 0U);
1277  return cfi_info;
1278}
1279
1280static void EncodeUnsignedLeb128(std::vector<uint8_t>& buf, uint32_t value) {
1281  uint8_t buffer[12];
1282  uint8_t *ptr = EncodeUnsignedLeb128(buffer, value);
1283  for (uint8_t *p = buffer; p < ptr; p++) {
1284    buf.push_back(*p);
1285  }
1286}
1287
1288std::vector<uint8_t>* X86Mir2Lir::ReturnCallFrameInformation() {
1289  std::vector<uint8_t>*cfi_info = new std::vector<uint8_t>;
1290
1291  // Generate the FDE for the method.
1292  DCHECK_NE(data_offset_, 0U);
1293
1294  // Length (will be filled in later in this routine).
1295  PushWord(*cfi_info, 0);
1296
1297  // CIE_pointer (can be filled in by linker); might be left at 0 if there is only
1298  // one CIE for the whole debug_frame section.
1299  PushWord(*cfi_info, 0);
1300
1301  // 'initial_location' (filled in by linker).
1302  PushWord(*cfi_info, 0);
1303
1304  // 'address_range' (number of bytes in the method).
1305  PushWord(*cfi_info, data_offset_);
1306
1307  // The instructions in the FDE.
1308  if (stack_decrement_ != nullptr) {
1309    // Advance LOC to just past the stack decrement.
1310    uint32_t pc = NEXT_LIR(stack_decrement_)->offset;
1311    AdvanceLoc(*cfi_info, pc);
1312
1313    // Now update the offset to the call frame: DW_CFA_def_cfa_offset frame_size.
1314    cfi_info->push_back(0x0e);
1315    EncodeUnsignedLeb128(*cfi_info, frame_size_);
1316
1317    // We continue with that stack until the epilogue.
1318    if (stack_increment_ != nullptr) {
1319      uint32_t new_pc = NEXT_LIR(stack_increment_)->offset;
1320      AdvanceLoc(*cfi_info, new_pc - pc);
1321
1322      // We probably have code snippets after the epilogue, so save the
1323      // current state: DW_CFA_remember_state.
1324      cfi_info->push_back(0x0a);
1325
1326      // We have now popped the stack: DW_CFA_def_cfa_offset 4.  There is only the return
1327      // PC on the stack now.
1328      cfi_info->push_back(0x0e);
1329      EncodeUnsignedLeb128(*cfi_info, 4);
1330
1331      // Everything after that is the same as before the epilogue.
1332      // Stack bump was followed by RET instruction.
1333      LIR *post_ret_insn = NEXT_LIR(NEXT_LIR(stack_increment_));
1334      if (post_ret_insn != nullptr) {
1335        pc = new_pc;
1336        new_pc = post_ret_insn->offset;
1337        AdvanceLoc(*cfi_info, new_pc - pc);
1338        // Restore the state: DW_CFA_restore_state.
1339        cfi_info->push_back(0x0b);
1340      }
1341    }
1342  }
1343
1344  // Padding to a multiple of 4
1345  while ((cfi_info->size() & 3) != 0) {
1346    // DW_CFA_nop is encoded as 0.
1347    cfi_info->push_back(0);
1348  }
1349
1350  // Set the length of the FDE inside the generated bytes.
1351  uint32_t length = cfi_info->size() - 4;
1352  (*cfi_info)[0] = length;
1353  (*cfi_info)[1] = length >> 8;
1354  (*cfi_info)[2] = length >> 16;
1355  (*cfi_info)[3] = length >> 24;
1356  return cfi_info;
1357}
1358
1359void X86Mir2Lir::GenMachineSpecificExtendedMethodMIR(BasicBlock* bb, MIR* mir) {
1360  switch (static_cast<ExtendedMIROpcode>(mir->dalvikInsn.opcode)) {
1361    case kMirOpConstVector:
1362      GenConst128(bb, mir);
1363      break;
1364    case kMirOpMoveVector:
1365      GenMoveVector(bb, mir);
1366      break;
1367    case kMirOpPackedMultiply:
1368      GenMultiplyVector(bb, mir);
1369      break;
1370    case kMirOpPackedAddition:
1371      GenAddVector(bb, mir);
1372      break;
1373    case kMirOpPackedSubtract:
1374      GenSubtractVector(bb, mir);
1375      break;
1376    case kMirOpPackedShiftLeft:
1377      GenShiftLeftVector(bb, mir);
1378      break;
1379    case kMirOpPackedSignedShiftRight:
1380      GenSignedShiftRightVector(bb, mir);
1381      break;
1382    case kMirOpPackedUnsignedShiftRight:
1383      GenUnsignedShiftRightVector(bb, mir);
1384      break;
1385    case kMirOpPackedAnd:
1386      GenAndVector(bb, mir);
1387      break;
1388    case kMirOpPackedOr:
1389      GenOrVector(bb, mir);
1390      break;
1391    case kMirOpPackedXor:
1392      GenXorVector(bb, mir);
1393      break;
1394    case kMirOpPackedAddReduce:
1395      GenAddReduceVector(bb, mir);
1396      break;
1397    case kMirOpPackedReduce:
1398      GenReduceVector(bb, mir);
1399      break;
1400    case kMirOpPackedSet:
1401      GenSetVector(bb, mir);
1402      break;
1403    default:
1404      break;
1405  }
1406}
1407
1408void X86Mir2Lir::GenConst128(BasicBlock* bb, MIR* mir) {
1409  int type_size = mir->dalvikInsn.vA;
1410  // We support 128 bit vectors.
1411  DCHECK_EQ(type_size & 0xFFFF, 128);
1412  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vB);
1413  uint32_t *args = mir->dalvikInsn.arg;
1414  int reg = rs_dest.GetReg();
1415  // Check for all 0 case.
1416  if (args[0] == 0 && args[1] == 0 && args[2] == 0 && args[3] == 0) {
1417    NewLIR2(kX86XorpsRR, reg, reg);
1418    return;
1419  }
1420  // Okay, load it from the constant vector area.
1421  LIR *data_target = ScanVectorLiteral(mir);
1422  if (data_target == nullptr) {
1423    data_target = AddVectorLiteral(mir);
1424  }
1425
1426  // Address the start of the method.
1427  RegLocation rl_method = mir_graph_->GetRegLocation(base_of_code_->s_reg_low);
1428  rl_method = LoadValue(rl_method, kCoreReg);
1429
1430  // Load the proper value from the literal area.
1431  // We don't know the proper offset for the value, so pick one that will force
1432  // 4 byte offset.  We will fix this up in the assembler later to have the right
1433  // value.
1434  LIR *load = NewLIR3(kX86Mova128RM, reg, rl_method.reg.GetReg(),  256 /* bogus */);
1435  load->flags.fixup = kFixupLoad;
1436  load->target = data_target;
1437  SetMemRefType(load, true, kLiteral);
1438}
1439
1440void X86Mir2Lir::GenMoveVector(BasicBlock *bb, MIR *mir) {
1441  // We only support 128 bit registers.
1442  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1443  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vB);
1444  RegStorage rs_src = RegStorage::Solo128(mir->dalvikInsn.vC);
1445  NewLIR2(kX86Mova128RR, rs_dest.GetReg(), rs_src.GetReg());
1446}
1447
1448void X86Mir2Lir::GenMultiplyVector(BasicBlock *bb, MIR *mir) {
1449  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1450  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1451  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1452  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1453  int opcode = 0;
1454  switch (opsize) {
1455    case k32:
1456      opcode = kX86PmulldRR;
1457      break;
1458    case kSignedHalf:
1459      opcode = kX86PmullwRR;
1460      break;
1461    case kSingle:
1462      opcode = kX86MulpsRR;
1463      break;
1464    case kDouble:
1465      opcode = kX86MulpdRR;
1466      break;
1467    default:
1468      LOG(FATAL) << "Unsupported vector multiply " << opsize;
1469      break;
1470  }
1471  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1472}
1473
1474void X86Mir2Lir::GenAddVector(BasicBlock *bb, MIR *mir) {
1475  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1476  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1477  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1478  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1479  int opcode = 0;
1480  switch (opsize) {
1481    case k32:
1482      opcode = kX86PadddRR;
1483      break;
1484    case kSignedHalf:
1485    case kUnsignedHalf:
1486      opcode = kX86PaddwRR;
1487      break;
1488    case kUnsignedByte:
1489    case kSignedByte:
1490      opcode = kX86PaddbRR;
1491      break;
1492    case kSingle:
1493      opcode = kX86AddpsRR;
1494      break;
1495    case kDouble:
1496      opcode = kX86AddpdRR;
1497      break;
1498    default:
1499      LOG(FATAL) << "Unsupported vector addition " << opsize;
1500      break;
1501  }
1502  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1503}
1504
1505void X86Mir2Lir::GenSubtractVector(BasicBlock *bb, MIR *mir) {
1506  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1507  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1508  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1509  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1510  int opcode = 0;
1511  switch (opsize) {
1512    case k32:
1513      opcode = kX86PsubdRR;
1514      break;
1515    case kSignedHalf:
1516    case kUnsignedHalf:
1517      opcode = kX86PsubwRR;
1518      break;
1519    case kUnsignedByte:
1520    case kSignedByte:
1521      opcode = kX86PsubbRR;
1522      break;
1523    case kSingle:
1524      opcode = kX86SubpsRR;
1525      break;
1526    case kDouble:
1527      opcode = kX86SubpdRR;
1528      break;
1529    default:
1530      LOG(FATAL) << "Unsupported vector subtraction " << opsize;
1531      break;
1532  }
1533  NewLIR2(opcode, rs_dest_src1.GetReg(), rs_src2.GetReg());
1534}
1535
1536void X86Mir2Lir::GenShiftLeftVector(BasicBlock *bb, MIR *mir) {
1537  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1538  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1539  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1540  int imm = mir->dalvikInsn.vC;
1541  int opcode = 0;
1542  switch (opsize) {
1543    case k32:
1544      opcode = kX86PslldRI;
1545      break;
1546    case k64:
1547      opcode = kX86PsllqRI;
1548      break;
1549    case kSignedHalf:
1550    case kUnsignedHalf:
1551      opcode = kX86PsllwRI;
1552      break;
1553    default:
1554      LOG(FATAL) << "Unsupported vector shift left " << opsize;
1555      break;
1556  }
1557  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
1558}
1559
1560void X86Mir2Lir::GenSignedShiftRightVector(BasicBlock *bb, MIR *mir) {
1561  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1562  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1563  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1564  int imm = mir->dalvikInsn.vC;
1565  int opcode = 0;
1566  switch (opsize) {
1567    case k32:
1568      opcode = kX86PsradRI;
1569      break;
1570    case kSignedHalf:
1571    case kUnsignedHalf:
1572      opcode = kX86PsrawRI;
1573      break;
1574    default:
1575      LOG(FATAL) << "Unsupported vector signed shift right " << opsize;
1576      break;
1577  }
1578  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
1579}
1580
1581void X86Mir2Lir::GenUnsignedShiftRightVector(BasicBlock *bb, MIR *mir) {
1582  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1583  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1584  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1585  int imm = mir->dalvikInsn.vC;
1586  int opcode = 0;
1587  switch (opsize) {
1588    case k32:
1589      opcode = kX86PsrldRI;
1590      break;
1591    case k64:
1592      opcode = kX86PsrlqRI;
1593      break;
1594    case kSignedHalf:
1595    case kUnsignedHalf:
1596      opcode = kX86PsrlwRI;
1597      break;
1598    default:
1599      LOG(FATAL) << "Unsupported vector unsigned shift right " << opsize;
1600      break;
1601  }
1602  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
1603}
1604
1605void X86Mir2Lir::GenAndVector(BasicBlock *bb, MIR *mir) {
1606  // We only support 128 bit registers.
1607  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1608  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1609  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1610  NewLIR2(kX86PandRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
1611}
1612
1613void X86Mir2Lir::GenOrVector(BasicBlock *bb, MIR *mir) {
1614  // We only support 128 bit registers.
1615  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1616  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1617  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1618  NewLIR2(kX86PorRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
1619}
1620
1621void X86Mir2Lir::GenXorVector(BasicBlock *bb, MIR *mir) {
1622  // We only support 128 bit registers.
1623  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1624  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1625  RegStorage rs_src2 = RegStorage::Solo128(mir->dalvikInsn.vC);
1626  NewLIR2(kX86PxorRR, rs_dest_src1.GetReg(), rs_src2.GetReg());
1627}
1628
1629void X86Mir2Lir::GenAddReduceVector(BasicBlock *bb, MIR *mir) {
1630  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1631  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1632  RegStorage rs_dest_src1 = RegStorage::Solo128(mir->dalvikInsn.vB);
1633  int imm = mir->dalvikInsn.vC;
1634  int opcode = 0;
1635  switch (opsize) {
1636    case k32:
1637      opcode = kX86PhadddRR;
1638      break;
1639    case kSignedHalf:
1640    case kUnsignedHalf:
1641      opcode = kX86PhaddwRR;
1642      break;
1643    default:
1644      LOG(FATAL) << "Unsupported vector add reduce " << opsize;
1645      break;
1646  }
1647  NewLIR2(opcode, rs_dest_src1.GetReg(), imm);
1648}
1649
1650void X86Mir2Lir::GenReduceVector(BasicBlock *bb, MIR *mir) {
1651  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1652  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1653  RegStorage rs_src = RegStorage::Solo128(mir->dalvikInsn.vB);
1654  int index = mir->dalvikInsn.arg[0];
1655  int opcode = 0;
1656  switch (opsize) {
1657    case k32:
1658      opcode = kX86PextrdRRI;
1659      break;
1660    case kSignedHalf:
1661    case kUnsignedHalf:
1662      opcode = kX86PextrwRRI;
1663      break;
1664    case kUnsignedByte:
1665    case kSignedByte:
1666      opcode = kX86PextrbRRI;
1667      break;
1668    default:
1669      LOG(FATAL) << "Unsupported vector reduce " << opsize;
1670      break;
1671  }
1672  // We need to extract to a GPR.
1673  RegStorage temp = AllocTemp();
1674  NewLIR3(opcode, temp.GetReg(), rs_src.GetReg(), index);
1675
1676  // Assume that the destination VR is in the def for the mir.
1677  RegLocation rl_dest = mir_graph_->GetDest(mir);
1678  RegLocation rl_temp =
1679    {kLocPhysReg, 0, 0, 0, 0, 0, 0, 0, 1, temp, INVALID_SREG, INVALID_SREG};
1680  StoreValue(rl_dest, rl_temp);
1681}
1682
1683void X86Mir2Lir::GenSetVector(BasicBlock *bb, MIR *mir) {
1684  DCHECK_EQ(mir->dalvikInsn.vA & 0xFFFF, 128U);
1685  OpSize opsize = static_cast<OpSize>(mir->dalvikInsn.vA >> 16);
1686  RegStorage rs_dest = RegStorage::Solo128(mir->dalvikInsn.vB);
1687  int op_low = 0, op_high = 0;
1688  switch (opsize) {
1689    case k32:
1690      op_low = kX86PshufdRRI;
1691      break;
1692    case kSignedHalf:
1693    case kUnsignedHalf:
1694      // Handles low quadword.
1695      op_low = kX86PshuflwRRI;
1696      // Handles upper quadword.
1697      op_high = kX86PshufdRRI;
1698      break;
1699    default:
1700      LOG(FATAL) << "Unsupported vector set " << opsize;
1701      break;
1702  }
1703
1704  // Load the value from the VR into a GPR.
1705  RegLocation rl_src = mir_graph_->GetSrc(mir, 0);
1706  rl_src = LoadValue(rl_src, kCoreReg);
1707
1708  // Load the value into the XMM register.
1709  NewLIR2(kX86MovdxrRR, rs_dest.GetReg(), rl_src.reg.GetReg());
1710
1711  // Now shuffle the value across the destination.
1712  NewLIR3(op_low, rs_dest.GetReg(), rs_dest.GetReg(), 0);
1713
1714  // And then repeat as needed.
1715  if (op_high != 0) {
1716    NewLIR3(op_high, rs_dest.GetReg(), rs_dest.GetReg(), 0);
1717  }
1718}
1719
1720
1721LIR *X86Mir2Lir::ScanVectorLiteral(MIR *mir) {
1722  int *args = reinterpret_cast<int*>(mir->dalvikInsn.arg);
1723  for (LIR *p = const_vectors_; p != nullptr; p = p->next) {
1724    if (args[0] == p->operands[0] && args[1] == p->operands[1] &&
1725        args[2] == p->operands[2] && args[3] == p->operands[3]) {
1726      return p;
1727    }
1728  }
1729  return nullptr;
1730}
1731
1732LIR *X86Mir2Lir::AddVectorLiteral(MIR *mir) {
1733  LIR* new_value = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), kArenaAllocData));
1734  int *args = reinterpret_cast<int*>(mir->dalvikInsn.arg);
1735  new_value->operands[0] = args[0];
1736  new_value->operands[1] = args[1];
1737  new_value->operands[2] = args[2];
1738  new_value->operands[3] = args[3];
1739  new_value->next = const_vectors_;
1740  if (const_vectors_ == nullptr) {
1741    estimated_native_code_size_ += 12;  // Amount needed to align to 16 byte boundary.
1742  }
1743  estimated_native_code_size_ += 16;  // Space for one vector.
1744  const_vectors_ = new_value;
1745  return new_value;
1746}
1747
1748// ------------ ABI support: mapping of args to physical registers -------------
1749RegStorage X86Mir2Lir::InToRegStorageX86_64Mapper::GetNextReg(bool is_double_or_float, bool is_wide) {
1750  const RegStorage coreArgMappingToPhysicalReg[] = {rs_rX86_ARG1, rs_rX86_ARG2, rs_rX86_ARG3, rs_rX86_ARG4, rs_rX86_ARG5};
1751  const int coreArgMappingToPhysicalRegSize = sizeof(coreArgMappingToPhysicalReg) / sizeof(RegStorage);
1752  const RegStorage fpArgMappingToPhysicalReg[] = {rs_rX86_FARG0, rs_rX86_FARG1, rs_rX86_FARG2, rs_rX86_FARG3,
1753                                                  rs_rX86_FARG4, rs_rX86_FARG5, rs_rX86_FARG6, rs_rX86_FARG7};
1754  const int fpArgMappingToPhysicalRegSize = sizeof(fpArgMappingToPhysicalReg) / sizeof(RegStorage);
1755
1756  RegStorage result = RegStorage::InvalidReg();
1757  if (is_double_or_float) {
1758    if (cur_fp_reg_ < fpArgMappingToPhysicalRegSize) {
1759      result = fpArgMappingToPhysicalReg[cur_fp_reg_++];
1760      if (result.Valid()) {
1761        result = is_wide ? RegStorage::FloatSolo64(result.GetReg()) : RegStorage::FloatSolo32(result.GetReg());
1762      }
1763    }
1764  } else {
1765    if (cur_core_reg_ < coreArgMappingToPhysicalRegSize) {
1766      result = coreArgMappingToPhysicalReg[cur_core_reg_++];
1767      if (result.Valid()) {
1768        result = is_wide ? RegStorage::Solo64(result.GetReg()) : RegStorage::Solo32(result.GetReg());
1769      }
1770    }
1771  }
1772  return result;
1773}
1774
1775RegStorage X86Mir2Lir::InToRegStorageMapping::Get(int in_position) {
1776  DCHECK(IsInitialized());
1777  auto res = mapping_.find(in_position);
1778  return res != mapping_.end() ? res->second : RegStorage::InvalidReg();
1779}
1780
1781void X86Mir2Lir::InToRegStorageMapping::Initialize(RegLocation* arg_locs, int count, InToRegStorageMapper* mapper) {
1782  DCHECK(mapper != nullptr);
1783  max_mapped_in_ = -1;
1784  is_there_stack_mapped_ = false;
1785  for (int in_position = 0; in_position < count; in_position++) {
1786     RegStorage reg = mapper->GetNextReg(arg_locs[in_position].fp, arg_locs[in_position].wide);
1787     if (reg.Valid()) {
1788       mapping_[in_position] = reg;
1789       max_mapped_in_ = std::max(max_mapped_in_, in_position);
1790       if (reg.Is64BitSolo()) {
1791         // We covered 2 args, so skip the next one
1792         in_position++;
1793       }
1794     } else {
1795       is_there_stack_mapped_ = true;
1796     }
1797  }
1798  initialized_ = true;
1799}
1800
1801RegStorage X86Mir2Lir::GetArgMappingToPhysicalReg(int arg_num) {
1802  if (!Gen64Bit()) {
1803    return GetCoreArgMappingToPhysicalReg(arg_num);
1804  }
1805
1806  if (!in_to_reg_storage_mapping_.IsInitialized()) {
1807    int start_vreg = cu_->num_dalvik_registers - cu_->num_ins;
1808    RegLocation* arg_locs = &mir_graph_->reg_location_[start_vreg];
1809
1810    InToRegStorageX86_64Mapper mapper;
1811    in_to_reg_storage_mapping_.Initialize(arg_locs, cu_->num_ins, &mapper);
1812  }
1813  return in_to_reg_storage_mapping_.Get(arg_num);
1814}
1815
1816RegStorage X86Mir2Lir::GetCoreArgMappingToPhysicalReg(int core_arg_num) {
1817  // For the 32-bit internal ABI, the first 3 arguments are passed in registers.
1818  // Not used for 64-bit, TODO: Move X86_32 to the same framework
1819  switch (core_arg_num) {
1820    case 0:
1821      return rs_rX86_ARG1;
1822    case 1:
1823      return rs_rX86_ARG2;
1824    case 2:
1825      return rs_rX86_ARG3;
1826    default:
1827      return RegStorage::InvalidReg();
1828  }
1829}
1830
1831// ---------End of ABI support: mapping of args to physical registers -------------
1832
1833/*
1834 * If there are any ins passed in registers that have not been promoted
1835 * to a callee-save register, flush them to the frame.  Perform initial
1836 * assignment of promoted arguments.
1837 *
1838 * ArgLocs is an array of location records describing the incoming arguments
1839 * with one location record per word of argument.
1840 */
1841void X86Mir2Lir::FlushIns(RegLocation* ArgLocs, RegLocation rl_method) {
1842  if (!Gen64Bit()) return Mir2Lir::FlushIns(ArgLocs, rl_method);
1843  /*
1844   * Dummy up a RegLocation for the incoming Method*
1845   * It will attempt to keep kArg0 live (or copy it to home location
1846   * if promoted).
1847   */
1848
1849  RegLocation rl_src = rl_method;
1850  rl_src.location = kLocPhysReg;
1851  rl_src.reg = TargetReg(kArg0);
1852  rl_src.home = false;
1853  MarkLive(rl_src);
1854  StoreValue(rl_method, rl_src);
1855  // If Method* has been promoted, explicitly flush
1856  if (rl_method.location == kLocPhysReg) {
1857    StoreRefDisp(TargetReg(kSp), 0, TargetReg(kArg0));
1858  }
1859
1860  if (cu_->num_ins == 0) {
1861    return;
1862  }
1863
1864  int start_vreg = cu_->num_dalvik_registers - cu_->num_ins;
1865  /*
1866   * Copy incoming arguments to their proper home locations.
1867   * NOTE: an older version of dx had an issue in which
1868   * it would reuse static method argument registers.
1869   * This could result in the same Dalvik virtual register
1870   * being promoted to both core and fp regs. To account for this,
1871   * we only copy to the corresponding promoted physical register
1872   * if it matches the type of the SSA name for the incoming
1873   * argument.  It is also possible that long and double arguments
1874   * end up half-promoted.  In those cases, we must flush the promoted
1875   * half to memory as well.
1876   */
1877  for (int i = 0; i < cu_->num_ins; i++) {
1878    PromotionMap* v_map = &promotion_map_[start_vreg + i];
1879    RegStorage reg = RegStorage::InvalidReg();
1880    // get reg corresponding to input
1881    reg = GetArgMappingToPhysicalReg(i);
1882
1883    if (reg.Valid()) {
1884      // If arriving in register
1885      bool need_flush = true;
1886      RegLocation* t_loc = &ArgLocs[i];
1887      if ((v_map->core_location == kLocPhysReg) && !t_loc->fp) {
1888        OpRegCopy(RegStorage::Solo32(v_map->core_reg), reg);
1889        need_flush = false;
1890      } else if ((v_map->fp_location == kLocPhysReg) && t_loc->fp) {
1891        OpRegCopy(RegStorage::Solo32(v_map->FpReg), reg);
1892        need_flush = false;
1893      } else {
1894        need_flush = true;
1895      }
1896
1897      // For wide args, force flush if not fully promoted
1898      if (t_loc->wide) {
1899        PromotionMap* p_map = v_map + (t_loc->high_word ? -1 : +1);
1900        // Is only half promoted?
1901        need_flush |= (p_map->core_location != v_map->core_location) ||
1902            (p_map->fp_location != v_map->fp_location);
1903      }
1904      if (need_flush) {
1905        if (t_loc->wide && t_loc->fp) {
1906          StoreBaseDisp(TargetReg(kSp), SRegOffset(start_vreg + i), reg, k64);
1907          // Increment i to skip the next one
1908          i++;
1909        } else if (t_loc->wide && !t_loc->fp) {
1910          StoreBaseDisp(TargetReg(kSp), SRegOffset(start_vreg + i), reg, k64);
1911          // Increment i to skip the next one
1912          i++;
1913        } else {
1914          Store32Disp(TargetReg(kSp), SRegOffset(start_vreg + i), reg);
1915        }
1916      }
1917    } else {
1918      // If arriving in frame & promoted
1919      if (v_map->core_location == kLocPhysReg) {
1920        Load32Disp(TargetReg(kSp), SRegOffset(start_vreg + i), RegStorage::Solo32(v_map->core_reg));
1921      }
1922      if (v_map->fp_location == kLocPhysReg) {
1923        Load32Disp(TargetReg(kSp), SRegOffset(start_vreg + i), RegStorage::Solo32(v_map->FpReg));
1924      }
1925    }
1926  }
1927}
1928
1929/*
1930 * Load up to 5 arguments, the first three of which will be in
1931 * kArg1 .. kArg3.  On entry kArg0 contains the current method pointer,
1932 * and as part of the load sequence, it must be replaced with
1933 * the target method pointer.  Note, this may also be called
1934 * for "range" variants if the number of arguments is 5 or fewer.
1935 */
1936int X86Mir2Lir::GenDalvikArgsNoRange(CallInfo* info,
1937                                  int call_state, LIR** pcrLabel, NextCallInsn next_call_insn,
1938                                  const MethodReference& target_method,
1939                                  uint32_t vtable_idx, uintptr_t direct_code,
1940                                  uintptr_t direct_method, InvokeType type, bool skip_this) {
1941  if (!Gen64Bit()) {
1942    return Mir2Lir::GenDalvikArgsNoRange(info,
1943                                  call_state, pcrLabel, next_call_insn,
1944                                  target_method,
1945                                  vtable_idx, direct_code,
1946                                  direct_method, type, skip_this);
1947  }
1948  return GenDalvikArgsRange(info,
1949                       call_state, pcrLabel, next_call_insn,
1950                       target_method,
1951                       vtable_idx, direct_code,
1952                       direct_method, type, skip_this);
1953}
1954
1955/*
1956 * May have 0+ arguments (also used for jumbo).  Note that
1957 * source virtual registers may be in physical registers, so may
1958 * need to be flushed to home location before copying.  This
1959 * applies to arg3 and above (see below).
1960 *
1961 * Two general strategies:
1962 *    If < 20 arguments
1963 *       Pass args 3-18 using vldm/vstm block copy
1964 *       Pass arg0, arg1 & arg2 in kArg1-kArg3
1965 *    If 20+ arguments
1966 *       Pass args arg19+ using memcpy block copy
1967 *       Pass arg0, arg1 & arg2 in kArg1-kArg3
1968 *
1969 */
1970int X86Mir2Lir::GenDalvikArgsRange(CallInfo* info, int call_state,
1971                                LIR** pcrLabel, NextCallInsn next_call_insn,
1972                                const MethodReference& target_method,
1973                                uint32_t vtable_idx, uintptr_t direct_code, uintptr_t direct_method,
1974                                InvokeType type, bool skip_this) {
1975  if (!Gen64Bit()) {
1976    return Mir2Lir::GenDalvikArgsRange(info, call_state,
1977                                pcrLabel, next_call_insn,
1978                                target_method,
1979                                vtable_idx, direct_code, direct_method,
1980                                type, skip_this);
1981  }
1982
1983  /* If no arguments, just return */
1984  if (info->num_arg_words == 0)
1985    return call_state;
1986
1987  const int start_index = skip_this ? 1 : 0;
1988
1989  InToRegStorageX86_64Mapper mapper;
1990  InToRegStorageMapping in_to_reg_storage_mapping;
1991  in_to_reg_storage_mapping.Initialize(info->args, info->num_arg_words, &mapper);
1992  const int last_mapped_in = in_to_reg_storage_mapping.GetMaxMappedIn();
1993  const int size_of_the_last_mapped = last_mapped_in == -1 ? 1 :
1994          in_to_reg_storage_mapping.Get(last_mapped_in).Is64BitSolo() ? 2 : 1;
1995  int regs_left_to_pass_via_stack = info->num_arg_words - (last_mapped_in + size_of_the_last_mapped);
1996
1997  // Fisrt of all, check whether it make sense to use bulk copying
1998  // Optimization is aplicable only for range case
1999  // TODO: make a constant instead of 2
2000  if (info->is_range && regs_left_to_pass_via_stack >= 2) {
2001    // Scan the rest of the args - if in phys_reg flush to memory
2002    for (int next_arg = last_mapped_in + size_of_the_last_mapped; next_arg < info->num_arg_words;) {
2003      RegLocation loc = info->args[next_arg];
2004      if (loc.wide) {
2005        loc = UpdateLocWide(loc);
2006        if (loc.location == kLocPhysReg) {
2007          StoreBaseDisp(TargetReg(kSp), SRegOffset(loc.s_reg_low), loc.reg, k64);
2008        }
2009        next_arg += 2;
2010      } else {
2011        loc = UpdateLoc(loc);
2012        if (loc.location == kLocPhysReg) {
2013          StoreBaseDisp(TargetReg(kSp), SRegOffset(loc.s_reg_low), loc.reg, k32);
2014        }
2015        next_arg++;
2016      }
2017    }
2018
2019    // Logic below assumes that Method pointer is at offset zero from SP.
2020    DCHECK_EQ(VRegOffset(static_cast<int>(kVRegMethodPtrBaseReg)), 0);
2021
2022    // The rest can be copied together
2023    int start_offset = SRegOffset(info->args[last_mapped_in + size_of_the_last_mapped].s_reg_low);
2024    int outs_offset = StackVisitor::GetOutVROffset(last_mapped_in + size_of_the_last_mapped, cu_->instruction_set);
2025
2026    int current_src_offset = start_offset;
2027    int current_dest_offset = outs_offset;
2028
2029    while (regs_left_to_pass_via_stack > 0) {
2030      // This is based on the knowledge that the stack itself is 16-byte aligned.
2031      bool src_is_16b_aligned = (current_src_offset & 0xF) == 0;
2032      bool dest_is_16b_aligned = (current_dest_offset & 0xF) == 0;
2033      size_t bytes_to_move;
2034
2035      /*
2036       * The amount to move defaults to 32-bit. If there are 4 registers left to move, then do a
2037       * a 128-bit move because we won't get the chance to try to aligned. If there are more than
2038       * 4 registers left to move, consider doing a 128-bit only if either src or dest are aligned.
2039       * We do this because we could potentially do a smaller move to align.
2040       */
2041      if (regs_left_to_pass_via_stack == 4 ||
2042          (regs_left_to_pass_via_stack > 4 && (src_is_16b_aligned || dest_is_16b_aligned))) {
2043        // Moving 128-bits via xmm register.
2044        bytes_to_move = sizeof(uint32_t) * 4;
2045
2046        // Allocate a free xmm temp. Since we are working through the calling sequence,
2047        // we expect to have an xmm temporary available.  AllocTempDouble will abort if
2048        // there are no free registers.
2049        RegStorage temp = AllocTempDouble();
2050
2051        LIR* ld1 = nullptr;
2052        LIR* ld2 = nullptr;
2053        LIR* st1 = nullptr;
2054        LIR* st2 = nullptr;
2055
2056        /*
2057         * The logic is similar for both loads and stores. If we have 16-byte alignment,
2058         * do an aligned move. If we have 8-byte alignment, then do the move in two
2059         * parts. This approach prevents possible cache line splits. Finally, fall back
2060         * to doing an unaligned move. In most cases we likely won't split the cache
2061         * line but we cannot prove it and thus take a conservative approach.
2062         */
2063        bool src_is_8b_aligned = (current_src_offset & 0x7) == 0;
2064        bool dest_is_8b_aligned = (current_dest_offset & 0x7) == 0;
2065
2066        if (src_is_16b_aligned) {
2067          ld1 = OpMovRegMem(temp, TargetReg(kSp), current_src_offset, kMovA128FP);
2068        } else if (src_is_8b_aligned) {
2069          ld1 = OpMovRegMem(temp, TargetReg(kSp), current_src_offset, kMovLo128FP);
2070          ld2 = OpMovRegMem(temp, TargetReg(kSp), current_src_offset + (bytes_to_move >> 1),
2071                            kMovHi128FP);
2072        } else {
2073          ld1 = OpMovRegMem(temp, TargetReg(kSp), current_src_offset, kMovU128FP);
2074        }
2075
2076        if (dest_is_16b_aligned) {
2077          st1 = OpMovMemReg(TargetReg(kSp), current_dest_offset, temp, kMovA128FP);
2078        } else if (dest_is_8b_aligned) {
2079          st1 = OpMovMemReg(TargetReg(kSp), current_dest_offset, temp, kMovLo128FP);
2080          st2 = OpMovMemReg(TargetReg(kSp), current_dest_offset + (bytes_to_move >> 1),
2081                            temp, kMovHi128FP);
2082        } else {
2083          st1 = OpMovMemReg(TargetReg(kSp), current_dest_offset, temp, kMovU128FP);
2084        }
2085
2086        // TODO If we could keep track of aliasing information for memory accesses that are wider
2087        // than 64-bit, we wouldn't need to set up a barrier.
2088        if (ld1 != nullptr) {
2089          if (ld2 != nullptr) {
2090            // For 64-bit load we can actually set up the aliasing information.
2091            AnnotateDalvikRegAccess(ld1, current_src_offset >> 2, true, true);
2092            AnnotateDalvikRegAccess(ld2, (current_src_offset + (bytes_to_move >> 1)) >> 2, true, true);
2093          } else {
2094            // Set barrier for 128-bit load.
2095            SetMemRefType(ld1, true /* is_load */, kDalvikReg);
2096            ld1->u.m.def_mask = ENCODE_ALL;
2097          }
2098        }
2099        if (st1 != nullptr) {
2100          if (st2 != nullptr) {
2101            // For 64-bit store we can actually set up the aliasing information.
2102            AnnotateDalvikRegAccess(st1, current_dest_offset >> 2, false, true);
2103            AnnotateDalvikRegAccess(st2, (current_dest_offset + (bytes_to_move >> 1)) >> 2, false, true);
2104          } else {
2105            // Set barrier for 128-bit store.
2106            SetMemRefType(st1, false /* is_load */, kDalvikReg);
2107            st1->u.m.def_mask = ENCODE_ALL;
2108          }
2109        }
2110
2111        // Free the temporary used for the data movement.
2112        FreeTemp(temp);
2113      } else {
2114        // Moving 32-bits via general purpose register.
2115        bytes_to_move = sizeof(uint32_t);
2116
2117        // Instead of allocating a new temp, simply reuse one of the registers being used
2118        // for argument passing.
2119        RegStorage temp = TargetReg(kArg3);
2120
2121        // Now load the argument VR and store to the outs.
2122        Load32Disp(TargetReg(kSp), current_src_offset, temp);
2123        Store32Disp(TargetReg(kSp), current_dest_offset, temp);
2124      }
2125
2126      current_src_offset += bytes_to_move;
2127      current_dest_offset += bytes_to_move;
2128      regs_left_to_pass_via_stack -= (bytes_to_move >> 2);
2129    }
2130    DCHECK_EQ(regs_left_to_pass_via_stack, 0);
2131  }
2132
2133  // Now handle rest not registers if they are
2134  if (in_to_reg_storage_mapping.IsThereStackMapped()) {
2135    RegStorage regSingle = TargetReg(kArg2);
2136    RegStorage regWide = RegStorage::Solo64(TargetReg(kArg3).GetReg());
2137    for (int i = start_index; i <= last_mapped_in + regs_left_to_pass_via_stack; i++) {
2138      RegLocation rl_arg = info->args[i];
2139      rl_arg = UpdateRawLoc(rl_arg);
2140      RegStorage reg = in_to_reg_storage_mapping.Get(i);
2141      if (!reg.Valid()) {
2142        int out_offset = StackVisitor::GetOutVROffset(i, cu_->instruction_set);
2143
2144        if (rl_arg.wide) {
2145          if (rl_arg.location == kLocPhysReg) {
2146            StoreBaseDisp(TargetReg(kSp), out_offset, rl_arg.reg, k64);
2147          } else {
2148            LoadValueDirectWideFixed(rl_arg, regWide);
2149            StoreBaseDisp(TargetReg(kSp), out_offset, regWide, k64);
2150          }
2151          i++;
2152        } else {
2153          if (rl_arg.location == kLocPhysReg) {
2154            StoreBaseDisp(TargetReg(kSp), out_offset, rl_arg.reg, k32);
2155          } else {
2156            LoadValueDirectFixed(rl_arg, regSingle);
2157            StoreBaseDisp(TargetReg(kSp), out_offset, regSingle, k32);
2158          }
2159        }
2160        call_state = next_call_insn(cu_, info, call_state, target_method,
2161                                    vtable_idx, direct_code, direct_method, type);
2162      }
2163    }
2164  }
2165
2166  // Finish with mapped registers
2167  for (int i = start_index; i <= last_mapped_in; i++) {
2168    RegLocation rl_arg = info->args[i];
2169    rl_arg = UpdateRawLoc(rl_arg);
2170    RegStorage reg = in_to_reg_storage_mapping.Get(i);
2171    if (reg.Valid()) {
2172      if (rl_arg.wide) {
2173        LoadValueDirectWideFixed(rl_arg, reg);
2174        i++;
2175      } else {
2176        LoadValueDirectFixed(rl_arg, reg);
2177      }
2178      call_state = next_call_insn(cu_, info, call_state, target_method, vtable_idx,
2179                               direct_code, direct_method, type);
2180    }
2181  }
2182
2183  call_state = next_call_insn(cu_, info, call_state, target_method, vtable_idx,
2184                           direct_code, direct_method, type);
2185  if (pcrLabel) {
2186    if (Runtime::Current()->ExplicitNullChecks()) {
2187      *pcrLabel = GenExplicitNullCheck(TargetReg(kArg1), info->opt_flags);
2188    } else {
2189      *pcrLabel = nullptr;
2190      // In lieu of generating a check for kArg1 being null, we need to
2191      // perform a load when doing implicit checks.
2192      RegStorage tmp = AllocTemp();
2193      Load32Disp(TargetReg(kArg1), 0, tmp);
2194      MarkPossibleNullPointerException(info->opt_flags);
2195      FreeTemp(tmp);
2196    }
2197  }
2198  return call_state;
2199}
2200
2201}  // namespace art
2202
2203