/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *   Mupen64plus/PCSX - assem_arm.c                                        *
 *   Copyright (C) 2009-2011 Ari64                                         *
 *   Copyright (C) 2010-2021 Gražvydas "notaz" Ignotas                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include <strings.h> // ffs
#define FLAGLESS
#include "../gte.h"
#undef FLAGLESS
#include "../gte_arm.h"
#include "../gte_neon.h"
#include "pcnt.h"
#include "arm_features.h"

#ifdef TC_WRITE_OFFSET
#error "not implemented"
#endif

#ifdef DRC_DBG
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif

void indirect_jump_indexed();
void indirect_jump();
void do_interrupt();
void jump_vaddr_r0();
void jump_vaddr_r1();
void jump_vaddr_r2();
void jump_vaddr_r3();
void jump_vaddr_r4();
void jump_vaddr_r5();
void jump_vaddr_r6();
void jump_vaddr_r7();
void jump_vaddr_r8();
void jump_vaddr_r9();
void jump_vaddr_r10();
void jump_vaddr_r12();

void * const jump_vaddr_reg[16] = {
  jump_vaddr_r0,
  jump_vaddr_r1,
  jump_vaddr_r2,
  jump_vaddr_r3,
  jump_vaddr_r4,
  jump_vaddr_r5,
  jump_vaddr_r6,
  jump_vaddr_r7,
  jump_vaddr_r8,
  jump_vaddr_r9,
  jump_vaddr_r10,
  0,
  jump_vaddr_r12,
  0,
  0,
  0
};

void invalidate_addr_r0();
void invalidate_addr_r1();
void invalidate_addr_r2();
void invalidate_addr_r3();
void invalidate_addr_r4();
void invalidate_addr_r5();
void invalidate_addr_r6();
void invalidate_addr_r7();
void invalidate_addr_r8();
void invalidate_addr_r9();
void invalidate_addr_r10();
void invalidate_addr_r12();

const void *invalidate_addr_reg[16] = {
  invalidate_addr_r0,
  invalidate_addr_r1,
  invalidate_addr_r2,
  invalidate_addr_r3,
  invalidate_addr_r4,
  invalidate_addr_r5,
  invalidate_addr_r6,
  invalidate_addr_r7,
  invalidate_addr_r8,
  invalidate_addr_r9,
  invalidate_addr_r10,
  0,
  invalidate_addr_r12,
  0,
  0,
  0
};

/* Linker */

static void set_jump_target_far1(u_int *insn, void *target)
{
  u_int ni = *insn & 0xff000000;
  ni |= (((u_int)target - (u_int)insn - 8u) << 6) >> 8;
  assert((ni & 0x0e000000) == 0x0a000000);
  *insn = ni;
}

static void set_jump_target(void *addr, void *target_)
{
  const u_int target = (u_int)target_;
  const u_char *ptr = addr;
  u_int *ptr2 = (u_int *)ptr;
  if(ptr[3]==0xe2) {
    assert((target-(u_int)ptr2-8)<1024);
    assert(((uintptr_t)addr&3)==0);
    assert((target&3)==0);
    *ptr2=(*ptr2&0xFFFFF000)|((target-(u_int)ptr2-8)>>2)|0xF00;
    //printf("target=%x addr=%p insn=%x\n",target,addr,*ptr2);
  }
  else if(ptr[3]==0x72) {
    // generated by emit_jno_unlikely
    if((target-(u_int)ptr2-8)<1024) {
      assert(((uintptr_t)addr&3)==0);
      assert((target&3)==0);
      *ptr2=(*ptr2&0xFFFFF000)|((target-(u_int)ptr2-8)>>2)|0xF00;
    }
    else if((target-(u_int)ptr2-8)<4096&&!((target-(u_int)ptr2-8)&15)) {
      assert(((uintptr_t)addr&3)==0);
      assert((target&3)==0);
      *ptr2=(*ptr2&0xFFFFF000)|((target-(u_int)ptr2-8)>>4)|0xE00;
    }
    else *ptr2=(0x7A000000)|(((target-(u_int)ptr2-8)<<6)>>8);
  }
  else {
    set_jump_target_far1(ptr2, target_);
  }
}

// This optionally copies the instruction from the target of the branch into
// the space before the branch.  Works, but the difference in speed is
// usually insignificant.
#if 0
static void set_jump_target_fillslot(int addr,u_int target,int copy)
{
  u_char *ptr=(u_char *)addr;
  u_int *ptr2=(u_int *)ptr;
  assert(!copy||ptr2[-1]==0xe28dd000);
  if(ptr[3]==0xe2) {
    assert(!copy);
    assert((target-(u_int)ptr2-8)<4096);
    *ptr2=(*ptr2&0xFFFFF000)|(target-(u_int)ptr2-8);
  }
  else {
    assert((ptr[3]&0x0e)==0xa);
    u_int target_insn=*(u_int *)target;
    if((target_insn&0x0e100000)==0) { // ALU, no immediate, no flags
      copy=0;
    }
    if((target_insn&0x0c100000)==0x04100000) { // Load
      copy=0;
    }
    if(target_insn&0x08000000) {
      copy=0;
    }
    if(copy) {
      ptr2[-1]=target_insn;
      target+=4;
    }
    *ptr2=(*ptr2&0xFF000000)|(((target-(u_int)ptr2-8)<<6)>>8);
  }
}
#endif

/* Literal pool */
static void add_literal(int addr,int val)
{
  assert(literalcount<sizeof(literals)/sizeof(literals[0]));
  literals[literalcount][0]=addr;
  literals[literalcount][1]=val;
  literalcount++;
}

// from a pointer to external jump stub (which was produced by emit_extjump2)
// find where the jumping insn is
static void *find_extjump_insn(void *stub)
{
  int *ptr=(int *)(stub+4);
  assert((*ptr&0x0fff0000)==0x059f0000); // ldr rx, [pc, #ofs]
  u_int offset=*ptr&0xfff;
  void **l_ptr=(void *)ptr+offset+8;
  return *l_ptr;
}

// Allocate a specific ARM register.
static void alloc_arm_reg(struct regstat *cur,int i,signed char reg,int hr)
{
  int n;
  int dirty=0;

  // see if it's already allocated (and dealloc it)
  for(n=0;n<HOST_REGS;n++)
  {
    if(n!=EXCLUDE_REG&&cur->regmap[n]==reg) {
      dirty=(cur->dirty>>n)&1;
      cur->regmap[n]=-1;
    }
  }

  assert(n == hr || cur->regmap[hr] < 0 || !((cur->noevict >> hr) & 1));
  cur->regmap[hr] = reg;
  cur->dirty &= ~(1 << hr);
  cur->dirty |= dirty << hr;
  cur->isconst &= ~(1u << hr);
  cur->noevict |= 1u << hr;
}

// Alloc cycle count into dedicated register
static void alloc_cc(struct regstat *cur, int i)
{
  alloc_arm_reg(cur, i, CCREG, HOST_CCREG);
}

static void alloc_cc_optional(struct regstat *cur, int i)
{
  if (cur->regmap[HOST_CCREG] < 0) {
    alloc_arm_reg(cur, i, CCREG, HOST_CCREG);
    cur->noevict &= ~(1u << HOST_CCREG);
  }
}

/* Assembler */

static attr_unused char regname[16][4] = {
 "r0",
 "r1",
 "r2",
 "r3",
 "r4",
 "r5",
 "r6",
 "r7",
 "r8",
 "r9",
 "r10",
 "fp",
 "r12",
 "sp",
 "lr",
 "pc"};

static void output_w32(u_int word)
{
  *((u_int *)out)=word;
  out+=4;
}

static u_int rd_rn_rm(u_int rd, u_int rn, u_int rm)
{
  assert(rd<16);
  assert(rn<16);
  assert(rm<16);
  return((rn<<16)|(rd<<12)|rm);
}

static u_int rd_rn_imm_shift(u_int rd, u_int rn, u_int imm, u_int shift)
{
  assert(rd<16);
  assert(rn<16);
  assert(imm<256);
  assert((shift&1)==0);
  return((rn<<16)|(rd<<12)|(((32-shift)&30)<<7)|imm);
}

static u_int genimm(u_int imm,u_int *encoded)
{
  *encoded=0;
  if(imm==0) return 1;
  int i=32;
  while(i>0)
  {
    if(imm<256) {
      *encoded=((i&30)<<7)|imm;
      return 1;
    }
    imm=(imm>>2)|(imm<<30);i-=2;
  }
  return 0;
}

static void genimm_checked(u_int imm,u_int *encoded)
{
  u_int ret=genimm(imm,encoded);
  assert(ret);
  (void)ret;
}

static u_int genjmp(u_int addr)
{
  if (addr < 3) return 0; // a branch that will be patched later
  int offset = addr-(int)out-8;
  if (offset < -33554432 || offset >= 33554432) {
    SysPrintf("genjmp: out of range: %08x\n", offset);
    abort();
    return 0;
  }
  return ((u_int)offset>>2)&0xffffff;
}

static attr_unused void emit_breakpoint(void)
{
  assem_debug("bkpt #0\n");
  //output_w32(0xe1200070);
  output_w32(0xe7f001f0);
}

static void emit_mov(int rs,int rt)
{
  assem_debug("mov %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs));
}

static void emit_movs(int rs,int rt)
{
  assem_debug("movs %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe1b00000|rd_rn_rm(rt,0,rs));
}

static void emit_add(int rs1,int rs2,int rt)
{
  assem_debug("add %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0800000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_adds(int rs1,int rs2,int rt)
{
  assem_debug("adds %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0900000|rd_rn_rm(rt,rs1,rs2));
}
#define emit_adds_ptr emit_adds

static void emit_adcs(int rs1,int rs2,int rt)
{
  assem_debug("adcs %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0b00000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_neg(int rs, int rt)
{
  assem_debug("rsb %s,%s,#0\n",regname[rt],regname[rs]);
  output_w32(0xe2600000|rd_rn_rm(rt,rs,0));
}

static void emit_negs(int rs, int rt)
{
  assem_debug("rsbs %s,%s,#0\n",regname[rt],regname[rs]);
  output_w32(0xe2700000|rd_rn_rm(rt,rs,0));
}

static void emit_sub(int rs1,int rs2,int rt)
{
  assem_debug("sub %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0400000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_subs(int rs1,int rs2,int rt)
{
  assem_debug("subs %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0500000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_zeroreg(int rt)
{
  assem_debug("mov %s,#0\n",regname[rt]);
  output_w32(0xe3a00000|rd_rn_rm(rt,0,0));
}

static void emit_loadlp(u_int imm,u_int rt)
{
  add_literal((int)out,imm);
  assem_debug("ldr %s,pc+? [=%x]\n",regname[rt],imm);
  output_w32(0xe5900000|rd_rn_rm(rt,15,0));
}

#ifdef HAVE_ARMV7
static void emit_movw(u_int imm,u_int rt)
{
  assert(imm<65536);
  assem_debug("movw %s,#%d (0x%x)\n",regname[rt],imm,imm);
  output_w32(0xe3000000|rd_rn_rm(rt,0,0)|(imm&0xfff)|((imm<<4)&0xf0000));
}

static void emit_movt(u_int imm,u_int rt)
{
  assem_debug("movt %s,#%d (0x%x)\n",regname[rt],imm&0xffff0000,imm&0xffff0000);
  output_w32(0xe3400000|rd_rn_rm(rt,0,0)|((imm>>16)&0xfff)|((imm>>12)&0xf0000));
}
#endif

static void emit_movimm(u_int imm,u_int rt)
{
  u_int armval;
  if(genimm(imm,&armval)) {
    assem_debug("mov %s,#%d\n",regname[rt],imm);
    output_w32(0xe3a00000|rd_rn_rm(rt,0,0)|armval);
  }else if(genimm(~imm,&armval)) {
    assem_debug("mvn %s,#%d\n",regname[rt],imm);
    output_w32(0xe3e00000|rd_rn_rm(rt,0,0)|armval);
  }else if(imm<65536) {
    #ifndef HAVE_ARMV7
    assem_debug("mov %s,#%d\n",regname[rt],imm&0xFF00);
    output_w32(0xe3a00000|rd_rn_imm_shift(rt,0,imm>>8,8));
    assem_debug("add %s,%s,#%d\n",regname[rt],regname[rt],imm&0xFF);
    output_w32(0xe2800000|rd_rn_imm_shift(rt,rt,imm&0xff,0));
    #else
    emit_movw(imm,rt);
    #endif
  }else{
    #ifndef HAVE_ARMV7
    emit_loadlp(imm,rt);
    #else
    emit_movw(imm&0x0000FFFF,rt);
    emit_movt(imm&0xFFFF0000,rt);
    #endif
  }
}

static void emit_pcreladdr(u_int rt)
{
  assem_debug("add %s,pc,#?\n",regname[rt]);
  output_w32(0xe2800000|rd_rn_rm(rt,15,0));
}

static void emit_loadreg(int r, int hr)
{
  assert(hr != EXCLUDE_REG);
  if (r == 0)
    emit_zeroreg(hr);
  else {
    void *addr;
    switch (r) {
    //case HIREG: addr = &hi; break;
    //case LOREG: addr = &lo; break;
    case CCREG: addr = &cycle_count; break;
    case INVCP: addr = &invc_ptr; break;
    case ROREG: addr = &ram_offset; break;
    default:
      assert(r < 34);
      addr = &psxRegs.GPR.r[r];
      break;
    }
    u_int offset = (u_char *)addr - (u_char *)&dynarec_local;
    assert(offset<4096);
    assem_debug("ldr %s,fp+%d # r%d\n",regname[hr],offset,r);
    output_w32(0xe5900000|rd_rn_rm(hr,FP,0)|offset);
  }
}

static void emit_storereg(int r, int hr)
{
  assert(hr != EXCLUDE_REG);
  void *addr;
  switch (r) {
  //case HIREG: addr = &hi; break;
  //case LOREG: addr = &lo; break;
  case CCREG: addr = &cycle_count; break;
  default: assert(r < 34u); addr = &psxRegs.GPR.r[r]; break;
  }
  uintptr_t offset = (char *)addr - (char *)&dynarec_local;
  assert(offset < 4096u);
  assem_debug("str %s,fp+%d # r%d\n",regname[hr],offset,r);
  output_w32(0xe5800000|rd_rn_rm(hr,FP,0)|offset);
}

static void emit_test(int rs, int rt)
{
  assem_debug("tst %s,%s\n",regname[rs],regname[rt]);
  output_w32(0xe1100000|rd_rn_rm(0,rs,rt));
}

static void emit_testimm(int rs,int imm)
{
  u_int armval;
  assem_debug("tst %s,#%d\n",regname[rs],imm);
  genimm_checked(imm,&armval);
  output_w32(0xe3100000|rd_rn_rm(0,rs,0)|armval);
}

static void emit_testeqimm(int rs,int imm)
{
  u_int armval;
  assem_debug("tsteq %s,$%d\n",regname[rs],imm);
  genimm_checked(imm,&armval);
  output_w32(0x03100000|rd_rn_rm(0,rs,0)|armval);
}

static void emit_not(int rs,int rt)
{
  assem_debug("mvn %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe1e00000|rd_rn_rm(rt,0,rs));
}

static void emit_mvneq(int rs,int rt)
{
  assem_debug("mvneq %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x01e00000|rd_rn_rm(rt,0,rs));
}

static void emit_and(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("and %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0000000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_or(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("orr %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe1800000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_orrshl_imm(u_int rs,u_int imm,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(imm<32);
  assem_debug("orr %s,%s,%s,lsl #%d\n",regname[rt],regname[rt],regname[rs],imm);
  output_w32(0xe1800000|rd_rn_rm(rt,rt,rs)|(imm<<7));
}

static void emit_orrshr_imm(u_int rs,u_int imm,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(imm<32);
  assem_debug("orr %s,%s,%s,lsr #%d\n",regname[rt],regname[rt],regname[rs],imm);
  output_w32(0xe1800020|rd_rn_rm(rt,rt,rs)|(imm<<7));
}

static void emit_xor(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("eor %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe0200000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_xorsar_imm(u_int rs1,u_int rs2,u_int imm,u_int rt)
{
  assem_debug("eor %s,%s,%s,asr #%d\n",regname[rt],regname[rs1],regname[rs2],imm);
  output_w32(0xe0200040|rd_rn_rm(rt,rs1,rs2)|(imm<<7));
}

static void emit_addimm(u_int rs,int imm,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  if(imm!=0) {
    u_int armval;
    if(genimm(imm,&armval)) {
      assem_debug("add %s,%s,#%d\n",regname[rt],regname[rs],imm);
      output_w32(0xe2800000|rd_rn_rm(rt,rs,0)|armval);
    }else if(genimm(-imm,&armval)) {
      assem_debug("sub %s,%s,#%d\n",regname[rt],regname[rs],-imm);
      output_w32(0xe2400000|rd_rn_rm(rt,rs,0)|armval);
    #ifdef HAVE_ARMV7
    }else if(rt!=rs&&(u_int)imm<65536) {
      emit_movw(imm&0x0000ffff,rt);
      emit_add(rs,rt,rt);
    }else if(rt!=rs&&(u_int)-imm<65536) {
      emit_movw(-imm&0x0000ffff,rt);
      emit_sub(rs,rt,rt);
    #endif
    }else if((u_int)-imm<65536) {
      assem_debug("sub %s,%s,#%d\n",regname[rt],regname[rs],(-imm)&0xFF00);
      assem_debug("sub %s,%s,#%d\n",regname[rt],regname[rt],(-imm)&0xFF);
      output_w32(0xe2400000|rd_rn_imm_shift(rt,rs,(-imm)>>8,8));
      output_w32(0xe2400000|rd_rn_imm_shift(rt,rt,(-imm)&0xff,0));
    }else {
      do {
        int shift = (ffs(imm) - 1) & ~1;
        int imm8 = imm & (0xff << shift);
        genimm_checked(imm8,&armval);
        assem_debug("add %s,%s,#0x%x\n",regname[rt],regname[rs],imm8);
        output_w32(0xe2800000|rd_rn_rm(rt,rs,0)|armval);
        rs = rt;
        imm &= ~imm8;
      }
      while (imm != 0);
    }
  }
  else if(rs!=rt) emit_mov(rs,rt);
}

static void emit_addimm_ptr(u_int rs, uintptr_t imm, u_int rt)
{
  emit_addimm(rs, imm, rt);
}

static void emit_addimm_and_set_flags3(u_int rs, int imm, u_int rt)
{
  assert(imm>-65536&&imm<65536);
  u_int armval;
  if (genimm(imm, &armval)) {
    assem_debug("adds %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe2900000|rd_rn_rm(rt,rs,0)|armval);
  } else if (genimm(-imm, &armval)) {
    assem_debug("subs %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe2500000|rd_rn_rm(rt,rs,0)|armval);
  } else if (rs != rt) {
    emit_movimm(imm, rt);
    emit_adds(rs, rt, rt);
  } else if (imm < 0) {
    assem_debug("sub %s,%s,#%d\n",regname[rt],regname[rs],(-imm)&0xFF00);
    assem_debug("subs %s,%s,#%d\n",regname[rt],regname[rt],(-imm)&0xFF);
    output_w32(0xe2400000|rd_rn_imm_shift(rt,rs,(-imm)>>8,8));
    output_w32(0xe2500000|rd_rn_imm_shift(rt,rt,(-imm)&0xff,0));
  } else {
    assem_debug("add %s,%s,#%d\n",regname[rt],regname[rs],imm&0xFF00);
    assem_debug("adds %s,%s,#%d\n",regname[rt],regname[rt],imm&0xFF);
    output_w32(0xe2800000|rd_rn_imm_shift(rt,rs,imm>>8,8));
    output_w32(0xe2900000|rd_rn_imm_shift(rt,rt,imm&0xff,0));
  }
}

static void emit_addimm_and_set_flags(int imm, u_int rt)
{
  emit_addimm_and_set_flags3(rt, imm, rt);
}

static void emit_addnop(u_int r)
{
  assert(r<16);
  assem_debug("add %s,%s,#0 (nop)\n",regname[r],regname[r]);
  output_w32(0xe2800000|rd_rn_rm(r,r,0));
}

static void emit_andimm(int rs,int imm,int rt)
{
  u_int armval;
  if(imm==0) {
    emit_zeroreg(rt);
  }else if(genimm(imm,&armval)) {
    assem_debug("and %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe2000000|rd_rn_rm(rt,rs,0)|armval);
  }else if(genimm(~imm,&armval)) {
    assem_debug("bic %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe3c00000|rd_rn_rm(rt,rs,0)|armval);
  }else if(imm==65535) {
    #ifndef HAVE_ARMV6
    assem_debug("bic %s,%s,#FF000000\n",regname[rt],regname[rs]);
    output_w32(0xe3c00000|rd_rn_rm(rt,rs,0)|0x4FF);
    assem_debug("bic %s,%s,#00FF0000\n",regname[rt],regname[rt]);
    output_w32(0xe3c00000|rd_rn_rm(rt,rt,0)|0x8FF);
    #else
    assem_debug("uxth %s,%s\n",regname[rt],regname[rs]);
    output_w32(0xe6ff0070|rd_rn_rm(rt,0,rs));
    #endif
  }else{
    assert(imm>0&&imm<65535);
    #ifndef HAVE_ARMV7
    assem_debug("mov r14,#%d\n",imm&0xFF00);
    output_w32(0xe3a00000|rd_rn_imm_shift(HOST_TEMPREG,0,imm>>8,8));
    assem_debug("add r14,r14,#%d\n",imm&0xFF);
    output_w32(0xe2800000|rd_rn_imm_shift(HOST_TEMPREG,HOST_TEMPREG,imm&0xff,0));
    #else
    emit_movw(imm,HOST_TEMPREG);
    #endif
    assem_debug("and %s,%s,r14\n",regname[rt],regname[rs]);
    output_w32(0xe0000000|rd_rn_rm(rt,rs,HOST_TEMPREG));
  }
}

static void emit_orimm(int rs,int imm,int rt)
{
  u_int armval;
  if(imm==0) {
    if(rs!=rt) emit_mov(rs,rt);
  }else if(genimm(imm,&armval)) {
    assem_debug("orr %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe3800000|rd_rn_rm(rt,rs,0)|armval);
  }else{
    assert(imm>0&&imm<65536);
    assem_debug("orr %s,%s,#%d\n",regname[rt],regname[rs],imm&0xFF00);
    assem_debug("orr %s,%s,#%d\n",regname[rt],regname[rs],imm&0xFF);
    output_w32(0xe3800000|rd_rn_imm_shift(rt,rs,imm>>8,8));
    output_w32(0xe3800000|rd_rn_imm_shift(rt,rt,imm&0xff,0));
  }
}

static void emit_xorimm(int rs,int imm,int rt)
{
  u_int armval;
  if(imm==0) {
    if(rs!=rt) emit_mov(rs,rt);
  }else if(genimm(imm,&armval)) {
    assem_debug("eor %s,%s,#%d\n",regname[rt],regname[rs],imm);
    output_w32(0xe2200000|rd_rn_rm(rt,rs,0)|armval);
  }else{
    assert(imm>0&&imm<65536);
    assem_debug("eor %s,%s,#%d\n",regname[rt],regname[rs],imm&0xFF00);
    assem_debug("eor %s,%s,#%d\n",regname[rt],regname[rs],imm&0xFF);
    output_w32(0xe2200000|rd_rn_imm_shift(rt,rs,imm>>8,8));
    output_w32(0xe2200000|rd_rn_imm_shift(rt,rt,imm&0xff,0));
  }
}

static void emit_shlimm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  //if(imm==1) ...
  assem_debug("lsl %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|(imm<<7));
}

static void emit_lsls_imm(int rs,int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("lsls %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe1b00000|rd_rn_rm(rt,0,rs)|(imm<<7));
}

static attr_unused void emit_lslpls_imm(int rs,int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("lslpls %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x51b00000|rd_rn_rm(rt,0,rs)|(imm<<7));
}

static void emit_shrimm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("lsr %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x20|(imm<<7));
}

static void emit_sarimm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("asr %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x40|(imm<<7));
}

static void emit_rorimm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("ror %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x60|(imm<<7));
}

static void emit_signextend16(int rs,int rt)
{
  #ifndef HAVE_ARMV6
  emit_shlimm(rs,16,rt);
  emit_sarimm(rt,16,rt);
  #else
  assem_debug("sxth %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe6bf0070|rd_rn_rm(rt,0,rs));
  #endif
}

static void emit_signextend8(int rs,int rt)
{
  #ifndef HAVE_ARMV6
  emit_shlimm(rs,24,rt);
  emit_sarimm(rt,24,rt);
  #else
  assem_debug("sxtb %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe6af0070|rd_rn_rm(rt,0,rs));
  #endif
}

static void emit_shl(u_int rs,u_int shift,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(shift<16);
  //if(imm==1) ...
  assem_debug("lsl %s,%s,%s\n",regname[rt],regname[rs],regname[shift]);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x10|(shift<<8));
}

static void emit_shr(u_int rs,u_int shift,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(shift<16);
  assem_debug("lsr %s,%s,%s\n",regname[rt],regname[rs],regname[shift]);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x30|(shift<<8));
}

static void emit_sar(u_int rs,u_int shift,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(shift<16);
  assem_debug("asr %s,%s,%s\n",regname[rt],regname[rs],regname[shift]);
  output_w32(0xe1a00000|rd_rn_rm(rt,0,rs)|0x50|(shift<<8));
}

static attr_unused void emit_orrshl(u_int rs,u_int shift,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(shift<16);
  assem_debug("orr %s,%s,%s,lsl %s\n",regname[rt],regname[rt],regname[rs],regname[shift]);
  output_w32(0xe1800000|rd_rn_rm(rt,rt,rs)|0x10|(shift<<8));
}

static attr_unused void emit_orrshr(u_int rs,u_int shift,u_int rt)
{
  assert(rs<16);
  assert(rt<16);
  assert(shift<16);
  assem_debug("orr %s,%s,%s,lsr %s\n",regname[rt],regname[rt],regname[rs],regname[shift]);
  output_w32(0xe1800000|rd_rn_rm(rt,rt,rs)|0x30|(shift<<8));
}

static void emit_cmpimm(int rs,int imm)
{
  u_int armval;
  if(genimm(imm,&armval)) {
    assem_debug("cmp %s,#%d\n",regname[rs],imm);
    output_w32(0xe3500000|rd_rn_rm(0,rs,0)|armval);
  }else if(genimm(-imm,&armval)) {
    assem_debug("cmn %s,#%d\n",regname[rs],imm);
    output_w32(0xe3700000|rd_rn_rm(0,rs,0)|armval);
  }else if(imm>0) {
    assert(imm<65536);
    emit_movimm(imm,HOST_TEMPREG);
    assem_debug("cmp %s,r14\n",regname[rs]);
    output_w32(0xe1500000|rd_rn_rm(0,rs,HOST_TEMPREG));
  }else{
    assert(imm>-65536);
    emit_movimm(-imm,HOST_TEMPREG);
    assem_debug("cmn %s,r14\n",regname[rs]);
    output_w32(0xe1700000|rd_rn_rm(0,rs,HOST_TEMPREG));
  }
}

static void emit_cmovne_imm(int imm,int rt)
{
  assem_debug("movne %s,#%d\n",regname[rt],imm);
  u_int armval;
  genimm_checked(imm,&armval);
  output_w32(0x13a00000|rd_rn_rm(rt,0,0)|armval);
}

static void emit_cmovl_imm(int imm,int rt)
{
  assem_debug("movlt %s,#%d\n",regname[rt],imm);
  u_int armval;
  genimm_checked(imm,&armval);
  output_w32(0xb3a00000|rd_rn_rm(rt,0,0)|armval);
}

static void emit_cmovb_imm(int imm,int rt)
{
  assem_debug("movcc %s,#%d\n",regname[rt],imm);
  u_int armval;
  genimm_checked(imm,&armval);
  output_w32(0x33a00000|rd_rn_rm(rt,0,0)|armval);
}

static void emit_cmovae_imm(int imm,int rt)
{
  assem_debug("movcs %s,#%d\n",regname[rt],imm);
  u_int armval;
  genimm_checked(imm,&armval);
  output_w32(0x23a00000|rd_rn_rm(rt,0,0)|armval);
}

static void emit_cmovs_imm(int imm,int rt)
{
  assem_debug("movmi %s,#%d\n",regname[rt],imm);
  u_int armval;
  genimm_checked(imm,&armval);
  output_w32(0x43a00000|rd_rn_rm(rt,0,0)|armval);
}

static attr_unused void emit_cmovne_reg(int rs,int rt)
{
  assem_debug("movne %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x11a00000|rd_rn_rm(rt,0,rs));
}

static void emit_cmovl_reg(int rs,int rt)
{
  assem_debug("movlt %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xb1a00000|rd_rn_rm(rt,0,rs));
}

static void emit_cmovb_reg(int rs,int rt)
{
  assem_debug("movcc %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x31a00000|rd_rn_rm(rt,0,rs));
}

static void emit_cmovs_reg(int rs,int rt)
{
  assem_debug("movmi %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x41a00000|rd_rn_rm(rt,0,rs));
}

static void emit_slti32(int rs,int imm,int rt)
{
  if(rs!=rt) emit_zeroreg(rt);
  emit_cmpimm(rs,imm);
  if(rs==rt) emit_movimm(0,rt);
  emit_cmovl_imm(1,rt);
}

static void emit_sltiu32(int rs,int imm,int rt)
{
  if(rs!=rt) emit_zeroreg(rt);
  emit_cmpimm(rs,imm);
  if(rs==rt) emit_movimm(0,rt);
  emit_cmovb_imm(1,rt);
}

static void emit_cmp(int rs,int rt)
{
  assem_debug("cmp %s,%s\n",regname[rs],regname[rt]);
  output_w32(0xe1500000|rd_rn_rm(0,rs,rt));
}

static void emit_cmpcs(int rs,int rt)
{
  assem_debug("cmpcs %s,%s\n",regname[rs],regname[rt]);
  output_w32(0x21500000|rd_rn_rm(0,rs,rt));
}

static void emit_set_gz32(int rs, int rt)
{
  //assem_debug("set_gz32\n");
  emit_cmpimm(rs,1);
  emit_movimm(1,rt);
  emit_cmovl_imm(0,rt);
}

static void emit_set_nz32(int rs, int rt)
{
  //assem_debug("set_nz32\n");
  if(rs!=rt) emit_movs(rs,rt);
  else emit_test(rs,rs);
  emit_cmovne_imm(1,rt);
}

static void emit_set_if_less32(int rs1, int rs2, int rt)
{
  //assem_debug("set if less (%%%s,%%%s),%%%s\n",regname[rs1],regname[rs2],regname[rt]);
  if(rs1!=rt&&rs2!=rt) emit_zeroreg(rt);
  emit_cmp(rs1,rs2);
  if(rs1==rt||rs2==rt) emit_movimm(0,rt);
  emit_cmovl_imm(1,rt);
}

static void emit_set_if_carry32(int rs1, int rs2, int rt)
{
  //assem_debug("set if carry (%%%s,%%%s),%%%s\n",regname[rs1],regname[rs2],regname[rt]);
  if(rs1!=rt&&rs2!=rt) emit_zeroreg(rt);
  emit_cmp(rs1,rs2);
  if(rs1==rt||rs2==rt) emit_movimm(0,rt);
  emit_cmovb_imm(1,rt);
}

static int can_jump_or_call(const void *a)
{
  intptr_t offset = (u_char *)a - out - 8;
  return (-33554432 <= offset && offset < 33554432);
}

static void emit_call(const void *a_)
{
  int a = (int)a_;
  assem_debug("bl %p%s\n", log_addr(a), func_name(a_));
  u_int offset=genjmp(a);
  output_w32(0xeb000000|offset);
}

static void emit_jmp(const void *a_)
{
  int a = (int)a_;
  assem_debug("b %p%s\n", log_addr(a_), func_name(a_));
  u_int offset=genjmp(a);
  output_w32(0xea000000|offset);
}

static void emit_jne(const void *a_)
{
  int a = (int)a_;
  assem_debug("bne %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x1a000000|offset);
}

static void emit_jeq(const void *a_)
{
  int a = (int)a_;
  assem_debug("beq %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x0a000000|offset);
}

static void emit_js(const void *a_)
{
  int a = (int)a_;
  assem_debug("bmi %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x4a000000|offset);
}

static void emit_jns(const void *a_)
{
  int a = (int)a_;
  assem_debug("bpl %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x5a000000|offset);
}

static void emit_jl(const void *a_)
{
  int a = (int)a_;
  assem_debug("blt %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0xba000000|offset);
}

static void emit_jge(const void *a_)
{
  int a = (int)a_;
  assem_debug("bge %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0xaa000000|offset);
}

static void emit_jo(const void *a_)
{
  int a = (int)a_;
  assem_debug("bvs %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x6a000000|offset);
}

static void emit_jno(const void *a_)
{
  int a = (int)a_;
  assem_debug("bvc %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x7a000000|offset);
}

static void emit_jc(const void *a_)
{
  int a = (int)a_;
  assem_debug("bcs %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x2a000000|offset);
}

static void emit_jcc(const void *a_)
{
  int a = (int)a_;
  assem_debug("bcc %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x3a000000|offset);
}

static void *emit_cbz(int rs, const void *a)
{
  void *ret;
  emit_test(rs, rs);
  ret = out;
  emit_jeq(a);
  return ret;
}

static attr_unused void emit_callreg(u_int r)
{
  assert(r<15);
  assem_debug("blx %s\n",regname[r]);
  output_w32(0xe12fff30|r);
}

static void emit_jmpreg(u_int r)
{
  assem_debug("mov pc,%s\n",regname[r]);
  output_w32(0xe1a00000|rd_rn_rm(15,0,r));
}

static void emit_ret(void)
{
  emit_jmpreg(14);
}

static void emit_readword_indexed(int offset, int rs, int rt)
{
  assert(offset>-4096&&offset<4096);
  assem_debug("ldr %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe5900000|rd_rn_rm(rt,rs,0)|offset);
  }else{
    output_w32(0xe5100000|rd_rn_rm(rt,rs,0)|(-offset));
  }
}

static void emit_readword_dualindexedx4(int rs1, int rs2, int rt)
{
  assem_debug("ldr %s,%s,%s lsl #2\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe7900000|rd_rn_rm(rt,rs1,rs2)|0x100);
}
#define emit_readptr_dualindexedx_ptrlen emit_readword_dualindexedx4

static void emit_ldr_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldr %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe7900000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrcc_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrcc %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x37900000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe7d00000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrccb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrccb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x37d00000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrsb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrsb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe19000d0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrccsb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrccsb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x319000d0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrh_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrh %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe19000b0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrcch_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrcch %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x319000b0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrsh_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrsh %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe19000f0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_ldrccsh_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("ldrccsh %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x319000f0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_str_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("str %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe7800000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_strb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("strb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe7c00000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_strh_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("strh %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0xe18000b0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_movsbl_indexed(int offset, int rs, int rt)
{
  assert(offset>-256&&offset<256);
  assem_debug("ldrsb %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe1d000d0|rd_rn_rm(rt,rs,0)|((offset<<4)&0xf00)|(offset&0xf));
  }else{
    output_w32(0xe15000d0|rd_rn_rm(rt,rs,0)|(((-offset)<<4)&0xf00)|((-offset)&0xf));
  }
}

static void emit_movswl_indexed(int offset, int rs, int rt)
{
  assert(offset>-256&&offset<256);
  assem_debug("ldrsh %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe1d000f0|rd_rn_rm(rt,rs,0)|((offset<<4)&0xf00)|(offset&0xf));
  }else{
    output_w32(0xe15000f0|rd_rn_rm(rt,rs,0)|(((-offset)<<4)&0xf00)|((-offset)&0xf));
  }
}

static void emit_movzbl_indexed(int offset, int rs, int rt)
{
  assert(offset>-4096&&offset<4096);
  assem_debug("ldrb %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe5d00000|rd_rn_rm(rt,rs,0)|offset);
  }else{
    output_w32(0xe5500000|rd_rn_rm(rt,rs,0)|(-offset));
  }
}

static void emit_movzwl_indexed(int offset, int rs, int rt)
{
  assert(offset>-256&&offset<256);
  assem_debug("ldrh %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe1d000b0|rd_rn_rm(rt,rs,0)|((offset<<4)&0xf00)|(offset&0xf));
  }else{
    output_w32(0xe15000b0|rd_rn_rm(rt,rs,0)|(((-offset)<<4)&0xf00)|((-offset)&0xf));
  }
}

static void emit_ldrd(int offset, int rs, int rt)
{
  assert(offset>-256&&offset<256);
  assem_debug("ldrd %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe1c000d0|rd_rn_rm(rt,rs,0)|((offset<<4)&0xf00)|(offset&0xf));
  }else{
    output_w32(0xe14000d0|rd_rn_rm(rt,rs,0)|(((-offset)<<4)&0xf00)|((-offset)&0xf));
  }
}

static void emit_readword(void *addr, int rt)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  assert(offset<4096);
  assem_debug("ldr %s,fp+%#x%s\n", regname[rt], offset, fpofs_name(offset));
  output_w32(0xe5900000|rd_rn_rm(rt,FP,0)|offset);
}
#define emit_readptr emit_readword

static void emit_writeword_indexed(int rt, int offset, int rs)
{
  assert(offset>-4096&&offset<4096);
  assem_debug("str %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe5800000|rd_rn_rm(rt,rs,0)|offset);
  }else{
    output_w32(0xe5000000|rd_rn_rm(rt,rs,0)|(-offset));
  }
}

static void emit_writehword_indexed(int rt, int offset, int rs)
{
  assert(offset>-256&&offset<256);
  assem_debug("strh %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe1c000b0|rd_rn_rm(rt,rs,0)|((offset<<4)&0xf00)|(offset&0xf));
  }else{
    output_w32(0xe14000b0|rd_rn_rm(rt,rs,0)|(((-offset)<<4)&0xf00)|((-offset)&0xf));
  }
}

static void emit_writebyte_indexed(int rt, int offset, int rs)
{
  assert(offset>-4096&&offset<4096);
  assem_debug("strb %s,%s+%d\n",regname[rt],regname[rs],offset);
  if(offset>=0) {
    output_w32(0xe5c00000|rd_rn_rm(rt,rs,0)|offset);
  }else{
    output_w32(0xe5400000|rd_rn_rm(rt,rs,0)|(-offset));
  }
}

static void emit_strcc_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("strcc %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x37800000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_strccb_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("strccb %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x37c00000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_strcch_dualindexed(int rs1, int rs2, int rt)
{
  assem_debug("strcch %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x318000b0|rd_rn_rm(rt,rs1,rs2));
}

static void emit_writeword(int rt, void *addr)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  assert(offset<4096);
  assem_debug("str %s,fp+%#x%s\n", regname[rt], offset, fpofs_name(offset));
  output_w32(0xe5800000|rd_rn_rm(rt,FP,0)|offset);
}

static void emit_umull(u_int rs1, u_int rs2, u_int hi, u_int lo)
{
  assem_debug("umull %s, %s, %s, %s\n",regname[lo],regname[hi],regname[rs1],regname[rs2]);
  assert(rs1<16);
  assert(rs2<16);
  assert(hi<16);
  assert(lo<16);
  output_w32(0xe0800090|(hi<<16)|(lo<<12)|(rs2<<8)|rs1);
}

static void emit_smull(u_int rs1, u_int rs2, u_int hi, u_int lo)
{
  assem_debug("smull %s, %s, %s, %s\n",regname[lo],regname[hi],regname[rs1],regname[rs2]);
  assert(rs1<16);
  assert(rs2<16);
  assert(hi<16);
  assert(lo<16);
  output_w32(0xe0c00090|(hi<<16)|(lo<<12)|(rs2<<8)|rs1);
}

static void emit_clz(int rs,int rt)
{
  assem_debug("clz %s,%s\n",regname[rt],regname[rs]);
  output_w32(0xe16f0f10|rd_rn_rm(rt,0,rs));
}

static void emit_subcs(int rs1,int rs2,int rt)
{
  assem_debug("subcs %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x20400000|rd_rn_rm(rt,rs1,rs2));
}

static void emit_shrcc_imm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("lsrcc %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x31a00000|rd_rn_rm(rt,0,rs)|0x20|(imm<<7));
}

static void emit_shrne_imm(int rs,u_int imm,int rt)
{
  assert(imm>0);
  assert(imm<32);
  assem_debug("lsrne %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x11a00000|rd_rn_rm(rt,0,rs)|0x20|(imm<<7));
}

static void emit_negmi(int rs, int rt)
{
  assem_debug("rsbmi %s,%s,#0\n",regname[rt],regname[rs]);
  output_w32(0x42600000|rd_rn_rm(rt,rs,0));
}

static void emit_negsmi(int rs, int rt)
{
  assem_debug("rsbsmi %s,%s,#0\n",regname[rt],regname[rs]);
  output_w32(0x42700000|rd_rn_rm(rt,rs,0));
}

static void emit_bic_lsl(u_int rs1,u_int rs2,u_int shift,u_int rt)
{
  assem_debug("bic %s,%s,%s lsl %s\n",regname[rt],regname[rs1],regname[rs2],regname[shift]);
  output_w32(0xe1C00000|rd_rn_rm(rt,rs1,rs2)|0x10|(shift<<8));
}

static void emit_bic_lsr(u_int rs1,u_int rs2,u_int shift,u_int rt)
{
  assem_debug("bic %s,%s,%s lsr %s\n",regname[rt],regname[rs1],regname[rs2],regname[shift]);
  output_w32(0xe1C00000|rd_rn_rm(rt,rs1,rs2)|0x30|(shift<<8));
}

static void emit_teq(int rs, int rt)
{
  assem_debug("teq %s,%s\n",regname[rs],regname[rt]);
  output_w32(0xe1300000|rd_rn_rm(0,rs,rt));
}

static attr_unused void emit_rsbimm(int rs, int imm, int rt)
{
  u_int armval;
  genimm_checked(imm,&armval);
  assem_debug("rsb %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xe2600000|rd_rn_rm(rt,rs,0)|armval);
}

// Conditionally select one of two immediates, optimizing for small code size
// This will only be called if HAVE_CMOV_IMM is defined
static void emit_cmov2imm_e_ne_compact(int imm1,int imm2,u_int rt)
{
  u_int armval;
  if(genimm(imm2-imm1,&armval)) {
    emit_movimm(imm1,rt);
    assem_debug("addne %s,%s,#%d\n",regname[rt],regname[rt],imm2-imm1);
    output_w32(0x12800000|rd_rn_rm(rt,rt,0)|armval);
  }else if(genimm(imm1-imm2,&armval)) {
    emit_movimm(imm1,rt);
    assem_debug("subne %s,%s,#%d\n",regname[rt],regname[rt],imm1-imm2);
    output_w32(0x12400000|rd_rn_rm(rt,rt,0)|armval);
  }
  else {
    #ifndef HAVE_ARMV7
    emit_movimm(imm1,rt);
    add_literal((int)out,imm2);
    assem_debug("ldrne %s,pc+? [=%x]\n",regname[rt],imm2);
    output_w32(0x15900000|rd_rn_rm(rt,15,0));
    #else
    emit_movw(imm1&0x0000FFFF,rt);
    if((imm1&0xFFFF)!=(imm2&0xFFFF)) {
      assem_debug("movwne %s,#%d (0x%x)\n",regname[rt],imm2&0xFFFF,imm2&0xFFFF);
      output_w32(0x13000000|rd_rn_rm(rt,0,0)|(imm2&0xfff)|((imm2<<4)&0xf0000));
    }
    emit_movt(imm1&0xFFFF0000,rt);
    if((imm1&0xFFFF0000)!=(imm2&0xFFFF0000)) {
      assem_debug("movtne %s,#%d (0x%x)\n",regname[rt],imm2&0xffff0000,imm2&0xffff0000);
      output_w32(0x13400000|rd_rn_rm(rt,0,0)|((imm2>>16)&0xfff)|((imm2>>12)&0xf0000));
    }
    #endif
  }
}

// special case for checking invalid_code
static void emit_ldrb_indexedsr12_reg(int base, int r, int rt)
{
  assem_debug("ldrb %s,%s,%s lsr #12\n",regname[rt],regname[base],regname[r]);
  output_w32(0xe7d00000|rd_rn_rm(rt,base,r)|0x620);
}

static void emit_callne(const void *a_)
{
  int a = (int)a_;
  assem_debug("blne %p\n", log_addr(a_));
  u_int offset=genjmp(a);
  output_w32(0x1b000000|offset);
}

// Used to preload hash table entries
static attr_unused void emit_prefetchreg(int r)
{
  assem_debug("pld %s\n",regname[r]);
  output_w32(0xf5d0f000|rd_rn_rm(0,r,0));
}

// Special case for mini_ht
static void emit_ldreq_indexed(int rs, u_int offset, int rt)
{
  assert(offset<4096);
  assem_debug("ldreq %s,[%s, #%d]\n",regname[rt],regname[rs],offset);
  output_w32(0x05900000|rd_rn_rm(rt,rs,0)|offset);
}

static void emit_orrne_imm(int rs,int imm,int rt)
{
  u_int armval;
  genimm_checked(imm,&armval);
  assem_debug("orrne %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x13800000|rd_rn_rm(rt,rs,0)|armval);
}

static attr_unused void emit_addpl_imm(int rs,int imm,int rt)
{
  u_int armval;
  genimm_checked(imm,&armval);
  assem_debug("addpl %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x52800000|rd_rn_rm(rt,rs,0)|armval);
}

static void emit_jno_unlikely(void *a_)
{
  //emit_jno(a_);
  assert(a_ == NULL);
  assem_debug("addvc pc,pc,#? (%p)\n", /*a-(int)out-8,*/ log_addr(a_));
  output_w32(0x72800000|rd_rn_rm(15,15,0));
}

static void save_regs_all(u_int reglist)
{
  int i;
  if(!reglist) return;
  assem_debug("stmia fp,{");
  for(i=0;i<16;i++)
    if(reglist&(1<<i))
      assem_debug("r%d,",i);
  assem_debug("}\n");
  output_w32(0xe88b0000|reglist);
}

static void restore_regs_all(u_int reglist)
{
  int i;
  if(!reglist) return;
  assem_debug("ldmia fp,{");
  for(i=0;i<16;i++)
    if(reglist&(1<<i))
      assem_debug("r%d,",i);
  assem_debug("}\n");
  output_w32(0xe89b0000|reglist);
}

// Save registers before function call
static void save_regs(u_int reglist)
{
  reglist&=CALLER_SAVE_REGS; // only save the caller-save registers, r0-r3, r12
  save_regs_all(reglist);
}

// Restore registers after function call
static void restore_regs(u_int reglist)
{
  reglist&=CALLER_SAVE_REGS;
  restore_regs_all(reglist);
}

/* Stubs/epilogue */

static void literal_pool(int n)
{
  if(!literalcount) return;
  if(n) {
    if((int)out-literals[0][0]<4096-n) return;
  }
  u_int *ptr;
  int i;
  for(i=0;i<literalcount;i++)
  {
    u_int l_addr=(u_int)out;
    int j;
    for(j=0;j<i;j++) {
      if(literals[j][1]==literals[i][1]) {
        //printf("dup %08x\n",literals[i][1]);
        l_addr=literals[j][0];
        break;
      }
    }
    ptr=(u_int *)literals[i][0];
    u_int offset=l_addr-(u_int)ptr-8;
    assert(offset<4096);
    assert(!(offset&3));
    *ptr|=offset;
    if(l_addr==(u_int)out) {
      literals[i][0]=l_addr; // remember for dupes
      output_w32(literals[i][1]);
    }
  }
  literalcount=0;
}

static void literal_pool_jumpover(int n)
{
  if(!literalcount) return;
  if(n) {
    if((int)out-literals[0][0]<4096-n) return;
  }
  void *jaddr = out;
  emit_jmp(0);
  literal_pool(0);
  set_jump_target(jaddr, out);
}

// parsed by find_extjump_insn, check_extjump2
static void emit_extjump(u_char *addr, u_int target)
{
  u_char *ptr=(u_char *)addr;
  assert((ptr[3]&0x0e)==0xa);
  (void)ptr;

  emit_loadlp(target,0);
  emit_loadlp((u_int)addr,1);
  assert(ndrc->translation_cache <= addr &&
         addr < ndrc->translation_cache + sizeof(ndrc->translation_cache));
  emit_far_jump(dyna_linker);
}

static void check_extjump2(void *src)
{
  u_int *ptr = src;
  assert((ptr[1] & 0x0fff0000) == 0x059f0000); // ldr rx, [pc, #ofs]
  (void)ptr;
}

// put rt_val into rt, potentially making use of rs with value rs_val
static void emit_movimm_from(u_int rs_val,int rs,u_int rt_val,int rt)
{
  u_int armval;
  int diff;
  if(genimm(rt_val,&armval)) {
    assem_debug("mov %s,#%d\n",regname[rt],rt_val);
    output_w32(0xe3a00000|rd_rn_rm(rt,0,0)|armval);
    return;
  }
  if(genimm(~rt_val,&armval)) {
    assem_debug("mvn %s,#%d\n",regname[rt],rt_val);
    output_w32(0xe3e00000|rd_rn_rm(rt,0,0)|armval);
    return;
  }
  diff=rt_val-rs_val;
  if(genimm(diff,&armval)) {
    assem_debug("add %s,%s,#%d\n",regname[rt],regname[rs],diff);
    output_w32(0xe2800000|rd_rn_rm(rt,rs,0)|armval);
    return;
  }else if(genimm(-diff,&armval)) {
    assem_debug("sub %s,%s,#%d\n",regname[rt],regname[rs],-diff);
    output_w32(0xe2400000|rd_rn_rm(rt,rs,0)|armval);
    return;
  }
  emit_movimm(rt_val,rt);
}

// return 1 if above function can do it's job cheaply
static int is_similar_value(u_int v1,u_int v2)
{
  u_int xs;
  int diff;
  if(v1==v2) return 1;
  diff=v2-v1;
  for(xs=diff;xs!=0&&(xs&3)==0;xs>>=2)
    ;
  if(xs<0x100) return 1;
  for(xs=-diff;xs!=0&&(xs&3)==0;xs>>=2)
    ;
  if(xs<0x100) return 1;
  return 0;
}

static void mov_loadtype_adj(enum stub_type type,int rs,int rt)
{
  switch(type) {
    case LOADB_STUB:  emit_signextend8(rs,rt); break;
    case LOADBU_STUB: emit_andimm(rs,0xff,rt); break;
    case LOADH_STUB:  emit_signextend16(rs,rt); break;
    case LOADHU_STUB: emit_andimm(rs,0xffff,rt); break;
    case LOADW_STUB:  if(rs!=rt) emit_mov(rs,rt); break;
    default: assert(0);
  }
}

#include "pcsxmem.h"
#include "pcsxmem_inline.c"

static void do_readstub(int n)
{
  assem_debug("do_readstub %p\n", log_addr(start + stubs[n].a*4));
  literal_pool(256);
  set_jump_target(stubs[n].addr, out);
  enum stub_type type=stubs[n].type;
  int i=stubs[n].a;
  int rs=stubs[n].b;
  const struct regstat *i_regs=(struct regstat *)stubs[n].c;
  u_int reglist=stubs[n].e;
  const signed char *i_regmap=i_regs->regmap;
  int rt;
  if(dops[i].itype==C2LS||dops[i].itype==LOADLR) {
    rt=get_reg(i_regmap,FTEMP);
  }else{
    rt=get_reg(i_regmap,dops[i].rt1);
  }
  assert(rs>=0);
  int r,temp=-1,temp2=HOST_TEMPREG,regs_saved=0;
  void *restore_jump = NULL;
  reglist|=(1<<rs);
  for(r=0;r<=12;r++) {
    if(((1<<r)&0x13ff)&&((1<<r)&reglist)==0) {
      temp=r; break;
    }
  }
  if(rt>=0&&dops[i].rt1!=0)
    reglist&=~(1<<rt);
  if(temp==-1) {
    save_regs(reglist);
    regs_saved=1;
    temp=(rs==0)?2:0;
  }
  if((regs_saved||(reglist&2)==0)&&temp!=1&&rs!=1)
    temp2=1;
  emit_readword(&mem_rtab,temp);
  emit_shrimm(rs,12,temp2);
  emit_readword_dualindexedx4(temp,temp2,temp2);
  emit_lsls_imm(temp2,1,temp2);
  if(dops[i].itype==C2LS||(rt>=0&&dops[i].rt1!=0)) {
    switch(type) {
      case LOADB_STUB:  emit_ldrccsb_dualindexed(temp2,rs,rt); break;
      case LOADBU_STUB: emit_ldrccb_dualindexed(temp2,rs,rt); break;
      case LOADH_STUB:  emit_ldrccsh_dualindexed(temp2,rs,rt); break;
      case LOADHU_STUB: emit_ldrcch_dualindexed(temp2,rs,rt); break;
      case LOADW_STUB:  emit_ldrcc_dualindexed(temp2,rs,rt); break;
      default: assert(0);
    }
  }
  if(regs_saved) {
    restore_jump=out;
    emit_jcc(0); // jump to reg restore
  }
  else
    emit_jcc(stubs[n].retaddr); // return address

  if(!regs_saved)
    save_regs(reglist);
  void *handler=NULL;
  if(type==LOADB_STUB||type==LOADBU_STUB)
    handler=jump_handler_read8;
  if(type==LOADH_STUB||type==LOADHU_STUB)
    handler=jump_handler_read16;
  if(type==LOADW_STUB)
    handler=jump_handler_read32;
  assert(handler);
  pass_args(rs,temp2);
  int cc=get_reg(i_regmap,CCREG);
  if(cc<0)
    emit_loadreg(CCREG,2);
  emit_addimm(cc<0?2:cc,(int)stubs[n].d,2);
  emit_far_call(handler);
#if 0
  if (type == LOADW_STUB) {
    // new cycle_count returned in r2
    emit_addimm(2, -(int)stubs[n].d, cc<0?2:cc);
    if (cc < 0)
      emit_storereg(CCREG, 2);
  }
#endif
  if(dops[i].itype==C2LS||(rt>=0&&dops[i].rt1!=0)) {
    mov_loadtype_adj(type,0,rt);
  }
  if(restore_jump)
    set_jump_target(restore_jump, out);
  restore_regs(reglist);
  emit_jmp(stubs[n].retaddr); // return address
}

static void inline_readstub(enum stub_type type, int i, u_int addr,
  const signed char regmap[], int target, int adj, u_int reglist)
{
  int ra = cinfo[i].addr;
  int rt = get_reg(regmap,target);
  assert(ra >= 0);
  u_int is_dynamic;
  uintptr_t host_addr = 0;
  void *handler;
  int cc=get_reg(regmap,CCREG);
  if(pcsx_direct_read(type,addr,adj,cc,target?ra:-1,rt))
    return;
  handler = get_direct_memhandler(mem_rtab, addr, type, &host_addr);
  if (handler == NULL) {
    if(rt<0||dops[i].rt1==0)
      return;
    if(addr!=host_addr)
      emit_movimm_from(addr,ra,host_addr,ra);
    switch(type) {
      case LOADB_STUB:  emit_movsbl_indexed(0,ra,rt); break;
      case LOADBU_STUB: emit_movzbl_indexed(0,ra,rt); break;
      case LOADH_STUB:  emit_movswl_indexed(0,ra,rt); break;
      case LOADHU_STUB: emit_movzwl_indexed(0,ra,rt); break;
      case LOADW_STUB:  emit_readword_indexed(0,ra,rt); break;
      default:          assert(0);
    }
    return;
  }
  is_dynamic=pcsxmem_is_handler_dynamic(addr);
  if(is_dynamic) {
    if(type==LOADB_STUB||type==LOADBU_STUB)
      handler=jump_handler_read8;
    if(type==LOADH_STUB||type==LOADHU_STUB)
      handler=jump_handler_read16;
    if(type==LOADW_STUB)
      handler=jump_handler_read32;
  }

  // call a memhandler
  if(rt>=0&&dops[i].rt1!=0)
    reglist&=~(1<<rt);
  save_regs(reglist);
  if(target==0)
    emit_movimm(addr,0);
  else if(ra!=0)
    emit_mov(ra,0);
  if(cc<0)
    emit_loadreg(CCREG,2);
  if(is_dynamic) {
    emit_movimm(((u_int *)mem_rtab)[addr>>12]<<1,1);
    emit_addimm(cc<0?2:cc,adj,2);
  }
  else {
    emit_readword(&last_count,3);
    emit_addimm(cc<0?2:cc,adj,2);
    emit_add(2,3,2);
    emit_writeword(2,&psxRegs.cycle);
  }

  emit_far_call(handler);

#if 0
  if (type == LOADW_STUB) {
    // new cycle_count returned in r2
    emit_addimm(2, -adj, cc<0?2:cc);
    if (cc < 0)
      emit_storereg(CCREG, 2);
  }
#endif
  if(rt>=0&&dops[i].rt1!=0) {
    switch(type) {
      case LOADB_STUB:  emit_signextend8(0,rt); break;
      case LOADBU_STUB: emit_andimm(0,0xff,rt); break;
      case LOADH_STUB:  emit_signextend16(0,rt); break;
      case LOADHU_STUB: emit_andimm(0,0xffff,rt); break;
      case LOADW_STUB:  if(rt!=0) emit_mov(0,rt); break;
      default:          assert(0);
    }
  }
  restore_regs(reglist);
}

static void do_writestub(int n)
{
  assem_debug("do_writestub %p\n", log_addr(start + stubs[n].a*4));
  literal_pool(256);
  set_jump_target(stubs[n].addr, out);
  enum stub_type type=stubs[n].type;
  int i=stubs[n].a;
  int rs=stubs[n].b;
  const struct regstat *i_regs=(struct regstat *)stubs[n].c;
  u_int reglist=stubs[n].e;
  const signed char *i_regmap=i_regs->regmap;
  int rt,r;
  if(dops[i].itype==C2LS) {
    rt=get_reg(i_regmap,r=FTEMP);
  }else{
    rt=get_reg(i_regmap,r=dops[i].rs2);
  }
  assert(rs>=0);
  assert(rt>=0);
  int rtmp,temp=-1,temp2=HOST_TEMPREG,regs_saved=0;
  void *restore_jump = NULL;
  int reglist2=reglist|(1<<rs)|(1<<rt);
  for(rtmp=0;rtmp<=12;rtmp++) {
    if(((1<<rtmp)&0x13ff)&&((1<<rtmp)&reglist2)==0) {
      temp=rtmp; break;
    }
  }
  if(temp==-1) {
    save_regs(reglist);
    regs_saved=1;
    for(rtmp=0;rtmp<=3;rtmp++)
      if(rtmp!=rs&&rtmp!=rt)
        {temp=rtmp;break;}
  }
  if((regs_saved||(reglist2&8)==0)&&temp!=3&&rs!=3&&rt!=3)
    temp2=3;
  emit_readword(&mem_wtab,temp);
  emit_shrimm(rs,12,temp2);
  emit_readword_dualindexedx4(temp,temp2,temp2);
  emit_lsls_imm(temp2,1,temp2);
  switch(type) {
    case STOREB_STUB: emit_strccb_dualindexed(temp2,rs,rt); break;
    case STOREH_STUB: emit_strcch_dualindexed(temp2,rs,rt); break;
    case STOREW_STUB: emit_strcc_dualindexed(temp2,rs,rt); break;
    default:          assert(0);
  }
  if(regs_saved) {
    restore_jump=out;
    emit_jcc(0); // jump to reg restore
  }
  else
    emit_jcc(stubs[n].retaddr); // return address (invcode check)

  if(!regs_saved)
    save_regs(reglist);
  void *handler=NULL;
  switch(type) {
    case STOREB_STUB: handler=jump_handler_write8; break;
    case STOREH_STUB: handler=jump_handler_write16; break;
    case STOREW_STUB: handler=jump_handler_write32; break;
    default: assert(0);
  }
  assert(handler);
  pass_args(rs,rt);
  if(temp2!=3)
    emit_mov(temp2,3);
  int cc=get_reg(i_regmap,CCREG);
  if(cc<0)
    emit_loadreg(CCREG,2);
  emit_addimm(cc<0?2:cc,(int)stubs[n].d,2);
  emit_far_call(handler);
  // new cycle_count returned in r2
  emit_addimm(2,-(int)stubs[n].d,cc<0?2:cc);
  if(cc<0)
    emit_storereg(CCREG,2);
  if(restore_jump)
    set_jump_target(restore_jump, out);
  restore_regs(reglist);
  emit_jmp(stubs[n].retaddr);
}

static void inline_writestub(enum stub_type type, int i, u_int addr,
  const signed char regmap[], int target, int adj, u_int reglist)
{
  int ra = cinfo[i].addr;
  int rt = get_reg(regmap, target);
  assert(ra>=0);
  assert(rt>=0);
  uintptr_t host_addr = 0;
  void *handler = get_direct_memhandler(mem_wtab, addr, type, &host_addr);
  if (handler == NULL) {
    if(addr!=host_addr)
      emit_movimm_from(addr,ra,host_addr,ra);
    switch(type) {
      case STOREB_STUB: emit_writebyte_indexed(rt,0,ra); break;
      case STOREH_STUB: emit_writehword_indexed(rt,0,ra); break;
      case STOREW_STUB: emit_writeword_indexed(rt,0,ra); break;
      default:          assert(0);
    }
    return;
  }

  // call a memhandler
  save_regs(reglist);
  pass_args(ra,rt);
  int cc=get_reg(regmap,CCREG);
  if(cc<0)
    emit_loadreg(CCREG,2);
  emit_addimm(cc<0?2:cc,adj,2);
  emit_movimm((u_int)handler,3);
  emit_far_call(jump_handler_write_h);
  // new cycle_count returned in r2
  emit_addimm(2,-adj,cc<0?2:cc);
  if(cc<0)
    emit_storereg(CCREG,2);
  restore_regs(reglist);
}

/* Special assem */

static void c2op_prologue(u_int op, int i, const struct regstat *i_regs, u_int reglist)
{
  save_regs_all(reglist);
  cop2_do_stall_check(op, i, i_regs, 0);
#ifdef PCNT
  emit_movimm(op, 0);
  emit_far_call(pcnt_gte_start);
#endif
  emit_addimm(FP, (u_char *)&psxRegs.CP2D.r[0] - (u_char *)&dynarec_local, 0); // cop2 regs
}

static void c2op_epilogue(u_int op,u_int reglist)
{
#ifdef PCNT
  emit_movimm(op,0);
  emit_far_call(pcnt_gte_end);
#endif
  restore_regs_all(reglist);
}

static void c2op_call_MACtoIR(int lm,int need_flags)
{
  if(need_flags)
    emit_far_call(lm?gteMACtoIR_lm1:gteMACtoIR_lm0);
  else
    emit_far_call(lm?gteMACtoIR_lm1_nf:gteMACtoIR_lm0_nf);
}

static void c2op_call_rgb_func(void *func,int lm,int need_ir,int need_flags)
{
  emit_far_call(func);
  // func is C code and trashes r0
  emit_addimm(FP,(int)&psxRegs.CP2D.r[0]-(int)&dynarec_local,0);
  if(need_flags||need_ir)
    c2op_call_MACtoIR(lm,need_flags);
  emit_far_call(need_flags?gteMACtoRGB:gteMACtoRGB_nf);
}

static void c2op_assemble(int i, const struct regstat *i_regs)
{
  u_int c2op = source[i] & 0x3f;
  u_int reglist_full = get_host_reglist(i_regs->regmap);
  u_int reglist = reglist_full & CALLER_SAVE_REGS;
  int need_flags, need_ir;

  if (gte_handlers[c2op]!=NULL) {
    need_flags=!(gte_unneeded[i+1]>>63); // +1 because of how liveness detection works
    need_ir=(gte_unneeded[i+1]&0xe00)!=0xe00;
    assem_debug("gte op %08x, unneeded %016llx, need_flags %d, need_ir %d\n",
      source[i],gte_unneeded[i+1],need_flags,need_ir);
    if(HACK_ENABLED(NDHACK_GTE_NO_FLAGS))
      need_flags=0;
    int shift = (source[i] >> 19) & 1;
    int lm = (source[i] >> 10) & 1;
    switch(c2op) {
#ifndef DRC_DBG
      case GTE_MVMVA: {
#ifdef HAVE_ARMV5
        int v  = (source[i] >> 15) & 3;
        int cv = (source[i] >> 13) & 3;
        int mx = (source[i] >> 17) & 3;
        reglist=reglist_full&(CALLER_SAVE_REGS|0xf0); // +{r4-r7}
        c2op_prologue(c2op,i,i_regs,reglist);
        /* r4,r5 = VXYZ(v) packed; r6 = &MX11(mx); r7 = &CV1(cv) */
        if(v<3)
          emit_ldrd(v*8,0,4);
        else {
          emit_movzwl_indexed(9*4,0,4);  // gteIR
          emit_movzwl_indexed(10*4,0,6);
          emit_movzwl_indexed(11*4,0,5);
          emit_orrshl_imm(6,16,4);
        }
        if(mx<3)
          emit_addimm(0,32*4+mx*8*4,6);
        else
          emit_readword(&zeromem_ptr,6);
        if(cv<3)
          emit_addimm(0,32*4+(cv*8+5)*4,7);
        else
          emit_readword(&zeromem_ptr,7);
#ifdef __ARM_NEON__
        emit_movimm(source[i],1); // opcode
        emit_far_call(gteMVMVA_part_neon);
        if(need_flags) {
          emit_movimm(lm,1);
          emit_far_call(gteMACtoIR_flags_neon);
        }
#else
        if(cv==3&&shift)
          emit_far_call(gteMVMVA_part_cv3sh12_arm);
        else {
          emit_movimm(shift,1);
          emit_far_call(need_flags?gteMVMVA_part_arm:gteMVMVA_part_nf_arm);
        }
        if(need_flags||need_ir)
          c2op_call_MACtoIR(lm,need_flags);
#endif
#else /* if not HAVE_ARMV5 */
        c2op_prologue(c2op,i,i_regs,reglist);
        emit_movimm(source[i],1); // opcode
        emit_writeword(1,&psxRegs.code);
        emit_far_call(need_flags?gte_handlers[c2op]:gte_handlers_nf[c2op]);
#endif
        break;
      }
      case GTE_OP:
        c2op_prologue(c2op,i,i_regs,reglist);
        emit_far_call(shift?gteOP_part_shift:gteOP_part_noshift);
        if(need_flags||need_ir) {
          emit_addimm(FP,(int)&psxRegs.CP2D.r[0]-(int)&dynarec_local,0);
          c2op_call_MACtoIR(lm,need_flags);
        }
        break;
      case GTE_DPCS:
        c2op_prologue(c2op,i,i_regs,reglist);
        c2op_call_rgb_func(shift?gteDPCS_part_shift:gteDPCS_part_noshift,lm,need_ir,need_flags);
        break;
      case GTE_INTPL:
        c2op_prologue(c2op,i,i_regs,reglist);
        c2op_call_rgb_func(shift?gteINTPL_part_shift:gteINTPL_part_noshift,lm,need_ir,need_flags);
        break;
      case GTE_SQR:
        c2op_prologue(c2op,i,i_regs,reglist);
        emit_far_call(shift?gteSQR_part_shift:gteSQR_part_noshift);
        if(need_flags||need_ir) {
          emit_addimm(FP,(int)&psxRegs.CP2D.r[0]-(int)&dynarec_local,0);
          c2op_call_MACtoIR(lm,need_flags);
        }
        break;
      case GTE_DCPL:
        c2op_prologue(c2op,i,i_regs,reglist);
        c2op_call_rgb_func(gteDCPL_part,lm,need_ir,need_flags);
        break;
      case GTE_GPF:
        c2op_prologue(c2op,i,i_regs,reglist);
        c2op_call_rgb_func(shift?gteGPF_part_shift:gteGPF_part_noshift,lm,need_ir,need_flags);
        break;
      case GTE_GPL:
        c2op_prologue(c2op,i,i_regs,reglist);
        c2op_call_rgb_func(shift?gteGPL_part_shift:gteGPL_part_noshift,lm,need_ir,need_flags);
        break;
#endif
      default:
        c2op_prologue(c2op,i,i_regs,reglist);
#ifdef DRC_DBG
        emit_movimm(source[i],1); // opcode
        emit_writeword(1,&psxRegs.code);
#endif
        emit_far_call(need_flags?gte_handlers[c2op]:gte_handlers_nf[c2op]);
        break;
    }
    c2op_epilogue(c2op,reglist);
  }
}

static void c2op_ctc2_31_assemble(signed char sl, signed char temp)
{
  //value = value & 0x7ffff000;
  //if (value & 0x7f87e000) value |= 0x80000000;
  emit_shrimm(sl,12,temp);
  emit_shlimm(temp,12,temp);
  emit_testimm(temp,0x7f000000);
  emit_testeqimm(temp,0x00870000);
  emit_testeqimm(temp,0x0000e000);
  emit_orrne_imm(temp,0x80000000,temp);
}

static void do_mfc2_31_one(u_int copr,signed char temp)
{
  emit_readword(&reg_cop2d[copr],temp);
  emit_lsls_imm(temp,16,temp);
  emit_cmovs_imm(0,temp);
  emit_cmpimm(temp,0xf80<<16);
  emit_andimm(temp,0xf80<<16,temp);
  emit_cmovae_imm(0xf80<<16,temp);
}

static void c2op_mfc2_29_assemble(signed char tl, signed char temp)
{
  if (temp < 0) {
    host_tempreg_acquire();
    temp = HOST_TEMPREG;
  }
  do_mfc2_31_one(9,temp);
  emit_shrimm(temp,7+16,tl);
  do_mfc2_31_one(10,temp);
  emit_orrshr_imm(temp,2+16,tl);
  do_mfc2_31_one(11,temp);
  emit_orrshr_imm(temp,-3+16,tl);
  emit_writeword(tl,&reg_cop2d[29]);
  if (temp == HOST_TEMPREG)
    host_tempreg_release();
}

static void multdiv_assemble_arm(int i, const struct regstat *i_regs)
{
  //  case 0x18: MULT
  //  case 0x19: MULTU
  //  case 0x1A: DIV
  //  case 0x1B: DIVU
  if(dops[i].rs1&&dops[i].rs2)
  {
    switch (dops[i].opcode2)
    {
    case 0x18: // MULT
      {
        signed char m1=get_reg(i_regs->regmap,dops[i].rs1);
        signed char m2=get_reg(i_regs->regmap,dops[i].rs2);
        signed char hi=get_reg(i_regs->regmap,HIREG);
        signed char lo=get_reg(i_regs->regmap,LOREG);
        assert(m1>=0);
        assert(m2>=0);
        assert(hi>=0);
        assert(lo>=0);
        emit_smull(m1,m2,hi,lo);
      }
      break;
    case 0x19: // MULTU
      {
        signed char m1=get_reg(i_regs->regmap,dops[i].rs1);
        signed char m2=get_reg(i_regs->regmap,dops[i].rs2);
        signed char hi=get_reg(i_regs->regmap,HIREG);
        signed char lo=get_reg(i_regs->regmap,LOREG);
        assert(m1>=0);
        assert(m2>=0);
        assert(hi>=0);
        assert(lo>=0);
        emit_umull(m1,m2,hi,lo);
      }
      break;
    case 0x1A: // DIV
      {
        signed char d1=get_reg(i_regs->regmap,dops[i].rs1);
        signed char d2=get_reg(i_regs->regmap,dops[i].rs2);
        signed char quotient=get_reg(i_regs->regmap,LOREG);
        signed char remainder=get_reg(i_regs->regmap,HIREG);
        void *jaddr_div0;
        assert(d1>=0);
        assert(d2>=0);
        assert(quotient>=0);
        assert(remainder>=0);
        emit_movs(d1,remainder);
        emit_movimm(0xffffffff,quotient);
        emit_negmi(quotient,quotient); // .. quotient and ..
        emit_negmi(remainder,remainder); // .. remainder for div0 case (will be negated back after jump)
        emit_movs(d2,HOST_TEMPREG);
        jaddr_div0 = out;
        emit_jeq(0); // Division by zero
        emit_negsmi(HOST_TEMPREG,HOST_TEMPREG);
#ifdef HAVE_ARMV5
        emit_clz(HOST_TEMPREG,quotient);
        emit_shl(HOST_TEMPREG,quotient,HOST_TEMPREG);  // shifted divisor
#else
        emit_movimm(0,quotient);
        emit_addpl_imm(quotient,1,quotient);
        emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
        emit_jns(out-2*4);
#endif
        emit_orimm(quotient,1<<31,quotient);
        emit_shr(quotient,quotient,quotient);
        emit_cmp(remainder,HOST_TEMPREG);
        emit_subcs(remainder,HOST_TEMPREG,remainder);
        emit_adcs(quotient,quotient,quotient);
        emit_shrimm(HOST_TEMPREG,1,HOST_TEMPREG);
        emit_jcc(out-16); // -4
        emit_teq(d1,d2);
        emit_negmi(quotient,quotient);
        set_jump_target(jaddr_div0, out);
        emit_test(d1,d1);
        emit_negmi(remainder,remainder);
      }
      break;
    case 0x1B: // DIVU
      {
        signed char d1=get_reg(i_regs->regmap,dops[i].rs1); // dividend
        signed char d2=get_reg(i_regs->regmap,dops[i].rs2); // divisor
        signed char quotient=get_reg(i_regs->regmap,LOREG);
        signed char remainder=get_reg(i_regs->regmap,HIREG);
        void *jaddr_div0;
        assert(d1>=0);
        assert(d2>=0);
        assert(quotient>=0);
        assert(remainder>=0);
        emit_mov(d1,remainder);
        emit_movimm(0xffffffff,quotient); // div0 case
        emit_test(d2,d2);
        jaddr_div0 = out;
        emit_jeq(0); // Division by zero
#ifdef HAVE_ARMV5
        emit_clz(d2,HOST_TEMPREG);
        emit_movimm(1<<31,quotient);
        emit_shl(d2,HOST_TEMPREG,d2);
#else
        emit_movimm(0,HOST_TEMPREG);
        emit_addpl_imm(HOST_TEMPREG,1,HOST_TEMPREG);
        emit_lslpls_imm(d2,1,d2);
        emit_jns(out-2*4);
        emit_movimm(1<<31,quotient);
#endif
        emit_shr(quotient,HOST_TEMPREG,quotient);
        emit_cmp(remainder,d2);
        emit_subcs(remainder,d2,remainder);
        emit_adcs(quotient,quotient,quotient);
        emit_shrcc_imm(d2,1,d2);
        emit_jcc(out-16); // -4
        set_jump_target(jaddr_div0, out);
      }
      break;
    }
  }
  else
  {
    signed char hr=get_reg(i_regs->regmap,HIREG);
    signed char lr=get_reg(i_regs->regmap,LOREG);
    if ((dops[i].opcode2==0x1A || dops[i].opcode2==0x1B) && dops[i].rs2==0) // div 0
    {
      if (dops[i].rs1) {
        signed char numerator = get_reg(i_regs->regmap, dops[i].rs1);
        assert(numerator >= 0);
        if (hr < 0)
          hr = HOST_TEMPREG;
        emit_movs(numerator, hr);
        if (lr >= 0) {
          if (dops[i].opcode2 == 0x1A) { // DIV
            emit_movimm(0xffffffff, lr);
            emit_negmi(lr, lr);
          }
          else
            emit_movimm(~0, lr);
        }
      }
      else {
        if (hr >= 0) emit_zeroreg(hr);
        if (lr >= 0) emit_movimm(~0,lr);
      }
    }
    else if ((dops[i].opcode2==0x1A || dops[i].opcode2==0x1B) && dops[i].rs1==0)
    {
      signed char denominator = get_reg(i_regs->regmap, dops[i].rs2);
      assert(denominator >= 0);
      if (hr >= 0) emit_zeroreg(hr);
      if (lr >= 0) {
        emit_zeroreg(lr);
        emit_test(denominator, denominator);
        emit_mvneq(lr, lr);
      }
    }
    else
    {
      // Multiply by zero is zero.
      if (hr >= 0) emit_zeroreg(hr);
      if (lr >= 0) emit_zeroreg(lr);
    }
  }
}
#define multdiv_assemble multdiv_assemble_arm

static void do_jump_vaddr(int rs)
{
  emit_far_jump(jump_vaddr_reg[rs]);
}

static void do_preload_rhash(int r) {
  // Don't need this for ARM.  On x86, this puts the value 0xf8 into the
  // register.  On ARM the hash can be done with a single instruction (below)
}

static void do_preload_rhtbl(int ht) {
  emit_addimm(FP,(int)&mini_ht-(int)&dynarec_local,ht);
}

static void do_rhash(int rs,int rh) {
  emit_andimm(rs,0xf8,rh);
}

static void do_miniht_load(int ht,int rh) {
  assem_debug("ldr %s,[%s,%s]!\n",regname[rh],regname[ht],regname[rh]);
  output_w32(0xe7b00000|rd_rn_rm(rh,ht,rh));
}

static void do_miniht_jump(int rs,int rh,int ht) {
  emit_cmp(rh,rs);
  emit_ldreq_indexed(ht,4,15);
  #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
  if(rs!=7)
    emit_mov(rs,7);
  rs=7;
  #endif
  do_jump_vaddr(rs);
}

static void do_miniht_insert(u_int return_address,int rt,int temp) {
  #ifndef HAVE_ARMV7
  emit_movimm(return_address,rt); // PC into link register
  add_to_linker(out,return_address,1);
  emit_pcreladdr(temp);
  emit_writeword(rt,&mini_ht[(return_address&0xFF)>>3][0]);
  emit_writeword(temp,&mini_ht[(return_address&0xFF)>>3][1]);
  #else
  emit_movw(return_address&0x0000FFFF,rt);
  add_to_linker(out,return_address,1);
  emit_pcreladdr(temp);
  emit_writeword(temp,&mini_ht[(return_address&0xFF)>>3][1]);
  emit_movt(return_address&0xFFFF0000,rt);
  emit_writeword(rt,&mini_ht[(return_address&0xFF)>>3][0]);
  #endif
}

// CPU-architecture-specific initialization
static void arch_init(void)
{
  uintptr_t diff = (u_char *)&ndrc->tramp.f - (u_char *)&ndrc->tramp.ops - 8;
  struct tramp_insns *ops = ndrc->tramp.ops;
  size_t i;
  assert(!(diff & 3));
  assert(diff < 0x1000);
  start_tcache_write(ops, (u_char *)ops + sizeof(ndrc->tramp.ops));
  for (i = 0; i < ARRAY_SIZE(ndrc->tramp.ops); i++)
    ops[i].ldrpc = 0xe5900000 | rd_rn_rm(15,15,0) | diff; // ldr pc, [=val]
  end_tcache_write(ops, (u_char *)ops + sizeof(ndrc->tramp.ops));
}

// vim:shiftwidth=2:expandtab
