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