target_x86.cc revision 31c2aac7137b69d5622eea09597500731fbee2ef
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 "codegen_x86.h"
18#include "dex/compiler_internals.h"
19#include "dex/quick/mir_to_lir-inl.h"
20#include "x86_lir.h"
21
22#include <string>
23
24namespace art {
25
26// FIXME: restore "static" when usage uncovered
27/*static*/ int core_regs[] = {
28  rAX, rCX, rDX, rBX, rX86_SP, rBP, rSI, rDI
29#ifdef TARGET_REX_SUPPORT
30  r8, r9, r10, r11, r12, r13, r14, 15
31#endif
32};
33/*static*/ int ReservedRegs[] = {rX86_SP};
34/*static*/ int core_temps[] = {rAX, rCX, rDX, rBX};
35/*static*/ int FpRegs[] = {
36  fr0, fr1, fr2, fr3, fr4, fr5, fr6, fr7,
37#ifdef TARGET_REX_SUPPORT
38  fr8, fr9, fr10, fr11, fr12, fr13, fr14, fr15
39#endif
40};
41/*static*/ int fp_temps[] = {
42  fr0, fr1, fr2, fr3, fr4, fr5, fr6, fr7,
43#ifdef TARGET_REX_SUPPORT
44  fr8, fr9, fr10, fr11, fr12, fr13, fr14, fr15
45#endif
46};
47
48RegLocation X86Mir2Lir::LocCReturn() {
49  RegLocation res = X86_LOC_C_RETURN;
50  return res;
51}
52
53RegLocation X86Mir2Lir::LocCReturnWide() {
54  RegLocation res = X86_LOC_C_RETURN_WIDE;
55  return res;
56}
57
58RegLocation X86Mir2Lir::LocCReturnFloat() {
59  RegLocation res = X86_LOC_C_RETURN_FLOAT;
60  return res;
61}
62
63RegLocation X86Mir2Lir::LocCReturnDouble() {
64  RegLocation res = X86_LOC_C_RETURN_DOUBLE;
65  return res;
66}
67
68// Return a target-dependent special register.
69int X86Mir2Lir::TargetReg(SpecialTargetRegister reg) {
70  int res = INVALID_REG;
71  switch (reg) {
72    case kSelf: res = rX86_SELF; break;
73    case kSuspend: res =  rX86_SUSPEND; break;
74    case kLr: res =  rX86_LR; break;
75    case kPc: res =  rX86_PC; break;
76    case kSp: res =  rX86_SP; break;
77    case kArg0: res = rX86_ARG0; break;
78    case kArg1: res = rX86_ARG1; break;
79    case kArg2: res = rX86_ARG2; break;
80    case kArg3: res = rX86_ARG3; break;
81    case kFArg0: res = rX86_FARG0; break;
82    case kFArg1: res = rX86_FARG1; break;
83    case kFArg2: res = rX86_FARG2; break;
84    case kFArg3: res = rX86_FARG3; break;
85    case kRet0: res = rX86_RET0; break;
86    case kRet1: res = rX86_RET1; break;
87    case kInvokeTgt: res = rX86_INVOKE_TGT; break;
88    case kHiddenArg: res = rAX; break;
89    case kHiddenFpArg: res = fr0; break;
90    case kCount: res = rX86_COUNT; break;
91  }
92  return res;
93}
94
95// Create a double from a pair of singles.
96int X86Mir2Lir::S2d(int low_reg, int high_reg) {
97  return X86_S2D(low_reg, high_reg);
98}
99
100// Return mask to strip off fp reg flags and bias.
101uint32_t X86Mir2Lir::FpRegMask() {
102  return X86_FP_REG_MASK;
103}
104
105// True if both regs single, both core or both double.
106bool X86Mir2Lir::SameRegType(int reg1, int reg2) {
107  return (X86_REGTYPE(reg1) == X86_REGTYPE(reg2));
108}
109
110/*
111 * Decode the register id.
112 */
113uint64_t X86Mir2Lir::GetRegMaskCommon(int reg) {
114  uint64_t seed;
115  int shift;
116  int reg_id;
117
118  reg_id = reg & 0xf;
119  /* Double registers in x86 are just a single FP register */
120  seed = 1;
121  /* FP register starts at bit position 16 */
122  shift = X86_FPREG(reg) ? kX86FPReg0 : 0;
123  /* Expand the double register id into single offset */
124  shift += reg_id;
125  return (seed << shift);
126}
127
128uint64_t X86Mir2Lir::GetPCUseDefEncoding() {
129  /*
130   * FIXME: might make sense to use a virtual resource encoding bit for pc.  Might be
131   * able to clean up some of the x86/Arm_Mips differences
132   */
133  LOG(FATAL) << "Unexpected call to GetPCUseDefEncoding for x86";
134  return 0ULL;
135}
136
137void X86Mir2Lir::SetupTargetResourceMasks(LIR* lir, uint64_t flags) {
138  DCHECK_EQ(cu_->instruction_set, kX86);
139  DCHECK(!lir->flags.use_def_invalid);
140
141  // X86-specific resource map setup here.
142  if (flags & REG_USE_SP) {
143    lir->u.m.use_mask |= ENCODE_X86_REG_SP;
144  }
145
146  if (flags & REG_DEF_SP) {
147    lir->u.m.def_mask |= ENCODE_X86_REG_SP;
148  }
149
150  if (flags & REG_DEFA) {
151    SetupRegMask(&lir->u.m.def_mask, rAX);
152  }
153
154  if (flags & REG_DEFD) {
155    SetupRegMask(&lir->u.m.def_mask, rDX);
156  }
157  if (flags & REG_USEA) {
158    SetupRegMask(&lir->u.m.use_mask, rAX);
159  }
160
161  if (flags & REG_USEC) {
162    SetupRegMask(&lir->u.m.use_mask, rCX);
163  }
164
165  if (flags & REG_USED) {
166    SetupRegMask(&lir->u.m.use_mask, rDX);
167  }
168}
169
170/* For dumping instructions */
171static const char* x86RegName[] = {
172  "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
173  "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
174};
175
176static const char* x86CondName[] = {
177  "O",
178  "NO",
179  "B/NAE/C",
180  "NB/AE/NC",
181  "Z/EQ",
182  "NZ/NE",
183  "BE/NA",
184  "NBE/A",
185  "S",
186  "NS",
187  "P/PE",
188  "NP/PO",
189  "L/NGE",
190  "NL/GE",
191  "LE/NG",
192  "NLE/G"
193};
194
195/*
196 * Interpret a format string and build a string no longer than size
197 * See format key in Assemble.cc.
198 */
199std::string X86Mir2Lir::BuildInsnString(const char *fmt, LIR *lir, unsigned char* base_addr) {
200  std::string buf;
201  size_t i = 0;
202  size_t fmt_len = strlen(fmt);
203  while (i < fmt_len) {
204    if (fmt[i] != '!') {
205      buf += fmt[i];
206      i++;
207    } else {
208      i++;
209      DCHECK_LT(i, fmt_len);
210      char operand_number_ch = fmt[i];
211      i++;
212      if (operand_number_ch == '!') {
213        buf += "!";
214      } else {
215        int operand_number = operand_number_ch - '0';
216        DCHECK_LT(operand_number, 6);  // Expect upto 6 LIR operands.
217        DCHECK_LT(i, fmt_len);
218        int operand = lir->operands[operand_number];
219        switch (fmt[i]) {
220          case 'c':
221            DCHECK_LT(static_cast<size_t>(operand), sizeof(x86CondName));
222            buf += x86CondName[operand];
223            break;
224          case 'd':
225            buf += StringPrintf("%d", operand);
226            break;
227          case 'p': {
228            EmbeddedData *tab_rec = reinterpret_cast<EmbeddedData*>(UnwrapPointer(operand));
229            buf += StringPrintf("0x%08x", tab_rec->offset);
230            break;
231          }
232          case 'r':
233            if (X86_FPREG(operand) || X86_DOUBLEREG(operand)) {
234              int fp_reg = operand & X86_FP_REG_MASK;
235              buf += StringPrintf("xmm%d", fp_reg);
236            } else {
237              DCHECK_LT(static_cast<size_t>(operand), sizeof(x86RegName));
238              buf += x86RegName[operand];
239            }
240            break;
241          case 't':
242            buf += StringPrintf("0x%08x (L%p)",
243                                reinterpret_cast<uintptr_t>(base_addr)
244                                + lir->offset + operand, lir->target);
245            break;
246          default:
247            buf += StringPrintf("DecodeError '%c'", fmt[i]);
248            break;
249        }
250        i++;
251      }
252    }
253  }
254  return buf;
255}
256
257void X86Mir2Lir::DumpResourceMask(LIR *x86LIR, uint64_t mask, const char *prefix) {
258  char buf[256];
259  buf[0] = 0;
260
261  if (mask == ENCODE_ALL) {
262    strcpy(buf, "all");
263  } else {
264    char num[8];
265    int i;
266
267    for (i = 0; i < kX86RegEnd; i++) {
268      if (mask & (1ULL << i)) {
269        sprintf(num, "%d ", i);
270        strcat(buf, num);
271      }
272    }
273
274    if (mask & ENCODE_CCODE) {
275      strcat(buf, "cc ");
276    }
277    /* Memory bits */
278    if (x86LIR && (mask & ENCODE_DALVIK_REG)) {
279      sprintf(buf + strlen(buf), "dr%d%s", DECODE_ALIAS_INFO_REG(x86LIR->flags.alias_info),
280              (DECODE_ALIAS_INFO_WIDE(x86LIR->flags.alias_info)) ? "(+1)" : "");
281    }
282    if (mask & ENCODE_LITERAL) {
283      strcat(buf, "lit ");
284    }
285
286    if (mask & ENCODE_HEAP_REF) {
287      strcat(buf, "heap ");
288    }
289    if (mask & ENCODE_MUST_NOT_ALIAS) {
290      strcat(buf, "noalias ");
291    }
292  }
293  if (buf[0]) {
294    LOG(INFO) << prefix << ": " <<  buf;
295  }
296}
297
298void X86Mir2Lir::AdjustSpillMask() {
299  // Adjustment for LR spilling, x86 has no LR so nothing to do here
300  core_spill_mask_ |= (1 << rRET);
301  num_core_spills_++;
302}
303
304/*
305 * Mark a callee-save fp register as promoted.  Note that
306 * vpush/vpop uses contiguous register lists so we must
307 * include any holes in the mask.  Associate holes with
308 * Dalvik register INVALID_VREG (0xFFFFU).
309 */
310void X86Mir2Lir::MarkPreservedSingle(int v_reg, int reg) {
311  UNIMPLEMENTED(WARNING) << "MarkPreservedSingle";
312#if 0
313  LOG(FATAL) << "No support yet for promoted FP regs";
314#endif
315}
316
317void X86Mir2Lir::FlushRegWide(int reg1, int reg2) {
318  RegisterInfo* info1 = GetRegInfo(reg1);
319  RegisterInfo* info2 = GetRegInfo(reg2);
320  DCHECK(info1 && info2 && info1->pair && info2->pair &&
321         (info1->partner == info2->reg) &&
322         (info2->partner == info1->reg));
323  if ((info1->live && info1->dirty) || (info2->live && info2->dirty)) {
324    if (!(info1->is_temp && info2->is_temp)) {
325      /* Should not happen.  If it does, there's a problem in eval_loc */
326      LOG(FATAL) << "Long half-temp, half-promoted";
327    }
328
329    info1->dirty = false;
330    info2->dirty = false;
331    if (mir_graph_->SRegToVReg(info2->s_reg) < mir_graph_->SRegToVReg(info1->s_reg))
332      info1 = info2;
333    int v_reg = mir_graph_->SRegToVReg(info1->s_reg);
334    StoreBaseDispWide(rX86_SP, VRegOffset(v_reg), info1->reg, info1->partner);
335  }
336}
337
338void X86Mir2Lir::FlushReg(int reg) {
339  RegisterInfo* info = GetRegInfo(reg);
340  if (info->live && info->dirty) {
341    info->dirty = false;
342    int v_reg = mir_graph_->SRegToVReg(info->s_reg);
343    StoreBaseDisp(rX86_SP, VRegOffset(v_reg), reg, kWord);
344  }
345}
346
347/* Give access to the target-dependent FP register encoding to common code */
348bool X86Mir2Lir::IsFpReg(int reg) {
349  return X86_FPREG(reg);
350}
351
352/* Clobber all regs that might be used by an external C call */
353void X86Mir2Lir::ClobberCallerSave() {
354  Clobber(rAX);
355  Clobber(rCX);
356  Clobber(rDX);
357  Clobber(rBX);
358}
359
360RegLocation X86Mir2Lir::GetReturnWideAlt() {
361  RegLocation res = LocCReturnWide();
362  CHECK(res.low_reg == rAX);
363  CHECK(res.high_reg == rDX);
364  Clobber(rAX);
365  Clobber(rDX);
366  MarkInUse(rAX);
367  MarkInUse(rDX);
368  MarkPair(res.low_reg, res.high_reg);
369  return res;
370}
371
372RegLocation X86Mir2Lir::GetReturnAlt() {
373  RegLocation res = LocCReturn();
374  res.low_reg = rDX;
375  Clobber(rDX);
376  MarkInUse(rDX);
377  return res;
378}
379
380/* To be used when explicitly managing register use */
381void X86Mir2Lir::LockCallTemps() {
382  LockTemp(rX86_ARG0);
383  LockTemp(rX86_ARG1);
384  LockTemp(rX86_ARG2);
385  LockTemp(rX86_ARG3);
386}
387
388/* To be used when explicitly managing register use */
389void X86Mir2Lir::FreeCallTemps() {
390  FreeTemp(rX86_ARG0);
391  FreeTemp(rX86_ARG1);
392  FreeTemp(rX86_ARG2);
393  FreeTemp(rX86_ARG3);
394}
395
396void X86Mir2Lir::GenMemBarrier(MemBarrierKind barrier_kind) {
397#if ANDROID_SMP != 0
398  // TODO: optimize fences
399  NewLIR0(kX86Mfence);
400#endif
401}
402/*
403 * Alloc a pair of core registers, or a double.  Low reg in low byte,
404 * high reg in next byte.
405 */
406int X86Mir2Lir::AllocTypedTempPair(bool fp_hint,
407                          int reg_class) {
408  int high_reg;
409  int low_reg;
410  int res = 0;
411
412  if (((reg_class == kAnyReg) && fp_hint) || (reg_class == kFPReg)) {
413    low_reg = AllocTempDouble();
414    high_reg = low_reg + 1;
415    res = (low_reg & 0xff) | ((high_reg & 0xff) << 8);
416    return res;
417  }
418
419  low_reg = AllocTemp();
420  high_reg = AllocTemp();
421  res = (low_reg & 0xff) | ((high_reg & 0xff) << 8);
422  return res;
423}
424
425int X86Mir2Lir::AllocTypedTemp(bool fp_hint, int reg_class) {
426  if (((reg_class == kAnyReg) && fp_hint) || (reg_class == kFPReg)) {
427    return AllocTempFloat();
428  }
429  return AllocTemp();
430}
431
432void X86Mir2Lir::CompilerInitializeRegAlloc() {
433  int num_regs = sizeof(core_regs)/sizeof(*core_regs);
434  int num_reserved = sizeof(ReservedRegs)/sizeof(*ReservedRegs);
435  int num_temps = sizeof(core_temps)/sizeof(*core_temps);
436  int num_fp_regs = sizeof(FpRegs)/sizeof(*FpRegs);
437  int num_fp_temps = sizeof(fp_temps)/sizeof(*fp_temps);
438  reg_pool_ = static_cast<RegisterPool*>(arena_->Alloc(sizeof(*reg_pool_),
439                                                       ArenaAllocator::kAllocRegAlloc));
440  reg_pool_->num_core_regs = num_regs;
441  reg_pool_->core_regs =
442      static_cast<RegisterInfo*>(arena_->Alloc(num_regs * sizeof(*reg_pool_->core_regs),
443                                               ArenaAllocator::kAllocRegAlloc));
444  reg_pool_->num_fp_regs = num_fp_regs;
445  reg_pool_->FPRegs =
446      static_cast<RegisterInfo *>(arena_->Alloc(num_fp_regs * sizeof(*reg_pool_->FPRegs),
447                                                ArenaAllocator::kAllocRegAlloc));
448  CompilerInitPool(reg_pool_->core_regs, core_regs, reg_pool_->num_core_regs);
449  CompilerInitPool(reg_pool_->FPRegs, FpRegs, reg_pool_->num_fp_regs);
450  // Keep special registers from being allocated
451  for (int i = 0; i < num_reserved; i++) {
452    MarkInUse(ReservedRegs[i]);
453  }
454  // Mark temp regs - all others not in use can be used for promotion
455  for (int i = 0; i < num_temps; i++) {
456    MarkTemp(core_temps[i]);
457  }
458  for (int i = 0; i < num_fp_temps; i++) {
459    MarkTemp(fp_temps[i]);
460  }
461}
462
463void X86Mir2Lir::FreeRegLocTemps(RegLocation rl_keep,
464                     RegLocation rl_free) {
465  if ((rl_free.low_reg != rl_keep.low_reg) && (rl_free.low_reg != rl_keep.high_reg) &&
466      (rl_free.high_reg != rl_keep.low_reg) && (rl_free.high_reg != rl_keep.high_reg)) {
467    // No overlap, free both
468    FreeTemp(rl_free.low_reg);
469    FreeTemp(rl_free.high_reg);
470  }
471}
472
473void X86Mir2Lir::SpillCoreRegs() {
474  if (num_core_spills_ == 0) {
475    return;
476  }
477  // Spill mask not including fake return address register
478  uint32_t mask = core_spill_mask_ & ~(1 << rRET);
479  int offset = frame_size_ - (4 * num_core_spills_);
480  for (int reg = 0; mask; mask >>= 1, reg++) {
481    if (mask & 0x1) {
482      StoreWordDisp(rX86_SP, offset, reg);
483      offset += 4;
484    }
485  }
486}
487
488void X86Mir2Lir::UnSpillCoreRegs() {
489  if (num_core_spills_ == 0) {
490    return;
491  }
492  // Spill mask not including fake return address register
493  uint32_t mask = core_spill_mask_ & ~(1 << rRET);
494  int offset = frame_size_ - (4 * num_core_spills_);
495  for (int reg = 0; mask; mask >>= 1, reg++) {
496    if (mask & 0x1) {
497      LoadWordDisp(rX86_SP, offset, reg);
498      offset += 4;
499    }
500  }
501}
502
503bool X86Mir2Lir::IsUnconditionalBranch(LIR* lir) {
504  return (lir->opcode == kX86Jmp8 || lir->opcode == kX86Jmp32);
505}
506
507X86Mir2Lir::X86Mir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena)
508    : Mir2Lir(cu, mir_graph, arena) {
509  for (int i = 0; i < kX86Last; i++) {
510    if (X86Mir2Lir::EncodingMap[i].opcode != i) {
511      LOG(FATAL) << "Encoding order for " << X86Mir2Lir::EncodingMap[i].name
512                 << " is wrong: expecting " << i << ", seeing "
513                 << static_cast<int>(X86Mir2Lir::EncodingMap[i].opcode);
514    }
515  }
516}
517
518Mir2Lir* X86CodeGenerator(CompilationUnit* const cu, MIRGraph* const mir_graph,
519                          ArenaAllocator* const arena) {
520  return new X86Mir2Lir(cu, mir_graph, arena);
521}
522
523// Not used in x86
524int X86Mir2Lir::LoadHelper(ThreadOffset offset) {
525  LOG(FATAL) << "Unexpected use of LoadHelper in x86";
526  return INVALID_REG;
527}
528
529uint64_t X86Mir2Lir::GetTargetInstFlags(int opcode) {
530  DCHECK(!IsPseudoLirOp(opcode));
531  return X86Mir2Lir::EncodingMap[opcode].flags;
532}
533
534const char* X86Mir2Lir::GetTargetInstName(int opcode) {
535  DCHECK(!IsPseudoLirOp(opcode));
536  return X86Mir2Lir::EncodingMap[opcode].name;
537}
538
539const char* X86Mir2Lir::GetTargetInstFmt(int opcode) {
540  DCHECK(!IsPseudoLirOp(opcode));
541  return X86Mir2Lir::EncodingMap[opcode].fmt;
542}
543
544}  // namespace art
545