drc: another hack to try to get Vita to work
[pcsx_rearmed.git] / libpcsxcore / new_dynarec / new_dynarec.c
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  *   Mupen64plus - new_dynarec.c                                           *
3  *   Copyright (C) 2009-2011 Ari64                                         *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
20
21 #include <stdlib.h>
22 #include <stdint.h> //include for uint64_t
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 #ifdef __MACH__
27 #include <libkern/OSCacheControl.h>
28 #endif
29 #ifdef _3DS
30 #include <3ds_utils.h>
31 #endif
32
33 #include "new_dynarec_config.h"
34 #include "../psxhle.h"
35 #include "../psxinterpreter.h"
36 #include "../gte.h"
37 #include "emu_if.h" // emulator interface
38
39 #define noinline __attribute__((noinline,noclone))
40 #ifndef ARRAY_SIZE
41 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
42 #endif
43 #ifndef min
44 #define min(a, b) ((b) < (a) ? (b) : (a))
45 #endif
46 #ifndef max
47 #define max(a, b) ((b) > (a) ? (b) : (a))
48 #endif
49
50 //#define DISASM
51 //#define ASSEM_PRINT
52
53 #ifdef ASSEM_PRINT
54 #define assem_debug printf
55 #else
56 #define assem_debug(...)
57 #endif
58 //#define inv_debug printf
59 #define inv_debug(...)
60
61 #ifdef __i386__
62 #include "assem_x86.h"
63 #endif
64 #ifdef __x86_64__
65 #include "assem_x64.h"
66 #endif
67 #ifdef __arm__
68 #include "assem_arm.h"
69 #endif
70 #ifdef __aarch64__
71 #include "assem_arm64.h"
72 #endif
73
74 #define RAM_SIZE 0x200000
75 #define MAXBLOCK 4096
76 #define MAX_OUTPUT_BLOCK_SIZE 262144
77
78 #ifdef VITA
79 // apparently Vita has a 16MB limit, so either we cut tc in half,
80 // or use this hack (it's a hack because tc size was designed to be power-of-2)
81 #define TC_REDUCE_BYTES 4096
82 #else
83 #define TC_REDUCE_BYTES 0
84 #endif
85
86 struct ndrc_mem
87 {
88   u_char translation_cache[(1 << TARGET_SIZE_2) - TC_REDUCE_BYTES];
89   struct
90   {
91     struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
92     const void *f[2048 / sizeof(void *)];
93   } tramp;
94 };
95
96 #ifdef BASE_ADDR_DYNAMIC
97 static struct ndrc_mem *ndrc;
98 #else
99 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
100 static struct ndrc_mem *ndrc = &ndrc_;
101 #endif
102
103 // stubs
104 enum stub_type {
105   CC_STUB = 1,
106   FP_STUB = 2,
107   LOADB_STUB = 3,
108   LOADH_STUB = 4,
109   LOADW_STUB = 5,
110   LOADD_STUB = 6,
111   LOADBU_STUB = 7,
112   LOADHU_STUB = 8,
113   STOREB_STUB = 9,
114   STOREH_STUB = 10,
115   STOREW_STUB = 11,
116   STORED_STUB = 12,
117   STORELR_STUB = 13,
118   INVCODE_STUB = 14,
119 };
120
121 struct regstat
122 {
123   signed char regmap_entry[HOST_REGS]; // pre-insn + loop preloaded regs?
124   signed char regmap[HOST_REGS];
125   uint64_t wasdirty;
126   uint64_t dirty;
127   uint64_t u;
128   u_int wasconst;                // before; for example 'lw r2, (r2)' wasconst is true
129   u_int isconst;                 //  ... but isconst is false when r2 is known
130   u_int loadedconst;             // host regs that have constants loaded
131   u_int waswritten;              // MIPS regs that were used as store base before
132 };
133
134 // note: asm depends on this layout
135 struct ll_entry
136 {
137   u_int vaddr;
138   u_int reg_sv_flags;
139   void *addr;
140   struct ll_entry *next;
141 };
142
143 struct ht_entry
144 {
145   u_int vaddr[2];
146   void *tcaddr[2];
147 };
148
149 struct code_stub
150 {
151   enum stub_type type;
152   void *addr;
153   void *retaddr;
154   u_int a;
155   uintptr_t b;
156   uintptr_t c;
157   u_int d;
158   u_int e;
159 };
160
161 struct link_entry
162 {
163   void *addr;
164   u_int target;
165   u_int ext;
166 };
167
168 static struct decoded_insn
169 {
170   u_char itype;
171   u_char opcode;
172   u_char opcode2;
173   u_char rs1;
174   u_char rs2;
175   u_char rt1;
176   u_char rt2;
177   u_char lt1;
178   u_char bt:1;
179   u_char ooo:1;
180   u_char is_ds:1;
181   u_char is_jump:1;
182   u_char is_ujump:1;
183   u_char is_load:1;
184   u_char is_store:1;
185 } dops[MAXBLOCK];
186
187   // used by asm:
188   u_char *out;
189   struct ht_entry hash_table[65536]  __attribute__((aligned(16)));
190   struct ll_entry *jump_in[4096] __attribute__((aligned(16)));
191   struct ll_entry *jump_dirty[4096];
192
193   static struct ll_entry *jump_out[4096];
194   static u_int start;
195   static u_int *source;
196   static char insn[MAXBLOCK][10];
197   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
198   static uint64_t gte_rt[MAXBLOCK];
199   static uint64_t gte_unneeded[MAXBLOCK];
200   static u_int smrv[32]; // speculated MIPS register values
201   static u_int smrv_strong; // mask or regs that are likely to have correct values
202   static u_int smrv_weak; // same, but somewhat less likely
203   static u_int smrv_strong_next; // same, but after current insn executes
204   static u_int smrv_weak_next;
205   static int imm[MAXBLOCK];
206   static u_int ba[MAXBLOCK];
207   static uint64_t unneeded_reg[MAXBLOCK];
208   static uint64_t branch_unneeded_reg[MAXBLOCK];
209   // pre-instruction [i], excluding loop-preload regs?
210   static signed char regmap_pre[MAXBLOCK][HOST_REGS];
211   // contains 'real' consts at [i] insn, but may differ from what's actually
212   // loaded in host reg as 'final' value is always loaded, see get_final_value()
213   static uint32_t current_constmap[HOST_REGS];
214   static uint32_t constmap[MAXBLOCK][HOST_REGS];
215   static struct regstat regs[MAXBLOCK];
216   static struct regstat branch_regs[MAXBLOCK];
217   static signed char minimum_free_regs[MAXBLOCK];
218   static u_int needed_reg[MAXBLOCK];
219   static u_int wont_dirty[MAXBLOCK];
220   static u_int will_dirty[MAXBLOCK];
221   static int ccadj[MAXBLOCK];
222   static int slen;
223   static void *instr_addr[MAXBLOCK];
224   static struct link_entry link_addr[MAXBLOCK];
225   static int linkcount;
226   static struct code_stub stubs[MAXBLOCK*3];
227   static int stubcount;
228   static u_int literals[1024][2];
229   static int literalcount;
230   static int is_delayslot;
231   static char shadow[1048576]  __attribute__((aligned(16)));
232   static void *copy;
233   static int expirep;
234   static u_int stop_after_jal;
235   static u_int f1_hack;
236
237   int new_dynarec_hacks;
238   int new_dynarec_hacks_pergame;
239   int new_dynarec_hacks_old;
240   int new_dynarec_did_compile;
241
242   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
243
244   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
245   extern int last_count;  // last absolute target, often = next_interupt
246   extern int pcaddr;
247   extern int pending_exception;
248   extern int branch_target;
249   extern uintptr_t ram_offset;
250   extern uintptr_t mini_ht[32][2];
251   extern u_char restore_candidate[512];
252
253   /* registers that may be allocated */
254   /* 1-31 gpr */
255 #define LOREG 32 // lo
256 #define HIREG 33 // hi
257 //#define FSREG 34 // FPU status (FCSR)
258 #define CSREG 35 // Coprocessor status
259 #define CCREG 36 // Cycle count
260 #define INVCP 37 // Pointer to invalid_code
261 //#define MMREG 38 // Pointer to memory_map
262 #define ROREG 39 // ram offset (if rdram!=0x80000000)
263 #define TEMPREG 40
264 #define FTEMP 40 // FPU temporary register
265 #define PTEMP 41 // Prefetch temporary register
266 //#define TLREG 42 // TLB mapping offset
267 #define RHASH 43 // Return address hash
268 #define RHTBL 44 // Return address hash table address
269 #define RTEMP 45 // JR/JALR address register
270 #define MAXREG 45
271 #define AGEN1 46 // Address generation temporary register
272 //#define AGEN2 47 // Address generation temporary register
273 //#define MGEN1 48 // Maptable address generation temporary register
274 //#define MGEN2 49 // Maptable address generation temporary register
275 #define BTREG 50 // Branch target temporary register
276
277   /* instruction types */
278 #define NOP 0     // No operation
279 #define LOAD 1    // Load
280 #define STORE 2   // Store
281 #define LOADLR 3  // Unaligned load
282 #define STORELR 4 // Unaligned store
283 #define MOV 5     // Move
284 #define ALU 6     // Arithmetic/logic
285 #define MULTDIV 7 // Multiply/divide
286 #define SHIFT 8   // Shift by register
287 #define SHIFTIMM 9// Shift by immediate
288 #define IMM16 10  // 16-bit immediate
289 #define RJUMP 11  // Unconditional jump to register
290 #define UJUMP 12  // Unconditional jump
291 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
292 #define SJUMP 14  // Conditional branch (regimm format)
293 #define COP0 15   // Coprocessor 0
294 #define COP1 16   // Coprocessor 1
295 #define C1LS 17   // Coprocessor 1 load/store
296 //#define FJUMP 18  // Conditional branch (floating point)
297 //#define FLOAT 19  // Floating point unit
298 //#define FCONV 20  // Convert integer to float
299 //#define FCOMP 21  // Floating point compare (sets FSREG)
300 #define SYSCALL 22// SYSCALL
301 #define OTHER 23  // Other
302 #define SPAN 24   // Branch/delay slot spans 2 pages
303 #define NI 25     // Not implemented
304 #define HLECALL 26// PCSX fake opcodes for HLE
305 #define COP2 27   // Coprocessor 2 move
306 #define C2LS 28   // Coprocessor 2 load/store
307 #define C2OP 29   // Coprocessor 2 operation
308 #define INTCALL 30// Call interpreter to handle rare corner cases
309
310   /* branch codes */
311 #define TAKEN 1
312 #define NOTTAKEN 2
313 #define NULLDS 3
314
315 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
316 #define DJT_2 (void *)2l
317
318 // asm linkage
319 int new_recompile_block(u_int addr);
320 void *get_addr_ht(u_int vaddr);
321 void invalidate_block(u_int block);
322 void invalidate_addr(u_int addr);
323 void remove_hash(int vaddr);
324 void dyna_linker();
325 void dyna_linker_ds();
326 void verify_code();
327 void verify_code_ds();
328 void cc_interrupt();
329 void fp_exception();
330 void fp_exception_ds();
331 void jump_to_new_pc();
332 void call_gteStall();
333 void new_dyna_leave();
334
335 // Needed by assembler
336 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty);
337 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty);
338 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr);
339 static void load_all_regs(const signed char i_regmap[]);
340 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[]);
341 static void load_regs_entry(int t);
342 static void load_all_consts(const signed char regmap[], u_int dirty, int i);
343 static u_int get_host_reglist(const signed char *regmap);
344
345 static int verify_dirty(const u_int *ptr);
346 static int get_final_value(int hr, int i, int *value);
347 static void add_stub(enum stub_type type, void *addr, void *retaddr,
348   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
349 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
350   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
351 static void add_to_linker(void *addr, u_int target, int ext);
352 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
353   int addr, int *offset_reg, int *addr_reg_override);
354 static void *get_direct_memhandler(void *table, u_int addr,
355   enum stub_type type, uintptr_t *addr_host);
356 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
357 static void pass_args(int a0, int a1);
358 static void emit_far_jump(const void *f);
359 static void emit_far_call(const void *f);
360
361 #ifdef VITA
362 #include <psp2/kernel/sysmem.h>
363 static int sceBlock;
364 // note: this interacts with RetroArch's Vita bootstrap code: bootstrap/vita/sbrk.c
365 extern int getVMBlock();
366 int _newlib_vm_size_user = sizeof(*ndrc);
367 #endif
368
369 static void mprotect_w_x(void *start, void *end, int is_x)
370 {
371 #ifdef NO_WRITE_EXEC
372   #if defined(VITA)
373   // *Open* enables write on all memory that was
374   // allocated by sceKernelAllocMemBlockForVM()?
375   if (is_x)
376     sceKernelCloseVMDomain();
377   else
378     sceKernelOpenVMDomain();
379   #else
380   u_long mstart = (u_long)start & ~4095ul;
381   u_long mend = (u_long)end;
382   if (mprotect((void *)mstart, mend - mstart,
383                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
384     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
385   #endif
386 #endif
387 }
388
389 static void start_tcache_write(void *start, void *end)
390 {
391   mprotect_w_x(start, end, 0);
392 }
393
394 static void end_tcache_write(void *start, void *end)
395 {
396 #if defined(__arm__) || defined(__aarch64__)
397   size_t len = (char *)end - (char *)start;
398   #if   defined(__BLACKBERRY_QNX__)
399   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
400   #elif defined(__MACH__)
401   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
402   #elif defined(VITA)
403   sceKernelSyncVMDomain(sceBlock, start, len);
404   #elif defined(_3DS)
405   ctr_flush_invalidate_cache();
406   #elif defined(__aarch64__)
407   // as of 2021, __clear_cache() is still broken on arm64
408   // so here is a custom one :(
409   clear_cache_arm64(start, end);
410   #else
411   __clear_cache(start, end);
412   #endif
413   (void)len;
414 #endif
415
416   mprotect_w_x(start, end, 1);
417 }
418
419 static void *start_block(void)
420 {
421   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
422   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
423     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
424   start_tcache_write(out, end);
425   return out;
426 }
427
428 static void end_block(void *start)
429 {
430   end_tcache_write(start, out);
431 }
432
433 // also takes care of w^x mappings when patching code
434 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
435
436 static void mark_clear_cache(void *target)
437 {
438   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
439   u_int mask = 1u << ((offset >> 12) & 31);
440   if (!(needs_clear_cache[offset >> 17] & mask)) {
441     char *start = (char *)((uintptr_t)target & ~4095l);
442     start_tcache_write(start, start + 4095);
443     needs_clear_cache[offset >> 17] |= mask;
444   }
445 }
446
447 // Clearing the cache is rather slow on ARM Linux, so mark the areas
448 // that need to be cleared, and then only clear these areas once.
449 static void do_clear_cache(void)
450 {
451   int i, j;
452   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
453   {
454     u_int bitmap = needs_clear_cache[i];
455     if (!bitmap)
456       continue;
457     for (j = 0; j < 32; j++)
458     {
459       u_char *start, *end;
460       if (!(bitmap & (1<<j)))
461         continue;
462
463       start = ndrc->translation_cache + i*131072 + j*4096;
464       end = start + 4095;
465       for (j++; j < 32; j++) {
466         if (!(bitmap & (1<<j)))
467           break;
468         end += 4096;
469       }
470       end_tcache_write(start, end);
471     }
472     needs_clear_cache[i] = 0;
473   }
474 }
475
476 //#define DEBUG_CYCLE_COUNT 1
477
478 #define NO_CYCLE_PENALTY_THR 12
479
480 int cycle_multiplier = CYCLE_MULT_DEFAULT; // 100 for 1.0
481 int cycle_multiplier_override;
482 int cycle_multiplier_old;
483 static int cycle_multiplier_active;
484
485 static int CLOCK_ADJUST(int x)
486 {
487   int m = cycle_multiplier_active;
488   int s = (x >> 31) | 1;
489   return (x * m + s * 50) / 100;
490 }
491
492 static int ds_writes_rjump_rs(int i)
493 {
494   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
495 }
496
497 static u_int get_page(u_int vaddr)
498 {
499   u_int page=vaddr&~0xe0000000;
500   if (page < 0x1000000)
501     page &= ~0x0e00000; // RAM mirrors
502   page>>=12;
503   if(page>2048) page=2048+(page&2047);
504   return page;
505 }
506
507 // no virtual mem in PCSX
508 static u_int get_vpage(u_int vaddr)
509 {
510   return get_page(vaddr);
511 }
512
513 static struct ht_entry *hash_table_get(u_int vaddr)
514 {
515   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
516 }
517
518 static void hash_table_add(struct ht_entry *ht_bin, u_int vaddr, void *tcaddr)
519 {
520   ht_bin->vaddr[1] = ht_bin->vaddr[0];
521   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
522   ht_bin->vaddr[0] = vaddr;
523   ht_bin->tcaddr[0] = tcaddr;
524 }
525
526 // some messy ari64's code, seems to rely on unsigned 32bit overflow
527 static int doesnt_expire_soon(void *tcaddr)
528 {
529   u_int diff = (u_int)((u_char *)tcaddr - out) << (32-TARGET_SIZE_2);
530   return diff > (u_int)(0x60000000 + (MAX_OUTPUT_BLOCK_SIZE << (32-TARGET_SIZE_2)));
531 }
532
533 // Get address from virtual address
534 // This is called from the recompiled JR/JALR instructions
535 void noinline *get_addr(u_int vaddr)
536 {
537   u_int page=get_page(vaddr);
538   u_int vpage=get_vpage(vaddr);
539   struct ll_entry *head;
540   //printf("TRACE: count=%d next=%d (get_addr %x,page %d)\n",Count,next_interupt,vaddr,page);
541   head=jump_in[page];
542   while(head!=NULL) {
543     if(head->vaddr==vaddr) {
544   //printf("TRACE: count=%d next=%d (get_addr match %x: %p)\n",Count,next_interupt,vaddr,head->addr);
545       hash_table_add(hash_table_get(vaddr), vaddr, head->addr);
546       return head->addr;
547     }
548     head=head->next;
549   }
550   head=jump_dirty[vpage];
551   while(head!=NULL) {
552     if(head->vaddr==vaddr) {
553       //printf("TRACE: count=%d next=%d (get_addr match dirty %x: %p)\n",Count,next_interupt,vaddr,head->addr);
554       // Don't restore blocks which are about to expire from the cache
555       if (doesnt_expire_soon(head->addr))
556       if (verify_dirty(head->addr)) {
557         //printf("restore candidate: %x (%d) d=%d\n",vaddr,page,invalid_code[vaddr>>12]);
558         invalid_code[vaddr>>12]=0;
559         inv_code_start=inv_code_end=~0;
560         if(vpage<2048) {
561           restore_candidate[vpage>>3]|=1<<(vpage&7);
562         }
563         else restore_candidate[page>>3]|=1<<(page&7);
564         struct ht_entry *ht_bin = hash_table_get(vaddr);
565         if (ht_bin->vaddr[0] == vaddr)
566           ht_bin->tcaddr[0] = head->addr; // Replace existing entry
567         else
568           hash_table_add(ht_bin, vaddr, head->addr);
569
570         return head->addr;
571       }
572     }
573     head=head->next;
574   }
575   //printf("TRACE: count=%d next=%d (get_addr no-match %x)\n",Count,next_interupt,vaddr);
576   int r=new_recompile_block(vaddr);
577   if(r==0) return get_addr(vaddr);
578   // Execute in unmapped page, generate pagefault execption
579   Status|=2;
580   Cause=(vaddr<<31)|0x8;
581   EPC=(vaddr&1)?vaddr-5:vaddr;
582   BadVAddr=(vaddr&~1);
583   Context=(Context&0xFF80000F)|((BadVAddr>>9)&0x007FFFF0);
584   EntryHi=BadVAddr&0xFFFFE000;
585   return get_addr_ht(0x80000000);
586 }
587 // Look up address in hash table first
588 void *get_addr_ht(u_int vaddr)
589 {
590   //printf("TRACE: count=%d next=%d (get_addr_ht %x)\n",Count,next_interupt,vaddr);
591   const struct ht_entry *ht_bin = hash_table_get(vaddr);
592   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
593   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
594   return get_addr(vaddr);
595 }
596
597 void clear_all_regs(signed char regmap[])
598 {
599   int hr;
600   for (hr=0;hr<HOST_REGS;hr++) regmap[hr]=-1;
601 }
602
603 static signed char get_reg(const signed char regmap[],int r)
604 {
605   int hr;
606   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap[hr]==r) return hr;
607   return -1;
608 }
609
610 // Find a register that is available for two consecutive cycles
611 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
612 {
613   int hr;
614   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
615   return -1;
616 }
617
618 int count_free_regs(signed char regmap[])
619 {
620   int count=0;
621   int hr;
622   for(hr=0;hr<HOST_REGS;hr++)
623   {
624     if(hr!=EXCLUDE_REG) {
625       if(regmap[hr]<0) count++;
626     }
627   }
628   return count;
629 }
630
631 void dirty_reg(struct regstat *cur,signed char reg)
632 {
633   int hr;
634   if(!reg) return;
635   for (hr=0;hr<HOST_REGS;hr++) {
636     if((cur->regmap[hr]&63)==reg) {
637       cur->dirty|=1<<hr;
638     }
639   }
640 }
641
642 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
643 {
644   int hr;
645   if(!reg) return;
646   for (hr=0;hr<HOST_REGS;hr++) {
647     if(cur->regmap[hr]==reg) {
648       cur->isconst|=1<<hr;
649       current_constmap[hr]=value;
650     }
651   }
652 }
653
654 static void clear_const(struct regstat *cur, signed char reg)
655 {
656   int hr;
657   if(!reg) return;
658   for (hr=0;hr<HOST_REGS;hr++) {
659     if((cur->regmap[hr]&63)==reg) {
660       cur->isconst&=~(1<<hr);
661     }
662   }
663 }
664
665 static int is_const(struct regstat *cur, signed char reg)
666 {
667   int hr;
668   if(reg<0) return 0;
669   if(!reg) return 1;
670   for (hr=0;hr<HOST_REGS;hr++) {
671     if((cur->regmap[hr]&63)==reg) {
672       return (cur->isconst>>hr)&1;
673     }
674   }
675   return 0;
676 }
677
678 static uint32_t get_const(struct regstat *cur, signed char reg)
679 {
680   int hr;
681   if(!reg) return 0;
682   for (hr=0;hr<HOST_REGS;hr++) {
683     if(cur->regmap[hr]==reg) {
684       return current_constmap[hr];
685     }
686   }
687   SysPrintf("Unknown constant in r%d\n",reg);
688   abort();
689 }
690
691 // Least soon needed registers
692 // Look at the next ten instructions and see which registers
693 // will be used.  Try not to reallocate these.
694 void lsn(u_char hsn[], int i, int *preferred_reg)
695 {
696   int j;
697   int b=-1;
698   for(j=0;j<9;j++)
699   {
700     if(i+j>=slen) {
701       j=slen-i-1;
702       break;
703     }
704     if (dops[i+j].is_ujump)
705     {
706       // Don't go past an unconditonal jump
707       j++;
708       break;
709     }
710   }
711   for(;j>=0;j--)
712   {
713     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
714     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
715     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
716     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
717     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
718       // Stores can allocate zero
719       hsn[dops[i+j].rs1]=j;
720       hsn[dops[i+j].rs2]=j;
721     }
722     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
723       hsn[ROREG] = j;
724     // On some architectures stores need invc_ptr
725     #if defined(HOST_IMM8)
726     if (dops[i+j].is_store)
727       hsn[INVCP] = j;
728     #endif
729     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
730     {
731       hsn[CCREG]=j;
732       b=j;
733     }
734   }
735   if(b>=0)
736   {
737     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
738     {
739       // Follow first branch
740       int t=(ba[i+b]-start)>>2;
741       j=7-b;if(t+j>=slen) j=slen-t-1;
742       for(;j>=0;j--)
743       {
744         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
745         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
746         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
747         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
748       }
749     }
750     // TODO: preferred register based on backward branch
751   }
752   // Delay slot should preferably not overwrite branch conditions or cycle count
753   if (i > 0 && dops[i-1].is_jump) {
754     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
755     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
756     hsn[CCREG]=1;
757     // ...or hash tables
758     hsn[RHASH]=1;
759     hsn[RHTBL]=1;
760   }
761   // Coprocessor load/store needs FTEMP, even if not declared
762   if(dops[i].itype==C2LS) {
763     hsn[FTEMP]=0;
764   }
765   // Load L/R also uses FTEMP as a temporary register
766   if(dops[i].itype==LOADLR) {
767     hsn[FTEMP]=0;
768   }
769   // Also SWL/SWR/SDL/SDR
770   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
771     hsn[FTEMP]=0;
772   }
773   // Don't remove the miniht registers
774   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
775   {
776     hsn[RHASH]=0;
777     hsn[RHTBL]=0;
778   }
779 }
780
781 // We only want to allocate registers if we're going to use them again soon
782 int needed_again(int r, int i)
783 {
784   int j;
785   int b=-1;
786   int rn=10;
787
788   if (i > 0 && dops[i-1].is_ujump)
789   {
790     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
791       return 0; // Don't need any registers if exiting the block
792   }
793   for(j=0;j<9;j++)
794   {
795     if(i+j>=slen) {
796       j=slen-i-1;
797       break;
798     }
799     if (dops[i+j].is_ujump)
800     {
801       // Don't go past an unconditonal jump
802       j++;
803       break;
804     }
805     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
806     {
807       break;
808     }
809   }
810   for(;j>=1;j--)
811   {
812     if(dops[i+j].rs1==r) rn=j;
813     if(dops[i+j].rs2==r) rn=j;
814     if((unneeded_reg[i+j]>>r)&1) rn=10;
815     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
816     {
817       b=j;
818     }
819   }
820   if(rn<10) return 1;
821   (void)b;
822   return 0;
823 }
824
825 // Try to match register allocations at the end of a loop with those
826 // at the beginning
827 int loop_reg(int i, int r, int hr)
828 {
829   int j,k;
830   for(j=0;j<9;j++)
831   {
832     if(i+j>=slen) {
833       j=slen-i-1;
834       break;
835     }
836     if (dops[i+j].is_ujump)
837     {
838       // Don't go past an unconditonal jump
839       j++;
840       break;
841     }
842   }
843   k=0;
844   if(i>0){
845     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
846       k--;
847   }
848   for(;k<j;k++)
849   {
850     assert(r < 64);
851     if((unneeded_reg[i+k]>>r)&1) return hr;
852     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
853     {
854       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
855       {
856         int t=(ba[i+k]-start)>>2;
857         int reg=get_reg(regs[t].regmap_entry,r);
858         if(reg>=0) return reg;
859         //reg=get_reg(regs[t+1].regmap_entry,r);
860         //if(reg>=0) return reg;
861       }
862     }
863   }
864   return hr;
865 }
866
867
868 // Allocate every register, preserving source/target regs
869 void alloc_all(struct regstat *cur,int i)
870 {
871   int hr;
872
873   for(hr=0;hr<HOST_REGS;hr++) {
874     if(hr!=EXCLUDE_REG) {
875       if(((cur->regmap[hr]&63)!=dops[i].rs1)&&((cur->regmap[hr]&63)!=dops[i].rs2)&&
876          ((cur->regmap[hr]&63)!=dops[i].rt1)&&((cur->regmap[hr]&63)!=dops[i].rt2))
877       {
878         cur->regmap[hr]=-1;
879         cur->dirty&=~(1<<hr);
880       }
881       // Don't need zeros
882       if((cur->regmap[hr]&63)==0)
883       {
884         cur->regmap[hr]=-1;
885         cur->dirty&=~(1<<hr);
886       }
887     }
888   }
889 }
890
891 #ifndef NDEBUG
892 static int host_tempreg_in_use;
893
894 static void host_tempreg_acquire(void)
895 {
896   assert(!host_tempreg_in_use);
897   host_tempreg_in_use = 1;
898 }
899
900 static void host_tempreg_release(void)
901 {
902   host_tempreg_in_use = 0;
903 }
904 #else
905 static void host_tempreg_acquire(void) {}
906 static void host_tempreg_release(void) {}
907 #endif
908
909 #ifdef ASSEM_PRINT
910 extern void gen_interupt();
911 extern void do_insn_cmp();
912 #define FUNCNAME(f) { f, " " #f }
913 static const struct {
914   void *addr;
915   const char *name;
916 } function_names[] = {
917   FUNCNAME(cc_interrupt),
918   FUNCNAME(gen_interupt),
919   FUNCNAME(get_addr_ht),
920   FUNCNAME(get_addr),
921   FUNCNAME(jump_handler_read8),
922   FUNCNAME(jump_handler_read16),
923   FUNCNAME(jump_handler_read32),
924   FUNCNAME(jump_handler_write8),
925   FUNCNAME(jump_handler_write16),
926   FUNCNAME(jump_handler_write32),
927   FUNCNAME(invalidate_addr),
928   FUNCNAME(jump_to_new_pc),
929   FUNCNAME(call_gteStall),
930   FUNCNAME(new_dyna_leave),
931   FUNCNAME(pcsx_mtc0),
932   FUNCNAME(pcsx_mtc0_ds),
933 #ifdef DRC_DBG
934   FUNCNAME(do_insn_cmp),
935 #endif
936 #ifdef __arm__
937   FUNCNAME(verify_code),
938 #endif
939 };
940
941 static const char *func_name(const void *a)
942 {
943   int i;
944   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
945     if (function_names[i].addr == a)
946       return function_names[i].name;
947   return "";
948 }
949 #else
950 #define func_name(x) ""
951 #endif
952
953 #ifdef __i386__
954 #include "assem_x86.c"
955 #endif
956 #ifdef __x86_64__
957 #include "assem_x64.c"
958 #endif
959 #ifdef __arm__
960 #include "assem_arm.c"
961 #endif
962 #ifdef __aarch64__
963 #include "assem_arm64.c"
964 #endif
965
966 static void *get_trampoline(const void *f)
967 {
968   size_t i;
969
970   for (i = 0; i < ARRAY_SIZE(ndrc->tramp.f); i++) {
971     if (ndrc->tramp.f[i] == f || ndrc->tramp.f[i] == NULL)
972       break;
973   }
974   if (i == ARRAY_SIZE(ndrc->tramp.f)) {
975     SysPrintf("trampoline table is full, last func %p\n", f);
976     abort();
977   }
978   if (ndrc->tramp.f[i] == NULL) {
979     start_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
980     ndrc->tramp.f[i] = f;
981     end_tcache_write(&ndrc->tramp.f[i], &ndrc->tramp.f[i + 1]);
982   }
983   return &ndrc->tramp.ops[i];
984 }
985
986 static void emit_far_jump(const void *f)
987 {
988   if (can_jump_or_call(f)) {
989     emit_jmp(f);
990     return;
991   }
992
993   f = get_trampoline(f);
994   emit_jmp(f);
995 }
996
997 static void emit_far_call(const void *f)
998 {
999   if (can_jump_or_call(f)) {
1000     emit_call(f);
1001     return;
1002   }
1003
1004   f = get_trampoline(f);
1005   emit_call(f);
1006 }
1007
1008 // Add virtual address mapping to linked list
1009 void ll_add(struct ll_entry **head,int vaddr,void *addr)
1010 {
1011   struct ll_entry *new_entry;
1012   new_entry=malloc(sizeof(struct ll_entry));
1013   assert(new_entry!=NULL);
1014   new_entry->vaddr=vaddr;
1015   new_entry->reg_sv_flags=0;
1016   new_entry->addr=addr;
1017   new_entry->next=*head;
1018   *head=new_entry;
1019 }
1020
1021 void ll_add_flags(struct ll_entry **head,int vaddr,u_int reg_sv_flags,void *addr)
1022 {
1023   ll_add(head,vaddr,addr);
1024   (*head)->reg_sv_flags=reg_sv_flags;
1025 }
1026
1027 // Check if an address is already compiled
1028 // but don't return addresses which are about to expire from the cache
1029 void *check_addr(u_int vaddr)
1030 {
1031   struct ht_entry *ht_bin = hash_table_get(vaddr);
1032   size_t i;
1033   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1034     if (ht_bin->vaddr[i] == vaddr)
1035       if (doesnt_expire_soon((u_char *)ht_bin->tcaddr[i] - MAX_OUTPUT_BLOCK_SIZE))
1036         if (isclean(ht_bin->tcaddr[i]))
1037           return ht_bin->tcaddr[i];
1038   }
1039   u_int page=get_page(vaddr);
1040   struct ll_entry *head;
1041   head=jump_in[page];
1042   while (head != NULL) {
1043     if (head->vaddr == vaddr) {
1044       if (doesnt_expire_soon(head->addr)) {
1045         // Update existing entry with current address
1046         if (ht_bin->vaddr[0] == vaddr) {
1047           ht_bin->tcaddr[0] = head->addr;
1048           return head->addr;
1049         }
1050         if (ht_bin->vaddr[1] == vaddr) {
1051           ht_bin->tcaddr[1] = head->addr;
1052           return head->addr;
1053         }
1054         // Insert into hash table with low priority.
1055         // Don't evict existing entries, as they are probably
1056         // addresses that are being accessed frequently.
1057         if (ht_bin->vaddr[0] == -1) {
1058           ht_bin->vaddr[0] = vaddr;
1059           ht_bin->tcaddr[0] = head->addr;
1060         }
1061         else if (ht_bin->vaddr[1] == -1) {
1062           ht_bin->vaddr[1] = vaddr;
1063           ht_bin->tcaddr[1] = head->addr;
1064         }
1065         return head->addr;
1066       }
1067     }
1068     head=head->next;
1069   }
1070   return 0;
1071 }
1072
1073 void remove_hash(int vaddr)
1074 {
1075   //printf("remove hash: %x\n",vaddr);
1076   struct ht_entry *ht_bin = hash_table_get(vaddr);
1077   if (ht_bin->vaddr[1] == vaddr) {
1078     ht_bin->vaddr[1] = -1;
1079     ht_bin->tcaddr[1] = NULL;
1080   }
1081   if (ht_bin->vaddr[0] == vaddr) {
1082     ht_bin->vaddr[0] = ht_bin->vaddr[1];
1083     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
1084     ht_bin->vaddr[1] = -1;
1085     ht_bin->tcaddr[1] = NULL;
1086   }
1087 }
1088
1089 static void ll_remove_matching_addrs(struct ll_entry **head,
1090   uintptr_t base_offs_s, int shift)
1091 {
1092   struct ll_entry *next;
1093   while(*head) {
1094     uintptr_t o1 = (u_char *)(*head)->addr - ndrc->translation_cache;
1095     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1096     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1097     {
1098       inv_debug("EXP: Remove pointer to %p (%x)\n",(*head)->addr,(*head)->vaddr);
1099       remove_hash((*head)->vaddr);
1100       next=(*head)->next;
1101       free(*head);
1102       *head=next;
1103     }
1104     else
1105     {
1106       head=&((*head)->next);
1107     }
1108   }
1109 }
1110
1111 // Remove all entries from linked list
1112 void ll_clear(struct ll_entry **head)
1113 {
1114   struct ll_entry *cur;
1115   struct ll_entry *next;
1116   if((cur=*head)) {
1117     *head=0;
1118     while(cur) {
1119       next=cur->next;
1120       free(cur);
1121       cur=next;
1122     }
1123   }
1124 }
1125
1126 // Dereference the pointers and remove if it matches
1127 static void ll_kill_pointers(struct ll_entry *head,
1128   uintptr_t base_offs_s, int shift)
1129 {
1130   while(head) {
1131     u_char *ptr = get_pointer(head->addr);
1132     uintptr_t o1 = ptr - ndrc->translation_cache;
1133     uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
1134     inv_debug("EXP: Lookup pointer to %p at %p (%x)\n",ptr,head->addr,head->vaddr);
1135     if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s)
1136     {
1137       inv_debug("EXP: Kill pointer at %p (%x)\n",head->addr,head->vaddr);
1138       void *host_addr=find_extjump_insn(head->addr);
1139       mark_clear_cache(host_addr);
1140       set_jump_target(host_addr, head->addr);
1141     }
1142     head=head->next;
1143   }
1144 }
1145
1146 // This is called when we write to a compiled block (see do_invstub)
1147 static void invalidate_page(u_int page)
1148 {
1149   struct ll_entry *head;
1150   struct ll_entry *next;
1151   head=jump_in[page];
1152   jump_in[page]=0;
1153   while(head!=NULL) {
1154     inv_debug("INVALIDATE: %x\n",head->vaddr);
1155     remove_hash(head->vaddr);
1156     next=head->next;
1157     free(head);
1158     head=next;
1159   }
1160   head=jump_out[page];
1161   jump_out[page]=0;
1162   while(head!=NULL) {
1163     inv_debug("INVALIDATE: kill pointer to %x (%p)\n",head->vaddr,head->addr);
1164     void *host_addr=find_extjump_insn(head->addr);
1165     mark_clear_cache(host_addr);
1166     set_jump_target(host_addr, head->addr); // point back to dyna_linker
1167     next=head->next;
1168     free(head);
1169     head=next;
1170   }
1171 }
1172
1173 static void invalidate_block_range(u_int block, u_int first, u_int last)
1174 {
1175   u_int page=get_page(block<<12);
1176   //printf("first=%d last=%d\n",first,last);
1177   invalidate_page(page);
1178   assert(first+5>page); // NB: this assumes MAXBLOCK<=4096 (4 pages)
1179   assert(last<page+5);
1180   // Invalidate the adjacent pages if a block crosses a 4K boundary
1181   while(first<page) {
1182     invalidate_page(first);
1183     first++;
1184   }
1185   for(first=page+1;first<last;first++) {
1186     invalidate_page(first);
1187   }
1188   do_clear_cache();
1189
1190   // Don't trap writes
1191   invalid_code[block]=1;
1192
1193   #ifdef USE_MINI_HT
1194   memset(mini_ht,-1,sizeof(mini_ht));
1195   #endif
1196 }
1197
1198 void invalidate_block(u_int block)
1199 {
1200   u_int page=get_page(block<<12);
1201   u_int vpage=get_vpage(block<<12);
1202   inv_debug("INVALIDATE: %x (%d)\n",block<<12,page);
1203   //inv_debug("invalid_code[block]=%d\n",invalid_code[block]);
1204   u_int first,last;
1205   first=last=page;
1206   struct ll_entry *head;
1207   head=jump_dirty[vpage];
1208   //printf("page=%d vpage=%d\n",page,vpage);
1209   while(head!=NULL) {
1210     if(vpage>2047||(head->vaddr>>12)==block) { // Ignore vaddr hash collision
1211       u_char *start, *end;
1212       get_bounds(head->addr, &start, &end);
1213       //printf("start: %p end: %p\n", start, end);
1214       if (page < 2048 && start >= rdram && end < rdram+RAM_SIZE) {
1215         if (((start-rdram)>>12) <= page && ((end-1-rdram)>>12) >= page) {
1216           if ((((start-rdram)>>12)&2047) < first) first = ((start-rdram)>>12)&2047;
1217           if ((((end-1-rdram)>>12)&2047) > last)  last = ((end-1-rdram)>>12)&2047;
1218         }
1219       }
1220     }
1221     head=head->next;
1222   }
1223   invalidate_block_range(block,first,last);
1224 }
1225
1226 void invalidate_addr(u_int addr)
1227 {
1228   //static int rhits;
1229   // this check is done by the caller
1230   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1231   u_int page=get_vpage(addr);
1232   if(page<2048) { // RAM
1233     struct ll_entry *head;
1234     u_int addr_min=~0, addr_max=0;
1235     u_int mask=RAM_SIZE-1;
1236     u_int addr_main=0x80000000|(addr&mask);
1237     int pg1;
1238     inv_code_start=addr_main&~0xfff;
1239     inv_code_end=addr_main|0xfff;
1240     pg1=page;
1241     if (pg1>0) {
1242       // must check previous page too because of spans..
1243       pg1--;
1244       inv_code_start-=0x1000;
1245     }
1246     for(;pg1<=page;pg1++) {
1247       for(head=jump_dirty[pg1];head!=NULL;head=head->next) {
1248         u_char *start_h, *end_h;
1249         u_int start, end;
1250         get_bounds(head->addr, &start_h, &end_h);
1251         start = (uintptr_t)start_h - ram_offset;
1252         end = (uintptr_t)end_h - ram_offset;
1253         if(start<=addr_main&&addr_main<end) {
1254           if(start<addr_min) addr_min=start;
1255           if(end>addr_max) addr_max=end;
1256         }
1257         else if(addr_main<start) {
1258           if(start<inv_code_end)
1259             inv_code_end=start-1;
1260         }
1261         else {
1262           if(end>inv_code_start)
1263             inv_code_start=end;
1264         }
1265       }
1266     }
1267     if (addr_min!=~0) {
1268       inv_debug("INV ADDR: %08x hit %08x-%08x\n", addr, addr_min, addr_max);
1269       inv_code_start=inv_code_end=~0;
1270       invalidate_block_range(addr>>12,(addr_min&mask)>>12,(addr_max&mask)>>12);
1271       return;
1272     }
1273     else {
1274       inv_code_start=(addr&~mask)|(inv_code_start&mask);
1275       inv_code_end=(addr&~mask)|(inv_code_end&mask);
1276       inv_debug("INV ADDR: %08x miss, inv %08x-%08x, sk %d\n", addr, inv_code_start, inv_code_end, 0);
1277       return;
1278     }
1279   }
1280   invalidate_block(addr>>12);
1281 }
1282
1283 // This is called when loading a save state.
1284 // Anything could have changed, so invalidate everything.
1285 void invalidate_all_pages(void)
1286 {
1287   u_int page;
1288   for(page=0;page<4096;page++)
1289     invalidate_page(page);
1290   for(page=0;page<1048576;page++)
1291     if(!invalid_code[page]) {
1292       restore_candidate[(page&2047)>>3]|=1<<(page&7);
1293       restore_candidate[((page&2047)>>3)+256]|=1<<(page&7);
1294     }
1295   #ifdef USE_MINI_HT
1296   memset(mini_ht,-1,sizeof(mini_ht));
1297   #endif
1298   do_clear_cache();
1299 }
1300
1301 static void do_invstub(int n)
1302 {
1303   literal_pool(20);
1304   u_int reglist=stubs[n].a;
1305   set_jump_target(stubs[n].addr, out);
1306   save_regs(reglist);
1307   if(stubs[n].b!=0) emit_mov(stubs[n].b,0);
1308   emit_far_call(invalidate_addr);
1309   restore_regs(reglist);
1310   emit_jmp(stubs[n].retaddr); // return address
1311 }
1312
1313 // Add an entry to jump_out after making a link
1314 // src should point to code by emit_extjump2()
1315 void add_jump_out(u_int vaddr,void *src)
1316 {
1317   u_int page=get_page(vaddr);
1318   inv_debug("add_jump_out: %p -> %x (%d)\n",src,vaddr,page);
1319   check_extjump2(src);
1320   ll_add(jump_out+page,vaddr,src);
1321   //inv_debug("add_jump_out:  to %p\n",get_pointer(src));
1322 }
1323
1324 // If a code block was found to be unmodified (bit was set in
1325 // restore_candidate) and it remains unmodified (bit is clear
1326 // in invalid_code) then move the entries for that 4K page from
1327 // the dirty list to the clean list.
1328 void clean_blocks(u_int page)
1329 {
1330   struct ll_entry *head;
1331   inv_debug("INV: clean_blocks page=%d\n",page);
1332   head=jump_dirty[page];
1333   while(head!=NULL) {
1334     if(!invalid_code[head->vaddr>>12]) {
1335       // Don't restore blocks which are about to expire from the cache
1336       if (doesnt_expire_soon(head->addr)) {
1337         if(verify_dirty(head->addr)) {
1338           u_char *start, *end;
1339           //printf("Possibly Restore %x (%p)\n",head->vaddr, head->addr);
1340           u_int i;
1341           u_int inv=0;
1342           get_bounds(head->addr, &start, &end);
1343           if (start - rdram < RAM_SIZE) {
1344             for (i = (start-rdram+0x80000000)>>12; i <= (end-1-rdram+0x80000000)>>12; i++) {
1345               inv|=invalid_code[i];
1346             }
1347           }
1348           else if((signed int)head->vaddr>=(signed int)0x80000000+RAM_SIZE) {
1349             inv=1;
1350           }
1351           if(!inv) {
1352             void *clean_addr = get_clean_addr(head->addr);
1353             if (doesnt_expire_soon(clean_addr)) {
1354               u_int ppage=page;
1355               inv_debug("INV: Restored %x (%p/%p)\n",head->vaddr, head->addr, clean_addr);
1356               //printf("page=%x, addr=%x\n",page,head->vaddr);
1357               //assert(head->vaddr>>12==(page|0x80000));
1358               ll_add_flags(jump_in+ppage,head->vaddr,head->reg_sv_flags,clean_addr);
1359               struct ht_entry *ht_bin = hash_table_get(head->vaddr);
1360               if (ht_bin->vaddr[0] == head->vaddr)
1361                 ht_bin->tcaddr[0] = clean_addr; // Replace existing entry
1362               if (ht_bin->vaddr[1] == head->vaddr)
1363                 ht_bin->tcaddr[1] = clean_addr; // Replace existing entry
1364             }
1365           }
1366         }
1367       }
1368     }
1369     head=head->next;
1370   }
1371 }
1372
1373 /* Register allocation */
1374
1375 // Note: registers are allocated clean (unmodified state)
1376 // if you intend to modify the register, you must call dirty_reg().
1377 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1378 {
1379   int r,hr;
1380   int preferred_reg = PREFERRED_REG_FIRST
1381     + reg % (PREFERRED_REG_LAST - PREFERRED_REG_FIRST + 1);
1382   if (reg == CCREG) preferred_reg = HOST_CCREG;
1383   if (reg == PTEMP || reg == FTEMP) preferred_reg = 12;
1384   assert(PREFERRED_REG_FIRST != EXCLUDE_REG && EXCLUDE_REG != HOST_REGS);
1385
1386   // Don't allocate unused registers
1387   if((cur->u>>reg)&1) return;
1388
1389   // see if it's already allocated
1390   for(hr=0;hr<HOST_REGS;hr++)
1391   {
1392     if(cur->regmap[hr]==reg) return;
1393   }
1394
1395   // Keep the same mapping if the register was already allocated in a loop
1396   preferred_reg = loop_reg(i,reg,preferred_reg);
1397
1398   // Try to allocate the preferred register
1399   if(cur->regmap[preferred_reg]==-1) {
1400     cur->regmap[preferred_reg]=reg;
1401     cur->dirty&=~(1<<preferred_reg);
1402     cur->isconst&=~(1<<preferred_reg);
1403     return;
1404   }
1405   r=cur->regmap[preferred_reg];
1406   assert(r < 64);
1407   if((cur->u>>r)&1) {
1408     cur->regmap[preferred_reg]=reg;
1409     cur->dirty&=~(1<<preferred_reg);
1410     cur->isconst&=~(1<<preferred_reg);
1411     return;
1412   }
1413
1414   // Clear any unneeded registers
1415   // We try to keep the mapping consistent, if possible, because it
1416   // makes branches easier (especially loops).  So we try to allocate
1417   // first (see above) before removing old mappings.  If this is not
1418   // possible then go ahead and clear out the registers that are no
1419   // longer needed.
1420   for(hr=0;hr<HOST_REGS;hr++)
1421   {
1422     r=cur->regmap[hr];
1423     if(r>=0) {
1424       assert(r < 64);
1425       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1426     }
1427   }
1428
1429   // Try to allocate any available register, but prefer
1430   // registers that have not been used recently.
1431   if (i > 0) {
1432     for (hr = PREFERRED_REG_FIRST; ; ) {
1433       if (cur->regmap[hr] < 0) {
1434         int oldreg = regs[i-1].regmap[hr];
1435         if (oldreg < 0 || (oldreg != dops[i-1].rs1 && oldreg != dops[i-1].rs2
1436              && oldreg != dops[i-1].rt1 && oldreg != dops[i-1].rt2))
1437         {
1438           cur->regmap[hr]=reg;
1439           cur->dirty&=~(1<<hr);
1440           cur->isconst&=~(1<<hr);
1441           return;
1442         }
1443       }
1444       hr++;
1445       if (hr == EXCLUDE_REG)
1446         hr++;
1447       if (hr == HOST_REGS)
1448         hr = 0;
1449       if (hr == PREFERRED_REG_FIRST)
1450         break;
1451     }
1452   }
1453
1454   // Try to allocate any available register
1455   for (hr = PREFERRED_REG_FIRST; ; ) {
1456     if (cur->regmap[hr] < 0) {
1457       cur->regmap[hr]=reg;
1458       cur->dirty&=~(1<<hr);
1459       cur->isconst&=~(1<<hr);
1460       return;
1461     }
1462     hr++;
1463     if (hr == EXCLUDE_REG)
1464       hr++;
1465     if (hr == HOST_REGS)
1466       hr = 0;
1467     if (hr == PREFERRED_REG_FIRST)
1468       break;
1469   }
1470
1471   // Ok, now we have to evict someone
1472   // Pick a register we hopefully won't need soon
1473   u_char hsn[MAXREG+1];
1474   memset(hsn,10,sizeof(hsn));
1475   int j;
1476   lsn(hsn,i,&preferred_reg);
1477   //printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",cur->regmap[0],cur->regmap[1],cur->regmap[2],cur->regmap[3],cur->regmap[5],cur->regmap[6],cur->regmap[7]);
1478   //printf("hsn(%x): %d %d %d %d %d %d %d\n",start+i*4,hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1479   if(i>0) {
1480     // Don't evict the cycle count at entry points, otherwise the entry
1481     // stub will have to write it.
1482     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1483     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1484     for(j=10;j>=3;j--)
1485     {
1486       // Alloc preferred register if available
1487       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1488         for(hr=0;hr<HOST_REGS;hr++) {
1489           // Evict both parts of a 64-bit register
1490           if((cur->regmap[hr]&63)==r) {
1491             cur->regmap[hr]=-1;
1492             cur->dirty&=~(1<<hr);
1493             cur->isconst&=~(1<<hr);
1494           }
1495         }
1496         cur->regmap[preferred_reg]=reg;
1497         return;
1498       }
1499       for(r=1;r<=MAXREG;r++)
1500       {
1501         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1502           for(hr=0;hr<HOST_REGS;hr++) {
1503             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1504               if(cur->regmap[hr]==r) {
1505                 cur->regmap[hr]=reg;
1506                 cur->dirty&=~(1<<hr);
1507                 cur->isconst&=~(1<<hr);
1508                 return;
1509               }
1510             }
1511           }
1512         }
1513       }
1514     }
1515   }
1516   for(j=10;j>=0;j--)
1517   {
1518     for(r=1;r<=MAXREG;r++)
1519     {
1520       if(hsn[r]==j) {
1521         for(hr=0;hr<HOST_REGS;hr++) {
1522           if(cur->regmap[hr]==r) {
1523             cur->regmap[hr]=reg;
1524             cur->dirty&=~(1<<hr);
1525             cur->isconst&=~(1<<hr);
1526             return;
1527           }
1528         }
1529       }
1530     }
1531   }
1532   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1533 }
1534
1535 // Allocate a temporary register.  This is done without regard to
1536 // dirty status or whether the register we request is on the unneeded list
1537 // Note: This will only allocate one register, even if called multiple times
1538 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1539 {
1540   int r,hr;
1541   int preferred_reg = -1;
1542
1543   // see if it's already allocated
1544   for(hr=0;hr<HOST_REGS;hr++)
1545   {
1546     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1547   }
1548
1549   // Try to allocate any available register
1550   for(hr=HOST_REGS-1;hr>=0;hr--) {
1551     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1552       cur->regmap[hr]=reg;
1553       cur->dirty&=~(1<<hr);
1554       cur->isconst&=~(1<<hr);
1555       return;
1556     }
1557   }
1558
1559   // Find an unneeded register
1560   for(hr=HOST_REGS-1;hr>=0;hr--)
1561   {
1562     r=cur->regmap[hr];
1563     if(r>=0) {
1564       assert(r < 64);
1565       if((cur->u>>r)&1) {
1566         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1567           cur->regmap[hr]=reg;
1568           cur->dirty&=~(1<<hr);
1569           cur->isconst&=~(1<<hr);
1570           return;
1571         }
1572       }
1573     }
1574   }
1575
1576   // Ok, now we have to evict someone
1577   // Pick a register we hopefully won't need soon
1578   // TODO: we might want to follow unconditional jumps here
1579   // TODO: get rid of dupe code and make this into a function
1580   u_char hsn[MAXREG+1];
1581   memset(hsn,10,sizeof(hsn));
1582   int j;
1583   lsn(hsn,i,&preferred_reg);
1584   //printf("hsn: %d %d %d %d %d %d %d\n",hsn[cur->regmap[0]&63],hsn[cur->regmap[1]&63],hsn[cur->regmap[2]&63],hsn[cur->regmap[3]&63],hsn[cur->regmap[5]&63],hsn[cur->regmap[6]&63],hsn[cur->regmap[7]&63]);
1585   if(i>0) {
1586     // Don't evict the cycle count at entry points, otherwise the entry
1587     // stub will have to write it.
1588     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1589     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1590     for(j=10;j>=3;j--)
1591     {
1592       for(r=1;r<=MAXREG;r++)
1593       {
1594         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1595           for(hr=0;hr<HOST_REGS;hr++) {
1596             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1597               if(cur->regmap[hr]==r) {
1598                 cur->regmap[hr]=reg;
1599                 cur->dirty&=~(1<<hr);
1600                 cur->isconst&=~(1<<hr);
1601                 return;
1602               }
1603             }
1604           }
1605         }
1606       }
1607     }
1608   }
1609   for(j=10;j>=0;j--)
1610   {
1611     for(r=1;r<=MAXREG;r++)
1612     {
1613       if(hsn[r]==j) {
1614         for(hr=0;hr<HOST_REGS;hr++) {
1615           if(cur->regmap[hr]==r) {
1616             cur->regmap[hr]=reg;
1617             cur->dirty&=~(1<<hr);
1618             cur->isconst&=~(1<<hr);
1619             return;
1620           }
1621         }
1622       }
1623     }
1624   }
1625   SysPrintf("This shouldn't happen");abort();
1626 }
1627
1628 static void mov_alloc(struct regstat *current,int i)
1629 {
1630   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1631     alloc_cc(current,i); // for stalls
1632     dirty_reg(current,CCREG);
1633   }
1634
1635   // Note: Don't need to actually alloc the source registers
1636   //alloc_reg(current,i,dops[i].rs1);
1637   alloc_reg(current,i,dops[i].rt1);
1638
1639   clear_const(current,dops[i].rs1);
1640   clear_const(current,dops[i].rt1);
1641   dirty_reg(current,dops[i].rt1);
1642 }
1643
1644 static void shiftimm_alloc(struct regstat *current,int i)
1645 {
1646   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1647   {
1648     if(dops[i].rt1) {
1649       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1650       else dops[i].lt1=dops[i].rs1;
1651       alloc_reg(current,i,dops[i].rt1);
1652       dirty_reg(current,dops[i].rt1);
1653       if(is_const(current,dops[i].rs1)) {
1654         int v=get_const(current,dops[i].rs1);
1655         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1656         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1657         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1658       }
1659       else clear_const(current,dops[i].rt1);
1660     }
1661   }
1662   else
1663   {
1664     clear_const(current,dops[i].rs1);
1665     clear_const(current,dops[i].rt1);
1666   }
1667
1668   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1669   {
1670     assert(0);
1671   }
1672   if(dops[i].opcode2==0x3c) // DSLL32
1673   {
1674     assert(0);
1675   }
1676   if(dops[i].opcode2==0x3e) // DSRL32
1677   {
1678     assert(0);
1679   }
1680   if(dops[i].opcode2==0x3f) // DSRA32
1681   {
1682     assert(0);
1683   }
1684 }
1685
1686 static void shift_alloc(struct regstat *current,int i)
1687 {
1688   if(dops[i].rt1) {
1689     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1690     {
1691       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1692       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1693       alloc_reg(current,i,dops[i].rt1);
1694       if(dops[i].rt1==dops[i].rs2) {
1695         alloc_reg_temp(current,i,-1);
1696         minimum_free_regs[i]=1;
1697       }
1698     } else { // DSLLV/DSRLV/DSRAV
1699       assert(0);
1700     }
1701     clear_const(current,dops[i].rs1);
1702     clear_const(current,dops[i].rs2);
1703     clear_const(current,dops[i].rt1);
1704     dirty_reg(current,dops[i].rt1);
1705   }
1706 }
1707
1708 static void alu_alloc(struct regstat *current,int i)
1709 {
1710   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1711     if(dops[i].rt1) {
1712       if(dops[i].rs1&&dops[i].rs2) {
1713         alloc_reg(current,i,dops[i].rs1);
1714         alloc_reg(current,i,dops[i].rs2);
1715       }
1716       else {
1717         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1718         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1719       }
1720       alloc_reg(current,i,dops[i].rt1);
1721     }
1722   }
1723   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1724     if(dops[i].rt1) {
1725       alloc_reg(current,i,dops[i].rs1);
1726       alloc_reg(current,i,dops[i].rs2);
1727       alloc_reg(current,i,dops[i].rt1);
1728     }
1729   }
1730   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1731     if(dops[i].rt1) {
1732       if(dops[i].rs1&&dops[i].rs2) {
1733         alloc_reg(current,i,dops[i].rs1);
1734         alloc_reg(current,i,dops[i].rs2);
1735       }
1736       else
1737       {
1738         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1739         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1740       }
1741       alloc_reg(current,i,dops[i].rt1);
1742     }
1743   }
1744   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1745     assert(0);
1746   }
1747   clear_const(current,dops[i].rs1);
1748   clear_const(current,dops[i].rs2);
1749   clear_const(current,dops[i].rt1);
1750   dirty_reg(current,dops[i].rt1);
1751 }
1752
1753 static void imm16_alloc(struct regstat *current,int i)
1754 {
1755   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1756   else dops[i].lt1=dops[i].rs1;
1757   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1758   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1759     assert(0);
1760   }
1761   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1762     clear_const(current,dops[i].rs1);
1763     clear_const(current,dops[i].rt1);
1764   }
1765   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1766     if(is_const(current,dops[i].rs1)) {
1767       int v=get_const(current,dops[i].rs1);
1768       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1769       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1770       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1771     }
1772     else clear_const(current,dops[i].rt1);
1773   }
1774   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1775     if(is_const(current,dops[i].rs1)) {
1776       int v=get_const(current,dops[i].rs1);
1777       set_const(current,dops[i].rt1,v+imm[i]);
1778     }
1779     else clear_const(current,dops[i].rt1);
1780   }
1781   else {
1782     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1783   }
1784   dirty_reg(current,dops[i].rt1);
1785 }
1786
1787 static void load_alloc(struct regstat *current,int i)
1788 {
1789   clear_const(current,dops[i].rt1);
1790   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
1791   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
1792   if (needed_again(dops[i].rs1, i))
1793     alloc_reg(current, i, dops[i].rs1);
1794   if (ram_offset)
1795     alloc_reg(current, i, ROREG);
1796   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
1797     alloc_reg(current,i,dops[i].rt1);
1798     assert(get_reg(current->regmap,dops[i].rt1)>=0);
1799     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
1800     {
1801       assert(0);
1802     }
1803     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1804     {
1805       assert(0);
1806     }
1807     dirty_reg(current,dops[i].rt1);
1808     // LWL/LWR need a temporary register for the old value
1809     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1810     {
1811       alloc_reg(current,i,FTEMP);
1812       alloc_reg_temp(current,i,-1);
1813       minimum_free_regs[i]=1;
1814     }
1815   }
1816   else
1817   {
1818     // Load to r0 or unneeded register (dummy load)
1819     // but we still need a register to calculate the address
1820     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
1821     {
1822       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
1823     }
1824     alloc_reg_temp(current,i,-1);
1825     minimum_free_regs[i]=1;
1826     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1827     {
1828       assert(0);
1829     }
1830   }
1831 }
1832
1833 void store_alloc(struct regstat *current,int i)
1834 {
1835   clear_const(current,dops[i].rs2);
1836   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
1837   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1838   alloc_reg(current,i,dops[i].rs2);
1839   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
1840     assert(0);
1841   }
1842   if (ram_offset)
1843     alloc_reg(current, i, ROREG);
1844   #if defined(HOST_IMM8)
1845   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1846   alloc_reg(current, i, INVCP);
1847   #endif
1848   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
1849     alloc_reg(current,i,FTEMP);
1850   }
1851   // We need a temporary register for address generation
1852   alloc_reg_temp(current,i,-1);
1853   minimum_free_regs[i]=1;
1854 }
1855
1856 void c1ls_alloc(struct regstat *current,int i)
1857 {
1858   clear_const(current,dops[i].rt1);
1859   alloc_reg(current,i,CSREG); // Status
1860 }
1861
1862 void c2ls_alloc(struct regstat *current,int i)
1863 {
1864   clear_const(current,dops[i].rt1);
1865   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1866   alloc_reg(current,i,FTEMP);
1867   if (ram_offset)
1868     alloc_reg(current, i, ROREG);
1869   #if defined(HOST_IMM8)
1870   // On CPUs without 32-bit immediates we need a pointer to invalid_code
1871   if (dops[i].opcode == 0x3a) // SWC2
1872     alloc_reg(current,i,INVCP);
1873   #endif
1874   // We need a temporary register for address generation
1875   alloc_reg_temp(current,i,-1);
1876   minimum_free_regs[i]=1;
1877 }
1878
1879 #ifndef multdiv_alloc
1880 void multdiv_alloc(struct regstat *current,int i)
1881 {
1882   //  case 0x18: MULT
1883   //  case 0x19: MULTU
1884   //  case 0x1A: DIV
1885   //  case 0x1B: DIVU
1886   //  case 0x1C: DMULT
1887   //  case 0x1D: DMULTU
1888   //  case 0x1E: DDIV
1889   //  case 0x1F: DDIVU
1890   clear_const(current,dops[i].rs1);
1891   clear_const(current,dops[i].rs2);
1892   alloc_cc(current,i); // for stalls
1893   if(dops[i].rs1&&dops[i].rs2)
1894   {
1895     if((dops[i].opcode2&4)==0) // 32-bit
1896     {
1897       current->u&=~(1LL<<HIREG);
1898       current->u&=~(1LL<<LOREG);
1899       alloc_reg(current,i,HIREG);
1900       alloc_reg(current,i,LOREG);
1901       alloc_reg(current,i,dops[i].rs1);
1902       alloc_reg(current,i,dops[i].rs2);
1903       dirty_reg(current,HIREG);
1904       dirty_reg(current,LOREG);
1905     }
1906     else // 64-bit
1907     {
1908       assert(0);
1909     }
1910   }
1911   else
1912   {
1913     // Multiply by zero is zero.
1914     // MIPS does not have a divide by zero exception.
1915     // The result is undefined, we return zero.
1916     alloc_reg(current,i,HIREG);
1917     alloc_reg(current,i,LOREG);
1918     dirty_reg(current,HIREG);
1919     dirty_reg(current,LOREG);
1920   }
1921 }
1922 #endif
1923
1924 void cop0_alloc(struct regstat *current,int i)
1925 {
1926   if(dops[i].opcode2==0) // MFC0
1927   {
1928     if(dops[i].rt1) {
1929       clear_const(current,dops[i].rt1);
1930       alloc_all(current,i);
1931       alloc_reg(current,i,dops[i].rt1);
1932       dirty_reg(current,dops[i].rt1);
1933     }
1934   }
1935   else if(dops[i].opcode2==4) // MTC0
1936   {
1937     if(dops[i].rs1){
1938       clear_const(current,dops[i].rs1);
1939       alloc_reg(current,i,dops[i].rs1);
1940       alloc_all(current,i);
1941     }
1942     else {
1943       alloc_all(current,i); // FIXME: Keep r0
1944       current->u&=~1LL;
1945       alloc_reg(current,i,0);
1946     }
1947   }
1948   else
1949   {
1950     // TLBR/TLBWI/TLBWR/TLBP/ERET
1951     assert(dops[i].opcode2==0x10);
1952     alloc_all(current,i);
1953   }
1954   minimum_free_regs[i]=HOST_REGS;
1955 }
1956
1957 static void cop2_alloc(struct regstat *current,int i)
1958 {
1959   if (dops[i].opcode2 < 3) // MFC2/CFC2
1960   {
1961     alloc_cc(current,i); // for stalls
1962     dirty_reg(current,CCREG);
1963     if(dops[i].rt1){
1964       clear_const(current,dops[i].rt1);
1965       alloc_reg(current,i,dops[i].rt1);
1966       dirty_reg(current,dops[i].rt1);
1967     }
1968   }
1969   else if (dops[i].opcode2 > 3) // MTC2/CTC2
1970   {
1971     if(dops[i].rs1){
1972       clear_const(current,dops[i].rs1);
1973       alloc_reg(current,i,dops[i].rs1);
1974     }
1975     else {
1976       current->u&=~1LL;
1977       alloc_reg(current,i,0);
1978     }
1979   }
1980   alloc_reg_temp(current,i,-1);
1981   minimum_free_regs[i]=1;
1982 }
1983
1984 void c2op_alloc(struct regstat *current,int i)
1985 {
1986   alloc_cc(current,i); // for stalls
1987   dirty_reg(current,CCREG);
1988   alloc_reg_temp(current,i,-1);
1989 }
1990
1991 void syscall_alloc(struct regstat *current,int i)
1992 {
1993   alloc_cc(current,i);
1994   dirty_reg(current,CCREG);
1995   alloc_all(current,i);
1996   minimum_free_regs[i]=HOST_REGS;
1997   current->isconst=0;
1998 }
1999
2000 void delayslot_alloc(struct regstat *current,int i)
2001 {
2002   switch(dops[i].itype) {
2003     case UJUMP:
2004     case CJUMP:
2005     case SJUMP:
2006     case RJUMP:
2007     case SYSCALL:
2008     case HLECALL:
2009     case SPAN:
2010       assem_debug("jump in the delay slot.  this shouldn't happen.\n");//abort();
2011       SysPrintf("Disabled speculative precompilation\n");
2012       stop_after_jal=1;
2013       break;
2014     case IMM16:
2015       imm16_alloc(current,i);
2016       break;
2017     case LOAD:
2018     case LOADLR:
2019       load_alloc(current,i);
2020       break;
2021     case STORE:
2022     case STORELR:
2023       store_alloc(current,i);
2024       break;
2025     case ALU:
2026       alu_alloc(current,i);
2027       break;
2028     case SHIFT:
2029       shift_alloc(current,i);
2030       break;
2031     case MULTDIV:
2032       multdiv_alloc(current,i);
2033       break;
2034     case SHIFTIMM:
2035       shiftimm_alloc(current,i);
2036       break;
2037     case MOV:
2038       mov_alloc(current,i);
2039       break;
2040     case COP0:
2041       cop0_alloc(current,i);
2042       break;
2043     case COP1:
2044       break;
2045     case COP2:
2046       cop2_alloc(current,i);
2047       break;
2048     case C1LS:
2049       c1ls_alloc(current,i);
2050       break;
2051     case C2LS:
2052       c2ls_alloc(current,i);
2053       break;
2054     case C2OP:
2055       c2op_alloc(current,i);
2056       break;
2057   }
2058 }
2059
2060 // Special case where a branch and delay slot span two pages in virtual memory
2061 static void pagespan_alloc(struct regstat *current,int i)
2062 {
2063   current->isconst=0;
2064   current->wasconst=0;
2065   regs[i].wasconst=0;
2066   minimum_free_regs[i]=HOST_REGS;
2067   alloc_all(current,i);
2068   alloc_cc(current,i);
2069   dirty_reg(current,CCREG);
2070   if(dops[i].opcode==3) // JAL
2071   {
2072     alloc_reg(current,i,31);
2073     dirty_reg(current,31);
2074   }
2075   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
2076   {
2077     alloc_reg(current,i,dops[i].rs1);
2078     if (dops[i].rt1!=0) {
2079       alloc_reg(current,i,dops[i].rt1);
2080       dirty_reg(current,dops[i].rt1);
2081     }
2082   }
2083   if((dops[i].opcode&0x2E)==4) // BEQ/BNE/BEQL/BNEL
2084   {
2085     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2086     if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
2087   }
2088   else
2089   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ/BLEZL/BGTZL
2090   {
2091     if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
2092   }
2093   //else ...
2094 }
2095
2096 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2097   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2098 {
2099   assert(stubcount < ARRAY_SIZE(stubs));
2100   stubs[stubcount].type = type;
2101   stubs[stubcount].addr = addr;
2102   stubs[stubcount].retaddr = retaddr;
2103   stubs[stubcount].a = a;
2104   stubs[stubcount].b = b;
2105   stubs[stubcount].c = c;
2106   stubs[stubcount].d = d;
2107   stubs[stubcount].e = e;
2108   stubcount++;
2109 }
2110
2111 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2112   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2113 {
2114   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2115 }
2116
2117 // Write out a single register
2118 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty)
2119 {
2120   int hr;
2121   for(hr=0;hr<HOST_REGS;hr++) {
2122     if(hr!=EXCLUDE_REG) {
2123       if((regmap[hr]&63)==r) {
2124         if((dirty>>hr)&1) {
2125           assert(regmap[hr]<64);
2126           emit_storereg(r,hr);
2127         }
2128       }
2129     }
2130   }
2131 }
2132
2133 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2134 {
2135   //if(dirty_pre==dirty) return;
2136   int hr,reg;
2137   for(hr=0;hr<HOST_REGS;hr++) {
2138     if(hr!=EXCLUDE_REG) {
2139       reg=pre[hr];
2140       if(((~u)>>(reg&63))&1) {
2141         if(reg>0) {
2142           if(((dirty_pre&~dirty)>>hr)&1) {
2143             if(reg>0&&reg<34) {
2144               emit_storereg(reg,hr);
2145             }
2146             else if(reg>=64) {
2147               assert(0);
2148             }
2149           }
2150         }
2151       }
2152     }
2153   }
2154 }
2155
2156 // trashes r2
2157 static void pass_args(int a0, int a1)
2158 {
2159   if(a0==1&&a1==0) {
2160     // must swap
2161     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2162   }
2163   else if(a0!=0&&a1==0) {
2164     emit_mov(a1,1);
2165     if (a0>=0) emit_mov(a0,0);
2166   }
2167   else {
2168     if(a0>=0&&a0!=0) emit_mov(a0,0);
2169     if(a1>=0&&a1!=1) emit_mov(a1,1);
2170   }
2171 }
2172
2173 static void alu_assemble(int i, const struct regstat *i_regs)
2174 {
2175   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2176     if(dops[i].rt1) {
2177       signed char s1,s2,t;
2178       t=get_reg(i_regs->regmap,dops[i].rt1);
2179       if(t>=0) {
2180         s1=get_reg(i_regs->regmap,dops[i].rs1);
2181         s2=get_reg(i_regs->regmap,dops[i].rs2);
2182         if(dops[i].rs1&&dops[i].rs2) {
2183           assert(s1>=0);
2184           assert(s2>=0);
2185           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2186           else emit_add(s1,s2,t);
2187         }
2188         else if(dops[i].rs1) {
2189           if(s1>=0) emit_mov(s1,t);
2190           else emit_loadreg(dops[i].rs1,t);
2191         }
2192         else if(dops[i].rs2) {
2193           if(s2>=0) {
2194             if(dops[i].opcode2&2) emit_neg(s2,t);
2195             else emit_mov(s2,t);
2196           }
2197           else {
2198             emit_loadreg(dops[i].rs2,t);
2199             if(dops[i].opcode2&2) emit_neg(t,t);
2200           }
2201         }
2202         else emit_zeroreg(t);
2203       }
2204     }
2205   }
2206   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2207     assert(0);
2208   }
2209   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2210     if(dops[i].rt1) {
2211       signed char s1l,s2l,t;
2212       {
2213         t=get_reg(i_regs->regmap,dops[i].rt1);
2214         //assert(t>=0);
2215         if(t>=0) {
2216           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2217           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2218           if(dops[i].rs2==0) // rx<r0
2219           {
2220             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2221               assert(s1l>=0);
2222               emit_shrimm(s1l,31,t);
2223             }
2224             else // SLTU (unsigned can not be less than zero, 0<0)
2225               emit_zeroreg(t);
2226           }
2227           else if(dops[i].rs1==0) // r0<rx
2228           {
2229             assert(s2l>=0);
2230             if(dops[i].opcode2==0x2a) // SLT
2231               emit_set_gz32(s2l,t);
2232             else // SLTU (set if not zero)
2233               emit_set_nz32(s2l,t);
2234           }
2235           else{
2236             assert(s1l>=0);assert(s2l>=0);
2237             if(dops[i].opcode2==0x2a) // SLT
2238               emit_set_if_less32(s1l,s2l,t);
2239             else // SLTU
2240               emit_set_if_carry32(s1l,s2l,t);
2241           }
2242         }
2243       }
2244     }
2245   }
2246   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2247     if(dops[i].rt1) {
2248       signed char s1l,s2l,tl;
2249       tl=get_reg(i_regs->regmap,dops[i].rt1);
2250       {
2251         if(tl>=0) {
2252           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2253           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2254           if(dops[i].rs1&&dops[i].rs2) {
2255             assert(s1l>=0);
2256             assert(s2l>=0);
2257             if(dops[i].opcode2==0x24) { // AND
2258               emit_and(s1l,s2l,tl);
2259             } else
2260             if(dops[i].opcode2==0x25) { // OR
2261               emit_or(s1l,s2l,tl);
2262             } else
2263             if(dops[i].opcode2==0x26) { // XOR
2264               emit_xor(s1l,s2l,tl);
2265             } else
2266             if(dops[i].opcode2==0x27) { // NOR
2267               emit_or(s1l,s2l,tl);
2268               emit_not(tl,tl);
2269             }
2270           }
2271           else
2272           {
2273             if(dops[i].opcode2==0x24) { // AND
2274               emit_zeroreg(tl);
2275             } else
2276             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2277               if(dops[i].rs1){
2278                 if(s1l>=0) emit_mov(s1l,tl);
2279                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2280               }
2281               else
2282               if(dops[i].rs2){
2283                 if(s2l>=0) emit_mov(s2l,tl);
2284                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2285               }
2286               else emit_zeroreg(tl);
2287             } else
2288             if(dops[i].opcode2==0x27) { // NOR
2289               if(dops[i].rs1){
2290                 if(s1l>=0) emit_not(s1l,tl);
2291                 else {
2292                   emit_loadreg(dops[i].rs1,tl);
2293                   emit_not(tl,tl);
2294                 }
2295               }
2296               else
2297               if(dops[i].rs2){
2298                 if(s2l>=0) emit_not(s2l,tl);
2299                 else {
2300                   emit_loadreg(dops[i].rs2,tl);
2301                   emit_not(tl,tl);
2302                 }
2303               }
2304               else emit_movimm(-1,tl);
2305             }
2306           }
2307         }
2308       }
2309     }
2310   }
2311 }
2312
2313 static void imm16_assemble(int i, const struct regstat *i_regs)
2314 {
2315   if (dops[i].opcode==0x0f) { // LUI
2316     if(dops[i].rt1) {
2317       signed char t;
2318       t=get_reg(i_regs->regmap,dops[i].rt1);
2319       //assert(t>=0);
2320       if(t>=0) {
2321         if(!((i_regs->isconst>>t)&1))
2322           emit_movimm(imm[i]<<16,t);
2323       }
2324     }
2325   }
2326   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2327     if(dops[i].rt1) {
2328       signed char s,t;
2329       t=get_reg(i_regs->regmap,dops[i].rt1);
2330       s=get_reg(i_regs->regmap,dops[i].rs1);
2331       if(dops[i].rs1) {
2332         //assert(t>=0);
2333         //assert(s>=0);
2334         if(t>=0) {
2335           if(!((i_regs->isconst>>t)&1)) {
2336             if(s<0) {
2337               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2338               emit_addimm(t,imm[i],t);
2339             }else{
2340               if(!((i_regs->wasconst>>s)&1))
2341                 emit_addimm(s,imm[i],t);
2342               else
2343                 emit_movimm(constmap[i][s]+imm[i],t);
2344             }
2345           }
2346         }
2347       } else {
2348         if(t>=0) {
2349           if(!((i_regs->isconst>>t)&1))
2350             emit_movimm(imm[i],t);
2351         }
2352       }
2353     }
2354   }
2355   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2356     if(dops[i].rt1) {
2357       signed char sl,tl;
2358       tl=get_reg(i_regs->regmap,dops[i].rt1);
2359       sl=get_reg(i_regs->regmap,dops[i].rs1);
2360       if(tl>=0) {
2361         if(dops[i].rs1) {
2362           assert(sl>=0);
2363           emit_addimm(sl,imm[i],tl);
2364         } else {
2365           emit_movimm(imm[i],tl);
2366         }
2367       }
2368     }
2369   }
2370   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2371     if(dops[i].rt1) {
2372       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2373       signed char sl,t;
2374       t=get_reg(i_regs->regmap,dops[i].rt1);
2375       sl=get_reg(i_regs->regmap,dops[i].rs1);
2376       //assert(t>=0);
2377       if(t>=0) {
2378         if(dops[i].rs1>0) {
2379             if(dops[i].opcode==0x0a) { // SLTI
2380               if(sl<0) {
2381                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2382                 emit_slti32(t,imm[i],t);
2383               }else{
2384                 emit_slti32(sl,imm[i],t);
2385               }
2386             }
2387             else { // SLTIU
2388               if(sl<0) {
2389                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2390                 emit_sltiu32(t,imm[i],t);
2391               }else{
2392                 emit_sltiu32(sl,imm[i],t);
2393               }
2394             }
2395         }else{
2396           // SLTI(U) with r0 is just stupid,
2397           // nonetheless examples can be found
2398           if(dops[i].opcode==0x0a) // SLTI
2399             if(0<imm[i]) emit_movimm(1,t);
2400             else emit_zeroreg(t);
2401           else // SLTIU
2402           {
2403             if(imm[i]) emit_movimm(1,t);
2404             else emit_zeroreg(t);
2405           }
2406         }
2407       }
2408     }
2409   }
2410   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2411     if(dops[i].rt1) {
2412       signed char sl,tl;
2413       tl=get_reg(i_regs->regmap,dops[i].rt1);
2414       sl=get_reg(i_regs->regmap,dops[i].rs1);
2415       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2416         if(dops[i].opcode==0x0c) //ANDI
2417         {
2418           if(dops[i].rs1) {
2419             if(sl<0) {
2420               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2421               emit_andimm(tl,imm[i],tl);
2422             }else{
2423               if(!((i_regs->wasconst>>sl)&1))
2424                 emit_andimm(sl,imm[i],tl);
2425               else
2426                 emit_movimm(constmap[i][sl]&imm[i],tl);
2427             }
2428           }
2429           else
2430             emit_zeroreg(tl);
2431         }
2432         else
2433         {
2434           if(dops[i].rs1) {
2435             if(sl<0) {
2436               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2437             }
2438             if(dops[i].opcode==0x0d) { // ORI
2439               if(sl<0) {
2440                 emit_orimm(tl,imm[i],tl);
2441               }else{
2442                 if(!((i_regs->wasconst>>sl)&1))
2443                   emit_orimm(sl,imm[i],tl);
2444                 else
2445                   emit_movimm(constmap[i][sl]|imm[i],tl);
2446               }
2447             }
2448             if(dops[i].opcode==0x0e) { // XORI
2449               if(sl<0) {
2450                 emit_xorimm(tl,imm[i],tl);
2451               }else{
2452                 if(!((i_regs->wasconst>>sl)&1))
2453                   emit_xorimm(sl,imm[i],tl);
2454                 else
2455                   emit_movimm(constmap[i][sl]^imm[i],tl);
2456               }
2457             }
2458           }
2459           else {
2460             emit_movimm(imm[i],tl);
2461           }
2462         }
2463       }
2464     }
2465   }
2466 }
2467
2468 static void shiftimm_assemble(int i, const struct regstat *i_regs)
2469 {
2470   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2471   {
2472     if(dops[i].rt1) {
2473       signed char s,t;
2474       t=get_reg(i_regs->regmap,dops[i].rt1);
2475       s=get_reg(i_regs->regmap,dops[i].rs1);
2476       //assert(t>=0);
2477       if(t>=0&&!((i_regs->isconst>>t)&1)){
2478         if(dops[i].rs1==0)
2479         {
2480           emit_zeroreg(t);
2481         }
2482         else
2483         {
2484           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2485           if(imm[i]) {
2486             if(dops[i].opcode2==0) // SLL
2487             {
2488               emit_shlimm(s<0?t:s,imm[i],t);
2489             }
2490             if(dops[i].opcode2==2) // SRL
2491             {
2492               emit_shrimm(s<0?t:s,imm[i],t);
2493             }
2494             if(dops[i].opcode2==3) // SRA
2495             {
2496               emit_sarimm(s<0?t:s,imm[i],t);
2497             }
2498           }else{
2499             // Shift by zero
2500             if(s>=0 && s!=t) emit_mov(s,t);
2501           }
2502         }
2503       }
2504       //emit_storereg(dops[i].rt1,t); //DEBUG
2505     }
2506   }
2507   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2508   {
2509     assert(0);
2510   }
2511   if(dops[i].opcode2==0x3c) // DSLL32
2512   {
2513     assert(0);
2514   }
2515   if(dops[i].opcode2==0x3e) // DSRL32
2516   {
2517     assert(0);
2518   }
2519   if(dops[i].opcode2==0x3f) // DSRA32
2520   {
2521     assert(0);
2522   }
2523 }
2524
2525 #ifndef shift_assemble
2526 static void shift_assemble(int i, const struct regstat *i_regs)
2527 {
2528   signed char s,t,shift;
2529   if (dops[i].rt1 == 0)
2530     return;
2531   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2532   t = get_reg(i_regs->regmap, dops[i].rt1);
2533   s = get_reg(i_regs->regmap, dops[i].rs1);
2534   shift = get_reg(i_regs->regmap, dops[i].rs2);
2535   if (t < 0)
2536     return;
2537
2538   if(dops[i].rs1==0)
2539     emit_zeroreg(t);
2540   else if(dops[i].rs2==0) {
2541     assert(s>=0);
2542     if(s!=t) emit_mov(s,t);
2543   }
2544   else {
2545     host_tempreg_acquire();
2546     emit_andimm(shift,31,HOST_TEMPREG);
2547     switch(dops[i].opcode2) {
2548     case 4: // SLLV
2549       emit_shl(s,HOST_TEMPREG,t);
2550       break;
2551     case 6: // SRLV
2552       emit_shr(s,HOST_TEMPREG,t);
2553       break;
2554     case 7: // SRAV
2555       emit_sar(s,HOST_TEMPREG,t);
2556       break;
2557     default:
2558       assert(0);
2559     }
2560     host_tempreg_release();
2561   }
2562 }
2563
2564 #endif
2565
2566 enum {
2567   MTYPE_8000 = 0,
2568   MTYPE_8020,
2569   MTYPE_0000,
2570   MTYPE_A000,
2571   MTYPE_1F80,
2572 };
2573
2574 static int get_ptr_mem_type(u_int a)
2575 {
2576   if(a < 0x00200000) {
2577     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2578       // return wrong, must use memhandler for BIOS self-test to pass
2579       // 007 does similar stuff from a00 mirror, weird stuff
2580       return MTYPE_8000;
2581     return MTYPE_0000;
2582   }
2583   if(0x1f800000 <= a && a < 0x1f801000)
2584     return MTYPE_1F80;
2585   if(0x80200000 <= a && a < 0x80800000)
2586     return MTYPE_8020;
2587   if(0xa0000000 <= a && a < 0xa0200000)
2588     return MTYPE_A000;
2589   return MTYPE_8000;
2590 }
2591
2592 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2593 {
2594   int r = get_reg(i_regs->regmap, ROREG);
2595   if (r < 0 && host_tempreg_free) {
2596     host_tempreg_acquire();
2597     emit_loadreg(ROREG, r = HOST_TEMPREG);
2598   }
2599   if (r < 0)
2600     abort();
2601   return r;
2602 }
2603
2604 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2605   int addr, int *offset_reg, int *addr_reg_override)
2606 {
2607   void *jaddr = NULL;
2608   int type = 0;
2609   int mr = dops[i].rs1;
2610   *offset_reg = -1;
2611   if(((smrv_strong|smrv_weak)>>mr)&1) {
2612     type=get_ptr_mem_type(smrv[mr]);
2613     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2614   }
2615   else {
2616     // use the mirror we are running on
2617     type=get_ptr_mem_type(start);
2618     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2619   }
2620
2621   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2622     host_tempreg_acquire();
2623     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2624     addr=*addr_reg_override=HOST_TEMPREG;
2625     type=0;
2626   }
2627   else if(type==MTYPE_0000) { // RAM 0 mirror
2628     host_tempreg_acquire();
2629     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2630     addr=*addr_reg_override=HOST_TEMPREG;
2631     type=0;
2632   }
2633   else if(type==MTYPE_A000) { // RAM A mirror
2634     host_tempreg_acquire();
2635     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2636     addr=*addr_reg_override=HOST_TEMPREG;
2637     type=0;
2638   }
2639   else if(type==MTYPE_1F80) { // scratchpad
2640     if (psxH == (void *)0x1f800000) {
2641       host_tempreg_acquire();
2642       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2643       emit_cmpimm(HOST_TEMPREG,0x1000);
2644       host_tempreg_release();
2645       jaddr=out;
2646       emit_jc(0);
2647     }
2648     else {
2649       // do the usual RAM check, jump will go to the right handler
2650       type=0;
2651     }
2652   }
2653
2654   if (type == 0) // need ram check
2655   {
2656     emit_cmpimm(addr,RAM_SIZE);
2657     jaddr = out;
2658     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2659     // Hint to branch predictor that the branch is unlikely to be taken
2660     if (dops[i].rs1 >= 28)
2661       emit_jno_unlikely(0);
2662     else
2663     #endif
2664       emit_jno(0);
2665     if (ram_offset != 0)
2666       *offset_reg = get_ro_reg(i_regs, 0);
2667   }
2668
2669   return jaddr;
2670 }
2671
2672 // return memhandler, or get directly accessable address and return 0
2673 static void *get_direct_memhandler(void *table, u_int addr,
2674   enum stub_type type, uintptr_t *addr_host)
2675 {
2676   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2677   uintptr_t l1, l2 = 0;
2678   l1 = ((uintptr_t *)table)[addr>>12];
2679   if (!(l1 & msb)) {
2680     uintptr_t v = l1 << 1;
2681     *addr_host = v + addr;
2682     return NULL;
2683   }
2684   else {
2685     l1 <<= 1;
2686     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2687       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2688     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2689       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2690     else
2691       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2692     if (!(l2 & msb)) {
2693       uintptr_t v = l2 << 1;
2694       *addr_host = v + (addr&0xfff);
2695       return NULL;
2696     }
2697     return (void *)(l2 << 1);
2698   }
2699 }
2700
2701 static u_int get_host_reglist(const signed char *regmap)
2702 {
2703   u_int reglist = 0, hr;
2704   for (hr = 0; hr < HOST_REGS; hr++) {
2705     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2706       reglist |= 1 << hr;
2707   }
2708   return reglist;
2709 }
2710
2711 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2712 {
2713   if (r1 >= 0)
2714     reglist &= ~(1u << r1);
2715   if (r2 >= 0)
2716     reglist &= ~(1u << r2);
2717   return reglist;
2718 }
2719
2720 // find a temp caller-saved register not in reglist (so assumed to be free)
2721 static int reglist_find_free(u_int reglist)
2722 {
2723   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2724   if (free_regs == 0)
2725     return -1;
2726   return __builtin_ctz(free_regs);
2727 }
2728
2729 static void do_load_word(int a, int rt, int offset_reg)
2730 {
2731   if (offset_reg >= 0)
2732     emit_ldr_dualindexed(offset_reg, a, rt);
2733   else
2734     emit_readword_indexed(0, a, rt);
2735 }
2736
2737 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2738 {
2739   if (offset_reg < 0) {
2740     emit_writeword_indexed(rt, ofs, a);
2741     return;
2742   }
2743   if (ofs != 0)
2744     emit_addimm(a, ofs, a);
2745   emit_str_dualindexed(offset_reg, a, rt);
2746   if (ofs != 0 && preseve_a)
2747     emit_addimm(a, -ofs, a);
2748 }
2749
2750 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2751 {
2752   if (offset_reg < 0) {
2753     emit_writehword_indexed(rt, ofs, a);
2754     return;
2755   }
2756   if (ofs != 0)
2757     emit_addimm(a, ofs, a);
2758   emit_strh_dualindexed(offset_reg, a, rt);
2759   if (ofs != 0 && preseve_a)
2760     emit_addimm(a, -ofs, a);
2761 }
2762
2763 static void do_store_byte(int a, int rt, int offset_reg)
2764 {
2765   if (offset_reg >= 0)
2766     emit_strb_dualindexed(offset_reg, a, rt);
2767   else
2768     emit_writebyte_indexed(rt, 0, a);
2769 }
2770
2771 static void load_assemble(int i, const struct regstat *i_regs, int ccadj_)
2772 {
2773   int s,tl,addr;
2774   int offset;
2775   void *jaddr=0;
2776   int memtarget=0,c=0;
2777   int offset_reg = -1;
2778   int fastio_reg_override = -1;
2779   u_int reglist=get_host_reglist(i_regs->regmap);
2780   tl=get_reg(i_regs->regmap,dops[i].rt1);
2781   s=get_reg(i_regs->regmap,dops[i].rs1);
2782   offset=imm[i];
2783   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2784   if(s>=0) {
2785     c=(i_regs->wasconst>>s)&1;
2786     if (c) {
2787       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2788     }
2789   }
2790   //printf("load_assemble: c=%d\n",c);
2791   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2792   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2793   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2794     ||dops[i].rt1==0) {
2795       // could be FIFO, must perform the read
2796       // ||dummy read
2797       assem_debug("(forced read)\n");
2798       tl=get_reg(i_regs->regmap,-1);
2799       assert(tl>=0);
2800   }
2801   if(offset||s<0||c) addr=tl;
2802   else addr=s;
2803   //if(tl<0) tl=get_reg(i_regs->regmap,-1);
2804  if(tl>=0) {
2805   //printf("load_assemble: c=%d\n",c);
2806   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2807   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2808   reglist&=~(1<<tl);
2809   if(!c) {
2810     #ifdef R29_HACK
2811     // Strmnnrmn's speed hack
2812     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2813     #endif
2814     {
2815       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2816                 &offset_reg, &fastio_reg_override);
2817     }
2818   }
2819   else if (ram_offset && memtarget) {
2820     offset_reg = get_ro_reg(i_regs, 0);
2821   }
2822   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2823   switch (dops[i].opcode) {
2824   case 0x20: // LB
2825     if(!c||memtarget) {
2826       if(!dummy) {
2827         int a = tl;
2828         if (!c) a = addr;
2829         if (fastio_reg_override >= 0)
2830           a = fastio_reg_override;
2831
2832         if (offset_reg >= 0)
2833           emit_ldrsb_dualindexed(offset_reg, a, tl);
2834         else
2835           emit_movsbl_indexed(0, a, tl);
2836       }
2837       if(jaddr)
2838         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2839     }
2840     else
2841       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2842     break;
2843   case 0x21: // LH
2844     if(!c||memtarget) {
2845       if(!dummy) {
2846         int a = tl;
2847         if (!c) a = addr;
2848         if (fastio_reg_override >= 0)
2849           a = fastio_reg_override;
2850         if (offset_reg >= 0)
2851           emit_ldrsh_dualindexed(offset_reg, a, tl);
2852         else
2853           emit_movswl_indexed(0, a, tl);
2854       }
2855       if(jaddr)
2856         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2857     }
2858     else
2859       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2860     break;
2861   case 0x23: // LW
2862     if(!c||memtarget) {
2863       if(!dummy) {
2864         int a = addr;
2865         if (fastio_reg_override >= 0)
2866           a = fastio_reg_override;
2867         do_load_word(a, tl, offset_reg);
2868       }
2869       if(jaddr)
2870         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2871     }
2872     else
2873       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2874     break;
2875   case 0x24: // LBU
2876     if(!c||memtarget) {
2877       if(!dummy) {
2878         int a = tl;
2879         if (!c) a = addr;
2880         if (fastio_reg_override >= 0)
2881           a = fastio_reg_override;
2882
2883         if (offset_reg >= 0)
2884           emit_ldrb_dualindexed(offset_reg, a, tl);
2885         else
2886           emit_movzbl_indexed(0, a, tl);
2887       }
2888       if(jaddr)
2889         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2890     }
2891     else
2892       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2893     break;
2894   case 0x25: // LHU
2895     if(!c||memtarget) {
2896       if(!dummy) {
2897         int a = tl;
2898         if(!c) a = addr;
2899         if (fastio_reg_override >= 0)
2900           a = fastio_reg_override;
2901         if (offset_reg >= 0)
2902           emit_ldrh_dualindexed(offset_reg, a, tl);
2903         else
2904           emit_movzwl_indexed(0, a, tl);
2905       }
2906       if(jaddr)
2907         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2908     }
2909     else
2910       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2911     break;
2912   case 0x27: // LWU
2913   case 0x37: // LD
2914   default:
2915     assert(0);
2916   }
2917  }
2918  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2919    host_tempreg_release();
2920 }
2921
2922 #ifndef loadlr_assemble
2923 static void loadlr_assemble(int i, const struct regstat *i_regs, int ccadj_)
2924 {
2925   int s,tl,temp,temp2,addr;
2926   int offset;
2927   void *jaddr=0;
2928   int memtarget=0,c=0;
2929   int offset_reg = -1;
2930   int fastio_reg_override = -1;
2931   u_int reglist=get_host_reglist(i_regs->regmap);
2932   tl=get_reg(i_regs->regmap,dops[i].rt1);
2933   s=get_reg(i_regs->regmap,dops[i].rs1);
2934   temp=get_reg(i_regs->regmap,-1);
2935   temp2=get_reg(i_regs->regmap,FTEMP);
2936   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
2937   assert(addr<0);
2938   offset=imm[i];
2939   reglist|=1<<temp;
2940   if(offset||s<0||c) addr=temp2;
2941   else addr=s;
2942   if(s>=0) {
2943     c=(i_regs->wasconst>>s)&1;
2944     if(c) {
2945       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2946     }
2947   }
2948   if(!c) {
2949     emit_shlimm(addr,3,temp);
2950     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2951       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
2952     }else{
2953       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
2954     }
2955     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
2956               &offset_reg, &fastio_reg_override);
2957   }
2958   else {
2959     if (ram_offset && memtarget) {
2960       offset_reg = get_ro_reg(i_regs, 0);
2961     }
2962     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
2963       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
2964     }else{
2965       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
2966     }
2967   }
2968   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
2969     if(!c||memtarget) {
2970       int a = temp2;
2971       if (fastio_reg_override >= 0)
2972         a = fastio_reg_override;
2973       do_load_word(a, temp2, offset_reg);
2974       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
2975         host_tempreg_release();
2976       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj_,reglist);
2977     }
2978     else
2979       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj_,reglist);
2980     if(dops[i].rt1) {
2981       assert(tl>=0);
2982       emit_andimm(temp,24,temp);
2983       if (dops[i].opcode==0x22) // LWL
2984         emit_xorimm(temp,24,temp);
2985       host_tempreg_acquire();
2986       emit_movimm(-1,HOST_TEMPREG);
2987       if (dops[i].opcode==0x26) {
2988         emit_shr(temp2,temp,temp2);
2989         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
2990       }else{
2991         emit_shl(temp2,temp,temp2);
2992         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
2993       }
2994       host_tempreg_release();
2995       emit_or(temp2,tl,tl);
2996     }
2997     //emit_storereg(dops[i].rt1,tl); // DEBUG
2998   }
2999   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
3000     assert(0);
3001   }
3002 }
3003 #endif
3004
3005 static void store_assemble(int i, const struct regstat *i_regs, int ccadj_)
3006 {
3007   int s,tl;
3008   int addr,temp;
3009   int offset;
3010   void *jaddr=0;
3011   enum stub_type type=0;
3012   int memtarget=0,c=0;
3013   int agr=AGEN1+(i&1);
3014   int offset_reg = -1;
3015   int fastio_reg_override = -1;
3016   u_int reglist=get_host_reglist(i_regs->regmap);
3017   tl=get_reg(i_regs->regmap,dops[i].rs2);
3018   s=get_reg(i_regs->regmap,dops[i].rs1);
3019   temp=get_reg(i_regs->regmap,agr);
3020   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3021   offset=imm[i];
3022   if(s>=0) {
3023     c=(i_regs->wasconst>>s)&1;
3024     if(c) {
3025       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3026     }
3027   }
3028   assert(tl>=0);
3029   assert(temp>=0);
3030   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
3031   if(offset||s<0||c) addr=temp;
3032   else addr=s;
3033   if (!c) {
3034     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3035               &offset_reg, &fastio_reg_override);
3036   }
3037   else if (ram_offset && memtarget) {
3038     offset_reg = get_ro_reg(i_regs, 0);
3039   }
3040
3041   switch (dops[i].opcode) {
3042   case 0x28: // SB
3043     if(!c||memtarget) {
3044       int a = temp;
3045       if (!c) a = addr;
3046       if (fastio_reg_override >= 0)
3047         a = fastio_reg_override;
3048       do_store_byte(a, tl, offset_reg);
3049     }
3050     type = STOREB_STUB;
3051     break;
3052   case 0x29: // SH
3053     if(!c||memtarget) {
3054       int a = temp;
3055       if (!c) a = addr;
3056       if (fastio_reg_override >= 0)
3057         a = fastio_reg_override;
3058       do_store_hword(a, 0, tl, offset_reg, 1);
3059     }
3060     type = STOREH_STUB;
3061     break;
3062   case 0x2B: // SW
3063     if(!c||memtarget) {
3064       int a = addr;
3065       if (fastio_reg_override >= 0)
3066         a = fastio_reg_override;
3067       do_store_word(a, 0, tl, offset_reg, 1);
3068     }
3069     type = STOREW_STUB;
3070     break;
3071   case 0x3F: // SD
3072   default:
3073     assert(0);
3074   }
3075   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3076     host_tempreg_release();
3077   if(jaddr) {
3078     // PCSX store handlers don't check invcode again
3079     reglist|=1<<addr;
3080     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3081     jaddr=0;
3082   }
3083   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3084     if(!c||memtarget) {
3085       #ifdef DESTRUCTIVE_SHIFT
3086       // The x86 shift operation is 'destructive'; it overwrites the
3087       // source register, so we need to make a copy first and use that.
3088       addr=temp;
3089       #endif
3090       #if defined(HOST_IMM8)
3091       int ir=get_reg(i_regs->regmap,INVCP);
3092       assert(ir>=0);
3093       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3094       #else
3095       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3096       #endif
3097       #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3098       emit_callne(invalidate_addr_reg[addr]);
3099       #else
3100       void *jaddr2 = out;
3101       emit_jne(0);
3102       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3103       #endif
3104     }
3105   }
3106   u_int addr_val=constmap[i][s]+offset;
3107   if(jaddr) {
3108     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3109   } else if(c&&!memtarget) {
3110     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj_,reglist);
3111   }
3112   // basic current block modification detection..
3113   // not looking back as that should be in mips cache already
3114   // (see Spyro2 title->attract mode)
3115   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3116     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3117     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3118     if(i_regs->regmap==regs[i].regmap) {
3119       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3120       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3121       emit_movimm(start+i*4+4,0);
3122       emit_writeword(0,&pcaddr);
3123       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3124       emit_far_call(get_addr_ht);
3125       emit_jmpreg(0);
3126     }
3127   }
3128 }
3129
3130 static void storelr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3131 {
3132   int s,tl;
3133   int temp;
3134   int offset;
3135   void *jaddr=0;
3136   void *case1, *case23, *case3;
3137   void *done0, *done1, *done2;
3138   int memtarget=0,c=0;
3139   int agr=AGEN1+(i&1);
3140   int offset_reg = -1;
3141   u_int reglist=get_host_reglist(i_regs->regmap);
3142   tl=get_reg(i_regs->regmap,dops[i].rs2);
3143   s=get_reg(i_regs->regmap,dops[i].rs1);
3144   temp=get_reg(i_regs->regmap,agr);
3145   if(temp<0) temp=get_reg(i_regs->regmap,-1);
3146   offset=imm[i];
3147   if(s>=0) {
3148     c=(i_regs->isconst>>s)&1;
3149     if(c) {
3150       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3151     }
3152   }
3153   assert(tl>=0);
3154   assert(temp>=0);
3155   if(!c) {
3156     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3157     if(!offset&&s!=temp) emit_mov(s,temp);
3158     jaddr=out;
3159     emit_jno(0);
3160   }
3161   else
3162   {
3163     if(!memtarget||!dops[i].rs1) {
3164       jaddr=out;
3165       emit_jmp(0);
3166     }
3167   }
3168   if (ram_offset)
3169     offset_reg = get_ro_reg(i_regs, 0);
3170
3171   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3172     assert(0);
3173   }
3174
3175   emit_testimm(temp,2);
3176   case23=out;
3177   emit_jne(0);
3178   emit_testimm(temp,1);
3179   case1=out;
3180   emit_jne(0);
3181   // 0
3182   if (dops[i].opcode == 0x2A) { // SWL
3183     // Write msb into least significant byte
3184     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3185     do_store_byte(temp, tl, offset_reg);
3186     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3187   }
3188   else if (dops[i].opcode == 0x2E) { // SWR
3189     // Write entire word
3190     do_store_word(temp, 0, tl, offset_reg, 1);
3191   }
3192   done0 = out;
3193   emit_jmp(0);
3194   // 1
3195   set_jump_target(case1, out);
3196   if (dops[i].opcode == 0x2A) { // SWL
3197     // Write two msb into two least significant bytes
3198     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3199     do_store_hword(temp, -1, tl, offset_reg, 0);
3200     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3201   }
3202   else if (dops[i].opcode == 0x2E) { // SWR
3203     // Write 3 lsb into three most significant bytes
3204     do_store_byte(temp, tl, offset_reg);
3205     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3206     do_store_hword(temp, 1, tl, offset_reg, 0);
3207     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3208   }
3209   done1=out;
3210   emit_jmp(0);
3211   // 2,3
3212   set_jump_target(case23, out);
3213   emit_testimm(temp,1);
3214   case3 = out;
3215   emit_jne(0);
3216   // 2
3217   if (dops[i].opcode==0x2A) { // SWL
3218     // Write 3 msb into three least significant bytes
3219     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3220     do_store_hword(temp, -2, tl, offset_reg, 1);
3221     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3222     do_store_byte(temp, tl, offset_reg);
3223     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3224   }
3225   else if (dops[i].opcode == 0x2E) { // SWR
3226     // Write two lsb into two most significant bytes
3227     do_store_hword(temp, 0, tl, offset_reg, 1);
3228   }
3229   done2 = out;
3230   emit_jmp(0);
3231   // 3
3232   set_jump_target(case3, out);
3233   if (dops[i].opcode == 0x2A) { // SWL
3234     do_store_word(temp, -3, tl, offset_reg, 0);
3235   }
3236   else if (dops[i].opcode == 0x2E) { // SWR
3237     do_store_byte(temp, tl, offset_reg);
3238   }
3239   set_jump_target(done0, out);
3240   set_jump_target(done1, out);
3241   set_jump_target(done2, out);
3242   if (offset_reg == HOST_TEMPREG)
3243     host_tempreg_release();
3244   if(!c||!memtarget)
3245     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj_,reglist);
3246   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3247     #if defined(HOST_IMM8)
3248     int ir=get_reg(i_regs->regmap,INVCP);
3249     assert(ir>=0);
3250     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3251     #else
3252     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3253     #endif
3254     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3255     emit_callne(invalidate_addr_reg[temp]);
3256     #else
3257     void *jaddr2 = out;
3258     emit_jne(0);
3259     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3260     #endif
3261   }
3262 }
3263
3264 static void cop0_assemble(int i, const struct regstat *i_regs, int ccadj_)
3265 {
3266   if(dops[i].opcode2==0) // MFC0
3267   {
3268     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3269     u_int copr=(source[i]>>11)&0x1f;
3270     //assert(t>=0); // Why does this happen?  OOT is weird
3271     if(t>=0&&dops[i].rt1!=0) {
3272       emit_readword(&reg_cop0[copr],t);
3273     }
3274   }
3275   else if(dops[i].opcode2==4) // MTC0
3276   {
3277     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3278     char copr=(source[i]>>11)&0x1f;
3279     assert(s>=0);
3280     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3281     if(copr==9||copr==11||copr==12||copr==13) {
3282       emit_readword(&last_count,HOST_TEMPREG);
3283       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3284       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3285       emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3286       emit_writeword(HOST_CCREG,&Count);
3287     }
3288     // What a mess.  The status register (12) can enable interrupts,
3289     // so needs a special case to handle a pending interrupt.
3290     // The interrupt must be taken immediately, because a subsequent
3291     // instruction might disable interrupts again.
3292     if(copr==12||copr==13) {
3293       if (is_delayslot) {
3294         // burn cycles to cause cc_interrupt, which will
3295         // reschedule next_interupt. Relies on CCREG from above.
3296         assem_debug("MTC0 DS %d\n", copr);
3297         emit_writeword(HOST_CCREG,&last_count);
3298         emit_movimm(0,HOST_CCREG);
3299         emit_storereg(CCREG,HOST_CCREG);
3300         emit_loadreg(dops[i].rs1,1);
3301         emit_movimm(copr,0);
3302         emit_far_call(pcsx_mtc0_ds);
3303         emit_loadreg(dops[i].rs1,s);
3304         return;
3305       }
3306       emit_movimm(start+i*4+4,HOST_TEMPREG);
3307       emit_writeword(HOST_TEMPREG,&pcaddr);
3308       emit_movimm(0,HOST_TEMPREG);
3309       emit_writeword(HOST_TEMPREG,&pending_exception);
3310     }
3311     if(s==HOST_CCREG)
3312       emit_loadreg(dops[i].rs1,1);
3313     else if(s!=1)
3314       emit_mov(s,1);
3315     emit_movimm(copr,0);
3316     emit_far_call(pcsx_mtc0);
3317     if(copr==9||copr==11||copr==12||copr==13) {
3318       emit_readword(&Count,HOST_CCREG);
3319       emit_readword(&next_interupt,HOST_TEMPREG);
3320       emit_addimm(HOST_CCREG,-ccadj_,HOST_CCREG);
3321       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3322       emit_writeword(HOST_TEMPREG,&last_count);
3323       emit_storereg(CCREG,HOST_CCREG);
3324     }
3325     if(copr==12||copr==13) {
3326       assert(!is_delayslot);
3327       emit_readword(&pending_exception,14);
3328       emit_test(14,14);
3329       void *jaddr = out;
3330       emit_jeq(0);
3331       emit_readword(&pcaddr, 0);
3332       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3333       emit_far_call(get_addr_ht);
3334       emit_jmpreg(0);
3335       set_jump_target(jaddr, out);
3336     }
3337     emit_loadreg(dops[i].rs1,s);
3338   }
3339   else
3340   {
3341     assert(dops[i].opcode2==0x10);
3342     //if((source[i]&0x3f)==0x10) // RFE
3343     {
3344       emit_readword(&Status,0);
3345       emit_andimm(0,0x3c,1);
3346       emit_andimm(0,~0xf,0);
3347       emit_orrshr_imm(1,2,0);
3348       emit_writeword(0,&Status);
3349     }
3350   }
3351 }
3352
3353 static void cop1_unusable(int i, const struct regstat *i_regs)
3354 {
3355   // XXX: should just just do the exception instead
3356   //if(!cop1_usable)
3357   {
3358     void *jaddr=out;
3359     emit_jmp(0);
3360     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3361   }
3362 }
3363
3364 static void cop1_assemble(int i, const struct regstat *i_regs)
3365 {
3366   cop1_unusable(i, i_regs);
3367 }
3368
3369 static void c1ls_assemble(int i, const struct regstat *i_regs)
3370 {
3371   cop1_unusable(i, i_regs);
3372 }
3373
3374 // FP_STUB
3375 static void do_cop1stub(int n)
3376 {
3377   literal_pool(256);
3378   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3379   set_jump_target(stubs[n].addr, out);
3380   int i=stubs[n].a;
3381 //  int rs=stubs[n].b;
3382   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3383   int ds=stubs[n].d;
3384   if(!ds) {
3385     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3386     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3387   }
3388   //else {printf("fp exception in delay slot\n");}
3389   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3390   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3391   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3392   emit_addimm(HOST_CCREG,ccadj[i],HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3393   emit_far_jump(ds?fp_exception_ds:fp_exception);
3394 }
3395
3396 static int cop2_is_stalling_op(int i, int *cycles)
3397 {
3398   if (dops[i].opcode == 0x3a) { // SWC2
3399     *cycles = 0;
3400     return 1;
3401   }
3402   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3403     *cycles = 0;
3404     return 1;
3405   }
3406   if (dops[i].itype == C2OP) {
3407     *cycles = gte_cycletab[source[i] & 0x3f];
3408     return 1;
3409   }
3410   // ... what about MTC2/CTC2/LWC2?
3411   return 0;
3412 }
3413
3414 #if 0
3415 static void log_gte_stall(int stall, u_int cycle)
3416 {
3417   if ((u_int)stall <= 44)
3418     printf("x    stall %2d %u\n", stall, cycle + last_count);
3419 }
3420
3421 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3422 {
3423   save_regs(reglist);
3424   if (stall > 0)
3425     emit_movimm(stall, 0);
3426   else
3427     emit_mov(HOST_TEMPREG, 0);
3428   emit_addimm(HOST_CCREG, ccadj[i], 1);
3429   emit_far_call(log_gte_stall);
3430   restore_regs(reglist);
3431 }
3432 #endif
3433
3434 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3435 {
3436   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3437   int rtmp = reglist_find_free(reglist);
3438
3439   if (HACK_ENABLED(NDHACK_NO_STALLS))
3440     return;
3441   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3442     // happens occasionally... cc evicted? Don't bother then
3443     //printf("no cc %08x\n", start + i*4);
3444     return;
3445   }
3446   if (!dops[i].bt) {
3447     for (j = i - 1; j >= 0; j--) {
3448       //if (dops[j].is_ds) break;
3449       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3450         break;
3451       if (j > 0 && ccadj[j - 1] > ccadj[j])
3452         break;
3453     }
3454     j = max(j, 0);
3455   }
3456   cycles_passed = ccadj[i] - ccadj[j];
3457   if (other_gte_op_cycles >= 0)
3458     stall = other_gte_op_cycles - cycles_passed;
3459   else if (cycles_passed >= 44)
3460     stall = 0; // can't stall
3461   if (stall == -MAXBLOCK && rtmp >= 0) {
3462     // unknown stall, do the expensive runtime check
3463     assem_debug("; cop2_do_stall_check\n");
3464 #if 0 // too slow
3465     save_regs(reglist);
3466     emit_movimm(gte_cycletab[op], 0);
3467     emit_addimm(HOST_CCREG, ccadj[i], 1);
3468     emit_far_call(call_gteStall);
3469     restore_regs(reglist);
3470 #else
3471     host_tempreg_acquire();
3472     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3473     emit_addimm(rtmp, -ccadj[i], rtmp);
3474     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3475     emit_cmpimm(HOST_TEMPREG, 44);
3476     emit_cmovb_reg(rtmp, HOST_CCREG);
3477     //emit_log_gte_stall(i, 0, reglist);
3478     host_tempreg_release();
3479 #endif
3480   }
3481   else if (stall > 0) {
3482     //emit_log_gte_stall(i, stall, reglist);
3483     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3484   }
3485
3486   // save gteBusyCycle, if needed
3487   if (gte_cycletab[op] == 0)
3488     return;
3489   other_gte_op_cycles = -1;
3490   for (j = i + 1; j < slen; j++) {
3491     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3492       break;
3493     if (dops[j].is_jump) {
3494       // check ds
3495       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3496         j++;
3497       break;
3498     }
3499   }
3500   if (other_gte_op_cycles >= 0)
3501     // will handle stall when assembling that op
3502     return;
3503   cycles_passed = ccadj[min(j, slen -1)] - ccadj[i];
3504   if (cycles_passed >= 44)
3505     return;
3506   assem_debug("; save gteBusyCycle\n");
3507   host_tempreg_acquire();
3508 #if 0
3509   emit_readword(&last_count, HOST_TEMPREG);
3510   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3511   emit_addimm(HOST_TEMPREG, ccadj[i], HOST_TEMPREG);
3512   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3513   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3514 #else
3515   emit_addimm(HOST_CCREG, ccadj[i] + gte_cycletab[op], HOST_TEMPREG);
3516   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3517 #endif
3518   host_tempreg_release();
3519 }
3520
3521 static int is_mflohi(int i)
3522 {
3523   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3524 }
3525
3526 static int check_multdiv(int i, int *cycles)
3527 {
3528   if (dops[i].itype != MULTDIV)
3529     return 0;
3530   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3531     *cycles = 11; // approx from 7 11 14
3532   else
3533     *cycles = 37;
3534   return 1;
3535 }
3536
3537 static void multdiv_prepare_stall(int i, const struct regstat *i_regs, int ccadj_)
3538 {
3539   int j, found = 0, c = 0;
3540   if (HACK_ENABLED(NDHACK_NO_STALLS))
3541     return;
3542   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3543     // happens occasionally... cc evicted? Don't bother then
3544     return;
3545   }
3546   for (j = i + 1; j < slen; j++) {
3547     if (dops[j].bt)
3548       break;
3549     if ((found = is_mflohi(j)))
3550       break;
3551     if (dops[j].is_jump) {
3552       // check ds
3553       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3554         j++;
3555       break;
3556     }
3557   }
3558   if (found)
3559     // handle all in multdiv_do_stall()
3560     return;
3561   check_multdiv(i, &c);
3562   assert(c > 0);
3563   assem_debug("; muldiv prepare stall %d\n", c);
3564   host_tempreg_acquire();
3565   emit_addimm(HOST_CCREG, ccadj_ + c, HOST_TEMPREG);
3566   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3567   host_tempreg_release();
3568 }
3569
3570 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3571 {
3572   int j, known_cycles = 0;
3573   u_int reglist = get_host_reglist(i_regs->regmap);
3574   int rtmp = get_reg(i_regs->regmap, -1);
3575   if (rtmp < 0)
3576     rtmp = reglist_find_free(reglist);
3577   if (HACK_ENABLED(NDHACK_NO_STALLS))
3578     return;
3579   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3580     // happens occasionally... cc evicted? Don't bother then
3581     //printf("no cc/rtmp %08x\n", start + i*4);
3582     return;
3583   }
3584   if (!dops[i].bt) {
3585     for (j = i - 1; j >= 0; j--) {
3586       if (dops[j].is_ds) break;
3587       if (check_multdiv(j, &known_cycles))
3588         break;
3589       if (is_mflohi(j))
3590         // already handled by this op
3591         return;
3592       if (dops[j].bt || (j > 0 && ccadj[j - 1] > ccadj[j]))
3593         break;
3594     }
3595     j = max(j, 0);
3596   }
3597   if (known_cycles > 0) {
3598     known_cycles -= ccadj[i] - ccadj[j];
3599     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3600     if (known_cycles > 0)
3601       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3602     return;
3603   }
3604   assem_debug("; muldiv stall unresolved\n");
3605   host_tempreg_acquire();
3606   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3607   emit_addimm(rtmp, -ccadj[i], rtmp);
3608   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3609   emit_cmpimm(HOST_TEMPREG, 37);
3610   emit_cmovb_reg(rtmp, HOST_CCREG);
3611   //emit_log_gte_stall(i, 0, reglist);
3612   host_tempreg_release();
3613 }
3614
3615 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3616 {
3617   switch (copr) {
3618     case 1:
3619     case 3:
3620     case 5:
3621     case 8:
3622     case 9:
3623     case 10:
3624     case 11:
3625       emit_readword(&reg_cop2d[copr],tl);
3626       emit_signextend16(tl,tl);
3627       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3628       break;
3629     case 7:
3630     case 16:
3631     case 17:
3632     case 18:
3633     case 19:
3634       emit_readword(&reg_cop2d[copr],tl);
3635       emit_andimm(tl,0xffff,tl);
3636       emit_writeword(tl,&reg_cop2d[copr]);
3637       break;
3638     case 15:
3639       emit_readword(&reg_cop2d[14],tl); // SXY2
3640       emit_writeword(tl,&reg_cop2d[copr]);
3641       break;
3642     case 28:
3643     case 29:
3644       c2op_mfc2_29_assemble(tl,temp);
3645       break;
3646     default:
3647       emit_readword(&reg_cop2d[copr],tl);
3648       break;
3649   }
3650 }
3651
3652 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3653 {
3654   switch (copr) {
3655     case 15:
3656       emit_readword(&reg_cop2d[13],temp);  // SXY1
3657       emit_writeword(sl,&reg_cop2d[copr]);
3658       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3659       emit_readword(&reg_cop2d[14],temp);  // SXY2
3660       emit_writeword(sl,&reg_cop2d[14]);
3661       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3662       break;
3663     case 28:
3664       emit_andimm(sl,0x001f,temp);
3665       emit_shlimm(temp,7,temp);
3666       emit_writeword(temp,&reg_cop2d[9]);
3667       emit_andimm(sl,0x03e0,temp);
3668       emit_shlimm(temp,2,temp);
3669       emit_writeword(temp,&reg_cop2d[10]);
3670       emit_andimm(sl,0x7c00,temp);
3671       emit_shrimm(temp,3,temp);
3672       emit_writeword(temp,&reg_cop2d[11]);
3673       emit_writeword(sl,&reg_cop2d[28]);
3674       break;
3675     case 30:
3676       emit_xorsar_imm(sl,sl,31,temp);
3677 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3678       emit_clz(temp,temp);
3679 #else
3680       emit_movs(temp,HOST_TEMPREG);
3681       emit_movimm(0,temp);
3682       emit_jeq((int)out+4*4);
3683       emit_addpl_imm(temp,1,temp);
3684       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3685       emit_jns((int)out-2*4);
3686 #endif
3687       emit_writeword(sl,&reg_cop2d[30]);
3688       emit_writeword(temp,&reg_cop2d[31]);
3689       break;
3690     case 31:
3691       break;
3692     default:
3693       emit_writeword(sl,&reg_cop2d[copr]);
3694       break;
3695   }
3696 }
3697
3698 static void c2ls_assemble(int i, const struct regstat *i_regs, int ccadj_)
3699 {
3700   int s,tl;
3701   int ar;
3702   int offset;
3703   int memtarget=0,c=0;
3704   void *jaddr2=NULL;
3705   enum stub_type type;
3706   int agr=AGEN1+(i&1);
3707   int offset_reg = -1;
3708   int fastio_reg_override = -1;
3709   u_int reglist=get_host_reglist(i_regs->regmap);
3710   u_int copr=(source[i]>>16)&0x1f;
3711   s=get_reg(i_regs->regmap,dops[i].rs1);
3712   tl=get_reg(i_regs->regmap,FTEMP);
3713   offset=imm[i];
3714   assert(dops[i].rs1>0);
3715   assert(tl>=0);
3716
3717   if(i_regs->regmap[HOST_CCREG]==CCREG)
3718     reglist&=~(1<<HOST_CCREG);
3719
3720   // get the address
3721   if (dops[i].opcode==0x3a) { // SWC2
3722     ar=get_reg(i_regs->regmap,agr);
3723     if(ar<0) ar=get_reg(i_regs->regmap,-1);
3724     reglist|=1<<ar;
3725   } else { // LWC2
3726     ar=tl;
3727   }
3728   if(s>=0) c=(i_regs->wasconst>>s)&1;
3729   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3730   if (!offset&&!c&&s>=0) ar=s;
3731   assert(ar>=0);
3732
3733   cop2_do_stall_check(0, i, i_regs, reglist);
3734
3735   if (dops[i].opcode==0x3a) { // SWC2
3736     cop2_get_dreg(copr,tl,-1);
3737     type=STOREW_STUB;
3738   }
3739   else
3740     type=LOADW_STUB;
3741
3742   if(c&&!memtarget) {
3743     jaddr2=out;
3744     emit_jmp(0); // inline_readstub/inline_writestub?
3745   }
3746   else {
3747     if(!c) {
3748       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3749                 &offset_reg, &fastio_reg_override);
3750     }
3751     else if (ram_offset && memtarget) {
3752       offset_reg = get_ro_reg(i_regs, 0);
3753     }
3754     switch (dops[i].opcode) {
3755     case 0x32: { // LWC2
3756       int a = ar;
3757       if (fastio_reg_override >= 0)
3758         a = fastio_reg_override;
3759       do_load_word(a, tl, offset_reg);
3760       break;
3761     }
3762     case 0x3a: { // SWC2
3763       #ifdef DESTRUCTIVE_SHIFT
3764       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3765       #endif
3766       int a = ar;
3767       if (fastio_reg_override >= 0)
3768         a = fastio_reg_override;
3769       do_store_word(a, 0, tl, offset_reg, 1);
3770       break;
3771     }
3772     default:
3773       assert(0);
3774     }
3775   }
3776   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3777     host_tempreg_release();
3778   if(jaddr2)
3779     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj_,reglist);
3780   if(dops[i].opcode==0x3a) // SWC2
3781   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3782 #if defined(HOST_IMM8)
3783     int ir=get_reg(i_regs->regmap,INVCP);
3784     assert(ir>=0);
3785     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3786 #else
3787     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3788 #endif
3789     #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
3790     emit_callne(invalidate_addr_reg[ar]);
3791     #else
3792     void *jaddr3 = out;
3793     emit_jne(0);
3794     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3795     #endif
3796   }
3797   if (dops[i].opcode==0x32) { // LWC2
3798     host_tempreg_acquire();
3799     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3800     host_tempreg_release();
3801   }
3802 }
3803
3804 static void cop2_assemble(int i, const struct regstat *i_regs)
3805 {
3806   u_int copr = (source[i]>>11) & 0x1f;
3807   signed char temp = get_reg(i_regs->regmap, -1);
3808
3809   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3810     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3811     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
3812       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
3813       reglist = reglist_exclude(reglist, tl, -1);
3814     }
3815     cop2_do_stall_check(0, i, i_regs, reglist);
3816   }
3817   if (dops[i].opcode2==0) { // MFC2
3818     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3819     if(tl>=0&&dops[i].rt1!=0)
3820       cop2_get_dreg(copr,tl,temp);
3821   }
3822   else if (dops[i].opcode2==4) { // MTC2
3823     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3824     cop2_put_dreg(copr,sl,temp);
3825   }
3826   else if (dops[i].opcode2==2) // CFC2
3827   {
3828     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3829     if(tl>=0&&dops[i].rt1!=0)
3830       emit_readword(&reg_cop2c[copr],tl);
3831   }
3832   else if (dops[i].opcode2==6) // CTC2
3833   {
3834     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3835     switch(copr) {
3836       case 4:
3837       case 12:
3838       case 20:
3839       case 26:
3840       case 27:
3841       case 29:
3842       case 30:
3843         emit_signextend16(sl,temp);
3844         break;
3845       case 31:
3846         c2op_ctc2_31_assemble(sl,temp);
3847         break;
3848       default:
3849         temp=sl;
3850         break;
3851     }
3852     emit_writeword(temp,&reg_cop2c[copr]);
3853     assert(sl>=0);
3854   }
3855 }
3856
3857 static void do_unalignedwritestub(int n)
3858 {
3859   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
3860   literal_pool(256);
3861   set_jump_target(stubs[n].addr, out);
3862
3863   int i=stubs[n].a;
3864   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3865   int addr=stubs[n].b;
3866   u_int reglist=stubs[n].e;
3867   signed char *i_regmap=i_regs->regmap;
3868   int temp2=get_reg(i_regmap,FTEMP);
3869   int rt;
3870   rt=get_reg(i_regmap,dops[i].rs2);
3871   assert(rt>=0);
3872   assert(addr>=0);
3873   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
3874   reglist|=(1<<addr);
3875   reglist&=~(1<<temp2);
3876
3877   // don't bother with it and call write handler
3878   save_regs(reglist);
3879   pass_args(addr,rt);
3880   int cc=get_reg(i_regmap,CCREG);
3881   if(cc<0)
3882     emit_loadreg(CCREG,2);
3883   emit_addimm(cc<0?2:cc,(int)stubs[n].d+1,2);
3884   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
3885   emit_addimm(0,-((int)stubs[n].d+1),cc<0?2:cc);
3886   if(cc<0)
3887     emit_storereg(CCREG,2);
3888   restore_regs(reglist);
3889   emit_jmp(stubs[n].retaddr); // return address
3890 }
3891
3892 #ifndef multdiv_assemble
3893 void multdiv_assemble(int i,struct regstat *i_regs)
3894 {
3895   printf("Need multdiv_assemble for this architecture.\n");
3896   abort();
3897 }
3898 #endif
3899
3900 static void mov_assemble(int i, const struct regstat *i_regs)
3901 {
3902   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
3903   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
3904   if(dops[i].rt1) {
3905     signed char sl,tl;
3906     tl=get_reg(i_regs->regmap,dops[i].rt1);
3907     //assert(tl>=0);
3908     if(tl>=0) {
3909       sl=get_reg(i_regs->regmap,dops[i].rs1);
3910       if(sl>=0) emit_mov(sl,tl);
3911       else emit_loadreg(dops[i].rs1,tl);
3912     }
3913   }
3914   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
3915     multdiv_do_stall(i, i_regs);
3916 }
3917
3918 // call interpreter, exception handler, things that change pc/regs/cycles ...
3919 static void call_c_cpu_handler(int i, const struct regstat *i_regs, int ccadj_, u_int pc, void *func)
3920 {
3921   signed char ccreg=get_reg(i_regs->regmap,CCREG);
3922   assert(ccreg==HOST_CCREG);
3923   assert(!is_delayslot);
3924   (void)ccreg;
3925
3926   emit_movimm(pc,3); // Get PC
3927   emit_readword(&last_count,2);
3928   emit_writeword(3,&psxRegs.pc);
3929   emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3930   emit_add(2,HOST_CCREG,2);
3931   emit_writeword(2,&psxRegs.cycle);
3932   emit_far_call(func);
3933   emit_far_jump(jump_to_new_pc);
3934 }
3935
3936 static void syscall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3937 {
3938   emit_movimm(0x20,0); // cause code
3939   emit_movimm(0,1);    // not in delay slot
3940   call_c_cpu_handler(i, i_regs, ccadj_, start+i*4, psxException);
3941 }
3942
3943 static void hlecall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3944 {
3945   void *hlefunc = psxNULL;
3946   uint32_t hleCode = source[i] & 0x03ffffff;
3947   if (hleCode < ARRAY_SIZE(psxHLEt))
3948     hlefunc = psxHLEt[hleCode];
3949
3950   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4+4, hlefunc);
3951 }
3952
3953 static void intcall_assemble(int i, const struct regstat *i_regs, int ccadj_)
3954 {
3955   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4, execI);
3956 }
3957
3958 static void speculate_mov(int rs,int rt)
3959 {
3960   if(rt!=0) {
3961     smrv_strong_next|=1<<rt;
3962     smrv[rt]=smrv[rs];
3963   }
3964 }
3965
3966 static void speculate_mov_weak(int rs,int rt)
3967 {
3968   if(rt!=0) {
3969     smrv_weak_next|=1<<rt;
3970     smrv[rt]=smrv[rs];
3971   }
3972 }
3973
3974 static void speculate_register_values(int i)
3975 {
3976   if(i==0) {
3977     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
3978     // gp,sp are likely to stay the same throughout the block
3979     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
3980     smrv_weak_next=~smrv_strong_next;
3981     //printf(" llr %08x\n", smrv[4]);
3982   }
3983   smrv_strong=smrv_strong_next;
3984   smrv_weak=smrv_weak_next;
3985   switch(dops[i].itype) {
3986     case ALU:
3987       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
3988       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
3989       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
3990       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
3991       else {
3992         smrv_strong_next&=~(1<<dops[i].rt1);
3993         smrv_weak_next&=~(1<<dops[i].rt1);
3994       }
3995       break;
3996     case SHIFTIMM:
3997       smrv_strong_next&=~(1<<dops[i].rt1);
3998       smrv_weak_next&=~(1<<dops[i].rt1);
3999       // fallthrough
4000     case IMM16:
4001       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
4002         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
4003         if(hr>=0) {
4004           if(get_final_value(hr,i,&value))
4005                smrv[dops[i].rt1]=value;
4006           else smrv[dops[i].rt1]=constmap[i][hr];
4007           smrv_strong_next|=1<<dops[i].rt1;
4008         }
4009       }
4010       else {
4011         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4012         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4013       }
4014       break;
4015     case LOAD:
4016       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
4017         // special case for BIOS
4018         smrv[dops[i].rt1]=0xa0000000;
4019         smrv_strong_next|=1<<dops[i].rt1;
4020         break;
4021       }
4022       // fallthrough
4023     case SHIFT:
4024     case LOADLR:
4025     case MOV:
4026       smrv_strong_next&=~(1<<dops[i].rt1);
4027       smrv_weak_next&=~(1<<dops[i].rt1);
4028       break;
4029     case COP0:
4030     case COP2:
4031       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
4032         smrv_strong_next&=~(1<<dops[i].rt1);
4033         smrv_weak_next&=~(1<<dops[i].rt1);
4034       }
4035       break;
4036     case C2LS:
4037       if (dops[i].opcode==0x32) { // LWC2
4038         smrv_strong_next&=~(1<<dops[i].rt1);
4039         smrv_weak_next&=~(1<<dops[i].rt1);
4040       }
4041       break;
4042   }
4043 #if 0
4044   int r=4;
4045   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4046     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4047 #endif
4048 }
4049
4050 static void ujump_assemble(int i, const struct regstat *i_regs);
4051 static void rjump_assemble(int i, const struct regstat *i_regs);
4052 static void cjump_assemble(int i, const struct regstat *i_regs);
4053 static void sjump_assemble(int i, const struct regstat *i_regs);
4054 static void pagespan_assemble(int i, const struct regstat *i_regs);
4055
4056 static int assemble(int i, const struct regstat *i_regs, int ccadj_)
4057 {
4058   int ds = 0;
4059   switch (dops[i].itype) {
4060     case ALU:
4061       alu_assemble(i, i_regs);
4062       break;
4063     case IMM16:
4064       imm16_assemble(i, i_regs);
4065       break;
4066     case SHIFT:
4067       shift_assemble(i, i_regs);
4068       break;
4069     case SHIFTIMM:
4070       shiftimm_assemble(i, i_regs);
4071       break;
4072     case LOAD:
4073       load_assemble(i, i_regs, ccadj_);
4074       break;
4075     case LOADLR:
4076       loadlr_assemble(i, i_regs, ccadj_);
4077       break;
4078     case STORE:
4079       store_assemble(i, i_regs, ccadj_);
4080       break;
4081     case STORELR:
4082       storelr_assemble(i, i_regs, ccadj_);
4083       break;
4084     case COP0:
4085       cop0_assemble(i, i_regs, ccadj_);
4086       break;
4087     case COP1:
4088       cop1_assemble(i, i_regs);
4089       break;
4090     case C1LS:
4091       c1ls_assemble(i, i_regs);
4092       break;
4093     case COP2:
4094       cop2_assemble(i, i_regs);
4095       break;
4096     case C2LS:
4097       c2ls_assemble(i, i_regs, ccadj_);
4098       break;
4099     case C2OP:
4100       c2op_assemble(i, i_regs);
4101       break;
4102     case MULTDIV:
4103       multdiv_assemble(i, i_regs);
4104       multdiv_prepare_stall(i, i_regs, ccadj_);
4105       break;
4106     case MOV:
4107       mov_assemble(i, i_regs);
4108       break;
4109     case SYSCALL:
4110       syscall_assemble(i, i_regs, ccadj_);
4111       break;
4112     case HLECALL:
4113       hlecall_assemble(i, i_regs, ccadj_);
4114       break;
4115     case INTCALL:
4116       intcall_assemble(i, i_regs, ccadj_);
4117       break;
4118     case UJUMP:
4119       ujump_assemble(i, i_regs);
4120       ds = 1;
4121       break;
4122     case RJUMP:
4123       rjump_assemble(i, i_regs);
4124       ds = 1;
4125       break;
4126     case CJUMP:
4127       cjump_assemble(i, i_regs);
4128       ds = 1;
4129       break;
4130     case SJUMP:
4131       sjump_assemble(i, i_regs);
4132       ds = 1;
4133       break;
4134     case SPAN:
4135       pagespan_assemble(i, i_regs);
4136       break;
4137     case NOP:
4138     case OTHER:
4139     case NI:
4140       // not handled, just skip
4141       break;
4142     default:
4143       assert(0);
4144   }
4145   return ds;
4146 }
4147
4148 static void ds_assemble(int i, const struct regstat *i_regs)
4149 {
4150   speculate_register_values(i);
4151   is_delayslot = 1;
4152   switch (dops[i].itype) {
4153     case SYSCALL:
4154     case HLECALL:
4155     case INTCALL:
4156     case SPAN:
4157     case UJUMP:
4158     case RJUMP:
4159     case CJUMP:
4160     case SJUMP:
4161       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4162       break;
4163     default:
4164       assemble(i, i_regs, ccadj[i]);
4165   }
4166   is_delayslot = 0;
4167 }
4168
4169 // Is the branch target a valid internal jump?
4170 static int internal_branch(int addr)
4171 {
4172   if(addr&1) return 0; // Indirect (register) jump
4173   if(addr>=start && addr<start+slen*4-4)
4174   {
4175     return 1;
4176   }
4177   return 0;
4178 }
4179
4180 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4181 {
4182   int hr;
4183   for(hr=0;hr<HOST_REGS;hr++) {
4184     if(hr!=EXCLUDE_REG) {
4185       if(pre[hr]!=entry[hr]) {
4186         if(pre[hr]>=0) {
4187           if((dirty>>hr)&1) {
4188             if(get_reg(entry,pre[hr])<0) {
4189               assert(pre[hr]<64);
4190               if(!((u>>pre[hr])&1))
4191                 emit_storereg(pre[hr],hr);
4192             }
4193           }
4194         }
4195       }
4196     }
4197   }
4198   // Move from one register to another (no writeback)
4199   for(hr=0;hr<HOST_REGS;hr++) {
4200     if(hr!=EXCLUDE_REG) {
4201       if(pre[hr]!=entry[hr]) {
4202         if(pre[hr]>=0&&(pre[hr]&63)<TEMPREG) {
4203           int nr;
4204           if((nr=get_reg(entry,pre[hr]))>=0) {
4205             emit_mov(hr,nr);
4206           }
4207         }
4208       }
4209     }
4210   }
4211 }
4212
4213 // Load the specified registers
4214 // This only loads the registers given as arguments because
4215 // we don't want to load things that will be overwritten
4216 static void load_regs(signed char entry[],signed char regmap[],int rs1,int rs2)
4217 {
4218   int hr;
4219   // Load 32-bit regs
4220   for(hr=0;hr<HOST_REGS;hr++) {
4221     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4222       if(entry[hr]!=regmap[hr]) {
4223         if(regmap[hr]==rs1||regmap[hr]==rs2)
4224         {
4225           if(regmap[hr]==0) {
4226             emit_zeroreg(hr);
4227           }
4228           else
4229           {
4230             emit_loadreg(regmap[hr],hr);
4231           }
4232         }
4233       }
4234     }
4235   }
4236 }
4237
4238 // Load registers prior to the start of a loop
4239 // so that they are not loaded within the loop
4240 static void loop_preload(signed char pre[],signed char entry[])
4241 {
4242   int hr;
4243   for(hr=0;hr<HOST_REGS;hr++) {
4244     if(hr!=EXCLUDE_REG) {
4245       if(pre[hr]!=entry[hr]) {
4246         if(entry[hr]>=0) {
4247           if(get_reg(pre,entry[hr])<0) {
4248             assem_debug("loop preload:\n");
4249             //printf("loop preload: %d\n",hr);
4250             if(entry[hr]==0) {
4251               emit_zeroreg(hr);
4252             }
4253             else if(entry[hr]<TEMPREG)
4254             {
4255               emit_loadreg(entry[hr],hr);
4256             }
4257             else if(entry[hr]-64<TEMPREG)
4258             {
4259               emit_loadreg(entry[hr],hr);
4260             }
4261           }
4262         }
4263       }
4264     }
4265   }
4266 }
4267
4268 // Generate address for load/store instruction
4269 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4270 void address_generation(int i, const struct regstat *i_regs, signed char entry[])
4271 {
4272   if (dops[i].is_load || dops[i].is_store) {
4273     int ra=-1;
4274     int agr=AGEN1+(i&1);
4275     if(dops[i].itype==LOAD) {
4276       ra=get_reg(i_regs->regmap,dops[i].rt1);
4277       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4278       assert(ra>=0);
4279     }
4280     if(dops[i].itype==LOADLR) {
4281       ra=get_reg(i_regs->regmap,FTEMP);
4282     }
4283     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4284       ra=get_reg(i_regs->regmap,agr);
4285       if(ra<0) ra=get_reg(i_regs->regmap,-1);
4286     }
4287     if(dops[i].itype==C2LS) {
4288       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4289         ra=get_reg(i_regs->regmap,FTEMP);
4290       else { // SWC1/SDC1/SWC2/SDC2
4291         ra=get_reg(i_regs->regmap,agr);
4292         if(ra<0) ra=get_reg(i_regs->regmap,-1);
4293       }
4294     }
4295     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4296     if(ra>=0) {
4297       int offset=imm[i];
4298       int c=(i_regs->wasconst>>rs)&1;
4299       if(dops[i].rs1==0) {
4300         // Using r0 as a base address
4301         if(!entry||entry[ra]!=agr) {
4302           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4303             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4304           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4305             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4306           }else{
4307             emit_movimm(offset,ra);
4308           }
4309         } // else did it in the previous cycle
4310       }
4311       else if(rs<0) {
4312         if(!entry||entry[ra]!=dops[i].rs1)
4313           emit_loadreg(dops[i].rs1,ra);
4314         //if(!entry||entry[ra]!=dops[i].rs1)
4315         //  printf("poor load scheduling!\n");
4316       }
4317       else if(c) {
4318         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4319           if(!entry||entry[ra]!=agr) {
4320             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4321               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4322             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4323               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4324             }else{
4325               emit_movimm(constmap[i][rs]+offset,ra);
4326               regs[i].loadedconst|=1<<ra;
4327             }
4328           } // else did it in the previous cycle
4329         } // else load_consts already did it
4330       }
4331       if(offset&&!c&&dops[i].rs1) {
4332         if(rs>=0) {
4333           emit_addimm(rs,offset,ra);
4334         }else{
4335           emit_addimm(ra,offset,ra);
4336         }
4337       }
4338     }
4339   }
4340   // Preload constants for next instruction
4341   if (dops[i+1].is_load || dops[i+1].is_store) {
4342     int agr,ra;
4343     // Actual address
4344     agr=AGEN1+((i+1)&1);
4345     ra=get_reg(i_regs->regmap,agr);
4346     if(ra>=0) {
4347       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4348       int offset=imm[i+1];
4349       int c=(regs[i+1].wasconst>>rs)&1;
4350       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4351         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4352           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4353         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4354           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4355         }else{
4356           emit_movimm(constmap[i+1][rs]+offset,ra);
4357           regs[i+1].loadedconst|=1<<ra;
4358         }
4359       }
4360       else if(dops[i+1].rs1==0) {
4361         // Using r0 as a base address
4362         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4363           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4364         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4365           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4366         }else{
4367           emit_movimm(offset,ra);
4368         }
4369       }
4370     }
4371   }
4372 }
4373
4374 static int get_final_value(int hr, int i, int *value)
4375 {
4376   int reg=regs[i].regmap[hr];
4377   while(i<slen-1) {
4378     if(regs[i+1].regmap[hr]!=reg) break;
4379     if(!((regs[i+1].isconst>>hr)&1)) break;
4380     if(dops[i+1].bt) break;
4381     i++;
4382   }
4383   if(i<slen-1) {
4384     if (dops[i].is_jump) {
4385       *value=constmap[i][hr];
4386       return 1;
4387     }
4388     if(!dops[i+1].bt) {
4389       if (dops[i+1].is_jump) {
4390         // Load in delay slot, out-of-order execution
4391         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4392         {
4393           // Precompute load address
4394           *value=constmap[i][hr]+imm[i+2];
4395           return 1;
4396         }
4397       }
4398       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4399       {
4400         // Precompute load address
4401         *value=constmap[i][hr]+imm[i+1];
4402         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4403         return 1;
4404       }
4405     }
4406   }
4407   *value=constmap[i][hr];
4408   //printf("c=%lx\n",(long)constmap[i][hr]);
4409   if(i==slen-1) return 1;
4410   assert(reg < 64);
4411   return !((unneeded_reg[i+1]>>reg)&1);
4412 }
4413
4414 // Load registers with known constants
4415 static void load_consts(signed char pre[],signed char regmap[],int i)
4416 {
4417   int hr,hr2;
4418   // propagate loaded constant flags
4419   if(i==0||dops[i].bt)
4420     regs[i].loadedconst=0;
4421   else {
4422     for(hr=0;hr<HOST_REGS;hr++) {
4423       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4424          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4425       {
4426         regs[i].loadedconst|=1<<hr;
4427       }
4428     }
4429   }
4430   // Load 32-bit regs
4431   for(hr=0;hr<HOST_REGS;hr++) {
4432     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4433       //if(entry[hr]!=regmap[hr]) {
4434       if(!((regs[i].loadedconst>>hr)&1)) {
4435         assert(regmap[hr]<64);
4436         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4437           int value,similar=0;
4438           if(get_final_value(hr,i,&value)) {
4439             // see if some other register has similar value
4440             for(hr2=0;hr2<HOST_REGS;hr2++) {
4441               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4442                 if(is_similar_value(value,constmap[i][hr2])) {
4443                   similar=1;
4444                   break;
4445                 }
4446               }
4447             }
4448             if(similar) {
4449               int value2;
4450               if(get_final_value(hr2,i,&value2)) // is this needed?
4451                 emit_movimm_from(value2,hr2,value,hr);
4452               else
4453                 emit_movimm(value,hr);
4454             }
4455             else if(value==0) {
4456               emit_zeroreg(hr);
4457             }
4458             else {
4459               emit_movimm(value,hr);
4460             }
4461           }
4462           regs[i].loadedconst|=1<<hr;
4463         }
4464       }
4465     }
4466   }
4467 }
4468
4469 static void load_all_consts(const signed char regmap[], u_int dirty, int i)
4470 {
4471   int hr;
4472   // Load 32-bit regs
4473   for(hr=0;hr<HOST_REGS;hr++) {
4474     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4475       assert(regmap[hr] < 64);
4476       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4477         int value=constmap[i][hr];
4478         if(value==0) {
4479           emit_zeroreg(hr);
4480         }
4481         else {
4482           emit_movimm(value,hr);
4483         }
4484       }
4485     }
4486   }
4487 }
4488
4489 // Write out all dirty registers (except cycle count)
4490 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty)
4491 {
4492   int hr;
4493   for(hr=0;hr<HOST_REGS;hr++) {
4494     if(hr!=EXCLUDE_REG) {
4495       if(i_regmap[hr]>0) {
4496         if(i_regmap[hr]!=CCREG) {
4497           if((i_dirty>>hr)&1) {
4498             assert(i_regmap[hr]<64);
4499             emit_storereg(i_regmap[hr],hr);
4500           }
4501         }
4502       }
4503     }
4504   }
4505 }
4506
4507 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4508 // This writes the registers not written by store_regs_bt
4509 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr)
4510 {
4511   int hr;
4512   int t=(addr-start)>>2;
4513   for(hr=0;hr<HOST_REGS;hr++) {
4514     if(hr!=EXCLUDE_REG) {
4515       if(i_regmap[hr]>0) {
4516         if(i_regmap[hr]!=CCREG) {
4517           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4518             if((i_dirty>>hr)&1) {
4519               assert(i_regmap[hr]<64);
4520               emit_storereg(i_regmap[hr],hr);
4521             }
4522           }
4523         }
4524       }
4525     }
4526   }
4527 }
4528
4529 // Load all registers (except cycle count)
4530 static void load_all_regs(const signed char i_regmap[])
4531 {
4532   int hr;
4533   for(hr=0;hr<HOST_REGS;hr++) {
4534     if(hr!=EXCLUDE_REG) {
4535       if(i_regmap[hr]==0) {
4536         emit_zeroreg(hr);
4537       }
4538       else
4539       if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4540       {
4541         emit_loadreg(i_regmap[hr],hr);
4542       }
4543     }
4544   }
4545 }
4546
4547 // Load all current registers also needed by next instruction
4548 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[])
4549 {
4550   int hr;
4551   for(hr=0;hr<HOST_REGS;hr++) {
4552     if(hr!=EXCLUDE_REG) {
4553       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4554         if(i_regmap[hr]==0) {
4555           emit_zeroreg(hr);
4556         }
4557         else
4558         if(i_regmap[hr]>0 && (i_regmap[hr]&63)<TEMPREG && i_regmap[hr]!=CCREG)
4559         {
4560           emit_loadreg(i_regmap[hr],hr);
4561         }
4562       }
4563     }
4564   }
4565 }
4566
4567 // Load all regs, storing cycle count if necessary
4568 static void load_regs_entry(int t)
4569 {
4570   int hr;
4571   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4572   else if(ccadj[t]) emit_addimm(HOST_CCREG,-ccadj[t],HOST_CCREG);
4573   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4574     emit_storereg(CCREG,HOST_CCREG);
4575   }
4576   // Load 32-bit regs
4577   for(hr=0;hr<HOST_REGS;hr++) {
4578     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4579       if(regs[t].regmap_entry[hr]==0) {
4580         emit_zeroreg(hr);
4581       }
4582       else if(regs[t].regmap_entry[hr]!=CCREG)
4583       {
4584         emit_loadreg(regs[t].regmap_entry[hr],hr);
4585       }
4586     }
4587   }
4588 }
4589
4590 // Store dirty registers prior to branch
4591 void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4592 {
4593   if(internal_branch(addr))
4594   {
4595     int t=(addr-start)>>2;
4596     int hr;
4597     for(hr=0;hr<HOST_REGS;hr++) {
4598       if(hr!=EXCLUDE_REG) {
4599         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4600           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4601             if((i_dirty>>hr)&1) {
4602               assert(i_regmap[hr]<64);
4603               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4604                 emit_storereg(i_regmap[hr],hr);
4605             }
4606           }
4607         }
4608       }
4609     }
4610   }
4611   else
4612   {
4613     // Branch out of this block, write out all dirty regs
4614     wb_dirtys(i_regmap,i_dirty);
4615   }
4616 }
4617
4618 // Load all needed registers for branch target
4619 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4620 {
4621   //if(addr>=start && addr<(start+slen*4))
4622   if(internal_branch(addr))
4623   {
4624     int t=(addr-start)>>2;
4625     int hr;
4626     // Store the cycle count before loading something else
4627     if(i_regmap[HOST_CCREG]!=CCREG) {
4628       assert(i_regmap[HOST_CCREG]==-1);
4629     }
4630     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4631       emit_storereg(CCREG,HOST_CCREG);
4632     }
4633     // Load 32-bit regs
4634     for(hr=0;hr<HOST_REGS;hr++) {
4635       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4636         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4637           if(regs[t].regmap_entry[hr]==0) {
4638             emit_zeroreg(hr);
4639           }
4640           else if(regs[t].regmap_entry[hr]!=CCREG)
4641           {
4642             emit_loadreg(regs[t].regmap_entry[hr],hr);
4643           }
4644         }
4645       }
4646     }
4647   }
4648 }
4649
4650 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4651 {
4652   if(addr>=start && addr<start+slen*4-4)
4653   {
4654     int t=(addr-start)>>2;
4655     int hr;
4656     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4657     for(hr=0;hr<HOST_REGS;hr++)
4658     {
4659       if(hr!=EXCLUDE_REG)
4660       {
4661         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4662         {
4663           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4664           {
4665             return 0;
4666           }
4667           else
4668           if((i_dirty>>hr)&1)
4669           {
4670             if(i_regmap[hr]<TEMPREG)
4671             {
4672               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4673                 return 0;
4674             }
4675             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4676             {
4677               assert(0);
4678             }
4679           }
4680         }
4681         else // Same register but is it 32-bit or dirty?
4682         if(i_regmap[hr]>=0)
4683         {
4684           if(!((regs[t].dirty>>hr)&1))
4685           {
4686             if((i_dirty>>hr)&1)
4687             {
4688               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4689               {
4690                 //printf("%x: dirty no match\n",addr);
4691                 return 0;
4692               }
4693             }
4694           }
4695         }
4696       }
4697     }
4698     // Delay slots are not valid branch targets
4699     //if(t>0&&(dops[t-1].is_jump) return 0;
4700     // Delay slots require additional processing, so do not match
4701     if(dops[t].is_ds) return 0;
4702   }
4703   else
4704   {
4705     int hr;
4706     for(hr=0;hr<HOST_REGS;hr++)
4707     {
4708       if(hr!=EXCLUDE_REG)
4709       {
4710         if(i_regmap[hr]>=0)
4711         {
4712           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4713           {
4714             if((i_dirty>>hr)&1)
4715             {
4716               return 0;
4717             }
4718           }
4719         }
4720       }
4721     }
4722   }
4723   return 1;
4724 }
4725
4726 #ifdef DRC_DBG
4727 static void drc_dbg_emit_do_cmp(int i, int ccadj_)
4728 {
4729   extern void do_insn_cmp();
4730   //extern int cycle;
4731   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4732
4733   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4734   save_regs(reglist);
4735   // write out changed consts to match the interpreter
4736   if (i > 0 && !dops[i].bt) {
4737     for (hr = 0; hr < HOST_REGS; hr++) {
4738       int reg = regs[i].regmap_entry[hr]; // regs[i-1].regmap[hr];
4739       if (hr == EXCLUDE_REG || reg < 0)
4740         continue;
4741       if (!((regs[i-1].isconst >> hr) & 1))
4742         continue;
4743       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4744         continue;
4745       emit_movimm(constmap[i-1][hr],0);
4746       emit_storereg(reg, 0);
4747     }
4748   }
4749   emit_movimm(start+i*4,0);
4750   emit_writeword(0,&pcaddr);
4751   int cc = get_reg(regs[i].regmap_entry, CCREG);
4752   if (cc < 0)
4753     emit_loadreg(CCREG, cc = 0);
4754   emit_addimm(cc, ccadj_, 0);
4755   emit_writeword(0, &psxRegs.cycle);
4756   emit_far_call(do_insn_cmp);
4757   //emit_readword(&cycle,0);
4758   //emit_addimm(0,2,0);
4759   //emit_writeword(0,&cycle);
4760   (void)get_reg2;
4761   restore_regs(reglist);
4762   assem_debug("\\\\do_insn_cmp\n");
4763 }
4764 #else
4765 #define drc_dbg_emit_do_cmp(x,y)
4766 #endif
4767
4768 // Used when a branch jumps into the delay slot of another branch
4769 static void ds_assemble_entry(int i)
4770 {
4771   int t = (ba[i] - start) >> 2;
4772   int ccadj_ = -CLOCK_ADJUST(1);
4773   if (!instr_addr[t])
4774     instr_addr[t] = out;
4775   assem_debug("Assemble delay slot at %x\n",ba[i]);
4776   assem_debug("<->\n");
4777   drc_dbg_emit_do_cmp(t, ccadj_);
4778   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4779     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4780   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4781   address_generation(t,&regs[t],regs[t].regmap_entry);
4782   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4783     load_regs(regs[t].regmap_entry,regs[t].regmap,ROREG,ROREG);
4784   if (dops[t].is_store)
4785     load_regs(regs[t].regmap_entry,regs[t].regmap,INVCP,INVCP);
4786   is_delayslot=0;
4787   switch (dops[t].itype) {
4788     case SYSCALL:
4789     case HLECALL:
4790     case INTCALL:
4791     case SPAN:
4792     case UJUMP:
4793     case RJUMP:
4794     case CJUMP:
4795     case SJUMP:
4796       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4797       break;
4798     default:
4799       assemble(t, &regs[t], ccadj_);
4800   }
4801   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4802   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4803   if(internal_branch(ba[i]+4))
4804     assem_debug("branch: internal\n");
4805   else
4806     assem_debug("branch: external\n");
4807   assert(internal_branch(ba[i]+4));
4808   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4809   emit_jmp(0);
4810 }
4811
4812 static void emit_extjump(void *addr, u_int target)
4813 {
4814   emit_extjump2(addr, target, dyna_linker);
4815 }
4816
4817 static void emit_extjump_ds(void *addr, u_int target)
4818 {
4819   emit_extjump2(addr, target, dyna_linker_ds);
4820 }
4821
4822 // Load 2 immediates optimizing for small code size
4823 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4824 {
4825   emit_movimm(imm1,rt1);
4826   emit_movimm_from(imm1,rt1,imm2,rt2);
4827 }
4828
4829 static void do_cc(int i, const signed char i_regmap[], int *adj,
4830   int addr, int taken, int invert)
4831 {
4832   int count, count_plus2;
4833   void *jaddr;
4834   void *idle=NULL;
4835   int t=0;
4836   if(dops[i].itype==RJUMP)
4837   {
4838     *adj=0;
4839   }
4840   //if(ba[i]>=start && ba[i]<(start+slen*4))
4841   if(internal_branch(ba[i]))
4842   {
4843     t=(ba[i]-start)>>2;
4844     if(dops[t].is_ds) *adj=-CLOCK_ADJUST(1); // Branch into delay slot adds an extra cycle
4845     else *adj=ccadj[t];
4846   }
4847   else
4848   {
4849     *adj=0;
4850   }
4851   count = ccadj[i];
4852   count_plus2 = count + CLOCK_ADJUST(2);
4853   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4854     // Idle loop
4855     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4856     idle=out;
4857     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4858     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4859     jaddr=out;
4860     emit_jmp(0);
4861   }
4862   else if(*adj==0||invert) {
4863     int cycles = count_plus2;
4864     // faster loop HACK
4865 #if 0
4866     if (t&&*adj) {
4867       int rel=t-i;
4868       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4869         cycles=*adj+count+2-*adj;
4870     }
4871 #endif
4872     emit_addimm_and_set_flags(cycles, HOST_CCREG);
4873     jaddr = out;
4874     emit_jns(0);
4875   }
4876   else
4877   {
4878     emit_cmpimm(HOST_CCREG, -count_plus2);
4879     jaddr = out;
4880     emit_jns(0);
4881   }
4882   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:count_plus2,i,addr,taken,0);
4883 }
4884
4885 static void do_ccstub(int n)
4886 {
4887   literal_pool(256);
4888   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4889   set_jump_target(stubs[n].addr, out);
4890   int i=stubs[n].b;
4891   if(stubs[n].d==NULLDS) {
4892     // Delay slot instruction is nullified ("likely" branch)
4893     wb_dirtys(regs[i].regmap,regs[i].dirty);
4894   }
4895   else if(stubs[n].d!=TAKEN) {
4896     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
4897   }
4898   else {
4899     if(internal_branch(ba[i]))
4900       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
4901   }
4902   if(stubs[n].c!=-1)
4903   {
4904     // Save PC as return address
4905     emit_movimm(stubs[n].c,EAX);
4906     emit_writeword(EAX,&pcaddr);
4907   }
4908   else
4909   {
4910     // Return address depends on which way the branch goes
4911     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
4912     {
4913       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
4914       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
4915       if(dops[i].rs1==0)
4916       {
4917         s1l=s2l;
4918         s2l=-1;
4919       }
4920       else if(dops[i].rs2==0)
4921       {
4922         s2l=-1;
4923       }
4924       assert(s1l>=0);
4925       #ifdef DESTRUCTIVE_WRITEBACK
4926       if(dops[i].rs1) {
4927         if((branch_regs[i].dirty>>s1l)&&1)
4928           emit_loadreg(dops[i].rs1,s1l);
4929       }
4930       else {
4931         if((branch_regs[i].dirty>>s1l)&1)
4932           emit_loadreg(dops[i].rs2,s1l);
4933       }
4934       if(s2l>=0)
4935         if((branch_regs[i].dirty>>s2l)&1)
4936           emit_loadreg(dops[i].rs2,s2l);
4937       #endif
4938       int hr=0;
4939       int addr=-1,alt=-1,ntaddr=-1;
4940       while(hr<HOST_REGS)
4941       {
4942         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4943            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4944            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4945         {
4946           addr=hr++;break;
4947         }
4948         hr++;
4949       }
4950       while(hr<HOST_REGS)
4951       {
4952         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4953            (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4954            (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4955         {
4956           alt=hr++;break;
4957         }
4958         hr++;
4959       }
4960       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
4961       {
4962         while(hr<HOST_REGS)
4963         {
4964           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
4965              (branch_regs[i].regmap[hr]&63)!=dops[i].rs1 &&
4966              (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 )
4967           {
4968             ntaddr=hr;break;
4969           }
4970           hr++;
4971         }
4972         assert(hr<HOST_REGS);
4973       }
4974       if((dops[i].opcode&0x2f)==4) // BEQ
4975       {
4976         #ifdef HAVE_CMOV_IMM
4977         if(s2l>=0) emit_cmp(s1l,s2l);
4978         else emit_test(s1l,s1l);
4979         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
4980         #else
4981         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
4982         if(s2l>=0) emit_cmp(s1l,s2l);
4983         else emit_test(s1l,s1l);
4984         emit_cmovne_reg(alt,addr);
4985         #endif
4986       }
4987       if((dops[i].opcode&0x2f)==5) // BNE
4988       {
4989         #ifdef HAVE_CMOV_IMM
4990         if(s2l>=0) emit_cmp(s1l,s2l);
4991         else emit_test(s1l,s1l);
4992         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
4993         #else
4994         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
4995         if(s2l>=0) emit_cmp(s1l,s2l);
4996         else emit_test(s1l,s1l);
4997         emit_cmovne_reg(alt,addr);
4998         #endif
4999       }
5000       if((dops[i].opcode&0x2f)==6) // BLEZ
5001       {
5002         //emit_movimm(ba[i],alt);
5003         //emit_movimm(start+i*4+8,addr);
5004         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5005         emit_cmpimm(s1l,1);
5006         emit_cmovl_reg(alt,addr);
5007       }
5008       if((dops[i].opcode&0x2f)==7) // BGTZ
5009       {
5010         //emit_movimm(ba[i],addr);
5011         //emit_movimm(start+i*4+8,ntaddr);
5012         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5013         emit_cmpimm(s1l,1);
5014         emit_cmovl_reg(ntaddr,addr);
5015       }
5016       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
5017       {
5018         //emit_movimm(ba[i],alt);
5019         //emit_movimm(start+i*4+8,addr);
5020         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5021         emit_test(s1l,s1l);
5022         emit_cmovs_reg(alt,addr);
5023       }
5024       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
5025       {
5026         //emit_movimm(ba[i],addr);
5027         //emit_movimm(start+i*4+8,alt);
5028         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5029         emit_test(s1l,s1l);
5030         emit_cmovs_reg(alt,addr);
5031       }
5032       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5033         if(source[i]&0x10000) // BC1T
5034         {
5035           //emit_movimm(ba[i],alt);
5036           //emit_movimm(start+i*4+8,addr);
5037           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5038           emit_testimm(s1l,0x800000);
5039           emit_cmovne_reg(alt,addr);
5040         }
5041         else // BC1F
5042         {
5043           //emit_movimm(ba[i],addr);
5044           //emit_movimm(start+i*4+8,alt);
5045           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5046           emit_testimm(s1l,0x800000);
5047           emit_cmovne_reg(alt,addr);
5048         }
5049       }
5050       emit_writeword(addr,&pcaddr);
5051     }
5052     else
5053     if(dops[i].itype==RJUMP)
5054     {
5055       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
5056       if (ds_writes_rjump_rs(i)) {
5057         r=get_reg(branch_regs[i].regmap,RTEMP);
5058       }
5059       emit_writeword(r,&pcaddr);
5060     }
5061     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
5062   }
5063   // Update cycle count
5064   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
5065   if(stubs[n].a) emit_addimm(HOST_CCREG,(int)stubs[n].a,HOST_CCREG);
5066   emit_far_call(cc_interrupt);
5067   if(stubs[n].a) emit_addimm(HOST_CCREG,-(int)stubs[n].a,HOST_CCREG);
5068   if(stubs[n].d==TAKEN) {
5069     if(internal_branch(ba[i]))
5070       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
5071     else if(dops[i].itype==RJUMP) {
5072       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
5073         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
5074       else
5075         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
5076     }
5077   }else if(stubs[n].d==NOTTAKEN) {
5078     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
5079     else load_all_regs(branch_regs[i].regmap);
5080   }else if(stubs[n].d==NULLDS) {
5081     // Delay slot instruction is nullified ("likely" branch)
5082     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5083     else load_all_regs(regs[i].regmap);
5084   }else{
5085     load_all_regs(branch_regs[i].regmap);
5086   }
5087   if (stubs[n].retaddr)
5088     emit_jmp(stubs[n].retaddr);
5089   else
5090     do_jump_vaddr(stubs[n].e);
5091 }
5092
5093 static void add_to_linker(void *addr, u_int target, int ext)
5094 {
5095   assert(linkcount < ARRAY_SIZE(link_addr));
5096   link_addr[linkcount].addr = addr;
5097   link_addr[linkcount].target = target;
5098   link_addr[linkcount].ext = ext;
5099   linkcount++;
5100 }
5101
5102 static void ujump_assemble_write_ra(int i)
5103 {
5104   int rt;
5105   unsigned int return_address;
5106   rt=get_reg(branch_regs[i].regmap,31);
5107   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5108   //assert(rt>=0);
5109   return_address=start+i*4+8;
5110   if(rt>=0) {
5111     #ifdef USE_MINI_HT
5112     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5113       int temp=-1; // note: must be ds-safe
5114       #ifdef HOST_TEMPREG
5115       temp=HOST_TEMPREG;
5116       #endif
5117       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5118       else emit_movimm(return_address,rt);
5119     }
5120     else
5121     #endif
5122     {
5123       #ifdef REG_PREFETCH
5124       if(temp>=0)
5125       {
5126         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5127       }
5128       #endif
5129       emit_movimm(return_address,rt); // PC into link register
5130       #ifdef IMM_PREFETCH
5131       emit_prefetch(hash_table_get(return_address));
5132       #endif
5133     }
5134   }
5135 }
5136
5137 static void ujump_assemble(int i, const struct regstat *i_regs)
5138 {
5139   int ra_done=0;
5140   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5141   address_generation(i+1,i_regs,regs[i].regmap_entry);
5142   #ifdef REG_PREFETCH
5143   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5144   if(dops[i].rt1==31&&temp>=0)
5145   {
5146     signed char *i_regmap=i_regs->regmap;
5147     int return_address=start+i*4+8;
5148     if(get_reg(branch_regs[i].regmap,31)>0)
5149     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5150   }
5151   #endif
5152   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5153     ujump_assemble_write_ra(i); // writeback ra for DS
5154     ra_done=1;
5155   }
5156   ds_assemble(i+1,i_regs);
5157   uint64_t bc_unneeded=branch_regs[i].u;
5158   bc_unneeded|=1|(1LL<<dops[i].rt1);
5159   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5160   load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5161   if(!ra_done&&dops[i].rt1==31)
5162     ujump_assemble_write_ra(i);
5163   int cc,adj;
5164   cc=get_reg(branch_regs[i].regmap,CCREG);
5165   assert(cc==HOST_CCREG);
5166   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5167   #ifdef REG_PREFETCH
5168   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5169   #endif
5170   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5171   if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5172   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5173   if(internal_branch(ba[i]))
5174     assem_debug("branch: internal\n");
5175   else
5176     assem_debug("branch: external\n");
5177   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5178     ds_assemble_entry(i);
5179   }
5180   else {
5181     add_to_linker(out,ba[i],internal_branch(ba[i]));
5182     emit_jmp(0);
5183   }
5184 }
5185
5186 static void rjump_assemble_write_ra(int i)
5187 {
5188   int rt,return_address;
5189   assert(dops[i+1].rt1!=dops[i].rt1);
5190   assert(dops[i+1].rt2!=dops[i].rt1);
5191   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5192   assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5193   assert(rt>=0);
5194   return_address=start+i*4+8;
5195   #ifdef REG_PREFETCH
5196   if(temp>=0)
5197   {
5198     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5199   }
5200   #endif
5201   emit_movimm(return_address,rt); // PC into link register
5202   #ifdef IMM_PREFETCH
5203   emit_prefetch(hash_table_get(return_address));
5204   #endif
5205 }
5206
5207 static void rjump_assemble(int i, const struct regstat *i_regs)
5208 {
5209   int temp;
5210   int rs,cc;
5211   int ra_done=0;
5212   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5213   assert(rs>=0);
5214   if (ds_writes_rjump_rs(i)) {
5215     // Delay slot abuse, make a copy of the branch address register
5216     temp=get_reg(branch_regs[i].regmap,RTEMP);
5217     assert(temp>=0);
5218     assert(regs[i].regmap[temp]==RTEMP);
5219     emit_mov(rs,temp);
5220     rs=temp;
5221   }
5222   address_generation(i+1,i_regs,regs[i].regmap_entry);
5223   #ifdef REG_PREFETCH
5224   if(dops[i].rt1==31)
5225   {
5226     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5227       signed char *i_regmap=i_regs->regmap;
5228       int return_address=start+i*4+8;
5229       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5230     }
5231   }
5232   #endif
5233   #ifdef USE_MINI_HT
5234   if(dops[i].rs1==31) {
5235     int rh=get_reg(regs[i].regmap,RHASH);
5236     if(rh>=0) do_preload_rhash(rh);
5237   }
5238   #endif
5239   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5240     rjump_assemble_write_ra(i);
5241     ra_done=1;
5242   }
5243   ds_assemble(i+1,i_regs);
5244   uint64_t bc_unneeded=branch_regs[i].u;
5245   bc_unneeded|=1|(1LL<<dops[i].rt1);
5246   bc_unneeded&=~(1LL<<dops[i].rs1);
5247   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5248   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5249   if(!ra_done&&dops[i].rt1!=0)
5250     rjump_assemble_write_ra(i);
5251   cc=get_reg(branch_regs[i].regmap,CCREG);
5252   assert(cc==HOST_CCREG);
5253   (void)cc;
5254   #ifdef USE_MINI_HT
5255   int rh=get_reg(branch_regs[i].regmap,RHASH);
5256   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5257   if(dops[i].rs1==31) {
5258     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5259     do_preload_rhtbl(ht);
5260     do_rhash(rs,rh);
5261   }
5262   #endif
5263   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5264   #ifdef DESTRUCTIVE_WRITEBACK
5265   if((branch_regs[i].dirty>>rs)&1) {
5266     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5267       emit_loadreg(dops[i].rs1,rs);
5268     }
5269   }
5270   #endif
5271   #ifdef REG_PREFETCH
5272   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5273   #endif
5274   #ifdef USE_MINI_HT
5275   if(dops[i].rs1==31) {
5276     do_miniht_load(ht,rh);
5277   }
5278   #endif
5279   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5280   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5281   //assert(adj==0);
5282   emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5283   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5284   if(dops[i+1].itype==COP0&&(source[i+1]&0x3f)==0x10)
5285     // special case for RFE
5286     emit_jmp(0);
5287   else
5288     emit_jns(0);
5289   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5290   #ifdef USE_MINI_HT
5291   if(dops[i].rs1==31) {
5292     do_miniht_jump(rs,rh,ht);
5293   }
5294   else
5295   #endif
5296   {
5297     do_jump_vaddr(rs);
5298   }
5299   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5300   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5301   #endif
5302 }
5303
5304 static void cjump_assemble(int i, const struct regstat *i_regs)
5305 {
5306   const signed char *i_regmap = i_regs->regmap;
5307   int cc;
5308   int match;
5309   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5310   assem_debug("match=%d\n",match);
5311   int s1l,s2l;
5312   int unconditional=0,nop=0;
5313   int invert=0;
5314   int internal=internal_branch(ba[i]);
5315   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5316   if(!match) invert=1;
5317   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5318   if(i>(ba[i]-start)>>2) invert=1;
5319   #endif
5320   #ifdef __aarch64__
5321   invert=1; // because of near cond. branches
5322   #endif
5323
5324   if(dops[i].ooo) {
5325     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5326     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5327   }
5328   else {
5329     s1l=get_reg(i_regmap,dops[i].rs1);
5330     s2l=get_reg(i_regmap,dops[i].rs2);
5331   }
5332   if(dops[i].rs1==0&&dops[i].rs2==0)
5333   {
5334     if(dops[i].opcode&1) nop=1;
5335     else unconditional=1;
5336     //assert(dops[i].opcode!=5);
5337     //assert(dops[i].opcode!=7);
5338     //assert(dops[i].opcode!=0x15);
5339     //assert(dops[i].opcode!=0x17);
5340   }
5341   else if(dops[i].rs1==0)
5342   {
5343     s1l=s2l;
5344     s2l=-1;
5345   }
5346   else if(dops[i].rs2==0)
5347   {
5348     s2l=-1;
5349   }
5350
5351   if(dops[i].ooo) {
5352     // Out of order execution (delay slot first)
5353     //printf("OOOE\n");
5354     address_generation(i+1,i_regs,regs[i].regmap_entry);
5355     ds_assemble(i+1,i_regs);
5356     int adj;
5357     uint64_t bc_unneeded=branch_regs[i].u;
5358     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5359     bc_unneeded|=1;
5360     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5361     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5362     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5363     cc=get_reg(branch_regs[i].regmap,CCREG);
5364     assert(cc==HOST_CCREG);
5365     if(unconditional)
5366       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5367     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5368     //assem_debug("cycle count (adj)\n");
5369     if(unconditional) {
5370       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5371       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5372         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5373         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5374         if(internal)
5375           assem_debug("branch: internal\n");
5376         else
5377           assem_debug("branch: external\n");
5378         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5379           ds_assemble_entry(i);
5380         }
5381         else {
5382           add_to_linker(out,ba[i],internal);
5383           emit_jmp(0);
5384         }
5385         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5386         if(((u_int)out)&7) emit_addnop(0);
5387         #endif
5388       }
5389     }
5390     else if(nop) {
5391       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5392       void *jaddr=out;
5393       emit_jns(0);
5394       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5395     }
5396     else {
5397       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5398       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5399       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5400
5401       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5402       assert(s1l>=0);
5403       if(dops[i].opcode==4) // BEQ
5404       {
5405         if(s2l>=0) emit_cmp(s1l,s2l);
5406         else emit_test(s1l,s1l);
5407         if(invert){
5408           nottaken=out;
5409           emit_jne(DJT_1);
5410         }else{
5411           add_to_linker(out,ba[i],internal);
5412           emit_jeq(0);
5413         }
5414       }
5415       if(dops[i].opcode==5) // BNE
5416       {
5417         if(s2l>=0) emit_cmp(s1l,s2l);
5418         else emit_test(s1l,s1l);
5419         if(invert){
5420           nottaken=out;
5421           emit_jeq(DJT_1);
5422         }else{
5423           add_to_linker(out,ba[i],internal);
5424           emit_jne(0);
5425         }
5426       }
5427       if(dops[i].opcode==6) // BLEZ
5428       {
5429         emit_cmpimm(s1l,1);
5430         if(invert){
5431           nottaken=out;
5432           emit_jge(DJT_1);
5433         }else{
5434           add_to_linker(out,ba[i],internal);
5435           emit_jl(0);
5436         }
5437       }
5438       if(dops[i].opcode==7) // BGTZ
5439       {
5440         emit_cmpimm(s1l,1);
5441         if(invert){
5442           nottaken=out;
5443           emit_jl(DJT_1);
5444         }else{
5445           add_to_linker(out,ba[i],internal);
5446           emit_jge(0);
5447         }
5448       }
5449       if(invert) {
5450         if(taken) set_jump_target(taken, out);
5451         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5452         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5453           if(adj) {
5454             emit_addimm(cc,-adj,cc);
5455             add_to_linker(out,ba[i],internal);
5456           }else{
5457             emit_addnop(13);
5458             add_to_linker(out,ba[i],internal*2);
5459           }
5460           emit_jmp(0);
5461         }else
5462         #endif
5463         {
5464           if(adj) emit_addimm(cc,-adj,cc);
5465           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5466           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5467           if(internal)
5468             assem_debug("branch: internal\n");
5469           else
5470             assem_debug("branch: external\n");
5471           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5472             ds_assemble_entry(i);
5473           }
5474           else {
5475             add_to_linker(out,ba[i],internal);
5476             emit_jmp(0);
5477           }
5478         }
5479         set_jump_target(nottaken, out);
5480       }
5481
5482       if(nottaken1) set_jump_target(nottaken1, out);
5483       if(adj) {
5484         if(!invert) emit_addimm(cc,adj,cc);
5485       }
5486     } // (!unconditional)
5487   } // if(ooo)
5488   else
5489   {
5490     // In-order execution (branch first)
5491     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5492     if(!unconditional&&!nop) {
5493       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5494       assert(s1l>=0);
5495       if((dops[i].opcode&0x2f)==4) // BEQ
5496       {
5497         if(s2l>=0) emit_cmp(s1l,s2l);
5498         else emit_test(s1l,s1l);
5499         nottaken=out;
5500         emit_jne(DJT_2);
5501       }
5502       if((dops[i].opcode&0x2f)==5) // BNE
5503       {
5504         if(s2l>=0) emit_cmp(s1l,s2l);
5505         else emit_test(s1l,s1l);
5506         nottaken=out;
5507         emit_jeq(DJT_2);
5508       }
5509       if((dops[i].opcode&0x2f)==6) // BLEZ
5510       {
5511         emit_cmpimm(s1l,1);
5512         nottaken=out;
5513         emit_jge(DJT_2);
5514       }
5515       if((dops[i].opcode&0x2f)==7) // BGTZ
5516       {
5517         emit_cmpimm(s1l,1);
5518         nottaken=out;
5519         emit_jl(DJT_2);
5520       }
5521     } // if(!unconditional)
5522     int adj;
5523     uint64_t ds_unneeded=branch_regs[i].u;
5524     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5525     ds_unneeded|=1;
5526     // branch taken
5527     if(!nop) {
5528       if(taken) set_jump_target(taken, out);
5529       assem_debug("1:\n");
5530       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5531       // load regs
5532       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5533       address_generation(i+1,&branch_regs[i],0);
5534       if (ram_offset)
5535         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5536       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5537       ds_assemble(i+1,&branch_regs[i]);
5538       cc=get_reg(branch_regs[i].regmap,CCREG);
5539       if(cc==-1) {
5540         emit_loadreg(CCREG,cc=HOST_CCREG);
5541         // CHECK: Is the following instruction (fall thru) allocated ok?
5542       }
5543       assert(cc==HOST_CCREG);
5544       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5545       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5546       assem_debug("cycle count (adj)\n");
5547       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5548       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5549       if(internal)
5550         assem_debug("branch: internal\n");
5551       else
5552         assem_debug("branch: external\n");
5553       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5554         ds_assemble_entry(i);
5555       }
5556       else {
5557         add_to_linker(out,ba[i],internal);
5558         emit_jmp(0);
5559       }
5560     }
5561     // branch not taken
5562     if(!unconditional) {
5563       if(nottaken1) set_jump_target(nottaken1, out);
5564       set_jump_target(nottaken, out);
5565       assem_debug("2:\n");
5566       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5567       // load regs
5568       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5569       address_generation(i+1,&branch_regs[i],0);
5570       if (ram_offset)
5571         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5572       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5573       ds_assemble(i+1,&branch_regs[i]);
5574       cc=get_reg(branch_regs[i].regmap,CCREG);
5575       if (cc == -1) {
5576         // Cycle count isn't in a register, temporarily load it then write it out
5577         emit_loadreg(CCREG,HOST_CCREG);
5578         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5579         void *jaddr=out;
5580         emit_jns(0);
5581         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5582         emit_storereg(CCREG,HOST_CCREG);
5583       }
5584       else{
5585         cc=get_reg(i_regmap,CCREG);
5586         assert(cc==HOST_CCREG);
5587         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5588         void *jaddr=out;
5589         emit_jns(0);
5590         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5591       }
5592     }
5593   }
5594 }
5595
5596 static void sjump_assemble(int i, const struct regstat *i_regs)
5597 {
5598   const signed char *i_regmap = i_regs->regmap;
5599   int cc;
5600   int match;
5601   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5602   assem_debug("smatch=%d\n",match);
5603   int s1l;
5604   int unconditional=0,nevertaken=0;
5605   int invert=0;
5606   int internal=internal_branch(ba[i]);
5607   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5608   if(!match) invert=1;
5609   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5610   if(i>(ba[i]-start)>>2) invert=1;
5611   #endif
5612   #ifdef __aarch64__
5613   invert=1; // because of near cond. branches
5614   #endif
5615
5616   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5617   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5618
5619   if(dops[i].ooo) {
5620     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5621   }
5622   else {
5623     s1l=get_reg(i_regmap,dops[i].rs1);
5624   }
5625   if(dops[i].rs1==0)
5626   {
5627     if(dops[i].opcode2&1) unconditional=1;
5628     else nevertaken=1;
5629     // These are never taken (r0 is never less than zero)
5630     //assert(dops[i].opcode2!=0);
5631     //assert(dops[i].opcode2!=2);
5632     //assert(dops[i].opcode2!=0x10);
5633     //assert(dops[i].opcode2!=0x12);
5634   }
5635
5636   if(dops[i].ooo) {
5637     // Out of order execution (delay slot first)
5638     //printf("OOOE\n");
5639     address_generation(i+1,i_regs,regs[i].regmap_entry);
5640     ds_assemble(i+1,i_regs);
5641     int adj;
5642     uint64_t bc_unneeded=branch_regs[i].u;
5643     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5644     bc_unneeded|=1;
5645     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5646     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5647     load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5648     if(dops[i].rt1==31) {
5649       int rt,return_address;
5650       rt=get_reg(branch_regs[i].regmap,31);
5651       assem_debug("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5652       if(rt>=0) {
5653         // Save the PC even if the branch is not taken
5654         return_address=start+i*4+8;
5655         emit_movimm(return_address,rt); // PC into link register
5656         #ifdef IMM_PREFETCH
5657         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5658         #endif
5659       }
5660     }
5661     cc=get_reg(branch_regs[i].regmap,CCREG);
5662     assert(cc==HOST_CCREG);
5663     if(unconditional)
5664       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5665     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5666     assem_debug("cycle count (adj)\n");
5667     if(unconditional) {
5668       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5669       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5670         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5671         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5672         if(internal)
5673           assem_debug("branch: internal\n");
5674         else
5675           assem_debug("branch: external\n");
5676         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5677           ds_assemble_entry(i);
5678         }
5679         else {
5680           add_to_linker(out,ba[i],internal);
5681           emit_jmp(0);
5682         }
5683         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5684         if(((u_int)out)&7) emit_addnop(0);
5685         #endif
5686       }
5687     }
5688     else if(nevertaken) {
5689       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5690       void *jaddr=out;
5691       emit_jns(0);
5692       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5693     }
5694     else {
5695       void *nottaken = NULL;
5696       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5697       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5698       {
5699         assert(s1l>=0);
5700         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5701         {
5702           emit_test(s1l,s1l);
5703           if(invert){
5704             nottaken=out;
5705             emit_jns(DJT_1);
5706           }else{
5707             add_to_linker(out,ba[i],internal);
5708             emit_js(0);
5709           }
5710         }
5711         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5712         {
5713           emit_test(s1l,s1l);
5714           if(invert){
5715             nottaken=out;
5716             emit_js(DJT_1);
5717           }else{
5718             add_to_linker(out,ba[i],internal);
5719             emit_jns(0);
5720           }
5721         }
5722       }
5723
5724       if(invert) {
5725         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5726         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5727           if(adj) {
5728             emit_addimm(cc,-adj,cc);
5729             add_to_linker(out,ba[i],internal);
5730           }else{
5731             emit_addnop(13);
5732             add_to_linker(out,ba[i],internal*2);
5733           }
5734           emit_jmp(0);
5735         }else
5736         #endif
5737         {
5738           if(adj) emit_addimm(cc,-adj,cc);
5739           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5740           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5741           if(internal)
5742             assem_debug("branch: internal\n");
5743           else
5744             assem_debug("branch: external\n");
5745           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5746             ds_assemble_entry(i);
5747           }
5748           else {
5749             add_to_linker(out,ba[i],internal);
5750             emit_jmp(0);
5751           }
5752         }
5753         set_jump_target(nottaken, out);
5754       }
5755
5756       if(adj) {
5757         if(!invert) emit_addimm(cc,adj,cc);
5758       }
5759     } // (!unconditional)
5760   } // if(ooo)
5761   else
5762   {
5763     // In-order execution (branch first)
5764     //printf("IOE\n");
5765     void *nottaken = NULL;
5766     if(dops[i].rt1==31) {
5767       int rt,return_address;
5768       rt=get_reg(branch_regs[i].regmap,31);
5769       if(rt>=0) {
5770         // Save the PC even if the branch is not taken
5771         return_address=start+i*4+8;
5772         emit_movimm(return_address,rt); // PC into link register
5773         #ifdef IMM_PREFETCH
5774         emit_prefetch(hash_table_get(return_address));
5775         #endif
5776       }
5777     }
5778     if(!unconditional) {
5779       //printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
5780         assert(s1l>=0);
5781         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5782         {
5783           emit_test(s1l,s1l);
5784           nottaken=out;
5785           emit_jns(DJT_1);
5786         }
5787         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5788         {
5789           emit_test(s1l,s1l);
5790           nottaken=out;
5791           emit_js(DJT_1);
5792         }
5793     } // if(!unconditional)
5794     int adj;
5795     uint64_t ds_unneeded=branch_regs[i].u;
5796     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5797     ds_unneeded|=1;
5798     // branch taken
5799     if(!nevertaken) {
5800       //assem_debug("1:\n");
5801       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5802       // load regs
5803       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5804       address_generation(i+1,&branch_regs[i],0);
5805       if (ram_offset)
5806         load_regs(regs[i].regmap,branch_regs[i].regmap,ROREG,ROREG);
5807       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5808       ds_assemble(i+1,&branch_regs[i]);
5809       cc=get_reg(branch_regs[i].regmap,CCREG);
5810       if(cc==-1) {
5811         emit_loadreg(CCREG,cc=HOST_CCREG);
5812         // CHECK: Is the following instruction (fall thru) allocated ok?
5813       }
5814       assert(cc==HOST_CCREG);
5815       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5816       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5817       assem_debug("cycle count (adj)\n");
5818       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5819       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5820       if(internal)
5821         assem_debug("branch: internal\n");
5822       else
5823         assem_debug("branch: external\n");
5824       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5825         ds_assemble_entry(i);
5826       }
5827       else {
5828         add_to_linker(out,ba[i],internal);
5829         emit_jmp(0);
5830       }
5831     }
5832     // branch not taken
5833     if(!unconditional) {
5834       set_jump_target(nottaken, out);
5835       assem_debug("1:\n");
5836       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5837       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5838       address_generation(i+1,&branch_regs[i],0);
5839       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,CCREG);
5840       ds_assemble(i+1,&branch_regs[i]);
5841       cc=get_reg(branch_regs[i].regmap,CCREG);
5842       if (cc == -1) {
5843         // Cycle count isn't in a register, temporarily load it then write it out
5844         emit_loadreg(CCREG,HOST_CCREG);
5845         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5846         void *jaddr=out;
5847         emit_jns(0);
5848         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5849         emit_storereg(CCREG,HOST_CCREG);
5850       }
5851       else{
5852         cc=get_reg(i_regmap,CCREG);
5853         assert(cc==HOST_CCREG);
5854         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5855         void *jaddr=out;
5856         emit_jns(0);
5857         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5858       }
5859     }
5860   }
5861 }
5862
5863 static void pagespan_assemble(int i, const struct regstat *i_regs)
5864 {
5865   int s1l=get_reg(i_regs->regmap,dops[i].rs1);
5866   int s2l=get_reg(i_regs->regmap,dops[i].rs2);
5867   void *taken = NULL;
5868   void *nottaken = NULL;
5869   int unconditional=0;
5870   if(dops[i].rs1==0)
5871   {
5872     s1l=s2l;
5873     s2l=-1;
5874   }
5875   else if(dops[i].rs2==0)
5876   {
5877     s2l=-1;
5878   }
5879   int hr=0;
5880   int addr=-1,alt=-1,ntaddr=-1;
5881   if(i_regs->regmap[HOST_BTREG]<0) {addr=HOST_BTREG;}
5882   else {
5883     while(hr<HOST_REGS)
5884     {
5885       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5886          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5887          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5888       {
5889         addr=hr++;break;
5890       }
5891       hr++;
5892     }
5893   }
5894   while(hr<HOST_REGS)
5895   {
5896     if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5897        (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5898        (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5899     {
5900       alt=hr++;break;
5901     }
5902     hr++;
5903   }
5904   if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5905   {
5906     while(hr<HOST_REGS)
5907     {
5908       if(hr!=EXCLUDE_REG && hr!=HOST_CCREG && hr!=HOST_BTREG &&
5909          (i_regs->regmap[hr]&63)!=dops[i].rs1 &&
5910          (i_regs->regmap[hr]&63)!=dops[i].rs2 )
5911       {
5912         ntaddr=hr;break;
5913       }
5914       hr++;
5915     }
5916   }
5917   assert(hr<HOST_REGS);
5918   if((dops[i].opcode&0x2e)==4||dops[i].opcode==0x11) { // BEQ/BNE/BEQL/BNEL/BC1
5919     load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
5920   }
5921   emit_addimm(HOST_CCREG, ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5922   if(dops[i].opcode==2) // J
5923   {
5924     unconditional=1;
5925   }
5926   if(dops[i].opcode==3) // JAL
5927   {
5928     // TODO: mini_ht
5929     int rt=get_reg(i_regs->regmap,31);
5930     emit_movimm(start+i*4+8,rt);
5931     unconditional=1;
5932   }
5933   if(dops[i].opcode==0&&(dops[i].opcode2&0x3E)==8) // JR/JALR
5934   {
5935     emit_mov(s1l,addr);
5936     if(dops[i].opcode2==9) // JALR
5937     {
5938       int rt=get_reg(i_regs->regmap,dops[i].rt1);
5939       emit_movimm(start+i*4+8,rt);
5940     }
5941   }
5942   if((dops[i].opcode&0x3f)==4) // BEQ
5943   {
5944     if(dops[i].rs1==dops[i].rs2)
5945     {
5946       unconditional=1;
5947     }
5948     else
5949     #ifdef HAVE_CMOV_IMM
5950     if(1) {
5951       if(s2l>=0) emit_cmp(s1l,s2l);
5952       else emit_test(s1l,s1l);
5953       emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5954     }
5955     else
5956     #endif
5957     {
5958       assert(s1l>=0);
5959       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5960       if(s2l>=0) emit_cmp(s1l,s2l);
5961       else emit_test(s1l,s1l);
5962       emit_cmovne_reg(alt,addr);
5963     }
5964   }
5965   if((dops[i].opcode&0x3f)==5) // BNE
5966   {
5967     #ifdef HAVE_CMOV_IMM
5968     if(s2l>=0) emit_cmp(s1l,s2l);
5969     else emit_test(s1l,s1l);
5970     emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5971     #else
5972     assert(s1l>=0);
5973     emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5974     if(s2l>=0) emit_cmp(s1l,s2l);
5975     else emit_test(s1l,s1l);
5976     emit_cmovne_reg(alt,addr);
5977     #endif
5978   }
5979   if((dops[i].opcode&0x3f)==0x14) // BEQL
5980   {
5981     if(s2l>=0) emit_cmp(s1l,s2l);
5982     else emit_test(s1l,s1l);
5983     if(nottaken) set_jump_target(nottaken, out);
5984     nottaken=out;
5985     emit_jne(0);
5986   }
5987   if((dops[i].opcode&0x3f)==0x15) // BNEL
5988   {
5989     if(s2l>=0) emit_cmp(s1l,s2l);
5990     else emit_test(s1l,s1l);
5991     nottaken=out;
5992     emit_jeq(0);
5993     if(taken) set_jump_target(taken, out);
5994   }
5995   if((dops[i].opcode&0x3f)==6) // BLEZ
5996   {
5997     emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5998     emit_cmpimm(s1l,1);
5999     emit_cmovl_reg(alt,addr);
6000   }
6001   if((dops[i].opcode&0x3f)==7) // BGTZ
6002   {
6003     emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
6004     emit_cmpimm(s1l,1);
6005     emit_cmovl_reg(ntaddr,addr);
6006   }
6007   if((dops[i].opcode&0x3f)==0x16) // BLEZL
6008   {
6009     assert((dops[i].opcode&0x3f)!=0x16);
6010   }
6011   if((dops[i].opcode&0x3f)==0x17) // BGTZL
6012   {
6013     assert((dops[i].opcode&0x3f)!=0x17);
6014   }
6015   assert(dops[i].opcode!=1); // BLTZ/BGEZ
6016
6017   //FIXME: Check CSREG
6018   if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
6019     if((source[i]&0x30000)==0) // BC1F
6020     {
6021       emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
6022       emit_testimm(s1l,0x800000);
6023       emit_cmovne_reg(alt,addr);
6024     }
6025     if((source[i]&0x30000)==0x10000) // BC1T
6026     {
6027       emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
6028       emit_testimm(s1l,0x800000);
6029       emit_cmovne_reg(alt,addr);
6030     }
6031     if((source[i]&0x30000)==0x20000) // BC1FL
6032     {
6033       emit_testimm(s1l,0x800000);
6034       nottaken=out;
6035       emit_jne(0);
6036     }
6037     if((source[i]&0x30000)==0x30000) // BC1TL
6038     {
6039       emit_testimm(s1l,0x800000);
6040       nottaken=out;
6041       emit_jeq(0);
6042     }
6043   }
6044
6045   assert(i_regs->regmap[HOST_CCREG]==CCREG);
6046   wb_dirtys(regs[i].regmap,regs[i].dirty);
6047   if(unconditional)
6048   {
6049     emit_movimm(ba[i],HOST_BTREG);
6050   }
6051   else if(addr!=HOST_BTREG)
6052   {
6053     emit_mov(addr,HOST_BTREG);
6054   }
6055   void *branch_addr=out;
6056   emit_jmp(0);
6057   int target_addr=start+i*4+5;
6058   void *stub=out;
6059   void *compiled_target_addr=check_addr(target_addr);
6060   emit_extjump_ds(branch_addr, target_addr);
6061   if(compiled_target_addr) {
6062     set_jump_target(branch_addr, compiled_target_addr);
6063     add_jump_out(target_addr,stub);
6064   }
6065   else set_jump_target(branch_addr, stub);
6066 }
6067
6068 // Assemble the delay slot for the above
6069 static void pagespan_ds()
6070 {
6071   assem_debug("initial delay slot:\n");
6072   u_int vaddr=start+1;
6073   u_int page=get_page(vaddr);
6074   u_int vpage=get_vpage(vaddr);
6075   ll_add(jump_dirty+vpage,vaddr,(void *)out);
6076   do_dirty_stub_ds(slen*4);
6077   ll_add(jump_in+page,vaddr,(void *)out);
6078   assert(regs[0].regmap_entry[HOST_CCREG]==CCREG);
6079   if(regs[0].regmap[HOST_CCREG]!=CCREG)
6080     wb_register(CCREG,regs[0].regmap_entry,regs[0].wasdirty);
6081   if(regs[0].regmap[HOST_BTREG]!=BTREG)
6082     emit_writeword(HOST_BTREG,&branch_target);
6083   load_regs(regs[0].regmap_entry,regs[0].regmap,dops[0].rs1,dops[0].rs2);
6084   address_generation(0,&regs[0],regs[0].regmap_entry);
6085   if (ram_offset && (dops[0].is_load || dops[0].is_store))
6086     load_regs(regs[0].regmap_entry,regs[0].regmap,ROREG,ROREG);
6087   if (dops[0].is_store)
6088     load_regs(regs[0].regmap_entry,regs[0].regmap,INVCP,INVCP);
6089   is_delayslot=0;
6090   switch (dops[0].itype) {
6091     case SYSCALL:
6092     case HLECALL:
6093     case INTCALL:
6094     case SPAN:
6095     case UJUMP:
6096     case RJUMP:
6097     case CJUMP:
6098     case SJUMP:
6099       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
6100       break;
6101     default:
6102       assemble(0, &regs[0], 0);
6103   }
6104   int btaddr=get_reg(regs[0].regmap,BTREG);
6105   if(btaddr<0) {
6106     btaddr=get_reg(regs[0].regmap,-1);
6107     emit_readword(&branch_target,btaddr);
6108   }
6109   assert(btaddr!=HOST_CCREG);
6110   if(regs[0].regmap[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
6111 #ifdef HOST_IMM8
6112   host_tempreg_acquire();
6113   emit_movimm(start+4,HOST_TEMPREG);
6114   emit_cmp(btaddr,HOST_TEMPREG);
6115   host_tempreg_release();
6116 #else
6117   emit_cmpimm(btaddr,start+4);
6118 #endif
6119   void *branch = out;
6120   emit_jeq(0);
6121   store_regs_bt(regs[0].regmap,regs[0].dirty,-1);
6122   do_jump_vaddr(btaddr);
6123   set_jump_target(branch, out);
6124   store_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6125   load_regs_bt(regs[0].regmap,regs[0].dirty,start+4);
6126 }
6127
6128 // Basic liveness analysis for MIPS registers
6129 void unneeded_registers(int istart,int iend,int r)
6130 {
6131   int i;
6132   uint64_t u,gte_u,b,gte_b;
6133   uint64_t temp_u,temp_gte_u=0;
6134   uint64_t gte_u_unknown=0;
6135   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
6136     gte_u_unknown=~0ll;
6137   if(iend==slen-1) {
6138     u=1;
6139     gte_u=gte_u_unknown;
6140   }else{
6141     //u=unneeded_reg[iend+1];
6142     u=1;
6143     gte_u=gte_unneeded[iend+1];
6144   }
6145
6146   for (i=iend;i>=istart;i--)
6147   {
6148     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
6149     if(dops[i].is_jump)
6150     {
6151       // If subroutine call, flag return address as a possible branch target
6152       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
6153
6154       if(ba[i]<start || ba[i]>=(start+slen*4))
6155       {
6156         // Branch out of this block, flush all regs
6157         u=1;
6158         gte_u=gte_u_unknown;
6159         branch_unneeded_reg[i]=u;
6160         // Merge in delay slot
6161         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6162         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6163         u|=1;
6164         gte_u|=gte_rt[i+1];
6165         gte_u&=~gte_rs[i+1];
6166       }
6167       else
6168       {
6169         // Internal branch, flag target
6170         dops[(ba[i]-start)>>2].bt=1;
6171         if(ba[i]<=start+i*4) {
6172           // Backward branch
6173           if(dops[i].is_ujump)
6174           {
6175             // Unconditional branch
6176             temp_u=1;
6177             temp_gte_u=0;
6178           } else {
6179             // Conditional branch (not taken case)
6180             temp_u=unneeded_reg[i+2];
6181             temp_gte_u&=gte_unneeded[i+2];
6182           }
6183           // Merge in delay slot
6184           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6185           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6186           temp_u|=1;
6187           temp_gte_u|=gte_rt[i+1];
6188           temp_gte_u&=~gte_rs[i+1];
6189           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
6190           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
6191           temp_u|=1;
6192           temp_gte_u|=gte_rt[i];
6193           temp_gte_u&=~gte_rs[i];
6194           unneeded_reg[i]=temp_u;
6195           gte_unneeded[i]=temp_gte_u;
6196           // Only go three levels deep.  This recursion can take an
6197           // excessive amount of time if there are a lot of nested loops.
6198           if(r<2) {
6199             unneeded_registers((ba[i]-start)>>2,i-1,r+1);
6200           }else{
6201             unneeded_reg[(ba[i]-start)>>2]=1;
6202             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
6203           }
6204         } /*else*/ if(1) {
6205           if (dops[i].is_ujump)
6206           {
6207             // Unconditional branch
6208             u=unneeded_reg[(ba[i]-start)>>2];
6209             gte_u=gte_unneeded[(ba[i]-start)>>2];
6210             branch_unneeded_reg[i]=u;
6211             // Merge in delay slot
6212             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6213             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6214             u|=1;
6215             gte_u|=gte_rt[i+1];
6216             gte_u&=~gte_rs[i+1];
6217           } else {
6218             // Conditional branch
6219             b=unneeded_reg[(ba[i]-start)>>2];
6220             gte_b=gte_unneeded[(ba[i]-start)>>2];
6221             branch_unneeded_reg[i]=b;
6222             // Branch delay slot
6223             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
6224             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
6225             b|=1;
6226             gte_b|=gte_rt[i+1];
6227             gte_b&=~gte_rs[i+1];
6228             u&=b;
6229             gte_u&=gte_b;
6230             if(i<slen-1) {
6231               branch_unneeded_reg[i]&=unneeded_reg[i+2];
6232             } else {
6233               branch_unneeded_reg[i]=1;
6234             }
6235           }
6236         }
6237       }
6238     }
6239     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6240     {
6241       // SYSCALL instruction (software interrupt)
6242       u=1;
6243     }
6244     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6245     {
6246       // ERET instruction (return from interrupt)
6247       u=1;
6248     }
6249     //u=1; // DEBUG
6250     // Written registers are unneeded
6251     u|=1LL<<dops[i].rt1;
6252     u|=1LL<<dops[i].rt2;
6253     gte_u|=gte_rt[i];
6254     // Accessed registers are needed
6255     u&=~(1LL<<dops[i].rs1);
6256     u&=~(1LL<<dops[i].rs2);
6257     gte_u&=~gte_rs[i];
6258     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
6259       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
6260     // Source-target dependencies
6261     // R0 is always unneeded
6262     u|=1;
6263     // Save it
6264     unneeded_reg[i]=u;
6265     gte_unneeded[i]=gte_u;
6266     /*
6267     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
6268     printf("U:");
6269     int r;
6270     for(r=1;r<=CCREG;r++) {
6271       if((unneeded_reg[i]>>r)&1) {
6272         if(r==HIREG) printf(" HI");
6273         else if(r==LOREG) printf(" LO");
6274         else printf(" r%d",r);
6275       }
6276     }
6277     printf("\n");
6278     */
6279   }
6280 }
6281
6282 // Write back dirty registers as soon as we will no longer modify them,
6283 // so that we don't end up with lots of writes at the branches.
6284 void clean_registers(int istart,int iend,int wr)
6285 {
6286   int i;
6287   int r;
6288   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
6289   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
6290   if(iend==slen-1) {
6291     will_dirty_i=will_dirty_next=0;
6292     wont_dirty_i=wont_dirty_next=0;
6293   }else{
6294     will_dirty_i=will_dirty_next=will_dirty[iend+1];
6295     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
6296   }
6297   for (i=iend;i>=istart;i--)
6298   {
6299     if(dops[i].is_jump)
6300     {
6301       if(ba[i]<start || ba[i]>=(start+slen*4))
6302       {
6303         // Branch out of this block, flush all regs
6304         if (dops[i].is_ujump)
6305         {
6306           // Unconditional branch
6307           will_dirty_i=0;
6308           wont_dirty_i=0;
6309           // Merge in delay slot (will dirty)
6310           for(r=0;r<HOST_REGS;r++) {
6311             if(r!=EXCLUDE_REG) {
6312               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6313               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6314               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6315               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6316               if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6317               if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6318               if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6319               if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6320               if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6321               if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6322               if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6323               if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6324               if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6325               if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6326             }
6327           }
6328         }
6329         else
6330         {
6331           // Conditional branch
6332           will_dirty_i=0;
6333           wont_dirty_i=wont_dirty_next;
6334           // Merge in delay slot (will dirty)
6335           for(r=0;r<HOST_REGS;r++) {
6336             if(r!=EXCLUDE_REG) {
6337               if (1) { // !dops[i].likely) {
6338                 // Might not dirty if likely branch is not taken
6339                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6340                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6341                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6342                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6343                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6344                 if(branch_regs[i].regmap[r]==0) will_dirty_i&=~(1<<r);
6345                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6346                 //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6347                 //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6348                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6349                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6350                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6351                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6352                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6353               }
6354             }
6355           }
6356         }
6357         // Merge in delay slot (wont dirty)
6358         for(r=0;r<HOST_REGS;r++) {
6359           if(r!=EXCLUDE_REG) {
6360             if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6361             if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6362             if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6363             if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6364             if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6365             if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6366             if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6367             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6368             if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6369             if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6370           }
6371         }
6372         if(wr) {
6373           #ifndef DESTRUCTIVE_WRITEBACK
6374           branch_regs[i].dirty&=wont_dirty_i;
6375           #endif
6376           branch_regs[i].dirty|=will_dirty_i;
6377         }
6378       }
6379       else
6380       {
6381         // Internal branch
6382         if(ba[i]<=start+i*4) {
6383           // Backward branch
6384           if (dops[i].is_ujump)
6385           {
6386             // Unconditional branch
6387             temp_will_dirty=0;
6388             temp_wont_dirty=0;
6389             // Merge in delay slot (will dirty)
6390             for(r=0;r<HOST_REGS;r++) {
6391               if(r!=EXCLUDE_REG) {
6392                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6393                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6394                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6395                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6396                 if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6397                 if(branch_regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6398                 if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6399                 if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6400                 if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6401                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6402                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6403                 if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6404                 if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6405                 if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6406               }
6407             }
6408           } else {
6409             // Conditional branch (not taken case)
6410             temp_will_dirty=will_dirty_next;
6411             temp_wont_dirty=wont_dirty_next;
6412             // Merge in delay slot (will dirty)
6413             for(r=0;r<HOST_REGS;r++) {
6414               if(r!=EXCLUDE_REG) {
6415                 if (1) { // !dops[i].likely) {
6416                   // Will not dirty if likely branch is not taken
6417                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6418                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6419                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6420                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6421                   if((branch_regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6422                   if(branch_regs[i].regmap[r]==0) temp_will_dirty&=~(1<<r);
6423                   if(branch_regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6424                   //if((regs[i].regmap[r]&63)==dops[i].rt1) temp_will_dirty|=1<<r;
6425                   //if((regs[i].regmap[r]&63)==dops[i].rt2) temp_will_dirty|=1<<r;
6426                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_will_dirty|=1<<r;
6427                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_will_dirty|=1<<r;
6428                   if((regs[i].regmap[r]&63)>33) temp_will_dirty&=~(1<<r);
6429                   if(regs[i].regmap[r]<=0) temp_will_dirty&=~(1<<r);
6430                   if(regs[i].regmap[r]==CCREG) temp_will_dirty|=1<<r;
6431                 }
6432               }
6433             }
6434           }
6435           // Merge in delay slot (wont dirty)
6436           for(r=0;r<HOST_REGS;r++) {
6437             if(r!=EXCLUDE_REG) {
6438               if((regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6439               if((regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6440               if((regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6441               if((regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6442               if(regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6443               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) temp_wont_dirty|=1<<r;
6444               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) temp_wont_dirty|=1<<r;
6445               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) temp_wont_dirty|=1<<r;
6446               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) temp_wont_dirty|=1<<r;
6447               if(branch_regs[i].regmap[r]==CCREG) temp_wont_dirty|=1<<r;
6448             }
6449           }
6450           // Deal with changed mappings
6451           if(i<iend) {
6452             for(r=0;r<HOST_REGS;r++) {
6453               if(r!=EXCLUDE_REG) {
6454                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
6455                   temp_will_dirty&=~(1<<r);
6456                   temp_wont_dirty&=~(1<<r);
6457                   if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6458                     temp_will_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6459                     temp_wont_dirty|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6460                   } else {
6461                     temp_will_dirty|=1<<r;
6462                     temp_wont_dirty|=1<<r;
6463                   }
6464                 }
6465               }
6466             }
6467           }
6468           if(wr) {
6469             will_dirty[i]=temp_will_dirty;
6470             wont_dirty[i]=temp_wont_dirty;
6471             clean_registers((ba[i]-start)>>2,i-1,0);
6472           }else{
6473             // Limit recursion.  It can take an excessive amount
6474             // of time if there are a lot of nested loops.
6475             will_dirty[(ba[i]-start)>>2]=0;
6476             wont_dirty[(ba[i]-start)>>2]=-1;
6477           }
6478         }
6479         /*else*/ if(1)
6480         {
6481           if (dops[i].is_ujump)
6482           {
6483             // Unconditional branch
6484             will_dirty_i=0;
6485             wont_dirty_i=0;
6486           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6487             for(r=0;r<HOST_REGS;r++) {
6488               if(r!=EXCLUDE_REG) {
6489                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6490                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
6491                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6492                 }
6493                 if(branch_regs[i].regmap[r]>=0) {
6494                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6495                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(branch_regs[i].regmap[r]&63))&1)<<r;
6496                 }
6497               }
6498             }
6499           //}
6500             // Merge in delay slot
6501             for(r=0;r<HOST_REGS;r++) {
6502               if(r!=EXCLUDE_REG) {
6503                 if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6504                 if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6505                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6506                 if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6507                 if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6508                 if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6509                 if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6510                 if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6511                 if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6512                 if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6513                 if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6514                 if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6515                 if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6516                 if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6517               }
6518             }
6519           } else {
6520             // Conditional branch
6521             will_dirty_i=will_dirty_next;
6522             wont_dirty_i=wont_dirty_next;
6523           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
6524             for(r=0;r<HOST_REGS;r++) {
6525               if(r!=EXCLUDE_REG) {
6526                 signed char target_reg=branch_regs[i].regmap[r];
6527                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
6528                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
6529                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
6530                 }
6531                 else if(target_reg>=0) {
6532                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6533                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>(target_reg&63))&1)<<r;
6534                 }
6535               }
6536             }
6537           //}
6538             // Merge in delay slot
6539             for(r=0;r<HOST_REGS;r++) {
6540               if(r!=EXCLUDE_REG) {
6541                 if (1) { // !dops[i].likely) {
6542                   // Might not dirty if likely branch is not taken
6543                   if((branch_regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6544                   if((branch_regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6545                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6546                   if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6547                   if((branch_regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6548                   if(branch_regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6549                   if(branch_regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6550                   //if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6551                   //if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6552                   if((regs[i].regmap[r]&63)==dops[i+1].rt1) will_dirty_i|=1<<r;
6553                   if((regs[i].regmap[r]&63)==dops[i+1].rt2) will_dirty_i|=1<<r;
6554                   if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6555                   if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6556                   if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6557                 }
6558               }
6559             }
6560           }
6561           // Merge in delay slot (won't dirty)
6562           for(r=0;r<HOST_REGS;r++) {
6563             if(r!=EXCLUDE_REG) {
6564               if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6565               if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6566               if((regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6567               if((regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6568               if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6569               if((branch_regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6570               if((branch_regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6571               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt1) wont_dirty_i|=1<<r;
6572               if((branch_regs[i].regmap[r]&63)==dops[i+1].rt2) wont_dirty_i|=1<<r;
6573               if(branch_regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6574             }
6575           }
6576           if(wr) {
6577             #ifndef DESTRUCTIVE_WRITEBACK
6578             branch_regs[i].dirty&=wont_dirty_i;
6579             #endif
6580             branch_regs[i].dirty|=will_dirty_i;
6581           }
6582         }
6583       }
6584     }
6585     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
6586     {
6587       // SYSCALL instruction (software interrupt)
6588       will_dirty_i=0;
6589       wont_dirty_i=0;
6590     }
6591     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
6592     {
6593       // ERET instruction (return from interrupt)
6594       will_dirty_i=0;
6595       wont_dirty_i=0;
6596     }
6597     will_dirty_next=will_dirty_i;
6598     wont_dirty_next=wont_dirty_i;
6599     for(r=0;r<HOST_REGS;r++) {
6600       if(r!=EXCLUDE_REG) {
6601         if((regs[i].regmap[r]&63)==dops[i].rt1) will_dirty_i|=1<<r;
6602         if((regs[i].regmap[r]&63)==dops[i].rt2) will_dirty_i|=1<<r;
6603         if((regs[i].regmap[r]&63)>33) will_dirty_i&=~(1<<r);
6604         if(regs[i].regmap[r]<=0) will_dirty_i&=~(1<<r);
6605         if(regs[i].regmap[r]==CCREG) will_dirty_i|=1<<r;
6606         if((regs[i].regmap[r]&63)==dops[i].rt1) wont_dirty_i|=1<<r;
6607         if((regs[i].regmap[r]&63)==dops[i].rt2) wont_dirty_i|=1<<r;
6608         if(regs[i].regmap[r]==CCREG) wont_dirty_i|=1<<r;
6609         if(i>istart) {
6610           if (!dops[i].is_jump)
6611           {
6612             // Don't store a register immediately after writing it,
6613             // may prevent dual-issue.
6614             if((regs[i].regmap[r]&63)==dops[i-1].rt1) wont_dirty_i|=1<<r;
6615             if((regs[i].regmap[r]&63)==dops[i-1].rt2) wont_dirty_i|=1<<r;
6616           }
6617         }
6618       }
6619     }
6620     // Save it
6621     will_dirty[i]=will_dirty_i;
6622     wont_dirty[i]=wont_dirty_i;
6623     // Mark registers that won't be dirtied as not dirty
6624     if(wr) {
6625         regs[i].dirty|=will_dirty_i;
6626         #ifndef DESTRUCTIVE_WRITEBACK
6627         regs[i].dirty&=wont_dirty_i;
6628         if(dops[i].is_jump)
6629         {
6630           if (i < iend-1 && !dops[i].is_ujump) {
6631             for(r=0;r<HOST_REGS;r++) {
6632               if(r!=EXCLUDE_REG) {
6633                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
6634                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
6635                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6636               }
6637             }
6638           }
6639         }
6640         else
6641         {
6642           if(i<iend) {
6643             for(r=0;r<HOST_REGS;r++) {
6644               if(r!=EXCLUDE_REG) {
6645                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
6646                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
6647                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
6648               }
6649             }
6650           }
6651         }
6652         #endif
6653       //}
6654     }
6655     // Deal with changed mappings
6656     temp_will_dirty=will_dirty_i;
6657     temp_wont_dirty=wont_dirty_i;
6658     for(r=0;r<HOST_REGS;r++) {
6659       if(r!=EXCLUDE_REG) {
6660         int nr;
6661         if(regs[i].regmap[r]==regmap_pre[i][r]) {
6662           if(wr) {
6663             #ifndef DESTRUCTIVE_WRITEBACK
6664             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6665             #endif
6666             regs[i].wasdirty|=will_dirty_i&(1<<r);
6667           }
6668         }
6669         else if(regmap_pre[i][r]>=0&&(nr=get_reg(regs[i].regmap,regmap_pre[i][r]))>=0) {
6670           // Register moved to a different register
6671           will_dirty_i&=~(1<<r);
6672           wont_dirty_i&=~(1<<r);
6673           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
6674           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
6675           if(wr) {
6676             #ifndef DESTRUCTIVE_WRITEBACK
6677             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
6678             #endif
6679             regs[i].wasdirty|=will_dirty_i&(1<<r);
6680           }
6681         }
6682         else {
6683           will_dirty_i&=~(1<<r);
6684           wont_dirty_i&=~(1<<r);
6685           if((regmap_pre[i][r]&63)>0 && (regmap_pre[i][r]&63)<34) {
6686             will_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6687             wont_dirty_i|=((unneeded_reg[i]>>(regmap_pre[i][r]&63))&1)<<r;
6688           } else {
6689             wont_dirty_i|=1<<r;
6690             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
6691           }
6692         }
6693       }
6694     }
6695   }
6696 }
6697
6698 #ifdef DISASM
6699   /* disassembly */
6700 void disassemble_inst(int i)
6701 {
6702     if (dops[i].bt) printf("*"); else printf(" ");
6703     switch(dops[i].itype) {
6704       case UJUMP:
6705         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6706       case CJUMP:
6707         printf (" %x: %s r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,i?start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14):*ba);break;
6708       case SJUMP:
6709         printf (" %x: %s r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14));break;
6710       case RJUMP:
6711         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6712           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6713         else
6714           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6715         break;
6716       case SPAN:
6717         printf (" %x: %s (pagespan) r%d,r%d,%8x\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2,ba[i]);break;
6718       case IMM16:
6719         if(dops[i].opcode==0xf) //LUI
6720           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6721         else
6722           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6723         break;
6724       case LOAD:
6725       case LOADLR:
6726         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6727         break;
6728       case STORE:
6729       case STORELR:
6730         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6731         break;
6732       case ALU:
6733       case SHIFT:
6734         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6735         break;
6736       case MULTDIV:
6737         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6738         break;
6739       case SHIFTIMM:
6740         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6741         break;
6742       case MOV:
6743         if((dops[i].opcode2&0x1d)==0x10)
6744           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6745         else if((dops[i].opcode2&0x1d)==0x11)
6746           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6747         else
6748           printf (" %x: %s\n",start+i*4,insn[i]);
6749         break;
6750       case COP0:
6751         if(dops[i].opcode2==0)
6752           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6753         else if(dops[i].opcode2==4)
6754           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6755         else printf (" %x: %s\n",start+i*4,insn[i]);
6756         break;
6757       case COP1:
6758         if(dops[i].opcode2<3)
6759           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6760         else if(dops[i].opcode2>3)
6761           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6762         else printf (" %x: %s\n",start+i*4,insn[i]);
6763         break;
6764       case COP2:
6765         if(dops[i].opcode2<3)
6766           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6767         else if(dops[i].opcode2>3)
6768           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6769         else printf (" %x: %s\n",start+i*4,insn[i]);
6770         break;
6771       case C1LS:
6772         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6773         break;
6774       case C2LS:
6775         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6776         break;
6777       case INTCALL:
6778         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6779         break;
6780       default:
6781         //printf (" %s %8x\n",insn[i],source[i]);
6782         printf (" %x: %s\n",start+i*4,insn[i]);
6783     }
6784 }
6785 #else
6786 static void disassemble_inst(int i) {}
6787 #endif // DISASM
6788
6789 #define DRC_TEST_VAL 0x74657374
6790
6791 static void new_dynarec_test(void)
6792 {
6793   int (*testfunc)(void);
6794   void *beginning;
6795   int ret[2];
6796   size_t i;
6797
6798   // check structure linkage
6799   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6800   {
6801     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6802   }
6803
6804   SysPrintf("testing if we can run recompiled code @%p...\n", out);
6805   ((volatile u_int *)out)[0]++; // make cache dirty
6806
6807   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6808     out = ndrc->translation_cache;
6809     beginning = start_block();
6810     emit_movimm(DRC_TEST_VAL + i, 0); // test
6811     emit_ret();
6812     literal_pool(0);
6813     end_block(beginning);
6814     testfunc = beginning;
6815     ret[i] = testfunc();
6816   }
6817
6818   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6819     SysPrintf("test passed.\n");
6820   else
6821     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6822   out = ndrc->translation_cache;
6823 }
6824
6825 // clear the state completely, instead of just marking
6826 // things invalid like invalidate_all_pages() does
6827 void new_dynarec_clear_full(void)
6828 {
6829   int n;
6830   out = ndrc->translation_cache;
6831   memset(invalid_code,1,sizeof(invalid_code));
6832   memset(hash_table,0xff,sizeof(hash_table));
6833   memset(mini_ht,-1,sizeof(mini_ht));
6834   memset(restore_candidate,0,sizeof(restore_candidate));
6835   memset(shadow,0,sizeof(shadow));
6836   copy=shadow;
6837   expirep=16384; // Expiry pointer, +2 blocks
6838   pending_exception=0;
6839   literalcount=0;
6840   stop_after_jal=0;
6841   inv_code_start=inv_code_end=~0;
6842   hack_addr=0;
6843   f1_hack=0;
6844   // TLB
6845   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6846   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6847   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6848
6849   cycle_multiplier_old = cycle_multiplier;
6850   new_dynarec_hacks_old = new_dynarec_hacks;
6851 }
6852
6853 void new_dynarec_init(void)
6854 {
6855   SysPrintf("Init new dynarec, ndrc size %x\n", (int)sizeof(*ndrc));
6856
6857 #ifdef _3DS
6858   check_rosalina();
6859 #endif
6860 #ifdef BASE_ADDR_DYNAMIC
6861   #ifdef VITA
6862   sceBlock = getVMBlock(); //sceKernelAllocMemBlockForVM("code", sizeof(*ndrc));
6863   if (sceBlock <= 0)
6864     SysPrintf("sceKernelAllocMemBlockForVM failed: %x\n", sceBlock);
6865   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6866   if (ret < 0)
6867     SysPrintf("sceKernelGetMemBlockBase failed: %x\n", ret);
6868   sceKernelOpenVMDomain();
6869   sceClibPrintf("translation_cache = 0x%08lx\n ", (long)ndrc->translation_cache);
6870   #elif defined(_MSC_VER)
6871   ndrc = VirtualAlloc(NULL, sizeof(*ndrc), MEM_COMMIT | MEM_RESERVE,
6872     PAGE_EXECUTE_READWRITE);
6873   #else
6874   uintptr_t desired_addr = 0;
6875   #ifdef __ELF__
6876   extern char _end;
6877   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6878   #endif
6879   ndrc = mmap((void *)desired_addr, sizeof(*ndrc),
6880             PROT_READ | PROT_WRITE | PROT_EXEC,
6881             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
6882   if (ndrc == MAP_FAILED) {
6883     SysPrintf("mmap() failed: %s\n", strerror(errno));
6884     abort();
6885   }
6886   #endif
6887 #else
6888   #ifndef NO_WRITE_EXEC
6889   // not all systems allow execute in data segment by default
6890   // size must be 4K aligned for 3DS?
6891   if (mprotect(ndrc, sizeof(*ndrc),
6892                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6893     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6894   #endif
6895 #endif
6896   out = ndrc->translation_cache;
6897   cycle_multiplier=200;
6898   new_dynarec_clear_full();
6899 #ifdef HOST_IMM8
6900   // Copy this into local area so we don't have to put it in every literal pool
6901   invc_ptr=invalid_code;
6902 #endif
6903   arch_init();
6904   new_dynarec_test();
6905   ram_offset=(uintptr_t)rdram-0x80000000;
6906   if (ram_offset!=0)
6907     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6908 }
6909
6910 void new_dynarec_cleanup(void)
6911 {
6912   int n;
6913 #ifdef BASE_ADDR_DYNAMIC
6914   #ifdef VITA
6915   // sceBlock is managed by retroarch's bootstrap code
6916   //sceKernelFreeMemBlock(sceBlock);
6917   //sceBlock = -1;
6918   #else
6919   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6920     SysPrintf("munmap() failed\n");
6921   #endif
6922 #endif
6923   for(n=0;n<4096;n++) ll_clear(jump_in+n);
6924   for(n=0;n<4096;n++) ll_clear(jump_out+n);
6925   for(n=0;n<4096;n++) ll_clear(jump_dirty+n);
6926   #ifdef ROM_COPY
6927   if (munmap (ROM_COPY, 67108864) < 0) {SysPrintf("munmap() failed\n");}
6928   #endif
6929 }
6930
6931 static u_int *get_source_start(u_int addr, u_int *limit)
6932 {
6933   if (addr < 0x00200000 ||
6934     (0xa0000000 <= addr && addr < 0xa0200000))
6935   {
6936     // used for BIOS calls mostly?
6937     *limit = (addr&0xa0000000)|0x00200000;
6938     return (u_int *)(rdram + (addr&0x1fffff));
6939   }
6940   else if (!Config.HLE && (
6941     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6942     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6943   {
6944     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6945     // but timings in PCSX are too tied to the interpreter's BIAS
6946     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6947       cycle_multiplier_active = 200;
6948
6949     *limit = (addr & 0xfff00000) | 0x80000;
6950     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6951   }
6952   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6953     *limit = (addr & 0x80600000) + 0x00200000;
6954     return (u_int *)(rdram + (addr&0x1fffff));
6955   }
6956   return NULL;
6957 }
6958
6959 static u_int scan_for_ret(u_int addr)
6960 {
6961   u_int limit = 0;
6962   u_int *mem;
6963
6964   mem = get_source_start(addr, &limit);
6965   if (mem == NULL)
6966     return addr;
6967
6968   if (limit > addr + 0x1000)
6969     limit = addr + 0x1000;
6970   for (; addr < limit; addr += 4, mem++) {
6971     if (*mem == 0x03e00008) // jr $ra
6972       return addr + 8;
6973   }
6974   return addr;
6975 }
6976
6977 struct savestate_block {
6978   uint32_t addr;
6979   uint32_t regflags;
6980 };
6981
6982 static int addr_cmp(const void *p1_, const void *p2_)
6983 {
6984   const struct savestate_block *p1 = p1_, *p2 = p2_;
6985   return p1->addr - p2->addr;
6986 }
6987
6988 int new_dynarec_save_blocks(void *save, int size)
6989 {
6990   struct savestate_block *blocks = save;
6991   int maxcount = size / sizeof(blocks[0]);
6992   struct savestate_block tmp_blocks[1024];
6993   struct ll_entry *head;
6994   int p, s, d, o, bcnt;
6995   u_int addr;
6996
6997   o = 0;
6998   for (p = 0; p < ARRAY_SIZE(jump_in); p++) {
6999     bcnt = 0;
7000     for (head = jump_in[p]; head != NULL; head = head->next) {
7001       tmp_blocks[bcnt].addr = head->vaddr;
7002       tmp_blocks[bcnt].regflags = head->reg_sv_flags;
7003       bcnt++;
7004     }
7005     if (bcnt < 1)
7006       continue;
7007     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
7008
7009     addr = tmp_blocks[0].addr;
7010     for (s = d = 0; s < bcnt; s++) {
7011       if (tmp_blocks[s].addr < addr)
7012         continue;
7013       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
7014         tmp_blocks[d++] = tmp_blocks[s];
7015       addr = scan_for_ret(tmp_blocks[s].addr);
7016     }
7017
7018     if (o + d > maxcount)
7019       d = maxcount - o;
7020     memcpy(&blocks[o], tmp_blocks, d * sizeof(blocks[0]));
7021     o += d;
7022   }
7023
7024   return o * sizeof(blocks[0]);
7025 }
7026
7027 void new_dynarec_load_blocks(const void *save, int size)
7028 {
7029   const struct savestate_block *blocks = save;
7030   int count = size / sizeof(blocks[0]);
7031   u_int regs_save[32];
7032   uint32_t f;
7033   int i, b;
7034
7035   get_addr(psxRegs.pc);
7036
7037   // change GPRs for speculation to at least partially work..
7038   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
7039   for (i = 1; i < 32; i++)
7040     psxRegs.GPR.r[i] = 0x80000000;
7041
7042   for (b = 0; b < count; b++) {
7043     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7044       if (f & 1)
7045         psxRegs.GPR.r[i] = 0x1f800000;
7046     }
7047
7048     get_addr(blocks[b].addr);
7049
7050     for (f = blocks[b].regflags, i = 0; f; f >>= 1, i++) {
7051       if (f & 1)
7052         psxRegs.GPR.r[i] = 0x80000000;
7053     }
7054   }
7055
7056   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
7057 }
7058
7059 static int apply_hacks(void)
7060 {
7061   int i;
7062   if (HACK_ENABLED(NDHACK_NO_COMPAT_HACKS))
7063     return 0;
7064   /* special hack(s) */
7065   for (i = 0; i < slen - 4; i++)
7066   {
7067     // lui a4, 0xf200; jal <rcnt_read>; addu a0, 2; slti v0, 28224
7068     if (source[i] == 0x3c04f200 && dops[i+1].itype == UJUMP
7069         && source[i+2] == 0x34840002 && dops[i+3].opcode == 0x0a
7070         && imm[i+3] == 0x6e40 && dops[i+3].rs1 == 2)
7071     {
7072       SysPrintf("PE2 hack @%08x\n", start + (i+3)*4);
7073       dops[i + 3].itype = NOP;
7074     }
7075   }
7076   i = slen;
7077   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
7078       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
7079       && dops[i-7].itype == STORE)
7080   {
7081     i = i-8;
7082     if (dops[i].itype == IMM16)
7083       i--;
7084     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
7085     if (dops[i].itype == STORELR && dops[i].rs1 == 6
7086       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
7087     {
7088       SysPrintf("F1 hack from %08x, old dst %08x\n", start, hack_addr);
7089       f1_hack = 1;
7090       return 1;
7091     }
7092   }
7093   return 0;
7094 }
7095
7096 int new_recompile_block(u_int addr)
7097 {
7098   u_int pagelimit = 0;
7099   u_int state_rflags = 0;
7100   int i;
7101
7102   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
7103   //printf("TRACE: count=%d next=%d (compile %x)\n",Count,next_interupt,addr);
7104   //if(debug)
7105   //printf("fpu mapping=%x enabled=%x\n",(Status & 0x04000000)>>26,(Status & 0x20000000)>>29);
7106
7107   // this is just for speculation
7108   for (i = 1; i < 32; i++) {
7109     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
7110       state_rflags |= 1 << i;
7111   }
7112
7113   start = (u_int)addr&~3;
7114   //assert(((u_int)addr&1)==0); // start-in-delay-slot flag
7115   new_dynarec_did_compile=1;
7116   if (Config.HLE && start == 0x80001000) // hlecall
7117   {
7118     // XXX: is this enough? Maybe check hleSoftCall?
7119     void *beginning=start_block();
7120     u_int page=get_page(start);
7121
7122     invalid_code[start>>12]=0;
7123     emit_movimm(start,0);
7124     emit_writeword(0,&pcaddr);
7125     emit_far_jump(new_dyna_leave);
7126     literal_pool(0);
7127     end_block(beginning);
7128     ll_add_flags(jump_in+page,start,state_rflags,(void *)beginning);
7129     return 0;
7130   }
7131   else if (f1_hack && hack_addr == 0) {
7132     void *beginning = start_block();
7133     u_int page = get_page(start);
7134     emit_movimm(start, 0);
7135     emit_writeword(0, &hack_addr);
7136     emit_readword(&psxRegs.GPR.n.sp, 0);
7137     emit_readptr(&mem_rtab, 1);
7138     emit_shrimm(0, 12, 2);
7139     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
7140     emit_addimm(0, 0x18, 0);
7141     emit_adds_ptr(1, 1, 1);
7142     emit_ldr_dualindexed(1, 0, 0);
7143     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
7144     emit_far_call(get_addr_ht);
7145     emit_jmpreg(0); // jr k0
7146     literal_pool(0);
7147     end_block(beginning);
7148
7149     ll_add_flags(jump_in + page, start, state_rflags, beginning);
7150     SysPrintf("F1 hack to   %08x\n", start);
7151     return 0;
7152   }
7153
7154   cycle_multiplier_active = cycle_multiplier_override && cycle_multiplier == CYCLE_MULT_DEFAULT
7155     ? cycle_multiplier_override : cycle_multiplier;
7156
7157   source = get_source_start(start, &pagelimit);
7158   if (source == NULL) {
7159     SysPrintf("Compile at bogus memory address: %08x\n", addr);
7160     abort();
7161   }
7162
7163   /* Pass 1: disassemble */
7164   /* Pass 2: register dependencies, branch targets */
7165   /* Pass 3: register allocation */
7166   /* Pass 4: branch dependencies */
7167   /* Pass 5: pre-alloc */
7168   /* Pass 6: optimize clean/dirty state */
7169   /* Pass 7: flag 32-bit registers */
7170   /* Pass 8: assembly */
7171   /* Pass 9: linker */
7172   /* Pass 10: garbage collection / free memory */
7173
7174   int j;
7175   int done=0;
7176   unsigned int type,op,op2;
7177
7178   //printf("addr = %x source = %x %x\n", addr,source,source[0]);
7179
7180   /* Pass 1 disassembly */
7181
7182   for (i = 0; !done; i++)
7183   {
7184     memset(&dops[i], 0, sizeof(dops[i]));
7185     op2=0;
7186     minimum_free_regs[i]=0;
7187     dops[i].opcode=op=source[i]>>26;
7188     switch(op)
7189     {
7190       case 0x00: strcpy(insn[i],"special"); type=NI;
7191         op2=source[i]&0x3f;
7192         switch(op2)
7193         {
7194           case 0x00: strcpy(insn[i],"SLL"); type=SHIFTIMM; break;
7195           case 0x02: strcpy(insn[i],"SRL"); type=SHIFTIMM; break;
7196           case 0x03: strcpy(insn[i],"SRA"); type=SHIFTIMM; break;
7197           case 0x04: strcpy(insn[i],"SLLV"); type=SHIFT; break;
7198           case 0x06: strcpy(insn[i],"SRLV"); type=SHIFT; break;
7199           case 0x07: strcpy(insn[i],"SRAV"); type=SHIFT; break;
7200           case 0x08: strcpy(insn[i],"JR"); type=RJUMP; break;
7201           case 0x09: strcpy(insn[i],"JALR"); type=RJUMP; break;
7202           case 0x0C: strcpy(insn[i],"SYSCALL"); type=SYSCALL; break;
7203           case 0x0D: strcpy(insn[i],"BREAK"); type=OTHER; break;
7204           case 0x0F: strcpy(insn[i],"SYNC"); type=OTHER; break;
7205           case 0x10: strcpy(insn[i],"MFHI"); type=MOV; break;
7206           case 0x11: strcpy(insn[i],"MTHI"); type=MOV; break;
7207           case 0x12: strcpy(insn[i],"MFLO"); type=MOV; break;
7208           case 0x13: strcpy(insn[i],"MTLO"); type=MOV; break;
7209           case 0x18: strcpy(insn[i],"MULT"); type=MULTDIV; break;
7210           case 0x19: strcpy(insn[i],"MULTU"); type=MULTDIV; break;
7211           case 0x1A: strcpy(insn[i],"DIV"); type=MULTDIV; break;
7212           case 0x1B: strcpy(insn[i],"DIVU"); type=MULTDIV; break;
7213           case 0x20: strcpy(insn[i],"ADD"); type=ALU; break;
7214           case 0x21: strcpy(insn[i],"ADDU"); type=ALU; break;
7215           case 0x22: strcpy(insn[i],"SUB"); type=ALU; break;
7216           case 0x23: strcpy(insn[i],"SUBU"); type=ALU; break;
7217           case 0x24: strcpy(insn[i],"AND"); type=ALU; break;
7218           case 0x25: strcpy(insn[i],"OR"); type=ALU; break;
7219           case 0x26: strcpy(insn[i],"XOR"); type=ALU; break;
7220           case 0x27: strcpy(insn[i],"NOR"); type=ALU; break;
7221           case 0x2A: strcpy(insn[i],"SLT"); type=ALU; break;
7222           case 0x2B: strcpy(insn[i],"SLTU"); type=ALU; break;
7223           case 0x30: strcpy(insn[i],"TGE"); type=NI; break;
7224           case 0x31: strcpy(insn[i],"TGEU"); type=NI; break;
7225           case 0x32: strcpy(insn[i],"TLT"); type=NI; break;
7226           case 0x33: strcpy(insn[i],"TLTU"); type=NI; break;
7227           case 0x34: strcpy(insn[i],"TEQ"); type=NI; break;
7228           case 0x36: strcpy(insn[i],"TNE"); type=NI; break;
7229 #if 0
7230           case 0x14: strcpy(insn[i],"DSLLV"); type=SHIFT; break;
7231           case 0x16: strcpy(insn[i],"DSRLV"); type=SHIFT; break;
7232           case 0x17: strcpy(insn[i],"DSRAV"); type=SHIFT; break;
7233           case 0x1C: strcpy(insn[i],"DMULT"); type=MULTDIV; break;
7234           case 0x1D: strcpy(insn[i],"DMULTU"); type=MULTDIV; break;
7235           case 0x1E: strcpy(insn[i],"DDIV"); type=MULTDIV; break;
7236           case 0x1F: strcpy(insn[i],"DDIVU"); type=MULTDIV; break;
7237           case 0x2C: strcpy(insn[i],"DADD"); type=ALU; break;
7238           case 0x2D: strcpy(insn[i],"DADDU"); type=ALU; break;
7239           case 0x2E: strcpy(insn[i],"DSUB"); type=ALU; break;
7240           case 0x2F: strcpy(insn[i],"DSUBU"); type=ALU; break;
7241           case 0x38: strcpy(insn[i],"DSLL"); type=SHIFTIMM; break;
7242           case 0x3A: strcpy(insn[i],"DSRL"); type=SHIFTIMM; break;
7243           case 0x3B: strcpy(insn[i],"DSRA"); type=SHIFTIMM; break;
7244           case 0x3C: strcpy(insn[i],"DSLL32"); type=SHIFTIMM; break;
7245           case 0x3E: strcpy(insn[i],"DSRL32"); type=SHIFTIMM; break;
7246           case 0x3F: strcpy(insn[i],"DSRA32"); type=SHIFTIMM; break;
7247 #endif
7248         }
7249         break;
7250       case 0x01: strcpy(insn[i],"regimm"); type=NI;
7251         op2=(source[i]>>16)&0x1f;
7252         switch(op2)
7253         {
7254           case 0x00: strcpy(insn[i],"BLTZ"); type=SJUMP; break;
7255           case 0x01: strcpy(insn[i],"BGEZ"); type=SJUMP; break;
7256           //case 0x02: strcpy(insn[i],"BLTZL"); type=SJUMP; break;
7257           //case 0x03: strcpy(insn[i],"BGEZL"); type=SJUMP; break;
7258           //case 0x08: strcpy(insn[i],"TGEI"); type=NI; break;
7259           //case 0x09: strcpy(insn[i],"TGEIU"); type=NI; break;
7260           //case 0x0A: strcpy(insn[i],"TLTI"); type=NI; break;
7261           //case 0x0B: strcpy(insn[i],"TLTIU"); type=NI; break;
7262           //case 0x0C: strcpy(insn[i],"TEQI"); type=NI; break;
7263           //case 0x0E: strcpy(insn[i],"TNEI"); type=NI; break;
7264           case 0x10: strcpy(insn[i],"BLTZAL"); type=SJUMP; break;
7265           case 0x11: strcpy(insn[i],"BGEZAL"); type=SJUMP; break;
7266           //case 0x12: strcpy(insn[i],"BLTZALL"); type=SJUMP; break;
7267           //case 0x13: strcpy(insn[i],"BGEZALL"); type=SJUMP; break;
7268         }
7269         break;
7270       case 0x02: strcpy(insn[i],"J"); type=UJUMP; break;
7271       case 0x03: strcpy(insn[i],"JAL"); type=UJUMP; break;
7272       case 0x04: strcpy(insn[i],"BEQ"); type=CJUMP; break;
7273       case 0x05: strcpy(insn[i],"BNE"); type=CJUMP; break;
7274       case 0x06: strcpy(insn[i],"BLEZ"); type=CJUMP; break;
7275       case 0x07: strcpy(insn[i],"BGTZ"); type=CJUMP; break;
7276       case 0x08: strcpy(insn[i],"ADDI"); type=IMM16; break;
7277       case 0x09: strcpy(insn[i],"ADDIU"); type=IMM16; break;
7278       case 0x0A: strcpy(insn[i],"SLTI"); type=IMM16; break;
7279       case 0x0B: strcpy(insn[i],"SLTIU"); type=IMM16; break;
7280       case 0x0C: strcpy(insn[i],"ANDI"); type=IMM16; break;
7281       case 0x0D: strcpy(insn[i],"ORI"); type=IMM16; break;
7282       case 0x0E: strcpy(insn[i],"XORI"); type=IMM16; break;
7283       case 0x0F: strcpy(insn[i],"LUI"); type=IMM16; break;
7284       case 0x10: strcpy(insn[i],"cop0"); type=NI;
7285         op2=(source[i]>>21)&0x1f;
7286         switch(op2)
7287         {
7288           case 0x00: strcpy(insn[i],"MFC0"); type=COP0; break;
7289           case 0x02: strcpy(insn[i],"CFC0"); type=COP0; break;
7290           case 0x04: strcpy(insn[i],"MTC0"); type=COP0; break;
7291           case 0x06: strcpy(insn[i],"CTC0"); type=COP0; break;
7292           case 0x10: strcpy(insn[i],"RFE"); type=COP0; break;
7293         }
7294         break;
7295       case 0x11: strcpy(insn[i],"cop1"); type=COP1;
7296         op2=(source[i]>>21)&0x1f;
7297         break;
7298 #if 0
7299       case 0x14: strcpy(insn[i],"BEQL"); type=CJUMP; break;
7300       case 0x15: strcpy(insn[i],"BNEL"); type=CJUMP; break;
7301       case 0x16: strcpy(insn[i],"BLEZL"); type=CJUMP; break;
7302       case 0x17: strcpy(insn[i],"BGTZL"); type=CJUMP; break;
7303       case 0x18: strcpy(insn[i],"DADDI"); type=IMM16; break;
7304       case 0x19: strcpy(insn[i],"DADDIU"); type=IMM16; break;
7305       case 0x1A: strcpy(insn[i],"LDL"); type=LOADLR; break;
7306       case 0x1B: strcpy(insn[i],"LDR"); type=LOADLR; break;
7307 #endif
7308       case 0x20: strcpy(insn[i],"LB"); type=LOAD; break;
7309       case 0x21: strcpy(insn[i],"LH"); type=LOAD; break;
7310       case 0x22: strcpy(insn[i],"LWL"); type=LOADLR; break;
7311       case 0x23: strcpy(insn[i],"LW"); type=LOAD; break;
7312       case 0x24: strcpy(insn[i],"LBU"); type=LOAD; break;
7313       case 0x25: strcpy(insn[i],"LHU"); type=LOAD; break;
7314       case 0x26: strcpy(insn[i],"LWR"); type=LOADLR; break;
7315 #if 0
7316       case 0x27: strcpy(insn[i],"LWU"); type=LOAD; break;
7317 #endif
7318       case 0x28: strcpy(insn[i],"SB"); type=STORE; break;
7319       case 0x29: strcpy(insn[i],"SH"); type=STORE; break;
7320       case 0x2A: strcpy(insn[i],"SWL"); type=STORELR; break;
7321       case 0x2B: strcpy(insn[i],"SW"); type=STORE; break;
7322 #if 0
7323       case 0x2C: strcpy(insn[i],"SDL"); type=STORELR; break;
7324       case 0x2D: strcpy(insn[i],"SDR"); type=STORELR; break;
7325 #endif
7326       case 0x2E: strcpy(insn[i],"SWR"); type=STORELR; break;
7327       case 0x2F: strcpy(insn[i],"CACHE"); type=NOP; break;
7328       case 0x30: strcpy(insn[i],"LL"); type=NI; break;
7329       case 0x31: strcpy(insn[i],"LWC1"); type=C1LS; break;
7330 #if 0
7331       case 0x34: strcpy(insn[i],"LLD"); type=NI; break;
7332       case 0x35: strcpy(insn[i],"LDC1"); type=C1LS; break;
7333       case 0x37: strcpy(insn[i],"LD"); type=LOAD; break;
7334 #endif
7335       case 0x38: strcpy(insn[i],"SC"); type=NI; break;
7336       case 0x39: strcpy(insn[i],"SWC1"); type=C1LS; break;
7337 #if 0
7338       case 0x3C: strcpy(insn[i],"SCD"); type=NI; break;
7339       case 0x3D: strcpy(insn[i],"SDC1"); type=C1LS; break;
7340       case 0x3F: strcpy(insn[i],"SD"); type=STORE; break;
7341 #endif
7342       case 0x12: strcpy(insn[i],"COP2"); type=NI;
7343         op2=(source[i]>>21)&0x1f;
7344         //if (op2 & 0x10)
7345         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
7346           if (gte_handlers[source[i]&0x3f]!=NULL) {
7347             if (gte_regnames[source[i]&0x3f]!=NULL)
7348               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
7349             else
7350               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
7351             type=C2OP;
7352           }
7353         }
7354         else switch(op2)
7355         {
7356           case 0x00: strcpy(insn[i],"MFC2"); type=COP2; break;
7357           case 0x02: strcpy(insn[i],"CFC2"); type=COP2; break;
7358           case 0x04: strcpy(insn[i],"MTC2"); type=COP2; break;
7359           case 0x06: strcpy(insn[i],"CTC2"); type=COP2; break;
7360         }
7361         break;
7362       case 0x32: strcpy(insn[i],"LWC2"); type=C2LS; break;
7363       case 0x3A: strcpy(insn[i],"SWC2"); type=C2LS; break;
7364       case 0x3B: strcpy(insn[i],"HLECALL"); type=HLECALL; break;
7365       default: strcpy(insn[i],"???"); type=NI;
7366         SysPrintf("NI %08x @%08x (%08x)\n", source[i], addr + i*4, addr);
7367         break;
7368     }
7369     dops[i].itype=type;
7370     dops[i].opcode2=op2;
7371     /* Get registers/immediates */
7372     dops[i].lt1=0;
7373     gte_rs[i]=gte_rt[i]=0;
7374     switch(type) {
7375       case LOAD:
7376         dops[i].rs1=(source[i]>>21)&0x1f;
7377         dops[i].rs2=0;
7378         dops[i].rt1=(source[i]>>16)&0x1f;
7379         dops[i].rt2=0;
7380         imm[i]=(short)source[i];
7381         break;
7382       case STORE:
7383       case STORELR:
7384         dops[i].rs1=(source[i]>>21)&0x1f;
7385         dops[i].rs2=(source[i]>>16)&0x1f;
7386         dops[i].rt1=0;
7387         dops[i].rt2=0;
7388         imm[i]=(short)source[i];
7389         break;
7390       case LOADLR:
7391         // LWL/LWR only load part of the register,
7392         // therefore the target register must be treated as a source too
7393         dops[i].rs1=(source[i]>>21)&0x1f;
7394         dops[i].rs2=(source[i]>>16)&0x1f;
7395         dops[i].rt1=(source[i]>>16)&0x1f;
7396         dops[i].rt2=0;
7397         imm[i]=(short)source[i];
7398         break;
7399       case IMM16:
7400         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
7401         else dops[i].rs1=(source[i]>>21)&0x1f;
7402         dops[i].rs2=0;
7403         dops[i].rt1=(source[i]>>16)&0x1f;
7404         dops[i].rt2=0;
7405         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
7406           imm[i]=(unsigned short)source[i];
7407         }else{
7408           imm[i]=(short)source[i];
7409         }
7410         break;
7411       case UJUMP:
7412         dops[i].rs1=0;
7413         dops[i].rs2=0;
7414         dops[i].rt1=0;
7415         dops[i].rt2=0;
7416         // The JAL instruction writes to r31.
7417         if (op&1) {
7418           dops[i].rt1=31;
7419         }
7420         dops[i].rs2=CCREG;
7421         break;
7422       case RJUMP:
7423         dops[i].rs1=(source[i]>>21)&0x1f;
7424         dops[i].rs2=0;
7425         dops[i].rt1=0;
7426         dops[i].rt2=0;
7427         // The JALR instruction writes to rd.
7428         if (op2&1) {
7429           dops[i].rt1=(source[i]>>11)&0x1f;
7430         }
7431         dops[i].rs2=CCREG;
7432         break;
7433       case CJUMP:
7434         dops[i].rs1=(source[i]>>21)&0x1f;
7435         dops[i].rs2=(source[i]>>16)&0x1f;
7436         dops[i].rt1=0;
7437         dops[i].rt2=0;
7438         if(op&2) { // BGTZ/BLEZ
7439           dops[i].rs2=0;
7440         }
7441         break;
7442       case SJUMP:
7443         dops[i].rs1=(source[i]>>21)&0x1f;
7444         dops[i].rs2=CCREG;
7445         dops[i].rt1=0;
7446         dops[i].rt2=0;
7447         if(op2&0x10) { // BxxAL
7448           dops[i].rt1=31;
7449           // NOTE: If the branch is not taken, r31 is still overwritten
7450         }
7451         break;
7452       case ALU:
7453         dops[i].rs1=(source[i]>>21)&0x1f; // source
7454         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
7455         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7456         dops[i].rt2=0;
7457         break;
7458       case MULTDIV:
7459         dops[i].rs1=(source[i]>>21)&0x1f; // source
7460         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
7461         dops[i].rt1=HIREG;
7462         dops[i].rt2=LOREG;
7463         break;
7464       case MOV:
7465         dops[i].rs1=0;
7466         dops[i].rs2=0;
7467         dops[i].rt1=0;
7468         dops[i].rt2=0;
7469         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
7470         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
7471         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
7472         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
7473         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
7474         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
7475         break;
7476       case SHIFT:
7477         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
7478         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
7479         dops[i].rt1=(source[i]>>11)&0x1f; // destination
7480         dops[i].rt2=0;
7481         break;
7482       case SHIFTIMM:
7483         dops[i].rs1=(source[i]>>16)&0x1f;
7484         dops[i].rs2=0;
7485         dops[i].rt1=(source[i]>>11)&0x1f;
7486         dops[i].rt2=0;
7487         imm[i]=(source[i]>>6)&0x1f;
7488         // DSxx32 instructions
7489         if(op2>=0x3c) imm[i]|=0x20;
7490         break;
7491       case COP0:
7492         dops[i].rs1=0;
7493         dops[i].rs2=0;
7494         dops[i].rt1=0;
7495         dops[i].rt2=0;
7496         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
7497         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
7498         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
7499         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
7500         break;
7501       case COP1:
7502         dops[i].rs1=0;
7503         dops[i].rs2=0;
7504         dops[i].rt1=0;
7505         dops[i].rt2=0;
7506         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
7507         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
7508         dops[i].rs2=CSREG;
7509         break;
7510       case COP2:
7511         dops[i].rs1=0;
7512         dops[i].rs2=0;
7513         dops[i].rt1=0;
7514         dops[i].rt2=0;
7515         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
7516         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
7517         dops[i].rs2=CSREG;
7518         int gr=(source[i]>>11)&0x1F;
7519         switch(op2)
7520         {
7521           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
7522           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
7523           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
7524           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
7525         }
7526         break;
7527       case C1LS:
7528         dops[i].rs1=(source[i]>>21)&0x1F;
7529         dops[i].rs2=CSREG;
7530         dops[i].rt1=0;
7531         dops[i].rt2=0;
7532         imm[i]=(short)source[i];
7533         break;
7534       case C2LS:
7535         dops[i].rs1=(source[i]>>21)&0x1F;
7536         dops[i].rs2=0;
7537         dops[i].rt1=0;
7538         dops[i].rt2=0;
7539         imm[i]=(short)source[i];
7540         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
7541         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
7542         break;
7543       case C2OP:
7544         dops[i].rs1=0;
7545         dops[i].rs2=0;
7546         dops[i].rt1=0;
7547         dops[i].rt2=0;
7548         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
7549         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
7550         gte_rt[i]|=1ll<<63; // every op changes flags
7551         if((source[i]&0x3f)==GTE_MVMVA) {
7552           int v = (source[i] >> 15) & 3;
7553           gte_rs[i]&=~0xe3fll;
7554           if(v==3) gte_rs[i]|=0xe00ll;
7555           else gte_rs[i]|=3ll<<(v*2);
7556         }
7557         break;
7558       case SYSCALL:
7559       case HLECALL:
7560       case INTCALL:
7561         dops[i].rs1=CCREG;
7562         dops[i].rs2=0;
7563         dops[i].rt1=0;
7564         dops[i].rt2=0;
7565         break;
7566       default:
7567         dops[i].rs1=0;
7568         dops[i].rs2=0;
7569         dops[i].rt1=0;
7570         dops[i].rt2=0;
7571     }
7572     /* Calculate branch target addresses */
7573     if(type==UJUMP)
7574       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
7575     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
7576       ba[i]=start+i*4+8; // Ignore never taken branch
7577     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
7578       ba[i]=start+i*4+8; // Ignore never taken branch
7579     else if(type==CJUMP||type==SJUMP)
7580       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
7581     else ba[i]=-1;
7582
7583     /* simplify always (not)taken branches */
7584     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
7585       dops[i].rs1 = dops[i].rs2 = 0;
7586       if (!(op & 1)) {
7587         dops[i].itype = type = UJUMP;
7588         dops[i].rs2 = CCREG;
7589       }
7590     }
7591     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
7592       dops[i].itype = type = UJUMP;
7593
7594     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
7595     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
7596     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
7597     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
7598
7599     /* messy cases to just pass over to the interpreter */
7600     if (i > 0 && dops[i-1].is_jump) {
7601       int do_in_intrp=0;
7602       // branch in delay slot?
7603       if (dops[i].is_jump) {
7604         // don't handle first branch and call interpreter if it's hit
7605         SysPrintf("branch in delay slot @%08x (%08x)\n", addr + i*4, addr);
7606         do_in_intrp=1;
7607       }
7608       // basic load delay detection
7609       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
7610         int t=(ba[i-1]-start)/4;
7611         if(0 <= t && t < i &&(dops[i].rt1==dops[t].rs1||dops[i].rt1==dops[t].rs2)&&dops[t].itype!=CJUMP&&dops[t].itype!=SJUMP) {
7612           // jump target wants DS result - potential load delay effect
7613           SysPrintf("load delay @%08x (%08x)\n", addr + i*4, addr);
7614           do_in_intrp=1;
7615           dops[t+1].bt=1; // expected return from interpreter
7616         }
7617         else if(i>=2&&dops[i-2].rt1==2&&dops[i].rt1==2&&dops[i].rs1!=2&&dops[i].rs2!=2&&dops[i-1].rs1!=2&&dops[i-1].rs2!=2&&
7618               !(i>=3&&dops[i-3].is_jump)) {
7619           // v0 overwrite like this is a sign of trouble, bail out
7620           SysPrintf("v0 overwrite @%08x (%08x)\n", addr + i*4, addr);
7621           do_in_intrp=1;
7622         }
7623       }
7624       if (do_in_intrp) {
7625         memset(&dops[i-1], 0, sizeof(dops[i-1]));
7626         dops[i-1].itype = INTCALL;
7627         dops[i-1].rs1 = CCREG;
7628         ba[i-1] = -1;
7629         done = 2;
7630         i--; // don't compile the DS
7631       }
7632     }
7633
7634     /* Is this the end of the block? */
7635     if (i > 0 && dops[i-1].is_ujump) {
7636       if(dops[i-1].rt1==0) { // Continue past subroutine call (JAL)
7637         done=2;
7638       }
7639       else {
7640         if(stop_after_jal) done=1;
7641         // Stop on BREAK
7642         if((source[i+1]&0xfc00003f)==0x0d) done=1;
7643       }
7644       // Don't recompile stuff that's already compiled
7645       if(check_addr(start+i*4+4)) done=1;
7646       // Don't get too close to the limit
7647       if(i>MAXBLOCK/2) done=1;
7648     }
7649     if(dops[i].itype==SYSCALL&&stop_after_jal) done=1;
7650     if(dops[i].itype==HLECALL||dops[i].itype==INTCALL) done=2;
7651     if(done==2) {
7652       // Does the block continue due to a branch?
7653       for(j=i-1;j>=0;j--)
7654       {
7655         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
7656         if(ba[j]==start+i*4+4) done=j=0;
7657         if(ba[j]==start+i*4+8) done=j=0;
7658       }
7659     }
7660     //assert(i<MAXBLOCK-1);
7661     if(start+i*4==pagelimit-4) done=1;
7662     assert(start+i*4<pagelimit);
7663     if (i==MAXBLOCK-1) done=1;
7664     // Stop if we're compiling junk
7665     if(dops[i].itype==NI&&dops[i].opcode==0x11) {
7666       done=stop_after_jal=1;
7667       SysPrintf("Disabled speculative precompilation\n");
7668     }
7669   }
7670   slen=i;
7671   if (dops[i-1].is_jump) {
7672     if(start+i*4==pagelimit) {
7673       dops[i-1].itype=SPAN;
7674     }
7675   }
7676   assert(slen>0);
7677
7678   int clear_hack_addr = apply_hacks();
7679
7680   /* Pass 2 - Register dependencies and branch targets */
7681
7682   unneeded_registers(0,slen-1,0);
7683
7684   /* Pass 3 - Register allocation */
7685
7686   struct regstat current; // Current register allocations/status
7687   current.dirty=0;
7688   current.u=unneeded_reg[0];
7689   clear_all_regs(current.regmap);
7690   alloc_reg(&current,0,CCREG);
7691   dirty_reg(&current,CCREG);
7692   current.isconst=0;
7693   current.wasconst=0;
7694   current.waswritten=0;
7695   int ds=0;
7696   int cc=0;
7697   int hr=-1;
7698
7699   if((u_int)addr&1) {
7700     // First instruction is delay slot
7701     cc=-1;
7702     dops[1].bt=1;
7703     ds=1;
7704     unneeded_reg[0]=1;
7705     current.regmap[HOST_BTREG]=BTREG;
7706   }
7707
7708   for(i=0;i<slen;i++)
7709   {
7710     if(dops[i].bt)
7711     {
7712       int hr;
7713       for(hr=0;hr<HOST_REGS;hr++)
7714       {
7715         // Is this really necessary?
7716         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7717       }
7718       current.isconst=0;
7719       current.waswritten=0;
7720     }
7721
7722     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7723     regs[i].wasconst=current.isconst;
7724     regs[i].wasdirty=current.dirty;
7725     regs[i].loadedconst=0;
7726     if (!dops[i].is_jump) {
7727       if(i+1<slen) {
7728         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7729         current.u|=1;
7730       } else {
7731         current.u=1;
7732       }
7733     } else {
7734       if(i+1<slen) {
7735         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7736         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7737         current.u|=1;
7738       } else {
7739         SysPrintf("oops, branch at end of block with no delay slot @%08x\n", start + i*4);
7740         abort();
7741       }
7742     }
7743     dops[i].is_ds=ds;
7744     if(ds) {
7745       ds=0; // Skip delay slot, already allocated as part of branch
7746       // ...but we need to alloc it in case something jumps here
7747       if(i+1<slen) {
7748         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7749       }else{
7750         current.u=branch_unneeded_reg[i-1];
7751       }
7752       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7753       current.u|=1;
7754       struct regstat temp;
7755       memcpy(&temp,&current,sizeof(current));
7756       temp.wasdirty=temp.dirty;
7757       // TODO: Take into account unconditional branches, as below
7758       delayslot_alloc(&temp,i);
7759       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7760       regs[i].wasdirty=temp.wasdirty;
7761       regs[i].dirty=temp.dirty;
7762       regs[i].isconst=0;
7763       regs[i].wasconst=0;
7764       current.isconst=0;
7765       // Create entry (branch target) regmap
7766       for(hr=0;hr<HOST_REGS;hr++)
7767       {
7768         int r=temp.regmap[hr];
7769         if(r>=0) {
7770           if(r!=regmap_pre[i][hr]) {
7771             regs[i].regmap_entry[hr]=-1;
7772           }
7773           else
7774           {
7775               assert(r < 64);
7776               if((current.u>>r)&1) {
7777                 regs[i].regmap_entry[hr]=-1;
7778                 regs[i].regmap[hr]=-1;
7779                 //Don't clear regs in the delay slot as the branch might need them
7780                 //current.regmap[hr]=-1;
7781               }else
7782                 regs[i].regmap_entry[hr]=r;
7783           }
7784         } else {
7785           // First instruction expects CCREG to be allocated
7786           if(i==0&&hr==HOST_CCREG)
7787             regs[i].regmap_entry[hr]=CCREG;
7788           else
7789             regs[i].regmap_entry[hr]=-1;
7790         }
7791       }
7792     }
7793     else { // Not delay slot
7794       switch(dops[i].itype) {
7795         case UJUMP:
7796           //current.isconst=0; // DEBUG
7797           //current.wasconst=0; // DEBUG
7798           //regs[i].wasconst=0; // DEBUG
7799           clear_const(&current,dops[i].rt1);
7800           alloc_cc(&current,i);
7801           dirty_reg(&current,CCREG);
7802           if (dops[i].rt1==31) {
7803             alloc_reg(&current,i,31);
7804             dirty_reg(&current,31);
7805             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7806             //assert(dops[i+1].rt1!=dops[i].rt1);
7807             #ifdef REG_PREFETCH
7808             alloc_reg(&current,i,PTEMP);
7809             #endif
7810           }
7811           dops[i].ooo=1;
7812           delayslot_alloc(&current,i+1);
7813           //current.isconst=0; // DEBUG
7814           ds=1;
7815           //printf("i=%d, isconst=%x\n",i,current.isconst);
7816           break;
7817         case RJUMP:
7818           //current.isconst=0;
7819           //current.wasconst=0;
7820           //regs[i].wasconst=0;
7821           clear_const(&current,dops[i].rs1);
7822           clear_const(&current,dops[i].rt1);
7823           alloc_cc(&current,i);
7824           dirty_reg(&current,CCREG);
7825           if (!ds_writes_rjump_rs(i)) {
7826             alloc_reg(&current,i,dops[i].rs1);
7827             if (dops[i].rt1!=0) {
7828               alloc_reg(&current,i,dops[i].rt1);
7829               dirty_reg(&current,dops[i].rt1);
7830               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7831               assert(dops[i+1].rt1!=dops[i].rt1);
7832               #ifdef REG_PREFETCH
7833               alloc_reg(&current,i,PTEMP);
7834               #endif
7835             }
7836             #ifdef USE_MINI_HT
7837             if(dops[i].rs1==31) { // JALR
7838               alloc_reg(&current,i,RHASH);
7839               alloc_reg(&current,i,RHTBL);
7840             }
7841             #endif
7842             delayslot_alloc(&current,i+1);
7843           } else {
7844             // The delay slot overwrites our source register,
7845             // allocate a temporary register to hold the old value.
7846             current.isconst=0;
7847             current.wasconst=0;
7848             regs[i].wasconst=0;
7849             delayslot_alloc(&current,i+1);
7850             current.isconst=0;
7851             alloc_reg(&current,i,RTEMP);
7852           }
7853           //current.isconst=0; // DEBUG
7854           dops[i].ooo=1;
7855           ds=1;
7856           break;
7857         case CJUMP:
7858           //current.isconst=0;
7859           //current.wasconst=0;
7860           //regs[i].wasconst=0;
7861           clear_const(&current,dops[i].rs1);
7862           clear_const(&current,dops[i].rs2);
7863           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7864           {
7865             alloc_cc(&current,i);
7866             dirty_reg(&current,CCREG);
7867             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7868             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7869             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7870                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7871               // The delay slot overwrites one of our conditions.
7872               // Allocate the branch condition registers instead.
7873               current.isconst=0;
7874               current.wasconst=0;
7875               regs[i].wasconst=0;
7876               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7877               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7878             }
7879             else
7880             {
7881               dops[i].ooo=1;
7882               delayslot_alloc(&current,i+1);
7883             }
7884           }
7885           else
7886           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7887           {
7888             alloc_cc(&current,i);
7889             dirty_reg(&current,CCREG);
7890             alloc_reg(&current,i,dops[i].rs1);
7891             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7892               // The delay slot overwrites one of our conditions.
7893               // Allocate the branch condition registers instead.
7894               current.isconst=0;
7895               current.wasconst=0;
7896               regs[i].wasconst=0;
7897               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7898             }
7899             else
7900             {
7901               dops[i].ooo=1;
7902               delayslot_alloc(&current,i+1);
7903             }
7904           }
7905           else
7906           // Don't alloc the delay slot yet because we might not execute it
7907           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7908           {
7909             current.isconst=0;
7910             current.wasconst=0;
7911             regs[i].wasconst=0;
7912             alloc_cc(&current,i);
7913             dirty_reg(&current,CCREG);
7914             alloc_reg(&current,i,dops[i].rs1);
7915             alloc_reg(&current,i,dops[i].rs2);
7916           }
7917           else
7918           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7919           {
7920             current.isconst=0;
7921             current.wasconst=0;
7922             regs[i].wasconst=0;
7923             alloc_cc(&current,i);
7924             dirty_reg(&current,CCREG);
7925             alloc_reg(&current,i,dops[i].rs1);
7926           }
7927           ds=1;
7928           //current.isconst=0;
7929           break;
7930         case SJUMP:
7931           //current.isconst=0;
7932           //current.wasconst=0;
7933           //regs[i].wasconst=0;
7934           clear_const(&current,dops[i].rs1);
7935           clear_const(&current,dops[i].rt1);
7936           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7937           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7938           {
7939             alloc_cc(&current,i);
7940             dirty_reg(&current,CCREG);
7941             alloc_reg(&current,i,dops[i].rs1);
7942             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7943               alloc_reg(&current,i,31);
7944               dirty_reg(&current,31);
7945               //#ifdef REG_PREFETCH
7946               //alloc_reg(&current,i,PTEMP);
7947               //#endif
7948             }
7949             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) // The delay slot overwrites the branch condition.
7950                ||(dops[i].rt1==31&&(dops[i+1].rs1==31||dops[i+1].rs2==31||dops[i+1].rt1==31||dops[i+1].rt2==31))) { // DS touches $ra
7951               // Allocate the branch condition registers instead.
7952               current.isconst=0;
7953               current.wasconst=0;
7954               regs[i].wasconst=0;
7955               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7956             }
7957             else
7958             {
7959               dops[i].ooo=1;
7960               delayslot_alloc(&current,i+1);
7961             }
7962           }
7963           else
7964           // Don't alloc the delay slot yet because we might not execute it
7965           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7966           {
7967             current.isconst=0;
7968             current.wasconst=0;
7969             regs[i].wasconst=0;
7970             alloc_cc(&current,i);
7971             dirty_reg(&current,CCREG);
7972             alloc_reg(&current,i,dops[i].rs1);
7973           }
7974           ds=1;
7975           //current.isconst=0;
7976           break;
7977         case IMM16:
7978           imm16_alloc(&current,i);
7979           break;
7980         case LOAD:
7981         case LOADLR:
7982           load_alloc(&current,i);
7983           break;
7984         case STORE:
7985         case STORELR:
7986           store_alloc(&current,i);
7987           break;
7988         case ALU:
7989           alu_alloc(&current,i);
7990           break;
7991         case SHIFT:
7992           shift_alloc(&current,i);
7993           break;
7994         case MULTDIV:
7995           multdiv_alloc(&current,i);
7996           break;
7997         case SHIFTIMM:
7998           shiftimm_alloc(&current,i);
7999           break;
8000         case MOV:
8001           mov_alloc(&current,i);
8002           break;
8003         case COP0:
8004           cop0_alloc(&current,i);
8005           break;
8006         case COP1:
8007           break;
8008         case COP2:
8009           cop2_alloc(&current,i);
8010           break;
8011         case C1LS:
8012           c1ls_alloc(&current,i);
8013           break;
8014         case C2LS:
8015           c2ls_alloc(&current,i);
8016           break;
8017         case C2OP:
8018           c2op_alloc(&current,i);
8019           break;
8020         case SYSCALL:
8021         case HLECALL:
8022         case INTCALL:
8023           syscall_alloc(&current,i);
8024           break;
8025         case SPAN:
8026           pagespan_alloc(&current,i);
8027           break;
8028       }
8029
8030       // Create entry (branch target) regmap
8031       for(hr=0;hr<HOST_REGS;hr++)
8032       {
8033         int r,or;
8034         r=current.regmap[hr];
8035         if(r>=0) {
8036           if(r!=regmap_pre[i][hr]) {
8037             // TODO: delay slot (?)
8038             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
8039             if(or<0||(r&63)>=TEMPREG){
8040               regs[i].regmap_entry[hr]=-1;
8041             }
8042             else
8043             {
8044               // Just move it to a different register
8045               regs[i].regmap_entry[hr]=r;
8046               // If it was dirty before, it's still dirty
8047               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r&63);
8048             }
8049           }
8050           else
8051           {
8052             // Unneeded
8053             if(r==0){
8054               regs[i].regmap_entry[hr]=0;
8055             }
8056             else
8057             {
8058               assert(r<64);
8059               if((current.u>>r)&1) {
8060                 regs[i].regmap_entry[hr]=-1;
8061                 //regs[i].regmap[hr]=-1;
8062                 current.regmap[hr]=-1;
8063               }else
8064                 regs[i].regmap_entry[hr]=r;
8065             }
8066           }
8067         } else {
8068           // Branches expect CCREG to be allocated at the target
8069           if(regmap_pre[i][hr]==CCREG)
8070             regs[i].regmap_entry[hr]=CCREG;
8071           else
8072             regs[i].regmap_entry[hr]=-1;
8073         }
8074       }
8075       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
8076     }
8077
8078     if(i>0&&(dops[i-1].itype==STORE||dops[i-1].itype==STORELR||(dops[i-1].itype==C2LS&&dops[i-1].opcode==0x3a))&&(u_int)imm[i-1]<0x800)
8079       current.waswritten|=1<<dops[i-1].rs1;
8080     current.waswritten&=~(1<<dops[i].rt1);
8081     current.waswritten&=~(1<<dops[i].rt2);
8082     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
8083       current.waswritten&=~(1<<dops[i].rs1);
8084
8085     /* Branch post-alloc */
8086     if(i>0)
8087     {
8088       current.wasdirty=current.dirty;
8089       switch(dops[i-1].itype) {
8090         case UJUMP:
8091           memcpy(&branch_regs[i-1],&current,sizeof(current));
8092           branch_regs[i-1].isconst=0;
8093           branch_regs[i-1].wasconst=0;
8094           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8095           alloc_cc(&branch_regs[i-1],i-1);
8096           dirty_reg(&branch_regs[i-1],CCREG);
8097           if(dops[i-1].rt1==31) { // JAL
8098             alloc_reg(&branch_regs[i-1],i-1,31);
8099             dirty_reg(&branch_regs[i-1],31);
8100           }
8101           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8102           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8103           break;
8104         case RJUMP:
8105           memcpy(&branch_regs[i-1],&current,sizeof(current));
8106           branch_regs[i-1].isconst=0;
8107           branch_regs[i-1].wasconst=0;
8108           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8109           alloc_cc(&branch_regs[i-1],i-1);
8110           dirty_reg(&branch_regs[i-1],CCREG);
8111           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
8112           if(dops[i-1].rt1!=0) { // JALR
8113             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
8114             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
8115           }
8116           #ifdef USE_MINI_HT
8117           if(dops[i-1].rs1==31) { // JALR
8118             alloc_reg(&branch_regs[i-1],i-1,RHASH);
8119             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
8120           }
8121           #endif
8122           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8123           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8124           break;
8125         case CJUMP:
8126           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
8127           {
8128             alloc_cc(&current,i-1);
8129             dirty_reg(&current,CCREG);
8130             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
8131                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
8132               // The delay slot overwrote one of our conditions
8133               // Delay slot goes after the test (in order)
8134               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8135               current.u|=1;
8136               delayslot_alloc(&current,i);
8137               current.isconst=0;
8138             }
8139             else
8140             {
8141               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
8142               // Alloc the branch condition registers
8143               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
8144               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
8145             }
8146             memcpy(&branch_regs[i-1],&current,sizeof(current));
8147             branch_regs[i-1].isconst=0;
8148             branch_regs[i-1].wasconst=0;
8149             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8150             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8151           }
8152           else
8153           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
8154           {
8155             alloc_cc(&current,i-1);
8156             dirty_reg(&current,CCREG);
8157             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8158               // The delay slot overwrote the branch condition
8159               // Delay slot goes after the test (in order)
8160               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8161               current.u|=1;
8162               delayslot_alloc(&current,i);
8163               current.isconst=0;
8164             }
8165             else
8166             {
8167               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8168               // Alloc the branch condition register
8169               alloc_reg(&current,i-1,dops[i-1].rs1);
8170             }
8171             memcpy(&branch_regs[i-1],&current,sizeof(current));
8172             branch_regs[i-1].isconst=0;
8173             branch_regs[i-1].wasconst=0;
8174             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8175             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8176           }
8177           else
8178           // Alloc the delay slot in case the branch is taken
8179           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
8180           {
8181             memcpy(&branch_regs[i-1],&current,sizeof(current));
8182             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8183             alloc_cc(&branch_regs[i-1],i);
8184             dirty_reg(&branch_regs[i-1],CCREG);
8185             delayslot_alloc(&branch_regs[i-1],i);
8186             branch_regs[i-1].isconst=0;
8187             alloc_reg(&current,i,CCREG); // Not taken path
8188             dirty_reg(&current,CCREG);
8189             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8190           }
8191           else
8192           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
8193           {
8194             memcpy(&branch_regs[i-1],&current,sizeof(current));
8195             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8196             alloc_cc(&branch_regs[i-1],i);
8197             dirty_reg(&branch_regs[i-1],CCREG);
8198             delayslot_alloc(&branch_regs[i-1],i);
8199             branch_regs[i-1].isconst=0;
8200             alloc_reg(&current,i,CCREG); // Not taken path
8201             dirty_reg(&current,CCREG);
8202             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8203           }
8204           break;
8205         case SJUMP:
8206           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
8207           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
8208           {
8209             alloc_cc(&current,i-1);
8210             dirty_reg(&current,CCREG);
8211             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
8212               // The delay slot overwrote the branch condition
8213               // Delay slot goes after the test (in order)
8214               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
8215               current.u|=1;
8216               delayslot_alloc(&current,i);
8217               current.isconst=0;
8218             }
8219             else
8220             {
8221               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
8222               // Alloc the branch condition register
8223               alloc_reg(&current,i-1,dops[i-1].rs1);
8224             }
8225             memcpy(&branch_regs[i-1],&current,sizeof(current));
8226             branch_regs[i-1].isconst=0;
8227             branch_regs[i-1].wasconst=0;
8228             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
8229             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
8230           }
8231           else
8232           // Alloc the delay slot in case the branch is taken
8233           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
8234           {
8235             memcpy(&branch_regs[i-1],&current,sizeof(current));
8236             branch_regs[i-1].u=(branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2)|(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2)))|1;
8237             alloc_cc(&branch_regs[i-1],i);
8238             dirty_reg(&branch_regs[i-1],CCREG);
8239             delayslot_alloc(&branch_regs[i-1],i);
8240             branch_regs[i-1].isconst=0;
8241             alloc_reg(&current,i,CCREG); // Not taken path
8242             dirty_reg(&current,CCREG);
8243             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
8244           }
8245           // FIXME: BLTZAL/BGEZAL
8246           if(dops[i-1].opcode2&0x10) { // BxxZAL
8247             alloc_reg(&branch_regs[i-1],i-1,31);
8248             dirty_reg(&branch_regs[i-1],31);
8249           }
8250           break;
8251       }
8252
8253       if (dops[i-1].is_ujump)
8254       {
8255         if(dops[i-1].rt1==31) // JAL/JALR
8256         {
8257           // Subroutine call will return here, don't alloc any registers
8258           current.dirty=0;
8259           clear_all_regs(current.regmap);
8260           alloc_reg(&current,i,CCREG);
8261           dirty_reg(&current,CCREG);
8262         }
8263         else if(i+1<slen)
8264         {
8265           // Internal branch will jump here, match registers to caller
8266           current.dirty=0;
8267           clear_all_regs(current.regmap);
8268           alloc_reg(&current,i,CCREG);
8269           dirty_reg(&current,CCREG);
8270           for(j=i-1;j>=0;j--)
8271           {
8272             if(ba[j]==start+i*4+4) {
8273               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
8274               current.dirty=branch_regs[j].dirty;
8275               break;
8276             }
8277           }
8278           while(j>=0) {
8279             if(ba[j]==start+i*4+4) {
8280               for(hr=0;hr<HOST_REGS;hr++) {
8281                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
8282                   current.regmap[hr]=-1;
8283                 }
8284                 current.dirty&=branch_regs[j].dirty;
8285               }
8286             }
8287             j--;
8288           }
8289         }
8290       }
8291     }
8292
8293     // Count cycles in between branches
8294     ccadj[i] = CLOCK_ADJUST(cc);
8295     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
8296     {
8297       cc=0;
8298     }
8299 #if !defined(DRC_DBG)
8300     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
8301     {
8302       // this should really be removed since the real stalls have been implemented,
8303       // but doing so causes sizeable perf regression against the older version
8304       u_int gtec = gte_cycletab[source[i] & 0x3f];
8305       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
8306     }
8307     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
8308     {
8309       cc+=4;
8310     }
8311     else if(dops[i].itype==C2LS)
8312     {
8313       // same as with C2OP
8314       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
8315     }
8316 #endif
8317     else
8318     {
8319       cc++;
8320     }
8321
8322     if(!dops[i].is_ds) {
8323       regs[i].dirty=current.dirty;
8324       regs[i].isconst=current.isconst;
8325       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
8326     }
8327     for(hr=0;hr<HOST_REGS;hr++) {
8328       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
8329         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
8330           regs[i].wasconst&=~(1<<hr);
8331         }
8332       }
8333     }
8334     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
8335     regs[i].waswritten=current.waswritten;
8336   }
8337
8338   /* Pass 4 - Cull unused host registers */
8339
8340   uint64_t nr=0;
8341
8342   for (i=slen-1;i>=0;i--)
8343   {
8344     int hr;
8345     if(dops[i].is_jump)
8346     {
8347       if(ba[i]<start || ba[i]>=(start+slen*4))
8348       {
8349         // Branch out of this block, don't need anything
8350         nr=0;
8351       }
8352       else
8353       {
8354         // Internal branch
8355         // Need whatever matches the target
8356         nr=0;
8357         int t=(ba[i]-start)>>2;
8358         for(hr=0;hr<HOST_REGS;hr++)
8359         {
8360           if(regs[i].regmap_entry[hr]>=0) {
8361             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
8362           }
8363         }
8364       }
8365       // Conditional branch may need registers for following instructions
8366       if (!dops[i].is_ujump)
8367       {
8368         if(i<slen-2) {
8369           nr|=needed_reg[i+2];
8370           for(hr=0;hr<HOST_REGS;hr++)
8371           {
8372             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
8373             //if((regmap_entry[i+2][hr])>=0) if(!((nr>>hr)&1)) printf("%x-bogus(%d=%d)\n",start+i*4,hr,regmap_entry[i+2][hr]);
8374           }
8375         }
8376       }
8377       // Don't need stuff which is overwritten
8378       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8379       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8380       // Merge in delay slot
8381       for(hr=0;hr<HOST_REGS;hr++)
8382       {
8383         if(dops[i+1].rt1&&dops[i+1].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8384         if(dops[i+1].rt2&&dops[i+1].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8385         if(dops[i+1].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8386         if(dops[i+1].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8387         if(dops[i+1].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8388         if(dops[i+1].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8389         if(ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
8390           if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8391           if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8392         }
8393         if(dops[i+1].is_store) {
8394           if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8395           if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8396         }
8397       }
8398     }
8399     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8400     {
8401       // SYSCALL instruction (software interrupt)
8402       nr=0;
8403     }
8404     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8405     {
8406       // ERET instruction (return from interrupt)
8407       nr=0;
8408     }
8409     else // Non-branch
8410     {
8411       if(i<slen-1) {
8412         for(hr=0;hr<HOST_REGS;hr++) {
8413           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
8414           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
8415           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
8416           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
8417         }
8418       }
8419     }
8420     for(hr=0;hr<HOST_REGS;hr++)
8421     {
8422       // Overwritten registers are not needed
8423       if(dops[i].rt1&&dops[i].rt1==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8424       if(dops[i].rt2&&dops[i].rt2==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8425       if(FTEMP==(regs[i].regmap[hr]&63)) nr&=~(1<<hr);
8426       // Source registers are needed
8427       if(dops[i].rs1==regmap_pre[i][hr]) nr|=1<<hr;
8428       if(dops[i].rs2==regmap_pre[i][hr]) nr|=1<<hr;
8429       if(dops[i].rs1==regs[i].regmap_entry[hr]) nr|=1<<hr;
8430       if(dops[i].rs2==regs[i].regmap_entry[hr]) nr|=1<<hr;
8431       if(ram_offset && (dops[i].is_load || dops[i].is_store)) {
8432         if(regmap_pre[i][hr]==ROREG) nr|=1<<hr;
8433         if(regs[i].regmap_entry[hr]==ROREG) nr|=1<<hr;
8434       }
8435       if(dops[i].is_store) {
8436         if(regmap_pre[i][hr]==INVCP) nr|=1<<hr;
8437         if(regs[i].regmap_entry[hr]==INVCP) nr|=1<<hr;
8438       }
8439       // Don't store a register immediately after writing it,
8440       // may prevent dual-issue.
8441       // But do so if this is a branch target, otherwise we
8442       // might have to load the register before the branch.
8443       if(i>0&&!dops[i].bt&&((regs[i].wasdirty>>hr)&1)) {
8444         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
8445           if(dops[i-1].rt1==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8446           if(dops[i-1].rt2==(regmap_pre[i][hr]&63)) nr|=1<<hr;
8447         }
8448         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
8449           if(dops[i-1].rt1==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8450           if(dops[i-1].rt2==(regs[i].regmap_entry[hr]&63)) nr|=1<<hr;
8451         }
8452       }
8453     }
8454     // Cycle count is needed at branches.  Assume it is needed at the target too.
8455     if(i==0||dops[i].bt||dops[i].itype==CJUMP||dops[i].itype==SPAN) {
8456       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8457       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
8458     }
8459     // Save it
8460     needed_reg[i]=nr;
8461
8462     // Deallocate unneeded registers
8463     for(hr=0;hr<HOST_REGS;hr++)
8464     {
8465       if(!((nr>>hr)&1)) {
8466         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
8467         if(dops[i].is_jump)
8468         {
8469           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
8470           if (dops[i+1].is_load || dops[i+1].is_store)
8471             map1 = ROREG;
8472           if (dops[i+1].is_store)
8473             map2 = INVCP;
8474           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
8475             temp = FTEMP;
8476           if((regs[i].regmap[hr]&63)!=dops[i].rs1 && (regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8477              (regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8478              (regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8479              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
8480              (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=PTEMP &&
8481              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
8482              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
8483              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
8484           {
8485             regs[i].regmap[hr]=-1;
8486             regs[i].isconst&=~(1<<hr);
8487             if((branch_regs[i].regmap[hr]&63)!=dops[i].rs1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rs2 &&
8488                (branch_regs[i].regmap[hr]&63)!=dops[i].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8489                (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt1 && (branch_regs[i].regmap[hr]&63)!=dops[i+1].rt2 &&
8490                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
8491                (branch_regs[i].regmap[hr]&63)!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
8492                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
8493                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
8494                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
8495             {
8496               branch_regs[i].regmap[hr]=-1;
8497               branch_regs[i].regmap_entry[hr]=-1;
8498               if (!dops[i].is_ujump)
8499               {
8500                 if (i < slen-2) {
8501                   regmap_pre[i+2][hr]=-1;
8502                   regs[i+2].wasconst&=~(1<<hr);
8503                 }
8504               }
8505             }
8506           }
8507         }
8508         else
8509         {
8510           // Non-branch
8511           if(i>0)
8512           {
8513             int map1 = -1, map2 = -1, temp=-1;
8514             if (dops[i].is_load || dops[i].is_store)
8515               map1 = ROREG;
8516             if (dops[i].is_store)
8517               map2 = INVCP;
8518             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8519               temp = FTEMP;
8520             if((regs[i].regmap[hr]&63)!=dops[i].rt1 && (regs[i].regmap[hr]&63)!=dops[i].rt2 &&
8521                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8522                (regs[i].regmap[hr]&63)!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8523                //(dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG)
8524                regs[i].regmap[hr] != CCREG)
8525             {
8526               if(i<slen-1&&!dops[i].is_ds) {
8527                 assert(regs[i].regmap[hr]<64);
8528                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8529                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8530                 {
8531                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8532                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8533                 }
8534                 regmap_pre[i+1][hr]=-1;
8535                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8536                 regs[i+1].wasconst&=~(1<<hr);
8537               }
8538               regs[i].regmap[hr]=-1;
8539               regs[i].isconst&=~(1<<hr);
8540             }
8541           }
8542         }
8543       } // if needed
8544     } // for hr
8545   }
8546
8547   /* Pass 5 - Pre-allocate registers */
8548
8549   // If a register is allocated during a loop, try to allocate it for the
8550   // entire loop, if possible.  This avoids loading/storing registers
8551   // inside of the loop.
8552
8553   signed char f_regmap[HOST_REGS];
8554   clear_all_regs(f_regmap);
8555   for(i=0;i<slen-1;i++)
8556   {
8557     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8558     {
8559       if(ba[i]>=start && ba[i]<(start+i*4))
8560       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8561       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8562       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8563       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8564       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8565       {
8566         int t=(ba[i]-start)>>2;
8567         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8568         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8569         for(hr=0;hr<HOST_REGS;hr++)
8570         {
8571           if(regs[i].regmap[hr]>=0) {
8572             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8573               // dealloc old register
8574               int n;
8575               for(n=0;n<HOST_REGS;n++)
8576               {
8577                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8578               }
8579               // and alloc new one
8580               f_regmap[hr]=regs[i].regmap[hr];
8581             }
8582           }
8583           if(branch_regs[i].regmap[hr]>=0) {
8584             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8585               // dealloc old register
8586               int n;
8587               for(n=0;n<HOST_REGS;n++)
8588               {
8589                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8590               }
8591               // and alloc new one
8592               f_regmap[hr]=branch_regs[i].regmap[hr];
8593             }
8594           }
8595           if(dops[i].ooo) {
8596             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8597               f_regmap[hr]=branch_regs[i].regmap[hr];
8598           }else{
8599             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8600               f_regmap[hr]=branch_regs[i].regmap[hr];
8601           }
8602           // Avoid dirty->clean transition
8603           #ifdef DESTRUCTIVE_WRITEBACK
8604           if(t>0) if(get_reg(regmap_pre[t],f_regmap[hr])>=0) if((regs[t].wasdirty>>get_reg(regmap_pre[t],f_regmap[hr]))&1) f_regmap[hr]=-1;
8605           #endif
8606           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8607           // case above, however it's always a good idea.  We can't hoist the
8608           // load if the register was already allocated, so there's no point
8609           // wasting time analyzing most of these cases.  It only "succeeds"
8610           // when the mapping was different and the load can be replaced with
8611           // a mov, which is of negligible benefit.  So such cases are
8612           // skipped below.
8613           if(f_regmap[hr]>0) {
8614             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8615               int r=f_regmap[hr];
8616               for(j=t;j<=i;j++)
8617               {
8618                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8619                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8620                 assert(r < 64);
8621                 if(regs[j].regmap[hr]==f_regmap[hr]&&(f_regmap[hr]&63)<TEMPREG) {
8622                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8623                   int k;
8624                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8625                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8626                     if(r>63) {
8627                       if(get_reg(regs[i].regmap,r&63)<0) break;
8628                       if(get_reg(branch_regs[i].regmap,r&63)<0) break;
8629                     }
8630                     k=i;
8631                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8632                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8633                         //printf("no free regs for store %x\n",start+(k-1)*4);
8634                         break;
8635                       }
8636                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8637                         //printf("no-match due to different register\n");
8638                         break;
8639                       }
8640                       if (dops[k-2].is_jump) {
8641                         //printf("no-match due to branch\n");
8642                         break;
8643                       }
8644                       // call/ret fast path assumes no registers allocated
8645                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8646                         break;
8647                       }
8648                       assert(r < 64);
8649                       k--;
8650                     }
8651                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8652                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8653                       while(k<i) {
8654                         regs[k].regmap_entry[hr]=f_regmap[hr];
8655                         regs[k].regmap[hr]=f_regmap[hr];
8656                         regmap_pre[k+1][hr]=f_regmap[hr];
8657                         regs[k].wasdirty&=~(1<<hr);
8658                         regs[k].dirty&=~(1<<hr);
8659                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8660                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8661                         regs[k].wasconst&=~(1<<hr);
8662                         regs[k].isconst&=~(1<<hr);
8663                         k++;
8664                       }
8665                     }
8666                     else {
8667                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8668                       break;
8669                     }
8670                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8671                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8672                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8673                       regs[i].regmap_entry[hr]=f_regmap[hr];
8674                       regs[i].regmap[hr]=f_regmap[hr];
8675                       regs[i].wasdirty&=~(1<<hr);
8676                       regs[i].dirty&=~(1<<hr);
8677                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8678                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8679                       regs[i].wasconst&=~(1<<hr);
8680                       regs[i].isconst&=~(1<<hr);
8681                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8682                       branch_regs[i].wasdirty&=~(1<<hr);
8683                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8684                       branch_regs[i].regmap[hr]=f_regmap[hr];
8685                       branch_regs[i].dirty&=~(1<<hr);
8686                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8687                       branch_regs[i].wasconst&=~(1<<hr);
8688                       branch_regs[i].isconst&=~(1<<hr);
8689                       if (!dops[i].is_ujump) {
8690                         regmap_pre[i+2][hr]=f_regmap[hr];
8691                         regs[i+2].wasdirty&=~(1<<hr);
8692                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8693                       }
8694                     }
8695                   }
8696                   for(k=t;k<j;k++) {
8697                     // Alloc register clean at beginning of loop,
8698                     // but may dirty it in pass 6
8699                     regs[k].regmap_entry[hr]=f_regmap[hr];
8700                     regs[k].regmap[hr]=f_regmap[hr];
8701                     regs[k].dirty&=~(1<<hr);
8702                     regs[k].wasconst&=~(1<<hr);
8703                     regs[k].isconst&=~(1<<hr);
8704                     if (dops[k].is_jump) {
8705                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8706                       branch_regs[k].regmap[hr]=f_regmap[hr];
8707                       branch_regs[k].dirty&=~(1<<hr);
8708                       branch_regs[k].wasconst&=~(1<<hr);
8709                       branch_regs[k].isconst&=~(1<<hr);
8710                       if (!dops[k].is_ujump) {
8711                         regmap_pre[k+2][hr]=f_regmap[hr];
8712                         regs[k+2].wasdirty&=~(1<<hr);
8713                       }
8714                     }
8715                     else
8716                     {
8717                       regmap_pre[k+1][hr]=f_regmap[hr];
8718                       regs[k+1].wasdirty&=~(1<<hr);
8719                     }
8720                   }
8721                   if(regs[j].regmap[hr]==f_regmap[hr])
8722                     regs[j].regmap_entry[hr]=f_regmap[hr];
8723                   break;
8724                 }
8725                 if(j==i) break;
8726                 if(regs[j].regmap[hr]>=0)
8727                   break;
8728                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8729                   //printf("no-match due to different register\n");
8730                   break;
8731                 }
8732                 if (dops[j].is_ujump)
8733                 {
8734                   // Stop on unconditional branch
8735                   break;
8736                 }
8737                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8738                 {
8739                   if(dops[j].ooo) {
8740                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8741                       break;
8742                   }else{
8743                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8744                       break;
8745                   }
8746                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8747                     //printf("no-match due to different register (branch)\n");
8748                     break;
8749                   }
8750                 }
8751                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8752                   //printf("No free regs for store %x\n",start+j*4);
8753                   break;
8754                 }
8755                 assert(f_regmap[hr]<64);
8756               }
8757             }
8758           }
8759         }
8760       }
8761     }else{
8762       // Non branch or undetermined branch target
8763       for(hr=0;hr<HOST_REGS;hr++)
8764       {
8765         if(hr!=EXCLUDE_REG) {
8766           if(regs[i].regmap[hr]>=0) {
8767             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8768               // dealloc old register
8769               int n;
8770               for(n=0;n<HOST_REGS;n++)
8771               {
8772                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8773               }
8774               // and alloc new one
8775               f_regmap[hr]=regs[i].regmap[hr];
8776             }
8777           }
8778         }
8779       }
8780       // Try to restore cycle count at branch targets
8781       if(dops[i].bt) {
8782         for(j=i;j<slen-1;j++) {
8783           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8784           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8785             //printf("no free regs for store %x\n",start+j*4);
8786             break;
8787           }
8788         }
8789         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8790           int k=i;
8791           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8792           while(k<j) {
8793             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8794             regs[k].regmap[HOST_CCREG]=CCREG;
8795             regmap_pre[k+1][HOST_CCREG]=CCREG;
8796             regs[k+1].wasdirty|=1<<HOST_CCREG;
8797             regs[k].dirty|=1<<HOST_CCREG;
8798             regs[k].wasconst&=~(1<<HOST_CCREG);
8799             regs[k].isconst&=~(1<<HOST_CCREG);
8800             k++;
8801           }
8802           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8803         }
8804         // Work backwards from the branch target
8805         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8806         {
8807           //printf("Extend backwards\n");
8808           int k;
8809           k=i;
8810           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8811             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8812               //printf("no free regs for store %x\n",start+(k-1)*4);
8813               break;
8814             }
8815             k--;
8816           }
8817           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8818             //printf("Extend CC, %x ->\n",start+k*4);
8819             while(k<=i) {
8820               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8821               regs[k].regmap[HOST_CCREG]=CCREG;
8822               regmap_pre[k+1][HOST_CCREG]=CCREG;
8823               regs[k+1].wasdirty|=1<<HOST_CCREG;
8824               regs[k].dirty|=1<<HOST_CCREG;
8825               regs[k].wasconst&=~(1<<HOST_CCREG);
8826               regs[k].isconst&=~(1<<HOST_CCREG);
8827               k++;
8828             }
8829           }
8830           else {
8831             //printf("Fail Extend CC, %x ->\n",start+k*4);
8832           }
8833         }
8834       }
8835       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8836          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8837          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8838       {
8839         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8840       }
8841     }
8842   }
8843
8844   // This allocates registers (if possible) one instruction prior
8845   // to use, which can avoid a load-use penalty on certain CPUs.
8846   for(i=0;i<slen-1;i++)
8847   {
8848     if (!i || !dops[i-1].is_jump)
8849     {
8850       if(!dops[i+1].bt)
8851       {
8852         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8853            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8854         {
8855           if(dops[i+1].rs1) {
8856             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8857             {
8858               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8859               {
8860                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8861                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8862                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8863                 regs[i].isconst&=~(1<<hr);
8864                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8865                 constmap[i][hr]=constmap[i+1][hr];
8866                 regs[i+1].wasdirty&=~(1<<hr);
8867                 regs[i].dirty&=~(1<<hr);
8868               }
8869             }
8870           }
8871           if(dops[i+1].rs2) {
8872             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8873             {
8874               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8875               {
8876                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8877                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8878                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8879                 regs[i].isconst&=~(1<<hr);
8880                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8881                 constmap[i][hr]=constmap[i+1][hr];
8882                 regs[i+1].wasdirty&=~(1<<hr);
8883                 regs[i].dirty&=~(1<<hr);
8884               }
8885             }
8886           }
8887           // Preload target address for load instruction (non-constant)
8888           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8889             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8890             {
8891               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8892               {
8893                 regs[i].regmap[hr]=dops[i+1].rs1;
8894                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8895                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8896                 regs[i].isconst&=~(1<<hr);
8897                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8898                 constmap[i][hr]=constmap[i+1][hr];
8899                 regs[i+1].wasdirty&=~(1<<hr);
8900                 regs[i].dirty&=~(1<<hr);
8901               }
8902             }
8903           }
8904           // Load source into target register
8905           if(dops[i+1].lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8906             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8907             {
8908               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8909               {
8910                 regs[i].regmap[hr]=dops[i+1].rs1;
8911                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8912                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8913                 regs[i].isconst&=~(1<<hr);
8914                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8915                 constmap[i][hr]=constmap[i+1][hr];
8916                 regs[i+1].wasdirty&=~(1<<hr);
8917                 regs[i].dirty&=~(1<<hr);
8918               }
8919             }
8920           }
8921           // Address for store instruction (non-constant)
8922           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8923              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8924             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8925               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8926               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8927               else {regs[i+1].regmap[hr]=AGEN1+((i+1)&1);regs[i+1].isconst&=~(1<<hr);}
8928               assert(hr>=0);
8929               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8930               {
8931                 regs[i].regmap[hr]=dops[i+1].rs1;
8932                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8933                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8934                 regs[i].isconst&=~(1<<hr);
8935                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8936                 constmap[i][hr]=constmap[i+1][hr];
8937                 regs[i+1].wasdirty&=~(1<<hr);
8938                 regs[i].dirty&=~(1<<hr);
8939               }
8940             }
8941           }
8942           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8943             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8944               int nr;
8945               hr=get_reg(regs[i+1].regmap,FTEMP);
8946               assert(hr>=0);
8947               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8948               {
8949                 regs[i].regmap[hr]=dops[i+1].rs1;
8950                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8951                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8952                 regs[i].isconst&=~(1<<hr);
8953                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8954                 constmap[i][hr]=constmap[i+1][hr];
8955                 regs[i+1].wasdirty&=~(1<<hr);
8956                 regs[i].dirty&=~(1<<hr);
8957               }
8958               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8959               {
8960                 // move it to another register
8961                 regs[i+1].regmap[hr]=-1;
8962                 regmap_pre[i+2][hr]=-1;
8963                 regs[i+1].regmap[nr]=FTEMP;
8964                 regmap_pre[i+2][nr]=FTEMP;
8965                 regs[i].regmap[nr]=dops[i+1].rs1;
8966                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8967                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8968                 regs[i].isconst&=~(1<<nr);
8969                 regs[i+1].isconst&=~(1<<nr);
8970                 regs[i].dirty&=~(1<<nr);
8971                 regs[i+1].wasdirty&=~(1<<nr);
8972                 regs[i+1].dirty&=~(1<<nr);
8973                 regs[i+2].wasdirty&=~(1<<nr);
8974               }
8975             }
8976           }
8977           if(dops[i+1].itype==LOAD||dops[i+1].itype==LOADLR||dops[i+1].itype==STORE||dops[i+1].itype==STORELR/*||dops[i+1].itype==C1LS||||dops[i+1].itype==C2LS*/) {
8978             if(dops[i+1].itype==LOAD)
8979               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8980             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8981               hr=get_reg(regs[i+1].regmap,FTEMP);
8982             if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SWC1/SDC1/SWC2/SDC2
8983               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8984               if(hr<0) hr=get_reg(regs[i+1].regmap,-1);
8985             }
8986             if(hr>=0&&regs[i].regmap[hr]<0) {
8987               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8988               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8989                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8990                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8991                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8992                 regs[i].isconst&=~(1<<hr);
8993                 regs[i+1].wasdirty&=~(1<<hr);
8994                 regs[i].dirty&=~(1<<hr);
8995               }
8996             }
8997           }
8998         }
8999       }
9000     }
9001   }
9002
9003   /* Pass 6 - Optimize clean/dirty state */
9004   clean_registers(0,slen-1,1);
9005
9006   /* Pass 7 - Identify 32-bit registers */
9007   for (i=slen-1;i>=0;i--)
9008   {
9009     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9010     {
9011       // Conditional branch
9012       if((source[i]>>16)!=0x1000&&i<slen-2) {
9013         // Mark this address as a branch target since it may be called
9014         // upon return from interrupt
9015         dops[i+2].bt=1;
9016       }
9017     }
9018   }
9019
9020   if(dops[slen-1].itype==SPAN) {
9021     dops[slen-1].bt=1; // Mark as a branch target so instruction can restart after exception
9022   }
9023
9024 #ifdef DISASM
9025   /* Debug/disassembly */
9026   for(i=0;i<slen;i++)
9027   {
9028     printf("U:");
9029     int r;
9030     for(r=1;r<=CCREG;r++) {
9031       if((unneeded_reg[i]>>r)&1) {
9032         if(r==HIREG) printf(" HI");
9033         else if(r==LOREG) printf(" LO");
9034         else printf(" r%d",r);
9035       }
9036     }
9037     printf("\n");
9038     #if defined(__i386__) || defined(__x86_64__)
9039     printf("pre: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7]);
9040     #endif
9041     #ifdef __arm__
9042     printf("pre: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regmap_pre[i][0],regmap_pre[i][1],regmap_pre[i][2],regmap_pre[i][3],regmap_pre[i][4],regmap_pre[i][5],regmap_pre[i][6],regmap_pre[i][7],regmap_pre[i][8],regmap_pre[i][9],regmap_pre[i][10],regmap_pre[i][12]);
9043     #endif
9044     #if defined(__i386__) || defined(__x86_64__)
9045     printf("needs: ");
9046     if(needed_reg[i]&1) printf("eax ");
9047     if((needed_reg[i]>>1)&1) printf("ecx ");
9048     if((needed_reg[i]>>2)&1) printf("edx ");
9049     if((needed_reg[i]>>3)&1) printf("ebx ");
9050     if((needed_reg[i]>>5)&1) printf("ebp ");
9051     if((needed_reg[i]>>6)&1) printf("esi ");
9052     if((needed_reg[i]>>7)&1) printf("edi ");
9053     printf("\n");
9054     printf("entry: eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7]);
9055     printf("dirty: ");
9056     if(regs[i].wasdirty&1) printf("eax ");
9057     if((regs[i].wasdirty>>1)&1) printf("ecx ");
9058     if((regs[i].wasdirty>>2)&1) printf("edx ");
9059     if((regs[i].wasdirty>>3)&1) printf("ebx ");
9060     if((regs[i].wasdirty>>5)&1) printf("ebp ");
9061     if((regs[i].wasdirty>>6)&1) printf("esi ");
9062     if((regs[i].wasdirty>>7)&1) printf("edi ");
9063     #endif
9064     #ifdef __arm__
9065     printf("entry: r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d\n",regs[i].regmap_entry[0],regs[i].regmap_entry[1],regs[i].regmap_entry[2],regs[i].regmap_entry[3],regs[i].regmap_entry[4],regs[i].regmap_entry[5],regs[i].regmap_entry[6],regs[i].regmap_entry[7],regs[i].regmap_entry[8],regs[i].regmap_entry[9],regs[i].regmap_entry[10],regs[i].regmap_entry[12]);
9066     printf("dirty: ");
9067     if(regs[i].wasdirty&1) printf("r0 ");
9068     if((regs[i].wasdirty>>1)&1) printf("r1 ");
9069     if((regs[i].wasdirty>>2)&1) printf("r2 ");
9070     if((regs[i].wasdirty>>3)&1) printf("r3 ");
9071     if((regs[i].wasdirty>>4)&1) printf("r4 ");
9072     if((regs[i].wasdirty>>5)&1) printf("r5 ");
9073     if((regs[i].wasdirty>>6)&1) printf("r6 ");
9074     if((regs[i].wasdirty>>7)&1) printf("r7 ");
9075     if((regs[i].wasdirty>>8)&1) printf("r8 ");
9076     if((regs[i].wasdirty>>9)&1) printf("r9 ");
9077     if((regs[i].wasdirty>>10)&1) printf("r10 ");
9078     if((regs[i].wasdirty>>12)&1) printf("r12 ");
9079     #endif
9080     printf("\n");
9081     disassemble_inst(i);
9082     //printf ("ccadj[%d] = %d\n",i,ccadj[i]);
9083     #if defined(__i386__) || defined(__x86_64__)
9084     printf("eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7]);
9085     if(regs[i].dirty&1) printf("eax ");
9086     if((regs[i].dirty>>1)&1) printf("ecx ");
9087     if((regs[i].dirty>>2)&1) printf("edx ");
9088     if((regs[i].dirty>>3)&1) printf("ebx ");
9089     if((regs[i].dirty>>5)&1) printf("ebp ");
9090     if((regs[i].dirty>>6)&1) printf("esi ");
9091     if((regs[i].dirty>>7)&1) printf("edi ");
9092     #endif
9093     #ifdef __arm__
9094     printf("r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",regs[i].regmap[0],regs[i].regmap[1],regs[i].regmap[2],regs[i].regmap[3],regs[i].regmap[4],regs[i].regmap[5],regs[i].regmap[6],regs[i].regmap[7],regs[i].regmap[8],regs[i].regmap[9],regs[i].regmap[10],regs[i].regmap[12]);
9095     if(regs[i].dirty&1) printf("r0 ");
9096     if((regs[i].dirty>>1)&1) printf("r1 ");
9097     if((regs[i].dirty>>2)&1) printf("r2 ");
9098     if((regs[i].dirty>>3)&1) printf("r3 ");
9099     if((regs[i].dirty>>4)&1) printf("r4 ");
9100     if((regs[i].dirty>>5)&1) printf("r5 ");
9101     if((regs[i].dirty>>6)&1) printf("r6 ");
9102     if((regs[i].dirty>>7)&1) printf("r7 ");
9103     if((regs[i].dirty>>8)&1) printf("r8 ");
9104     if((regs[i].dirty>>9)&1) printf("r9 ");
9105     if((regs[i].dirty>>10)&1) printf("r10 ");
9106     if((regs[i].dirty>>12)&1) printf("r12 ");
9107     #endif
9108     printf("\n");
9109     if(regs[i].isconst) {
9110       printf("constants: ");
9111       #if defined(__i386__) || defined(__x86_64__)
9112       if(regs[i].isconst&1) printf("eax=%x ",(u_int)constmap[i][0]);
9113       if((regs[i].isconst>>1)&1) printf("ecx=%x ",(u_int)constmap[i][1]);
9114       if((regs[i].isconst>>2)&1) printf("edx=%x ",(u_int)constmap[i][2]);
9115       if((regs[i].isconst>>3)&1) printf("ebx=%x ",(u_int)constmap[i][3]);
9116       if((regs[i].isconst>>5)&1) printf("ebp=%x ",(u_int)constmap[i][5]);
9117       if((regs[i].isconst>>6)&1) printf("esi=%x ",(u_int)constmap[i][6]);
9118       if((regs[i].isconst>>7)&1) printf("edi=%x ",(u_int)constmap[i][7]);
9119       #endif
9120       #if defined(__arm__) || defined(__aarch64__)
9121       int r;
9122       for (r = 0; r < ARRAY_SIZE(constmap[i]); r++)
9123         if ((regs[i].isconst >> r) & 1)
9124           printf(" r%d=%x", r, (u_int)constmap[i][r]);
9125       #endif
9126       printf("\n");
9127     }
9128     if(dops[i].is_jump) {
9129       #if defined(__i386__) || defined(__x86_64__)
9130       printf("branch(%d): eax=%d ecx=%d edx=%d ebx=%d ebp=%d esi=%d edi=%d dirty: ",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7]);
9131       if(branch_regs[i].dirty&1) printf("eax ");
9132       if((branch_regs[i].dirty>>1)&1) printf("ecx ");
9133       if((branch_regs[i].dirty>>2)&1) printf("edx ");
9134       if((branch_regs[i].dirty>>3)&1) printf("ebx ");
9135       if((branch_regs[i].dirty>>5)&1) printf("ebp ");
9136       if((branch_regs[i].dirty>>6)&1) printf("esi ");
9137       if((branch_regs[i].dirty>>7)&1) printf("edi ");
9138       #endif
9139       #ifdef __arm__
9140       printf("branch(%d): r0=%d r1=%d r2=%d r3=%d r4=%d r5=%d r6=%d r7=%d r8=%d r9=%d r10=%d r12=%d dirty: ",i,branch_regs[i].regmap[0],branch_regs[i].regmap[1],branch_regs[i].regmap[2],branch_regs[i].regmap[3],branch_regs[i].regmap[4],branch_regs[i].regmap[5],branch_regs[i].regmap[6],branch_regs[i].regmap[7],branch_regs[i].regmap[8],branch_regs[i].regmap[9],branch_regs[i].regmap[10],branch_regs[i].regmap[12]);
9141       if(branch_regs[i].dirty&1) printf("r0 ");
9142       if((branch_regs[i].dirty>>1)&1) printf("r1 ");
9143       if((branch_regs[i].dirty>>2)&1) printf("r2 ");
9144       if((branch_regs[i].dirty>>3)&1) printf("r3 ");
9145       if((branch_regs[i].dirty>>4)&1) printf("r4 ");
9146       if((branch_regs[i].dirty>>5)&1) printf("r5 ");
9147       if((branch_regs[i].dirty>>6)&1) printf("r6 ");
9148       if((branch_regs[i].dirty>>7)&1) printf("r7 ");
9149       if((branch_regs[i].dirty>>8)&1) printf("r8 ");
9150       if((branch_regs[i].dirty>>9)&1) printf("r9 ");
9151       if((branch_regs[i].dirty>>10)&1) printf("r10 ");
9152       if((branch_regs[i].dirty>>12)&1) printf("r12 ");
9153       #endif
9154     }
9155   }
9156 #endif // DISASM
9157
9158   /* Pass 8 - Assembly */
9159   linkcount=0;stubcount=0;
9160   ds=0;is_delayslot=0;
9161   u_int dirty_pre=0;
9162   void *beginning=start_block();
9163   if((u_int)addr&1) {
9164     ds=1;
9165     pagespan_ds();
9166   }
9167   void *instr_addr0_override = NULL;
9168
9169   if (start == 0x80030000) {
9170     // nasty hack for the fastbios thing
9171     // override block entry to this code
9172     instr_addr0_override = out;
9173     emit_movimm(start,0);
9174     // abuse io address var as a flag that we
9175     // have already returned here once
9176     emit_readword(&address,1);
9177     emit_writeword(0,&pcaddr);
9178     emit_writeword(0,&address);
9179     emit_cmp(0,1);
9180     #ifdef __aarch64__
9181     emit_jeq(out + 4*2);
9182     emit_far_jump(new_dyna_leave);
9183     #else
9184     emit_jne(new_dyna_leave);
9185     #endif
9186   }
9187   for(i=0;i<slen;i++)
9188   {
9189     //if(ds) printf("ds: ");
9190     disassemble_inst(i);
9191     if(ds) {
9192       ds=0; // Skip delay slot
9193       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9194       instr_addr[i] = NULL;
9195     } else {
9196       speculate_register_values(i);
9197       #ifndef DESTRUCTIVE_WRITEBACK
9198       if (i < 2 || !dops[i-2].is_ujump)
9199       {
9200         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9201       }
9202       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9203         dirty_pre=branch_regs[i].dirty;
9204       }else{
9205         dirty_pre=regs[i].dirty;
9206       }
9207       #endif
9208       // write back
9209       if (i < 2 || !dops[i-2].is_ujump)
9210       {
9211         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9212         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9213       }
9214       // branch target entry point
9215       instr_addr[i] = out;
9216       assem_debug("<->\n");
9217       drc_dbg_emit_do_cmp(i, ccadj[i]);
9218       if (clear_hack_addr) {
9219         emit_movimm(0, 0);
9220         emit_writeword(0, &hack_addr);
9221         clear_hack_addr = 0;
9222       }
9223
9224       // load regs
9225       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9226         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9227       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9228       address_generation(i,&regs[i],regs[i].regmap_entry);
9229       load_consts(regmap_pre[i],regs[i].regmap,i);
9230       if(dops[i].is_jump)
9231       {
9232         // Load the delay slot registers if necessary
9233         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2&&(dops[i+1].rs1!=dops[i].rt1||dops[i].rt1==0))
9234           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9235         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2&&(dops[i+1].rs2!=dops[i].rt1||dops[i].rt1==0))
9236           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9237         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9238           load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9239         if (dops[i+1].is_store)
9240           load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9241       }
9242       else if(i+1<slen)
9243       {
9244         // Preload registers for following instruction
9245         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9246           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9247             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9248         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9249           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9250             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9251       }
9252       // TODO: if(is_ooo(i)) address_generation(i+1);
9253       if (!dops[i].is_jump || dops[i].itype == CJUMP)
9254         load_regs(regs[i].regmap_entry,regs[i].regmap,CCREG,CCREG);
9255       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9256         load_regs(regs[i].regmap_entry,regs[i].regmap,ROREG,ROREG);
9257       if (dops[i].is_store)
9258         load_regs(regs[i].regmap_entry,regs[i].regmap,INVCP,INVCP);
9259
9260       ds = assemble(i, &regs[i], ccadj[i]);
9261
9262       if (dops[i].is_ujump)
9263         literal_pool(1024);
9264       else
9265         literal_pool_jumpover(256);
9266     }
9267   }
9268
9269   assert(slen > 0);
9270   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9271     // no ending needed for this block since INTCALL never returns
9272   }
9273   // If the block did not end with an unconditional branch,
9274   // add a jump to the next instruction.
9275   else if (i > 1) {
9276     if (!dops[i-2].is_ujump && dops[i-1].itype != SPAN) {
9277       assert(!dops[i-1].is_jump);
9278       assert(i==slen);
9279       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9280         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9281         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9282           emit_loadreg(CCREG,HOST_CCREG);
9283         emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9284       }
9285       else
9286       {
9287         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9288         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9289       }
9290       add_to_linker(out,start+i*4,0);
9291       emit_jmp(0);
9292     }
9293   }
9294   else
9295   {
9296     assert(i>0);
9297     assert(!dops[i-1].is_jump);
9298     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9299     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9300       emit_loadreg(CCREG,HOST_CCREG);
9301     emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9302     add_to_linker(out,start+i*4,0);
9303     emit_jmp(0);
9304   }
9305
9306   // TODO: delay slot stubs?
9307   // Stubs
9308   for(i=0;i<stubcount;i++)
9309   {
9310     switch(stubs[i].type)
9311     {
9312       case LOADB_STUB:
9313       case LOADH_STUB:
9314       case LOADW_STUB:
9315       case LOADD_STUB:
9316       case LOADBU_STUB:
9317       case LOADHU_STUB:
9318         do_readstub(i);break;
9319       case STOREB_STUB:
9320       case STOREH_STUB:
9321       case STOREW_STUB:
9322       case STORED_STUB:
9323         do_writestub(i);break;
9324       case CC_STUB:
9325         do_ccstub(i);break;
9326       case INVCODE_STUB:
9327         do_invstub(i);break;
9328       case FP_STUB:
9329         do_cop1stub(i);break;
9330       case STORELR_STUB:
9331         do_unalignedwritestub(i);break;
9332     }
9333   }
9334
9335   if (instr_addr0_override)
9336     instr_addr[0] = instr_addr0_override;
9337
9338   /* Pass 9 - Linker */
9339   for(i=0;i<linkcount;i++)
9340   {
9341     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9342     literal_pool(64);
9343     if (!link_addr[i].ext)
9344     {
9345       void *stub = out;
9346       void *addr = check_addr(link_addr[i].target);
9347       emit_extjump(link_addr[i].addr, link_addr[i].target);
9348       if (addr) {
9349         set_jump_target(link_addr[i].addr, addr);
9350         add_jump_out(link_addr[i].target,stub);
9351       }
9352       else
9353         set_jump_target(link_addr[i].addr, stub);
9354     }
9355     else
9356     {
9357       // Internal branch
9358       int target=(link_addr[i].target-start)>>2;
9359       assert(target>=0&&target<slen);
9360       assert(instr_addr[target]);
9361       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9362       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9363       //#else
9364       set_jump_target(link_addr[i].addr, instr_addr[target]);
9365       //#endif
9366     }
9367   }
9368
9369   u_int source_len = slen*4;
9370   if (dops[slen-1].itype == INTCALL && source_len > 4)
9371     // no need to treat the last instruction as compiled
9372     // as interpreter fully handles it
9373     source_len -= 4;
9374
9375   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9376     copy = shadow;
9377
9378   // External Branch Targets (jump_in)
9379   for(i=0;i<slen;i++)
9380   {
9381     if(dops[i].bt||i==0)
9382     {
9383       if(instr_addr[i]) // TODO - delay slots (=null)
9384       {
9385         u_int vaddr=start+i*4;
9386         u_int page=get_page(vaddr);
9387         u_int vpage=get_vpage(vaddr);
9388         literal_pool(256);
9389         {
9390           assem_debug("%p (%d) <- %8x\n",instr_addr[i],i,start+i*4);
9391           assem_debug("jump_in: %x\n",start+i*4);
9392           ll_add(jump_dirty+vpage,vaddr,out);
9393           void *entry_point = do_dirty_stub(i, source_len);
9394           ll_add_flags(jump_in+page,vaddr,state_rflags,entry_point);
9395           // If there was an existing entry in the hash table,
9396           // replace it with the new address.
9397           // Don't add new entries.  We'll insert the
9398           // ones that actually get used in check_addr().
9399           struct ht_entry *ht_bin = hash_table_get(vaddr);
9400           if (ht_bin->vaddr[0] == vaddr)
9401             ht_bin->tcaddr[0] = entry_point;
9402           if (ht_bin->vaddr[1] == vaddr)
9403             ht_bin->tcaddr[1] = entry_point;
9404         }
9405       }
9406     }
9407   }
9408   // Write out the literal pool if necessary
9409   literal_pool(0);
9410   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9411   // Align code
9412   if(((u_int)out)&7) emit_addnop(13);
9413   #endif
9414   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9415   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9416   memcpy(copy, source, source_len);
9417   copy += source_len;
9418
9419   end_block(beginning);
9420
9421   // If we're within 256K of the end of the buffer,
9422   // start over from the beginning. (Is 256K enough?)
9423   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9424     out = ndrc->translation_cache;
9425
9426   // Trap writes to any of the pages we compiled
9427   for(i=start>>12;i<=(start+slen*4)>>12;i++) {
9428     invalid_code[i]=0;
9429   }
9430   inv_code_start=inv_code_end=~0;
9431
9432   // for PCSX we need to mark all mirrors too
9433   if(get_page(start)<(RAM_SIZE>>12))
9434     for(i=start>>12;i<=(start+slen*4)>>12;i++)
9435       invalid_code[((u_int)0x00000000>>12)|(i&0x1ff)]=
9436       invalid_code[((u_int)0x80000000>>12)|(i&0x1ff)]=
9437       invalid_code[((u_int)0xa0000000>>12)|(i&0x1ff)]=0;
9438
9439   /* Pass 10 - Free memory by expiring oldest blocks */
9440
9441   int end=(((out-ndrc->translation_cache)>>(TARGET_SIZE_2-16))+16384)&65535;
9442   while(expirep!=end)
9443   {
9444     int shift=TARGET_SIZE_2-3; // Divide into 8 blocks
9445     uintptr_t base_offs = ((uintptr_t)(expirep >> 13) << shift); // Base offset of this block
9446     uintptr_t base_offs_s = base_offs >> shift;
9447     inv_debug("EXP: Phase %d\n",expirep);
9448     switch((expirep>>11)&3)
9449     {
9450       case 0:
9451         // Clear jump_in and jump_dirty
9452         ll_remove_matching_addrs(jump_in+(expirep&2047),base_offs_s,shift);
9453         ll_remove_matching_addrs(jump_dirty+(expirep&2047),base_offs_s,shift);
9454         ll_remove_matching_addrs(jump_in+2048+(expirep&2047),base_offs_s,shift);
9455         ll_remove_matching_addrs(jump_dirty+2048+(expirep&2047),base_offs_s,shift);
9456         break;
9457       case 1:
9458         // Clear pointers
9459         ll_kill_pointers(jump_out[expirep&2047],base_offs_s,shift);
9460         ll_kill_pointers(jump_out[(expirep&2047)+2048],base_offs_s,shift);
9461         break;
9462       case 2:
9463         // Clear hash table
9464         for(i=0;i<32;i++) {
9465           struct ht_entry *ht_bin = &hash_table[((expirep&2047)<<5)+i];
9466           uintptr_t o1 = (u_char *)ht_bin->tcaddr[1] - ndrc->translation_cache;
9467           uintptr_t o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9468           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9469             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[1],ht_bin->tcaddr[1]);
9470             ht_bin->vaddr[1] = -1;
9471             ht_bin->tcaddr[1] = NULL;
9472           }
9473           o1 = (u_char *)ht_bin->tcaddr[0] - ndrc->translation_cache;
9474           o2 = o1 - MAX_OUTPUT_BLOCK_SIZE;
9475           if ((o1 >> shift) == base_offs_s || (o2 >> shift) == base_offs_s) {
9476             inv_debug("EXP: Remove hash %x -> %p\n",ht_bin->vaddr[0],ht_bin->tcaddr[0]);
9477             ht_bin->vaddr[0] = ht_bin->vaddr[1];
9478             ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
9479             ht_bin->vaddr[1] = -1;
9480             ht_bin->tcaddr[1] = NULL;
9481           }
9482         }
9483         break;
9484       case 3:
9485         // Clear jump_out
9486         if((expirep&2047)==0)
9487           do_clear_cache();
9488         ll_remove_matching_addrs(jump_out+(expirep&2047),base_offs_s,shift);
9489         ll_remove_matching_addrs(jump_out+2048+(expirep&2047),base_offs_s,shift);
9490         break;
9491     }
9492     expirep=(expirep+1)&65535;
9493   }
9494 #ifdef ASSEM_PRINT
9495   fflush(stdout);
9496 #endif
9497   return 0;
9498 }
9499
9500 // vim:shiftwidth=2:expandtab